Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/shader-translation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
7 changes: 7 additions & 0 deletions src/FiveStar.Loader/Shims/D3D12X/Binding/CapCounts.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>The cap counts last seen per slot, one array per kind (<see cref="WindowGuard.CapHits"/>).</summary>
internal sealed record CapCounts(uint[] Blocks, uint[] Rounds, uint[] Loops);
10 changes: 10 additions & 0 deletions src/FiveStar.Loader/Shims/D3D12X/Binding/CapHit.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// A program's new cap hits since the last report (<see cref="WindowGuard.CapHits"/>): threads past the superstep block
/// cap, groups past the round bound, waves past the loop cap.
/// </summary>
internal readonly record struct CapHit(uint Id, uint Blocks, uint Rounds, uint Loops);
38 changes: 20 additions & 18 deletions src/FiveStar.Loader/Shims/D3D12X/Binding/WindowGuard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 (<see cref="CapDefine"/>): 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.
/// </summary>
internal static unsafe class WindowGuard
{
Expand Down Expand Up @@ -46,16 +47,16 @@ internal static unsafe class WindowGuard
/// <summary>A slot: the program id, then its drops.</summary>
private const uint SlotDwords = 2;

/// <summary>A cap slot: the program id, threads past the block cap, groups past the round bound, unused.</summary>
/// <summary>A cap slot: the program id, threads past the block cap, groups past the round bound, waves past the loop cap.</summary>
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<uint, string>? _names;

/// <summary>Whether programs made on demand drop their stores into the window.</summary>
Expand Down Expand Up @@ -122,8 +123,8 @@ public static void Report(long present, LoaderLog log)
}

/// <summary>
/// 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.
/// </summary>
public static void ReportCaps(long present, LoaderLog log)
{
Expand All @@ -134,41 +135,42 @@ 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)
{
return;
}

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());
}

/// <summary>
/// The programs of the cap <paramref name="table"/> whose counts grew since <paramref name="blocks"/> and
/// <paramref name="rounds"/> (the counts last seen, updated): {id, new block-cap threads, new round-bound groups}.
/// The programs of the cap <paramref name="table"/> whose counts grew since <paramref name="seen"/> (the counts last
/// seen, updated): the program id and the new block-cap threads, round-bound groups and loop-cap waves.
/// </summary>
public static List<(uint Id, uint Blocks, uint Rounds)> CapHits(uint* table, uint[] blocks, uint[] rounds)
public static List<CapHit> CapHits(uint* table, CapCounts seen)
{
var hits = new List<(uint Id, uint Blocks, uint Rounds)>();
var hits = new List<CapHit>();

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);
}
}

Expand Down
12 changes: 9 additions & 3 deletions src/FiveStar.Shaders/Translation/Runtime/rdna_prelude.hlsli
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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, "}");

Expand Down
26 changes: 14 additions & 12 deletions tests/FiveStar.Loader.Tests/SuperstepCapTableTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
namespace FiveStar.Loader.Tests;

/// <summary>
/// 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.
/// </summary>
public sealed unsafe class SuperstepCapTableTests
{
Expand All @@ -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);
Expand All @@ -45,9 +47,9 @@ public void Each_report_names_the_programs_whose_cap_counts_grew_since_the_last(
}

/// <summary>The slot of <paramref name="id"/> (id &amp; 1023) as a program leaves it.</summary>
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);
}
}
Binary file not shown.
24 changes: 24 additions & 0 deletions tests/FiveStar.Shaders.Tests/Cases/ComputeCaseRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,30 @@ public IReadOnlyList<string> RunDirect(ComputeCase testCase)
return (Compare(testCase, written, Math.Min(_fixture.ComputeWaveSize, testCase.Wave)), records, sites);
}

/// <summary>
/// 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 <paramref name="id"/>: the case's mismatches and the four dwords of the program's slot.
/// </summary>
public (IReadOnlyList<string> 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).
Expand Down
46 changes: 46 additions & 0 deletions tests/FiveStar.Shaders.Tests/LoopCapCountTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
public sealed class LoopCapCountTests : IClassFixture<WarpFixture>
{
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);
}
}
Loading