From b2a1957d42110d2dfda983bc98ef0d4c6cd861cb Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 05:29:45 +0100 Subject: [PATCH 01/10] startup: keep sample_b and get_lod past a divergent EXEC with a per-quad vote --- CMakeLists.txt | 18 + docs/experiments.md | 15 + tests/startup_gfx2hlsl_image_get_lod_check.py | 7 +- tests/startup_image_get_lod_flow_check.py | 247 ++++++++++++ tests/startup_image_sample_b_check.py | 8 +- tests/startup_image_sample_b_flow_check.py | 350 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 55 ++- 7 files changed, 692 insertions(+), 8 deletions(-) create mode 100644 tests/startup_image_get_lod_flow_check.py create mode 100644 tests/startup_image_sample_b_flow_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 9d345680f..ff0c962d2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3815,6 +3815,24 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_sample_b_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl image_sample_b past a divergent EXEC: EXEC branches decided per quad, drawn against a CPU reference. + add_test(NAME startup_image_sample_b_flow_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_b_flow_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_b_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_b_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_b_flow_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() + # gfx2hlsl image_get_lod past a divergent EXEC: EXEC branches decided per quad, drawn against a CPU reference. + add_test(NAME startup_image_get_lod_flow_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_get_lod_flow_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_get_lod_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_get_lod_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_get_lod_flow_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # Constant-sampler LOD limits of image_sample, _l and _lz (#2177): each form drawn alone against a plain-smp control. foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_image_sample_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 7c6a5415d..c486db55f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16920,3 +16920,18 @@ or `scalar_wide_op()`). Reads where incoming SCC is unverified are refused: at s control-flow joins/branch targets, after descriptor-elided SCC writes, and after unmodeled SCC writers in `SCC_UNMODELLED` such as `s_add_u32` (after `s_add_u32` finishes reading its own sources). Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_src_scc$' -V`. + + +## Startup translator: derivative image ops under a divergent EXEC + +`image_sample_b` and `image_get_lod` take implicit derivatives of the four lanes of a pixel quad. A pixel program +with such an op and no backward branch now decides its `s_cbranch_execz` / `s_cbranch_execnz` per quad +(`x2w_quad_any(exec)`: some lane of the 2x2 quad has its EXEC bit, from fine derivatives of the 0/1 bit), as the guest's +wave skips a block only when no lane is active and runs it with the other lanes masked. A voted branch parts no quad, +so it keeps `uniform_cf` (#2659); the vote reads the quad, so it is taken only while the control flow is quad-uniform +and no lane-exec break (`s_wqm` of a narrowed EXEC, a discard under an unknown EXEC) came first. With that, a derivative +op may sit under `v_cmpx`, inside an `execz` block, past an `execnz` kill branch, or after an EXEC restore. Still +refused: any branch that can differ between lanes and is not an EXEC branch (VCC, SCC not proven uniform), loops with +such a branch, and an `s_wqm` of a narrowed EXEC before the op. +`tests/startup_image_sample_b_flow_check.py` and `tests/startup_image_get_lod_flow_check.py` draw each shape against a +CPU reference (DXC ps_6_0 and FXC ps_5_1) with wrong-value controls. diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index 70475ee59..89ead9b57 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -12,7 +12,7 @@ (image_get_lod; the decoder reads it back with a 2-register address), sampler word 2 loaded from a literal (mip filter point), and for the second form dmask 0x3. Checks: dmask 0x1, 0x2 and 0x3 lower to the two calls on the sampler, which carries its LOD limits. A uniform join -before the read is accepted. Controls (refused): dmask 0x4, a 2D array, divergent EXEC, s_cbranch_vccz/execz before +before the read is accepted. Controls (refused): dmask 0x4, a 2D array, s_cbranch_vccz/execz before the read, a sampler LOD bias, a sampler with mipmapping disabled, and the stage without op_image_get_lod (negative control: refused as on main). draw [fxc]: also compile the dmask 0x3 stage with dxc ps_6_0 (and fxc ps_5_1). @@ -98,7 +98,8 @@ def controls(): assert call in text and 'v4 = U(t.x);' in text, text refused(stage(dmask=4), 'image_get_lod form') refused(stage(dim=5), 'image_get_lod form') # SQ_RSRC_IMG_2D_ARRAY - refused(stage(divergent=True), 'image_get_lod needs implicit derivatives') + _, text = ps(stage(divergent=True)) # a cleared EXEC is an exact per-lane write: the quad program keeps the proof + assert call in text, text for op in (7, 9): # vccnz, execnz back edge after the read refused(stage(back_op=op), 'image_get_lod needs implicit derivatives') for op in (6, 7, 8, 9): # vccz, vccnz, execz, execnz @@ -112,7 +113,7 @@ def controls(): finally: G.Stage.op_image_get_lod = saved print('image_get_lod: CalculateLevelOfDetail / Unclamped for dmask 0x1, 0x2 and 0x3; uniform join/branch before ' - 'the read accepted; dmask 0x4, a 2D array, divergent EXEC, vcc/exec branches, a sampler bias and a ' + 'the read accepted, also after a cleared EXEC; dmask 0x4, a 2D array, vcc/exec branches, a sampler bias and a ' 'sampler without mipmapping refused; refused without the handler') return pipe diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py new file mode 100644 index 000000000..b7e583540 --- /dev/null +++ b/tests/startup_image_get_lod_flow_check.py @@ -0,0 +1,247 @@ +"""image_get_lod past a branch or an EXEC change in tools/startup/gfx2hlsl.py (implicit derivatives of the quad). + + (no arguments) translation controls and refusals, pure Python + binary reassemble every fixture source and compare it with the recorded words + draw [fxc] + translate, compile (DXC ps_6_0, and FXC ps_5_1 when given), draw each accepted + fixture and compare the readback with the CPU reference; each mutant must differ + +Semantics. image_get_lod returns the LOD a sample would use, clamped, and the LOD before the clamp, from the same quad +derivatives as image_sample_b; the lowering is CalculateLevelOfDetail / CalculateLevelOfDetailUnclamped and the +control-flow proof is Stage.uniform_cf with the quad vote of EXEC branches (see tests/startup_image_sample_b_flow_check.py +for the model: a lane EXEC masked off offers the address it last wrote). + +Fixtures (synthetic gfx1013 wave64 programs, no game data). v0 is the packed pixel position, x = v0 & 0xffff. Every +program starts with `s_wqm_b64 exec, exec`, sets u = 0.125 + 0.5 * x and v = 0.25 and queries the LOD of the 4x4, +three-mip 2D texture of tests/startup_image_3d.cpp (--startup-image-2d-view 0/3: one covered pixel at (0, 0), three +helper lanes) through a sampler with mip filter point, MIN_LOD 0 and MAX_LOD 2. The unclamped LOD is +log2(4 * |u(x=1) - u(x=0)|); the clamped one is that in [0, 2]. The export is (clamped, unclamped, 0, 0): + join_pixel lanes with x == 0 branch into u -= 0.5, the quad queries at the join: |du| = 1, LOD 2 + join_helper the helper column x == 1 branches into u += 1.5: |du| = 2, unclamped 3, clamped 2 + cmpx v_cmpx keeps x == 0, u -= 0.5 there only, the query runs with that EXEC: stale helper u, LOD 2 + scc a branch on root constant 1 (the same in every lane, not taken) before the query: LOD 1 + inside the query inside the s_cbranch_execz block of x == 0 after u -= 0.5 there (EXEC branches are decided + per quad, see tests/startup_image_sample_b_flow_check.py): stale helper u, LOD 2 + kill v_cmpx keeps x == 0, s_cbranch_execnz past an s_endpgm, u -= 0.5, query: LOD 2 +Refused: the query inside a block a VCC branch skips. +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 +from startup_image_sample_b_flow_check import PS_INPUTS, assemble # noqa: E402 + +PROLOGUE = """\ +s_wqm_b64 exec, exec +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0x200000 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_and_b32_e32 v8, 0xffff, v0 +v_cvt_f32_u32_e32 v9, v8 +v_mul_f32_e32 v9, 0.5, v9 +v_add_f32_e32 v2, 0x3e000000, v9 +v_mov_b32_e32 v3, 0x3e800000 +v_mov_b32_e32 v12, 0 +v_mov_b32_e32 v13, 0 +""" +QUERY = """\ +s_waitcnt lgkmcnt(0) +image_get_lod v[10:11], v[2:3], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D +""" +EXPORT = """\ +s_waitcnt vmcnt(0) +exp mrt0 v10, v11, v12, v13 done vm +s_endpgm +""" + + +def branch_on_x(x, delta): + return ('v_cmp_eq_u32_e32 vcc, %d, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 'v_add_f32_e32 v2, %s, v2\nBB1:\ns_or_b64 exec, exec, s[0:1]\n' % (x, delta)) + + +# name: (source, u at x = 0 and x = 1 when the quad queries) +FIXTURES = { + 'join_pixel': (PROLOGUE + branch_on_x(0, '-0.5') + QUERY + EXPORT, (Fraction(-3, 8), Fraction(5, 8))), + 'join_helper': (PROLOGUE + branch_on_x(1, '0x3fc00000') + QUERY + EXPORT, (Fraction(1, 8), Fraction(17, 8))), + 'cmpx': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + (Fraction(-3, 8), Fraction(5, 8))), + 'scc': (PROLOGUE + 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + QUERY + 'BB1:\n' + EXPORT, + (Fraction(1, 8), Fraction(5, 8))), + 'inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 'v_add_f32_e32 v2, -0.5, v2\n' + QUERY + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, + (Fraction(-3, 8), Fraction(5, 8))), + 'kill': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\ns_cbranch_execnz BB1\ns_endpgm\nBB1:\nv_add_f32_e32 v2, -0.5, v2\n' + + QUERY + EXPORT, (Fraction(-3, 8), Fraction(5, 8))), +} +REFUSED = { + 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + QUERY + 'BB1:\n' + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), +} +# llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources +WORDS_HEX = { + 'join_pixel': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d6a2480be010088bff10404067e00fe88' + '7fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'join_helper': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8110847d6a2480be020088bfff0404060000c03f' + '7e00fe887fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'cmpx': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010a47df10404067fc08cbf080380f1020ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'scc': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e098007bf030085bf7fc08cbf080380f1020ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d6a2480be040088bff10404067fc08cbf' + '080380f1020ac4007e00fe88703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'kill': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010a47d010089bf000081bff10404067fc08cbf' + '080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'vcc_inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d030086bf7fc08cbf080380f1020ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), +} +CALL = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v2), F(v3))), ' + 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v2), F(v3))), 0.0, 0.0);') + + +def all_sources(): + return dict({k: v[0] for k, v in FIXTURES.items()}, **{k: v[0] for k, v in REFUSED.items()}) + + +def pipeline(name): + return G.Pipeline(VS_WORDS, bytes.fromhex(WORDS_HEX[name]), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def refused(name, text): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (name, text, str(error)) + else: + raise AssertionError('%s accepted, expected %r' % (name, text)) + + +def reference(u): + """(clamped, unclamped) LOD of the drawn pixel: u is the same down a column, v is constant.""" + lod = math.log2(4 * abs(u[1] - u[0])) + assert lod == int(lod), u + return min(max(lod, 0.0), 2.0), lod + + +def controls(): + for name in FIXTURES: + text = pipeline(name).hlsl_ps() + assert text.count(CALL) == 1, (name, text) + for name, (_source, text) in REFUSED.items(): + refused(name, text) + print('image_get_lod after a join, under a v_cmpx EXEC, after a uniform branch, inside an EXEC branch and ' + 'past a kill branch: CalculateLevelOfDetail; ' + 'references %s' % ', '.join('%s=%s' % (n, reference(f[1])) for n, f in FIXTURES.items())) + print('refused: inside a block a VCC branch skips') + + +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = assemble(llvm_mc, source) + if built.hex() != WORDS_HEX[name]: + raise AssertionError('%s: assembled %s, recorded %s' % (name, built.hex(), WORDS_HEX[name])) + print('every fixture reassembles to its recorded words with %s' % llvm_mc) + + +def mutants(name, hlsl): + """HLSL variants that must give another LOD: the branch write dropped, or the EXEC guard dropped.""" + write = re.search(r'\n\s*if \(exec & 1\) v2 = U\((-0\.5|F\(0x3fc00000u\)) \+ F\(v2\)\);', hlsl) + if name.startswith('join'): + return [('without the branch write', hlsl.replace(write.group(0), ''))] + if name in ('cmpx', 'inside', 'kill'): + return [('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))] + return [] + + +def read_lod(renderer, adapter, vs, ps, sampler): + run = subprocess.run([renderer, adapter, '--startup-image-2d-view', str(vs), str(ps), sampler, '0/3'], + capture_output=True, text=True, timeout=60) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + match = re.search(r'view_rgba=((?:[0-9a-f]{8},){3}[0-9a-f]{8})', run.stdout) + if run.returncode or not match: + raise AssertionError(run.stdout + run.stderr) + return struct.unpack('>4f', bytes.fromhex(match.group(1).replace(',', ''))) + + +def close(got, want): + # One D3D12 LOD fractional step (1/256), as tests/startup_image_get_lod_view_check.py allows. + return all(abs(g - w) <= 1 / 256 for g, w in zip(got, want)) + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name, (_source, u) in FIXTURES.items(): + pipe = pipeline(name) + hlsl = pipe.hlsl_ps() + sampler, = (line for line in pipe.manifest().splitlines() if line.startswith('smpl ')) + want = reference(u) + (0.0, 0.0) + ps = compile_hlsl(compiler, kind, hlsl, '%s_%s' % (name, kind), ps_profile, directory) + got = read_lod(renderer, adapter, vs, ps, sampler) + if not close(got, want): + raise AssertionError('%s %s %s: GPU %s, CPU reference %s' % (adapter, kind, name, got, want)) + seen = [] + for i, (label, text) in enumerate(mutants(name, hlsl)): + ps = compile_hlsl(compiler, kind, text, '%s_m%d_%s' % (name, i, kind), ps_profile, directory) + other = read_lod(renderer, adapter, vs, ps, sampler) + if close(other, want): + raise AssertionError('%s %s %s: mutant "%s" matched the reference %s' + % (adapter, kind, name, label, other)) + seen.append('%s -> %s' % (label, other[:2])) + print('%s %s %s: GPU %s == CPU reference %s; %s' + % (adapter, kind, name, got[:2], want[:2], '; '.join(seen) or 'no mutant'), flush=True) + + +def main(): + if len(sys.argv) == 1 or sys.argv[1] == 'controls': + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + elif sys.argv[1] == 'draw' and len(sys.argv) in (5, 6): + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index d398e8676..540ae3c9a 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -13,7 +13,9 @@ IMAGE_SAMPLE_B the gfx10 opcode 0x25. HLSL Texture.SampleBias(sampler, location, bias) adds the bias to the implicit mip level, so the lowering is tex.SampleBias(smp, uv, bias). D3D documents the bias range as -16.0 to 15.99; the ISA text states no hardware clamp, so values outside that range are an unverified difference. Accepted under the -entry EXEC mask and wave-uniform control flow even after a uniform (scc) join or later loop; divergent EXEC or a +entry EXEC mask and wave-uniform control flow even after a uniform (scc) join or later loop; an EXEC written per lane +(v_cmpx, saveexec, a cleared EXEC) is followed exactly by the one-lane model, so it is accepted in a program without a +backward branch (tests/startup_image_sample_b_flow_check.py draws it); divergent EXEC or a vcc/exec-conditioned branch before the sample stays refused. Each fixture is a source-built gfx1013 pixel stage: v0 = bias, v1 = u = 0.75, v2 = v = 0.25 and v3 = the slice (root @@ -472,7 +474,6 @@ def controls(): join_ps = G.Pipeline(VS_WORDS, with_join_before_sample(plain), root_blob()).hlsl_ps() assert 'SampleBias' in join_ps and bias_call(join_ps, 'float2') == (['v1', 'v2'], 'v0'), join_ps for label, mutate in ( - ('divergent EXEC', with_divergent_exec_before_sample), ('s_cbranch_vccz', lambda d: with_branch_before_sample(d, 6)), ('s_cbranch_vccnz', lambda d: with_branch_before_sample(d, 7)), ('s_cbranch_execz', lambda d: with_branch_before_sample(d, 8)), @@ -485,6 +486,9 @@ def controls(): assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) else: raise AssertionError('image_sample_b accepted after %s' % label) + # A cleared EXEC is an exact per-lane write: the quad program (no backward branch) keeps the proof. + cleared = G.Pipeline(VS_WORDS, with_divergent_exec_before_sample(plain), root_blob()).hlsl_ps() + assert 'SampleBias' in cleared and 'exec = (0x00000000u) & 1;' in cleared, cleared print('uniform join before sample_b accepted; divergent EXEC and vcc/exec branches before sample_b refused') # Address order: the bias register comes first and is the third SampleBias argument. expected = { diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py new file mode 100644 index 000000000..ec6d0b420 --- /dev/null +++ b/tests/startup_image_sample_b_flow_check.py @@ -0,0 +1,350 @@ +"""image_sample_b past a branch or an EXEC change in tools/startup/gfx2hlsl.py (implicit derivatives of the quad). + + (no arguments) translation controls and refusals, pure Python + binary reassemble every fixture source and compare it with the recorded words + draw [fxc] + translate, compile (DXC ps_6_0, and FXC ps_5_1 when given), draw each accepted + fixture and compare the readback with the CPU reference; each mutant must differ + +Semantics. image_sample_b adds its bias to the LOD the texture unit derives from the address VGPRs of the four lanes of +the pixel quad (RDNA 2 ISA section 8.2.4, "_B LOD BIAS: Add this BIAS to the LOD computed"). The lanes are read whatever +their EXEC bits (that is why compilers switch to whole quad mode before computing coordinates): a lane EXEC masked off +offers the value it last wrote. The translation runs one guest lane per D3D pixel or helper lane, writes a VGPR only +where the lane's EXEC bit is 1 and calls SampleBias unconditionally, so HLSL derives from the same four values when the +four lanes reach the call together. In a pixel program with such an op and no backward branch, s_cbranch_execz/execnz +are decided per quad (x2w_quad_any, fine derivatives of the EXEC bit): the guest's wave skips a +block only when no lane is active and runs it with the other lanes masked, so a quad with an active lane stays together. +A voted branch parts no quad, so it does not clear Stage.uniform_cf; the vote reads the quad, so it is only taken while +uniform_cf holds and no lane-exec break (s_wqm of a narrowed EXEC, a discard) came first. Any other branch that can +differ between lanes (a VCC test, an SCC not proven uniform) clears uniform_cf, as in #2659. + +Fixtures (synthetic gfx1013 wave64 programs, no game data). v0 is the packed pixel position (POS_FIXED_PT, the only +pixel input enabled), x = v0 & 0xffff. Every program starts with `s_wqm_b64 exec, exec`, sets u = 0.125 + 0.5 * x, +v = 0.25, the slice from root constant 1 (s9, drawn as 0), the bias -1, and samples the 4x4, two-slice, three-mip array +of tests/startup_image_3d.cpp (--startup-image-2d-array-mips: one covered pixel at (0, 0) and its three helper lanes) +with a point sampler, mip filter point, MAX_LOD 2. u depends on x only, so the LOD is log2(4 * |u(x=1) - u(x=0)|) - 1: + join_pixel lanes with x == 0 (the drawn pixel's column) branch into u -= 0.5, then EXEC is restored and the quad + samples at the join: u = (-0.375, 0.625), LOD 2 - 1 = 1 + join_helper the helper column x == 1 branches into u += 0.5: u = (0.125, 1.125), LOD 1; the drawn pixel did not branch + cmpx v_cmpx keeps x == 0, u -= 0.5 runs on those lanes only and the sample runs with that EXEC: the helper column + offers its stale u = 0.625, LOD 2 - 1 = 1 (u = 0.125 there would give LOD 0) + scc a branch on root constant 1 (the same in every lane, not taken) before the sample: LOD 1 - 1 = 0 + inside the sample inside the s_cbranch_execz block of x == 0, after u -= 0.5 there: the quad enters together, + the helper column masked with its stale u: LOD 1 + kill v_cmpx keeps x == 0, s_cbranch_execnz past an s_endpgm, u -= 0.5, sample: the quad goes on, LOD 1 + uni_loop a loop of two passes on a constant SGPR counter (SCC proven uniform): sample, then u -= 0.5 on every + lane; the second pass reads u = (-0.375, 0.125), LOD 0 +Refused: the sample inside or after a block a VCC branch skips (the guest takes a VCC branch once per wave, with EXEC +unchanged, so a lane skipping it on its own bit can hold another u), and inside a loop whose exit reads VCC. +""" +import math +import re +import struct +import subprocess +import sys +import tempfile +from fractions import Fraction +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_image_2d_array_check import mip_cell # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +PS_INPUTS = (0x8000, 0x8000) # SPI_PS_INPUT_ENA / ADDR: POS_FIXED_PT only, so v0 holds x | y << 16 +PROLOGUE = """\ +s_wqm_b64 exec, exec +s_load_dwordx8 s[16:23], s[8:9], 0x0 +s_mov_b32 s24, 0 +s_mov_b32 s25, 0x200000 +s_mov_b32 s26, 0x4000000 +s_mov_b32 s27, 0 +v_and_b32_e32 v8, 0xffff, v0 +v_cvt_f32_u32_e32 v9, v8 +v_mul_f32_e32 v9, 0.5, v9 +v_add_f32_e32 v2, 0x3e000000, v9 +v_mov_b32_e32 v1, -1.0 +v_mov_b32_e32 v3, 0x3e800000 +v_mov_b32_e32 v4, s9 +""" +SAMPLE = """\ +s_waitcnt lgkmcnt(0) +image_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +""" +EXPORT = """\ +s_waitcnt vmcnt(0) +exp mrt0 v10, v11, v12, v13 done vm +s_endpgm +""" + + +def branch_on_x(x, delta): + return ('v_cmp_eq_u32_e32 vcc, %d, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 'v_add_f32_e32 v2, %s, v2\nBB1:\ns_or_b64 exec, exec, s[0:1]\n' % (x, delta)) + + +# name: (source, u at x = 0 and x = 1 when the quad samples, bias) for the drawn fixtures +SUB = 'v_add_f32_e32 v2, -0.5, v2\n' +CMPX = 'v_cmpx_eq_u32_e32 0, v8\n' +FIXTURES = { + 'join_pixel': (PROLOGUE + branch_on_x(0, '-0.5') + SAMPLE + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + 'join_helper': (PROLOGUE + branch_on_x(1, '0.5') + SAMPLE + EXPORT, (Fraction(1, 8), Fraction(9, 8)), -1), + 'cmpx': (PROLOGUE + CMPX + SUB + SAMPLE + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + 'scc': (PROLOGUE + 's_cmp_lg_u32 s9, 0\ns_cbranch_scc1 BB1\n' + SAMPLE + 'BB1:\n' + EXPORT, + (Fraction(1, 8), Fraction(5, 8)), -1), + 'inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + SUB + + SAMPLE + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + 'kill': (PROLOGUE + CMPX + 's_cbranch_execnz BB1\ns_endpgm\nBB1:\n' + SUB + SAMPLE + EXPORT, + (Fraction(-3, 8), Fraction(5, 8)), -1), + 'uni_loop': (PROLOGUE + 's_mov_b32 s30, 2\nBB1:\n' + SAMPLE + SUB + 's_add_i32 s30, s30, -1\ns_cmp_lg_u32 s30, 0\n' + 's_cbranch_scc1 BB1\n' + EXPORT, (Fraction(-3, 8), Fraction(1, 8)), -1), +} +# name: (source, text of the refusal) +REFUSED = { + # The wave takes a VCC branch once for all lanes and runs the block with EXEC unchanged, while a lane here follows + # its own bit: it clears uniform_cf, so the sample after it is refused (#2659). + 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + SAMPLE + 'BB1:\n' + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'vcc_join': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + SUB + 'BB1:\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'loop': (PROLOGUE + 'BB1:\n' + SAMPLE + 's_waitcnt vmcnt(0)\nv_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccnz BB1\n' + + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # s_wqm of a narrowed EXEC is a no-op here while the guest turns the quad back on: a lane-exec break. + 'wqm_break': (PROLOGUE + CMPX + 's_wqm_b64 exec, exec\n' + SUB + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), +} +# llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources +WORDS_HEX = { + 'join_pixel': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d6a2480be010088bff10404067e00fe88' + '7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'join_helper': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8110847d6a2480be010088bff00404067e00fe88' + '7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'cmpx': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47df10404067fc08cbf280f94f0010ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'scc': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e098007bf030085bf7fc08cbf280f94f0010ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d6a2480be040088bff10404067fc08cbf' + '280f94f0010ac4007e00fe88703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'kill': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d010089bf000081bff10404067fc08cbf' + '280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'wqm_break': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d7e0afebef10404067fc08cbf280f94f0' + '010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'uni_loop': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e82039ebe7fc08cbf280f94f0010ac400f1040406' + '1ec11e811e8007bff9ff85bf703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'vcc_inside': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d030086bf7fc08cbf280f94f0010ac400' + '703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'vcc_join': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010847d010086bff10404067fc08cbf280f94f0' + '010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'loop': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7fc08cbf280f94f0010ac400703f8cbf8010847d' + 'faff87bf703f8cbf0f1800f80a0b0c0d000081bf' + ), +} +BRANCH = re.compile(r'^(s_c?branch\w*) (BB\d+)$') + + +def resolve(source, sizes): + """The source with each label operand replaced by its SIMM16 (dwords after the next instruction).""" + lines = [line for line in source.splitlines() if line] + labels, at, off = {}, [], 0 + for line in lines: + if line.endswith(':'): + labels[line[:-1]] = off + else: + at.append(off) + off += sizes[len(at) - 1] + out = [] + for line in (line for line in lines if not line.endswith(':')): + m = BRANCH.match(line) + if m: + line = '%s %d' % (m.group(1), (labels[m.group(2)] - at[len(out)] - 4) // 4) + out.append(line) + return '\n'.join(out) + '\n' + + +def assemble(llvm_mc, source): + """Words of a labelled source: one pass with every branch at 0 sizes the instructions, the second encodes.""" + def encode(text): + run = subprocess.run([llvm_mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', + '-show-encoding'], input=text, capture_output=True, text=True, check=True) + return [bytes(int(b, 16) for b in m.group(1).split(',')) + for m in re.finditer(r'encoding: \[([^\]]*)\]', run.stdout)] + plain = [BRANCH.sub(r'\1 0', line) for line in source.splitlines() if line and not line.endswith(':')] + sizes = [len(w) for w in encode('\n'.join(plain) + '\n')] + assert len(sizes) == len(plain), (len(sizes), len(plain)) + return b''.join(encode(resolve(source, sizes))) + + +def all_sources(): + return dict({k: v[0] for k, v in FIXTURES.items()}, **{k: v[0] for k, v in REFUSED.items()}) + + +def words(name): + return bytes.fromhex(WORDS_HEX[name]) + + +def pipeline(name): + return G.Pipeline(VS_WORDS, words(name), root_blob(), ps_hw_inputs=PS_INPUTS) + + +def refused(name, text): + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert text in str(error), (name, text, str(error)) + else: + raise AssertionError('%s accepted, expected %r' % (name, text)) + + +def reference(name): + """The texel the drawn pixel reads: LOD log2(4 |du/dx|) + bias (u is the same down a column), mip filter point.""" + _source, (u0, u1), bias = FIXTURES[name] + footprint = 4 * abs(u1 - u0) + lod = math.log2(footprint) + assert lod == int(lod), (name, footprint) + mip = min(max(int(lod) + bias, 0), 2) + size = 4 >> mip + wrapped = u0 - math.floor(u0) + return mip_cell(int(wrapped * size), int(Fraction(1, 4) * size), 0, mip) + + +CALL = 't = r0.SampleBias(q0, float3(F(v2), F(v3), F(v4)), F(v1));' + + +def controls(): + for name in FIXTURES: + text = pipeline(name).hlsl_ps() + assert text.count(CALL) == 1, (name, text) + assert 'SampleLevel' not in text, (name, text) + for name, (_source, text) in REFUSED.items(): + refused(name, text) + # The quad votes: the EXEC branches of inside, kill and join_pixel, one vote each; v_cmpx alone needs none. + for name, votes in (('inside', 1), ('kill', 1), ('cmpx', 0), ('join_pixel', 1), ('join_helper', 1), ('scc', 0)): + text = pipeline(name).hlsl_ps() + assert text.count('x2w_quad_any(exec)') == votes, (name, text) + # The gate is the vote's: with the EXEC rule of #2659 (the entry mask only) the divergent-EXEC fixtures are refused. + saved = G.Stage.derivative_exec_ok + G.Stage.derivative_exec_ok = lambda self: self.exec_known + try: + for name in ('cmpx', 'inside', 'kill'): + refused(name, 'image_sample_b needs implicit derivatives') + finally: + G.Stage.derivative_exec_ok = saved + # A lane-exec break before the sample keeps it refused: s_wqm of a narrowed EXEC is a no-op in the one-lane model. + refused('wqm_break', 'image_sample_b needs implicit derivatives') + cells = {name: reference(name) for name in FIXTURES} + print('image_sample_b after a join, under a v_cmpx EXEC, after a uniform branch, inside an EXEC branch and ' + 'past a kill branch: SampleBias; references %s' + % ', '.join('%s=%s' % kv for kv in cells.items())) + print('refused: inside or after a block a VCC branch skips, in a VCC loop, after s_wqm of a narrowed EXEC') + + +def check_binary(llvm_mc): + for name, source in all_sources().items(): + built = assemble(llvm_mc, source) + if built != words(name): + raise AssertionError('%s: assembled %s, recorded %s' % (name, built.hex(), WORDS_HEX[name])) + print('every fixture reassembles to its recorded words with %s' % llvm_mc) + + +def mutants(name, hlsl): + """HLSL variants that must read another texel: the branch write dropped, the EXEC guard of the u write dropped, + the bias dropped.""" + out = [] + write = re.search(r'\n\s*if \(exec & 1\) v2 = U\(-?0\.5 \+ F\(v2\)\);', hlsl) + if name.startswith('join'): + out.append(('without the branch write', hlsl.replace(write.group(0), ''))) + if name in ('cmpx', 'inside', 'kill'): + out.append(('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))) + out.append(('bias ignored', hlsl.replace(CALL, CALL.replace('F(v1))', '0.0)')))) + for label, text in out: + assert text != hlsl, (name, label) + return out + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + + def draw(vs, ps, expected, sampler): + run = subprocess.run([renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected, + sampler], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name in FIXTURES: + pipe = pipeline(name) + hlsl = pipe.hlsl_ps() + sampler = [line for line in pipe.manifest().splitlines() if line.startswith(('smp ', 'smpl '))] + assert len(sampler) == 1, pipe.manifest() + want = reference(name) + ps = compile_hlsl(compiler, kind, hlsl, '%s_%s' % (name, kind), ps_profile, directory) + run = draw(vs, ps, want, sampler[0]) + if run.returncode: + raise AssertionError('%s %s %s: GPU differs from the CPU reference %s\n%s%s' + % (adapter, kind, name, want, run.stdout, run.stderr)) + seen = [] + for i, (label, text) in enumerate(mutants(name, hlsl)): + ps = compile_hlsl(compiler, kind, text, '%s_m%d_%s' % (name, i, kind), ps_profile, directory) + run = draw(vs, ps, want, sampler[0]) + got = re.search(r'actual=(\S+)', run.stderr) + if run.returncode == 0 or not got: + raise AssertionError('%s %s %s: mutant "%s" matched the reference\n%s%s' + % (adapter, kind, name, label, run.stdout, run.stderr)) + seen.append('%s -> %s' % (label, got.group(1))) + print('%s %s %s: GPU == CPU reference %s; %s' % (adapter, kind, name, want, '; '.join(seen)), + flush=True) + + +def main(): + if len(sys.argv) == 1 or sys.argv[1] == 'controls': + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + elif sys.argv[1] == 'draw' and len(sys.argv) in (5, 6): + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f33c70de3..526f6bbea 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -977,6 +977,17 @@ def smem_mods(mods): # DPP quad_perm selections that exchange lanes of a 2x2 pixel quad (lane = 2 * y + x), with the SM 6.0 intrinsic. +# Image ops that take implicit derivatives of the pixel quad (see Stage.quad_vote). +DERIVATIVE_OPS = ('image_sample_b', 'image_get_lod') +# "Some lane of the 2x2 quad has bit 0 set": fine derivatives of a 0/1 value read the row neighbour (ddx_fine), then +# the other row (ddy_fine). Exact for 0/1 and defined only where the quad runs the statement together (SM 5.0 and 6.0). +QUAD_ANY_HLSL = [ + 'bool x2w_quad_any(uint bit) {', + ' float lane = (bit & 1u) != 0u ? 1.0 : 0.0;', + ' float row = (lane != 0.0 || ddx_fine(lane) != 0.0) ? 1.0 : 0.0;', + ' return row != 0.0 || ddy_fine(row) != 0.0;', + '}', +] QUAD_SWAPS = {(1, 0, 3, 2): 'QuadReadAcrossX', (2, 3, 0, 1): 'QuadReadAcrossY', (3, 2, 1, 0): 'QuadReadAcrossDiagonal'} @@ -3052,6 +3063,11 @@ def translate(self): splits.update((self.mesh_allocation_block, self.ins[at + 2][0])) join_writes = self.join_writes(branches) refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ + # A pixel program with an implicit-derivative op and no backward branch decides its EXEC branches per quad + # (quad vote): see Stage.quad_vote. Loops keep the rules of the back-edge proof below. + self.quad_exec = getattr(self, 'kind', None) == 'ps' and not any(t <= pc for pc, t in branches) and any( + name in DERIVATIVE_OPS for _off, _n, name, _asm in self.ins) + self.uses_quad_vote = False joined, forward_splits, div_targets, self.spill_cfg = self.joined_registers(with_cfg=True) self.spill_reach = self.spill_reaching(self.spill_cfg) init_sym = dict(self.sym) @@ -3089,6 +3105,8 @@ def translate(self): self.uniform_cf = True self.derivative_sites = [] # (offset, name) of image_sample_b / image_get_lod, for the back-edge proof self.divergent_back_edges = [] # (target, branch offset) of divergent backward branches + self.lane_exec_breaks = [] # (offset, what): the lane's EXEC bit may stop following the guest's from here + self.voted_branches = set() # EXEC branches decided per quad (x2w_quad_any); they part no quad self.masks = set(init_masks) self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined) last_write = {} # SGPR -> offset of its last write in program order @@ -3287,6 +3305,14 @@ def translate(self): cond_uniform = True if cond_uniform: self.uniform_branches.add(off) + elif (cond in ('execz', 'execnz') and self.quad_exec and not self.exec_known + and self.uniform_cf and not self.lane_exec_breaks): + # Decided per quad (x2w_quad_any): every lane of a quad takes it together, so it parts no + # quad and the derivative ops after it still see their four lanes. It reads the quad, so it + # is only taken while the control flow so far is quad-uniform and every lane's EXEC bit + # still follows the guest's. + self.voted_branches.add(off) + cond_uniform = True if not cond_uniform: # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. self.uniform_cf = False @@ -3471,6 +3497,17 @@ def tid_shift(self, count, source): def pc_index(self): return next((i for i, ins in enumerate(self.ins) if ins[0] == self.pc), None) + def derivative_exec_ok(self): + """Whether an implicit-derivative op may rely on the EXEC the lanes hold here. + + At the entry mask every lane runs the call. Past an EXEC write (v_cmpx, saveexec, a restore) the one-lane + model still follows the guest's bit of each lane exactly (EXEC is written per lane, set_v is EXEC guarded), + so a quad program (a pixel program with a derivative op and no backward branch) is proven as long as no + lane-exec break happened: an s_wqm of a narrowed EXEC (a no-op here, while the guest turns on the lanes of + every touched quad) or a discard under an unknown EXEC. The callers also need uniform_cf, which a branch + that parts a quad clears; an EXEC branch decided per quad (quad_vote) does not.""" + return self.exec_known or (getattr(self, 'quad_exec', False) and not getattr(self, 'lane_exec_breaks', None)) + def uniform_source(self, tok): r = reg_range(tok) if r: @@ -3683,6 +3720,10 @@ def lower(self, base, asm, ops, mods): if base in ('s_wqm_b32', 's_wqm_b64'): if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False): self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included + elif hasattr(self, 'lane_exec_breaks'): + # Any other s_wqm is a no-op here, while the guest turns on the inactive lanes of every touched quad + # (or writes a whole-quad mask somewhere): a lane's EXEC bit may be 0 where the guest's is 1. + self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) if hasattr(self, 'uniform_v'): self.uniform_v.clear() if hasattr(self, 'scc_uniform'): @@ -3738,6 +3779,11 @@ def lower(self, base, asm, ops, mods): raise Unsupported('slot 57 mesh: a branch reads SCC that is not proven wave-uniform') cond = {'scc0': '!scc', 'scc1': 'scc', 'vccz': '(vcc & 1) == 0', 'vccnz': '(vcc & 1) != 0', 'execz': '(exec & 1) == 0', 'execnz': '(exec & 1) != 0'}[base[10:]] + if base[10:] in ('execz', 'execnz') and getattr(self, 'pc', None) in getattr(self, 'voted_branches', ()): + # The wave skips the block only when no lane is active; a quad with an active lane runs it whole, its + # other lanes masked (their VGPRs kept for the derivatives, writes guarded by EXEC), as the guest does. + self.uses_quad_vote = True + cond = ('!' if base.endswith('execz') else '') + 'x2w_quad_any(exec)' return ('branch', cond, int(ops[0].split('_')[1], 16)) if base == 'exp': return self.export(asm) @@ -5875,7 +5921,7 @@ def image(self, ops, mods, how): # Elsewhere the plain sample is lowered to level 0, which would drop the bias, so the bias form is # refused instead. A uniform join (scc with scc_uniform) or later loop does not drop the proof # (M200-01 B/L). Divergent EXEC or a vcc/exec-conditioned branch before the sample stays refused. - if (self.kind != 'ps' or not self.exec_known or + if (self.kind != 'ps' or not self.derivative_exec_ok() or not getattr(self, 'uniform_cf', True)): raise Unsupported('image_sample_b needs implicit derivatives: pixel stage with the entry EXEC ' 'mask and wave-uniform control flow') @@ -5892,7 +5938,7 @@ def image(self, ops, mods, how): if self.kind != 'ps' or dim != 'SQ_RSRC_IMG_2D' or not dmask or dmask & ~3 or len(cs) != 2: raise Unsupported('image_get_lod form %s %s' % (', '.join(ops), ' '.join(mods))) # Both HLSL calls take implicit derivatives, so the rule of image_sample_b applies. - if not self.exec_known or not getattr(self, 'uniform_cf', True): + if not self.derivative_exec_ok() or not getattr(self, 'uniform_cf', True): raise Unsupported('image_get_lod needs implicit derivatives: pixel stage with the entry EXEC ' 'mask and wave-uniform control flow') if hasattr(self, 'derivative_sites'): @@ -7710,6 +7756,8 @@ def export(self, asm): % next(f for f in flags if f.startswith('en:'))[3:]) if 'vm' in flags and not self.exec_known: self.emit('if (!(exec & 1)) discard;') + if hasattr(self, 'lane_exec_breaks'): + self.lane_exec_breaks.append((self.pc, 'a discard')) if target == 'null': return None # the null target writes no render target; its only effect is the vm discard above if target == 'mrtz': @@ -8750,7 +8798,8 @@ def hlsl_ps(self): s = self.ps targets = sorted(int(k[3:]) for k in s.exports if k.startswith('mrt')) depth = 'depth' in s.exports - out = self.common() + ['struct PSIn {'] + self.interface(True) + ['};'] + quad = QUAD_ANY_HLSL if getattr(s, 'uses_quad_vote', False) else [] + out = self.common() + quad + ['struct PSIn {'] + self.interface(True) + ['};'] if not targets and not depth: out += ['void main(PSIn i) {'] + s.declarations() + s.body() + ['}'] return '\n'.join(out) + '\n' From 087c789a99957e622f64fcf6e9c4e08e83c8ade8 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 05:47:30 +0100 Subject: [PATCH 02/10] startup: vote EXEC branches with an arithmetic helper and only over vector-only blocks --- tests/startup_image_get_lod_flow_check.py | 8 +++++++ tests/startup_image_sample_b_flow_check.py | 8 +++++++ tools/startup/gfx2hlsl.py | 28 +++++++++++++++++++--- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py index b7e583540..9f5c96bf5 100644 --- a/tests/startup_image_get_lod_flow_check.py +++ b/tests/startup_image_get_lod_flow_check.py @@ -90,6 +90,11 @@ def branch_on_x(x, delta): REFUSED = { 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + QUERY + 'BB1:\n' + EXPORT, 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A scalar write inside the block an EXEC branch can skip happens once for the wave in the guest; a quad that + # votes to skip it would miss it (review of the first version): the branch is not voted, the op is refused. + 'scalar_in_block': (PROLOGUE + 's_mov_b32 s28, -1.0\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 's_mov_b32 s28, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\nv_mov_b32_e32 v1, s28\n' + + QUERY + EXPORT, 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { @@ -128,6 +133,9 @@ def branch_on_x(x, delta): 'f0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010847d030086bf7fc08cbf080380f1020ac400' '703f8cbf0f1800f80a0b0c0d000081bf' ), + 'scalar_in_block': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7ef3039cbe8210847d6a2480be010088bf80039cbe7e00fe881c02027e7fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } CALL = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v2), F(v3))), ' 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v2), F(v3))), 0.0, 0.0);') diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index ec6d0b420..130f59083 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -114,6 +114,11 @@ def branch_on_x(x, delta): + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), # s_wqm of a narrowed EXEC is a no-op here while the guest turns the quad back on: a lane-exec break. 'wqm_break': (PROLOGUE + CMPX + 's_wqm_b64 exec, exec\n' + SUB + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A scalar write inside the block an EXEC branch can skip happens once for the wave in the guest; a quad that + # votes to skip it would miss it (review of the first version): the branch is not voted, the op is refused. + 'scalar_in_block': (PROLOGUE + 's_mov_b32 s28, -1.0\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + 's_mov_b32 s28, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\nv_mov_b32_e32 v1, s28\n' + + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { @@ -172,6 +177,9 @@ def branch_on_x(x, delta): 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7fc08cbf280f94f0010ac400703f8cbf8010847d' 'faff87bf703f8cbf0f1800f80a0b0c0d000081bf' ), + 'scalar_in_block': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef3039cbe8210847d6a2480be010088bf80039cbe7e00fe881c02027e7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } BRANCH = re.compile(r'^(s_c?branch\w*) (BB\d+)$') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 08962c342..f342b1472 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -981,11 +981,13 @@ def smem_mods(mods): DERIVATIVE_OPS = ('image_sample_b', 'image_get_lod') # "Some lane of the 2x2 quad has bit 0 set": fine derivatives of a 0/1 value read the row neighbour (ddx_fine), then # the other row (ddy_fine). Exact for 0/1 and defined only where the quad runs the statement together (SM 5.0 and 6.0). +# The derivatives are arithmetic operands, not operands of a short-circuit ||: a DXC build for some GPUs moved a derivative +# under the condition of an ||, where only some lanes ran it (measured on a hardware adapter). QUAD_ANY_HLSL = [ 'bool x2w_quad_any(uint bit) {', ' float lane = (bit & 1u) != 0u ? 1.0 : 0.0;', - ' float row = (lane != 0.0 || ddx_fine(lane) != 0.0) ? 1.0 : 0.0;', - ' return row != 0.0 || ddy_fine(row) != 0.0;', + ' float row = (lane + abs(ddx_fine(lane)) != 0.0) ? 1.0 : 0.0;', + ' return row + abs(ddy_fine(row)) != 0.0;', '}', ] QUAD_SWAPS = {(1, 0, 3, 2): 'QuadReadAcrossX', (2, 3, 0, 1): 'QuadReadAcrossY', (3, 2, 1, 0): 'QuadReadAcrossDiagonal'} @@ -3306,7 +3308,8 @@ def translate(self): if cond_uniform: self.uniform_branches.add(off) elif (cond in ('execz', 'execnz') and self.quad_exec and not self.exec_known - and self.uniform_cf and not self.lane_exec_breaks): + and self.uniform_cf and not self.lane_exec_breaks + and self.skipped_block_vector_only(off, int(parse(asm)[1][0].split('_')[1], 16))): # Decided per quad (x2w_quad_any): every lane of a quad takes it together, so it parts no # quad and the derivative ops after it still see their four lanes. It reads the quad, so it # is only taken while the control flow so far is quad-uniform and every lane's EXEC bit @@ -3497,6 +3500,25 @@ def tid_shift(self, count, source): def pc_index(self): return next((i for i, ins in enumerate(self.ins) if ins[0] == self.pc), None) + def skipped_block_vector_only(self, branch, target): + """Whether the instructions a forward EXEC branch can skip are per-lane vector work only. + + The guest takes the branch once for the whole wave, so a scalar write, a mask write or a branch inside the block + happens once for the wave when any quad takes the block. A quad that votes to skip it would miss that effect while + a later read in the same wave sees it. Only vector ALU/memory/export instructions and waits, which each lane + applies to its own registers, are allowed between the branch and its target; s_endpgm too (a quad that ends + reads nothing later).""" + if target <= branch: + return False + for off, _n, name, _asm in self.ins: + if branch < off < target and not ( + (name.startswith('v_') and not name.startswith(('v_cmp', 'v_readlane', 'v_readfirstlane', + 'v_writelane'))) + or name.startswith(('image_', 'buffer_', 'tbuffer_', 'global_', 'flat_', 'exp')) + or name in ('s_waitcnt', 's_nop', 's_waitcnt_vscnt', 's_endpgm')): + return False + return True + def derivative_exec_ok(self): """Whether an implicit-derivative op may rely on the EXEC the lanes hold here. From 5c907ddec5cafbfb3912b49698abd10aa4b77977 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 05:48:25 +0100 Subject: [PATCH 03/10] tests: draw the saved-and-restored EXEC shape in the derivative flow checks --- tests/startup_image_get_lod_flow_check.py | 7 +++++++ tests/startup_image_sample_b_flow_check.py | 9 ++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py index 9f5c96bf5..493e37cde 100644 --- a/tests/startup_image_get_lod_flow_check.py +++ b/tests/startup_image_get_lod_flow_check.py @@ -86,6 +86,10 @@ def branch_on_x(x, delta): (Fraction(-3, 8), Fraction(5, 8))), 'kill': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\ns_cbranch_execnz BB1\ns_endpgm\nBB1:\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, (Fraction(-3, 8), Fraction(5, 8))), + # The exact mask saved before s_wqm and restored before the op (the usual compiled pixel shader): a cleared lane + # still offers its address; nothing is drawn differently from the plain sample. + 'restore': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + QUERY + EXPORT, + (Fraction(1, 8), Fraction(5, 8))), } REFUSED = { 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + QUERY + 'BB1:\n' + EXPORT, @@ -136,6 +140,9 @@ def branch_on_x(x, delta): 'scalar_in_block': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7ef3039cbe8210847d6a2480be010088bf80039cbe7e00fe881c02027e7fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' ), + 'restore': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e7e0cfe877fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } CALL = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v2), F(v3))), ' 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v2), F(v3))), 0.0, 0.0);') diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index 130f59083..536d4b839 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -101,6 +101,10 @@ def branch_on_x(x, delta): (Fraction(-3, 8), Fraction(5, 8)), -1), 'uni_loop': (PROLOGUE + 's_mov_b32 s30, 2\nBB1:\n' + SAMPLE + SUB + 's_add_i32 s30, s30, -1\ns_cmp_lg_u32 s30, 0\n' 's_cbranch_scc1 BB1\n' + EXPORT, (Fraction(-3, 8), Fraction(1, 8)), -1), + # The exact mask saved before s_wqm and restored before the op (the usual compiled pixel shader): a cleared lane + # still offers its address; nothing is drawn differently from the plain sample. + 'restore': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + SAMPLE + EXPORT, + (Fraction(1, 8), Fraction(5, 8)), -1), } # name: (source, text of the refusal) REFUSED = { @@ -180,6 +184,9 @@ def branch_on_x(x, delta): 'scalar_in_block': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef3039cbe8210847d6a2480be010088bf80039cbe7e00fe881c02027e7fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' ), + 'restore': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e7e0cfe877fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } BRANCH = re.compile(r'^(s_c?branch\w*) (BB\d+)$') @@ -260,7 +267,7 @@ def controls(): for name, (_source, text) in REFUSED.items(): refused(name, text) # The quad votes: the EXEC branches of inside, kill and join_pixel, one vote each; v_cmpx alone needs none. - for name, votes in (('inside', 1), ('kill', 1), ('cmpx', 0), ('join_pixel', 1), ('join_helper', 1), ('scc', 0)): + for name, votes in (('inside', 1), ('kill', 1), ('cmpx', 0), ('join_pixel', 1), ('join_helper', 1), ('scc', 0), ('restore', 0)): text = pipeline(name).hlsl_ps() assert text.count('x2w_quad_any(exec)') == votes, (name, text) # The gate is the vote's: with the EXEC rule of #2659 (the entry mask only) the divergent-EXEC fixtures are refused. From 9402a52cc6c7dd47caf520bfd94ea277078594ab Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 06:02:20 +0100 Subject: [PATCH 04/10] startup: refuse a per-lane sample_b bias past a divergent EXEC --- tests/startup_image_sample_b_flow_check.py | 7 ++++ tools/startup/gfx2hlsl.py | 40 ++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index 536d4b839..92d47761e 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -123,6 +123,10 @@ def branch_on_x(x, delta): 'scalar_in_block': (PROLOGUE + 's_mov_b32 s28, -1.0\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' 's_mov_b32 s28, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\nv_mov_b32_e32 v1, s28\n' + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + # A bias that differs per lane (a join of two values) past a divergent EXEC is not drawn: refused by name. + 'bias_per_lane': (PROLOGUE + 'v_mov_b32_e32 v14, 1.0\nv_cmp_eq_u32_e32 vcc, 0, v8\nv_cndmask_b32_e32 v1, v1, v14, vcc\n' + + branch_on_x(0, '-0.5') + SAMPLE + EXPORT, + 'image_sample_b with a per-lane bias past a divergent EXEC'), } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { @@ -187,6 +191,9 @@ def branch_on_x(x, delta): 'restore': ( '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e7e0cfe877fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' ), + 'bias_per_lane': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef2021c7e8010847d011d02028010847d6a2480be010088bff10404067e00fe887fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } BRANCH = re.compile(r'^(s_c?branch\w*) (BB\d+)$') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f342b1472..ec330f2d4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3519,6 +3519,42 @@ def skipped_block_vector_only(self, branch, target): return False return True + def uniform_bias(self, tok): + """Whether a VGPR holds one value in every lane at the op: its last earlier write is a v_mov_b32 of a constant + that every lane ran (no EXEC write and no branch before it, so no lane skipped it and the other lanes keep an + older value). No backward branch exists in a quad program, so later writes cannot reach the op.""" + r = reg_range(tok) + if not r or r[0] != 'v' or r[1] != r[2]: + return False + last = None + for off, _n, name, asm in self.ins: + if off >= self.pc: + break + ops = parse(asm)[1] + first = reg_range(ops[0]) if ops else None + if first and first[0] == 'v' and first[1] <= r[1] <= first[2]: + const = (re.sub(r'_e(32|64)$', '', name) == 'v_mov_b32' and len(ops) == 2 and not reg_range(ops[1])) + last = off if const else None + if last is None: + return False + narrowed = 0 + for off, _n, name, asm in self.ins: + if off >= last: + break + base = re.sub(r'_e(32|64)$', '', name) + ops = parse(asm)[1] + if name.startswith('s_cbranch') or name == 's_branch': + target = int(ops[0].split('_')[1], 16) if '_' in ops[0] else None + if target is None or target > last: + return False # the write can be skipped by some lanes + elif base in ('s_or_b64', 's_or_b32') and ops[:2] in (['exec', 'exec'], ['exec_lo', 'exec_lo']): + narrowed = max(narrowed - 1, 0) # the restore that ends a saveexec region + elif base.startswith('s_and_saveexec') or (base.startswith('s_wqm') and ops[:2] not in (['exec', 'exec'], ['exec_lo', 'exec_lo'])): + narrowed += 1 + elif writes_exec(name, ops) and not (base.startswith('s_wqm') and ops[:2] in (['exec', 'exec'], ['exec_lo', 'exec_lo'])): + return False + return narrowed == 0 + def derivative_exec_ok(self): """Whether an implicit-derivative op may rely on the EXEC the lanes hold here. @@ -5949,6 +5985,10 @@ def image(self, ops, mods, how): 'mask and wave-uniform control flow') if hasattr(self, 'derivative_sites'): self.derivative_sites.append((self.pc, 'image_sample_b')) + if not self.exec_known and not self.uniform_bias(cs[0]): + # Past a divergent EXEC the op is only drawn with one bias for the quad (tests/startup_image_sample_b_ + # flow_check.py); a bias that differs per lane (a join of different values) stays refused by name. + raise Unsupported('image_sample_b with a per-lane bias past a divergent EXEC') bias, cs = cs[0], cs[1:] if how == 'get_lod': # image_get_lod returns [0] the LOD a sample would use, clamped, and [1] the computed LOD before the clamp From 1b7ae02004ae0ea6e3615895f10911aff5f22fb3 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 07:28:20 +0100 Subject: [PATCH 05/10] fix: quad vote and lane-exact EXEC for derivative ops (review threads) - a voted block may hold only instructions whose destinations are VGPRs (no carry-out, compare, readlane); - s_endpgm in a voted block only when no EXEC write follows the branch; - a scalar EXEC write from a non-mask source (s_mov exec, 1) records a lane-exec break. Three refused fixtures with recorded words; each fails on the previous head. --- tests/startup_image_sample_b_flow_check.py | 18 ++++++++ tools/startup/gfx2hlsl.py | 52 +++++++++++++++++++--- 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index 92d47761e..ec0171425 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -123,6 +123,9 @@ def branch_on_x(x, delta): 'scalar_in_block': (PROLOGUE + 's_mov_b32 s28, -1.0\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' 's_mov_b32 s28, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\nv_mov_b32_e32 v1, s28\n' + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'carry_in_block': (PROLOGUE + 's_mov_b64 s[28:29], exec\nv_cmp_eq_u32_e32 vcc, 2, v8\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\nv_add_co_u32_e64 v14, s[28:29], 0, 0\nBB1:\ns_or_b64 exec, exec, s[0:1]\ns_or_b64 exec, exec, s[28:29]\ns_waitcnt lgkmcnt(0)\nimage_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\ns_waitcnt vmcnt(0)\nexp mrt0 v10, v11, v12, v13 done vm\ns_endpgm\n', 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'exec_const_mask': (PROLOGUE + 's_mov_b64 s[12:13], exec\ns_mov_b64 exec, 1\nv_add_f32_e32 v2, 0.5, v2\ns_mov_b64 exec, s[12:13]\ns_waitcnt lgkmcnt(0)\nimage_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\ns_waitcnt vmcnt(0)\nexp mrt0 v10, v11, v12, v13 done vm\ns_endpgm\n', 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), + 'kill_then_restore': (PROLOGUE + 's_mov_b64 s[12:13], exec\nv_cmpx_eq_u32_e32 0, v8\ns_cbranch_execnz BB1\ns_endpgm\nBB1:\ns_mov_b64 exec, s[12:13]\nv_add_f32_e32 v2, -0.5, v2\ns_waitcnt lgkmcnt(0)\nimage_sample_b v[10:13], v[1:4], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\ns_waitcnt vmcnt(0)\nexp mrt0 v10, v11, v12, v13 done vm\ns_endpgm\n', 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), # A bias that differs per lane (a join of two values) past a divergent EXEC is not drawn: refused by name. 'bias_per_lane': (PROLOGUE + 'v_mov_b32_e32 v14, 1.0\nv_cmp_eq_u32_e32 vcc, 0, v8\nv_cndmask_b32_e32 v1, v1, v14, vcc\n' + branch_on_x(0, '-0.5') + SAMPLE + EXPORT, @@ -191,6 +194,21 @@ def branch_on_x(x, delta): 'restore': ( '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e7e0cfe877fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' ), + 'carry_in_block': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7e049cbe8210847d6a2480be020088bf0e1c0fd7' + '800001007e00fe887e1cfe887fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'exec_const_mask': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7e048cbe8104febef00404060c04febe7fc08cbf' + '280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), + 'kill_then_restore': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e7e048cbe8010a47d010089bf000081bf0c04febe' + 'f10404067fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), 'bias_per_lane': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef2021c7e8010847d011d02028010847d6a2480be010088bff10404067e00fe887fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' ), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 01e831df2..525a7a26c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3597,6 +3597,23 @@ def tid_shift(self, count, source): def pc_index(self): return next((i for i, ins in enumerate(self.ins) if ins[0] == self.pc), None) + def exec_write_exact(self, srcs, syms): + """Whether a scalar EXEC write takes every source from a lane mask (vcc, exec, a saved EXEC or a tagged mask) or + from the all-zero / all-ones constants: then each lane's bit is the guest's. Any other source (a mask built + from a number such as 1) selects guest lanes the one-lane model cannot tell apart.""" + for tok, sym in zip(srcs, syms): + r = reg_range(tok) + if tok in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or sym == ('execcopy',) or ( + r and r[0] == 's' and r[1] in getattr(self, 'masks', ())): + continue + try: + if int(tok, 0) in (0, -1, 0xffffffff, 0xffffffffffffffff): + continue + except ValueError: + pass + return False + return True + def skipped_block_vector_only(self, branch, target): """Whether the instructions a forward EXEC branch can skip are per-lane vector work only. @@ -3607,12 +3624,33 @@ def skipped_block_vector_only(self, branch, target): reads nothing later).""" if target <= branch: return False - for off, _n, name, _asm in self.ins: - if branch < off < target and not ( - (name.startswith('v_') and not name.startswith(('v_cmp', 'v_readlane', 'v_readfirstlane', - 'v_writelane'))) + for off, _n, name, asm in self.ins: + if not branch < off < target: + continue + if name == 's_endpgm': + # A quad that ends reads nothing later, unless later code can turn it back on: an EXEC write after the + # branch (a restore of a saved mask) would reactivate every quad of the guest wave. + if any(o > branch and writes_exec(n, parse(a)[1]) for o, _s, n, a in self.ins): + return False + continue + if not (self.vector_only_instruction(name, asm) or name.startswith(('image_', 'buffer_', 'tbuffer_', 'global_', 'flat_', 'exp')) - or name in ('s_waitcnt', 's_nop', 's_waitcnt_vscnt', 's_endpgm')): + or name in ('s_waitcnt', 's_nop', 's_waitcnt_vscnt')): + return False + return True + + @staticmethod + def vector_only_instruction(name, asm): + """A vector ALU instruction whose only destination is a VGPR: no SGPR, VCC or EXEC write (a carry-out, a compare, + a readlane), which the guest performs once for the whole wave.""" + if not name.startswith('v_') or name.startswith(('v_cmp', 'v_readlane', 'v_readfirstlane', 'v_writelane', + 'v_div_scale', 'v_mad_u64', 'v_mad_i64')): + return False + if re.match(r'v_(add|sub|subrev)_co|v_addc|v_subb', name): + return False + for tok in destinations(name, parse(asm)[1]): + r = reg_range(tok) + if tok in ('vcc', 'vcc_lo', 'vcc_hi', 'exec', 'exec_lo', 'exec_hi', 'm0') or (r and r[0] == 's'): return False return True @@ -4800,6 +4838,10 @@ def src_sym(t): self.uniform_v.clear() return None self.exec_known = False + if hasattr(self, 'lane_exec_breaks') and not self.exec_write_exact(srcs, syms): + # exec = (expr) & 1 writes every pixel and helper lane alike; the guest enables only the lanes the + # source selects, so the lane's EXEC bit may stop following the guest's from here. + self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) self.emit('%s = (%s) & 1;' % (var, expr)) if scc: self.set_scc(scc.replace('$', var)) From 706fc0846c02089dbbe07720a12f1f4dcf772916 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 08:55:10 +0100 Subject: [PATCH 06/10] fix: refuse a restore of a pre-s_wqm EXEC copy and 32-bit EXEC sources as lane-exact; shader cache revision 23 A mask saved before s_wqm exec, exec has the guest's helper lanes off, while every thread here starts with exec = 1: writing it back is now a lane-exec break. exec_lo / vcc_lo are no longer exact EXEC sources (wave64 keeps lanes 32..63). New refused fixtures restore, restore_helper, discard_break, exec_lo_mask; new inside_y fixture with a mutant that drops the vertical derivative of the vote. The voted branches change the HLSL of programs accepted on main, so the shader cache revision moves to x2w-startup-shader-23 / 23cs. --- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_draw.inl | 4 +- .../startup_compute_request_offline_check.py | 4 +- tests/startup_gfx2hlsl_buffer_store_check.py | 4 +- .../startup_gfx2hlsl_const_copy_join_check.py | 2 +- tests/startup_gfx2hlsl_fract_check.py | 4 +- tests/startup_image_get_lod_flow_check.py | 51 ++++++++++++++++--- tests/startup_image_sample_b_flow_check.py | 49 ++++++++++++++++-- tests/startup_indirect_draw_indexed.cpp | 2 +- ...tartup_packed_position_provenance_check.py | 2 +- tests/startup_resource_retire_title.cpp | 2 +- tests/startup_shader_cache_key_check.py | 6 +-- tools/startup/gfx2hlsl.py | 25 +++++++-- 13 files changed, 127 insertions(+), 30 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8d821d396..7adaac137 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -208,7 +208,7 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -Graphics and compute use cache revisions `x2w-startup-shader-22` and `x2w-startup-shader-22cs`. +Graphics and compute use cache revisions `x2w-startup-shader-23` and `x2w-startup-shader-23cs`. Revision 22 invalidates compute shaders that assumed the entry EXEC mask at a load reached on a later loop iteration after an EXEC write. The two cache keys advance together. Revision 21 refuses a compute lane-mask form that revision 20 translated (`s_and_b32 M, X, exec_lo` with X data). diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 22a8ca313..7ec2cc724 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -353,7 +353,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-22"; + constexpr char revision[] = "x2w-startup-shader-23"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -474,7 +474,7 @@ u64 publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-22cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-23cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index cb5c4c0f5..415dcc7f4 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x5159f6a85d77858e # framed key at revision 22cs +KEY = 0x76dc3fbef14b59e7 # framed key at revision 23cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-22cs': + for b in b'x2w-startup-shader-23cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-22"; + constexpr char revision[] = "x2w-startup-shader-23"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_packed_position_provenance_check.py b/tests/startup_packed_position_provenance_check.py index 03b27c195..ff87a0355 100644 --- a/tests/startup_packed_position_provenance_check.py +++ b/tests/startup_packed_position_provenance_check.py @@ -206,7 +206,7 @@ def refused(label, cache, key, reason): cache = Path(tmp) bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob()) check('without a description the key is unchanged', - bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-22'))))) + bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-23'))))) keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)] check('same stages, root and layout with three mask pairs: three request identities', len(set(keys)) == 3 and bare not in keys diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 4e02039b3..93422b833 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -407,7 +407,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-22"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-23"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py index 670adeb66..f7c61c8c1 100644 --- a/tests/startup_shader_cache_key_check.py +++ b/tests/startup_shader_cache_key_check.py @@ -49,10 +49,10 @@ def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): def main(): # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. - # Revision x2w-startup-shader-22 excludes NUL. Stored order is a, b, root, then optional input layout. + # Revision x2w-startup-shader-23 excludes NUL. Stored order is a, b, root, then optional input layout. vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") - assert gfx2hlsl.pipeline_key(*vector) == 0x30009a5d8295d679 - assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xdae7d34c534837e5 + assert gfx2hlsl.pipeline_key(*vector) == 0x5b4228f0459cf6fc + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0x7f467f3465edf080 blobs = (VERTEX, PIXEL, ROOT) canonical = gfx2hlsl.pipeline_key(*blobs) check_request(blobs, canonical) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 4d17fd3c1..5de310919 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3442,6 +3442,7 @@ def translate(self): self.sym = dict(init_sym) self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec + self.wqm_count, self.execcopy_epoch = 0, {} # True until a wave-divergent branch: SampleBias / CalculateLevelOfDetail need uniform CF. self.uniform_cf = True self.derivative_sites = [] # (offset, name) of image_sample_b / image_get_lod, for the back-edge proof @@ -3909,13 +3910,25 @@ def tid_shift(self, count, source): def pc_index(self): return next((i for i, ins in enumerate(self.ins) if ins[0] == self.pc), None) + def helper_off_copy(self, tok, sym): + """Whether `tok` is a copy of EXEC saved before an `s_wqm_b64 exec, exec`: the guest's entry EXEC leaves the + helper lanes off, while every thread here starts with exec = 1, so writing it back would turn the guest's helper + lanes off (stale VGPRs) and keep the translation's on.""" + r = reg_range(tok) + return bool(r and r[0] == 's' and sym == ('execcopy',) + and getattr(self, 'execcopy_epoch', {}).get(r[1], 0) < getattr(self, 'wqm_count', 0)) + def exec_write_exact(self, srcs, syms): """Whether a scalar EXEC write takes every source from a lane mask (vcc, exec, a saved EXEC or a tagged mask) or from the all-zero / all-ones constants: then each lane's bit is the guest's. Any other source (a mask built from a number such as 1) selects guest lanes the one-lane model cannot tell apart.""" for tok, sym in zip(srcs, syms): r = reg_range(tok) - if tok in ('exec', 'exec_lo', 'vcc', 'vcc_lo') or sym == ('execcopy',) or ( + if self.helper_off_copy(tok, sym): + return False + # The 64-bit forms only: in wave64 a 32-bit write (s_mov_b32 exec_lo, vcc_lo) keeps the old bits of lanes + # 32..63, while the model sets every lane. + if tok in ('exec', 'vcc') or sym == ('execcopy',) or ( r and r[0] == 's' and r[1] in getattr(self, 'masks', ())): continue try: @@ -4336,6 +4349,7 @@ def lower(self, base, asm, ops, mods): if base in ('s_wqm_b32', 's_wqm_b64'): if ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'exec_known', False): self.wqm_exec = True # every lane of a touched quad is now active, helper lanes included + self.wqm_count = getattr(self, 'wqm_count', 0) + 1 if getattr(self, 'wqm_set_at', False) is None: self.wqm_set_at = getattr(self, 'pc', None) # where the quad-read flow proof starts elif hasattr(self, 'lane_exec_breaks'): @@ -5197,6 +5211,8 @@ def src_sym(t): if var == 'exec': copy = base in ('s_mov_b64', 's_mov_b32') and self.exec_known and (syms[0] == ('execcopy',)) if copy: + if hasattr(self, 'lane_exec_breaks') and self.helper_off_copy(srcs[0], syms[0]): + self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) # A restored copy can re-activate lanes a WQM added: drop every VGPR proof. self.wqm_exec = False # and the copy can be older than the WQM if hasattr(self, 'uniform_v'): @@ -5262,6 +5278,9 @@ def known(tok): if base in ('s_mov_b64', 's_mov_b32') and srcs[0] in ('exec', 'exec_lo') and self.exec_known: self.set_s(d, 'exec') self.sym[d] = ('execcopy',) + if not hasattr(self, 'execcopy_epoch'): + self.execcopy_epoch = {} + self.execcopy_epoch[d] = getattr(self, 'wqm_count', 0) # the s_wqm count when the mask was saved self.masks.add(d) if pair: self.sym.pop(d + 1, None) @@ -10198,7 +10217,7 @@ def pipeline_key(vs_code, ps_code, root_blob, layout=b'', ps_inputs=None): SPI_PS_INPUT_ENA and SPI_PS_INPUT_ADDR as little-endian u32. Two pipelines with the same stages, root signature and input layout but different masks are then two requests with their own results. Without a description the key is unchanged.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-22')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-23')))) key = fnv(layout, key) if layout else key return key if ps_inputs is None else fnv(b'psin1' + struct.pack(' Date: Thu, 26 Nov 2026 09:06:24 +0100 Subject: [PATCH 07/10] fix: a 32-bit EXEC write is never lane-exact, even from a constant --- tests/startup_image_get_lod_flow_check.py | 8 ++++++++ tests/startup_image_sample_b_flow_check.py | 8 ++++++++ tools/startup/gfx2hlsl.py | 8 ++++---- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py index 41f86609a..9902cc38a 100644 --- a/tests/startup_image_get_lod_flow_check.py +++ b/tests/startup_image_get_lod_flow_check.py @@ -91,6 +91,9 @@ def branch_on_x(x, delta): (Fraction(-3, 8), Fraction(5, 8))), } REFUSED = { + # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. + 'exec_lo_const': (PROLOGUE + 's_mov_b32 exec_lo, -1\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), # A mask saved before s_wqm exec, exec has the guest's helper lanes off, while every thread here starts # with exec = 1: writing it back is a lane-exec break (review of ef786354). 'restore': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + QUERY + EXPORT, @@ -117,6 +120,11 @@ def branch_on_x(x, delta): } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { + 'exec_lo_const': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003eff02067e0000803e8002187e80021a7ec103febef10404067fc08cbf080380f1020ac400703f' + '8cbf0f1800f80a0b0c0d000081bf' + ), 'inside_y': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' '121210ff1204060000003eff02067e0000803e8002187e80021a7e90000e2c800e847d6a2480be040088bff10404067fc0' diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index b96e79bb9..056b3cb68 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -108,6 +108,9 @@ def branch_on_x(x, delta): } # name: (source, text of the refusal) REFUSED = { + # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. + 'exec_lo_const': (PROLOGUE + 's_mov_b32 exec_lo, -1\nv_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), # A mask saved before s_wqm exec, exec has the guest's helper lanes off, while every thread here starts # with exec = 1: writing it back is a lane-exec break (review of ef786354). 'restore': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_and_b64 exec, exec, s[12:13]\n' + SAMPLE + EXPORT, @@ -149,6 +152,11 @@ def branch_on_x(x, delta): } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { + 'exec_lo_const': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003ef302027eff02067e0000803e0902087ec103febef10404067fc08cbf280f94f0010ac400703f' + '8cbf0f1800f80a0b0c0d000081bf' + ), 'inside_y': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' '121210ff1204060000003ef302027eff02067e0000803e0902087e90000e2c800e847d6a2480be040088bff10404067fc0' diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5de310919..a8cad1aa3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3926,8 +3926,8 @@ def exec_write_exact(self, srcs, syms): r = reg_range(tok) if self.helper_off_copy(tok, sym): return False - # The 64-bit forms only: in wave64 a 32-bit write (s_mov_b32 exec_lo, vcc_lo) keeps the old bits of lanes - # 32..63, while the model sets every lane. + # The 64-bit forms only (see also the exec_lo destination at the call site): in wave64 a 32-bit write + # (s_mov_b32 exec_lo, vcc_lo) keeps the old bits of lanes 32..63, while the model sets every lane. if tok in ('exec', 'vcc') or sym == ('execcopy',) or ( r and r[0] == 's' and r[1] in getattr(self, 'masks', ())): continue @@ -5209,7 +5209,7 @@ def src_sym(t): if dname in ('exec', 'exec_lo', 'vcc', 'vcc_lo'): var = dname[:4].rstrip('_') if dname.startswith('exec') else 'vcc' if var == 'exec': - copy = base in ('s_mov_b64', 's_mov_b32') and self.exec_known and (syms[0] == ('execcopy',)) + copy = base in ('s_mov_b64', 's_mov_b32') and dname == 'exec' and self.exec_known and (syms[0] == ('execcopy',)) if copy: if hasattr(self, 'lane_exec_breaks') and self.helper_off_copy(srcs[0], syms[0]): self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) @@ -5221,7 +5221,7 @@ def src_sym(t): self.align4_v.clear() return None self.exec_known = False - if hasattr(self, 'lane_exec_breaks') and not self.exec_write_exact(srcs, syms): + if hasattr(self, 'lane_exec_breaks') and (dname == 'exec_lo' or not self.exec_write_exact(srcs, syms)): # exec = (expr) & 1 writes every pixel and helper lane alike; the guest enables only the lanes the # source selects, so the lane's EXEC bit may stop following the guest's from here. self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) From 780a8fa0e06fe01791a5264eb6f76bb976abf212 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 09:06:56 +0100 Subject: [PATCH 08/10] test: use the 64-bit EXEC clear where a test expects the derivative proof to survive; refuse the 32-bit one --- tests/startup_gfx2hlsl_image_get_lod_check.py | 4 ++-- tests/startup_image_sample_b_check.py | 16 ++++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tests/startup_gfx2hlsl_image_get_lod_check.py b/tests/startup_gfx2hlsl_image_get_lod_check.py index 89ead9b57..f0508e5ad 100644 --- a/tests/startup_gfx2hlsl_image_get_lod_check.py +++ b/tests/startup_gfx2hlsl_image_get_lod_check.py @@ -58,8 +58,8 @@ def stage(dmask=1, dim=1, branch=False, divergent=False, join=False, cf_op=None, insert += sopp(4, 0) if join: # uniform forward join; every lane still has the entry EXEC at the read insert += (bytes.fromhex('800380be') + bytes.fromhex('008006bf') + sopp(5, 1) + bytes.fromhex('810381be')) - if divergent: # s_mov_b32 exec_lo, 0: the entry-mask proof is gone - insert += bytes.fromhex('8003febe') + if divergent: # s_mov_b64 exec, 0: the entry-mask proof is gone + insert += bytes.fromhex('8004febe') if cf_op is not None: # s_mov; s_cbranch_ +1; s_mov (vcc/exec: divergent CF) insert += bytes.fromhex('800380be') + sopp(cf_op, 1) + bytes.fromhex('810381be') if insert: diff --git a/tests/startup_image_sample_b_check.py b/tests/startup_image_sample_b_check.py index 731b11dbc..552a3aa7c 100644 --- a/tests/startup_image_sample_b_check.py +++ b/tests/startup_image_sample_b_check.py @@ -445,10 +445,11 @@ def with_join_before_sample(data): return data[:off] + join + data[off:] -def with_divergent_exec_before_sample(data): - """Clear exec_lo after the loads so the entry-mask proof is gone before the sample.""" +def with_divergent_exec_before_sample(data, word='8004febe'): + """Clear EXEC after the loads so the entry-mask proof is gone before the sample (s_mov_b64 exec, 0 by default; + 8003febe is s_mov_b32 exec_lo, 0).""" off = next(o for o, _s, _n, a in G.decode(data) if 'image_sample_b' in a) - return data[:off] + bytes.fromhex('8003febe') + data[off:] + return data[:off] + bytes.fromhex(word) + data[off:] def with_branch_before_sample(data, sopp_op): @@ -486,7 +487,14 @@ def controls(): assert 'image_sample_b needs implicit derivatives' in str(error), (label, error) else: raise AssertionError('image_sample_b accepted after %s' % label) - # A cleared EXEC is an exact per-lane write: the quad program (no backward branch) keeps the proof. + # A 64-bit cleared EXEC is an exact per-lane write: the quad program (no backward branch) keeps the proof. The + # 32-bit form keeps lanes 32..63 of the old mask in wave64, so it is refused. + try: + G.Pipeline(VS_WORDS, with_divergent_exec_before_sample(plain, '8003febe'), root_blob()).hlsl_ps() + except G.Unsupported as error: + assert 'image_sample_b needs implicit derivatives' in str(error), error + else: + raise AssertionError('image_sample_b accepted after s_mov_b32 exec_lo, 0') cleared = G.Pipeline(VS_WORDS, with_divergent_exec_before_sample(plain), root_blob()).hlsl_ps() assert 'SampleBias' in cleared and 'exec = (0x00000000u) & 1;' in cleared, cleared print('uniform join before sample_b accepted; divergent EXEC and vcc/exec branches before sample_b refused') From e4b9d1b738911fbb4e3cd7f43c016df88026cd0b Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 09:12:09 +0100 Subject: [PATCH 09/10] test: inside_y keeps u equal in every lane and varies v with y, so only the vertical derivative of the vote carries the LOD --- tests/startup_image_get_lod_flow_check.py | 29 +++++++++++----------- tests/startup_image_sample_b_flow_check.py | 17 +++++++------ 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py index 9902cc38a..e1b514ad8 100644 --- a/tests/startup_image_get_lod_flow_check.py +++ b/tests/startup_image_get_lod_flow_check.py @@ -86,9 +86,10 @@ def branch_on_x(x, delta): (Fraction(-3, 8), Fraction(5, 8))), 'kill': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\ns_cbranch_execnz BB1\ns_endpgm\nBB1:\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, (Fraction(-3, 8), Fraction(5, 8))), - 'inside_y': (PROLOGUE + 'v_lshrrev_b32_e32 v7, 16, v0\nv_cmp_eq_u32_e32 vcc, 0, v7\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' - 'v_add_f32_e32 v2, -0.5, v2\n' + QUERY + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, - (Fraction(-3, 8), Fraction(5, 8))), + # u is the same in every lane and v = 0.25 + 0.5 * y, so the LOD comes from the vertical derivative alone; only the row + # y == 0 enters the block. (u0, u1) is (u of the drawn pixel, u + the footprint along y): 4 * 0.5 = 2, LOD 1 - 1 = 0. + 'inside_y': (PROLOGUE + 'v_mov_b32_e32 v2, 0x3e000000\nv_lshrrev_b32_e32 v7, 16, v0\nv_cvt_f32_u32_e32 v6, v7\nv_mul_f32_e32 v6, 0.5, v6\nv_add_f32_e32 v3, 0x3e800000, v6\nv_cmp_eq_u32_e32 vcc, 0, v7\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\nv_mov_b32_e32 v14, 0\n' + + QUERY + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(1, 8), Fraction(5, 8))), } REFUSED = { # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. @@ -120,16 +121,17 @@ def branch_on_x(x, delta): } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { + 'inside_y': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003eff02067e0000803e8002187e80021a7eff02047e0000003e90000e2c070d0c7ef00c0c10ff0c' + '06060000803e800e847d6a2480be040088bf80021c7e7fc08cbf080380f1020ac4007e00fe88703f8cbf0f1800f80a0b0c' + '0d000081bf' + ), 'exec_lo_const': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' '121210ff1204060000003eff02067e0000803e8002187e80021a7ec103febef10404067fc08cbf080380f1020ac400703f' '8cbf0f1800f80a0b0c0d000081bf' ), - 'inside_y': ( - '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' - '121210ff1204060000003eff02067e0000803e8002187e80021a7e90000e2c800e847d6a2480be040088bff10404067fc0' - '8cbf080380f1020ac4007e00fe88703f8cbf0f1800f80a0b0c0d000081bf' - ), 'restore_helper': ( '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' '0d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e7e0cfe87f10404067fc08cbf080380f1020a' @@ -240,12 +242,11 @@ def mutants(name, hlsl): write = re.search(r'\n\s*if \(exec & 1\) v2 = U\((-0\.5|F\(0x3fc00000u\)) \+ F\(v2\)\);', hlsl) if name.startswith('join'): return [('without the branch write', hlsl.replace(write.group(0), ''))] - if name in ('cmpx', 'inside', 'kill', 'inside_y'): - out = [('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))] - if name == 'inside_y': - # The row that is off in the vote's x direction (y = 1) is only seen through the vertical derivative. - out.append(('vote without the vertical derivative', hlsl.replace('abs(ddy_fine(row))', '0.0'))) - return out + if name in ('cmpx', 'inside', 'kill'): + return [('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))] + if name == 'inside_y': + # The row that is off (y = 1) is only seen through the vertical derivative of the vote. + return [('vote without the vertical derivative', hlsl.replace('abs(ddy_fine(row))', '0.0'))] return [] diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index 056b3cb68..b42fc25eb 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -101,8 +101,10 @@ def branch_on_x(x, delta): + SAMPLE + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), 'kill': (PROLOGUE + CMPX + 's_cbranch_execnz BB1\ns_endpgm\nBB1:\n' + SUB + SAMPLE + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), - 'inside_y': (PROLOGUE + 'v_lshrrev_b32_e32 v7, 16, v0\nv_cmp_eq_u32_e32 vcc, 0, v7\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\n' + SUB - + SAMPLE + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(-3, 8), Fraction(5, 8)), -1), + # u is the same in every lane and v = 0.25 + 0.5 * y, so the LOD comes from the vertical derivative alone; only the row + # y == 0 enters the block. (u0, u1) is (u of the drawn pixel, u + the footprint along y): 4 * 0.5 = 2, LOD 1 - 1 = 0. + 'inside_y': (PROLOGUE + 'v_mov_b32_e32 v2, 0x3e000000\nv_lshrrev_b32_e32 v7, 16, v0\nv_cvt_f32_u32_e32 v6, v7\nv_mul_f32_e32 v6, 0.5, v6\nv_add_f32_e32 v3, 0x3e800000, v6\nv_cmp_eq_u32_e32 vcc, 0, v7\ns_and_saveexec_b64 s[0:1], vcc\ns_cbranch_execz BB1\nv_mov_b32_e32 v14, 0\n' + + SAMPLE + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(1, 8), Fraction(5, 8)), -1), 'uni_loop': (PROLOGUE + 's_mov_b32 s30, 2\nBB1:\n' + SAMPLE + SUB + 's_add_i32 s30, s30, -1\ns_cmp_lg_u32 s30, 0\n' 's_cbranch_scc1 BB1\n' + EXPORT, (Fraction(-3, 8), Fraction(1, 8)), -1), } @@ -152,16 +154,17 @@ def branch_on_x(x, delta): } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { + 'inside_y': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' + '121210ff1204060000003ef302027eff02067e0000803e0902087eff02047e0000003e90000e2c070d0c7ef00c0c10ff0c' + '06060000803e800e847d6a2480be040088bf80021c7e7fc08cbf280f94f0010ac4007e00fe88703f8cbf0f1800f80a0b0c' + '0d000081bf' + ), 'exec_lo_const': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' '121210ff1204060000003ef302027eff02067e0000803e0902087ec103febef10404067fc08cbf280f94f0010ac400703f' '8cbf0f1800f80a0b0c0d000081bf' ), - 'inside_y': ( - '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' - '121210ff1204060000003ef302027eff02067e0000803e0902087e90000e2c800e847d6a2480be040088bff10404067fc0' - '8cbf280f94f0010ac4007e00fe88703f8cbf0f1800f80a0b0c0d000081bf' - ), 'restore_helper': ( '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' '0d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e7e0cfe87f10404067fc08cbf280f94f0010a' From 74e00742d26f454c2a7b7bf284b9d7b11edee63f Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 10:00:34 +0100 Subject: [PATCH 10/10] test: draw the quad vote alone with one lane of the quad set at each position; refuse a mov restore of a pre-s_wqm mask --- tests/startup_image_get_lod_flow_check.py | 11 +++- tests/startup_image_sample_b_flow_check.py | 76 ++++++++++++++++++++-- tools/startup/gfx2hlsl.py | 6 +- 3 files changed, 82 insertions(+), 11 deletions(-) diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py index e1b514ad8..00be477e5 100644 --- a/tests/startup_image_get_lod_flow_check.py +++ b/tests/startup_image_get_lod_flow_check.py @@ -92,6 +92,9 @@ def branch_on_x(x, delta): + QUERY + 'BB1:\ns_or_b64 exec, exec, s[0:1]\n' + EXPORT, (Fraction(1, 8), Fraction(5, 8))), } REFUSED = { + # The plain s_mov_b64 exec, s[N] restore of a mask saved before s_wqm is a lane-exec break too (main accepts the form). + 'restore_mov': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_mov_b64 exec, s[12:13]\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. 'exec_lo_const': (PROLOGUE + 's_mov_b32 exec_lo, -1\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, 'image_get_lod needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), @@ -121,6 +124,11 @@ def branch_on_x(x, delta): } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { + 'restore_mov': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' + '0d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e0c04febef10404067fc08cbf080380f1020a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), 'inside_y': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' '121210ff1204060000003eff02067e0000803e8002187e80021a7eff02047e0000003e90000e2c070d0c7ef00c0c10ff0c' @@ -244,9 +252,6 @@ def mutants(name, hlsl): return [('without the branch write', hlsl.replace(write.group(0), ''))] if name in ('cmpx', 'inside', 'kill'): return [('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))] - if name == 'inside_y': - # The row that is off (y = 1) is only seen through the vertical derivative of the vote. - return [('vote without the vertical derivative', hlsl.replace('abs(ddy_fine(row))', '0.0'))] return [] diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index b42fc25eb..b51aea26b 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -32,8 +32,9 @@ inside the sample inside the s_cbranch_execz block of x == 0, after u -= 0.5 there: the quad enters together, the helper column masked with its stale u: LOD 1 kill v_cmpx keeps x == 0, s_cbranch_execnz past an s_endpgm, u -= 0.5, sample: the quad goes on, LOD 1 - inside_y the same block entered by the row y == 0 only: the rows are told apart by the vertical derivative of the - vote, the other row's lanes follow and the quad stays together: LOD 1 + inside_y u is the same in every lane and v = 0.25 + 0.5 * y: the block is entered by the row y == 0 only, the quad + stays together and the LOD comes from the vertical derivative: LOD 1 - 1 = 0. The vote itself is drawn + alone (VOTE_CASES): one lane of the quad set at each position, and each half of the helper dropped. uni_loop a loop of two passes on a constant SGPR counter (SCC proven uniform): sample, then u -= 0.5 on every lane; the second pass reads u = (-0.375, 0.125), LOD 0 Refused: the sample inside or after a block a VCC branch skips (the guest takes a VCC branch once per wave, with EXEC @@ -110,6 +111,9 @@ def branch_on_x(x, delta): } # name: (source, text of the refusal) REFUSED = { + # The plain s_mov_b64 exec, s[N] restore of a mask saved before s_wqm is a lane-exec break too (main accepts the form). + 'restore_mov': ('s_mov_b64 s[12:13], exec\n' + PROLOGUE + 's_mov_b64 exec, s[12:13]\nv_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, + 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), # A constant 32-bit EXEC write is no more exact than a mask one: lanes 32..63 keep their old bits in wave64. 'exec_lo_const': (PROLOGUE + 's_mov_b32 exec_lo, -1\nv_add_f32_e32 v2, -0.5, v2\n' + SAMPLE + EXPORT, 'image_sample_b needs implicit derivatives: pixel stage with the entry EXEC mask and wave-uniform control flow'), @@ -154,6 +158,11 @@ def branch_on_x(x, delta): } # llvm-mc-19 -arch=amdgcn -mcpu=gfx1013 -mattr=+wavefrontsize64,-wavefrontsize32 of the label-resolved sources WORDS_HEX = { + 'restore_mov': ( + '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff000008' + '0d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087e0c04febef10404067fc08cbf280f94f0010a' + 'c400703f8cbf0f1800f80a0b0c0d000081bf' + ), 'inside_y': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0' '121210ff1204060000003ef302027eff02067e0000803e0902087eff02047e0000003e90000e2c070d0c7ef00c0c10ff0c' @@ -352,6 +361,8 @@ def controls(): G.Stage.derivative_exec_ok = saved # A lane-exec break before the sample keeps it refused: s_wqm of a narrowed EXEC is a no-op in the one-lane model. refused('wqm_break', 'image_sample_b needs implicit derivatives') + # The drawn vote helper is the text the translation emits. + assert '\n'.join(G.QUAD_ANY_HLSL) in pipeline('inside').hlsl_ps() cells = {name: reference(name) for name in FIXTURES} print('image_sample_b after a join, under a v_cmpx EXEC, after a uniform branch, inside an EXEC branch and ' 'past a kill branch: SampleBias; references %s' @@ -376,21 +387,53 @@ def mutants(name, hlsl): out.append(('without the branch write', hlsl.replace(write.group(0), ''))) if name in ('cmpx', 'inside', 'kill'): out.append(('every lane writes u', hlsl.replace(write.group(0), write.group(0).replace('if (exec & 1) ', '')))) - if name == 'inside_y': - # The row that is off in the vote's x direction (y = 1) is only seen through the vertical derivative. - out.append(('vote without the vertical derivative', hlsl.replace('abs(ddy_fine(row))', '0.0'))) out.append(('bias ignored', hlsl.replace(CALL, CALL.replace('F(v1))', '0.0)')))) for label, text in out: assert text != hlsl, (name, label) return out +# The vote helper alone (QUAD_ANY_HLSL, the text the translation emits), drawn on the covered pixel (0, 0): a pixel shader +# whose bit is set on one lane of the quad only. The covered pixel answers 1 for every position of that lane, and each +# half of the helper is the only way to see one of them: the drawn lane is in row 0, column 0, so a lane at (1, 0) is +# seen through ddx_fine and a lane at (0, 1) through ddy_fine, and a lane at (1, 1) through both. Red is the answer. +VOTE_PS = """ +%s +float4 main(float4 pos : SV_Position) : SV_Target { + uint x = (uint)pos.x & 1u, y = (uint)pos.y & 1u; + return float4(x2w_quad_any(%s) ? 1.0 : 0.0, 0.0, 0.0, 1.0); +} +""" +ONE, ZERO = '3f800000,00000000,00000000,3f800000', '00000000,00000000,00000000,3f800000' +# name: (bit of the lane, red answer of the covered pixel); the quad is x, y in {0, 1}^2 +VOTE_CASES = { + 'lane_10': ('(x == 1u && y == 0u) ? 1u : 0u', ONE), + 'lane_01': ('(x == 0u && y == 1u) ? 1u : 0u', ONE), + 'lane_11': ('(x == 1u && y == 1u) ? 1u : 0u', ONE), + 'lane_00': ('(x == 0u && y == 0u) ? 1u : 0u', ONE), + 'none': ('0u', ZERO), +} +# what each case must stop answering when a half of the helper is dropped +VOTE_MUTANTS = { + 'lane_10': ('abs(ddx_fine(lane))', 'without the horizontal derivative'), + 'lane_01': ('abs(ddy_fine(row))', 'without the vertical derivative'), +} + + +def vote_hlsl(bit, mutant=None): + helper = '\n'.join(G.QUAD_ANY_HLSL) + if mutant: + assert mutant in helper, mutant + helper = helper.replace(mutant, '0.0') + return VOTE_PS % (helper, bit) + + def check_draw(dxc, renderer, adapter, fxc=None): compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) def draw(vs, ps, expected, sampler): - run = subprocess.run([renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected, - sampler], capture_output=True, text=True) + run = subprocess.run([renderer, adapter, '--startup-image-2d-array-mips', str(vs), str(ps), '0', expected] + + ([sampler] if sampler else []), capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) sys.exit(77) @@ -422,6 +465,25 @@ def draw(vs, ps, expected, sampler): seen.append('%s -> %s' % (label, got.group(1))) print('%s %s %s: GPU == CPU reference %s; %s' % (adapter, kind, name, want, '; '.join(seen)), flush=True) + for name, (bit, want) in VOTE_CASES.items(): + ps = compile_hlsl(compiler, kind, vote_hlsl(bit), 'vote_%s_%s' % (name, kind), ps_profile, directory) + run = draw(vs, ps, want, None) + if run.returncode: + raise AssertionError('%s %s vote %s: GPU differs from the CPU reference %s\n%s%s' + % (adapter, kind, name, want, run.stdout, run.stderr)) + seen = [] + if name in VOTE_MUTANTS: + cut, label = VOTE_MUTANTS[name] + ps = compile_hlsl(compiler, kind, vote_hlsl(bit, cut), 'vote_%s_m_%s' % (name, kind), + ps_profile, directory) + run = draw(vs, ps, want, None) + got = re.search(r'actual=(\S+)', run.stderr) + if run.returncode == 0 or not got: + raise AssertionError('%s %s vote %s: the helper %s matched the reference\n%s%s' + % (adapter, kind, name, label, run.stdout, run.stderr)) + seen.append('%s -> %s' % (label, got.group(1))) + print('%s %s vote %s: GPU == CPU reference %s; %s' % (adapter, kind, name, want, '; '.join(seen)), + flush=True) def main(): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fce8a1047..48f728c2c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3508,6 +3508,7 @@ def translate(self): self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.wqm_count, self.execcopy_epoch = 0, {} + self.helper_restore = False # True until a wave-divergent branch: SampleBias / CalculateLevelOfDetail need uniform CF. self.uniform_cf = True self.derivative_sites = [] # (offset, name) of image_sample_b / image_get_lod, for the back-edge proof @@ -4092,7 +4093,9 @@ def derivative_exec_ok(self): lane-exec break happened: an s_wqm of a narrowed EXEC (a no-op here, while the guest turns on the lanes of every touched quad) or a discard under an unknown EXEC. The callers also need uniform_cf, which a branch that parts a quad clears; an EXEC branch decided per quad (quad_vote) does not.""" - return self.exec_known or (getattr(self, 'quad_exec', False) and not getattr(self, 'lane_exec_breaks', None)) + # A restored pre-s_wqm mask (helper_restore) is the entry mask, but the guest's helper lanes are off from here. + return ((self.exec_known and not getattr(self, 'helper_restore', False)) + or (getattr(self, 'quad_exec', False) and not getattr(self, 'lane_exec_breaks', None))) def uniform_source(self, tok): r = reg_range(tok) @@ -5397,6 +5400,7 @@ def src_sym(t): if copy: if hasattr(self, 'lane_exec_breaks') and self.helper_off_copy(srcs[0], syms[0]): self.lane_exec_breaks.append((self.pc, '%s %s' % (base, ', '.join(ops)))) + self.helper_restore = True # A restored copy can re-activate lanes a WQM added: drop every VGPR proof. self.wqm_exec = False # and the copy can be older than the WQM if hasattr(self, 'uniform_v'):