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 00000000..3da10627 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_77.f08fafa408ce54d7.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_87.0919f048b53ed696.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_87.0919f048b53ed696.bin new file mode 100644 index 00000000..eef7cf0c Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_4_87.0919f048b53ed696.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_64_87.d363f093639c9b63.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_64_87.d363f093639c9b63.bin new file mode 100644 index 00000000..63725dc1 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/mesh_floor_64_87.d363f093639c9b63.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_124.74f38e3927b4dcbb.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_124.74f38e3927b4dcbb.bin new file mode 100644 index 00000000..9c0f9a52 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_124.74f38e3927b4dcbb.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_249.29401afbfeb39ee8.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_249.29401afbfeb39ee8.bin new file mode 100644 index 00000000..e00e2b99 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_249.29401afbfeb39ee8.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_259.894e3b0360f6e821.bin b/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_259.894e3b0360f6e821.bin new file mode 100644 index 00000000..f5330103 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/mesh_read_259.894e3b0360f6e821.bin differ 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;