From 11c630023dbdc319d03451c3561949df828b66de Mon Sep 17 00:00:00 2001 From: almostxxx27 <361921142+almostxxx27@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:15:54 +0100 Subject: [PATCH 1/2] Implement cheaper wave64 mesh shaders on 32-lane GPUs, IDEA 2 --- docs/issue-35-wave64-mesh.md | 106 ++++++++++++++++++ docs/shader-translation.md | 2 +- .../Translation/Waves/StatementTransfer.cs | 34 +++++- .../Translation/Waves/ValueRules.cs | 24 ++-- .../Translation/Waves/WindowStatement.cs | 50 +++++++++ .../mesh_floor_4_77.f08fafa408ce54d7.bin | Bin 0 -> 76 bytes .../mesh_floor_4_87.0919f048b53ed696.bin | Bin 0 -> 76 bytes .../mesh_floor_64_87.d363f093639c9b63.bin | Bin 0 -> 76 bytes .../mesh_window_4_58.29401afbfeb39ee8.bin | Bin 0 -> 64 bytes .../mesh_window_64_27.79f4c5b4db840eb2.bin | Bin 0 -> 56 bytes .../mesh_window_64_27.9a07faff13074e8b.bin | Bin 0 -> 56 bytes .../mesh_window_64_58.2d5af78d73c7c83d.bin | Bin 0 -> 64 bytes .../WaveEmulationTests.cs | 31 +++++ 13 files changed, 231 insertions(+), 16 deletions(-) create mode 100644 docs/issue-35-wave64-mesh.md create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_87.0919f048b53ed696.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_64_87.d363f093639c9b63.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_window_4_58.29401afbfeb39ee8.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_window_64_27.79f4c5b4db840eb2.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_window_64_27.9a07faff13074e8b.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_window_64_58.2d5af78d73c7c83d.bin diff --git a/docs/issue-35-wave64-mesh.md b/docs/issue-35-wave64-mesh.md new file mode 100644 index 00000000..fe9aa98e --- /dev/null +++ b/docs/issue-35-wave64-mesh.md @@ -0,0 +1,106 @@ +# #35: cheaper wave64 mesh shaders on 32-lane GPUs + +Notes on the three ideas from issue #35, grounded in [shader-translation.md](shader-translation.md). + +## The problem + +The console runs every mesh shader in 64-lane waves and the game's code depends on that: ballots read as numbers, +`readfirstlane` of per-lane values, GS_ALLOC_REQ counts. On a 32-lane GPU (NVIDIA) each console wave becomes two +hardware waves that cannot see each other's lanes. The exact fix, the **superstep form**, cuts the program at every +wave operation, deposits values in groupshared memory and passes a **group barrier** per cut. Correct, but +`MSNC_VS_LinearDepthSkin` has about 85 such stops: ~75 µs per round, and a draw can take seconds. 2,548 of 8,765 mesh +programs have floor = whole wave and so take this path on NVIDIA. AMD is already solved by #29 (RDNA runs mesh +shaders natively at 64). + +## Idea 1: XCL-style compute pre-pass at `[WaveSize(64)]` + +**Why it works.** Mesh shaders cannot choose their wave size, but compute shaders can (`[WaveSize(64)]`, SM 6.6+). +NVIDIA Ampere and later support wave64 *compute* even though their mesh waves are 32. So: run the real program as a +compute shader pinned to 64 lanes (console-exact, zero barriers), write vertices and primitives to a buffer, then a +trivial mesh shader copies that buffer into `SetMeshOutputCounts` and the outputs. + +**What already exists.** `MeshComputeFallback` (`.msfb_cs.hlsl` / `.msfb_vs.hlsl`) rewrites a mesh program as +compute plus a vertex-pulling vertex shader, and there is already a `.msfb_cs.w64.hlsl` variant pinned to the console +wave. That is about 80 % of this idea. The missing piece is a mesh-shader emitter instead of the VS, so the draw stays a +mesh dispatch (ExecuteIndirect arguments, primitive culling and per-primitive attributes stay intact). + +**Where to start.** + +1. `VariantSelector` (flowchart in shader-translation.md): add a branch "adapter supports `WaveSize(64)` compute but + measured mesh wave < floor → pre-pass". +2. A new emitter beside `MeshComputeFallback` that generates `.msfb_ms.hlsl`. +3. Runtime: the loader needs a compute dispatch before the mesh dispatch, sharing an intermediate buffer. + [d3d12x-pipelines.md](d3d12x-pipelines.md) shows how pipelines are keyed; the breadcrumb and ExecuteIndirect code + already handles multi-pass loader-owned work (`loader:` pipelines). + +**Cost and risk.** One extra buffer and barrier per draw; indirect draws need the compute pass to read the same +argument buffer. Still vastly cheaper than 85 group barriers. + +## Idea 2: prove more operations wave-size independent + +The compiler-analysis route: shrink the 2,548 whole-wave programs. The top reasons the analysis gives up: + +| Reason | Programs | +|---|---:| +| `readfirstlane` of a per-lane value in an output or GS_ALLOC_REQ | 1,338 | +| integer VCC branch | 588 | +| VCC branch whose mask lost its relation to EXEC | 304 | +| execz path that cannot be skipped | 246 | + +Each row is a candidate rule in `Translation/Waves/WindowAnalysis` (floor computation) or `SkipRegion` (deciding +that a path may be skipped or taken alone). Example attack on the biggest row: a `readfirstlane` is fine when the +value is provably uniform across the console wave even if per-lane in form, e.g. loaded from a uniform address or +derived from SGPRs only. Extending `WindowAnalysis.EntryFacts` to track "uniform on all active lanes" more precisely +would move programs from floor 64 to floor ≤ 32 and off the superstep path entirely. + +This is the most contained work: pure translator, testable with `fivestar shader translate` and the floor histogram +in shader-translation.md, no runtime changes. + +### First step (branch `issue-35-uniform-first-lane-reads`) + +Three rules in `Translation/Waves`, each sound by the prelude's semantics and covered by a floor test in +`WaveEmulationTests` that the old analysis fails: + +1. **Compound assignments keep facts** (`WindowStatement.Parts`, `StatementTransfer.Apply`). `v_mad_u64_u32` and the + 64-bit shifts (the address math of `base + readfirstlane(index) * stride`) emit + `if (active) { lo = (uint)_p; hi = (uint)(_p >> 32); } }`, which parsed as an opaque statement and dropped every + uniformity fact, so the `readfirstlane` that followed was "of a per-lane value". The halves are now applied as the + guarded assignments they are. +2. **Bits equal on all lanes are the console's under any EXEC** (`ValueRules.FirstLane`). `readfirstlane(x)` returns + some lane's `x` even when the window has no active lane or its active lanes are not the console's, so the + `AllUniform` bits (an SGPR copy, the group's bits of the mesh thread id) are exact regardless. Before, the result + was unknown unless EXEC was exact and non-empty. +3. **Non-effect opaque statements propagate uniformity** (`StatementTransfer.Opaque`). `GetDimensions`, the + class-switch loads and `asuint(double, lo, hi)` now give their results the uniformity of their reads (like any + assignment), an `asuint` split marks its out-parameters assigned (a soundness fix: they were left at their declared + "exact and uniform"), and effects (atomics' old values) stay per-lane. + +What this cannot prove, by design: a guarded uniform-address load leaves inactive lanes at 0 (uniform on the active +lanes, not on all), so its `readfirstlane` under a shrunk EXEC is only "held" and is lost when EXEC is restored; and +TransformD's data-dependent counts still need `FirstLaneExchange`. The corpus histogram above has to be re-run with +`fivestar shader translate` by someone holding the shader dump. + +## Idea 3: make `--fast-waves` safe + +`--fast-waves` keeps the native form and approximates: each hardware wave's `readfirstlane` is taken as the console's +and "any lane" branches are decided per hardware wave. 1,399 of 2,540 programs run this way. It is parked because of +`0194d7ba` (`MSNC_VS_CascadeShadows_drawskinnedTexture_3c28b1bd`): a branch at 0x9a8 on `vw_any(m_s_vcc)` is decided +per hardware wave and the two sides have **different numbers of mesh barriers** (one or two yields), so the two halves +of a console wave disagree on the barrier count and the group hangs. + +The doc's own diagnosis: the analysis treats that branch as uniform because its facts come from the approximated +`readfirstlane` values, so the dangerous branch is never checked. Refusing every barrier under a branch kills fast +waves for everything (0 of 127 sampled). + +**Fix: two fact sets.** Run `WindowAnalysis` once with exact facts and once with fast facts. For any branch that leads +to paths with unequal barrier counts, require the *exact* facts to prove it uniform; otherwise fall back to the +superstep form for that program only. That keeps most of the 1,399 fast and refuses only the genuinely +divergent-barrier ones. + +## Which to pick + +- **Fastest payoff for NVIDIA users:** Idea 1. It attacks the worst programs (LinearDepthSkin, + PropFoliageSkinDeferred, TerrainNormalTint) directly and reuses the fallback machinery. +- **Lowest risk, pure translator work:** Idea 2. +- **Best bang for compiler-analysis work:** Idea 3. Bounded, well diagnosed, one known failing program to validate + against. diff --git a/docs/shader-translation.md b/docs/shader-translation.md index 401c1b58..f4c982b5 100644 --- a/docs/shader-translation.md +++ b/docs/shader-translation.md @@ -575,7 +575,7 @@ branch, output, store and message reads only console values. On H < W: | `vw_any`/`vw_count`/`vw_ballot` result, e.g. the SCC of `s_and_saveexec` | not the console's | fine while never read (SCC is nearly always overwritten) | | `vw_any(m)`, m = EXEC and a uniform value (`s_cselect` + `s_and vcc, exec`) | the console's when the window holds an active lane | a window known to hold one: right | | execz / execnz / vccz / vccnz on such an m | a window without active lanes may take the other path than its console wave | fine when both paths, run with the window's lanes inactive, leave what is read where they meet as it was (below) | -| `v_readfirstlane` | first active lane of the window | right in the bits equal on all active lanes, when the window holds an active lane: after `exec = -1`, on the taken side of an execz branch, or for a value only written by lanes that are active then (EXEC only shrank since) | +| `v_readfirstlane` | first active lane of the window (some lane's value when none is active) | right in the bits equal on all lanes of the console wave whatever lanes the window holds (an SGPR copy, the group's bits of the mesh thread id, a 64-bit multiply or shift of scalars: the two halves of a compound `if (active) { lo = ...; hi = ...; }` keep their value's facts as plain assignments do), and in the bits equal on all active lanes when the window's active lanes are the console's and it holds one: after `exec = -1`, on the taken side of an execz branch, or for a value only written by lanes that are active then (EXEC only shrank since). A statement of another shape that is no effect (a `GetDimensions`, a load picked by a class switch, an `asuint` split of a double) gives its results the uniformity of what it reads; an effect's results (an atomic's old value) are each lane's own | | ballot used as a mask (`lane_bit`, `s_xor exec`) | each window lane's own bit is the console's | right | | ballot read as a number (popcount, compare with 0) | not the console's | floor = wave | diff --git a/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs b/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs index 1b4a1ec3..12f815de 100644 --- a/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs +++ b/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs @@ -20,6 +20,17 @@ public StatementTransfer(WindowState state, int threads) /// Applies one statement; null, or why its effect may not be the console's. public string? Apply(WindowStatement statement) { + if (statement.Parts.Count > 0) + { + // A compound of assignments (the halves of a 64-bit result): each keeps the facts an assignment keeps. + foreach (var part in statement.Parts) + { + Apply(part); + } + + return null; + } + if (statement.Kind is StatementKind.Effect or StatementKind.Other) { return Opaque(statement); @@ -124,14 +135,18 @@ private void AssignGuarded(string target, string value) /// /// A statement of another shape: an effect must read only console values (a guarded one only those it reads when - /// the window holds an active lane); what it assigns is exact when everything read is. + /// the window holds an active lane); what it assigns is exact when everything read is. What a statement that is + /// not an effect (a resource query, a load chosen by a class switch) assigns is uniform when everything it reads + /// is, as an assignment's value; an effect's results (an atomic's old value) are each lane's own. /// private string? Opaque(WindowStatement statement) { var calls = statement.Calls.Where(call => !statement.IsAllocation || call != AllocationProbe).ToList(); + var window = calls.Any(call => ValueRules.IsWindowCall(call, _state)); var exact = ValueRules.IsExact(statement.Reads, calls, _state); - var held = !calls.Any(call => ValueRules.IsWindowCall(call, _state)) && statement.Reads.All(name => _state.Get(name).IsHeld); + var held = !window && statement.Reads.All(name => _state.Get(name).IsHeld); var guardedHeld = statement.IsGuarded && _state.Get(WindowNames.Active).IsExact && held; + var (uniform, allUniform) = (false, false); string? reason = null; @@ -140,6 +155,15 @@ private void AssignGuarded(string target, string value) reason = $"effect on values the window may not share with the console: {statement.Text}"; } + if (statement.Kind == StatementKind.Other && !window && !calls.Any(WindowNames.IsLaneFunction) && !statement.Reads.Any(WindowNames.IsLaneInput)) + { + uniform = statement.Reads.All(name => _state.Get(name).IsActiveUniform); + + // A guarded write leaves the inactive lanes' values: equal on all lanes only when all are active. + allUniform = uniform && (!statement.IsGuarded || _state.Get(WindowNames.Active).Full) + && statement.Reads.All(name => _state.Get(name).AllUniform == ValueFact.AllBits); + } + if (statement.IsAllocation) { _state.Allocated = true; @@ -148,13 +172,13 @@ private void AssignGuarded(string target, string value) // Assigned even with a reason: the facts-only pass (WindowAnalysis.EntryFacts) goes on past it. foreach (var target in statement.Assigned) { - Assigned(target, Bits(exact), Bits(held)); + Assigned(target, Bits(exact), Bits(held), Bits(uniform), Bits(allUniform)); } return reason; } - private void Assigned(string target, uint exact, uint held) + private void Assigned(string target, uint exact, uint held, uint uniform, uint allUniform) { if (target == WindowNames.Active) { @@ -171,7 +195,7 @@ private void Assigned(string target, uint exact, uint held) return; } - _state.Set(target, ValueFact.Unknown with { Exact = exact, Held = held }); + _state.Set(target, new ValueFact(exact, held, uniform, allUniform, MaskKind.Other, false, null)); } private static uint Bits(bool all) diff --git a/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs b/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs index 882f8cb8..5fffbff5 100644 --- a/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs +++ b/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs @@ -167,20 +167,24 @@ private static ValueFact Generic(string text, WindowState state) return new ValueFact(exact, held, uniform, allUniform, MaskKind.Other, false, null); } - /// readfirstlane: the first active lane's value, the console's in the bits that are equal on all active lanes. + /// + /// readfirstlane: the first active lane's value (some lane's when none is active), the console's in the bits + /// that are equal on all lanes, and when the window's active lanes are the console's, in the bits equal on the + /// active lanes. + /// private static ValueFact FirstLane(ValueFact source, ValueFact active) { - if (!active.IsExact) - { - return ValueFact.Scalar with { Exact = 0, Held = 0 }; - } - - var held = source.Held & source.Uniform; - var exact = 0u; + var exact = source.Exact & source.AllUniform; + var held = source.Held & source.AllUniform; - if (active.NonEmpty) + if (active.IsExact) { - exact = source.Exact & source.Uniform; + held |= source.Held & source.Uniform; + + if (active.NonEmpty) + { + exact |= source.Exact & source.Uniform; + } } return ValueFact.Scalar with { Exact = exact, Held = held }; diff --git a/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs b/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs index b850cdcf..2a879519 100644 --- a/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs +++ b/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs @@ -65,6 +65,13 @@ private WindowStatement(StatementKind kind, string text) /// The functions the statement calls. public IReadOnlyList Calls { get; private init; } = []; + /// + /// The assignments of a compound statement that is only assignments in braces + /// (if (active) { a = x; b = y; }, a 64-bit multiply or shift's two halves), each guarded when the compound + /// is; empty for any other statement. + /// + public IReadOnlyList Parts { get; private init; } = []; + /// Runs only on active lanes (if (active) ...). public bool IsGuarded { get; private init; } @@ -163,11 +170,15 @@ private static WindowStatement ParseText(string line) assigned = assigned.Concat(Names(text)); } + // asuint(double, lo, hi) writes its last two arguments. + assigned = assigned.Concat(SplitDoublePattern().Matches(text).SelectMany(match => new[] { match.Groups["lo"].Value, match.Groups["hi"].Value })); + return new WindowStatement(kind, text) { Reads = Names(text), Calls = Functions(text), Assigned = [.. assigned.Distinct()], + Parts = kind == StatementKind.Other ? PartsOf(text) : [], IsGuarded = text.StartsWith("if (active) ", StringComparison.Ordinal), IsExport = ExportPattern().IsMatch(text), IsAllocation = AllocationPattern().IsMatch(text), @@ -176,6 +187,39 @@ private static WindowStatement ParseText(string line) }; } + /// + /// The assignments of [if (active) ]{ a = x; b = y; } (closing braces of a compound split over lines may + /// follow), as the statements [if (active) ]a = x;; empty unless every piece is a plain assignment. + /// + private static IReadOnlyList PartsOf(string text) + { + var compound = CompoundPattern().Match(text); + + if (!compound.Success) + { + return Array.Empty(); + } + + var guard = compound.Groups["guard"].Value; + var pieces = compound.Groups["body"].Value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var parts = new List(pieces.Length); + var expected = guard.Length > 0 ? StatementKind.Guarded : StatementKind.Assign; + + foreach (var piece in pieces) + { + var part = Parse($"{guard}{piece};"); + + if (part.Kind != expected) + { + return Array.Empty(); + } + + parts.Add(part); + } + + return parts; + } + private static IReadOnlyList NamesOf(string expression) { return [.. NamePattern().Matches(expression).Select(match => match.Groups[1].Value).Where(name => !Keywords.Contains(name)).Distinct()]; @@ -256,4 +300,10 @@ private static string Normalize(string line) [GeneratedRegex(@"\.GetDimensions\(")] private static partial Regex OutParameterPattern(); + + [GeneratedRegex(@"\basuint\([^;]*, (?[A-Za-z_]\w*), (?[A-Za-z_]\w*)\)")] + private static partial Regex SplitDoublePattern(); + + [GeneratedRegex(@"^(?if \(active\) )?\{ (?[^{}]+;) \}(?: \})*$")] + private static partial Regex CompoundPattern(); } diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin new file mode 100644 index 0000000000000000000000000000000000000000..3da10627c1c25edd7fcc02bfb8bf9fd8f4e9eebb GIT binary patch literal 76 zcmZQ%NWFfLfe{GPt{-G#VrXDqv9E!NrEU^aM{SnMw0%qr9s3)BVvM{jbz&_4_OUSh dzt+UUz`)8HRHw= {floor} lanes\n", ShaderWorkbench.Translate(program), StringComparison.Ordinal); + } + private static string Program(int wave, bool groupLanes) { var group = groupLanes ? 1 : 0; From d6f33b5505f07f5b8ae7bf26b633b9f3155bf58f Mon Sep 17 00:00:00 2001 From: almostxxx27 <361921142+almostxxx27@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:15:54 +0100 Subject: [PATCH 2/2] Shaders: prove more first-lane reads console-exact in mesh windows (#35) Compound if (active) { lo; hi; } assignments keep their facts, non-effect opaque statements (GetDimensions, texture view declarations, class-switch loads, asuint splits) pass on the uniformity of their reads, and a readfirstlane of bits equal on all lanes is exact when the window holds an active lane. Atomics mark their result argument assigned and per-lane, and a statement reading active (the v_movreld switch) counts as guarded. --- docs/shader-translation.md | 2 +- .../Translation/Waves/StatementTransfer.cs | 36 ++++++-- .../Translation/Waves/ValueRules.cs | 26 ++++-- .../Translation/Waves/WindowStatement.cs | 81 ++++++++++++++++-- .../mesh_floor_4_77.f08fafa408ce54d7.bin | Bin 0 -> 76 bytes .../mesh_floor_4_87.0919f048b53ed696.bin | Bin 0 -> 76 bytes .../mesh_floor_64_87.d363f093639c9b63.bin | Bin 0 -> 76 bytes .../mesh_read_124.74f38e3927b4dcbb.bin | Bin 0 -> 40 bytes .../mesh_read_249.29401afbfeb39ee8.bin | Bin 0 -> 64 bytes .../mesh_read_259.894e3b0360f6e821.bin | Bin 0 -> 68 bytes .../WaveEmulationTests.cs | 57 ++++++++++++ 11 files changed, 181 insertions(+), 21 deletions(-) create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_87.0919f048b53ed696.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_64_87.d363f093639c9b63.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_read_124.74f38e3927b4dcbb.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_read_249.29401afbfeb39ee8.bin create mode 100644 tests/FiveStar.Shaders.Tests/Assembled/mesh_read_259.894e3b0360f6e821.bin diff --git a/docs/shader-translation.md b/docs/shader-translation.md index 401c1b58..6b55e55c 100644 --- a/docs/shader-translation.md +++ b/docs/shader-translation.md @@ -575,7 +575,7 @@ branch, output, store and message reads only console values. On H < W: | `vw_any`/`vw_count`/`vw_ballot` result, e.g. the SCC of `s_and_saveexec` | not the console's | fine while never read (SCC is nearly always overwritten) | | `vw_any(m)`, m = EXEC and a uniform value (`s_cselect` + `s_and vcc, exec`) | the console's when the window holds an active lane | a window known to hold one: right | | execz / execnz / vccz / vccnz on such an m | a window without active lanes may take the other path than its console wave | fine when both paths, run with the window's lanes inactive, leave what is read where they meet as it was (below) | -| `v_readfirstlane` | first active lane of the window | right in the bits equal on all active lanes, when the window holds an active lane: after `exec = -1`, on the taken side of an execz branch, or for a value only written by lanes that are active then (EXEC only shrank since) | +| `v_readfirstlane` | first active lane of the window (some lane's value when none is active) | right in the bits equal on all lanes of the console wave when the window holds an active lane (an SGPR copy, the group's bits of the mesh thread id, a 64-bit multiply or shift of scalars: the two halves of a compound `if (active) { lo = ...; hi = ...; }` keep their value's facts as plain assignments do; with no active lane the prelude reads the window's lane 0, a lane the console never read), and in the bits equal on all active lanes when the window's active lanes are the console's and it holds one: after `exec = -1`, on the taken side of an execz branch, or for a value only written by lanes that are active then (EXEC only shrank since). A statement of another shape that is no effect (a `GetDimensions`, a load picked by a class switch, an `asuint` split of a double) gives its results the uniformity of what it reads; an effect's results (an atomic's old value, the last argument of its `Interlocked*` call) are each lane's own, and a statement reading `active` anywhere (the `v_movreld` switch, `if (active)` in each case) is guarded | | ballot used as a mask (`lane_bit`, `s_xor exec`) | each window lane's own bit is the console's | right | | ballot read as a number (popcount, compare with 0) | not the console's | floor = wave | diff --git a/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs b/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs index 1b4a1ec3..507dfecf 100644 --- a/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs +++ b/src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs @@ -20,6 +20,17 @@ public StatementTransfer(WindowState state, int threads) /// Applies one statement; null, or why its effect may not be the console's. public string? Apply(WindowStatement statement) { + if (statement.Parts.Count > 0) + { + // A compound of assignments (the halves of a 64-bit result): each keeps the facts an assignment keeps. + foreach (var part in statement.Parts) + { + Apply(part); + } + + return null; + } + if (statement.Kind is StatementKind.Effect or StatementKind.Other) { return Opaque(statement); @@ -124,14 +135,18 @@ private void AssignGuarded(string target, string value) /// /// A statement of another shape: an effect must read only console values (a guarded one only those it reads when - /// the window holds an active lane); what it assigns is exact when everything read is. + /// the window holds an active lane); what it assigns is exact when everything read is. What a statement that is + /// not an effect (a resource query, a load chosen by a class switch) assigns is uniform when everything it reads + /// is, as an assignment's value; an effect's results (an atomic's old value) are each lane's own. /// private string? Opaque(WindowStatement statement) { var calls = statement.Calls.Where(call => !statement.IsAllocation || call != AllocationProbe).ToList(); + var window = calls.Any(call => ValueRules.IsWindowCall(call, _state)); var exact = ValueRules.IsExact(statement.Reads, calls, _state); - var held = !calls.Any(call => ValueRules.IsWindowCall(call, _state)) && statement.Reads.All(name => _state.Get(name).IsHeld); + var held = !window && statement.Reads.All(name => _state.Get(name).IsHeld); var guardedHeld = statement.IsGuarded && _state.Get(WindowNames.Active).IsExact && held; + var (uniform, allUniform) = (false, false); string? reason = null; @@ -140,6 +155,17 @@ private void AssignGuarded(string target, string value) reason = $"effect on values the window may not share with the console: {statement.Text}"; } + if (statement.Kind == StatementKind.Other && !window && !calls.Any(WindowNames.IsLaneFunction) && !statement.Reads.Any(WindowNames.IsLaneInput)) + { + uniform = statement.Reads.All(name => _state.Get(name).IsActiveUniform); + + // A guarded write leaves the inactive lanes' values: equal on all lanes only when all are active. + // A switch with if (active) inside each case is guarded too. + var guarded = statement.IsGuarded || statement.Reads.Contains(WindowNames.Active); + allUniform = uniform && (!guarded || _state.Get(WindowNames.Active).Full) + && statement.Reads.All(name => _state.Get(name).AllUniform == ValueFact.AllBits); + } + if (statement.IsAllocation) { _state.Allocated = true; @@ -148,13 +174,13 @@ private void AssignGuarded(string target, string value) // Assigned even with a reason: the facts-only pass (WindowAnalysis.EntryFacts) goes on past it. foreach (var target in statement.Assigned) { - Assigned(target, Bits(exact), Bits(held)); + Assigned(target, Bits(exact), Bits(held), Bits(uniform), Bits(allUniform)); } return reason; } - private void Assigned(string target, uint exact, uint held) + private void Assigned(string target, uint exact, uint held, uint uniform, uint allUniform) { if (target == WindowNames.Active) { @@ -171,7 +197,7 @@ private void Assigned(string target, uint exact, uint held) return; } - _state.Set(target, ValueFact.Unknown with { Exact = exact, Held = held }); + _state.Set(target, new ValueFact(exact, held, uniform, allUniform, MaskKind.Other, false, null)); } private static uint Bits(bool all) diff --git a/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs b/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs index 882f8cb8..aee53bbf 100644 --- a/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs +++ b/src/FiveStar.Shaders/Translation/Waves/ValueRules.cs @@ -167,20 +167,30 @@ private static ValueFact Generic(string text, WindowState state) return new ValueFact(exact, held, uniform, allUniform, MaskKind.Other, false, null); } - /// readfirstlane: the first active lane's value, the console's in the bits that are equal on all active lanes. + /// + /// readfirstlane: the first active lane's value, on a window holding an active lane the console's in the bits that + /// are equal on all lanes, and when the window's active lanes are the console's, in the bits equal on the active + /// lanes. + /// private static ValueFact FirstLane(ValueFact source, ValueFact active) { - if (!active.IsExact) - { - return ValueFact.Scalar with { Exact = 0, Held = 0 }; - } - - var held = source.Held & source.Uniform; + // The prelude's readfirstlane gives 0 on a window without an active lane that does not hold console lane 0. var exact = 0u; + var held = source.Held & source.AllUniform; if (active.NonEmpty) { - exact = source.Exact & source.Uniform; + exact = source.Exact & source.AllUniform; + } + + if (active.IsExact) + { + held |= source.Held & source.Uniform; + + if (active.NonEmpty) + { + exact |= source.Exact & source.Uniform; + } } return ValueFact.Scalar with { Exact = exact, Held = held }; diff --git a/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs b/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs index b850cdcf..9d143543 100644 --- a/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs +++ b/src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs @@ -65,6 +65,13 @@ private WindowStatement(StatementKind kind, string text) /// The functions the statement calls. public IReadOnlyList Calls { get; private init; } = []; + /// + /// The assignments of a compound statement that is only assignments in braces + /// (if (active) { a = x; b = y; }, a 64-bit multiply or shift's two halves), each guarded when the compound + /// is; empty for any other statement. + /// + public IReadOnlyList Parts { get; private init; } = []; + /// Runs only on active lanes (if (active) ...). public bool IsGuarded { get; private init; } @@ -149,25 +156,23 @@ private static WindowStatement ParseText(string line) } var kind = StatementKind.Other; + IReadOnlyList parts = []; if (effect) { kind = StatementKind.Effect; } - - var assigned = TargetPattern().Matches(text).Select(match => match.Groups[1].Value).Where(name => !Keywords.Contains(name)); - - if (OutParameterPattern().IsMatch(text)) + else { - // GetDimensions writes its arguments. - assigned = assigned.Concat(Names(text)); + parts = PartsOf(text); } return new WindowStatement(kind, text) { Reads = Names(text), Calls = Functions(text), - Assigned = [.. assigned.Distinct()], + Assigned = AssignedBy(text), + Parts = parts, IsGuarded = text.StartsWith("if (active) ", StringComparison.Ordinal), IsExport = ExportPattern().IsMatch(text), IsAllocation = AllocationPattern().IsMatch(text), @@ -176,6 +181,59 @@ private static WindowStatement ParseText(string line) }; } + /// What a statement of another shape writes: its assignment targets and out-parameters. + private static IReadOnlyList AssignedBy(string text) + { + var assigned = TargetPattern().Matches(text).Select(match => match.Groups[1].Value).Where(name => !Keywords.Contains(name)); + + if (OutParameterPattern().IsMatch(text)) + { + // GetDimensions writes its arguments. + assigned = assigned.Concat(Names(text)); + } + + // An atomic writes the old value to its last argument. + assigned = assigned.Concat(AtomicResultPattern().Matches(text).Select(match => match.Groups["out"].Value)); + + // asuint(double, lo, hi) writes its last two arguments. + assigned = assigned.Concat(SplitDoublePattern().Matches(text).SelectMany(match => new[] { match.Groups["lo"].Value, match.Groups["hi"].Value })); + + return [.. assigned.Distinct()]; + } + + /// + /// The assignments of [if (active) ]{ a = x; b = y; } (closing braces of a compound split over lines may + /// follow), as the statements [if (active) ]a = x;; empty unless every piece is a plain assignment. + /// + private static IReadOnlyList PartsOf(string text) + { + var compound = CompoundPattern().Match(text); + + if (!compound.Success) + { + return Array.Empty(); + } + + var guard = compound.Groups["guard"].Value; + var pieces = compound.Groups["body"].Value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var parts = new List(pieces.Length); + var expected = guard.Length > 0 ? StatementKind.Guarded : StatementKind.Assign; + + foreach (var piece in pieces) + { + var part = Parse($"{guard}{piece};"); + + if (part.Kind != expected) + { + return Array.Empty(); + } + + parts.Add(part); + } + + return parts; + } + private static IReadOnlyList NamesOf(string expression) { return [.. NamePattern().Matches(expression).Select(match => match.Groups[1].Value).Where(name => !Keywords.Contains(name)).Distinct()]; @@ -256,4 +314,13 @@ private static string Normalize(string line) [GeneratedRegex(@"\.GetDimensions\(")] private static partial Regex OutParameterPattern(); + + [GeneratedRegex(@"\basuint\([^;]*, (?[A-Za-z_]\w*), (?[A-Za-z_]\w*)\)")] + private static partial Regex SplitDoublePattern(); + + [GeneratedRegex(@"\bInterlocked\w*\([^;]*?, (?[A-Za-z_]\w*)\)")] + private static partial Regex AtomicResultPattern(); + + [GeneratedRegex(@"^(?if \(active\) )?\{ (?[^{}]+;) \}(?: \})*$")] + private static partial Regex CompoundPattern(); } diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin new file mode 100644 index 0000000000000000000000000000000000000000..3da10627c1c25edd7fcc02bfb8bf9fd8f4e9eebb GIT binary patch literal 76 zcmZQ%NWFfLfe{GPt{-G#VrXDqv9E!NrEU^aM{SnMw0%qr9s3)BVvM{jbz&_4_OUSh dzt+UUz`)8HRHwvDKaDVEDnr4Aj8TxE}zZ8WZpU literal 0 HcmV?d00001 diff --git a/tests/FiveStar.Shaders.Tests/WaveEmulationTests.cs b/tests/FiveStar.Shaders.Tests/WaveEmulationTests.cs index 00123d6c..b3084492 100644 --- a/tests/FiveStar.Shaders.Tests/WaveEmulationTests.cs +++ b/tests/FiveStar.Shaders.Tests/WaveEmulationTests.cs @@ -96,6 +96,9 @@ s_cbranch_execz .Lskip [InlineData("v_mov_b32 v3, v2", 4, 4)] [InlineData("v_mov_b32 v3, s40", 64, 4)] [InlineData("v_readfirstlane_b32 s41, v1\nv_mov_b32 v3, s41", 64, 4)] + [InlineData("v_mad_u64_u32 v[4:5], s[10:11], s2, s3, 0\nv_readfirstlane_b32 s41, v4\nv_mov_b32 v3, s41", 4, 4)] + [InlineData("v_mad_u64_u32 v[4:5], s[10:11], v1, s3, 0\nv_readfirstlane_b32 s41, v4\nv_mov_b32 v3, s41", 64, 4)] + [InlineData("v_lshlrev_b64 v[4:5], 2, s[2:3]\nv_readfirstlane_b32 s41, v5\nv_mov_b32 v3, s41", 4, 4)] public void A_mesh_program_states_whether_narrower_waves_give_console_results(string tail, int floor, int fastFloor) { var code = $"{SkippedRegion}\n{tail}\nexp pos0 v2, v3, v2, v2 done\ns_endpgm"; @@ -113,6 +116,60 @@ public void A_mesh_program_states_whether_narrower_waves_give_console_results(st Assert.Equal(!tail.Contains("s40", StringComparison.Ordinal), fast.Contains("pc = (!vw_any(active))", StringComparison.Ordinal)); } + // The thread id's group bits (v5 from bit 7 up, the group size being 128) read first under an EXEC of the lanes below + // the window's first lane's id: a window holds no active lane there, and its readfirstlane gives 0, not the group. + private const string EmptyWindowRead = """ + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mov_b32 v2, 0 + v_readfirstlane_b32 s41, v1 + v_cmp_gt_u32_e32 vcc, s41, v1 + s_and_saveexec_b64 s[22:23], vcc + v_readfirstlane_b32 s42, v5 + s_and_b32 s42, s42, 0xffffff80 + s_mov_b64 exec, s[22:23] + """; + + // The old value of an atomic: each lane's own. + private const string AtomicRead = """ + v_mov_b32 v2, 0 + v_mov_b32 v6, 1 + buffer_atomic_add v6, v2, s[0:3], 0 offen glc + s_waitcnt vmcnt(0) + v_readfirstlane_b32 s42, v6 + """; + + // v_movreld under the EXEC of lanes 0..17 writes v7 only there (a switch on m0, guarded in each case). + private const string RelativeWriteRead = """ + v_mbcnt_lo_u32_b32 v1, -1, 0 + v_mbcnt_hi_u32_b32 v1, -1, v1 + v_mov_b32 v2, 0 + v_mov_b32 v6, s2 + v_mov_b32 v7, 0 + v_cmp_gt_u32_e32 vcc, 18, v1 + s_and_saveexec_b64 s[22:23], vcc + s_mov_b32 m0, 1 + v_movreld_b32 v7, v6 + s_mov_b64 exec, s[22:23] + v_readfirstlane_b32 s42, v8 + """; + + [WarpTheory] + [InlineData(EmptyWindowRead)] + [InlineData(AtomicRead)] + [InlineData(RelativeWriteRead)] + public void A_first_lane_read_of_a_value_a_narrower_wave_may_see_otherwise_is_not_the_consoles(string code) + { + var assembled = _fixture.Workbench.Assemble($"mesh_read_{code.Length}", $"{code}\nv_mov_b32 v3, s42\nexp pos0 v2, v3, v2, v2 done\ns_endpgm", 64); + var config = new ShaderConfig { Stage = HardwareStage.Ngg, WaveSize = 64, UserSgprs = 4, Ngg = new NggConfig(8, 0, 0) }; + var pipeline = new PipelineStateInfo { Stage = "ms", NumThreads = new ThreadGroupSize(128, 1, 1), MaxVertices = 128, MaxPrimitives = 128 }; + var program = new ShaderProgram(ShaderStage.Mesh, assembled.Instructions, assembled.Code, ShaderSignatures.None, config, pipeline); + var hlsl = ShaderWorkbench.Translate(program); + + Assert.StartsWith("// program wave 64; console results on hardware waves >= 64 lanes\n", hlsl, StringComparison.Ordinal); + Assert.DoesNotContain("s42 = v", hlsl, StringComparison.Ordinal); + } + private static string Program(int wave, bool groupLanes) { var group = groupLanes ? 1 : 0;