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
13 changes: 11 additions & 2 deletions docs/shader-translation.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ The container is read from `<fssm folder>/../dxbc/<name>.dxbc` (see Disassembly
text, so the decoder prints every instruction exactly as llvm-objdump does for gfx1013 (wave64 lane masks as with
`+wavefrontsize64`), branch targets appended as `@T0x<target>`. It also keeps the listing's quirks: a dword that is no
instruction is `.long 0x...`, a run of 8 or more zero bytes is left out, and an instruction llvm-objdump lists with an
alignment warning is dropped, as the listing parser drops that line. Opcode numbers and field layouts come from AMD's
alignment warning is dropped, as the listing parser drops that line. A VOP3 source the instruction does not read
may hold 0 or the inline constant 0 (llvm-mc 23 writes the latter, older releases the former); any other value makes the
dword `.long`. Opcode numbers and field layouts come from AMD's
"RDNA 2 Instruction Set Architecture" reference guide.

`LlvmDisassembler` (llvm-mc wraps the bytes in an object file, llvm-objdump lists it, `ObjdumpParser` reads the
Expand Down Expand Up @@ -55,7 +57,14 @@ Prints the program, code block and instruction counts and the first difference o
loop's end, while its last write in program order is an `s_buffer_load`) would be read in the wrong form, so a first
translation finds such registers and the second keeps them in their integer variables: each mask write also sets
them with a ballot, and mask reads test them with `lane_bit` (cases `cs_mask_on_taken_path`,
`cs_integer_on_taken_path`). On wave64 the high dword of every mask is set this way too.
`cs_integer_on_taken_path`). On wave64 the high dword of every mask is set this way too. The first translation
records, per block, the form each read assumed and each write left (`MaskForms`); `MaskFormAnalysis` carries the
forms each register may hold from block to block along the branches (registers not yet written are integers) and
keeps only those a read may reach in the other form. A register used as an integer in one part of a program and as
a mask in another stays a plain bool (`cs_mask_after_integer`). Before, any register ever used both ways was kept in
its integer variables: on `CS_ScreenProbes_ActivateProbes` (wave64) that was 33 of its 34 masks; now one is (s0,
also a `s_getpc`/`s_setpc` address), and its HLSL goes from 32,393 `vw_ballot` and 20,976 `lane_bit` to
17,411 and 2,167.
- SCC is the bool `scc`, set by compares, logic, carries and shifts as the hardware does.
- Registers read before any write are hardware inputs, assigned in a prologue (rules in [fssm.md](fssm.md)); a read
outside the input layout is 0.
Expand Down
5 changes: 4 additions & 1 deletion src/FiveStar.Shaders/Disassembly/Rdna/Vop3Decoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ internal static class Vop3Decoder
private const int TiedSources = 2;
private const int PermlaneSelects = 3;

/// <summary>The source code of the inline constant 0, which current llvm-mc writes in the sources an instruction does not read.</summary>
private const int InlineZero = 0x80;

public static Decoded? Decode(CodeWords code, int at)
{
if (!code.Has(at, Words))
Expand Down Expand Up @@ -51,7 +54,7 @@ internal static class Vop3Decoder
var count = SourceCount(info, fields.Opcode);
var words = Words;

if (fields.SourceCodes.Skip(count).Any(source => source != 0) || !ModifiersFit(info, fields, count))
if (fields.SourceCodes.Skip(count).Any(source => source is not (0 or InlineZero)) || !ModifiersFit(info, fields, count))
{
return null;
}
Expand Down
42 changes: 42 additions & 0 deletions src/FiveStar.Shaders/Translation/Core/BlockForms.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) 2026 Five Star Recomp contributors.
// SPDX-License-Identifier: GPL-3.0-or-later

namespace FiveStar.Shaders.Translation.Core;

/// <summary>
/// The forms (lane mask or integer) one translated block reads and leaves its SGPRs in: the form each read before the
/// block's first write of the register assumed, the form of its last write, and registers a read inside the block took
/// in another form than the block itself last wrote them in.
/// </summary>
internal sealed class BlockForms
{
/// <summary>Registers read before any write in the block: whether a read took the mask form, the integer form.</summary>
public Dictionary<RegisterKey, (bool Mask, bool Integer)> Exposed { get; } = [];

/// <summary>The form of the block's last write of each register it writes (true: a lane mask).</summary>
public Dictionary<RegisterKey, bool> Exits { get; } = [];

/// <summary>Registers read inside the block in another form than its own last write left.</summary>
public HashSet<RegisterKey> Conflicts { get; } = [];

public void Read(RegisterKey key, bool mask)
{
if (Exits.TryGetValue(key, out var written))
{
if (written != mask)
{
Conflicts.Add(key);
}

return;
}

var (asMask, asInteger) = Exposed.GetValueOrDefault(key);
Exposed[key] = (asMask || mask, asInteger || !mask);
}

public void Write(RegisterKey key, bool mask)
{
Exits[key] = mask;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ private void TranslateBlocks(HashSet<long> leaders, HashSet<long> reachable)
{
CloseBlock(current, terminated, instruction.Address);
current = instruction.Address;
_state.Forms.Begin(instruction.Address);

_state.Body = [];
terminated = false;
_exit = null;
Expand Down
39 changes: 39 additions & 0 deletions src/FiveStar.Shaders/Translation/Core/MaskForms.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) 2026 Five Star Recomp contributors.
// SPDX-License-Identifier: GPL-3.0-or-later

namespace FiveStar.Shaders.Translation.Core;

/// <summary>
/// Records, block by block, the form each SGPR read assumed and each write left (<see cref="BlockForms"/>), so
/// <see cref="Stages.MaskFormAnalysis"/> can find the registers a read may reach in both forms along the program's paths.
/// </summary>
internal sealed class MaskForms
{
private readonly Dictionary<long, BlockForms> _blocks = [];
private BlockForms? _current;

public IReadOnlyDictionary<long, BlockForms> Blocks => _blocks;

/// <summary>Starts the block at <paramref name="address"/>.</summary>
public void Begin(long address)
{
_current = new BlockForms();
_blocks[address] = _current;
}

public void Read(RegisterKey key, bool mask)
{
if (key.Kind == RegisterKey.Scalar)
{
_current?.Read(key, mask);
}
}

public void Write(RegisterKey key, bool mask)
{
if (key.Kind == RegisterKey.Scalar)
{
_current?.Write(key, mask);
}
}
}
13 changes: 13 additions & 0 deletions src/FiveStar.Shaders/Translation/Core/OperandAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public string Read(Operand operand, int component = 0)
{
// A lane mask used as an integer: rebuild it with a ballot in program lane numbers. Ballots are snapped into
// temporaries so they never run under a per-lane condition (HLSL 2021 short-circuits ?:, && and ||).
_state.Forms.Read(operand.At(0), mask: true);
var half = component <= HighDword ? Halves[component] : Halves[LowDword];

return SnapOne($"{WaveOps.Ballot}({Mask(operand)}).{half}");
Expand All @@ -68,6 +69,7 @@ public string Read(Operand operand, int component = 0)
if (key.Kind == RegisterKey.Scalar)
{
_state.IntegerUses.Add(key);
_state.Forms.Read(key, mask: false);
}

if (!_state.Written.Contains(key))
Expand Down Expand Up @@ -167,6 +169,14 @@ public void Write(Operand destination, string value, int component = 0)
/// <summary>After an integer write of an SGPR: it no longer holds a mask.</summary>
public void WroteInteger(RegisterKey key)
{
// An integer write of either dword ends a wave64 mask in the pair below it.
_state.Forms.Write(key, mask: false);

if (_state.IsWave64)
{
_state.Forms.Write(key.Plus(-1), mask: false);
}

_state.Masks.Remove(key);
_state.MaskHighHalves.Remove(key);
_state.IntegerUses.Add(key);
Expand Down Expand Up @@ -249,6 +259,7 @@ public void ShadowInteger(RegisterKey key)
/// <summary>Records that a register now holds a lane mask (and, on wave64, that the next one is its high half).</summary>
public void MarkMask(RegisterKey key)
{
_state.Forms.Write(key, mask: true);
_state.Touch(key);
_state.Masks.Add(key);
_state.MasksEver.Add(key);
Expand Down Expand Up @@ -290,6 +301,8 @@ public string Mask(Operand operand)

if (key is not null && _state.Masks.Contains(key.Value) && !_state.Coherent.Contains(key.Value))
{
_state.Forms.Read(key.Value, mask: true);

return key.Value.MaskName;
}

Expand Down
3 changes: 3 additions & 0 deletions src/FiveStar.Shaders/Translation/Core/TranslationState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ public TranslationState(ShaderProgram program, IReadOnlyList<Instruction> instru
/// <summary>SGPRs used as integers (written, or read while not a mask) somewhere in the program.</summary>
public HashSet<RegisterKey> IntegerUses { get; } = [];

/// <summary>The form each block reads and leaves its SGPRs in (Stages.MaskFormAnalysis).</summary>
public MaskForms Forms { get; } = new();

/// <summary>
/// SGPRs that are a lane mask on some paths and an integer on others (found by a first translation): their mask
/// writes also set the integer variables and every read uses those, so a read is right whichever path ran
Expand Down
130 changes: 130 additions & 0 deletions src/FiveStar.Shaders/Translation/Stages/MaskFormAnalysis.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright (c) 2026 Five Star Recomp contributors.
// SPDX-License-Identifier: GPL-3.0-or-later

using FiveStar.Shaders.Translation.Core;

namespace FiveStar.Shaders.Translation.Stages;

/// <summary>
/// Finds the SGPRs a read may reach in another form (lane mask or integer) than the one the translation gave it: mask
/// tracking follows emission order, so a read takes the form of the last write emitted before it, which on another path
/// may not be the last write that ran. A forward pass over the blocks (<see cref="TranslationState.Forms"/>) gives the
/// forms each register may hold on entry to each block; registers never written yet are integers (hardware inputs).
/// </summary>
internal static class MaskFormAnalysis
{
private const int MaskForm = 1;
private const int IntegerForm = 2;

/// <summary>The registers of <paramref name="candidates"/> some read may see in the other form.</summary>
public static HashSet<RegisterKey> Mixed(TranslationState state, IReadOnlySet<RegisterKey> candidates)
{
var forms = state.Forms.Blocks;
var blocks = state.Blocks.Where(block => forms.ContainsKey(block.Address)).ToList();
var entry = Reaching(state, blocks, candidates);
var mixed = new HashSet<RegisterKey>();

foreach (var block in blocks)
{
var recorded = forms[block.Address];
mixed.UnionWith(recorded.Conflicts.Where(candidates.Contains));

foreach (var (key, (mask, integer)) in recorded.Exposed)
{
var reaching = entry[block.Address].GetValueOrDefault(key);
var seenOther = (mask && (reaching & IntegerForm) != 0) || (integer && (reaching & MaskForm) != 0);

if (candidates.Contains(key) && seenOther)
{
mixed.Add(key);
}
}
}

return mixed;
}

/// <summary>The forms each candidate may hold on entry to each block; on entry to the program, only integers.</summary>
private static Dictionary<long, Dictionary<RegisterKey, int>> Reaching(
TranslationState state, List<CodeBlock> blocks, IReadOnlySet<RegisterKey> candidates)
{
var entry = blocks.ToDictionary(block => (long)block.Address, _ => new Dictionary<RegisterKey, int>());

if (blocks.Count > 0)
{
entry[blocks[0].Address] = candidates.ToDictionary(key => key, _ => IntegerForm);
}

var changed = true;

while (changed)
{
changed = false;

foreach (var block in blocks)
{
var exit = Exit(entry[block.Address], state.Forms.Blocks[block.Address], candidates);

foreach (var successor in Successors(block.Exit).Where(entry.ContainsKey))
{
changed |= Merge(entry[successor], exit);
}
}
}

return entry;
}

private static Dictionary<RegisterKey, int> Exit(Dictionary<RegisterKey, int> entry, BlockForms forms, IReadOnlySet<RegisterKey> candidates)
{
var exit = new Dictionary<RegisterKey, int>(entry);

foreach (var (key, mask) in forms.Exits)
{
if (candidates.Contains(key))
{
exit[key] = mask ? MaskForm : IntegerForm;
}
}

return exit;
}

/// <summary>Adds the forms of <paramref name="from"/> to <paramref name="into"/>; true when that added any.</summary>
private static bool Merge(Dictionary<RegisterKey, int> into, Dictionary<RegisterKey, int> from)
{
var added = false;

foreach (var (key, form) in from)
{
var before = into.GetValueOrDefault(key);
var after = before | form;

if (after != before)
{
added = true;
into[key] = after;
}
}

return added;
}

private static IEnumerable<long> Successors(BlockExit exit)
{
if (exit.Kind == BlockExitKind.End)
{
yield break;
}

if (exit.Target is not null)
{
yield return exit.Target.Value;
}

if (exit.Next is not null)
{
yield return exit.Next.Value;
}
}
}
3 changes: 2 additions & 1 deletion src/FiveStar.Shaders/Translation/Stages/ProgramTranslator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,11 @@ private static string Emit(Func<IReadOnlySet<RegisterKey>, TranslationState> cre
// second keeps them in their integer variables, which every mask write also sets (OperandAccess.ShadowInteger).
var state = create(new HashSet<RegisterKey>());
Run(state);
var mixed = state.MasksEver
var candidates = state.MasksEver
.Where(key => key != SpecialRegisters.Exec)
.Where(key => state.IntegerUses.Contains(key) || (state.IsWave64 && state.IntegerUses.Contains(key.Plus(1))))
.ToHashSet();
var mixed = MaskFormAnalysis.Mixed(state, candidates);

if (mixed.Count > 0)
{
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
23 changes: 22 additions & 1 deletion tests/FiveStar.Shaders.Tests/Cases/ComputeWaveCases.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ public static IEnumerable<ComputeCase> All()
.Append(ExecLowHalfCase())
.Append(MaskHighHalfPathCase())
.Concat(Variants("cs_mask_on_taken_path", MaskOnTakenPathCase))
.Concat(Variants("cs_integer_on_taken_path", IntegerOnTakenPathCase));
.Concat(Variants("cs_integer_on_taken_path", IntegerOnTakenPathCase))
.Concat(Variants("cs_mask_after_integer", MaskAfterIntegerCase));
}

// A loop's back-edge block (s_and exec, s[12:13], s[80:81]) reads the saveexec mask of the loop's end, but the
Expand Down Expand Up @@ -169,6 +170,26 @@ s_branch .Ljoin
return new ComputeCase(name, Pair40(Program, wave), 1, thread => [Convert.ToUInt32(thread.Lane is 1 or 2)]) { Wave = wave, User = [1] };
}

// A register read as an integer, then written as a mask on both paths and read as one where they meet: every read
// sees one form on every path (MaskFormAnalysis), so the mask stays a bool with no ballot or lane_bit.
private static ComputeCase MaskAfterIntegerCase(string name, int wave)
{
const string Program = """
s_mov_b32 s40, 5
v_mov_b32 v21, s40
s_cmp_eq_u32 s8, 0
s_cbranch_scc1 .Lother
v_cmp_gt_u32_e64 MASK40, 4, v0
s_branch .Ljoin
.Lother:
v_cmp_gt_u32_e64 MASK40, 2, v0
.Ljoin:
v_cndmask_b32_e64 v20, 0, 1, MASK40
""";

return new ComputeCase(name, Pair40(Program, wave), 2, thread => [Convert.ToUInt32(thread.GroupIndex < 4), 5]) { Wave = wave, User = [1] };
}

private static string Pair40(string program, int wave)
{
var pair = "s40";
Expand Down
12 changes: 12 additions & 0 deletions tests/FiveStar.Shaders.Tests/Disassembly/RdnaDecoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,18 @@ public void Lane_masks_follow_the_wave_size(int waveSize, string text)
Assert.Equal(text, Assert.Single(new RdnaDecoder().Disassemble(code, waveSize)).Text);
}

/// <summary>
/// llvm-mc 23 writes the inline constant 0 into the source a VOP3 compare does not read (d4c40028 02020084, where
/// older releases wrote 0): llvm-objdump lists it as the same compare.
/// </summary>
[Fact]
public void An_unread_vop3_source_may_be_the_inline_zero()
{
byte[] code = [0x28, 0x00, 0xC4, 0xD4, 0x84, 0x00, 0x02, 0x02];

Assert.Equal("v_cmp_gt_u32_e64 s40, 4, v0", Assert.Single(new RdnaDecoder().Disassemble(code, Wave32)).Text);
}

/// <summary>The smallest programs of each stage of the dump decode exactly as with llvm-mc/llvm-objdump.</summary>
[LlvmProgramTheory]
[InlineData(8)]
Expand Down
Loading