From d94dae50985bbd500a97d6d3b0079b3b0beba303 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 18:04:37 +0100 Subject: [PATCH 1/3] startup: lower scalar complements whose sources are all lane masks s_nand_b32, s_nor_b32 and s_xnor_b32 were refused whenever an operand was a lane mask. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask (vcc_lo, exec_lo or an SGPR holding a compare mask) and an SGPR destination the lane's bit of the result is exact. SCC is (the whole complemented word != 0), which the bits of the other lanes decide. It is not emitted: the write is recorded as an SCC effect that is not modelled, and the existing stale-SCC scan refuses a program that can read it before the next SCC write, through joins and back edges. The mask mark follows program order. At a branch target a marked SGPR stays proven only if its last write dominates the target and no block on a path from that write to the target writes it again; a complement on any other marked SGPR is refused until the register is written again. A mask mixed with a plain word or a constant, and a vcc_lo, exec_lo or m0 destination, stay refused. Co-Authored-By: Claude Fable 5.2 --- docs/experiments.md | 12 +- .../startup_gfx2hlsl_sop2_complement_check.py | 136 +++++++++++++++++- tools/startup/gfx2hlsl.py | 67 +++++++-- 3 files changed, 199 insertions(+), 16 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 222b1ee7a8..da5e88a74b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7515,11 +7515,15 @@ Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_b64_shift$' -V`. (#870, issue #1919). They now lower as `~(S0 & S1)`, `~(S0 | S1)` and `~(S0 ^ S1)` on 32 bits, the text `pixel_aot` uses, and set SCC when the result is nonzero like the other logic operations. The check decodes SGPR, in-place, inline-constant, literal and m0-destination forms and evaluates the emitted lines against an -integer reference over 0, all ones, alternating bits, every single bit and mixed words. Lane-mask forms (a -vcc_lo/exec_lo operand or destination, or an SGPR holding a compare mask) are refused: guest SCC reads the whole -32-bit mask, which the per-lane projection cannot show. A table +integer reference over 0, all ones, alternating bits, every single bit and mixed words. A table entry without the complement or without the SCC write must fail, and SOP2 operations with no lowering stay -refused by name. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with +refused by name. On lane masks (vcc_lo, exec_lo or an SGPR holding a compare mask) the result is exact per lane +when every source is a mask, because bit i of the complement depends only on bit i of each source: that form +lowers to `(~(a op b)) & 1` into an SGPR, checked on all 32 lanes of the edge words. Guest SCC reads the whole +32-bit result, which the per-lane projection cannot show, so SCC is not emitted and a program that can read it +before the next SCC write is refused, through joins and back edges. A mask mixed with a plain word or a constant +and a vcc_lo or exec_lo destination stay refused, as does a mask source whose last write does not dominate a +branch target crossed since, or which a block on a path to that target writes again. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with LLVM 15, `tests/startup_gfx2hlsl_sop2_complement_check.py binary ` and `decode ` round-trip the same words. diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 2655ba1342..6c1b7de02d 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -16,9 +16,18 @@ The lowering text and SCC rule equal pixel_aot's SCALAR entries for the same operations (#561). Every numeric form (SGPR, inline, literal or m0 operands) emits the lines of its non-complement sibling (s_and_b32, s_or_b32, s_xor_b32) -with the operation wrapped in ~( ). Lane-mask forms are refused: a vcc_lo or exec_lo operand or destination, or an -SGPR holding a compare mask, is the whole wave's mask, and SCC is set when any bit of the complemented 32-bit result -is; the translator's per-lane projection cannot show that, so no mask lowering is claimed. +with the operation wrapped in ~( ). + +Lane masks: vcc_lo, exec_lo or an SGPR holding a compare mask is the whole wave's mask, of which the translator keeps +one lane's bit. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask and an +SGPR destination the lane's bit of the result is exact: the form is accepted and checked here on every lane of the +edge words. SCC is set when any bit of the complemented 32-bit result is, which the other lanes decide (the bit of an +idle lane is set); the per-lane projection cannot show that, so SCC is not emitted and a program that can read it +before the next SCC write is refused (through branches too). A mask and a plain word mixed, a constant source, and a +vcc_lo or exec_lo destination stay refused. The mask mark follows program order, so a mark is a proof at a branch +target only if the register's last write dominates the target and no block on a path from that write to the target +writes the register again; otherwise the complement is refused until the register is written again. Mutations: the +join rule disabled and the SCC read scan disabled must each accept a refused program. Mutations: the table entry with the complement dropped, and the entry with the SCC write dropped, must each read a wrong result or SCC. Refused: every SOP2 operation the decoder names that still has no lowering. @@ -228,6 +237,124 @@ def first_mismatch(name, reference=None, updates_scc=True): return None +def run_text(*instructions): + """Translate disassembly text with the branch scan of a real stage -> emitted lines.""" + stage = Probe() + stage.attrs = {} + stage.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + stage.translate() + return [line for _, lines, _ in stage.blocks for line in lines] + + +def text_refusal(*instructions): + try: + return 'accepted: %s' % run_text(*instructions) + except G.Unsupported as error: + return str(error) + + +def lane_mask_controls(): + operator = {name: SIBLING_OPERATOR[sibling] for name, (sibling, _) in OPS.items()} + # 1. Every source a lane mask, SGPR destination: one line, the lane's bit of the complement, and no SCC write. + forms = [('s3, s1, s2', 's3', 's1', 's2'), ('s1, s2, s1', 's1', 's2', 's1'), ('s3, vcc_lo, s1', 's3', 'vcc', 's1'), + ('s3, s2, exec_lo', 's3', 's2', 'exec'), ('s3, vcc_lo, exec_lo', 's3', 'vcc', 'exec')] + for name, (_, reference) in OPS.items(): + wrong = [] + for operands, dest, left, right in forms: + stage = Probe() + stage.masks.update((1, 2)) + stage.one(name, '%s %s' % (name, operands)) + expected = ['%s = (~(%s %s %s)) & 1;' % (dest, left, operator[name], right)] + if stage.lines != expected or int(dest[1:]) not in stage.masks or stage.scc_effect != 'a lane-mask complement': + wrong.append((operands, stage.lines, expected, sorted(stage.masks), stage.scc_effect)) + continue + for a, b in ((a, b) for a in SPECIAL for b in SPECIAL): + for lane in range(32): + env = {left: (a >> lane) & 1, right: (b >> lane) & 1, 'scc': SCC_UNSET} + out = run_lines(stage.lines, env) + if (out[dest], out['scc']) != ((reference(a, b) >> lane) & 1, SCC_UNSET): + wrong.append((operands, hex(a), hex(b), lane, out[dest], out['scc'])) + break + check('%s: %d all-mask forms give the lane bit of the reference on 32 lanes x %d pairs, SCC not written' + % (name, len(forms), len(SPECIAL) ** 2), not wrong, str(wrong[:2])) + + # 2. Still refused: a constant or plain-word source next to a mask, a mask destination, a high-half mask name. + for name in OPS: + wrong = [] + for operands in ('s3, s1, s9', 's3, s9, vcc_lo', 's3, s1, -1', 's3, 0, vcc_lo', 'vcc_lo, s1, s2', + 'exec_lo, s1, s2', 's3, s1, vcc_hi', 'm0, s1, s2'): + stage = Probe() + stage.masks.update((1, 2)) + try: + stage.one(name, '%s %s' % (name, operands)) + wrong.append((operands, stage.lines)) + except G.Unsupported as error: + if str(error) != '%s on a lane mask' % name or stage.lines: + wrong.append((operands, str(error), stage.lines)) + check('%s: mixed, constant and mask-destination forms stay refused' % name, not wrong, str(wrong[:2])) + + # 3. Whole programs. SCC after the complement is not the guest's: a read before the next SCC write is refused. + masks = ('v_cmp_eq_f32_e64 s5, 0, v1', 'v_cmp_lt_f32_e64 s4, 0, v2') + for name in OPS: + complement = '%s s4, s5, s4' % name + line = 's4 = (~(s5 %s s4)) & 1;' % operator[name] + lines = run_text(*masks, complement, 's_and_saveexec_b32 s4, s4', 's_endpgm') + at = lines.index(line) if line in lines else -1 + check('%s between two compares and s_and_saveexec_b32 is accepted' % name, + at >= 0 and lines[at + 1:at + 3] == ['w = s4;', 's4 = exec;'] and 'scc = s4 != 0;' not in lines, str(lines)) + lines = run_text(*masks, complement, 's_cmp_eq_u32 s2, 0', 's_cselect_b32 s6, 1, 0', 's_endpgm') + check('%s then an SCC write then a read is accepted' % name, + line in lines and any(text.startswith('s6 = scc ?') for text in lines), str(lines)) + programs = { + 's_cselect_b32': (*masks, complement, 's_cselect_b32 s6, 1, 0', 's_endpgm'), + 's_cbranch_scc1': (*masks, complement, 's_cbranch_scc1 label_0010', 's_endpgm'), + # the read sits behind a jump that skips the SCC write + 's_cmov_b32': (*masks, complement, 's_branch label_0014', 's_cmp_eq_u32 s2, 0', 's_cmov_b32 s6, s7', + 's_endpgm'), + # the read sits at a loop head that the complement reaches over the back edge + 's_cselect_b64': ('s_cmp_eq_u32 s2, 0', 's_cselect_b64 s[6:7], 1, 0', *masks, complement, + 's_cbranch_vccz label_0004', 's_endpgm'), + } + got = {reader: text_refusal(*program) for reader, program in programs.items()} + want = {reader: 'scc from a lane-mask complement in %s' % reader for reader in programs} + check('%s: an SCC read before the next SCC write is refused (%d programs)' % (name, len(programs)), + got == want, str(got)) + + # 4. The mask mark at a branch target. + skip = ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_0010', *masks) # the branch skips both compares + loop = (*masks, 's_nand_b32 s6, s5, s4', 's_mov_b32 s5, s3', 's_cmp_eq_u32 s2, 0', 's_cbranch_scc0 label_0008', + 's_endpgm') # the body overwrites s5 before the back edge + arms = ('v_cmp_eq_f32_e64 s5, 0, v1', 's_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_0014', 'v_cmp_lt_f32_e64 s4, 0, v2', + 's_branch label_0020', 'v_cmp_lt_f32_e64 s4, 0, v3', 's_nand_b32 s4, s5, s4', 's_and_saveexec_b32 s4, s4', + 's_endpgm') # s5 is written before the split only + joined = 's_nand_b32 on a lane mask joined at a branch target' + got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] + check('a mask that another path into the branch target changes is refused (skipped write, loop body write)', + got == [joined, joined], str(got)) + lines = run_text(*arms) + check('a mask written before the split and on no arm crosses the join', 's4 = (~(s5 & s4)) & 1;' in lines, str(lines)) + lines = run_text(*skip, *masks, 's_nand_b32 s6, s5, s4', 's_endpgm') + check('a mask written again after the join is proven again', 's6 = (~(s5 & s4)) & 1;' in lines, str(lines)) + got = text_refusal(*masks, 's_mov_b32 s5, s3', 's_nand_b32 s6, s5, s4', 's_endpgm') + check('an overwritten mask is a plain word: refused', got == 's_nand_b32 on a lane mask', got) + + # 5. Mutations: each rule disabled accepts a program refused above. + saved = G.Stage.unjoined_masks + G.Stage.unjoined_masks = lambda self, target, last_write: set() + try: + got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] + finally: + G.Stage.unjoined_masks = saved + check('mutation without the join rule accepts both programs', all(t.startswith('accepted') for t in got), str(got)) + saved = G.Stage.descriptor_scc_reads + G.Stage.descriptor_scc_reads = lambda self, branches, effects: iter(()) + try: + got = text_refusal(*masks, 's_nand_b32 s4, s5, s4', 's_cselect_b32 s6, 1, 0', 's_endpgm') + finally: + G.Stage.descriptor_scc_reads = saved + check('mutation without the SCC read scan accepts the read', got.startswith('accepted'), got) + + def pack_controls(): def reference(a, b): return (b // 65536) * 65536 + a // 65536 @@ -501,7 +628,7 @@ def controls(): check('%s: %d numeric forms emit the %s lines complemented, same mask and EXEC bookkeeping' % (name, len(VALUE_FORMS), sibling), not wrong, str(wrong[:2])) - # 5b. Lane-mask forms are refused: vcc_lo/exec_lo operands and destinations, and an SGPR holding a compare mask. + # 5b. Refused: a lane mask next to a plain word, or as the destination (lane_mask_controls has the accepted forms). for name in OPS: accepted = [] for form in MASK_FORMS: @@ -560,6 +687,7 @@ def controls(): wrong.append((asm, str(error))) check('%d SOP2 operations without a lowering are refused by name (%s)' % (len(missing), ', '.join(missing)), missing and not wrong and not set(OPS) & set(missing), str(wrong)) + lane_mask_controls() pack_controls() bfe_controls() mul_controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 221cedb43b..1815e235c9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1610,8 +1610,35 @@ def joined_registers(self, with_cfg=False): regs = set().union(*(writes[w] for w in div)) if div else set() affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets div_targets[off] = (regs, affected) + self.flow = (index, block_of, succ, dom, writes, {}) return joined, forward_splits, div_targets + def unjoined_masks(self, target, last_write): + """Marked SGPRs whose mark is not proven at a branch target. self.masks follows program order, so a mark + holds on every path into the target only if the block of the register's last write dominates the target and + no block on a path from that write to the target writes the register again.""" + index, block_of, succ, dom, writes, reached = self.flow + if target not in index: + return set(self.masks) + def after(block): # blocks reached from block over at least one edge + if block not in reached: + seen, todo = set(), list(succ[block]) + while todo: + b = todo.pop() + if b not in seen: + seen.add(b) + todo += succ[b] + reached[block] = seen + return reached[block] + t = block_of[index[target]] + into = {b for b in range(len(succ)) if t in after(b)} + out = set() + for reg in self.masks: + w = block_of[index[last_write[reg]]] if reg in last_write else 0 + if w not in dom[t] or any(reg in writes[b] for b in (after(w) & into) - {w}): + out.add(reg) + return out + def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ try: @@ -1663,6 +1690,8 @@ def translate(self): self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.masks = set(init_masks) + self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined_masks) + last_write = {} # SGPR -> offset of its last write in program order self.attrs = dict(init_attrs) self.used_s, self.used_v = set(init_used_s), set(init_used_v) self.exports = {} @@ -1740,6 +1769,7 @@ def translate(self): if reg != 'm0': self.used_s.add(reg) clobber = here if off in joined else every_sgpr + self.join_masks |= self.unjoined_masks(off, last_write) fwd_clobber = forward_splits.get(off, clobber) blocked = force_unproven | force_at.get(off, set()) kept_u = { @@ -1778,6 +1808,7 @@ def translate(self): falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests + last_write.update(dict.fromkeys(dests, off)) try: if off in refused: raise Unsupported(refused[off]) @@ -1807,6 +1838,8 @@ def translate(self): raise refusals.append((handler_error(name, error, refusals), self.kind)) continue + # A write proves the mark again: every path from here on runs it. s_movreld can write any SGPR. + self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests if self.scc_effect: scc_effects[off] = self.scc_effect if term: @@ -1835,9 +1868,9 @@ def translate(self): if self.lines: self.blocks.append((start, self.lines, None)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) - if 'descriptor' in scc_effects.values(): - for name in self.descriptor_scc_reads(dict(branches), scc_effects): - reason = 'scc from descriptor data in %s' % name + if set(scc_effects.values()) - {'emitted'}: + for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): + reason = 'scc from %s in %s' % ('descriptor data' if kind == 'descriptor' else kind, name) if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) @@ -1852,7 +1885,7 @@ def translate(self): def descriptor_scc_reads(self, branches, effects): """Find reads reachable with an elided SCC write, including through joins and back edges.""" instructions = {off: (size, name, asm) for off, size, name, asm in self.ins} - pending = [(0, False)] + pending = [(0, None)] # stale: None, or the scc_effect of the write that left the emitted scc behind seen = set() while pending: off, stale = pending.pop() @@ -1861,9 +1894,9 @@ def descriptor_scc_reads(self, branches, effects): seen.add((off, stale)) size, name, asm = instructions[off] if stale and off not in self.calculated_pc and reads_scc(name, asm): - yield name + yield stale, name if off in effects: - stale = effects[off] == 'descriptor' + stale = effects[off] if effects[off] != 'emitted' else None if off in branches: pending.append((branches[off], stale)) if name not in ('s_branch', 's_setpc_b64', 's_endpgm'): @@ -2371,6 +2404,7 @@ def low(tok): srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16) shift_add = base in SHIFT_ADD word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') + lane_complement = False # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. word_pack = base in ('s_pack_hh_b32_b16', 's_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') if shift_add or word_complement or word_pack: @@ -2378,8 +2412,19 @@ def low(tok): # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' else self.is_lane_mask(dname)) - if mask_dest or any(self.is_lane_mask(t) for t in srcs): + # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's + # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. + def mask_source(tok): + r = reg_range(tok) + return tok in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or bool( + r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks) + lane_complement = (word_complement and bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 + and all(mask_source(t) for t in srcs)) + if not lane_complement and (mask_dest or any(self.is_lane_mask(t) for t in srcs)): raise Unsupported('%s on a lane mask' % base) + if lane_complement and any(reg_range(t) and reg_range(t)[1] in getattr(self, 'join_masks', ()) + for t in srcs): + raise Unsupported('%s on a lane mask joined at a branch target' % base) if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) if word_pack: @@ -2519,7 +2564,13 @@ def known(tok): high_source = 's%d' % high if high is not None else srcs[0] high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) - self.set_s(d, expr, scc=scc) + self.set_s(d, expr, scc=None if lane_complement else scc) + if lane_complement: + # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an + # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. + self.scc_effect = 'a lane-mask complement' + if self.tracks_uniformity(): + self.scc_uniform = False if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': From 661c9a1a8b1b4aa7cd7d52d561ca8a7168d1e4ee Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 18:11:54 +0100 Subject: [PATCH 2/3] startup: keep a scalar constant across a branch target when its write dominates At a branch target the translator drops every scalar constant whose register is in the target's joined set. That set also holds the writes of every earlier block that is off the dominator chain, so a register used inside an earlier conditional block and then set to a constant on every path lost the constant at each later join. A constant sampler built from s_movk_i32, s_bfm_b32 and s_mov_b64 then reached the image instruction as four plain words and was refused as a descriptor operand without a symbol. The constant is now dropped only when it is not proven by its own write: the block of the register's last write must dominate the target and no block on a path from that write to the target may write the register again (the rule the lane-mask complement uses for mask marks, now shared as Stage.unjoined). A later arm or a loop body that writes the register still drops it. Co-Authored-By: Claude Fable 5.2 --- .../startup_gfx2hlsl_loop_constants_check.py | 40 ++++++++++++++++++- .../startup_gfx2hlsl_sop2_complement_check.py | 6 +-- tools/startup/gfx2hlsl.py | 26 +++++++----- 3 files changed, 56 insertions(+), 16 deletions(-) diff --git a/tests/startup_gfx2hlsl_loop_constants_check.py b/tests/startup_gfx2hlsl_loop_constants_check.py index 3533074178..b652996b9f 100644 --- a/tests/startup_gfx2hlsl_loop_constants_check.py +++ b/tests/startup_gfx2hlsl_loop_constants_check.py @@ -11,8 +11,14 @@ A constant that no other path writes stays folded (control). Folding the counter froze it at 1, so the exit test fired only for a trip count of 1 and every other loop ran until the dispatcher guard (65,536 iterations). -Mutations (each must turn the battery red): constants kept at every join (the behavior before this check), and -the loop body range left out (only forward branches handled). +"No other path writes the register" is judged from the constant's own write: the constant stays known at a branch +target when the block of that write dominates the target and no block on a path from the write to the target writes +the register again. A write in an earlier arm, before the constant was set, does not count (a register reused for a +constant sampler word after an earlier conditional block used it for something else). A later arm or a loop body +that writes it still drops it. + +Mutation (must turn the battery red): constants kept at every join (the behavior before this check). Leaving the +loop body range out of join_writes alone does not: the joined set and the dominance rule see the loop body too. """ import os import sys @@ -67,6 +73,36 @@ def run(*instructions): 's_endpgm'), ['s8 = 0x00000003u + 0x00000001u;', 's14 = s14 + 0x00000001u;'], ['s8 = s7 + 0x00000001u;']), + # An earlier arm writes s7, then every path sets it to 3; the second conditional block does not write it. + ('constant set after an earlier arm wrote the register', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_cmp_eq_u32 s2, 1', + 's_cbranch_scc1 label_001c', 's_mov_b32 s9, 1', 's_add_u32 s8, s7, 1', 's_endpgm'), + ['s8 = 0x00000003u + 0x00000001u;'], + ['s8 = s7 + 0x00000001u;']), + # The same program with the second arm writing s7: two values reach the join. + ('constant set after an earlier arm, later arm writes it', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_cmp_eq_u32 s2, 1', + 's_cbranch_scc1 label_001c', 's_mov_b32 s7, 9', 's_add_u32 s8, s7, 1', 's_endpgm'), + ['s8 = s7 + 0x00000001u;'], + ['s8 = 0x00000003u + 0x00000001u;', 's8 = 0x00000009u + 0x00000001u;']), + # The constant is set in an arm only: its write does not dominate the join, whatever the arm before it did. + ('constant set in an arm after an earlier arm wrote the register', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_cmp_eq_u32 s2, 1', + 's_cbranch_scc1 label_0018', 's_mov_b32 s7, 3', 's_add_u32 s8, s7, 1', 's_endpgm'), + ['s8 = s7 + 0x00000001u;'], + ['s8 = 0x00000003u + 0x00000001u;', 's8 = 0x00000005u + 0x00000001u;']), + # An earlier arm writes s7, every path sets it to 3, and a loop reads it: kept when the body leaves it alone, + # dropped when the body writes it after the read. + ('constant set after an earlier arm, read in a loop', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_add_u32 s8, s7, 1', + 's_cmp_eq_u32 s8, s2', 's_cbranch_scc0 label_0010', 's_endpgm'), + ['s8 = 0x00000003u + 0x00000001u;'], + ['s8 = s7 + 0x00000001u;']), + ('constant set after an earlier arm, written in the loop', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_add_u32 s8, s7, 1', + 's_mov_b32 s7, 4', 's_cmp_eq_u32 s8, s2', 's_cbranch_scc0 label_0010', 's_endpgm'), + ['s8 = s7 + 0x00000001u;'], + ['s8 = 0x00000003u + 0x00000001u;', 's8 = 0x00000004u + 0x00000001u;']), ] for label, program, wanted, unwanted in CASES: diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 6c1b7de02d..6a4394bb9d 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -339,12 +339,12 @@ def lane_mask_controls(): check('an overwritten mask is a plain word: refused', got == 's_nand_b32 on a lane mask', got) # 5. Mutations: each rule disabled accepts a program refused above. - saved = G.Stage.unjoined_masks - G.Stage.unjoined_masks = lambda self, target, last_write: set() + saved = G.Stage.unjoined + G.Stage.unjoined = lambda self, target, last_write, regs: set() try: got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] finally: - G.Stage.unjoined_masks = saved + G.Stage.unjoined = saved check('mutation without the join rule accepts both programs', all(t.startswith('accepted') for t in got), str(got)) saved = G.Stage.descriptor_scc_reads G.Stage.descriptor_scc_reads = lambda self, branches, effects: iter(()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 1815e235c9..783c5565b4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1613,13 +1613,14 @@ def joined_registers(self, with_cfg=False): self.flow = (index, block_of, succ, dom, writes, {}) return joined, forward_splits, div_targets - def unjoined_masks(self, target, last_write): - """Marked SGPRs whose mark is not proven at a branch target. self.masks follows program order, so a mark - holds on every path into the target only if the block of the register's last write dominates the target and - no block on a path from that write to the target writes the register again.""" + def unjoined(self, target, last_write, regs): + """The registers of regs whose program-order state is not proven at a branch target. A lane-mask mark or a + constant follows program order, so it holds on every path into the target only if the block of the register's + last write dominates the target and no block on a path from that write to the target writes the register + again.""" index, block_of, succ, dom, writes, reached = self.flow if target not in index: - return set(self.masks) + return set(regs) def after(block): # blocks reached from block over at least one edge if block not in reached: seen, todo = set(), list(succ[block]) @@ -1633,7 +1634,7 @@ def after(block): # blocks reached from block over at least one edge t = block_of[index[target]] into = {b for b in range(len(succ)) if t in after(b)} out = set() - for reg in self.masks: + for reg in regs: w = block_of[index[last_write[reg]]] if reg in last_write else 0 if w not in dom[t] or any(reg in writes[b] for b in (after(w) & into) - {w}): out.add(reg) @@ -1769,7 +1770,7 @@ def translate(self): if reg != 'm0': self.used_s.add(reg) clobber = here if off in joined else every_sgpr - self.join_masks |= self.unjoined_masks(off, last_write) + self.join_masks |= self.unjoined(off, last_write, self.masks) fwd_clobber = forward_splits.get(off, clobber) blocked = force_unproven | force_at.get(off, set()) kept_u = { @@ -1782,9 +1783,12 @@ def translate(self): # A constant is only known here if no other path into the join writes the register: a loop counter # set before the loop and incremented in it reaches the loop head with a new value on every pass. # set_s also assigns constants at run time, so the register reads its real value once it is dropped. - for reg in join_writes.get(off, ()) | (clobber & every_sgpr): - if (self.sym.get(reg) or ('',))[0] == 'const': - del self.sym[reg] + # clobber also holds the writes of every earlier block off the dominator chain; a constant written + # after those, by a block every path runs, with no later write on any path, is still known. + consts = {reg for reg in join_writes.get(off, set()) | (clobber & every_sgpr) + if (self.sym.get(reg) or ('',))[0] == 'const'} + for reg in self.unjoined(off, last_write, consts): + del self.sym[reg] self.defined_uniform_s = set(kept_u) | { k for k, v in self.sym.items() if isinstance(k, int) and v and ( @@ -1808,7 +1812,7 @@ def translate(self): falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests - last_write.update(dict.fromkeys(dests, off)) + last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) try: if off in refused: raise Unsupported(refused[off]) From dfff36eae2ae8bc20f25f53ccba338b0056a3750 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:32:12 +0100 Subject: [PATCH 3/3] gfx2hlsl: drop the unreachable target guard in Stage.unjoined Both callers pass the offset of an instruction in self.ins, and the flow index is built from the same list, so the target is always in index. Co-Authored-By: Claude Sonnet 5.5 --- tools/startup/gfx2hlsl.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a94eb4d2f2..21ac53c5f5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1870,8 +1870,6 @@ def unjoined(self, target, last_write, regs): last write dominates the target and no block on a path from that write to the target writes the register again.""" index, block_of, succ, dom, writes, reached = self.flow - if target not in index: - return set(regs) def after(block): # blocks reached from block over at least one edge if block not in reached: seen, todo = set(), list(succ[block])