From 9c0fea946564e909269e1657b7d02b3d9fab4c16 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 00:45:59 +0100 Subject: [PATCH 1/4] fix: prove v_readfirstlane_b32 sources inside one basic block when the shader has branches Part of #1723. VGPR uniformity is proven per basic block and cleared at every join; refused when any instruction writes exec; scalar sources that can carry a lane mask are excluded program-wide. --- CMakeLists.txt | 3 ++ ...up_gfx2hlsl_readfirstlane_uniform_check.py | 6 +++ tests/startup_readfirstlane_branch_check.py | 44 ++++++++++++++++ tools/startup/gfx2hlsl.py | 50 +++++++++++++++++-- 4 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 tests/startup_readfirstlane_branch_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 36aa44a2b7..6fb6a57870 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2371,6 +2371,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_live_view PROPERTIES TIMEOUT 60) add_test(NAME startup_uniform_lane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_uniform_lane_check.py") + # v_readfirstlane_b32 in a program with branches: proven inside one basic block, refused across a join or exec write. + add_test(NAME startup_readfirstlane_branch COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_readfirstlane_branch_check.py") # NGG primitive-shader cases (#1723): identity triangle against single-change contrasts, reference model. add_test(NAME startup_ngg_slice COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_ngg_slice_check.py") diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index b5b7dd2422..6d308a39c4 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -170,6 +170,12 @@ def run(*instructions, exec_known=True): for label, instructions in REFUSED: got = run(*instructions) check(f'{label} refused', got == EARLIER.get(label, REFUSAL), repr(got)) +# A branch later in the program no longer blocks a read whose source is proven in its own block. +got = run('v_mov_b32_e32 v7, s2', READ, 's_branch label_000C', 's_endpgm') +check('branch after read accepted', got == ['v7 = s2;', 's9 = v7;'], repr(got)) +# A proven chain inside one block stays accepted when a branch follows it. +got = run('v_cvt_f32_u32_e32 v7, s3', 'v_rcp_f32_e32 v7, v7', READ, 's_cbranch_scc0 label_0010', 's_endpgm') +check('chain before a branch accepted', got == ['v7 = U(float(s3));', 'v7 = U(1.0 / F(v7));', 's9 = v7;'], repr(got)) # SCC written through m0 (#1931 review): a compare mask carried into m0 makes SCC varying, so the # select that reads it, and a VGPR copied from that select, stay unproven; EXEC is left unchanged. got = run('v_cmp_lt_f32_e32 vcc_lo, v0, v1', 's_and_b32 m0, vcc_lo, -1', 's_cselect_b32 s2, 1, 0', diff --git a/tests/startup_readfirstlane_branch_check.py b/tests/startup_readfirstlane_branch_check.py new file mode 100644 index 0000000000..4af03a8d2f --- /dev/null +++ b/tests/startup_readfirstlane_branch_check.py @@ -0,0 +1,44 @@ +"""v_readfirstlane_b32 in a program with branches: proven inside one basic block, refused across a join or exec write.""" +from pathlib import Path +import struct +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools/startup")) +import gfx2hlsl as gfx + + +class TestPipeline: + root = {"params": [{"type": 2}], "flags": 0} + + def resource(self, key, kind): + return "r0" + + +S_BRANCH_NEXT = 0xbf820000 # s_branch +0: the next instruction becomes a block start +S_EXEC_LO_ZERO = 0xbe800300 | 126 << 16 | 128 # s_mov_b32 exec_lo, 0 +S_LOAD = [0xf4000000 | 8 << 18 | 7 << 6 | 4, 125 << 25 | 12] # s_buffer_load_dword s7, s[8:11], 12 +CVT_V4 = 0x7e000000 | 4 << 17 | 8 << 9 | 7 # v_cvt_i32_f32 v4, s7 +READ_V4 = 0x7e000000 | 6 << 17 | 2 << 9 | 256 + 4 # v_readfirstlane_b32 s6, v4 +END = 0xbf810000 + + +def translate(*words): + words = [*S_LOAD, *words] + return gfx.Stage(TestPipeline(), "ps", struct.pack(f"<{len(words)}I", *words)) + + +# A branch after the read does not stop the read from being proven in its own block. +body = "\n".join(line for block in translate(CVT_V4, READ_V4, S_BRANCH_NEXT, END).blocks for line in block[1]) +assert "s6 = v4;" in body, body + +# A join point between the proof and the read, or an exec write anywhere, leaves the source unproven. +for words in ([CVT_V4, S_BRANCH_NEXT, READ_V4, END], + [CVT_V4, READ_V4, S_BRANCH_NEXT, S_EXEC_LO_ZERO, END], + [S_EXEC_LO_ZERO, CVT_V4, READ_V4, S_BRANCH_NEXT, END]): + try: + translate(*words) + except gfx.Unsupported as error: + assert "requires a proven uniform source" in str(error), str(error) + else: + raise AssertionError("accepted an unproven readfirstlane: %r" % (words,)) +print("readfirstlane with branches: block-local proof accepted; three unproven reads rejected") diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 18688048c3..91427e0d15 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -700,12 +700,15 @@ def translate(self): self.varying_s = set() self.scc_uniform = True self.has_branches = bool(targets) + self.entry_loop = 0 in targets + self.branch_proof, self.tainted_s = self.scan_branch_safety() if targets else (False, set()) start = 0 refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ for off, n, name, asm in self.ins: if off in targets and off != start: self.blocks.append((start, self.lines, None)) self.lines, start = [], off + self.uniform_v.clear() # a join point: no VGPR proof survives from the code above it self.pc = off # Before the first branch target or terminator every path has run exactly the instructions above, so # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a @@ -726,9 +729,49 @@ def translate(self): if term: self.blocks.append((start, self.lines, term)) self.lines, start = [], off + n + self.uniform_v.clear() if self.lines: self.blocks.append((start, self.lines, None)) + def scan_branch_safety(self): + """-> (proof_ok, tainted_s) for a program with branches. VGPR uniformity is proven inside one basic block + only (see translate), and only when no instruction anywhere writes exec, so exec_known holds on every path. + tainted_s holds each scalar register that can carry a per-lane value (a compare or exec-derived mask), + found over the whole program because a loop can bring a later write back to an earlier read.""" + lane_names = ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') + parsed = [] + proof_ok = True + for _, _, name, asm in self.ins: + _, ops, _ = parse(asm) + parsed.append((name, ops)) + if ops and (ops[0] in ('exec', 'exec_lo', 'exec_hi') or 'saveexec' in name or name.startswith('v_cmpx')): + proof_ok = False + tainted = set() + changed = True + while changed: + changed = False + for name, ops in parsed: + dst = reg_range(ops[0]) if ops else None + if not dst or dst[0] != 's' or name.startswith('v_readfirstlane'): + continue + hot = name.startswith('v_cmp') or any(op in lane_names for op in ops[1:]) + for tok in ops[1:]: + src = reg_range(tok) + if src and src[0] == 's' and any(r in tainted for r in range(src[1], src[2] + 1)): + hot = True + if hot and not all(r in tainted for r in range(dst[1], dst[2] + 1)): + tainted.update(range(dst[1], dst[2] + 1)) + changed = True + return proof_ok, tainted + + def proof_allowed(self): + """Entry-block code is exact in program order (merged entry proof). Later blocks need the branch scan to + pass and no branch back to offset 0, so an entry loop keeps refusing.""" + if not getattr(self, 'past_entry', True): + return True + return (not getattr(self, 'entry_loop', True) and + (not getattr(self, 'has_branches', True) or getattr(self, 'branch_proof', False))) + def tracks_uniformity(self): return all(hasattr(self, name) for name in ('uniform_v', 'varying_s', 'scc_uniform')) @@ -740,7 +783,8 @@ def uniform_source(self, tok): return False if kind == 'v': return lo in self.uniform_v - if lo in getattr(self, 'masks', ()): + if lo in getattr(self, 'masks', ()) or (getattr(self, 'has_branches', False) and + lo in getattr(self, 'tainted_s', ())): return False sym = self.sym.get(lo) if sym: @@ -761,7 +805,7 @@ def one(self, name, asm): dst = None # Unit probes build a Stage without __init__: without the tracking state, prove nothing. if (base in UNIFORM_VALU and ops and self.tracks_uniformity() and - not getattr(self, 'past_entry', True) and getattr(self, 'exec_known', False) and + self.proof_allowed() and getattr(self, 'exec_known', False) and (not mods or (base in VEC_F or base in VEC_U_TO_F) and all(m in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods))): candidate = reg_range(ops[0]) @@ -1855,7 +1899,7 @@ def op_v_cvt_i32_f32(self, ops, mods): def op_v_readfirstlane_b32(self, ops, mods): src, dst = reg_range(ops[1]), reg_range(ops[0]) - if (mods or not self.tracks_uniformity() or getattr(self, 'past_entry', True) or + if (mods or not self.tracks_uniformity() or not self.proof_allowed() or not getattr(self, 'exec_known', False) or not dst or dst[0] != 's' or dst[1] != dst[2] or not src or src[0] != 'v' or src[1] != src[2] or src[1] not in self.uniform_v): raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') From 2ddf6bc725dfdbc41607bd264a1ef04389911866 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 02:00:53 +0100 Subject: [PATCH 2/4] fix: track wrexec, per-lane SCC and m0 in the readfirstlane branch scan; document the branch case --- docs/experiments.md | 6 ++- tests/startup_readfirstlane_branch_check.py | 16 ++++++++ tools/startup/gfx2hlsl.py | 43 ++++++++++++++------- 3 files changed, 49 insertions(+), 16 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c441b2ca8b..e3a006135c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12144,12 +12144,14 @@ In straight-line code with a known `exec`, the proof follows `v_cvt_u32_f32`, `v Uniform sources include inline constants and literals, SGPRs holding constants, user data or fixed buffer words, other SGPRs tracked as uniform, and VGPRs with an existing proof. A scalar result is tracked as varying when its expression depends on `vcc`, `exec`, `m0`, a varying scalar register, a VGPR without a proof, or a varying `scc`. Descriptor, pointer, and sampler symbols, and SGPRs holding a lane mask (a compare result, even from uniform operands), are treated as non-uniform sources. A 64-bit move proves its high word only from the source high word as it was before the move, never when the destination overlaps it, and a descriptor-path move carries a high-word symbol only when that symbol does not depend on the register's run-time contents. SCC follows the same dependency tracking, with saveexec and wrexec marking it varying. A scalar write to `m0` that also sets SCC judges SCC from the write's sources, so `s_and_b32 m0, vcc_lo, -1` makes it varying while a write from uniform scalars makes it uniform. Instructions whose SCC result is not modelled (`s_add`, `s_sub`, `s_min` and `s_max`, `s_wqm`, and scalar ops on symbolic descriptor words, which emit nothing) mark SCC varying. Scalar buffer loads track the original offset across every destination word, including when the emitted code saves it in a temporary. -An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read requires known `exec` and no modifiers. In a program with branches, the proof and the read are accepted only in the entry block: before the first branch target and before the first terminator. Every path reaches those instructions through the same instructions, so the program-order tracking is exact there. A branch back to the first instruction makes the whole program refuse, because a loop re-enters the entry block. It now explicitly checks for a single SGPR destination and a single VGPR source. +An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read requires known `exec` and no modifiers. In a program with branches, the entry block (before the first branch target and the first terminator) is always exact in program order, because every path reaches it through the same instructions. Later blocks are accepted only when the proof is made inside one basic block: every branch target clears all VGPR proofs, and no instruction anywhere in the program writes `exec` (`exec` moves, `saveexec`, `wrexec` and `v_cmpx` all count). A whole-program scan also marks every scalar register, and `m0`, that can hold a per-lane value (compare results, `exec`/`vcc` copies, and selects on a per-lane SCC) as non-uniform, even when the write sits in a later block that loops back. A branch back to the first instruction refuses every proof, because a loop re-enters the entry block. It now explicitly checks for a single SGPR destination and a single VGPR source. `tests/startup_gfx2hlsl_readfirstlane_uniform_check.py` translates short sequences through the stage's dispatch without shader machine code. It checks emitted assignments for the listed operations, supported modifiers, and in-place and cross-register chains, including the unsigned-division reciprocal estimate (`v_cvt_f32_u32`, `v_rcp_f32`, `v_mul_f32` by `0x4f7ffffe`, `v_cvt_u32_f32`) that compiled shaders read back with `v_readfirstlane_b32`. That chain stays refused from a lane-varying source or a lane mask, across an `exec` write or an overwrite, and from a definition in another block. Refusal cases cover varying sources and offsets, overwrites that invalidate a proof, WQM, a restored `exec` copy and other exec writes, lane masks, overlapping and descriptor-path 64-bit moves, branch and operand restrictions (a read at the first branch target, after the first terminator, or in an entry block re-entered by a loop), and constructor-less probes with incomplete tracking state. The negative control empties the allowlist and requires every accepted sequence to refuse. +`tests/startup_readfirstlane_branch_check.py` covers the branch case: a block-local read is accepted, while a join point, an `exec` write, `wrexec`, a per-lane SCC and `m0` taint are refused. + ```powershell -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_readfirstlane_uniform$' -V +ctest --preset dev --no-tests=error -R '^startup_(gfx2hlsl_readfirstlane_uniform|readfirstlane_branch)$' -V ``` ## Desktop audio render sink diff --git a/tests/startup_readfirstlane_branch_check.py b/tests/startup_readfirstlane_branch_check.py index 4af03a8d2f..b1ae9e3d32 100644 --- a/tests/startup_readfirstlane_branch_check.py +++ b/tests/startup_readfirstlane_branch_check.py @@ -42,3 +42,19 @@ def translate(*words): else: raise AssertionError("accepted an unproven readfirstlane: %r" % (words,)) print("readfirstlane with branches: block-local proof accepted; three unproven reads rejected") + + +# The whole-program scan: implicit exec writes, a per-lane SCC and m0 must reach an earlier block through a loop. +def scan(*asm): + stage = gfx.Stage.__new__(gfx.Stage) + stage.ins = [(4 * i, 1, line.split()[0], line) for i, line in enumerate(asm)] + return stage.scan_branch_safety() + + +assert not scan("s_andn2_wrexec_b64 s[2:3], s[4:5]")[0] +assert not scan("s_andn2_wrexec_b32 s2, s4")[0] +tainted = scan("v_cmp_lt_f32 vcc_lo, v1, v2", "s_cmp_eq_u32 vcc_lo, 0", "s_cselect_b32 s2, 1, 0")[1] +assert 2 in tainted, tainted +assert 2 in scan("v_cmp_lt_f32 vcc_lo, v1, v2", "s_mov_b32 m0, vcc_lo", "s_mov_b32 s2, m0")[1] +assert 2 not in scan("s_mov_b32 s3, 5", "s_cmp_eq_u32 s3, 0", "s_cselect_b32 s2, 1, 0")[1] +print("readfirstlane branch scan: wrexec, per-lane SCC and m0 are tracked") diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 91427e0d15..906b23b9bb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -735,32 +735,47 @@ def translate(self): def scan_branch_safety(self): """-> (proof_ok, tainted_s) for a program with branches. VGPR uniformity is proven inside one basic block - only (see translate), and only when no instruction anywhere writes exec, so exec_known holds on every path. - tainted_s holds each scalar register that can carry a per-lane value (a compare or exec-derived mask), - found over the whole program because a loop can bring a later write back to an earlier read.""" - lane_names = ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') + only (see translate), and only when no instruction anywhere writes exec (including the implicit writes of + saveexec, wrexec and v_cmpx), so exec_known holds on every path. tainted_s holds each scalar register + (and 'm0') that can carry a per-lane value: a compare, an exec-derived mask, or a select on a per-lane SCC. + It is found over the whole program because a loop can bring a later write back to an earlier read.""" + lane_names = ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi', 'vccz', 'execz') parsed = [] proof_ok = True for _, _, name, asm in self.ins: _, ops, _ = parse(asm) parsed.append((name, ops)) - if ops and (ops[0] in ('exec', 'exec_lo', 'exec_hi') or 'saveexec' in name or name.startswith('v_cmpx')): + if (ops and ops[0] in ('exec', 'exec_lo', 'exec_hi')) or 'saveexec' in name or 'wrexec' in name or \ + name.startswith('v_cmpx'): proof_ok = False + + def keys(tok): + if tok == 'm0': + return ['m0'] + r = reg_range(tok) + return list(range(r[1], r[2] + 1)) if r and r[0] == 's' else [] + tainted = set() + scc_tainted = False changed = True while changed: changed = False for name, ops in parsed: - dst = reg_range(ops[0]) if ops else None - if not dst or dst[0] != 's' or name.startswith('v_readfirstlane'): + if not ops or name.startswith('v_readfirstlane'): + continue + no_dst = re.match(r's_(cmp|bitcmp|cbranch)', name) is not None + srcs = ops if no_dst else ops[1:] + src_hot = any(tok in lane_names or any(k in tainted for k in keys(tok)) for tok in srcs) + # Any scalar op fed by a per-lane value may leave a per-lane SCC (compare, and/or, shifts, ...). + if name.startswith('s_') and src_hot and not scc_tainted: + scc_tainted = changed = True + dst = [] if no_dst else keys(ops[0]) + if not dst: continue - hot = name.startswith('v_cmp') or any(op in lane_names for op in ops[1:]) - for tok in ops[1:]: - src = reg_range(tok) - if src and src[0] == 's' and any(r in tainted for r in range(src[1], src[2] + 1)): - hot = True - if hot and not all(r in tainted for r in range(dst[1], dst[2] + 1)): - tainted.update(range(dst[1], dst[2] + 1)) + hot = name.startswith('v_cmp') or src_hot or ( + scc_tainted and re.match(r's_(cselect|cmov|addc|subb)', name) is not None) + if hot and not all(k in tainted for k in dst): + tainted.update(dst) changed = True return proof_ok, tainted From c346072cb90fae2009386d3e1561e7c5fa911c6f Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 05:01:12 +0100 Subject: [PATCH 3/4] test: cover entry-block and later-block readfirstlane proofs and both refusal sets --- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 6 --- tests/startup_readfirstlane_branch_check.py | 40 ++++++++----------- 2 files changed, 16 insertions(+), 30 deletions(-) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index 6d308a39c4..b5b7dd2422 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -170,12 +170,6 @@ def run(*instructions, exec_known=True): for label, instructions in REFUSED: got = run(*instructions) check(f'{label} refused', got == EARLIER.get(label, REFUSAL), repr(got)) -# A branch later in the program no longer blocks a read whose source is proven in its own block. -got = run('v_mov_b32_e32 v7, s2', READ, 's_branch label_000C', 's_endpgm') -check('branch after read accepted', got == ['v7 = s2;', 's9 = v7;'], repr(got)) -# A proven chain inside one block stays accepted when a branch follows it. -got = run('v_cvt_f32_u32_e32 v7, s3', 'v_rcp_f32_e32 v7, v7', READ, 's_cbranch_scc0 label_0010', 's_endpgm') -check('chain before a branch accepted', got == ['v7 = U(float(s3));', 'v7 = U(1.0 / F(v7));', 's9 = v7;'], repr(got)) # SCC written through m0 (#1931 review): a compare mask carried into m0 makes SCC varying, so the # select that reads it, and a VGPR copied from that select, stay unproven; EXEC is left unchanged. got = run('v_cmp_lt_f32_e32 vcc_lo, v0, v1', 's_and_b32 m0, vcc_lo, -1', 's_cselect_b32 s2, 1, 0', diff --git a/tests/startup_readfirstlane_branch_check.py b/tests/startup_readfirstlane_branch_check.py index b1ae9e3d32..be9242bc6a 100644 --- a/tests/startup_readfirstlane_branch_check.py +++ b/tests/startup_readfirstlane_branch_check.py @@ -1,4 +1,5 @@ -"""v_readfirstlane_b32 in a program with branches: proven inside one basic block, refused across a join or exec write.""" +"""v_readfirstlane_b32 in a program with branches: the entry block is proven in program order (#2183); a later block is +proven only inside itself, with no exec write anywhere and no loop back to the entry.""" from pathlib import Path import struct import sys @@ -15,6 +16,7 @@ def resource(self, key, kind): S_BRANCH_NEXT = 0xbf820000 # s_branch +0: the next instruction becomes a block start +S_BRANCH_ENTRY = 0xbf820000 | 0xfffb # s_branch back to offset 0 when placed at word 4 (after S_LOAD, CVT, READ) S_EXEC_LO_ZERO = 0xbe800300 | 126 << 16 | 128 # s_mov_b32 exec_lo, 0 S_LOAD = [0xf4000000 | 8 << 18 | 7 << 6 | 4, 125 << 25 | 12] # s_buffer_load_dword s7, s[8:11], 12 CVT_V4 = 0x7e000000 | 4 << 17 | 8 << 9 | 7 # v_cvt_i32_f32 v4, s7 @@ -27,34 +29,24 @@ def translate(*words): return gfx.Stage(TestPipeline(), "ps", struct.pack(f"<{len(words)}I", *words)) -# A branch after the read does not stop the read from being proven in its own block. -body = "\n".join(line for block in translate(CVT_V4, READ_V4, S_BRANCH_NEXT, END).blocks for line in block[1]) -assert "s6 = v4;" in body, body +def body(*words): + return "\n".join(line for block in translate(*words).blocks for line in block[1]) -# A join point between the proof and the read, or an exec write anywhere, leaves the source unproven. + +# Accepted, one per rule: the entry block, and a later block whose proof is made inside that block. +assert "s6 = v4;" in body(CVT_V4, READ_V4, S_BRANCH_NEXT, END), "entry block read refused" +assert "s6 = v4;" in body(S_BRANCH_NEXT, CVT_V4, READ_V4, END), "later block read refused" + +# Refused: a join between proof and read, an exec write before the read (even in a later block), an exec write +# in a later block when the read sits in a later block, and a loop back to the entry block. for words in ([CVT_V4, S_BRANCH_NEXT, READ_V4, END], - [CVT_V4, READ_V4, S_BRANCH_NEXT, S_EXEC_LO_ZERO, END], - [S_EXEC_LO_ZERO, CVT_V4, READ_V4, S_BRANCH_NEXT, END]): + [S_EXEC_LO_ZERO, CVT_V4, READ_V4, S_BRANCH_NEXT, END], + [S_BRANCH_NEXT, CVT_V4, READ_V4, S_EXEC_LO_ZERO, END], + [CVT_V4, READ_V4, S_BRANCH_ENTRY, END]): try: translate(*words) except gfx.Unsupported as error: assert "requires a proven uniform source" in str(error), str(error) else: raise AssertionError("accepted an unproven readfirstlane: %r" % (words,)) -print("readfirstlane with branches: block-local proof accepted; three unproven reads rejected") - - -# The whole-program scan: implicit exec writes, a per-lane SCC and m0 must reach an earlier block through a loop. -def scan(*asm): - stage = gfx.Stage.__new__(gfx.Stage) - stage.ins = [(4 * i, 1, line.split()[0], line) for i, line in enumerate(asm)] - return stage.scan_branch_safety() - - -assert not scan("s_andn2_wrexec_b64 s[2:3], s[4:5]")[0] -assert not scan("s_andn2_wrexec_b32 s2, s4")[0] -tainted = scan("v_cmp_lt_f32 vcc_lo, v1, v2", "s_cmp_eq_u32 vcc_lo, 0", "s_cselect_b32 s2, 1, 0")[1] -assert 2 in tainted, tainted -assert 2 in scan("v_cmp_lt_f32 vcc_lo, v1, v2", "s_mov_b32 m0, vcc_lo", "s_mov_b32 s2, m0")[1] -assert 2 not in scan("s_mov_b32 s3, 5", "s_cmp_eq_u32 s3, 0", "s_cselect_b32 s2, 1, 0")[1] -print("readfirstlane branch scan: wrexec, per-lane SCC and m0 are tracked") +print("readfirstlane with branches: entry and later-block proofs accepted; four unproven reads rejected") From fc30b13b4714ca39fda948dd2bff34a58ff23da9 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Wed, 25 Nov 2026 05:59:53 +0100 Subject: [PATCH 4/4] fix: refuse readfirstlane sources written on different paths into a join A scalar register written in a later block is only a proven source in a block that redefines it; the value recorded from the last visited arm no longer leaks into the join. Adds the two-arm negative control and a same-block redefinition positive. --- docs/experiments.md | 2 +- tests/startup_readfirstlane_branch_check.py | 18 +++++++++++-- tools/startup/gfx2hlsl.py | 30 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index e3a006135c..f4e02f7d9a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12144,7 +12144,7 @@ In straight-line code with a known `exec`, the proof follows `v_cvt_u32_f32`, `v Uniform sources include inline constants and literals, SGPRs holding constants, user data or fixed buffer words, other SGPRs tracked as uniform, and VGPRs with an existing proof. A scalar result is tracked as varying when its expression depends on `vcc`, `exec`, `m0`, a varying scalar register, a VGPR without a proof, or a varying `scc`. Descriptor, pointer, and sampler symbols, and SGPRs holding a lane mask (a compare result, even from uniform operands), are treated as non-uniform sources. A 64-bit move proves its high word only from the source high word as it was before the move, never when the destination overlaps it, and a descriptor-path move carries a high-word symbol only when that symbol does not depend on the register's run-time contents. SCC follows the same dependency tracking, with saveexec and wrexec marking it varying. A scalar write to `m0` that also sets SCC judges SCC from the write's sources, so `s_and_b32 m0, vcc_lo, -1` makes it varying while a write from uniform scalars makes it uniform. Instructions whose SCC result is not modelled (`s_add`, `s_sub`, `s_min` and `s_max`, `s_wqm`, and scalar ops on symbolic descriptor words, which emit nothing) mark SCC varying. Scalar buffer loads track the original offset across every destination word, including when the emitted code saves it in a temporary. -An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read requires known `exec` and no modifiers. In a program with branches, the entry block (before the first branch target and the first terminator) is always exact in program order, because every path reaches it through the same instructions. Later blocks are accepted only when the proof is made inside one basic block: every branch target clears all VGPR proofs, and no instruction anywhere in the program writes `exec` (`exec` moves, `saveexec`, `wrexec` and `v_cmpx` all count). A whole-program scan also marks every scalar register, and `m0`, that can hold a per-lane value (compare results, `exec`/`vcc` copies, and selects on a per-lane SCC) as non-uniform, even when the write sits in a later block that loops back. A branch back to the first instruction refuses every proof, because a loop re-enters the entry block. It now explicitly checks for a single SGPR destination and a single VGPR source. +An overwrite clears the destination's old proof unless the new value is proven uniform. This applies to SDWA forms and all three interpolation forms (`v_interp_p1_f32`, `v_interp_p2_f32`, and `v_interp_mov_f32`). Either WQM form, and restoring `exec` from a saved copy, clears all existing VGPR proofs because they can activate helper lanes. The read requires known `exec` and no modifiers. In a program with branches, the entry block (before the first branch target and the first terminator) is always exact in program order, because every path reaches it through the same instructions. Later blocks are accepted only when the proof is made inside one basic block: every branch target clears all VGPR proofs, and no instruction anywhere in the program writes `exec` (`exec` moves, `saveexec`, `wrexec` and `v_cmpx` all count). A whole-program scan also marks every scalar register, and `m0`, that can hold a per-lane value (compare results, `exec`/`vcc` copies, and selects on a per-lane SCC) as non-uniform, even when the write sits in a later block that loops back. A scalar register written in any later block is trusted in a later block only if that same block redefines it, because a join carries a different value per incoming path (two arms that set `s7` to 1 and 2 leave no single value at the join). A branch back to the first instruction refuses every proof, because a loop re-enters the entry block. It now explicitly checks for a single SGPR destination and a single VGPR source. `tests/startup_gfx2hlsl_readfirstlane_uniform_check.py` translates short sequences through the stage's dispatch without shader machine code. It checks emitted assignments for the listed operations, supported modifiers, and in-place and cross-register chains, including the unsigned-division reciprocal estimate (`v_cvt_f32_u32`, `v_rcp_f32`, `v_mul_f32` by `0x4f7ffffe`, `v_cvt_u32_f32`) that compiled shaders read back with `v_readfirstlane_b32`. That chain stays refused from a lane-varying source or a lane mask, across an `exec` write or an overwrite, and from a definition in another block. Refusal cases cover varying sources and offsets, overwrites that invalidate a proof, WQM, a restored `exec` copy and other exec writes, lane masks, overlapping and descriptor-path 64-bit moves, branch and operand restrictions (a read at the first branch target, after the first terminator, or in an entry block re-entered by a loop), and constructor-less probes with incomplete tracking state. The negative control empties the allowlist and requires every accepted sequence to refuse. diff --git a/tests/startup_readfirstlane_branch_check.py b/tests/startup_readfirstlane_branch_check.py index be9242bc6a..bfebe6b966 100644 --- a/tests/startup_readfirstlane_branch_check.py +++ b/tests/startup_readfirstlane_branch_check.py @@ -22,6 +22,14 @@ def resource(self, key, kind): CVT_V4 = 0x7e000000 | 4 << 17 | 8 << 9 | 7 # v_cvt_i32_f32 v4, s7 READ_V4 = 0x7e000000 | 6 << 17 | 2 << 9 | 256 + 4 # v_readfirstlane_b32 s6, v4 END = 0xbf810000 +CMP_V0 = 0x7c000000 | 0x82 << 17 | 128 # v_cmp_eq_i32 vcc, 0, v0 (per-lane) +BRANCH_VCCZ_2 = 0xbf860000 | 2 # s_cbranch_vccz +2 +BRANCH_OVER_1 = 0xbf820000 | 1 # s_branch +1 +MOV_V4_S7 = 0x7e000000 | 4 << 17 | 1 << 9 | 7 # v_mov_b32 v4, s7 + + +def mov_s7(value): # s_mov_b32 s7, + return 0xbe800300 | 7 << 16 | 128 + value def translate(*words): @@ -37,16 +45,22 @@ def body(*words): assert "s6 = v4;" in body(CVT_V4, READ_V4, S_BRANCH_NEXT, END), "entry block read refused" assert "s6 = v4;" in body(S_BRANCH_NEXT, CVT_V4, READ_V4, END), "later block read refused" +# Accepted: the join block redefines s7 itself, so the proof does not lean on the two arms. +DIAMOND = [CMP_V0, BRANCH_VCCZ_2, mov_s7(1), BRANCH_OVER_1, mov_s7(2)] +assert "s6 = v4;" in body(*DIAMOND, mov_s7(3), MOV_V4_S7, READ_V4, END), "same-block redefinition refused" + # Refused: a join between proof and read, an exec write before the read (even in a later block), an exec write # in a later block when the read sits in a later block, and a loop back to the entry block. for words in ([CVT_V4, S_BRANCH_NEXT, READ_V4, END], [S_EXEC_LO_ZERO, CVT_V4, READ_V4, S_BRANCH_NEXT, END], [S_BRANCH_NEXT, CVT_V4, READ_V4, S_EXEC_LO_ZERO, END], - [CVT_V4, READ_V4, S_BRANCH_ENTRY, END]): + [CVT_V4, READ_V4, S_BRANCH_ENTRY, END], + # a varying branch picks s7 = 1 or s7 = 2; the join reads whichever arm ran last in program order + [*DIAMOND, MOV_V4_S7, READ_V4, END]): try: translate(*words) except gfx.Unsupported as error: assert "requires a proven uniform source" in str(error), str(error) else: raise AssertionError("accepted an unproven readfirstlane: %r" % (words,)) -print("readfirstlane with branches: entry and later-block proofs accepted; four unproven reads rejected") +print("readfirstlane with branches: entry and later-block proofs accepted; five unproven reads rejected") diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 906b23b9bb..fe2963197f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -702,6 +702,8 @@ def translate(self): self.has_branches = bool(targets) self.entry_loop = 0 in targets self.branch_proof, self.tainted_s = self.scan_branch_safety() if targets else (False, set()) + self.later_written = self.scan_later_writes(targets) if targets else set() + self.block_sdef = set() # scalar registers written so far in the current block start = 0 refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ for off, n, name, asm in self.ins: @@ -709,6 +711,7 @@ def translate(self): self.blocks.append((start, self.lines, None)) self.lines, start = [], off self.uniform_v.clear() # a join point: no VGPR proof survives from the code above it + self.block_sdef = set() self.pc = off # Before the first branch target or terminator every path has run exactly the instructions above, so # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a @@ -726,10 +729,12 @@ def translate(self): raise refusals.append((handler_error(name, error, refusals), self.kind)) continue + self.block_sdef.update(self.scalar_dst(name, parse(asm)[1])) if term: self.blocks.append((start, self.lines, term)) self.lines, start = [], off + n self.uniform_v.clear() + self.block_sdef = set() if self.lines: self.blocks.append((start, self.lines, None)) @@ -779,6 +784,28 @@ def keys(tok): changed = True return proof_ok, tainted + @staticmethod + def scalar_dst(name, ops): + """Scalar registers (and 'm0') an instruction may write: its first operand when that is scalar.""" + if not ops or re.match(r's_(cmp|bitcmp|cbranch)', name): + return [] + if ops[0] == 'm0': + return ['m0'] + r = reg_range(ops[0]) + return list(range(r[1], r[2] + 1)) if r and r[0] == 's' else [] + + def scan_later_writes(self, targets): + """Scalar registers written anywhere after the first block boundary. Such a register holds a different + value per incoming path at a join, so the value last seen in program order proves nothing there.""" + ends = ('s_branch', 's_cbranch', 's_endpgm', 's_setpc', 's_swappc') + boundary = min([t for t in targets if t > 0] + [off + n for off, n, name, _ in self.ins + if name.startswith(ends)]) + written = set() + for off, _, name, asm in self.ins: + if off >= boundary: + written.update(self.scalar_dst(name, parse(asm)[1])) + return written + def proof_allowed(self): """Entry-block code is exact in program order (merged entry proof). Later blocks need the branch scan to pass and no branch back to offset 0, so an entry loop keeps refusing.""" @@ -801,6 +828,9 @@ def uniform_source(self, tok): if lo in getattr(self, 'masks', ()) or (getattr(self, 'has_branches', False) and lo in getattr(self, 'tainted_s', ())): return False + if (getattr(self, 'has_branches', False) and getattr(self, 'past_entry', False) and + lo in getattr(self, 'later_written', ()) and lo not in getattr(self, 'block_sdef', ())): + return False # per-path value at a join: redefine it in this block to prove it sym = self.sym.get(lo) if sym: return sym[0] in ('const', 'ud', 'fixed_buffer_word')