From 879875d0952076dc543cf5e3206b5b11da9e9ead Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Wed, 25 Nov 2026 14:27:01 +0100 Subject: [PATCH 1/2] Shaders: every loop-cap hit is counted and named like the superstep caps The loop cap keeps the device alive when a loop runs on, but a program that reaches it draws or computes the wrong thing, and nothing said so unless --trace-pool-stores was on. A hit is a bug to fix where the wrong input or translation comes from, so it has to be seen on every run. The loop guard now calls loop_cap_hit, which keeps the trace and counts the hit once per wave in dword 3 of the program's slot of the window guard's cap table (unused until now). The loader's cap report names the programs with their waves past the loop cap beside the threads past the superstep block cap and the groups past the round bound. Tests: on WARP, two nested loops of 1,000 iterations (past the compute cap of 65,536) count in the program's slot and bounds of 10 count nothing; the test fails without the count. The loader reads the new dword and reports only what grew. Co-Authored-By: Claude Opus 5.5 --- docs/shader-translation.md | 5 +- .../Shims/D3D12X/Binding/CapCounts.cs | 7 +++ .../Shims/D3D12X/Binding/CapHit.cs | 10 ++++ .../Shims/D3D12X/Binding/WindowGuard.cs | 38 +++++++-------- .../Translation/Runtime/rdna_prelude.hlsli | 12 +++-- .../Translation/Structure/RegionEmitter.cs | 2 +- .../SuperstepCapTableTests.cs | 26 ++++++----- .../Cases/ComputeCaseRunner.cs | 24 ++++++++++ .../LoopCapCountTests.cs | 46 +++++++++++++++++++ 9 files changed, 135 insertions(+), 35 deletions(-) create mode 100644 src/FiveStar.Loader/Shims/D3D12X/Binding/CapCounts.cs create mode 100644 src/FiveStar.Loader/Shims/D3D12X/Binding/CapHit.cs create mode 100644 tests/FiveStar.Shaders.Tests/LoopCapCountTests.cs diff --git a/docs/shader-translation.md b/docs/shader-translation.md index 758254bd..6f0712b5 100644 --- a/docs/shader-translation.md +++ b/docs/shader-translation.md @@ -116,7 +116,10 @@ for compute, 2^20 elsewhere; 2^24 for every stage before). A console program's l on the data the console gives it; on the PC one wrong input keeps a loop going until the driver removes the device. The console has no cap, so a cap is only a safety net against our own wrong inputs and must not bind for a correct -program. The caps count all loops of one invocation together (a cap per loop let nested loops multiply it, 65,536² in +program. It keeps the device alive, not the output right: a hit is a bug to fix where the wrong input or +translation comes from. So every hit is counted (`loop_cap_hit`, once per wave, in dword 3 of the program's slot of +the window guard's cap table, beside the superstep block and round caps) and the loader names the programs at each +captured present (`[window guard] present N: K programs ran into a cap`). The caps count all loops of one invocation together (a cap per loop let nested loops multiply it, 65,536² in `CS_InitDepthPyramidWithCpuOcclusion3x3`): | Stage | Cap | Why | diff --git a/src/FiveStar.Loader/Shims/D3D12X/Binding/CapCounts.cs b/src/FiveStar.Loader/Shims/D3D12X/Binding/CapCounts.cs new file mode 100644 index 00000000..9ac3483c --- /dev/null +++ b/src/FiveStar.Loader/Shims/D3D12X/Binding/CapCounts.cs @@ -0,0 +1,7 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Loader.Shims.D3D12X.Binding; + +/// The cap counts last seen per slot, one array per kind (). +internal sealed record CapCounts(uint[] Blocks, uint[] Rounds, uint[] Loops); diff --git a/src/FiveStar.Loader/Shims/D3D12X/Binding/CapHit.cs b/src/FiveStar.Loader/Shims/D3D12X/Binding/CapHit.cs new file mode 100644 index 00000000..43d03081 --- /dev/null +++ b/src/FiveStar.Loader/Shims/D3D12X/Binding/CapHit.cs @@ -0,0 +1,10 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Loader.Shims.D3D12X.Binding; + +/// +/// A program's new cap hits since the last report (): threads past the superstep block +/// cap, groups past the round bound, waves past the loop cap. +/// +internal readonly record struct CapHit(uint Id, uint Blocks, uint Rounds, uint Loops); diff --git a/src/FiveStar.Loader/Shims/D3D12X/Binding/WindowGuard.cs b/src/FiveStar.Loader/Shims/D3D12X/Binding/WindowGuard.cs index 14515a89..9e772d3c 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/Binding/WindowGuard.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/Binding/WindowGuard.cs @@ -16,7 +16,8 @@ namespace FiveStar.Loader.Shims.D3D12X.Binding; /// sink dword after the table. At every captured present the programs that dropped stores since the last are logged. /// Such stores come from pointers built from a V# base that holds a heap index, and from 32-bit table pointers. A cap /// table follows (): per program {id, threads past the superstep block cap, groups past the -/// round bound}, logged likewise, so a program whose loop runs to the caps (a garbage trip count) is named. +/// round bound, waves past the loop cap}, logged likewise. A cap only keeps the device alive while a wrong input or a +/// translation bug runs a loop on; every hit is named so that its cause is found and fixed. /// internal static unsafe class WindowGuard { @@ -46,16 +47,16 @@ internal static unsafe class WindowGuard /// A slot: the program id, then its drops. private const uint SlotDwords = 2; - /// A cap slot: the program id, threads past the block cap, groups past the round bound, unused. + /// A cap slot: the program id, threads past the block cap, groups past the round bound, waves past the loop cap. private const uint CapSlotDwords = 4; private const int BlockDword = 1; private const int RoundDword = 2; + private const int LoopDword = 3; private const int Shown = 12; private const string Prefix = " [window guard] "; private static readonly uint[] Reported = new uint[Slots]; - private static readonly uint[] ReportedBlocks = new uint[Slots]; - private static readonly uint[] ReportedRounds = new uint[Slots]; + private static readonly CapCounts ReportedCaps = new(new uint[Slots], new uint[Slots], new uint[Slots]); private static Dictionary? _names; /// Whether programs made on demand drop their stores into the window. @@ -122,8 +123,8 @@ public static void Report(long present, LoaderLog log) } /// - /// Logs the programs that ran into the superstep caps since the last report: threads past the block cap and groups - /// past the round bound, by name; nothing when none did. The GPU is idle. + /// Logs the programs that ran into a cap since the last report: threads past the superstep block cap, groups past + /// the round bound and waves past the loop cap, by name; nothing when none did. The GPU is idle. /// public static void ReportCaps(long present, LoaderLog log) { @@ -134,7 +135,7 @@ public static void ReportCaps(long present, LoaderLog log) return; } - var hits = CapHits((uint*)(window + Base + CapOffset), ReportedBlocks, ReportedRounds); + var hits = CapHits((uint*)(window + Base + CapOffset), ReportedCaps); if (hits.Count == 0) { @@ -142,33 +143,34 @@ public static void ReportCaps(long present, LoaderLog log) } var names = Names(); - var text = new StringBuilder($"{Prefix}present {present}: {hits.Count} programs ran into the superstep caps:"); + var text = new StringBuilder($"{Prefix}present {present}: {hits.Count} programs ran into a cap (a wrong input or translation to fix):"); - foreach (var (id, blocks, rounds) in hits.OrderByDescending(hit => hit.Blocks + hit.Rounds).Take(Shown)) + foreach (var hit in hits.OrderByDescending(hit => (long)hit.Blocks + hit.Rounds + hit.Loops).Take(Shown)) { - text.Append($"\n{Prefix} {names.GetValueOrDefault(id, $"program 0x{id:x8}")}: {blocks} threads past the block cap, {rounds} groups past the round bound"); + var name = names.GetValueOrDefault(hit.Id, $"program 0x{hit.Id:x8}"); + text.Append($"\n{Prefix} {name}: {hit.Blocks} threads past the block cap, {hit.Rounds} groups past the round bound, {hit.Loops} waves past the loop cap"); } log.Warn(text.ToString()); } /// - /// The programs of the cap whose counts grew since and - /// (the counts last seen, updated): {id, new block-cap threads, new round-bound groups}. + /// The programs of the cap whose counts grew since (the counts last + /// seen, updated): the program id and the new block-cap threads, round-bound groups and loop-cap waves. /// - public static List<(uint Id, uint Blocks, uint Rounds)> CapHits(uint* table, uint[] blocks, uint[] rounds) + public static List CapHits(uint* table, CapCounts seen) { - var hits = new List<(uint Id, uint Blocks, uint Rounds)>(); + var hits = new List(); for (uint slot = 0; slot < Slots; slot++) { uint* entry = table + (slot * CapSlotDwords); - var (block, round) = (entry[BlockDword] - blocks[slot], entry[RoundDword] - rounds[slot]); - (blocks[slot], rounds[slot]) = (entry[BlockDword], entry[RoundDword]); + var hit = new CapHit(entry[0], entry[BlockDword] - seen.Blocks[slot], entry[RoundDword] - seen.Rounds[slot], entry[LoopDword] - seen.Loops[slot]); + (seen.Blocks[slot], seen.Rounds[slot], seen.Loops[slot]) = (entry[BlockDword], entry[RoundDword], entry[LoopDword]); - if (block != 0 || round != 0) + if (hit.Blocks != 0 || hit.Rounds != 0 || hit.Loops != 0) { - hits.Add((entry[0], block, round)); + hits.Add(hit); } } diff --git a/src/FiveStar.Shaders/Translation/Runtime/rdna_prelude.hlsli b/src/FiveStar.Shaders/Translation/Runtime/rdna_prelude.hlsli index da2c487e..2ba35a3b 100644 --- a/src/FiveStar.Shaders/Translation/Runtime/rdna_prelude.hlsli +++ b/src/FiveStar.Shaders/Translation/Runtime/rdna_prelude.hlsli @@ -129,9 +129,11 @@ void window_guard_count() { m.InterlockedAdd(slot + 4u, 1u); } #endif -// ---- Superstep caps (with the window guard, FIVESTAR_CAP_TABLE is the byte offset of its table in the window): a -// thread that ran out of blocks (kind 0) or a group that ran out of rounds (kind 1, counted by thread 0) is counted -// in slot FIVESTAR_PROGRAM_ID & 1023: {program id, threads past the block cap, groups past the round bound, 0}. +// ---- Caps (with the window guard, FIVESTAR_CAP_TABLE is the byte offset of its table in the window): a thread that +// ran out of superstep blocks (kind 0), a group that ran out of rounds (kind 1, counted by thread 0) and a wave whose +// lanes spent the loop cap (kind 2, counted by its first active lane) are counted in slot FIVESTAR_PROGRAM_ID & 1023: +// {program id, threads past the block cap, groups past the round bound, waves past the loop cap}. A cap keeps the +// device alive; the loader names every program that reaches one, so the input or translation behind it gets fixed. #ifdef FIVESTAR_CAP_TABLE void ss_cap_hit(uint kind) { RWByteAddressBuffer m = ResourceDescriptorHeap[GPU_MEM_HEAP + 1]; @@ -142,6 +144,10 @@ void ss_cap_hit(uint kind) { #else void ss_cap_hit(uint kind) {} #endif +void loop_cap_hit(uint guard, uint cap) { // structured loop number guard spent the invocation's loop cap + TRACE_GUARD(guard, cap); + if (WaveIsFirstLane()) ss_cap_hit(2u); +} uint PtrLoad(uint lo, uint hi, uint off) { // off is signed (a dword offset or an SMEM offset) uint2 a = ptr_add(lo, hi, 0u, asint(off)); if (hi == 0u) return MemLoad(a.x, 0u); diff --git a/src/FiveStar.Shaders/Translation/Structure/RegionEmitter.cs b/src/FiveStar.Shaders/Translation/Structure/RegionEmitter.cs index 8d4640a4..edf753f1 100644 --- a/src/FiveStar.Shaders/Translation/Structure/RegionEmitter.cs +++ b/src/FiveStar.Shaders/Translation/Structure/RegionEmitter.cs @@ -383,7 +383,7 @@ private void EmitBlock(int node, int depth) _loopGuards++; Add(depth, "[loop] for (;;) {"); - Add(depth + 1, $"if (++loop_budget > {_cap}) {{ TRACE_GUARD({guard}, {_cap}); break; }}"); + Add(depth + 1, $"if (++loop_budget > {_cap}) {{ loop_cap_hit({guard}, {_cap}); break; }}"); EmitScope(scope, selector, depth + 1); Add(depth, "}"); diff --git a/tests/FiveStar.Loader.Tests/SuperstepCapTableTests.cs b/tests/FiveStar.Loader.Tests/SuperstepCapTableTests.cs index 74945816..f1f0a21a 100644 --- a/tests/FiveStar.Loader.Tests/SuperstepCapTableTests.cs +++ b/tests/FiveStar.Loader.Tests/SuperstepCapTableTests.cs @@ -8,8 +8,8 @@ namespace FiveStar.Loader.Tests; /// -/// The superstep cap table after the window guard's: programs report threads past the block cap and groups past the -/// round bound per program slot, and each report names only what grew since the last. +/// The cap table after the window guard's: programs report threads past the block cap, groups past the round bound and +/// waves past the loop cap per program slot, and each report names only what grew since the last. /// public sealed unsafe class SuperstepCapTableTests { @@ -20,20 +20,22 @@ public sealed unsafe class SuperstepCapTableTests public void Each_report_names_the_programs_whose_cap_counts_grew_since_the_last() { uint* table = (uint*)NativeMemory.AllocZeroed(Slots * SlotDwords * sizeof(uint)); - var (blocks, rounds) = (new uint[Slots], new uint[Slots]); + var seen = new CapCounts(new uint[Slots], new uint[Slots], new uint[Slots]); try { - // LinearDepthSkin's id in its slot: 3,456 threads ran out of blocks; another program ran out of rounds twice. - Write(table, 0x5EED, 3456, 0); - Write(table, 0x0123, 0, 2); + // LinearDepthSkin's id in its slot: 3,456 threads ran out of blocks; another program ran out of rounds twice, + // a third has 5 waves past the loop cap. + Write(table, 0x5EED, 3456, 0, 0); + Write(table, 0x0123, 0, 2, 0); + Write(table, 0x0777, 0, 0, 5); - Assert.Equal([(0x0123u, 0u, 2u), (0x5EEDu, 3456u, 0u)], WindowGuard.CapHits(table, blocks, rounds)); + Assert.Equal([new CapHit(0x0123, 0, 2, 0), new CapHit(0x5EED, 3456, 0, 0), new CapHit(0x0777, 0, 0, 5)], WindowGuard.CapHits(table, seen)); // Nothing new: no report. Then 128 more threads of the first. - Assert.Empty(WindowGuard.CapHits(table, blocks, rounds)); - Write(table, 0x5EED, 3456 + 128, 0); - Assert.Equal([(0x5EEDu, 128u, 0u)], WindowGuard.CapHits(table, blocks, rounds)); + Assert.Empty(WindowGuard.CapHits(table, seen)); + Write(table, 0x5EED, 3456 + 128, 0, 0); + Assert.Equal([new CapHit(0x5EED, 128, 0, 0)], WindowGuard.CapHits(table, seen)); Assert.Contains($"#define {WindowGuard.CapDefine} {WindowGuard.Base + WindowGuard.CapOffset}u", WindowGuard.Header, StringComparison.Ordinal); Assert.True(WindowGuard.CapOffset + (Slots * SlotDwords * sizeof(uint)) <= WindowGuard.RegionBytes); @@ -45,9 +47,9 @@ public void Each_report_names_the_programs_whose_cap_counts_grew_since_the_last( } /// The slot of (id & 1023) as a program leaves it. - private static void Write(uint* table, uint id, uint blocks, uint rounds) + private static void Write(uint* table, uint id, uint blocks, uint rounds, uint loops) { uint* slot = table + ((id & (Slots - 1)) * SlotDwords); - (slot[0], slot[1], slot[2]) = (id, blocks, rounds); + (slot[0], slot[1], slot[2], slot[3]) = (id, blocks, rounds, loops); } } diff --git a/tests/FiveStar.Shaders.Tests/Cases/ComputeCaseRunner.cs b/tests/FiveStar.Shaders.Tests/Cases/ComputeCaseRunner.cs index 48640fec..aebb2c6f 100644 --- a/tests/FiveStar.Shaders.Tests/Cases/ComputeCaseRunner.cs +++ b/tests/FiveStar.Shaders.Tests/Cases/ComputeCaseRunner.cs @@ -101,6 +101,30 @@ public IReadOnlyList RunDirect(ComputeCase testCase) return (Compare(testCase, written, Math.Min(_fixture.ComputeWaveSize, testCase.Wave)), records, sites); } + /// + /// Runs a case with the cap table (rdna_prelude FIVESTAR_CAP_TABLE at the start of the writable window, heap slot 1) + /// under program id : the case's mismatches and the four dwords of the program's slot. + /// + public (IReadOnlyList Mismatches, uint[] Slot) RunCapCounted(ComputeCase testCase, uint id) + { + const int SlotDwords = 4; + const int Slots = 1024; + var defines = $"#define FIVESTAR_PROGRAM_ID {id}u\n#define FIVESTAR_CAP_TABLE 0u\n"; + var shader = Build(testCase with { Name = testCase.Name + "_caps" }, program => defines + ShaderWorkbench.Translate(program), direct: false); + + uint[] user = [.. ComputeCase.Descriptor(ComputeCase.OutputHeap), .. testCase.SecondDescriptor, .. testCase.User, .. new uint[ComputeCase.UserSgprCount]]; + var output = new BufferResource(ComputeCase.OutputHeap, [.. Enumerable.Repeat(testCase.Fill, testCase.TotalThreads * testCase.Outputs)], Writable: true); + var table = new BufferResource(ProbeRingSlot, new uint[Slots * SlotDwords], Writable: true); + var bindings = new Bindings { UserSgprs = user[..ComputeCase.UserSgprCount], Buffers = [output, table, .. testCase.Buffers], Textures = testCase.Textures }; + + var (x, y, z) = testCase.Groups; + var result = _fixture.Runner.Compute(new ComputeJob(shader, x, y, z, bindings)); + var written = result.Buffers.Concat(result.Textures).ToDictionary(pair => pair.Key, pair => pair.Value); + var start = (int)(id & (Slots - 1)) * SlotDwords; + + return (Compare(testCase, written, Math.Min(_fixture.ComputeWaveSize, testCase.Wave)), result.Buffers[ProbeRingSlot][start..(start + SlotDwords)]); + } + private static string GroupWave(ShaderProgram program) { // As the corpus builds it: structured (WARP's shader compiler crashes on barriers in the dispatch switch). diff --git a/tests/FiveStar.Shaders.Tests/LoopCapCountTests.cs b/tests/FiveStar.Shaders.Tests/LoopCapCountTests.cs new file mode 100644 index 00000000..3c65b757 --- /dev/null +++ b/tests/FiveStar.Shaders.Tests/LoopCapCountTests.cs @@ -0,0 +1,46 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using FiveStar.Shaders.Tests.Cases; +using FiveStar.Shaders.Tests.Toolchain; +using Xunit; + +namespace FiveStar.Shaders.Tests; + +/// +/// The loop cap only keeps the device alive; reaching it is a bug to fix (a wrong input or translation). A program +/// whose loops spend the cap counts it in its slot of the cap table (dword 3, once per wave), which the loader reports +/// by name; one that stays under the cap counts nothing. +/// +public sealed class LoopCapCountTests : IClassFixture +{ + private const uint Id = 0x2A7; + private const int LoopDword = 3; + + private readonly WarpFixture _fixture; + + public LoopCapCountTests(WarpFixture fixture) + { + _fixture = fixture; + } + + [WarpFact] + public void A_program_that_reaches_the_loop_cap_is_counted_and_one_under_it_is_not() + { + var runner = new ComputeCaseRunner(_fixture); + var nested = ComputeCases.All().Single(testCase => testCase.Name == "cs_loop_cap"); + + // Two nested loops of 1,000 iterations: past the compute cap of 65,536 in every lane. + var (mismatches, slot) = runner.RunCapCounted(nested, Id); + Assert.True(mismatches.Count == 0, string.Join("\n", mismatches.Take(8))); + Assert.Equal(Id, slot[0]); + Assert.True(slot[LoopDword] > 0, $"no wave counted past the loop cap: {string.Join(", ", slot)}"); + Assert.Equal(0u, slot[1]); + Assert.Equal(0u, slot[2]); + + // Bounds of 10: 100 iterations, nothing counted. + var (few, quiet) = runner.RunCapCounted(nested with { User = [10], Expect = _ => [10 * 10] }, Id); + Assert.True(few.Count == 0, string.Join("\n", few.Take(8))); + Assert.Equal([0u, 0u, 0u, 0u], quiet); + } +} From 2ea8bd4152320c4474cbcf09d99cbbf88bb4288d Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Wed, 25 Nov 2026 14:27:10 +0100 Subject: [PATCH 2/2] Tests: the assembled loop-cap case of the cap count test Co-Authored-By: Claude Opus 5.5 --- .../cs_loop_cap_caps.207f0f738d94ad26.bin | Bin 0 -> 64 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/cs_loop_cap_caps.207f0f738d94ad26.bin diff --git a/tests/FiveStar.Shaders.Tests/Assembled/cs_loop_cap_caps.207f0f738d94ad26.bin b/tests/FiveStar.Shaders.Tests/Assembled/cs_loop_cap_caps.207f0f738d94ad26.bin new file mode 100644 index 0000000000000000000000000000000000000000..4efb9e5c3310ad91f5148baf68e23aa7deb17945 GIT binary patch literal 64 zcmd-%pgvihA;_zNNu#cTdCI;9=BfJ{H8i|L8$}yLIk@)!`QN%