Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/shader-translation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
36 changes: 31 additions & 5 deletions src/FiveStar.Shaders/Translation/Waves/StatementTransfer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ public StatementTransfer(WindowState state, int threads)
/// <summary>Applies one statement; null, or why its effect may not be the console's.</summary>
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);
Expand Down Expand Up @@ -124,14 +135,18 @@ private void AssignGuarded(string target, string value)

/// <summary>
/// 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.
/// </summary>
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;

Expand All @@ -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;
Expand All @@ -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)
{
Expand All @@ -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)
Expand Down
26 changes: 18 additions & 8 deletions src/FiveStar.Shaders/Translation/Waves/ValueRules.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,20 +167,30 @@ private static ValueFact Generic(string text, WindowState state)
return new ValueFact(exact, held, uniform, allUniform, MaskKind.Other, false, null);
}

/// <summary>readfirstlane: the first active lane's value, the console's in the bits that are equal on all active lanes.</summary>
/// <summary>
/// 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.
/// </summary>
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 };
Expand Down
81 changes: 74 additions & 7 deletions src/FiveStar.Shaders/Translation/Waves/WindowStatement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ private WindowStatement(StatementKind kind, string text)
/// <summary>The functions the statement calls.</summary>
public IReadOnlyList<string> Calls { get; private init; } = [];

/// <summary>
/// The assignments of a compound <see cref="StatementKind.Other"/> statement that is only assignments in braces
/// (<c>if (active) { a = x; b = y; }</c>, a 64-bit multiply or shift's two halves), each guarded when the compound
/// is; empty for any other statement.
/// </summary>
public IReadOnlyList<WindowStatement> Parts { get; private init; } = [];

/// <summary>Runs only on active lanes (<c>if (active) ...</c>).</summary>
public bool IsGuarded { get; private init; }

Expand Down Expand Up @@ -149,25 +156,23 @@ private static WindowStatement ParseText(string line)
}

var kind = StatementKind.Other;
IReadOnlyList<WindowStatement> 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),
Expand All @@ -176,6 +181,59 @@ private static WindowStatement ParseText(string line)
};
}

/// <summary>What a statement of another shape writes: its assignment targets and out-parameters.</summary>
private static IReadOnlyList<string> 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()];
}

/// <summary>
/// The assignments of <c>[if (active) ]{ a = x; b = y; }</c> (closing braces of a compound split over lines may
/// follow), as the statements <c>[if (active) ]a = x;</c>; empty unless every piece is a plain assignment.
/// </summary>
private static IReadOnlyList<WindowStatement> PartsOf(string text)
{
var compound = CompoundPattern().Match(text);

if (!compound.Success)
{
return Array.Empty<WindowStatement>();
}

var guard = compound.Groups["guard"].Value;
var pieces = compound.Groups["body"].Value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var parts = new List<WindowStatement>(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<WindowStatement>();
}

parts.Add(part);
}

return parts;
}

private static IReadOnlyList<string> NamesOf(string expression)
{
return [.. NamePattern().Matches(expression).Select(match => match.Groups[1].Value).Where(name => !Keywords.Contains(name)).Distinct()];
Expand Down Expand Up @@ -256,4 +314,13 @@ private static string Normalize(string line)

[GeneratedRegex(@"\.GetDimensions\(")]
private static partial Regex OutParameterPattern();

[GeneratedRegex(@"\basuint\([^;]*, (?<lo>[A-Za-z_]\w*), (?<hi>[A-Za-z_]\w*)\)")]
private static partial Regex SplitDoublePattern();

[GeneratedRegex(@"\bInterlocked\w*\([^;]*?, (?<out>[A-Za-z_]\w*)\)")]
private static partial Regex AtomicResultPattern();

[GeneratedRegex(@"^(?<guard>if \(active\) )?\{ (?<body>[^{}]+;) \}(?: \})*$")]
private static partial Regex CompoundPattern();
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
57 changes: 57 additions & 0 deletions tests/FiveStar.Shaders.Tests/WaveEmulationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand Down