From b2a1957d42110d2dfda983bc98ef0d4c6cd861cb Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 05:29:45 +0100 Subject: [PATCH 1/8] 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 9d345680f9..ff0c962d20 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 7c6a5415dc..c486db55f5 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 70475ee591..89ead9b575 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 0000000000..b7e5835408 --- /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 d398e86761..540ae3c9a3 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 0000000000..ec6d0b4204 --- /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 f33c70de3b..526f6bbeaf 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 2/8] 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 b7e5835408..9f5c96bf55 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 ec6d0b4204..130f59083d 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 08962c342a..f342b14721 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 3/8] 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 9f5c96bf55..493e37cde8 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 130f59083d..536d4b839d 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 4/8] 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 536d4b839d..92d47761e7 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 f342b14721..ec330f2d48 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 213847be273b266e386dcb928c5bcbc0d1379eb4 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 06:31:30 +0100 Subject: [PATCH 5/8] startup: lower s_wqm exec, exec on a narrowed EXEC as a quad vote --- tests/startup_image_get_lod_flow_check.py | 8 +++++ tests/startup_image_sample_b_flow_check.py | 35 +++++++++------------- tools/startup/gfx2hlsl.py | 7 +++++ 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/tests/startup_image_get_lod_flow_check.py b/tests/startup_image_get_lod_flow_check.py index 493e37cde8..cf879c9876 100644 --- a/tests/startup_image_get_lod_flow_check.py +++ b/tests/startup_image_get_lod_flow_check.py @@ -90,6 +90,9 @@ def branch_on_x(x, delta): # 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))), + # s_wqm exec, exec on a narrowed EXEC turns the whole quad back on (see tests/startup_image_sample_b_flow_check.py). + 'wqm': (PROLOGUE + 'v_cmpx_eq_u32_e32 0, v8\ns_wqm_b64 exec, exec\nv_add_f32_e32 v2, -0.5, v2\n' + QUERY + EXPORT, + (Fraction(-3, 8), Fraction(1, 8))), } REFUSED = { 'vcc_inside': (PROLOGUE + 'v_cmp_eq_u32_e32 vcc, 0, v8\ns_cbranch_vccz BB1\n' + QUERY + 'BB1:\n' + EXPORT, @@ -143,6 +146,9 @@ def branch_on_x(x, delta): 'restore': ( '7e048cbe7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e7e0cfe877fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' ), + 'wqm': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003eff02067e0000803e8002187e80021a7e8010a47d7e0afebef10404067fc08cbf080380f1020ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } CALL = ('t = float4(r0.CalculateLevelOfDetail(q0, float2(F(v2), F(v3))), ' 'r0.CalculateLevelOfDetailUnclamped(q0, float2(F(v2), F(v3))), 0.0, 0.0);') @@ -199,6 +205,8 @@ 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 == 'wqm': + return [('s_wqm as a no-op', hlsl.replace('exec = x2w_quad_any(exec) ? 1u : 0u;', ''))] return [] diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index 92d47761e7..7e220ba596 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -15,7 +15,8 @@ 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 +uniform_cf holds and no lane-exec break (a discard under an unknown EXEC, an s_wqm of other operands) came first. +s_wqm_b64 exec, exec on a narrowed EXEC is the same vote written back to EXEC (exec = x2w_quad_any(exec) ? 1u : 0u). 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 @@ -105,6 +106,9 @@ def branch_on_x(x, delta): # 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), + # s_wqm exec, exec on a narrowed EXEC turns the whole quad back on: every lane takes the subtraction (u1 = 1/8, not 5/8). + 'wqm': (PROLOGUE + CMPX + 's_wqm_b64 exec, exec\n' + SUB + SAMPLE + EXPORT, + (Fraction(-3, 8), Fraction(1, 8)), -1), } # name: (source, text of the refusal) REFUSED = { @@ -116,17 +120,6 @@ def branch_on_x(x, delta): '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'), - # 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'), - # 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 = { @@ -160,11 +153,6 @@ def branch_on_x(x, delta): 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d010089bf000081bff10404067fc08cbf' '280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' ), - 'wqm_break': ( - '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' - 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d7e0afebef10404067fc08cbf280f94f0' - '010ac400703f8cbf0f1800f80a0b0c0d000081bf' - ), 'uni_loop': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e82039ebe7fc08cbf280f94f0010ac400f1040406' @@ -194,6 +182,11 @@ def branch_on_x(x, delta): 'bias_per_lane': ( '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127ef0121210ff1204060000003ef302027eff02067e0000803e0902087ef2021c7e8010847d011d02028010847d6a2480be010088bff10404067e00fe887fc08cbf280f94f0010ac400703f8cbf0f1800f80a0b0c0d000081bf' ), + 'wqm': ( + '7e0afebe04040cf4000000fa800398beff0399be00002000ff039abe0000000480039bbeff001036ffff0000080d127e' + 'f0121210ff1204060000003ef302027eff02067e0000803e0902087e8010a47d7e0afebef10404067fc08cbf280f94f0' + '010ac400703f8cbf0f1800f80a0b0c0d000081bf' + ), } BRANCH = re.compile(r'^(s_c?branch\w*) (BB\d+)$') @@ -274,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), ('restore', 0)): + for name, votes in (('inside', 1), ('kill', 1), ('cmpx', 0), ('join_pixel', 1), ('join_helper', 1), ('scc', 0), ('restore', 0), ('wqm', 1)): 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. @@ -285,13 +278,11 @@ def controls(): 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') + print('refused: inside or after a block a VCC branch skips, in a VCC loop') def check_binary(llvm_mc): @@ -311,6 +302,8 @@ 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 == 'wqm': + out.append(('s_wqm as a no-op', hlsl.replace('exec = x2w_quad_any(exec) ? 1u : 0u;', ''))) out.append(('bias ignored', hlsl.replace(CALL, CALL.replace('F(v1))', '0.0)')))) for label, text in out: assert text != hlsl, (name, label) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f9a961c59d..f78ebe1dd5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3780,6 +3780,13 @@ 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 (ops[0] in ('exec', 'exec_lo') and ops[1:] == ops[:1] and getattr(self, 'quad_exec', False) + and getattr(self, 'uniform_cf', False) and not getattr(self, 'lane_exec_breaks', None)): + # s_wqm exec, exec on a narrowed EXEC: every lane of a quad with an active lane turns on. Exact in the + # one-lane model as a vote of the four lanes' bits (the quad runs this statement together while + # uniform_cf holds and no lane's EXEC bit has already left the guest's). + self.emit('exec = x2w_quad_any(exec) ? 1u : 0u;') + self.uses_quad_vote = True 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. From 846b2aa27c6fa7f3cfee9924854c7247e7cae4e2 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Thu, 26 Nov 2026 06:31:36 +0100 Subject: [PATCH 6/8] docs: the s_wqm vote of a narrowed EXEC --- docs/experiments.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 86feb9b5cc..8da400b97a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -17030,9 +17030,10 @@ with such an op and no backward branch now decides its `s_cbranch_execz` / `s_cb (`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 +and no lane-exec break (a discard under an unknown EXEC, an `s_wqm` with other operands) 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. +such a branch. `s_wqm_b64 exec, exec` on a narrowed EXEC turns every lane of a quad with an active lane on; it is +lowered as `exec = x2w_quad_any(exec) ? 1u : 0u;`, the same vote written back to EXEC. `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. From 9d8ca262d0eac460c74f2218959da49b79efc951 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 07:10:55 +0100 Subject: [PATCH 7/8] tests: restore the scalar_in_block and bias_per_lane refused fixtures of the sample_b flow check --- tests/startup_image_sample_b_flow_check.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/startup_image_sample_b_flow_check.py b/tests/startup_image_sample_b_flow_check.py index 7e220ba596..66b3e09ba1 100644 --- a/tests/startup_image_sample_b_flow_check.py +++ b/tests/startup_image_sample_b_flow_check.py @@ -120,6 +120,15 @@ def branch_on_x(x, delta): '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'), + # 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'), + # 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 = { From 1b7ae02004ae0ea6e3615895f10911aff5f22fb3 Mon Sep 17 00:00:00 2001 From: c1 Date: Thu, 26 Nov 2026 07:28:20 +0100 Subject: [PATCH 8/8] 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 92d47761e7..ec0171425c 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 01e831df25..525a7a26c1 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))