diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 58c2f00a5e..53cb798586 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -220,6 +220,7 @@ jobs: tests/startup_compute_request_offline_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ + tests/startup_gfx2hlsl_readfirstlane_recompute_check.py \ tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ tests/startup_flat_param_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 8951f7f7d9..b551eef9f5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,6 +163,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_recompute_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_accum_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 0b2089ecdc..2a0532dffb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2889,6 +2889,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: uniform sources of v_readfirstlane_b32 in straight-line code and entry blocks (#1723). add_test(NAME startup_gfx2hlsl_readfirstlane_uniform COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py") + # v_readfirstlane_b32 past the entry block of a branched program: recomputed definition, joins and EXEC refused. + add_test(NAME startup_gfx2hlsl_readfirstlane_recompute COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py") # Startup shader translator: read-only census of every refusal site (--refusals). add_test(NAME startup_gfx2hlsl_refusals COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_refusals_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 667398f0b8..ff64b7405c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12184,12 +12184,21 @@ 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 takes no modifiers. In straight-line code and in the entry block of a program with branches (before the first branch target and before the first terminator), the proof and the read require known `exec` and the read copies the VGPR; past the entry block the read recomputes the definition instead (below). Every path reaches those instructions through the same instructions, so the program-order tracking is exact there. A branch back to the first instruction ends the entry block at the first instruction, because a loop re-enters it. 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. +Past the entry block of a program with branches, the read does not copy the VGPR. It recomputes the uniform expression that defined the VGPR, for example `s9 = U(F(s3) * 2.0)` after `v_mul_f32 v7, s3, 2.0`. The value read is the first active lane's, and that lane ran the definition when nothing between the definition and the read could change which lanes ran it or what they computed: + +- 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. + +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. + +`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, 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$' -V +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_readfirstlane_(uniform|recompute)$' -V ``` ## Desktop audio render sink diff --git a/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py b/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py new file mode 100644 index 0000000000..9572b8885e --- /dev/null +++ b/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py @@ -0,0 +1,128 @@ +"""Check v_readfirstlane_b32 past the entry block of a program with branches, without shader machine code. + +There the read recomputes the uniform expression that defined its VGPR. It is accepted only when no branch +target (a join or a loop head), EXEC write, overwrite of the VGPR, or write of a scalar the expression reads +lies between the definition and the read, and every scalar source was itself written since the last join. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + def resource(self, key, kind): + return 'r0' + + +def run(*instructions): + """Translate disassembly text through the same dispatch and block split as a real stage.""" + s = G.Stage.__new__(G.Stage) + s.pipe, s.lines, s.attrs = Pipe(), [], {} + s.sym = {4 + i: ('desc', ('table', 0), 0, i) for i in range(4)} + s.used_s, s.used_v, s.masks = set(), set(), set() + s.exec_known = True + s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + try: + s.translate() + except G.Unsupported as error: + return str(error) + return [line for _, lines, _ in s.blocks for line in lines] + + +REFUSAL = 'v_readfirstlane_b32 requires a proven uniform source' +READ = 'v_readfirstlane_b32 s9, v7' +# Offset 0x8 is a join: the branch at 0x0 skips the instruction at 0x4. +JOIN = ('s_cbranch_scc0 label_0008', 's_nop 0') +LOAD = 's_buffer_load_dword s3, s[4:7], 0x10' # a uniform scalar written after the join +DEFINE = 'v_mul_f32_e64 v7, s3, 2.0' +RECOMPUTED = 's9 = U(F(s3) * 2.0);' + + +def read_line(lines): + return lines[-1] if isinstance(lines, list) and lines else lines + + +ACCEPTED = [ + ('definition and read after a join', JOIN + (LOAD, DEFINE, READ)), + # The read does not copy this lane's VGPR, so an EXEC write before the definition does not matter. + ('EXEC narrowed before the definition', JOIN + ('s_and_saveexec_b32 s8, s2', LOAD, DEFINE, READ)), + ('EXEC restored before the definition', JOIN + ('s_mov_b32 exec_lo, s8', LOAD, DEFINE, READ)), + # A conditional branch between them is a fall-through, not a join: one path reaches the read. + ('fall-through between definition and read', JOIN + (LOAD, DEFINE, 's_cbranch_scc1 label_0020', READ, + 's_endpgm')), + ('chain through a second VGPR', JOIN + (LOAD, 'v_mov_b32_e32 v6, s3', 'v_mul_f32_e64 v7, v6, 2.0', READ)), + ('unrelated scalar write in between', JOIN + (LOAD, DEFINE, 's_mov_b32 s2, 0', READ)), +] +EXPECTED = {'chain through a second VGPR': 's9 = U(F((s3)) * 2.0);'} +for label, instructions in ACCEPTED: + got = run(*instructions) + check(f'{label} accepted', read_line(got) == EXPECTED.get(label, RECOMPUTED), repr(got)) + +REFUSED = [ + # The first active lane at the read may not have run the definition. + ('EXEC widened between definition and read', JOIN + (LOAD, 's_and_saveexec_b32 s8, s2', DEFINE, + 's_mov_b32 exec_lo, s8', READ)), + ('EXEC narrowed between definition and read', JOIN + (LOAD, DEFINE, 's_and_saveexec_b32 s8, s2', READ)), + ('compare writes EXEC between definition and read', JOIN + (LOAD, DEFINE, 'v_cmpx_lt_f32_e32 v0, v1', READ)), + ('WQM between definition and read', JOIN + (LOAD, DEFINE, 's_wqm_b32 exec_lo, exec_lo', READ)), + # The recomputed expression would read a newer scalar. + ('scalar input rewritten in between', JOIN + (LOAD, DEFINE, 's_mov_b32 s3, 0', READ)), + ('scalar input reloaded in between', JOIN + (LOAD, DEFINE, 's_buffer_load_dword s3, s[4:7], 0x20', READ)), + ('scalar input pair rewritten in between', JOIN + (LOAD, DEFINE, 's_mov_b64 s[2:3], 0', READ)), + # A loop head between them: a later iteration reaches the read without the definition. + ('loop back edge between definition and read', JOIN + (LOAD, DEFINE, 's_nop 0', READ, + 's_cbranch_scc0 label_0014', 's_endpgm')), + # A join where two definitions reach. + ('join of two definitions', ('s_cbranch_scc0 label_0014', LOAD, DEFINE, 's_branch label_0014', + 'v_mov_b32_e32 v7, 0', READ, 's_endpgm')), + # A scalar written before the last join can hold another path's value. + ('scalar written before the join', (LOAD,) + JOIN + (DEFINE, READ)), + # A second join (here a loop head at the definition) resets the since-join marks again: on the next iteration + # s3 holds a lane mask. + ('scalar written before the second join', JOIN + (LOAD, DEFINE, READ, 's_mov_b32 s3, vcc_lo', + 's_cbranch_scc0 label_000C', 's_endpgm')), + ('lane-varying source', JOIN + ('v_mul_f32_e64 v7, v0, 2.0', READ)), + ('lane mask source', JOIN + ('v_cmp_lt_f32_e64 s3, v0, v1', DEFINE, READ)), + ('VGPR overwritten in between', JOIN + (LOAD, DEFINE, 'v_add_f32_e64 v7, v0, 1.0', READ)), + ('chain across an EXEC write', JOIN + (LOAD, 'v_mov_b32_e32 v6, s3', 's_and_saveexec_b32 s8, s2', + 'v_mul_f32_e64 v7, v6, 2.0', READ)), + ('select on an SCC from before the join', JOIN + ('s_cselect_b32 s3, 1, 0', DEFINE, READ)), +] +for label, instructions in REFUSED: + got = run(*instructions) + check(f'{label} refused', got == REFUSAL, repr(got)) + +# Writes the translator does not route through the first operand. +probe = G.Stage.__new__(G.Stage) +for name, ops, regs in (('v_add_co_u32_e64', ['v1', 's3', 'v2', 'v3'], {3}), + ('v_div_scale_f32', ['v1', 's3', 'v2', 'v3', 'v4'], {3}), + ('s_movreld_b32', ['s0', 's2'], {3, 2}), + ('s_cmp_eq_u32', ['s3', '0'], set())): + probe.uniform_expr, probe.since_join = {7: 'U(F(s3) * 2.0)', 8: 'U(F(s2) * 2.0)'}, {2, 3} + probe.forget_writes(name, ops) + check(f'{name} forgets s{sorted(regs)}', probe.since_join == {2, 3} - regs and + set(probe.uniform_expr) == {7, 8} - {7 if 3 in regs else 0, 8 if 2 in regs else 0}, + repr((probe.since_join, probe.uniform_expr))) +for name, ops, expected in (('s_mov_b64', ['exec', 's[2:3]'], True), ('s_mov_b32', ['exec_hi', 's2'], True), + ('s_load_dwordx2', ['s[126:127]', 's[2:3]', '0x0'], True), + ('s_mov_b32', ['s125', 's2'], False), ('s_mov_b32', ['s126', 's2'], True), + ('s_mov_b64', ['s[124:125]', 's[2:3]'], False), + ('s_or_saveexec_b64', ['s[2:3]', 's[4:5]'], True), + ('s_andn2_wrexec_b32', ['s2', 's4'], True), ('v_cmpx_lt_f32_e32', ['v0', 'v1'], True), + ('s_movreld_b32', ['s0', 's2'], True), ('s_mov_b32', ['s2', 'exec_lo'], False), + ('v_add_co_u32_e64', ['v1', 'exec_lo', 'v2', 'v3'], True), + ('v_mul_f32_e64', ['v1', 'exec_lo', 'v2'], False), ('s_cmp_eq_u32', ['exec_lo', '0'], False)): + check(f'{name} {ops[0]} writes EXEC: {expected}', G.writes_exec(name, ops) == expected) + +print('Readfirstlane recompute checks: %d failed' % len(failures)) +sys.exit(1 if failures else 0) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index b5b7dd2422..674bc35b6d 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -142,7 +142,6 @@ def run(*instructions, exec_known=True): 'v_rcp_f32_e32 v7, v7', READ, 's_endpgm')), # A program with branches proves only before its first branch target or terminator (the entry block). ('read at the first branch target', (MOVE, 's_cbranch_scc0 label_000C', 's_nop 0', READ, 's_endpgm')), - ('read after the first terminator', (MOVE, 's_cbranch_scc0 label_0010', READ, 's_endpgm', 's_endpgm')), ('entry block re-entered by a loop', (MOVE, READ, 's_mov_b32 s2, vcc_lo', 's_cbranch_scc0 label_0000', 's_endpgm')), ('exec write in the entry block', (MOVE, 's_and_saveexec_b32 s8, s2', READ, 's_branch label_0010', @@ -165,6 +164,10 @@ def run(*instructions, exec_known=True): 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 in the entry block accepted', got[:3] == ['v7 = U(float(s3));', 'v7 = U(1.0 / F(v7));', 's9 = v7;'], repr(got)) +# Past the entry block the read recomputes the definition instead of copying the VGPR +# (tests/startup_gfx2hlsl_readfirstlane_recompute_check.py covers that rule). +got = run(MOVE, 's_cbranch_scc0 label_0010', READ, 's_endpgm', 's_endpgm') +check('read after the first terminator recomputed', got[:2] == ['v7 = s2;', 's9 = s2;'], repr(got)) # Since #1755 the float lowering itself refuses an op_sel it does not model, before the read. EARLIER = {'op_sel overwrite': 'modifier op_sel:[0,0]'} for label, instructions in REFUSED: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index bd078c08b3..551affd235 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -437,6 +437,26 @@ def smem_mods(mods): QUAD_SWAPS = {(1, 0, 3, 2): 'QuadReadAcrossX', (2, 3, 0, 1): 'QuadReadAcrossY', (3, 2, 1, 0): 'QuadReadAcrossDiagonal'} +# VALU forms whose second operand is an SGPR destination (VOP3b carry-out or scale flag), not a source. +VOP3B_SDST = re.compile(r'v_(add|sub|subrev)_co(_ci)?_u32|v_div_scale_f(32|64)|v_mad_[iu]64_[iu]32') + + +def destinations(name, ops): + """The operands an instruction writes: the first, and the SGPR destination of the VOP3b forms. Compares write none.""" + if not ops or name.startswith(('s_cmp', 's_bitcmp')): + return [] + return [ops[0]] + ([ops[1]] if len(ops) > 1 and VOP3B_SDST.match(name) else []) + + +def writes_exec(name, ops): + """Conservatively: whether the instruction can write EXEC, explicitly or implicitly.""" + for tok in destinations(name, ops): + r = reg_range(tok) + if tok in ('exec', 'exec_lo', 'exec_hi') or r and r[0] == 's' and r[1] <= 127 and r[2] >= 126: + return True + return 'saveexec' in name or 'wrexec' in name or name.startswith(('v_cmpx', 's_movreld')) + + class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" @@ -617,6 +637,7 @@ def clear_low16(self, n): def set_v(self, n, expr, *, low16_only=False): if hasattr(self, 'uniform_v'): self.uniform_v.discard(n) + self.last_v = (n, expr) if low16_only: if not isinstance(self.low16_only_v, set): self.low16_only_v = set() @@ -684,6 +705,10 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None): self.varying_s.discard(n) else: self.varying_s.add(n) + # Invariant: since_join gains an SGPR only here, when set_s proves it uniform; forget_writes drops any SGPR + # an instruction writes first, so a write through an unmodelled path never keeps a stale mark. + if getattr(self, 'since_join', None) is not None: + (self.since_join.add if uniform else self.since_join.discard)(n) getattr(self, 'masks', set()).discard(n) # unit probes build a Stage without __init__ if sym is not None: self.sym[n] = sym @@ -742,6 +767,8 @@ def translate(self): 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) start = 0 refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ for off, n, name, asm in self.ins: @@ -754,6 +781,10 @@ def translate(self): # 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 try: term = self.one(name, asm) except Unsupported as reason: @@ -793,6 +824,8 @@ def uniform_source(self, tok): return lo in self.uniform_v if lo in getattr(self, 'masks', ()): return False + if getattr(self, 'since_join', None) is not None and lo not in self.since_join: + return False # written before the last join: program-order tracking is not exact there sym = self.sym.get(lo) if sym: return sym[0] in ('const', 'ud', 'fixed_buffer_word') @@ -810,9 +843,14 @@ 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 + if self.tracks_uniformity() and hasattr(self, 'uniform_expr'): + self.forget_writes(name, ops) # 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). 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 + (getattr(self, 'past_entry', False) and hasattr(self, 'uniform_expr') or + not getattr(self, 'past_entry', True) 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]) @@ -822,9 +860,19 @@ def one(self, name, asm): sources = [re.sub(r'^-(?=[^\d.])', '', tok).strip('|') for tok in sources] if sources and all(self.uniform_source(tok) for tok in sources): dst = candidate[1] + self.last_v = None term = self.lower(base, asm, ops, mods) if dst is not None: self.uniform_v.add(dst) + if hasattr(self, 'uniform_expr'): + # Proven sources are scalars, constants and VGPRs; each VGPR needs its own current expression. + expr = self.last_v[1] if self.last_v and self.last_v[0] == dst else None + vs = [int(n) for n in re.findall(r'\bv(\d+)\b', expr or '')] + if expr is None or any(n not in self.uniform_expr for n in vs): + self.uniform_expr.pop(dst, None) + else: + self.uniform_expr[dst] = re.sub(r'\bv(\d+)\b', lambda m: '(%s)' % self.uniform_expr[int(m[1])], + expr) return term def dpp_pair(self, base, asm, ops, mods): @@ -873,6 +921,25 @@ 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): + """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). + The VGPR proofs stay: the entry-block read copies the VGPR, which neither write changes.""" + if writes_exec(name, ops): + self.uniform_expr.clear() + regs = set(range(128)) if name.startswith('s_movreld') else set() # M0 picks the destination + for tok in destinations(name, ops): + r = reg_range(tok) + 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: + 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] + def lower(self, base, asm, ops, mods): if getattr(self, 'fetched', False): # unit probes build a Stage without __init__ # Behind a fetch call the definite-assignment guard relies on exec_known: every exec write must clear it. @@ -1942,11 +2009,20 @@ 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 - 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): + past_entry = getattr(self, 'past_entry', True) + # Past the entry block of a branch-free program is only dead code after s_endpgm: nothing to recompute. + if (mods or not self.tracks_uniformity() 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 or + (src[1] not in getattr(self, 'uniform_expr', {}) or not getattr(self, 'has_branches', False) + if past_entry else not getattr(self, 'exec_known', False))): raise Unsupported('v_readfirstlane_b32 requires a proven uniform source') - self.set_s(reg_range(ops[0])[1], self.u(ops[1])) + if past_entry: + # The first active lane ran the definition: no join, EXEC write or overwrite of the VGPR and no write + # of a scalar it read lies between them. A lane inactive at the definition kept an older VGPR value, + # so the read recomputes the definition from the scalars instead of reading this lane's copy. + self.set_s(dst[1], self.uniform_expr[src[1]]) + else: + self.set_s(dst[1], self.u(ops[1])) def op_v_mov_b32(self, ops, mods): self.set_v(reg_range(ops[0])[1], self.u(ops[1])) @@ -1970,6 +2046,9 @@ def op_v_swap_b32(self, ops, mods): uniform = (dst in self.uniform_v and self.exec_known, src in self.uniform_v and self.exec_known) for reg, flag in zip((src, dst), uniform): (self.uniform_v.add if flag else self.uniform_v.discard)(reg) + exprs = getattr(self, 'uniform_expr', {}) + moved = {src: exprs.pop(dst, None), dst: exprs.pop(src, None)} + exprs.update({reg: e for reg, e in moved.items() if e is not None and reg in self.uniform_v}) self.used_v.update((dst, src)) self.emit(body if self.exec_known else 'if (exec & 1) ' + body)