diff --git a/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp b/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp index d7fac7e84..f396d20e0 100644 --- a/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/ControlFlow.cpp @@ -72,6 +72,15 @@ void verifyStructured(const std::string& prefix, const ControlFlowGraph& graph) } } } + for (const auto& loop : graph.blocks) { + if (!loop.terminator.loopHeader) continue; + const auto continueBlock = loop.terminator.continueBlock; + for (const auto member : constructBlocks(graph, loop.id, loop.terminator.mergeBlock)) { + const auto& terminator = graph.FindBlock(member).terminator; + if (terminator.loopHeader || graph.Dominates(continueBlock, member)) continue; + require(terminator.mergeBlock != continueBlock, prefix + "the selection at block " + std::to_string(member) + " in the loop at block " + std::to_string(loop.id) + " merges at the loop's continue block " + std::to_string(continueBlock)); + } + } } std::uint32_t followEmptyBlocks(const std::string& prefix, const ControlFlowGraph& graph, std::uint32_t blockId, RouteState& routes) { @@ -279,6 +288,71 @@ latch: buffer_store_dword v1, off, s[0:3], 0 s_endpgm)", Store({0xbe880380u, 0x7e020280u, 0x7d880008u, 0xbf860004u, 0x7d880088u, 0xbf870003u, 0x4a020281u, 0xbf820002u, 0x4a020282u, 0x4a020283u, 0x80089008u, 0xbf0ac008u, 0xbf85fff5u}), Split::Clone}, + {"loop exit to the end of the program beside a kill exit", R"( + v_mov_b32 v1, 0 + s_mov_b64 s[20:21], exec + v_cmp_gt_u32 vcc, 4, v0 + s_andn2_b64 s[20:21], s[20:21], vcc + s_cbranch_scc0 kill + s_mov_b32 s8, 0 +loop: + v_add_nc_u32 v1, 1, v1 + v_cmp_eq_u32 vcc, s8, v0 + s_andn2_b64 s[20:21], s[20:21], vcc + s_cbranch_scc0 kill + s_add_u32 s8, s8, 1 + s_cmp_lt_u32 s8, 4 + s_cbranch_scc1 loop + s_mov_b64 exec, s[20:21] + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm +kill: + s_mov_b64 exec, 0 + s_endpgm)", + {0x7e020280u, 0xbe94047eu, 0x7d880084u, 0x8a946a14u, 0xbf84000cu, 0xbe880380u, 0x4a020281u, 0x7d840008u, 0x8a946a14u, 0xbf840007u, + 0x80088108u, 0xbf0a8408u, 0xbf85fff9u, 0xbefe0414u, 0xe0700000u, 0x80000100u, 0xbf810000u, 0xbefe0480u, 0xbf810000u}, + Split::Route, 0}, + {"inner loop exit to a return after the outer loop", R"( + v_mov_b32 v1, 0 + s_mov_b32 s8, 0 +outer: + s_mov_b32 s9, 0 +inner: + v_add_nc_u32 v1, 1, v1 + s_cmp_eq_u32 s9, s2 + s_cbranch_scc1 early_exit + s_add_u32 s9, s9, 1 + s_cmp_lt_u32 s9, 4 + s_cbranch_scc1 inner + s_add_u32 s8, s8, 1 + s_cmp_lt_u32 s8, 4 + s_cbranch_scc1 outer + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm +early_exit: + v_add_nc_u32 v1, 2, v1 + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + {0x7e020280u, 0xbe880380u, 0xbe890380u, 0x4a020281u, 0xbf060209u, 0xbf850009u, 0x80098109u, 0xbf0a8409u, 0xbf85fffau, 0x80088108u, + 0xbf0a8408u, 0xbf85fff6u, 0xe0700000u, 0x80000100u, 0xbf810000u, 0x4a020282u, 0xe0700000u, 0x80000100u, 0xbf810000u}, + Split::Route, 0}, + {"loop exit tail beside the continue block", R"( + v_mov_b32 v1, 0 + s_mov_b32 s8, 0 +loop: + v_add_nc_u32 v1, 1, v1 + s_cmp_eq_u32 s8, s2 + s_cbranch_scc0 latch + v_add_nc_u32 v1, 2, v1 + s_branch done +latch: + s_add_u32 s8, s8, 1 + s_cmp_lt_u32 s8, 4 + s_cbranch_scc1 loop +done: + buffer_store_dword v1, off, s[0:3], 0 + s_endpgm)", + Store({0x7e020280u, 0xbe880380u, 0x4a020281u, 0xbf060208u, 0xbf840002u, 0x4a020282u, 0xbf820003u, 0x80088108u, 0xbf0a8408u, 0xbf85fff8u}), Split::None}, {"shared early exit", R"( v_mov_b32 v1, 0 v_cmp_gt_u32 vcc, 16, v0 diff --git a/core/libs/prx/libSceAgcDriver/tests/Structurizer.cpp b/core/libs/prx/libSceAgcDriver/tests/Structurizer.cpp index 540652d6c..bd62650a5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Structurizer.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Structurizer.cpp @@ -59,8 +59,14 @@ const BasicBlock* innermostLoopHeader(const ControlFlowGraph& graph, std::uint32 void requireStructuredBranches(const ControlFlowGraph& graph, const char* name) { for (const auto& block : graph.blocks) { const auto& terminator = block.terminator; - if (terminator.kind != TerminatorKind::ConditionalBranch || terminator.loopHeader || terminator.mergeBlock != InvalidControlFlowId || terminator.trueBlock == terminator.falseBlock) continue; + if (terminator.kind != TerminatorKind::ConditionalBranch || terminator.loopHeader || terminator.trueBlock == terminator.falseBlock) continue; const auto* loop = innermostLoopHeader(graph, block.id); + if (terminator.mergeBlock != InvalidControlFlowId) { + if (loop != nullptr && terminator.mergeBlock == loop->terminator.continueBlock) { + throw std::runtime_error(std::string(name) + ": block " + std::to_string(block.id) + " in the loop at block " + std::to_string(loop->id) + " merges at the loop's continue block " + std::to_string(terminator.mergeBlock)); + } + continue; + } const auto exits = [&](std::uint32_t target) { return loop != nullptr && (target == loop->terminator.mergeBlock || target == loop->terminator.continueBlock); }; if (!exits(terminator.trueBlock) && !exits(terminator.falseBlock)) { throw std::runtime_error(std::string(name) + ": block " + std::to_string(block.id) + " branches to " + std::to_string(terminator.trueBlock) + "/" + std::to_string(terminator.falseBlock) + " without a merge, and neither is its loop's merge or continue"); @@ -85,6 +91,15 @@ int main() { auto exitTails = makeGraph({{1}, {2}, {3, 4}, {7}, {5, 6}, {7, 1}, {7}, {}}); Structurizer{}.Structurize(exitTails); requireStructuredBranches(exitTails, "a loop with two exit tails"); + auto endingExits = makeGraph({{6, 1}, {2}, {3}, {6, 4}, {2, 5}, {}, {}}); + Structurizer{}.Structurize(endingExits); + requireStructuredBranches(endingExits, "a loop whose two exits end the program"); + auto threeEndingExits = makeGraph({{1}, {2}, {5, 3}, {6, 4}, {1, 7}, {}, {}, {}}); + Structurizer{}.Structurize(threeEndingExits); + requireStructuredBranches(threeEndingExits, "a loop whose three exits end the program"); + auto innerEndingExit = makeGraph({{1}, {2}, {3}, {7, 4}, {2, 5}, {1, 6}, {}, {}}); + Structurizer{}.Structurize(innerEndingExit); + requireStructuredBranches(innerEndingExit, "an inner loop exit that ends the program"); auto earlyReturn = makeGraph({{2, 1}, {4, 2}, {3, 5}, {5}, {}, {}}); Structurizer{}.Structurize(earlyReturn); requireStructuredBranches(earlyReturn, "an early return inside a selection that joins its parent's merge"); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/LoopEndingExits.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/LoopEndingExits.cpp new file mode 100644 index 000000000..aee93278d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/LoopEndingExits.cpp @@ -0,0 +1,99 @@ +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Draw.hpp" +#include "Recompiler.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::Require; +using ShaderRecompiler::ShaderStage; + +constexpr std::uint32_t Threads = 64; +constexpr std::uint32_t Stride = 4; +constexpr std::uint32_t SelectorRegister = 8; +alignas(256) std::array Input{}; +alignas(256) std::array Output{}; + +alignas(256) constexpr std::array Code{ + 0x34020082, 0xe0302000, 0x80000401, 0xbf8c3f70, 0xbe890380, 0xbf068008, 0xbf85000a, 0x4a080881, 0x80098109, 0xbf060809, 0xbf850006, + 0xbf0a8409, 0xbf85fffa, 0x4a0808c0, 0xe0702000, 0x80010401, 0xbf810000, 0x4a0808a0, 0xe0702000, 0x80010401, 0xbf810000, +}; + +struct Case { + const char* name; + std::uint32_t selector; + std::uint32_t added; +}; + +const std::array Cases{{ + {"early exit before the loop", 0u, 32u}, + {"early exit from the first iteration", 1u, 33u}, + {"early exit from the third iteration", 3u, 35u}, + {"early exit from the last iteration", 4u, 36u}, + {"loop exit to the end of the program", 5u, 68u}, +}}; + +std::array BufferDescriptor(const void* data, std::uint32_t count) { + const auto address = reinterpret_cast(data); + return {static_cast(address), static_cast((address >> 32u) & 0xffffu) | (4u << 16u), count, 0x01016facu}; +} + +void Run(AgcDriver::VulkanDevice& device, const Case& test, std::uint32_t waveSize) { + for (std::uint32_t tid = 0; tid < Threads; ++tid) Input[tid * Stride] = tid * 0x01010101u + 7u; + Output.fill(0xdeadbeefu); + std::vector userData(SelectorRegister + 1u, 0u); + const auto input = BufferDescriptor(Input.data(), static_cast(Input.size())); + const auto output = BufferDescriptor(Output.data(), static_cast(Output.size())); + std::copy(input.begin(), input.end(), userData.begin()); + std::copy(output.begin(), output.end(), userData.begin() + 4); + userData[SelectorRegister] = test.selector; + const std::span code(Code); + const std::array memory{{{reinterpret_cast(code.data()), std::as_bytes(code)}}}; + const ShaderRecompiler::ShaderComputeStageInfo compute{{Threads, 1, 1}, 0, {false, false, false}, false, 1}; + ShaderRecompiler::RecompileRequest request{ + {ShaderStage::Compute, reinterpret_cast(code.data()), code, 0, {}}, + {waveSize, 0, userData, compute, std::nullopt, std::nullopt, memory}, + device.Target(), + {0, 0, 0, 128} + }; + request.useCache = false; + const auto result = ShaderRecompiler::Recompile(request); + device.Dispatch(result, 1, 1, 1, {}, reinterpret_cast(code.data())); + device.WaitIdle(); +} + +void Check(const Case& test, std::uint32_t waveSize) { + for (std::uint32_t tid = 0; tid < Threads; ++tid) { + const auto expected = Input[tid * Stride] + test.added; + const auto actual = Output[tid * Stride]; + Require(actual == expected, "loop ending exits wave" + std::to_string(waveSize) + ": " + test.name + ": thread " + std::to_string(tid) + " is " + std::to_string(actual) + ", expected " + std::to_string(expected)); + } +} + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + for (const auto waveSize : {32u, 64u}) { + for (const auto& test : Cases) { + Run(*device, test, waveSize); + Check(test, waveSize); + } + } + std::puts("loop ending exits tests passed"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/shader/recompiler/ControlFlow/src/Structurizer.cpp b/core/shader/recompiler/ControlFlow/src/Structurizer.cpp index 5560236f5..6f6eb09be 100644 --- a/core/shader/recompiler/ControlFlow/src/Structurizer.cpp +++ b/core/shader/recompiler/ControlFlow/src/Structurizer.cpp @@ -517,7 +517,7 @@ std::uint32_t exitTailSelectionMerge(const ControlFlowGraph& graph, const BasicB } const auto body = trueInBody ? trueTarget : falseTarget; const auto tail = trueInBody ? falseTarget : trueTarget; - if (tail == loop->mergeBlock || tail == loop->continueBlock || !isInsideLoopConstruct(graph, *loop, tail) || !graph.Dominates(block.id, body) || !graph.Dominates(block.id, tail)) { + if (tail == loop->mergeBlock || tail == loop->continueBlock || body == loop->continueBlock || !isInsideLoopConstruct(graph, *loop, tail) || !graph.Dominates(block.id, body) || !graph.Dominates(block.id, tail)) { return InvalidControlFlowId; } std::vector pending{tail}; @@ -889,6 +889,33 @@ void setBranch(BasicBlock& block, std::uint32_t target) { block.terminator.trueBlock = target; } +std::uint32_t appendAssignmentBlock(ControlFlowGraph& graph, std::uint32_t positionBlock, std::uint32_t target, std::uint32_t variable, std::int32_t value) { + const auto assignment = appendRouteBlock(graph, positionBlock); + auto& block = graph.FindBlock(assignment); + setBranch(block, target); + block.terminator.gotoVariable = variable; + block.terminator.gotoValue = value; + return assignment; +} + +std::uint32_t appendJunction(ControlFlowGraph& graph, const std::vector& targets, std::uint32_t firstVariable) { + auto next = targets.back(); + for (auto index = static_cast(targets.size() - 1u); index-- > 0u;) { + const auto dispatch = appendRouteBlock(graph, targets[index]); + auto& block = graph.FindBlock(dispatch); + block.successors = {targets[index], next}; + block.terminator.kind = TerminatorKind::ConditionalBranch; + block.terminator.condition = BranchCondition::GotoVariable; + block.terminator.trueBlock = targets[index]; + block.terminator.falseBlock = next; + block.terminator.gotoVariable = firstVariable + index; + next = dispatch; + } + const auto junction = appendRouteBlock(graph, targets.front()); + setBranch(graph.FindBlock(junction), next); + return junction; +} + std::optional routeThroughJunction(const ControlFlowGraph& graph, std::uint32_t header, std::uint32_t merge, const std::vector& region, const std::vector& entered, const std::vector& entryEdges, SplitBudget& budget, const std::function& recompute, std::string& refusal) { std::vector routed = entryEdges; std::vector sources = {header}; @@ -930,31 +957,12 @@ std::optional routeThroughJunction(const ControlFlowGraph& gra auto candidate = graph; const auto variableCount = static_cast(targets.size() - 1u); const auto firstVariable = budget.nextGotoVariable; - auto next = targets.back(); - for (auto index = variableCount; index-- > 0u;) { - const auto dispatch = appendRouteBlock(candidate, targets[index]); - auto& block = candidate.FindBlock(dispatch); - block.successors = {targets[index], next}; - block.terminator.kind = TerminatorKind::ConditionalBranch; - block.terminator.condition = BranchCondition::GotoVariable; - block.terminator.trueBlock = targets[index]; - block.terminator.falseBlock = next; - block.terminator.gotoVariable = firstVariable + index; - next = dispatch; - } - const auto junction = appendRouteBlock(candidate, targets.front()); - setBranch(candidate.FindBlock(junction), next); - + const auto junction = appendJunction(candidate, targets, firstVariable); for (const auto& [source, target] : routed) { const auto targetIndex = static_cast(std::distance(targets.begin(), std::find(targets.begin(), targets.end(), target))); auto entry = junction; for (auto index = std::min(targetIndex + 1u, variableCount); index-- > 0u;) { - const auto assignment = appendRouteBlock(candidate, target); - auto& block = candidate.FindBlock(assignment); - setBranch(block, entry); - block.terminator.gotoVariable = firstVariable + index; - block.terminator.gotoValue = index == targetIndex ? 1 : 0; - entry = assignment; + entry = appendAssignmentBlock(candidate, target, entry, firstVariable + index, index == targetIndex ? 1 : 0); } redirectEdge(candidate.FindBlock(source), target, entry); } @@ -972,6 +980,87 @@ std::optional routeThroughJunction(const ControlFlowGraph& gra return candidate; } +std::uint32_t nextGotoVariable(const ControlFlowGraph& graph) { + std::uint32_t next = 0; + for (const auto& block : graph.blocks) { + if (block.terminator.gotoVariable != InvalidControlFlowId) { + next = std::max(next, block.terminator.gotoVariable + 1u); + } + } + return next; +} + +std::optional routeLoopExits(const ControlFlowGraph& graph, const NaturalLoop& loop, const std::function& recompute, std::string& refusal) { + std::vector exits; + for (const auto member : loop.blocks) { + const auto& block = graph.FindBlock(member); + for (const auto successor : block.successors) { + if (contains(loop.blocks, successor)) { + continue; + } + if (block.terminator.kind != TerminatorKind::Branch && block.terminator.kind != TerminatorKind::ConditionalBranch) { + refusal = "block " + std::to_string(member) + " ends in an indirect or unsupported branch"; + return std::nullopt; + } + exits.emplace_back(member, successor); + } + } + + const auto order = reversePostOrder(graph); + const auto orderOf = [&](std::uint32_t blockId) { + return std::distance(order.begin(), std::find(order.begin(), order.end(), blockId)); + }; + std::vector targets; + for (const auto& edge : exits) { + addUnique(targets, edge.second); + } + std::sort(targets.begin(), targets.end(), [&](std::uint32_t lhs, std::uint32_t rhs) { return orderOf(lhs) < orderOf(rhs); }); + const auto latchExit = std::find_if(exits.begin(), exits.end(), [&](const Edge& edge) { return edge.first == loop.latchBlock; }); + const auto fallback = latchExit != exits.end() ? latchExit->second : targets.back(); + targets.erase(std::find(targets.begin(), targets.end(), fallback)); + targets.push_back(fallback); + + auto candidate = graph; + const auto firstVariable = nextGotoVariable(graph); + const auto variableCount = static_cast(targets.size() - 1u); + const auto junction = appendJunction(candidate, targets, firstVariable); + + auto entry = loop.headerBlock; + for (auto index = variableCount; index-- > 0u;) { + entry = appendAssignmentBlock(candidate, loop.headerBlock, entry, firstVariable + index, 0); + } + for (const auto predecessor : graph.FindBlock(loop.headerBlock).predecessors) { + if (!contains(loop.blocks, predecessor)) { + redirectEdge(candidate.FindBlock(predecessor), loop.headerBlock, entry); + } + } + if (candidate.entryBlock == loop.headerBlock) { + candidate.entryBlock = entry; + } + + for (const auto& [source, target] : exits) { + const auto index = static_cast(std::distance(targets.begin(), std::find(targets.begin(), targets.end(), target))); + const auto exit = index == variableCount ? junction : appendAssignmentBlock(candidate, target, junction, firstVariable + index, 1); + redirectEdge(candidate.FindBlock(source), target, exit); + } + rebuildPredecessors(candidate); + recompute(candidate); + if (candidate.irreducible || candidate.unsupported) { + refusal = "routing its exits through one block would make the graph irreducible"; + return std::nullopt; + } + if (loopEdges(candidate) != loopEdges(graph)) { + refusal = "routing its exits through one block would change the natural loops"; + return std::nullopt; + } + const auto routed = std::find_if(candidate.naturalLoops.begin(), candidate.naturalLoops.end(), [&](const NaturalLoop& value) { return value.headerBlock == loop.headerBlock; }); + if (routed == candidate.naturalLoops.end() || routed->mergeBlock != junction) { + refusal = "routing its exits through one block does not make that block its merge"; + return std::nullopt; + } + return candidate; +} + bool structurizeEnteredRegion(ControlFlowGraph& graph, std::uint32_t header, std::uint32_t merge, const std::vector& region, SplitBudget& budget, const std::function& recompute) { const auto entryEdges = externalEntryEdges(graph, header, region); if (entryEdges.empty()) { @@ -1269,7 +1358,7 @@ void Structurizer::detectNaturalLoops(ControlFlowGraph& graph) const { if (!loop.exitBlocks.empty()) { std::uint32_t merge = loop.exitBlocks.front(); - for (std::size_t i = 1; i < loop.exitBlocks.size(); ++i) { + for (std::size_t i = 1; i < loop.exitBlocks.size() && merge != InvalidControlFlowId; ++i) { merge = graph.FindNearestCommonPostDominator(merge, loop.exitBlocks[i]); } loop.mergeBlock = merge; @@ -1403,9 +1492,25 @@ void Structurizer::canonicalizeNaturalLoops(ControlFlowGraph& graph) const { changed = true; break; } - if (!changed) { + if (changed) { + continue; + } + + const NaturalLoop* unmerged = nullptr; + for (const auto& loop : graph.naturalLoops) { + if (loop.exitBlocks.size() > 1u && loop.mergeBlock == InvalidControlFlowId && (unmerged == nullptr || loop.blocks.size() < unmerged->blocks.size())) { + unmerged = &loop; + } + } + if (unmerged == nullptr) { return; } + std::string refusal; + auto routed = routeLoopExits(graph, *unmerged, [this](ControlFlowGraph& candidate) { recomputeAnalyses(candidate); }, refusal); + if (!routed) { + throw std::runtime_error("loop at block " + std::to_string(unmerged->headerBlock) + " has exits with no common post-dominator: " + refusal); + } + graph = std::move(*routed); } throw std::runtime_error("CFG loop canonicalization exceeded rewrite budget"); @@ -1415,13 +1520,7 @@ void Structurizer::splitSharedMergeBlocks(ControlFlowGraph& graph) const { const auto originalBlockCount = static_cast(graph.blocks.size()); const auto splitBudget = std::max(16u, originalBlockCount * 4u); const auto programWords = estimatedSpirvWords(graph, allBlockIds(originalBlockCount)); - std::uint32_t nextGotoVariable = 0; - for (const auto& block : graph.blocks) { - if (block.terminator.gotoVariable != InvalidControlFlowId) { - nextGotoVariable = std::max(nextGotoVariable, block.terminator.gotoVariable + 1u); - } - } - SplitBudget budget{programWords, std::max(CloneWordLimit, programWords / CloneBudgetDivisor), std::max(CloneWordLimit, programWords), nextGotoVariable}; + SplitBudget budget{programWords, std::max(CloneWordLimit, programWords / CloneBudgetDivisor), std::max(CloneWordLimit, programWords), nextGotoVariable(graph)}; for (std::uint32_t splits = 0; splits < splitBudget; ++splits) { if (!splitOneLoopMerge(graph) && !splitOneSelectionMerge(graph, budget, [this](ControlFlowGraph& candidate) { recomputeAnalyses(candidate); }) && !splitOneReturnJoin(graph)) { return;