diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 608ed2dc36..44dc01d7b4 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -89,6 +89,7 @@ jobs: (["tests/startup_image_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), @@ -226,6 +227,7 @@ jobs: tests/startup_gfx2hlsl_loop_constants_check.py \ tests/startup_gfx2hlsl_join_symbols_check.py \ tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ + tests/startup_compute_readfirstlane_check.py \ tests/startup_gfx2hlsl_calculated_target_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 5d54d91f9d..9c4bf2ca6f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2709,6 +2709,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_gather_lz_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") + add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py") add_test(NAME startup_image_sample_c COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_sample_c_check.py") add_test(NAME startup_image_gather_c_lz COMMAND "${INTAKE_PYTHON}" -B @@ -8634,6 +8636,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py" --dispatch "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_compute_image_store_d16_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_readfirstlane_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_readfirstlane_check.py" --dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_readfirstlane_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_image_gather_c_lz_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_gather_c_lz_check.py" --draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) diff --git a/docs/experiments.md b/docs/experiments.md index 2faa1f332f..13b7e6b747 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13699,14 +13699,17 @@ Past the entry block of a program with branches, the read does not copy the VGPR - no branch target lies between them (a join, a loop head or a back edge): a branch target clears every VGPR proof; - no instruction between them writes `exec`, explicitly or implicitly (`saveexec`, `wrexec`, `v_cmpx`, WQM, `s_movreld`); narrowing is refused as well as widening; - the VGPR is not written in between, and no SGPR that the expression reads is written in between (VOP3b carry-out destinations count); -- every SGPR source was proven uniform since the last branch target, so a value from another path cannot reach it; an SCC from before the last branch target is not trusted. +- every SGPR source was either written uniformly since the last branch target, or preserved across branch targets by the CFG proof: a one-path register written before a join and untouched along every non-dominating or back-reaching path, or a uniform loop counter initialized uniformly and updated only with uniform scalar ops under uniform `SCC` branches (validated across a fixed-point pass against non-uniform scalar writes and divergent CFG branch regions using dominators and post-dominators; an SCC from before the last branch target is not trusted). -A lane that was inactive at the definition keeps an older VGPR value; the recomputed expression gives every lane the first active lane's value instead. `exec` need not be known at the definition. A conditional branch between the definition and the read is a fall-through, not a join, and is accepted. The one case where hardware can differ is a read with no active lane: it returns lane 0's VGPR, which the program cannot rely on. `tests/startup_gfx2hlsl_readfirstlane_recompute_check.py` checks the accepted forms and refuses each condition above, including a definition under a narrower `exec` than the read, a rewritten scalar input, a loop back edge and a join where two definitions reach. +A lane that was inactive at the definition keeps an older VGPR value; the recomputed expression gives every lane the first active lane's value instead. `exec` need not be known at the definition. A conditional branch between the definition and the read is a fall-through, not a join, and is accepted. The one case where hardware can differ is a read with no active lane: it returns lane 0's VGPR, which the program cannot rely on. `tests/startup_gfx2hlsl_readfirstlane_recompute_check.py` checks the accepted forms (including one-path scalars and uniform loop counters both inside and after loops) and refuses each condition above, including a definition under a narrower `exec` than the read, a rewritten scalar input, a loop back edge, a divergent `else`-arm write before a join, a non-uniform loop back-edge and a join where two definitions reach. + +[`tests/startup_compute_readfirstlane_check.py`](../tests/startup_compute_readfirstlane_check.py) pairs that unit coverage with a source-built gfx1013 compute fixture (`(4, 1, 1)` local threads x `(2, 1, 1)` groups) containing both a one-path SGPR across a uniform forward branch join and a four-iteration uniform loop counter read via `v_readfirstlane_b32` inside the loop and after exit, machine-code refusal patches (non-uniform `s_cbranch_vccnz` back-edge, divergent `else`/`then` write before a join, lane-mask loop update) and 320-word GPU readback with pinned `dropped-one-path`, `dropped-loop-read` and `dropped-post-loop` negative controls. Verified with zero mismatches and zero D3D12 debug-layer errors or warnings on Windows 11 25H2 (build 26200.9974) across WARP 10.0.26100.9818 and an AMD Radeon RX 7900 XTX (driver 32.0.32029.2010). `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, the median of three that clamps a scalar to `[0, 0.5]`, 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, in a loop whose header is in the entry block, at a backward branch target, in an entry block re-entered by a loop, or after `s_endpgm` in a branch-free program; a read after the first terminator is recomputed), and constructor-less probes with incomplete tracking state. The negative control empties the allowlist and requires every accepted sequence to refuse. ```powershell -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_readfirstlane_(uniform|recompute)$' -V +ctest --preset dev --no-tests=error -R '^(startup_gfx2hlsl_readfirstlane_(uniform|recompute)|startup_compute_readfirstlane(_(warp|hardware))?)$' -V +python -B tests/startup_compute_readfirstlane_check.py --llvm-mc llvm-mc-15 ``` ## Desktop audio render sink diff --git a/tests/startup_compute_readfirstlane_check.py b/tests/startup_compute_readfirstlane_check.py new file mode 100644 index 0000000000..c229be9e2f --- /dev/null +++ b/tests/startup_compute_readfirstlane_check.py @@ -0,0 +1,266 @@ +"""Source-built gfx1013 compute fixture for one-path SGPRs and uniform loop counters with v_readfirstlane_b32 (#2274). + + (no arguments) decode, translate and check controls + negative controls (pure Python) + --llvm-mc / binary also reassemble the fixture and patched instructions with llvm-mc + --dispatch compile translated HLSL with DXC, run GPU readback and negative controls + +The shader builds a one-path SGPR ``s20`` across a uniform forward branch whose taken path does not write ``s20``, +reads it through ``v_readfirstlane_b32`` at the join, runs a four-iteration uniform loop whose counter ``s22`` is +incremented uniformly and read back via ``v_readfirstlane_b32`` both inside the loop and after loop exit, and stores +one combined word per thread across two four-thread groups ``(4, 1, 1) x (2, 1, 1)`` so both arms of the branch +run on the GPU. +""" +import argparse +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) + +import disasm_rdna2 as D # noqa: E402 +from startup_gfx2hlsl_compute_check import ( # noqa: E402 + CASES, G, KEY, MASK, SENTINEL, STRIDE, WORDS, patch, refused, root_blob, +) + +RSRC2 = CASES['D'][2] # USER7 | TGID_X | tidig(0) +LOCAL = (4, 1, 1) +GROUPS = (2, 1, 1) +ONE_PATH_LINE = 's25 = uint(max(F((U(2.0 * F((U(float(s20))))))), 0.0));' +LOOP_LINE = 's24 = uint(max(F((U(2.0 * F((U(float(s22))))))), 0.0));' +POST_LOOP_LINE = 's26 = s22;' + + +def opcode(table, name): + return next(op for op, info in table.items() if info[0] == name) + + +def ssrc(token): + if isinstance(token, str): + if token.startswith('v') and token != 'vcc_lo': + return 256 + int(token[1:]) + return {'2.0': 244, '0': 128, 'vcc_lo': 106}.get(token) or int(token[1:]) + if 0 <= token <= 64: + return 128 + token + raise ValueError(token) + + +def sop1(name, dst, src): + return [0xbe800000 | ssrc(dst) << 16 | opcode(D.SOP1_OPS, name) << 8 | ssrc(src)] + + +def sop2(name, dst, a, b): + return [0x80000000 | opcode(D.SOP2_OPS, name) << 23 | ssrc(dst) << 16 | ssrc(b) << 8 | ssrc(a)] + + +def sopc(name, a, b): + return [0xbf000000 | opcode(D.SOPC_OPS, name) << 16 | ssrc(b) << 8 | ssrc(a)] + + +def sopp(name, imm=0): + return [0xbf800000 | opcode(D.SOPP_OPS, name) << 16 | (imm & 0xffff)] + + +def vop1(name, dst, src): + dv = int(dst[1:]) if dst.startswith('v') else ssrc(dst) + return [0x7e000000 | dv << 17 | opcode(D.VOP1_OPS, name) << 9 | ssrc(src)] + + +def vop2(name, dst, a, b): + return [opcode(D.VOP2_OPS, name) << 25 | int(dst[1:]) << 17 | int(b[1:]) << 9 | ssrc(a)] + + +def build_words(): + # s_mov_b32 s10, s6; s_mov_b32 s11, 0; s_load_dwordx8 s[12:19], s[10:11], 0x0; s_waitcnt lgkmcnt(0) + ws = list(struct.unpack('<5I', bytes.fromhex('06038abe80038bbe05030cf4000000fa7fc08cbf'))) + ws += sop2('s_and_b32', 's20', 's5', 63) + sop2('s_add_u32', 's20', 's20', 's7') + ws += sop1('s_mov_b32', 's21', 5) + sopc('s_cmp_eq_u32', 's7', 0) + ws += sopp('s_cbranch_scc0', 1) + sop1('s_mov_b32', 's21', 9) + ws += (vop1('v_cvt_f32_u32_e32', 'v7', 's20') + vop2('v_mul_f32_e32', 'v7', '2.0', 'v7') + + vop1('v_cvt_u32_f32_e32', 'v7', 'v7') + vop1('v_readfirstlane_b32', 's25', 'v7')) + ws += sop1('s_mov_b32', 's22', 0) + sop1('s_mov_b32', 's23', 0) + loop_idx = len(ws) + ws += (vop1('v_cvt_f32_u32_e32', 'v8', 's22') + vop2('v_mul_f32_e32', 'v8', '2.0', 'v8') + + vop1('v_cvt_u32_f32_e32', 'v8', 'v8') + vop1('v_readfirstlane_b32', 's24', 'v8')) + ws += sop2('s_add_u32', 's23', 's23', 's24') + sop2('s_add_u32', 's22', 's22', 1) + ws += sopc('s_cmp_lt_u32', 's22', 4) + ws += sopp('s_cbranch_scc1', loop_idx - (len(ws) + 1)) + ws += vop1('v_mov_b32_e32', 'v9', 's22') + vop1('v_readfirstlane_b32', 's26', 'v9') + ws += sop2('s_lshl_b32', 's27', 's7', 2) + vop2('v_add_nc_u32_e32', 'v4', 's27', 'v0') + ws += sop2('s_add_u32', 's25', 's25', 's21') + sop2('s_add_u32', 's25', 's25', 's23') + ws += sop2('s_add_u32', 's25', 's25', 's26') + ws += vop2('v_add_nc_u32_e32', 'v5', 's25', 'v4') + vop2('v_lshlrev_b32_e32', 'v4', 2, 'v4') + # buffer_store_dword v5, v4, s[16:19], 0 offen; s_endpgm + ws += list(struct.unpack('<2I', bytes.fromhex('001070e004050480'))) + sopp('s_endpgm') + return struct.pack('<%dI' % len(ws), *ws) + + +PROGRAM_WORDS = build_words() +DECODED = G.decode(PROGRAM_WORDS) + + +def pack_hex(*ws): + return struct.pack('<%dI' % len(ws), *ws).hex() + + +PATCHES = ( + ('non-uniform loop back-edge', + [(pack_hex(*sopp('s_cbranch_scc1', -8)), pack_hex(*sopp('s_cbranch_vccnz', -8)))], + 'v_readfirstlane_b32 requires a proven uniform source'), + ('divergent then arm writes one-path scalar', + [(pack_hex(*sopp('s_cbranch_scc0', 1)), pack_hex(*sopp('s_cbranch_vccz', 1))), + (pack_hex(*sop1('s_mov_b32', 's21', 9)), pack_hex(*sop1('s_mov_b32', 's20', 9)))], + 'v_readfirstlane_b32 requires a proven uniform source'), + ('loop counter updated from lane mask', + [(pack_hex(*sop2('s_add_u32', 's22', 's22', 1)), pack_hex(*sop1('s_mov_b32', 's22', 'vcc_lo')))], + 'v_readfirstlane_b32 requires a proven uniform source'), +) + + +def translate(code=None): + return G.ComputePipeline(code or PROGRAM_WORDS, root_blob(), RSRC2, LOCAL) + + +def expected(): + out = [SENTINEL] * WORDS + base_stride = STRIDE & 63 + for gx in range(GROUPS[0]): + s20 = base_stride + gx + s25 = s20 * 2 + s21 = 9 if gx == 0 else 5 + s23 = 0 + 2 + 4 + 6 # sum over uniform loop iterations i=0..3 + s26 = 4 + combined = (s25 + s21 + s23 + s26) & MASK + for tx in range(LOCAL[0]): + idx = gx * LOCAL[0] + tx + out[idx] = (combined + idx) & MASK + return out + + +def llvm_lines(): + lines = [] + for off, _n, _name, asm in DECODED: + m = re.fullmatch(r'(s_branch|s_cbranch_\w+) label_0x([0-9a-f]+)', asm) + if m: + lines.append('%s %d' % (m.group(1), (int(m.group(2), 16) - off - 4) // 4)) + else: + lines.append(asm.replace('vcc_lo', 'vcc')) + lines += [ + 's_cbranch_vccnz -8', + 's_cbranch_vccz 1', + 's_mov_b32 s20, 9', + 's_mov_b32 s22, vcc_lo', + ] + return lines + + +def check_binary(llvm_mc): + lines = llvm_lines() + proc = subprocess.run( + [llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', '-show-encoding'], + input='\n'.join(lines) + '\n', capture_output=True, text=True, check=True) + built = [bytes(int(b, 16) for b in m.group(1).split(',')) + for m in re.finditer(r'encoding: \[([^\]]*)\]', proc.stdout)] + assert len(built) == len(lines), (len(built), len(lines), proc.stderr) + assembled = b''.join(built[:len(DECODED)]) + assert assembled == PROGRAM_WORDS, (assembled.hex(), PROGRAM_WORDS.hex()) + extra = [ + (built[-4], bytes.fromhex(pack_hex(*sopp('s_cbranch_vccnz', -8)))), + (built[-3], bytes.fromhex(pack_hex(*sopp('s_cbranch_vccz', 1)))), + (built[-2], bytes.fromhex(pack_hex(*sop1('s_mov_b32', 's20', 9)))), + (built[-1], bytes.fromhex(pack_hex(*sop1('s_mov_b32', 's22', 'vcc_lo')))), + ] + for got, want in extra: + assert got == want, (got.hex(), want.hex()) + print('%d fixture and negative-control instructions match %s' % (len(lines), llvm_mc)) + + +def controls(llvm_mc=None): + pipe = translate() + hlsl = pipe.hlsl_cs() + for snippet in (ONE_PATH_LINE, LOOP_LINE, POST_LOOP_LINE, 'u0.Store(a, v5);'): + assert hlsl.count(snippet) == 1, (snippet, hlsl) + assert 'uav 0 table 1 16' in pipe.manifest().splitlines(), pipe.manifest() + + for label, replacements, reason in PATCHES: + code = PROGRAM_WORDS + for old_hex, new_hex in replacements: + code = patch(code, old_hex, new_hex) + refused(reason, lambda code=code: translate(code)) + + if llvm_mc: + check_binary(llvm_mc) + print('Compute readfirstlane one-path, loop-counter and refusal checks passed') + + +CONTROLS = { + 'dropped-one-path': (ONE_PATH_LINE, 's25 = 0u;', 'word=0 expected=0000008b actual=00000019'), + 'dropped-loop-read': (LOOP_LINE, 's24 = 0u;', 'word=0 expected=0000008b actual=0000007f'), + 'dropped-post-loop': (POST_LOOP_LINE, 's26 = 0u;', 'word=0 expected=0000008b actual=00000087'), +} + + +def dispatch(dxc, runner, adapter): + controls() + hlsl = translate().hlsl_cs() + out_dir = HERE.parent / 'out' + out_dir.mkdir(exist_ok=True) + case_bytes = (struct.pack('= t: regs |= writes[b] # a loop body or a later block that comes back # Writes in dominating blocks hold on every path only if their textual order is their execution order. - if any(not (a in dom[c]) for a, c in zip(above_dominators, above_dominators[1:])): + non_chain = any(not (a in dom[c]) for a, c in zip(above_dominators, above_dominators[1:])) + if non_chain: regs |= set().union(*(writes[b] for b in above_dominators)) joined[target] = regs - return joined + if with_cfg: + above_set = dom[t] - {t} + split_blks, stodo = set(), [p for p in pred[t] if p < t and p not in above_set] + while stodo: + b = stodo.pop() + if b not in split_blks: + split_blks.add(b) + stodo += [p for p in pred[b] if p < t and p not in above_set] + fwd = set().union(*(writes[b] for b in split_blks)) if split_blks else set() + if non_chain: + fwd |= set().union(*(writes[b] for b in above_dominators)) + forward_splits[target] = fwd + if not with_cfg: + return joined + pdom = [set(range(len(bounds))) if succ[b] else {b} for b in range(len(bounds))] + changed = True + while changed: + changed = False + for b in range(len(bounds) - 1, -1, -1): + if not succ[b]: + continue + new = {b} | set.intersection(*(pdom[s] for s in succ[b])) + if new != pdom[b]: + pdom[b], changed = new, True + div_targets = {} + for b, (lo, hi) in enumerate(bounds): + off, _n, name, asm = ins[hi - 1] + if not name.startswith('s_cbranch'): + continue + tgt = target_of(off, name, asm) + if tgt is None: + continue + if tgt <= off: + t_blk = block_of[index[tgt]] if tgt in index else b + loop_blks = range(min(t_blk, b), b + 1) + regs = set().union(*(writes[w] for w in loop_blks)) + affected = {off_of[w] for w in loop_blks} & all_targets + else: + stop = pdom[b] - {b} + ipd = max(stop, key=lambda x: len(pdom[x])) if stop else None + div, dtodo = set(), list(succ[b]) + while dtodo: + w = dtodo.pop() + if w == ipd or w in div: + continue + div.add(w) + dtodo += succ[w] + 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) + return joined, forward_splits, div_targets def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ @@ -1239,127 +1315,201 @@ def translate(self): if name == 's_cbranch_execz' and self.kind == 'cs': skipped.append((off, target)) join_writes = self.join_writes(branches) - scc_effects = {} - self.blocks = [] # (offset, [lines], terminator) - self.uniform_v = set() - self.varying_s = set() - self.scc_uniform = True - self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load - self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries - self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer - self.has_branches = bool(targets) - self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it - self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) - joined = self.joined_registers() - forced = getattr(self, 'force_joined', {}) # unit probes build a Stage without __init__ - entry_ud = {reg: sym for reg, sym in self.sym.items() if sym[0] == 'ud'} # never assigned at run time - materialize = {} # entry register -> its root-constant source, assigned at entry because a join reads it - incoming = {} # forward target -> (the joined registers' symbols, those written) at each branch to it - kept = {} # target -> joined register -> the symbol every path known so far brings (kept there) - self.back_force = {} # target -> register -> 'run' | 'refuse': a back edge disagrees with what was kept - # SGPRs written on the path being translated. A path that never wrote a register brings no value to a join - # (reading it there would read whatever the hardware left), so it does not constrain the meet. Every SGPR up - # to the last one the entry state names counts as written (hardware-initialized), and for graphics stages all - # user SGPRs s0-s15 too, so an entry value is never taken for an unwritten register. - # (unit probes build a Stage without __init__, so kind and used_s may be missing) - entry = [r for r in set(self.sym) | set(getattr(self, 'used_s', ())) if isinstance(r, int)] - written = set(range(max(entry + [-1 if getattr(self, 'kind', None) == 'cs' else 15]) + 1)) | {'m0'} + joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) + init_sym = dict(self.sym) + init_exec_known = getattr(self, 'exec_known', True) + init_wqm_exec = getattr(self, 'wqm_exec', False) + init_masks = set(getattr(self, 'masks', ())) + init_attrs = dict(getattr(self, 'attrs', {})) + init_used_s = set(getattr(self, 'used_s', ())) + init_used_v = set(getattr(self, 'used_v', ())) + init_entry_uniform = set(getattr(self, 'entry_uniform_s', ())) | { + k for k, v in init_sym.items() + if isinstance(k, int) and v and ( + (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') + ) + } + entry_ud = {reg: sym for reg, sym in init_sym.items() if sym[0] == 'ud'} + forced = getattr(self, 'force_joined', {}) + force_unproven = set() + force_at = {} + first_refusal = len(refusals) if refusals is not None else 0 every_sgpr = set(range(106)) | {'m0'} - start = 0 - falls = True # the instruction above falls through (the entry path reaches the first one) - for off, n, name, asm in self.ins: - if off in targets and off != start: - self.pinned_low16_v.update(self.low16_only_v) - self.blocks.append((start, self.lines, None)) - self.lines, start = [], off - if off in targets: - # A branch target joins paths, and the symbol tracked in program order holds on all of them only for - # a register outside the joined set. A joined register keeps its symbol when every path into the - # target brings an equal one that names one value (back edges are checked once the loop body is - # translated, see back_force). Otherwise it is read at run time from here on, which every constant - # allows (each is assigned when set; entry root constants are assigned at entry); one that holds, on - # some path, a symbol with no run-time value (a descriptor word, a pointer, an unplaced entry - # register) gets a symbol that refuses any read before the next write. - kept[off] = {} - here = joined.get(off, set()) - arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ - incoming.get(off, []) - written = (written - here) | set().union(*(w for _, w in arriving)) - for reg in here: - paths = [s[reg] for s, w in arriving if reg in w] # paths that never wrote it bring nothing - force = forced.get(off, {}).get(reg) - if any(reg not in w for _, w in arriving) and any(p and not run_time_symbol(p) for p in paths): - # An edge with no definition brings the hardware's leftover, not this symbol: unproven. - self.sym[reg] = ('joined at a branch target',) - continue - if force is None and paths and names_one_value(paths[0]) and all(p == paths[0] for p in paths): - self.sym[reg] = kept[off][reg] = paths[0] - continue - if force == 'refuse' or any(p and not run_time_symbol(p) for p in paths): - self.sym[reg] = ('joined at a branch target',) - continue - if reg in entry_ud: - materialize[reg] = 'ud%d' % entry_ud[reg][1] - self.sym.pop(reg, None) - if reg != 'm0': - self.used_s.add(reg) - if name.startswith('s_cbranch') or name == 's_branch' or (name == 's_setpc_b64' and self.calculated_pc.get(off) is not None): - target = self.calculated_pc[off] if name == 's_setpc_b64' else int(parse(asm)[1][0].split('_')[1], 16) - there = joined.get(target, set()) - if target > off: - incoming.setdefault(target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) - else: - for reg in there & written: - back, sym = self.sym.get(reg), kept.get(target, {}).get(reg) - if back and not run_time_symbol(back) and back != sym: - self.back_force.setdefault(target, {})[reg] = 'refuse' - elif sym is not None and back != sym: - self.back_force.setdefault(target, {}).setdefault( - reg, 'run' if run_time_symbol(sym) else 'refuse') - 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 - self.pc = off - self.scc_effect = None - # 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 - # branch-free program is past it too (dead code). - self.past_entry = bool(self.blocks) or 0 in targets - if off in targets: - # A join: another path can reach here with other VGPR, SGPR and SCC values, so no proof survives. - self.uniform_v.clear() - self.since_join, self.scc_uniform = set(), False - # 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, ()): - if (self.sym.get(reg) or ('',))[0] == 'const': - del self.sym[reg] - try: - if any(branch < off < target or target <= off < branch for branch, target in skipped) and ( - name.startswith(('s_', 'v_readlane', 'v_readfirstlane', 'v_writelane')) - and not name.startswith(SKIPPABLE_SCALAR) - and not (name == 's_setpc_b64' and off in self.calculated_pc)): - # The wave runs this block when any lane is active, so its scalar state changes for every - # lane; the one-lane model would skip it for an inactive lane. - raise Unsupported('%s inside a block s_cbranch_execz skips per lane' % name) - term = self.one(name, asm) - except Unsupported as reason: - if refusals is None: - raise - refusals.append((str(reason), self.kind)) - continue - except Exception as error: - if refusals is None: - raise - refusals.append((handler_error(name, error, refusals), self.kind)) + init_entry = [r for r in set(init_sym) | init_used_s if isinstance(r, int)] + init_written = set(range(max(init_entry + [-1 if getattr(self, 'kind', None) == 'cs' else 15]) + 1)) | {'m0'} + + for _ in range(max(4, len(self.ins) + 2)): + scc_effects = {} + self.lines = [] + self.blocks = [] # (offset, [lines], terminator) + self.sym = dict(init_sym) + self.exec_known = init_exec_known + self.wqm_exec = init_wqm_exec + self.masks = set(init_masks) + self.attrs = dict(init_attrs) + self.used_s, self.used_v = set(init_used_s), set(init_used_v) + self.exports = {} + self.write_masks = {} + self.compr_params = set() + self.plain_params = {} + self.f16_plain = {} + self.uses_pos = False + self.fetched = False + self.uniform_v = set() + self.varying_s = set() + self.scc_uniform = True + self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load + self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries + self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer + self.has_branches = bool(targets) + self.uniform_expr = {} # proven VGPR -> uniform HLSL expression over scalars that defined it + self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) + self.defined_uniform_s = set(init_entry_uniform) + self.bad_sgprs = set() + bad_at_target = {} + tentative_kept = set() + materialize = {} + incoming = {} + kept = {} + self.back_force = {} + written = set(init_written) + falls = True + start = 0 + raised_unsupported = None + + for off, n, name, asm in self.ins: + if off in targets and off != start: + self.pinned_low16_v.update(self.low16_only_v) + self.blocks.append((start, self.lines, None)) + self.lines, start = [], off + self.pc = off + self.scc_effect = None + # 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 + # branch-free program is past it too (dead code). + self.past_entry = bool(self.blocks) or 0 in targets + if off in targets: + pre_uniform = { + r for r in (self.defined_uniform_s if self.since_join is None else self.since_join) + if r not in self.varying_s and r not in self.masks + } + kept[off] = {} + here = joined.get(off, set()) + arriving = ([({reg: self.sym.get(reg) for reg in here}, written & here)] if falls else []) + \ + incoming.get(off, []) + written = (written - here) | set().union(*(w for _, w in arriving)) + for reg in here: + paths = [s[reg] for s, w in arriving if reg in w] + force = forced.get(off, {}).get(reg) + if any(reg not in w for _, w in arriving) and any(p and not run_time_symbol(p) for p in paths): + self.sym[reg] = ('joined at a branch target',) + continue + if force is None and paths and names_one_value(paths[0]) and all(p == paths[0] for p in paths): + self.sym[reg] = kept[off][reg] = paths[0] + continue + if force == 'refuse' or any(p and not run_time_symbol(p) for p in paths): + self.sym[reg] = ('joined at a branch target',) + continue + if reg in entry_ud: + materialize[reg] = 'ud%d' % entry_ud[reg][1] + self.sym.pop(reg, None) + if reg != 'm0': + self.used_s.add(reg) + clobber = here if off in joined else every_sgpr + fwd_clobber = forward_splits.get(off, clobber) + blocked = force_unproven | force_at.get(off, set()) + kept_u = { + r for r in pre_uniform + if r not in clobber or (r not in fwd_clobber and r not in blocked) + } + tentative_kept.update((kept_u & clobber) - blocked) + self.uniform_v.clear() + self.since_join, self.scc_uniform = kept_u, False + # 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] + self.defined_uniform_s = set(kept_u) | { + k for k, v in self.sym.items() + if isinstance(k, int) and v and ( + (v[0] == 'const' and len(v) == 2) or v[0] in ('ud', 'fixed_buffer_word') + ) + } + if name.startswith('s_cbranch') or name == 's_branch' or ( + name == 's_setpc_b64' and self.calculated_pc.get(off) is not None): + b_target = self.calculated_pc[off] if name == 's_setpc_b64' else int(parse(asm)[1][0].split('_')[1], 16) + there = joined.get(b_target, set()) + if b_target > off: + incoming.setdefault(b_target, []).append(({reg: self.sym.get(reg) for reg in there}, written & there)) + else: + for reg in there & written: + back, sym = self.sym.get(reg), kept.get(b_target, {}).get(reg) + if back and not run_time_symbol(back) and back != sym: + self.back_force.setdefault(b_target, {})[reg] = 'refuse' + elif sym is not None and back != sym: + self.back_force.setdefault(b_target, {}).setdefault( + reg, 'run' if run_time_symbol(sym) else 'refuse') + 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 + try: + if any(branch < off < target or target <= off < branch for branch, target in skipped) and ( + name.startswith(('s_', 'v_readlane', 'v_readfirstlane', 'v_writelane')) + and not name.startswith(SKIPPABLE_SCALAR) + and not (name == 's_setpc_b64' and off in self.calculated_pc)): + # The wave runs this block when any lane is active, so its scalar state changes for every + # lane; the one-lane model would skip it for an inactive lane. + raise Unsupported('%s inside a block s_cbranch_execz skips per lane' % name) + base = re.sub(r'_e(32|64)$', '', name) + if base.startswith('s_cbranch_'): + cond = base[10:] + cond_uniform = cond in ('scc0', 'scc1') and self.scc_uniform + if not cond_uniform: + b_target = int(parse(asm)[1][0].split('_')[1], 16) + regs, affected = div_targets.get(off, (set(), set())) + regs = {r for r in regs if isinstance(r, int)} + if b_target <= off: + regs.update(r for r in joined.get(b_target, ()) if isinstance(r, int)) + for tgt_off in affected: + bad_at_target.setdefault(tgt_off, set()).update(regs) + term = self.one(name, asm) + except Unsupported as reason: + if refusals is None: + raised_unsupported = reason + break + refusals.append((str(reason), self.kind)) + continue + except Exception as error: + if refusals is None: + raise + refusals.append((handler_error(name, error, refusals), self.kind)) + continue + if self.scc_effect: + scc_effects[off] = self.scc_effect + if term: + self.pinned_low16_v.update(self.low16_only_v) + self.blocks.append((start, self.lines, term)) + self.lines, start = [], off + n + + new_bad = self.bad_sgprs - force_unproven + new_at = {k: v - force_at.get(k, set()) for k, v in bad_at_target.items() if v - force_at.get(k, set())} + if (new_bad or new_at) and tentative_kept: + force_unproven.update(new_bad) + for k, v in new_at.items(): + force_at.setdefault(k, set()).update(v) + if refusals is not None: + del refusals[first_refusal:] continue - if self.scc_effect: - scc_effects[off] = self.scc_effect - if term: - self.pinned_low16_v.update(self.low16_only_v) - self.blocks.append((start, self.lines, term)) - self.lines, start = [], off + n + if raised_unsupported is not None: + raise raised_unsupported + break + else: + reason = 'v_readfirstlane_b32 uniformity proof exceeded pass limit' + if refusals is None: + raise Unsupported(reason) + refusals.append((reason, self.kind)) if self.lines: self.blocks.append((start, self.lines, None)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) @@ -1449,8 +1599,11 @@ def one(self, name, asm): base = re.sub(r'_e(32|64)$', '', name) # Compute the proof before lowering, since a destination can also be a source. dst = None + self._uniform_written = set() if self.tracks_uniformity() and hasattr(self, 'uniform_expr'): - self.forget_writes(name, ops) + wrote_s = {r for r in self.forget_writes(name, ops, drop_since=False) if isinstance(r, int)} + else: + wrote_s = set() # Unit probes build a Stage without __init__: without the tracking state, prove nothing. # Past the entry block of a program with branches the read recomputes the defining expression, so the # proof no longer needs a known exec (see op_v_readfirstlane_b32). @@ -1468,6 +1621,18 @@ def one(self, name, asm): dst = candidate[1] self.last_v = None term = self.lower(base, asm, ops, mods) + uniform_written = self._uniform_written + if self.tracks_uniformity() and getattr(self, 'since_join', None) is not None and wrote_s: + self.since_join -= (wrote_s - uniform_written) + if wrote_s and self.bad_sgprs is not None: + for r in wrote_s - uniform_written: + sym = self.sym.get(r) + if (r in self.varying_s or r in getattr(self, 'masks', ()) or + (sym is not None and sym[0] not in ('const', 'ud', 'fixed_buffer_word')) or + (self.defined_uniform_s is not None and r not in self.defined_uniform_s)): + if self.defined_uniform_s is not None: + self.defined_uniform_s.discard(r) + self.bad_sgprs.add(r) if dst is not None: self.uniform_v.add(dst) if hasattr(self, 'uniform_expr'): @@ -1527,9 +1692,9 @@ def dpp_pair(self, base, asm, ops, mods): ops = [ops[0], '%sv%d%s' % (src.group(1), DPP_SCRATCH, src.group(3))] + ops[2:] return self.lower(base, asm, ops, []) - def forget_writes(self, name, ops): + def forget_writes(self, name, ops, drop_since=True): """Before an instruction runs: an EXEC write ends every recomputable expression, and an SGPR write ends the - expressions that read it and that SGPR's since-join mark (set_s marks it again when it proves the new value). + expressions that read it and (when drop_since is set) that SGPR's since-join mark (set_s marks it again when it proves the new value). The VGPR proofs stay: the entry-block read copies the VGPR, which neither write changes.""" if writes_exec(name, ops): self.uniform_expr.clear() @@ -1539,12 +1704,13 @@ def forget_writes(self, name, ops): if r and r[0] == 's': regs.update(range(r[1], r[2] + 1)) if not regs: - return - if self.since_join is not None: + return set() + if drop_since and self.since_join is not None: self.since_join -= regs for v in [v for v, expr in self.uniform_expr.items() if regs & {int(n) for n in re.findall(r'\bs(\d+)\b', expr)}]: del self.uniform_expr[v] + return regs def lower(self, base, asm, ops, mods): pc = getattr(self, 'pc', None)