diff --git a/.github/workflows/anykyty.yml b/.github/workflows/anykyty.yml index bd3b115ba4..a77cccb611 100644 --- a/.github/workflows/anykyty.yml +++ b/.github/workflows/anykyty.yml @@ -278,7 +278,7 @@ jobs: sanitizer: address env: GPU_TESTS: >- - ^(kyty_shim_(packed_unorm_blend|compute_execution|wave64_cross_lane|empty_buffer_replay|empty_buffer_replay_off|depth_target_alias|frame_capture_round_trip|buffer_null_range|descriptor_tables_draw|merged_hull_draw|image_write_back_alias|buffer_cache_pages))$ + ^(kyty_shim_(packed_unorm_blend|compute_execution|compute_sampler_spill|wave64_cross_lane|empty_buffer_replay|empty_buffer_replay_off|depth_target_alias|frame_capture_round_trip|buffer_null_range|descriptor_tables_draw|merged_hull_draw|image_write_back_alias|buffer_cache_pages))$ CPU_TESTS: ^(kyty_shim_.*|guest_gpu_fault|guest_host_write_filter|agc_kyty_shaders)$ steps: - uses: actions/checkout@v7 diff --git a/core/kyty/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp b/core/kyty/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp index 0fda7c5000..00c572b31e 100644 --- a/core/kyty/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp +++ b/core/kyty/graphics/shader/recompiler/ir/passes/ConstantPropagation.cpp @@ -37,7 +37,9 @@ class FoldWorklist { }; void Register(Block::iterator instruction) { - Queue(locations.emplace(&*instruction, Location {instruction}).first->second); + const auto [entry, inserted] = locations.emplace(&*instruction, Location {instruction}); + if (inserted && instruction->GetOpcode() == ValueOpcode::Phi) phis.push_back(&*instruction); + Queue(entry->second); } void Queue(Location& location) { @@ -72,6 +74,7 @@ class FoldWorklist { std::unordered_map locations; std::vector pending; std::unordered_set lowered_ancillary; + std::vector phis; private: std::vector affected; @@ -169,6 +172,119 @@ bool FoldPhi(Inst& inst) { return true; } +struct PhiConstant { + Value value; + bool varying = false; + std::vector users; + + bool Merge(Value incoming, bool incoming_varies) { + if (varying) return false; + if (incoming_varies || (!value.IsEmpty() && !incoming.IsEmpty() && value != incoming)) { + varying = true; + return true; + } + if (!value.IsEmpty() || incoming.IsEmpty()) return false; + value = incoming; + return true; + } +}; + +bool FoldReachablePhis(const BlockList& blocks, FoldWorklist& worklist) { + if (worklist.phis.empty()) return false; + std::unordered_map reachable; + std::vector pending_blocks {blocks.front()}; + while (!pending_blocks.empty()) { + const auto* block = pending_blocks.back(); + pending_blocks.pop_back(); + const auto [entry, inserted] = reachable.try_emplace(block, nullptr); + if (!inserted) continue; + const auto& term = block->terminator; + const auto condition = block->condition.Resolve(); + if (term.kind == CFG::TerminatorKind::ConditionalBranch && IsImmediate(condition, Type::U1)) { + entry->second = condition.U1() ? term.true_block : term.false_block; + } + if (entry->second != nullptr) { + pending_blocks.push_back(entry->second); + } else { + const auto successors = block->ImmSuccessors(); + pending_blocks.insert(pending_blocks.end(), successors.begin(), successors.end()); + } + } + + std::unordered_map constants; + std::vector phis; + const auto enabled = [&](const Inst& phi, size_t arg) { + const auto edge = reachable.find(phi.PhiBlock(arg)); + return edge != reachable.end() && (edge->second == nullptr || edge->second == phi.Parent()); + }; + bool changed = false; + const auto fold = [&](Inst& phi, Value value) { + worklist.QueueUsers(phi.Uses()); + Replace(phi, value); + changed = true; + }; + for (auto* phi: worklist.phis) { + if (phi->GetOpcode() != ValueOpcode::Phi || !reachable.contains(phi->Parent())) continue; + PhiConstant state; + bool dependent = false; + for (size_t arg = 0; arg < phi->NumArgs() && !state.varying; ++arg) { + if (!enabled(*phi, arg)) continue; + const auto source = Arg(*phi, arg); + const auto* inst = source.TryInstruction(); + if (inst != nullptr && inst->GetOpcode() == ValueOpcode::Phi) { + dependent = true; + } else { + state.Merge(source, !source.IsImmediate() || source.IsEmpty()); + } + } + if (state.varying) continue; + if (dependent) { + constants.try_emplace(phi); + phis.push_back(phi); + } else if (!state.value.IsEmpty()) { + fold(*phi, state.value); + } + } + std::vector pending; + for (auto* phi: phis) { + auto& state = constants.at(phi); + for (size_t arg = 0; arg < phi->NumArgs(); ++arg) { + if (!enabled(*phi, arg)) continue; + const auto source = Arg(*phi, arg); + if (const auto from = constants.find(source.TryInstruction()); from != constants.end()) { + from->second.users.push_back(&state); + } else if (source.IsImmediate() && !source.IsEmpty()) { + state.Merge(source, false); + } else { + state.Merge({}, true); + } + } + if (state.varying || !state.value.IsEmpty()) pending.push_back(&state); + } + const auto propagate = [&] { + for (size_t i = 0; i < pending.size(); ++i) { + const auto* source = pending[i]; + for (auto* target: source->users) { + if (target->Merge(source->value, source->varying)) pending.push_back(target); + } + } + pending.clear(); + }; + propagate(); + for (auto* phi: phis) { + auto& state = constants.at(phi); + if (state.value.IsEmpty() && state.Merge({}, true)) pending.push_back(&state); + } + propagate(); + + for (auto* phi: phis) { + const auto& state = constants.at(phi); + if (state.varying) continue; + fold(*phi, state.value); + } + return changed; +} + bool FoldBitCast(Inst& inst, ValueOpcode reverse) { const auto value = Arg(inst, 0); if (IsImmediate(value, Type::F32) && inst.GetOpcode() == ValueOpcode::BitCastU32F32) { @@ -992,7 +1108,7 @@ void ConstantPropagationPass(const BlockList& blocks, uint32_t wave_size) { drain(); bool normalized; do { - normalized = false; + normalized = FoldReachablePhis(blocks, worklist); for (auto* source: worklist.lowered_ancillary) { if (source->GetOpcode() == ValueOpcode::Identity) continue; const bool retained_only = std::ranges::all_of(source->Uses(), [](const Use& use) { diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt index 4d5bdc20d1..46562b120e 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/CMakeLists.txt @@ -470,6 +470,12 @@ if(NOT ANYPS5_KYTY_DLL) add_test(NAME kyty_shim_recompiler_stale_lane_spill COMMAND kyty_shim_recompiler_robustness_tests stale-lane-spill-after-read-lane-elimination) set_tests_properties(kyty_shim_recompiler_stale_lane_spill PROPERTIES TIMEOUT 60 PASS_REGULAR_EXPRESSION "kyty_shim_recompiler_robustness: ok" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") + add_test(NAME kyty_shim_recompiler_sampler_spill_phi COMMAND kyty_shim_recompiler_robustness_tests sampler-spill-phi) + set_tests_properties(kyty_shim_recompiler_sampler_spill_phi PROPERTIES TIMEOUT 20 + PASS_REGULAR_EXPRESSION "sampler-spill-phi: ok" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") + add_test(NAME kyty_shim_recompiler_phi_reachability COMMAND kyty_shim_recompiler_robustness_tests phi-reachability) + set_tests_properties(kyty_shim_recompiler_phi_reachability PROPERTIES TIMEOUT 20 + PASS_REGULAR_EXPRESSION "phi-reachability: ok" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") endif() add_test_executable(kyty_shim_compute_execution_tests ${CMAKE_CURRENT_SOURCE_DIR}/ComputeExecution.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../src/Log.cpp) @@ -483,6 +489,9 @@ target_link_libraries(kyty_shim_compute_execution_tests PRIVATE Kyty::gpu libker add_test(NAME kyty_shim_compute_execution COMMAND kyty_shim_compute_execution_tests) set_tests_properties(kyty_shim_compute_execution PROPERTIES TIMEOUT 20 SKIP_RETURN_CODE 77 PASS_REGULAR_EXPRESSION "kyty_shim_compute_execution: ok" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") +add_test(NAME kyty_shim_compute_sampler_spill COMMAND kyty_shim_compute_execution_tests sampler-spill) +set_tests_properties(kyty_shim_compute_sampler_spill PROPERTIES TIMEOUT 20 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "sampler spill: 32/32 lanes sampled 1.0" FAIL_REGULAR_EXPRESSION "terminate called|FAILED") add_test_executable(kyty_shim_pair_codegen_tests ${CMAKE_CURRENT_SOURCE_DIR}/PairCodegen.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../src/Log.cpp) target_include_directories(kyty_shim_pair_codegen_tests PRIVATE ${LIBS_INCLUDE_DIR}) diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ComputeExecution.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ComputeExecution.cpp index b18808009d..00a61cfd14 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/ComputeExecution.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/ComputeExecution.cpp @@ -1,3 +1,4 @@ +#include "SamplerSpillProgram.hpp" #include "common/assert.h" #include "graphics/host_gpu/vulkanCommon.h" #include "graphics/shader/recompiler/ShaderRecompiler.h" @@ -15,6 +16,7 @@ #include #include #include +#include #include namespace { @@ -65,12 +67,24 @@ struct Gpu { vk::Queue queue; uint32_t family = 0; vk::PhysicalDeviceMemoryProperties memory; + uint32_t compute_subgroup = 0; uint32_t min_subgroup = 0; uint32_t max_subgroup = 0; + uint32_t max_compute_subgroups = 0; bool subgroup_control = false; std::string name; }; +enum class Subgroup32 { Unavailable, Native, Required }; + +Subgroup32 ComputeSubgroup32(const Gpu& gpu, uint32_t threads) { + if (gpu.subgroup_control && gpu.min_subgroup <= HostSubgroup && HostSubgroup <= gpu.max_subgroup && + threads <= static_cast(gpu.max_compute_subgroups) * HostSubgroup) { + return Subgroup32::Required; + } + return gpu.compute_subgroup == HostSubgroup ? Subgroup32::Native : Subgroup32::Unavailable; +} + int NoDevice(const char* why) { const char* required = std::getenv("ANYPS5_REQUIRE_VULKAN"); Require(required == nullptr || std::strcmp(required, "1") != 0, std::string("ANYPS5_REQUIRE_VULKAN=1 and ") + why); @@ -144,13 +158,17 @@ std::optional OpenGpu(const char*& why) { gpu.memory = gpu.physical.getMemoryProperties(); vk::PhysicalDeviceVulkan13Properties properties13; + vk::PhysicalDeviceSubgroupProperties subgroup; vk::PhysicalDeviceDriverProperties driver; vk::PhysicalDeviceProperties2 properties; - driver.pNext = &properties13; + subgroup.pNext = &properties13; + driver.pNext = &subgroup; properties.pNext = &driver; gpu.physical.getProperties2(&properties); + if (subgroup.supportedStages & vk::ShaderStageFlagBits::eCompute) gpu.compute_subgroup = subgroup.subgroupSize; gpu.min_subgroup = properties13.minSubgroupSize; gpu.max_subgroup = properties13.maxSubgroupSize; + gpu.max_compute_subgroups = properties13.maxComputeWorkgroupSubgroups; gpu.subgroup_control = features13.subgroupSizeControl == VK_TRUE && (properties13.requiredSubgroupSizeStages & vk::ShaderStageFlagBits::eCompute); gpu.name = std::string(properties.properties.deviceName.data()) + " (" + driver.driverName.data() + ", " + @@ -200,6 +218,59 @@ void DestroyHostBuffer(const Gpu& gpu, HostBuffer& buffer) { gpu.device.freeMemory(buffer.memory); } +struct SampledTexture { + vk::Image image; + vk::DeviceMemory memory; + vk::ImageView view; + vk::Sampler sampler; +}; + +SampledTexture CreateSampledTexture(const Gpu& gpu) { + SampledTexture texture; + vk::ImageCreateInfo image; + image.imageType = vk::ImageType::e2D; + image.format = vk::Format::eR8G8B8A8Unorm; + image.extent = vk::Extent3D(1, 1, 1); + image.mipLevels = 1; + image.arrayLayers = 1; + image.usage = vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled; + texture.image = Checked(gpu.device.createImage(image), "sampled image creation"); + const auto needs = gpu.device.getImageMemoryRequirements(texture.image); + vk::MemoryAllocateInfo allocate; + allocate.allocationSize = needs.size; + allocate.memoryTypeIndex = std::countr_zero(needs.memoryTypeBits); + texture.memory = Checked(gpu.device.allocateMemory(allocate), "sampled image memory"); + Checked(gpu.device.bindImageMemory(texture.image, texture.memory, 0), "sampled image binding"); + vk::ImageViewCreateInfo view; + view.image = texture.image; + view.viewType = vk::ImageViewType::e2D; + view.format = image.format; + view.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; + texture.view = Checked(gpu.device.createImageView(view), "sampled image view"); + texture.sampler = Checked(gpu.device.createSampler(vk::SamplerCreateInfo {}), "sampler creation"); + return texture; +} + +void ClearSampledTexture(vk::CommandBuffer command, const SampledTexture& texture) { + vk::ImageMemoryBarrier barrier; + barrier.image = texture.image; + barrier.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}; + barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + barrier.newLayout = vk::ImageLayout::eTransferDstOptimal; + barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite; + command.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, + {}, 0, nullptr, 0, nullptr, 1, &barrier); + const vk::ClearColorValue red(std::array {1.0f, 0.0f, 0.0f, 1.0f}); + command.clearColorImage(texture.image, barrier.newLayout, &red, 1, &barrier.subresourceRange); + barrier.oldLayout = barrier.newLayout; + barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal; + barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite; + barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead; + command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eComputeShader, + {}, 0, nullptr, 0, nullptr, 1, &barrier); +} + void RequireValid(const std::vector& spirv, const std::string& what) { spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_3); std::string messages; @@ -221,6 +292,8 @@ struct Dispatch { std::span code; std::array user_data {}; uint32_t threads = 0; + uint32_t wave_size = WaveSize; + std::optional sampler_word; }; bool Run(const Gpu& gpu, const Dispatch& dispatch) { @@ -229,12 +302,12 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { compute.threads_num[0] = dispatch.threads; compute.threads_num[1] = 1u; compute.threads_num[2] = 1u; - compute.wave_size = WaveSize; + compute.wave_size = dispatch.wave_size; compute.host_subgroup_size = HostSubgroup; compute.thread_ids_num = 1; Recompiler::CompileOptions options; options.stage = ShaderType::Compute; - options.wave_size = WaveSize; + options.wave_size = dispatch.wave_size; options.user_data_base = 0u; options.shader_hash = 0x5ad0u; options.dump_ir = false; @@ -249,22 +322,20 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { Recompiler::IR::ResourceSpecialization specialization; Require(Recompiler::IR::MaterializeResources(plan, runtime, snapshot, specialization), what + ": the program's resources were not materialized"); + if (dispatch.sampler_word) { + Require(snapshot.samplers.size() == 1 && snapshot.samplers.front().dwords[0] == *dispatch.sampler_word, + what + ": sampler dword 0 did not match the saved value"); + } auto compiled = Recompiler::CompileProgram(std::move(translated), options, specialization, 0u); RequireValid(compiled.spirv, what); const auto info = std::move(compiled.program).TakeCompiledInfo(); - if (!lane_local && gpu.max_subgroup < HostSubgroup) { - std::printf("%s: %s: skipped, the program is not lane-local and the device's subgroups hold %u lanes\n", Name, - dispatch.name, gpu.max_subgroup); + const auto subgroup32 = ComputeSubgroup32(gpu, dispatch.threads); + if (!lane_local && subgroup32 == Subgroup32::Unavailable) { + std::printf("%s: %s: skipped, the program needs a 32-lane compute subgroup\n", Name, dispatch.name); return false; } const auto& layout = info.bindings; Require(layout.UsesPushData(), what + ": the shader data does not fit the push constants"); - for (auto mask = layout.descriptor_mask; mask != 0; mask &= mask - 1u) { - const auto kind = static_cast(std::countr_zero(mask)); - Require(kind == BindingKind::Buffers, what + ": descriptor binding kind " + - std::to_string(static_cast(kind)) + " is not served by this test"); - } - const auto buffer_count = layout.descriptor_counts[static_cast(BindingKind::Buffers)]; std::vector buffers(buffer_count); std::vector targets(buffer_count, nullptr); @@ -309,6 +380,25 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { set_bindings.push_back({Recompiler::IR::NativeBinding(ShaderType::Compute, BindingKind::Buffers), vk::DescriptorType::eStorageBuffer, buffer_count, vk::ShaderStageFlagBits::eCompute, nullptr}); } + std::optional texture; + if (dispatch.sampler_word) texture = CreateSampledTexture(gpu); + for (auto mask = layout.descriptor_mask; mask != 0; mask &= mask - 1u) { + const auto kind = static_cast(std::countr_zero(mask)); + if (kind == BindingKind::Buffers) continue; + const bool sampler = kind == BindingKind::Samplers; + Require(texture && layout.descriptor_counts[static_cast(kind)] == 1u && + (sampler || Recompiler::IR::ImageBindingResourceClass(kind) == Recompiler::IR::ImageResourceClass::Sampled), + what + ": unsupported descriptor binding " + std::to_string(static_cast(kind))); + set_bindings.push_back({Recompiler::IR::NativeBinding(ShaderType::Compute, kind), + sampler ? vk::DescriptorType::eSampler : vk::DescriptorType::eSampledImage, + 1, vk::ShaderStageFlagBits::eCompute, nullptr}); + } + if (texture) { + for (const auto type: {vk::DescriptorType::eSampledImage, vk::DescriptorType::eSampler}) { + Require(std::ranges::count(set_bindings, type, &vk::DescriptorSetLayoutBinding::descriptorType) == 1, + what + ": expected one image and one sampler binding"); + } + } vk::DescriptorSetLayoutCreateInfo set_layout_info; set_layout_info.bindingCount = static_cast(set_bindings.size()); set_layout_info.pBindings = set_bindings.data(); @@ -329,7 +419,7 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { pipeline_info.stage.stage = vk::ShaderStageFlagBits::eCompute; pipeline_info.stage.module = module; pipeline_info.stage.pName = "main"; - if (gpu.subgroup_control && HostSubgroup >= gpu.min_subgroup && HostSubgroup <= gpu.max_subgroup) { + if (subgroup32 == Subgroup32::Required) { subgroup.requiredSubgroupSize = HostSubgroup; pipeline_info.stage.pNext = &subgroup; } @@ -337,11 +427,13 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { vk::Pipeline pipeline; Checked(gpu.device.createComputePipelines(nullptr, 1, &pipeline_info, nullptr, &pipeline), "pipeline creation"); - const vk::DescriptorPoolSize pool_size {vk::DescriptorType::eStorageBuffer, std::max(buffer_count, 1u)}; + std::vector pool_sizes; + for (const auto& binding: set_bindings) pool_sizes.push_back({binding.descriptorType, binding.descriptorCount}); + if (pool_sizes.empty()) pool_sizes.push_back({vk::DescriptorType::eStorageBuffer, 1u}); vk::DescriptorPoolCreateInfo pool_info; pool_info.maxSets = 1; - pool_info.poolSizeCount = 1; - pool_info.pPoolSizes = &pool_size; + pool_info.poolSizeCount = static_cast(pool_sizes.size()); + pool_info.pPoolSizes = pool_sizes.data(); const auto pool = Checked(gpu.device.createDescriptorPool(pool_info), "descriptor pool creation"); vk::DescriptorSetAllocateInfo set_info; set_info.descriptorPool = pool; @@ -360,6 +452,19 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { write.pBufferInfo = buffer_infos.data(); gpu.device.updateDescriptorSets(1, &write, 0, nullptr); } + if (texture) { + const vk::DescriptorImageInfo image {texture->sampler, texture->view, vk::ImageLayout::eShaderReadOnlyOptimal}; + for (const auto& binding: set_bindings) { + if (binding.descriptorType == vk::DescriptorType::eStorageBuffer) continue; + vk::WriteDescriptorSet write; + write.dstSet = set; + write.dstBinding = binding.binding; + write.descriptorCount = 1; + write.descriptorType = binding.descriptorType; + write.pImageInfo = ℑ + gpu.device.updateDescriptorSets(1, &write, 0, nullptr); + } + } vk::CommandPoolCreateInfo command_pool_info; command_pool_info.queueFamilyIndex = gpu.family; @@ -373,6 +478,7 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { vk::CommandBufferBeginInfo begin; begin.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; Checked(command.begin(begin), "command buffer begin"); + if (texture) ClearSampledTexture(command, *texture); command.bindPipeline(vk::PipelineBindPoint::eCompute, pipeline); command.bindDescriptorSets(vk::PipelineBindPoint::eCompute, pipeline_layout, 0, 1, &set, 0, nullptr); command.pushConstants(pipeline_layout, vk::ShaderStageFlagBits::eCompute, 0, sizeof(push), &push); @@ -399,6 +505,12 @@ bool Run(const Gpu& gpu, const Dispatch& dispatch) { gpu.device.destroyShaderModule(module); gpu.device.destroyPipelineLayout(pipeline_layout); gpu.device.destroyDescriptorSetLayout(set_layout); + if (texture) { + gpu.device.destroySampler(texture->sampler); + gpu.device.destroyImageView(texture->view); + gpu.device.destroyImage(texture->image); + gpu.device.freeMemory(texture->memory); + } return true; } @@ -873,17 +985,55 @@ void MultiplyThenAddRoundsProduct(const Gpu& gpu) { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}); } +void SamplerSpill(const Gpu& gpu) { + constexpr uint32_t Threads = HostSubgroup; + alignas(256) std::array output; + alignas(256) const std::array texture {}; + output.fill(0xdeadbeefu); + Dispatch dispatch; + dispatch.name = "sampler spill"; + dispatch.code = SamplerSpillProgram::Words; + dispatch.threads = Threads; + dispatch.wave_size = 32; + dispatch.sampler_word = 18; + const auto buffer = BufferDescriptor(output.data(), sizeof(output), 0, 0x30014000u | 0xfacu); + std::ranges::copy(buffer, dispatch.user_data.begin() + 4); + const auto base = reinterpret_cast(texture.data()) >> 8u; + const std::array image { + static_cast(base), static_cast((base >> 32u) & 0xffu) | (56u << 20u) | (3u << 30u), + 15u, 0xfacu | (9u << 28u), 0u, 0u, 0u, 0u, + }; + std::ranges::copy(image, dispatch.user_data.begin() + 8); + Require(Run(gpu, dispatch), "sampler spill dispatch did not run"); + const auto sampled = std::ranges::count(output, 0x3f800000u); + Check(sampled == Threads, "sampler spill: every lane must sample 1.0"); + std::printf("sampler spill: %td/%u lanes sampled 1.0\n", sampled, Threads); } -int main() { +} + +int main(int argc, char** argv) { const char* why = nullptr; auto gpu = OpenGpu(why); if (!gpu) return NoDevice(why); - SumOfAbsoluteDifferences(*gpu); - ByteAverage(*gpu); - QuadSumOfAbsoluteDifferences(*gpu); - SumOfAbsoluteDifferencesClamp(*gpu); - MultiplyThenAddRoundsProduct(*gpu); + if (argc == 2 && std::string_view(argv[1]) == "sampler-spill") { + const auto subgroup32 = ComputeSubgroup32(*gpu, HostSubgroup); + if (subgroup32 == Subgroup32::Unavailable) { + std::printf("%s: sampler spill: skipped, %s has no 32-lane compute subgroup\n", Name, gpu->name.c_str()); + CloseGpu(*gpu); + return SkippedExit; + } + std::printf("sampler spill: %s compute subgroup size %u (native compute size %u, supported size range %u-%u)\n", + subgroup32 == Subgroup32::Required ? "requesting" : "using native", HostSubgroup, gpu->compute_subgroup, + gpu->min_subgroup, gpu->max_subgroup); + SamplerSpill(*gpu); + } else { + SumOfAbsoluteDifferences(*gpu); + ByteAverage(*gpu); + QuadSumOfAbsoluteDifferences(*gpu); + SumOfAbsoluteDifferencesClamp(*gpu); + MultiplyThenAddRoundsProduct(*gpu); + } const auto name = gpu->name; CloseGpu(*gpu); if (g_failures != 0) { diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/RecompilerRobustness.cpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/RecompilerRobustness.cpp index 388b8f6ad9..ad6091984c 100644 --- a/core/libs/prx/libSceAgcDriver/KytyShim/tests/RecompilerRobustness.cpp +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/RecompilerRobustness.cpp @@ -1,9 +1,13 @@ +#include "SamplerSpillProgram.hpp" #include "ShaderRecompilerRun.hpp" #include "graphics/shader/recompiler/frontend/decode/ShaderDecoder.h" +#include "graphics/shader/recompiler/ir/passes/ConstantPropagation.h" +#include "graphics/shader/recompiler/ir/passes/DeadCodeElimination.h" #include "spirv/unified1/spirv.hpp" #include #include +#include #include #include #include @@ -183,6 +187,124 @@ bool FlatOffsets() { return ok; } +bool SamplerSpillPhi() { + const auto& shader = SamplerSpillProgram::Words; + auto runtime_branch = shader; + runtime_branch[SamplerSpillProgram::RestoreCompare] = 0xbf068002u; + std::string refusal; + KytyFuzz::Run(runtime_branch, 1, 0, &refusal, nullptr, nullptr, nullptr, 32u); + if (refusal.find("GetSamplerResource dword 0 is not a valid runtime value") == std::string::npos) { + std::printf("sampler-spill-phi: FAILED, unexpected result on the reachable reuse path: %s\n", refusal.c_str()); + return false; + } + + auto unconditional_restore = shader; + unconditional_restore[SamplerSpillProgram::RestoreBranch] = 0xbf800000u; + const decltype(unconditional_restore)* cases[] {&unconditional_restore, &shader}; + for (const auto* code: cases) { + bool emitted = false; + std::vector spirv; + refusal.clear(); + KytyFuzz::Run(*code, 1, 0, &refusal, &emitted, nullptr, &spirv, 32u); + if (!emitted || !KytyFuzz::Valid(spirv, refusal)) { + std::printf("sampler-spill-phi: FAILED, %s restore: %s\n", + code == &shader ? "guarded" : "unconditional", refusal.c_str()); + return false; + } + } + return true; +} + +bool PhiReachability() { + using namespace KytyFuzz::IR; + using Term = KytyFuzz::Recompiler::CFG::TerminatorKind; + enum class Input { Same, Conflict, Undef, Runtime, Unreachable, Unseeded }; + for (const auto input: {Input::Same, Input::Conflict, Input::Undef, Input::Runtime, Input::Unreachable, + Input::Unseeded}) { + Program program; + program.user_data_count = 1; + for (uint32_t id = 0; id < 8; ++id) { + auto& block = *program.block_storage.emplace_back(std::make_unique()); + block.id = id; + program.blocks.push_back(&block); + } + auto& entry = *program.blocks[0]; + auto& outer = *program.blocks[1]; + auto& inner = *program.blocks[2]; + auto& keep = *program.blocks[3]; + auto& update = *program.blocks[4]; + auto& inner_latch = *program.blocks[5]; + auto& outer_latch = *program.blocks[6]; + auto& exit = *program.blocks[7]; + const auto link = [](Block& from, Block& yes, Block* no = nullptr, Value condition = {}) { + from.terminator.kind = no == nullptr ? Term::Branch : Term::ConditionalBranch; + from.terminator.true_block = &yes; + from.terminator.false_block = no; + from.condition = condition; + from.AddBranch(&yes); + if (no != nullptr) from.AddBranch(no); + }; + const Value runtime(&entry.AppendNewInst(ValueOpcode::GetUserData, {Value(static_cast(0u))})); + const Value predicate(&entry.AppendNewInst(ValueOpcode::INotEqual32, {runtime, Value(0u)})); + const auto phi_flags = static_cast(Type::U32); + auto& carried_outer = outer.AppendNewInst(ValueOpcode::Phi, {}, phi_flags); + auto& outer_count = outer.AppendNewInst(ValueOpcode::Phi, {}, phi_flags); + auto& carried_inner = inner.AppendNewInst(ValueOpcode::Phi, {}, phi_flags); + auto& inner_count = inner.AppendNewInst(ValueOpcode::Phi, {}, phi_flags); + auto& joined = inner_latch.AppendNewInst(ValueOpcode::Phi, {}, phi_flags); + constexpr auto exec_nonzero = KytyFuzz::Recompiler::CFG::BranchCondition::ExecNonZero; + const auto exec = input == Input::Unreachable ? Value(true) : predicate; + const Value condition(&inner.AppendNewInst(ValueOpcode::ConditionRef, {exec}, static_cast(exec_nonzero))); + link(entry, outer); + link(outer, inner); + link(inner, keep, &update, condition); + link(keep, inner_latch); + link(update, inner_latch); + const auto repeat = [&](Block& first, Block& header, Block& latch, Block& end, Inst& count) { + const Value next(&latch.AppendNewInst(ValueOpcode::IAdd32, {Value(&count), Value(1u)})); + const Value more(&latch.AppendNewInst(ValueOpcode::INotEqual32, {next, Value(2u)})); + link(latch, header, &end, more); + count.AddPhiOperand(&first, Value(0u)); + count.AddPhiOperand(&latch, next); + }; + repeat(outer, inner, inner_latch, outer_latch, inner_count); + repeat(entry, outer, outer_latch, exit, outer_count); + Value next(17u); + switch (input) { + case Input::Undef: next = Value(&update.AppendNewInst(ValueOpcode::UndefU32)); break; + case Input::Runtime: + case Input::Unseeded: next = runtime; break; + case Input::Conflict: + case Input::Unreachable: next = Value(29u); break; + case Input::Same: break; + } + const auto seed = input == Input::Unseeded ? Value(&entry.AppendNewInst(ValueOpcode::UndefU32)) : Value(17u); + carried_outer.AddPhiOperand(&entry, seed); + carried_outer.AddPhiOperand(&outer_latch, Value(&joined)); + carried_inner.AddPhiOperand(&outer, Value(&carried_outer)); + carried_inner.AddPhiOperand(&inner_latch, Value(&joined)); + joined.AddPhiOperand(&keep, Value(&carried_inner)); + joined.AddPhiOperand(&update, next); + auto& increment = exit.AppendNewInst(ValueOpcode::IAdd32, {Value(&joined), Value(1u)}); + auto& output = exit.AppendNewInst(ValueOpcode::ReferenceU32, {Value(&increment)}); + ValidateProgram(program); + ConstantPropagationPass(program.blocks); + RemoveIdentities(program); + ValidateProgram(program); + const bool fold = input == Input::Same || input == Input::Unreachable; + const auto* add = output.Arg(0).TryInstruction(); + const auto* phi = add != nullptr && add->GetOpcode() == ValueOpcode::IAdd32 + ? add->Arg(0).TryInstruction() : nullptr; + if (fold ? output.Arg(0) != Value(18u) + : phi == nullptr || phi->GetOpcode() != ValueOpcode::Phi || phi->Arg(1) != next) { + std::printf("phi-reachability: FAILED for nested loop input %u\n", static_cast(input)); + return false; + } + } + + return true; +} + } int main(int argc, char** argv) { @@ -197,6 +319,22 @@ int main(int argc, char** argv) { if (!FlatOffsets()) return 1; std::printf("flat-offsets: ok\n"); } + if (argc >= 2 && std::string_view(argv[1]) == "sampler-spill-phi") { + found = true; + if (!SamplerSpillPhi()) return 1; + std::printf("sampler-spill-phi: ok\n"); + } + if (argc >= 2 && std::string_view(argv[1]) == "phi-reachability") { + found = true; + Common::SoftExitScope soft; + try { + if (!PhiReachability()) return 1; + } catch (const std::exception& error) { + std::printf("phi-reachability: FAILED: %s\n", error.what()); + return 1; + } + std::printf("phi-reachability: ok\n"); + } for (const auto& entry: Cases) { if (argc >= 2 && std::string_view(argv[1]) != entry.name) continue; found = true; diff --git a/core/libs/prx/libSceAgcDriver/KytyShim/tests/SamplerSpillProgram.hpp b/core/libs/prx/libSceAgcDriver/KytyShim/tests/SamplerSpillProgram.hpp new file mode 100644 index 0000000000..4a2105443d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/KytyShim/tests/SamplerSpillProgram.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +namespace SamplerSpillProgram { + +inline constexpr std::size_t RestoreCompare = 15; +inline constexpr std::size_t RestoreBranch = 16; +inline constexpr std::array Words { + 0xbe980392u, 0xbe990380u, 0xbe9a0480u, 0xbe940382u, 0x7e1002f0u, 0x7e1202f0u, 0x7e140280u, + 0x3a200003u, 0xd7610018u, 0x00010a18u, 0xd7610018u, 0x00010c19u, 0x7e300510u, 0x7e320500u, 0x06101018u, + 0xbf068080u, 0xbf840004u, 0xd7600018u, 0x00010b18u, 0xd7600019u, 0x00010d18u, + 0xf0900f08u, 0x00c20408u, 0xbf8c3f70u, 0x34160082u, 0xe0701000u, 0x8001040bu, + 0x80948114u, 0xbf078014u, 0xbf85ffeau, 0xbf810000u, +}; + +}