diff --git a/docs/shader-translation.md b/docs/shader-translation.md index a8b3ac02..32233018 100644 --- a/docs/shader-translation.md +++ b/docs/shader-translation.md @@ -26,7 +26,9 @@ The container is read from `/../dxbc/.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`. 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 @@ -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. diff --git a/src/FiveStar.Shaders/Disassembly/Rdna/Vop3Decoder.cs b/src/FiveStar.Shaders/Disassembly/Rdna/Vop3Decoder.cs index 7d20a0af..61480d0d 100644 --- a/src/FiveStar.Shaders/Disassembly/Rdna/Vop3Decoder.cs +++ b/src/FiveStar.Shaders/Disassembly/Rdna/Vop3Decoder.cs @@ -17,6 +17,9 @@ internal static class Vop3Decoder private const int TiedSources = 2; private const int PermlaneSelects = 3; + /// The source code of the inline constant 0, which current llvm-mc writes in the sources an instruction does not read. + private const int InlineZero = 0x80; + public static Decoded? Decode(CodeWords code, int at) { if (!code.Has(at, Words)) @@ -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; } diff --git a/src/FiveStar.Shaders/Translation/Core/BlockForms.cs b/src/FiveStar.Shaders/Translation/Core/BlockForms.cs new file mode 100644 index 00000000..36293fa8 --- /dev/null +++ b/src/FiveStar.Shaders/Translation/Core/BlockForms.cs @@ -0,0 +1,42 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Shaders.Translation.Core; + +/// +/// 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. +/// +internal sealed class BlockForms +{ + /// Registers read before any write in the block: whether a read took the mask form, the integer form. + public Dictionary Exposed { get; } = []; + + /// The form of the block's last write of each register it writes (true: a lane mask). + public Dictionary Exits { get; } = []; + + /// Registers read inside the block in another form than its own last write left. + public HashSet 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; + } +} diff --git a/src/FiveStar.Shaders/Translation/Core/ControlFlowTranslator.cs b/src/FiveStar.Shaders/Translation/Core/ControlFlowTranslator.cs index e52957ea..837d82f9 100644 --- a/src/FiveStar.Shaders/Translation/Core/ControlFlowTranslator.cs +++ b/src/FiveStar.Shaders/Translation/Core/ControlFlowTranslator.cs @@ -235,6 +235,8 @@ private void TranslateBlocks(HashSet leaders, HashSet reachable) { CloseBlock(current, terminated, instruction.Address); current = instruction.Address; + _state.Forms.Begin(instruction.Address); + _state.Body = []; terminated = false; _exit = null; diff --git a/src/FiveStar.Shaders/Translation/Core/MaskForms.cs b/src/FiveStar.Shaders/Translation/Core/MaskForms.cs new file mode 100644 index 00000000..a46f7302 --- /dev/null +++ b/src/FiveStar.Shaders/Translation/Core/MaskForms.cs @@ -0,0 +1,39 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Shaders.Translation.Core; + +/// +/// Records, block by block, the form each SGPR read assumed and each write left (), so +/// can find the registers a read may reach in both forms along the program's paths. +/// +internal sealed class MaskForms +{ + private readonly Dictionary _blocks = []; + private BlockForms? _current; + + public IReadOnlyDictionary Blocks => _blocks; + + /// Starts the block at . + 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); + } + } +} diff --git a/src/FiveStar.Shaders/Translation/Core/OperandAccess.cs b/src/FiveStar.Shaders/Translation/Core/OperandAccess.cs index 50ec3857..36663eed 100644 --- a/src/FiveStar.Shaders/Translation/Core/OperandAccess.cs +++ b/src/FiveStar.Shaders/Translation/Core/OperandAccess.cs @@ -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}"); @@ -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)) @@ -167,6 +169,14 @@ public void Write(Operand destination, string value, int component = 0) /// After an integer write of an SGPR: it no longer holds a mask. 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); @@ -249,6 +259,7 @@ public void ShadowInteger(RegisterKey key) /// Records that a register now holds a lane mask (and, on wave64, that the next one is its high half). public void MarkMask(RegisterKey key) { + _state.Forms.Write(key, mask: true); _state.Touch(key); _state.Masks.Add(key); _state.MasksEver.Add(key); @@ -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; } diff --git a/src/FiveStar.Shaders/Translation/Core/TranslationState.cs b/src/FiveStar.Shaders/Translation/Core/TranslationState.cs index 3ec54332..bfe9b6d4 100644 --- a/src/FiveStar.Shaders/Translation/Core/TranslationState.cs +++ b/src/FiveStar.Shaders/Translation/Core/TranslationState.cs @@ -135,6 +135,9 @@ public TranslationState(ShaderProgram program, IReadOnlyList instru /// SGPRs used as integers (written, or read while not a mask) somewhere in the program. public HashSet IntegerUses { get; } = []; + /// The form each block reads and leaves its SGPRs in (Stages.MaskFormAnalysis). + public MaskForms Forms { get; } = new(); + /// /// 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 diff --git a/src/FiveStar.Shaders/Translation/Stages/MaskFormAnalysis.cs b/src/FiveStar.Shaders/Translation/Stages/MaskFormAnalysis.cs new file mode 100644 index 00000000..b5f4dec0 --- /dev/null +++ b/src/FiveStar.Shaders/Translation/Stages/MaskFormAnalysis.cs @@ -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; + +/// +/// 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 () gives the +/// forms each register may hold on entry to each block; registers never written yet are integers (hardware inputs). +/// +internal static class MaskFormAnalysis +{ + private const int MaskForm = 1; + private const int IntegerForm = 2; + + /// The registers of some read may see in the other form. + public static HashSet Mixed(TranslationState state, IReadOnlySet 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(); + + 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; + } + + /// The forms each candidate may hold on entry to each block; on entry to the program, only integers. + private static Dictionary> Reaching( + TranslationState state, List blocks, IReadOnlySet candidates) + { + var entry = blocks.ToDictionary(block => (long)block.Address, _ => new Dictionary()); + + 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 Exit(Dictionary entry, BlockForms forms, IReadOnlySet candidates) + { + var exit = new Dictionary(entry); + + foreach (var (key, mask) in forms.Exits) + { + if (candidates.Contains(key)) + { + exit[key] = mask ? MaskForm : IntegerForm; + } + } + + return exit; + } + + /// Adds the forms of to ; true when that added any. + private static bool Merge(Dictionary into, Dictionary 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 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; + } + } +} diff --git a/src/FiveStar.Shaders/Translation/Stages/ProgramTranslator.cs b/src/FiveStar.Shaders/Translation/Stages/ProgramTranslator.cs index 0f3ee851..201c2a8f 100644 --- a/src/FiveStar.Shaders/Translation/Stages/ProgramTranslator.cs +++ b/src/FiveStar.Shaders/Translation/Stages/ProgramTranslator.cs @@ -42,10 +42,11 @@ private static string Emit(Func, TranslationState> cre // second keeps them in their integer variables, which every mask write also sets (OperandAccess.ShadowInteger). var state = create(new HashSet()); 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) { diff --git a/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w32.8fd271588acd981e.bin b/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w32.8fd271588acd981e.bin new file mode 100644 index 00000000..94744802 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w32.8fd271588acd981e.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w64.582c2aa9424e3a9f.bin b/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w64.582c2aa9424e3a9f.bin new file mode 100644 index 00000000..c051328c Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w64.582c2aa9424e3a9f.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w64.fc484ed9a9452a6c.bin b/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w64.fc484ed9a9452a6c.bin new file mode 100644 index 00000000..94744802 Binary files /dev/null and b/tests/FiveStar.Shaders.Tests/Assembled/cs_mask_after_integer_w64.fc484ed9a9452a6c.bin differ diff --git a/tests/FiveStar.Shaders.Tests/Cases/ComputeWaveCases.cs b/tests/FiveStar.Shaders.Tests/Cases/ComputeWaveCases.cs index ba1c8418..1f72ec5d 100644 --- a/tests/FiveStar.Shaders.Tests/Cases/ComputeWaveCases.cs +++ b/tests/FiveStar.Shaders.Tests/Cases/ComputeWaveCases.cs @@ -123,7 +123,8 @@ public static IEnumerable 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 @@ -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"; diff --git a/tests/FiveStar.Shaders.Tests/Disassembly/RdnaDecoderTests.cs b/tests/FiveStar.Shaders.Tests/Disassembly/RdnaDecoderTests.cs index 4623e5a0..e51f9f5c 100644 --- a/tests/FiveStar.Shaders.Tests/Disassembly/RdnaDecoderTests.cs +++ b/tests/FiveStar.Shaders.Tests/Disassembly/RdnaDecoderTests.cs @@ -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); } + /// + /// 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. + /// + [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); + } + /// The smallest programs of each stage of the dump decode exactly as with llvm-mc/llvm-objdump. [LlvmProgramTheory] [InlineData(8)]