diff --git a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp index 7a14ddaac..073d28f5c 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ShaderMemory.cpp @@ -376,6 +376,108 @@ void verifyBindlessTable() { } +void verifyDescriptorPhis() { + using namespace ShaderRecompiler; + constexpr std::uint32_t Format8888UNorm = 56; + constexpr std::uint32_t Type2D = 9; + struct alignas(256) Texture { std::array bytes{}; }; + static Texture textures[2]; + const auto imageDescriptor = [&](const Texture& texture) { + const auto base = static_cast(reinterpret_cast(texture.bytes.data())); + return std::array{static_cast(base >> 8u), static_cast((base >> 40u) & 0xffu) | (Format8888UNorm << 20u) | (3u << 30u), 3u << 14u, 0xfacu | (Type2D << 28u), 0u, 0u, 0u, 0u}; + }; + const std::array pointWrap{0u, 0u, 0u, 0u}; + const std::array linearMirror{0x49u, 0u, 0x00500000u, 0u}; + std::array output{}; + const auto outputAddress = static_cast(reinterpret_cast(output.data())); + std::array srt{}; + const auto first = imageDescriptor(textures[0]); + const auto second = imageDescriptor(textures[1]); + std::copy(first.begin(), first.end(), srt.begin()); + std::copy(pointWrap.begin(), pointWrap.end(), srt.begin() + 8); + std::copy(linearMirror.begin(), linearMirror.end(), srt.begin() + 12); + const std::array outputV{static_cast(outputAddress), static_cast((outputAddress >> 32u) & 0xffffu), 16u, 0xfacu}; + std::copy(outputV.begin(), outputV.end(), srt.begin() + 16); + srt[20] = 1u; + std::copy(second.begin(), second.end(), srt.begin() + 24); + const auto srtAddress = static_cast(reinterpret_cast(srt.data())); + const std::array userData{static_cast(srtAddress), static_cast(srtAddress >> 32u)}; + const std::array capabilities{29u}; + const auto makeRequest = [&](const std::vector& code, std::uint32_t waveSize = 32u) { + RecompileRequest request{}; + request.shader = {ShaderStage::Compute, 0x21000u, code, 0, {}}; + request.context.waveSize = waveSize; + request.context.userDataBaseRegister = 0; + request.context.userData = userData; + request.context.compute = ShaderComputeStageInfo{{waveSize, 1u, 1u}, 0u, {false, false, false}, false, 1u}; + request.target.vulkanVersion = 0x00401000u; + request.target.spirvVersion = 0x00010300u; + request.target.subgroupSize = 32; + request.target.supportedCapabilities = capabilities; + request.target.fragmentShaderBarycentricEnabled = false; + request.layout.pushConstantSizeBytes = 128; + return request; + }; + const auto countOps = [](const std::vector& words, std::uint32_t opcode) { + std::size_t count = 0; + for (std::size_t cursor = 5; cursor < words.size();) { + const auto length = words[cursor] >> 16u; + require(length != 0 && length <= words.size() - cursor, "descriptor Phi: truncated SPIR-V instruction"); + count += (words[cursor] & 0xffffu) == opcode ? 1u : 0u; + cursor += length; + } + return count; + }; + constexpr std::uint32_t OpImageSampleExplicitLod = 88; + + const std::vector samplerCode{0xf40c0200u, 0xfa000000u, 0xf4000400u, 0xfa000050u, 0xbf8cc07fu, 0xbf068010u, 0xbf850003u, 0xf4080500u, 0xfa000020u, 0xbf820002u, 0xf4080500u, 0xfa000030u, 0xf4080600u, 0xfa000040u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf810000u}; + const std::vector imageCode{0xf4000400u, 0xfa000050u, 0xf4080500u, 0xfa000020u, 0xbf8cc07fu, 0xbf068010u, 0xbf850003u, 0xf40c0200u, 0xfa000000u, 0xbf820002u, 0xf40c0200u, 0xfa000060u, 0xf4080600u, 0xfa000040u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf810000u}; + const std::vector dynamicCode{0xf40c0200u, 0xfa000000u, 0xf4000400u, 0xfa000050u, 0xbf8cc07fu, 0xbf068010u, 0xbf850003u, 0xf4080500u, 0xfa000020u, 0xbf820002u, 0xf4080500u, 0x20000000u, 0xf4080600u, 0xfa000040u, 0xbf8cc07fu, 0xf09c0f08u, 0x00a20000u, 0xbf8c3f70u, 0xe0700000u, 0x80060000u, 0xbf810000u}; + + const auto compile = [&](const std::vector& code, std::size_t images, std::size_t samplers) { + auto request = makeRequest(code); + const auto plan = GetResourcePlan(request); + require(plan->info.images.size() == images && plan->info.samplers.size() == samplers && plan->info.sampledPairs.size() == 2u, "descriptor Phi: the edges were not given one resource each"); + AgcDriver::ShaderMemory memory({}); + const auto capture = memory.Capture(request); + request.context.memory = memory.Regions(); + const auto compiled = Recompile(request, *capture); + require(countOps(compiled->spirv, OpImageSampleExplicitLod) == 2u, "descriptor Phi: the SPIR-V does not sample once per edge"); +#if ANYPS5_ENABLE_SPIRV_TOOLS + static_cast(ValidateAndOptimizeSpirv(compiled->spirv, request.target.vulkanVersion, request.target.spirvVersion)); +#endif + return capture; + }; + const auto samplerCapture = compile(samplerCode, 1u, 2u); + const auto& samplers = samplerCapture->snapshot.samplers; + require(samplers.size() == 2u, "descriptor Phi: the snapshot does not hold both S#s"); + const auto holds = [&](const std::array& words) { + return std::ranges::any_of(samplers, [&](const DescriptorValue& value) { + return value.dwordCount == 4u && std::equal(words.begin(), words.end(), value.dwords.begin()); + }); + }; + require(holds(pointWrap) && holds(linearMirror), "descriptor Phi: the snapshot S#s are not the two edges' S#s"); + + const auto imageCapture = compile(imageCode, 2u, 1u); + const auto& images = imageCapture->snapshot.images; + require(images.size() == 2u, "descriptor Phi: the snapshot does not hold both T#s"); + const auto holdsImage = [&](const std::array& words) { + return std::ranges::any_of(images, [&](const DescriptorValue& value) { + return std::equal(words.begin(), words.end(), value.dwords.begin()); + }); + }; + require(holdsImage(first) && holdsImage(second), "descriptor Phi: the snapshot T#s are not the two edges' T#s"); + + auto twoLane = makeRequest(samplerCode, 64u); + AgcDriver::ShaderMemory twoLaneMemory({}); + const auto twoLaneCapture = twoLaneMemory.Capture(twoLane); + twoLane.context.memory = twoLaneMemory.Regions(); + require(countOps(Recompile(twoLane, *twoLaneCapture)->spirv, OpImageSampleExplicitLod) == 4u, "descriptor Phi: the two-lane SPIR-V does not sample once per edge and half"); + + auto dynamic = makeRequest(dynamicCode); + expectFailure([&] { static_cast(GetResourcePlan(dynamic)); }, "GetSamplerResource dword 0 is not a valid runtime value", "descriptor Phi: an edge without an SRT slot was accepted"); +} + void verifyProgramCounterRelativeData() { using namespace ShaderRecompiler; static const std::array code{ @@ -759,6 +861,7 @@ int main() { verifyRegisterSources(); verifyPureFlatSlots(); verifyBindlessTable(); + verifyDescriptorPhis(); verifyProgramCounterRelativeData(); verifyMeshConfiguration(); verifyPixelInputs(); diff --git a/core/shader/recompiler/Optimization/src/ResourceTracker.cpp b/core/shader/recompiler/Optimization/src/ResourceTracker.cpp index c7ced39e6..84eaa9545 100644 --- a/core/shader/recompiler/Optimization/src/ResourceTracker.cpp +++ b/core/shader/recompiler/Optimization/src/ResourceTracker.cpp @@ -2,11 +2,13 @@ #include "Optimization/SrtWalker.hpp" #include "Optimization/ResourceMaterializer.hpp" #include "IntermediateRepresentation/IrBuilder.hpp" +#include "Optimization/SrtWalker/SrtInstructionPredicates.hpp" #include #include #include #include +#include #include #include #include @@ -106,6 +108,7 @@ public: if (!m_program.Resources().srtPlanComplete) { fail("SRT plan is not ready"); } + SplitDescriptorPhis(); PlanIndirectImages(); for (auto& block : m_program.Blocks()) { for (IrValue* inst : block->Instructions()) { @@ -470,6 +473,269 @@ private: }); } + static constexpr std::uint32_t phiSearchDepth = 8u; + + static bool SplittableImageRead(const IrValue& inst) { + switch (inst.Opcode()) { + case IrOpcode::ImageSampleRaw: + case IrOpcode::ImageGatherRaw: + case IrOpcode::ImageQueryLod: + case IrOpcode::ImageQueryDimensions: + case IrOpcode::ImageRead: return inst.Type() == IrType::U32x4; + default: return false; + } + } + + void CollectDescriptorPhis(IrValue* value, std::vector& phis, std::uint32_t depth) const { + value = value->Resolve(); + if (value->HasImmediate()) { + return; + } + if (value->IsPhi()) { + if (ResolveInvariantPhi(m_program.Resources(), value) == nullptr && std::ranges::find(phis, value) == phis.end()) { + phis.push_back(value); + } + return; + } + if (depth == 0u || !Detail::IsRuntimeUniformOp(value->Opcode())) { + return; + } + for (std::size_t index = 0; index < value->ArgumentCount(); index++) { + CollectDescriptorPhis(value->Argument(index), phis, depth - 1u); + } + } + + static IrValue* PhiIncoming(const IrValue& phi, const IrBlock* predecessor) { + for (std::size_t index = 0; index < phi.ArgumentCount(); index++) { + if (phi.PhiBlock(index) == predecessor) { + return phi.Argument(index); + } + } + return nullptr; + } + + IrValue* EmitBefore(IrValue& position, IrOpcode op, IrType type, std::span arguments, std::uint64_t flags = 0) { + IrValue& value = m_program.CreateValue(op, type, flags); + for (IrValue* argument : arguments) { + value.AddArgument(argument); + } + position.Parent()->InsertInstructionBefore(&position, &value); + return &value; + } + + IrValue* EmitCopy(const IrValue& original, std::span arguments, IrValue& position) { + return EmitBefore(position, original.Opcode(), original.Type(), arguments, original.Flags()); + } + + IrValue* Rematerialize(IrValue* value, IrValue& position, bool emit, std::uint32_t depth) { + value = value->Resolve(); + if (value->HasImmediate()) { + return value; + } + if (value->IsPhi()) { + IrValue* invariant = ResolveInvariantPhi(m_program.Resources(), value); + return invariant == nullptr || invariant->IsPhi() ? nullptr : Rematerialize(invariant, position, emit, depth); + } + if (depth == 0u) { + return nullptr; + } + const auto op = value->Opcode(); + const bool register_ = op == IrOpcode::GetUserData; + const bool argumentless = (op == IrOpcode::GetShaderBase || op == IrOpcode::GetSrtResource) && value->ArgumentCount() == 0u; + const bool srtRead = op == IrOpcode::ReadConst && value->ArgumentCount() == 2u && value->Argument(0)->Resolve()->Opcode() == IrOpcode::GetSrtResource && value->Argument(1)->Resolve()->HasImmediate(); + if (!register_ && !argumentless && !srtRead && !Detail::IsRuntimeUniformOp(op)) { + return nullptr; + } + std::vector arguments; + for (std::size_t index = 0; index < value->ArgumentCount(); index++) { + IrValue* argument = register_ ? value->Argument(index) : Rematerialize(value->Argument(index), position, emit, depth - 1u); + if (argument == nullptr) { + return nullptr; + } + arguments.push_back(argument); + } + return emit ? EmitCopy(*value, arguments, position) : value; + } + + IrValue* SubstituteEdge(IrValue* value, const IrBlock* predecessor, IrValue& position, bool emit, std::uint32_t depth) { + value = value->Resolve(); + std::vector phis; + CollectDescriptorPhis(value, phis, depth); + if (phis.empty()) { + return value; + } + if (value->IsPhi()) { + IrValue* incoming = PhiIncoming(*value, predecessor); + return incoming == nullptr ? nullptr : Rematerialize(incoming, position, emit, phiSearchDepth); + } + std::vector arguments; + for (std::size_t index = 0; index < value->ArgumentCount(); index++) { + IrValue* argument = SubstituteEdge(value->Argument(index), predecessor, position, emit, depth - 1u); + if (argument == nullptr) { + return nullptr; + } + arguments.push_back(argument); + } + return emit ? EmitCopy(*value, arguments, position) : value; + } + + IrValue& EdgeSelector(IrBlock& block, const std::vector& edges) { + for (const auto& selector : m_edgeSelectors) { + if (selector.block == &block && selector.edges == edges) { + return *selector.value; + } + } + IrValue& phi = m_program.CreateValue(IrOpcode::Phi, IrType::Bool); + const auto& predecessors = block.Predecessors(); + for (std::size_t index = 0; index < predecessors.size(); index++) { + phi.AddPhiOperand(predecessors[index], &m_builder.ConstantBool(edges[index])); + } + block.InsertInstructionBefore(nullptr, &phi); + m_edgeSelectors.push_back({&block, edges, &phi}); + return phi; + } + + void SplitDescriptorPhi(IrValue& inst) { + const auto info = ImageOpcodeInfoOf(inst.Opcode()); + const std::uint32_t handleCount = info.needsSampler ? 2u : 1u; + if (inst.ArgumentCount() < handleCount) { + return; + } + std::array handles {}; + std::array split {}; + std::vector phis; + for (std::uint32_t slot = 0; slot < handleCount; slot++) { + IrValue* handle = inst.Argument(slot)->Resolve(); + const auto expected = slot == 0u ? IrOpcode::GetImageResource : IrOpcode::GetSamplerResource; + if (handle->Opcode() != expected || handle->ArgumentCount() != (slot == 0u ? 8u : 4u)) { + return; + } + handles[slot] = handle; + std::vector handlePhis; + for (std::size_t dword = 0; dword < handle->ArgumentCount(); dword++) { + CollectDescriptorPhis(handle->Argument(dword), handlePhis, phiSearchDepth); + } + split[slot] = !handlePhis.empty(); + for (IrValue* phi : handlePhis) { + if (std::ranges::find(phis, phi) == phis.end()) { + phis.push_back(phi); + } + } + } + if (phis.empty()) { + return; + } + IrBlock* block = phis.front()->Parent(); + if (block == nullptr || inst.Parent() == nullptr) { + return; + } + const auto& predecessors = block->Predecessors(); + if (predecessors.size() < 2u) { + return; + } + for (const IrValue* phi : phis) { + if (phi->Parent() != block || phi->PhiBlockCount() != predecessors.size()) { + return; + } + for (const IrBlock* predecessor : predecessors) { + if (PhiIncoming(*phi, predecessor) == nullptr) { + return; + } + } + } + + std::vector edgeArm(predecessors.size()); + std::vector arms; + for (std::size_t edge = 0; edge < predecessors.size(); edge++) { + std::uint32_t arm = 0; + for (; arm < arms.size(); arm++) { + const bool same = std::ranges::all_of(phis, [&](const IrValue* phi) { + return EquivalentValue(m_program.Resources(), PhiIncoming(*phi, predecessors[edge]), PhiIncoming(*phi, arms[arm])); + }); + if (same) { + break; + } + } + if (arm == arms.size()) { + arms.push_back(predecessors[edge]); + } + edgeArm[edge] = arm; + } + for (const IrBlock* arm : arms) { + for (std::uint32_t slot = 0; slot < handleCount; slot++) { + for (std::size_t dword = 0; split[slot] && dword < handles[slot]->ArgumentCount(); dword++) { + if (SubstituteEdge(handles[slot]->Argument(dword), arm, inst, false, phiSearchDepth) == nullptr) { + return; + } + } + } + } + + std::vector copies; + const auto flags = inst.Flags(); + const auto memory = m_program.Resources().memoryInfo.at(flags.index); + for (std::uint32_t arm = 0; arm < arms.size(); arm++) { + std::vector arguments(inst.Arguments().begin(), inst.Arguments().end()); + for (std::uint32_t slot = 0; slot < handleCount; slot++) { + if (!split[slot]) { + continue; + } + std::vector dwords; + for (std::size_t dword = 0; dword < handles[slot]->ArgumentCount(); dword++) { + dwords.push_back(SubstituteEdge(handles[slot]->Argument(dword), arms[arm], inst, true, phiSearchDepth)); + } + arguments[slot] = EmitCopy(*handles[slot], dwords, inst); + } + auto copyFlags = flags; + if (arm != 0u) { + copyFlags.index = static_cast(m_program.Resources().memoryInfo.size()); + m_program.Resources().memoryInfo.push_back(memory); + } + std::uint64_t rawFlags = 0; + std::memcpy(&rawFlags, ©Flags, sizeof(copyFlags)); + copies.push_back(EmitBefore(inst, inst.Opcode(), inst.Type(), arguments, rawFlags)); + } + + IrValue* result = copies.back(); + if (copies.size() > 1u) { + std::array components {}; + for (std::uint32_t component = 0; component < components.size(); component++) { + const auto extract = [&](IrValue* vector) { + const std::array arguments {vector, &m_builder.Constant(component)}; + return EmitBefore(inst, IrOpcode::CompositeExtractU32x4, IrType::U32, arguments); + }; + IrValue* selected = extract(copies.back()); + for (std::uint32_t arm = static_cast(copies.size()) - 1u; arm-- > 0u;) { + std::vector edges(edgeArm.size()); + for (std::size_t edge = 0; edge < edgeArm.size(); edge++) { + edges[edge] = edgeArm[edge] == arm; + } + const std::array arguments {&EdgeSelector(*block, edges), extract(copies[arm]), selected}; + selected = EmitBefore(inst, IrOpcode::SelectU32, IrType::U32, arguments); + } + components[component] = selected; + } + result = EmitBefore(inst, IrOpcode::CompositeConstructU32x4, IrType::U32x4, components); + } + inst.ReplaceAllUsesWith(result); + inst.Invalidate(); + inst.Parent()->RemoveInstruction(&inst); + } + + void SplitDescriptorPhis() { + std::vector candidates; + for (auto& block : m_program.Blocks()) { + for (IrValue* inst : block->Instructions()) { + if (SplittableImageRead(*inst)) { + candidates.push_back(inst); + } + } + } + for (IrValue* inst : candidates) { + SplitDescriptorPhi(*inst); + } + } + void PlanIndirectImages() { // Kill switch: APS5_NO_BINDLESS_IMAGES=1 leaves table-loaded T#s unplanned (GetHandle then // rejects them as before). @@ -822,6 +1088,12 @@ private: // APS5_TRACE_BDA: address accesses seen by Collect (the first bdaTraceLimit are printed). unsigned m_bdaTraces = 0; std::vector m_indirectImages; + struct EdgeSelectorEntry { + IrBlock* block = nullptr; + std::vector edges; + IrValue* value = nullptr; + }; + std::vector m_edgeSelectors; }; }