diff --git a/CMakeLists.txt b/CMakeLists.txt index a2c7fd6526..f31e857a52 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3493,6 +3493,10 @@ if(EXISTS "${INTAKE_PYTHON}") # refusals of every other DPP control. The draws are registered below. add_test(NAME startup_gfx2hlsl_dpp_pair COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_pair_check.py") + # DPP16 quad reads in a pixel program with a uniform loop and branch: the whole-program convergence proof and its + # refusals (vccz loop, SCC from a lane mask, EXEC write reaching the read, late s_wqm). The draws are below. + add_test(NAME startup_gfx2hlsl_dpp_quad_flow COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_flow_check.py") # DPP16 quad broadcasts quad_perm:[k,k,k,k] (#2125): lowered to QuadReadLaneAt, so the pixel stage compiles as # ps_6_0; the controls and refusals run here, the draws below compare every pixel with a CPU reference. add_test(NAME startup_gfx2hlsl_dpp_quad_broadcast COMMAND "${INTAKE_PYTHON}" -B @@ -3943,6 +3947,14 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_dpp_pair_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl DPP16 quad reads (swap, broadcast, pair) inside a uniform scalar loop with an if: 16 x 16 pixels against + # a CPU reference of the per-pass neighbour words; a read taking the wrong lane must fail. DXC ps_6_0 only. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_dpp_quad_flow_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_flow_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_dpp_quad_flow_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl lowers DPP16 quad swaps (quad_perm [1,0,3,2], [2,3,0,1], [3,2,1,0]) in a pixel stage to QuadReadAcross*. add_test(NAME startup_gfx2hlsl_dpp_quad_swap_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_dpp_quad_swap_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 57605f7ed1..f6e090fc75 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2077,7 +2077,7 @@ These are measured on one executable; treat them as hypotheses for others. `row_mask:0xf bank_mask:0xf`, and `bound_ctrl` since no source lane is disabled) lower on any VOP1 or VOP2 whose first source is a VGPR. The four lanes of the quad are read with the shader model 6.0 `QuadReadLaneAt` and the lane `quad_perm` names is selected by the parity of `SV_Position`; a stage that uses it compiles with DXC `ps_6_0` (`X2W_DXC`), and the result goes through a scratch register so a second source naming the same register keeps the pixel's own word. The form needs the four lanes of a quad to run together, as in a pixel - shader with helper lanes, proved by `s_wqm_b64 exec, exec` on the entry mask (a restored exact mask loses the proof): vertex stages, branches and a changed EXEC are refused, as are `row_*`, `wave_*`, partial masks and `fi`. Run + shader with helper lanes, proved by `s_wqm_b64 exec, exec` on the entry mask (a restored exact mask loses the proof): vertex stages and a changed EXEC are refused (branches and loops: see below), as are `row_*`, `wave_*`, partial masks and `fi`. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_pair"`: the controls model a quad on the CPU, and the draws on WARP and hardware compare 16 x 16 pixels of every pattern with a reference written from the lane table, with wrong-lane, own-lane, transposed-lane-index and permuted-second-source translations as failing controls. @@ -2093,6 +2093,15 @@ These are measured on one executable; treat them as hypotheses for others. check the translation and every refusal, and the draws on WARP and hardware compare all 256 pixels of two fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. [#2125](https://github.com/R0Y00/Xbox2Windows/issues/2125) +- **DPP quad reads in branches and loops.** The quad swaps, broadcasts and pair broadcasts above also lower in a pixel + program with branches or loops when a whole-program check proves that the four threads of the quad reach the read + together: the `s_wqm exec, exec` runs before every branch and target, no other EXEC write can reach the read (an + exact-mask restore after the last read is fine), and every conditional branch that can reach it is wave-uniform + (SCC proven uniform; `s_cbranch_execz`/`execnz` under the whole-quad mask). A `vccz`/`vccnz` loop, SCC taken from a + lane mask, an EXEC write inside the loop and a late `s_wqm` are refused with the offset that breaks the proof. No + wave size is assumed. Run `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_flow"`: the draws on + WARP and hardware run swap, broadcast and pair reads inside a five-pass scalar loop with an `if`, compare 16 x 16 + pixels with a CPU reference, and require wrong-lane translations to fail. - **Soft asserts.** Retail code keeps `int3` instructions followed by a continuation. Without a debugger the title's handler steps over them; under the startup debugger use `-ContinueAsserts N`. One of them fires about ten times a second in the texture-streaming path diff --git a/tests/startup_gfx2hlsl_dpp_quad_flow_check.py b/tests/startup_gfx2hlsl_dpp_quad_flow_check.py new file mode 100644 index 0000000000..27377b3201 --- /dev/null +++ b/tests/startup_gfx2hlsl_dpp_quad_flow_check.py @@ -0,0 +1,297 @@ +"""DPP16 quad reads in a pixel program with branches and loops (tools/startup/gfx2hlsl.py), read back from a real +D3D12 draw. + + (no arguments) translation controls and refusals, pure Python + binary assemble the fixture sources with LLVM (gfx1013) and compare with the words here + draw [fxc] + compile the translated pixel stage with DXC ps_6_0 (quad reads need shader + model 6.0; the optional fxc argument is accepted and ignored), draw 16 x 16 + pixels and compare every pixel with the CPU reference below + +The translator runs each guest lane as its own HLSL thread and turns branches into a pc dispatch loop. A quad read +(QuadReadAcross*, QuadReadLaneAt) gives the neighbour's word only when the four threads of the quad reach it together +with the words the four guest lanes hold. The guest wave runs as one, so this holds when every branch on a path to +the read is wave-uniform and EXEC is still the whole-quad mask of the entry s_wqm exec, exec. The translator proves +that over the whole program after translation (Stage.quad_flow_refusals) and refuses the read otherwise: a vccz/vccnz +loop, an SCC taken from a lane mask, an EXEC write that can reach the read (also around a loop back edge), and an +s_wqm that does not run before every branch. No wave size is assumed: the quad operations need only the 2 x 2 quad. + +The draw fixture LOOP is the shape of a uniform loop over a scalar counter with an if inside it: + s_mov_b64 s[4:5], exec ; s_wqm_b64 exec, exec entry: save the exact mask, whole quads on + v1 = (x | y << 16) * 0x9b5d ; v2 = v3 = v5 = 0 ; s0 = 0 + loop: k = s0 = 0 .. 4 + v2 += quad_perm:[1,0,3,2] v1 the pixel at x ^ 1 + v3 += quad_perm:[2,2,2,2] v1 lane 2 of the quad, pixel (x & ~1, y | 1) + if (s0 != 2) { v4 = quad_perm:[0,0,2,2] v1 ; v5 ^= v4 } pixel (x & ~1, y), skipped on pass 2 + v1 += 0x101 ; s0 += 1 ; loop while s0 < 5 + s_and_b64 exec, exec, s[4:5] ; exp mrt0 v2, v3, v5, v1 +So the neighbour word read on pass k is w(neighbour) + k * 0x101 and the reference below sums or XORs it with plain +integers. The EXEC restore after the loop does not reach any read and is allowed. Mutations of the translated text +(each of the three reads taking the wrong lane) must fail the same draw. +""" +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble # noqa: E402 +from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, compile_hlsl, root_blob # noqa: E402 + +MASK = 0xffffffff +WIDTH = HEIGHT = 16 +MULTIPLIER = 0x9b5d +STEP, PASSES, SKIPPED = 0x101, 5, 2 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +failures = [] + +# name -> (source with numeric branch offsets, words assembled by llvm-mc 19 for gfx1013) +FIXTURES = { + 'LOOP': ('''s_mov_b64 s[4:5], exec +s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_mov_b32_e32 v3, 0 +v_mov_b32_e32 v5, 0 +s_mov_b32 s0, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_dpp v3, v1, v3 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf +s_cmp_eq_u32 s0, 2 +s_cbranch_scc1 3 +v_mov_b32_dpp v4, v1 quad_perm:[0,0,2,2] row_mask:0xf bank_mask:0xf +v_xor_b32_e32 v5, v4, v5 +v_add_nc_u32_e32 v1, 0x101, v1 +s_add_u32 s0, s0, 1 +s_cmp_lt_u32 s0, 5 +s_cbranch_scc1 -14 +s_and_b64 exec, exec, s[4:5] +exp mrt0 v2, v3, v5, v1 done vm +s_endpgm +''', '7e0484be7e0afebeff0002165d9b00008002047e8002067e80020a7e800380befa04044a01b100fffa06064a01aa00ff008206bf030085bf' + 'fa02087e01a000ff040b0a3aff02024a010100000081008000850abff2ff85bf7e04fe870f1800f802030501000081bf'), + 'VCC_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_e32 v1, 3, v1 +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_cbranch_vccnz -6 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047efa04044a01b100ff8302024aff02887d00010000faff87bf0f1800f802010000000081bf'), + 'MASK_SCC_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_add_nc_u32_e32 v1, 3, v1 +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_and_b64 s[2:3], vcc, exec +s_cbranch_scc1 -7 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047efa04044a01b100ff8302024aff02887d000100006a7e8287f9ff85bf0f1800f802010000000081bf'), + 'EXEC_IN_LOOP': ('''s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_e32 v2, 0 +s_mov_b32 s0, 0 +v_add_nc_u32_dpp v2, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf +v_cmp_gt_u32_e32 vcc_lo, 0x100, v1 +s_and_saveexec_b64 s[4:5], vcc +v_add_nc_u32_e32 v1, 3, v1 +s_or_b64 exec, exec, s[4:5] +s_add_u32 s0, s0, 1 +s_cmp_lt_u32 s0, 4 +s_cbranch_scc1 -10 +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '7e0afebeff0002165d9b00008002047e800380befa04044a01b100ffff02887d000100006a2484be8302024a7e04fe880081008000840abf' + 'f6ff85bf0f1800f802010000000081bf'), + 'WQM_AFTER_BRANCH': ('''s_mov_b32 s0, 0 +s_cmp_eq_u32 s0, 0 +s_cbranch_scc1 1 +v_mov_b32_e32 v0, 1 +s_wqm_b64 exec, exec +v_mul_u32_u24_e32 v1, 0x9b5d, v0 +v_mov_b32_dpp v2, v1 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf +exp mrt0 v2, v1, v0, v0 done vm +s_endpgm +''', '800380be008006bf010085bf8102007e7e0afebeff0002165d9b0000fa02047e010000ff0f1800f802010000000081bf'), +} +REFUSALS = { + 'VCC_LOOP': 's_cbranch_vccnz at +0x24 is not proven wave-uniform', + 'MASK_SCC_LOOP': 's_cbranch_scc1 at +0x28 is not proven wave-uniform', + 'EXEC_IN_LOOP': 'the EXEC write at +0x24 reaches it', + 'WQM_AFTER_BRANCH': 'the s_wqm exec, exec does not run before every branch', +} + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH ' + detail[:2000])) + if not ok: + failures.append(label) + + +def words(name): + return bytes.fromhex(FIXTURES[name][1]) + + +def translate(name): + try: + return G.Pipeline(VS_WORDS, words(name), root_blob(), ps_hw_inputs=PACKED).hlsl_ps(), None + except G.Unsupported as reason: + return None, str(reason) + + +# ---- CPU reference ---------------------------------------------------------------------------------------------------- +def word(x, y): + return ((x | (y << 16)) * MULTIPLIER) & MASK + + +def image(): + out = [] + for y in range(HEIGHT): + for x in range(WIDTH): + swap = sum(word(x ^ 1, y) + k * STEP for k in range(PASSES)) & MASK + broadcast = sum(word(x & ~1, y | 1) + k * STEP for k in range(PASSES)) & MASK + pair = 0 + for k in range(PASSES): + if k != SKIPPED: + pair ^= (word(x & ~1, y) + k * STEP) & MASK + out += [swap, broadcast, pair, (word(x, y) + PASSES * STEP) & MASK] + return out + + +# ---- mutations of the translated text --------------------------------------------------------------------------------- +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new) + + +def swap_own(text): + return replace_once(text, 'QuadReadAcrossX(v1)', 'v1') + + +def broadcast_lane1(text): + return replace_once(text, 'QuadReadLaneAt(v1, 2u)', 'QuadReadLaneAt(v1, 1u)') + + +def pair_own(text): + chain = re.compile(r'x2w_lane == 0u \? x2w_q\d : x2w_lane == 1u \? x2w_q\d : x2w_lane == 2u \? x2w_q\d : x2w_q\d;') + assert len(chain.findall(text)) == 1 + return chain.sub('x2w_lane == 0u ? x2w_q0 : x2w_lane == 1u ? x2w_q1 : x2w_lane == 2u ? x2w_q2 : x2w_q3;', text) + + +MUTATIONS = {'swap reads its own lane': swap_own, 'broadcast reads lane 1': broadcast_lane1, + 'pair keeps every lane': pair_own} + + +# ---- controls --------------------------------------------------------------------------------------------------------- +def controls(): + text, reason = translate('LOOP') + check('LOOP translates (uniform scalar loop and if, quad reads inside)', text is not None, str(reason)) + if text is not None: + check('LOOP keeps the pc dispatch loop', '[loop] for' in text, text) + check('LOOP reads the quad: X swap, lane-2 broadcast, four-lane pair read', + 'QuadReadAcrossX(v1)' in text and 'QuadReadLaneAt(v1, 2u)' in text and text.count('QuadReadLaneAt(v1, ') == 5, + text) + for how, mutate in MUTATIONS.items(): + check('LOOP %s mutation changes the text' % how, mutate(text) != text) + for name, expected in REFUSALS.items(): + text, reason = translate(name) + check('%s refused: %s' % (name, expected), text is None and reason is not None and expected in reason, + str(reason)) + reference = image() + own = [v for y in range(HEIGHT) for x in range(WIDTH) + for v in (sum(word(x, y) + k * STEP for k in range(PASSES)) & MASK,) * 2 + (0, 0)] + check('reference differs from a lane-local reading', reference[0::4] != own[0::4] and reference[1::4] != own[1::4]) + # A dead quad read behind an early s_endpgm in a branch-free program has no branch to prove: no crash. + dead = bytes.fromhex('7e0afebeff0002165d9b00008002047e000081bffa04044a01b100fffa02087e01a000ff000081bf') + try: + G.Pipeline(VS_WORDS, dead, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + check('dead quad read after s_endpgm translates without a crash', True) + except G.Unsupported as reason: + check('dead quad read after s_endpgm translates without a crash', True, str(reason)) + except Exception as error: # noqa: BLE001 - the regression is an unexpected exception type + check('dead quad read after s_endpgm translates without a crash', False, repr(error)) + # A straight-line program with the same reads still translates as before. + straight = bytes.fromhex('7e0afebeff0002165d9b0000fa02047e01b100ff0f1800f802010000000081bf') + try: + G.Pipeline(VS_WORDS, straight, root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + check('straight-line quad swap still translates', True) + except G.Unsupported as reason: + check('straight-line quad swap still translates', False, str(reason)) + + +# ---- draw ------------------------------------------------------------------------------------------------------------- +def words_file(directory, name, values): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(values), *values)) + return path + + +def draw(renderer, adapter, vs, ps, expected): + run = subprocess.run([renderer, adapter, '--startup-pixel-words', str(vs), str(ps), str(WIDTH), str(HEIGHT), + str(expected)], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(1 if failures else 77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + text, reason = translate('LOOP') + if text is None: + check('LOOP translates for the draw', False, str(reason)) + return + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'vs_dxc', 'vs_6_0', directory) + reference = words_file(directory, 'reference', image()) + ps = compile_hlsl(dxc, 'dxc', text, 'ps_loop', 'ps_6_0', directory) + run = draw(renderer, adapter, vs, ps, reference) + print(' ' + ' '.join(ln for ln in run.stdout.splitlines() + if ln.startswith(('backend=', 'adapter=', 'driver=', 'debug_errors=')))) + check('dxc %s LOOP: all %d pixels match the reference' % (adapter, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, run.stdout + run.stderr) + for how, mutate in MUTATIONS.items(): + bad = compile_hlsl(dxc, 'dxc', mutate(text), 'ps_' + how.replace(' ', '_'), 'ps_6_0', directory) + run = draw(renderer, adapter, vs, bad, reference) + lines = [ln for ln in run.stderr.splitlines() if 'pixel' in ln] + check('dxc %s LOOP %s mutation fails against the reference: %s' % (adapter, how, ' / '.join(lines)), + run.returncode != 0 and bool(lines) and lines[0].startswith('pixel mismatch'), run.stdout + run.stderr) + + +def check_binary(llvm_mc): + for name, (source, hexwords) in FIXTURES.items(): + check('llvm-mc assembles the %s fixture to the same words' % name, + assemble(llvm_mc, source) == bytes.fromhex(hexwords)) + + +def main(): + if len(sys.argv) == 1: + controls() + else: + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + controls() + check_draw(*args) + else: + raise SystemExit(__doc__) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ab5eed675e..72cf684402 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2996,6 +2996,9 @@ def translate(self): self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant self.has_branches = bool(targets) + self.quad_flow_reads = [] # (offset, mnemonic) of DPP quad reads lowered in a program with branches + self.divergent_branches = {} # s_cbranch offset -> mnemonic, for branches not proven wave-uniform + self.wqm_set_at = None # offset of the s_wqm exec, exec that proved whole-quad EXEC first self.spill_slots = {} # (vgpr, lane) -> (sym, uniform) for constant-lane SGPR spills self.vcc_events = {} self.entry_table_pointers = { @@ -3163,6 +3166,7 @@ def translate(self): if not cond_uniform: # Divergent CF: later SampleBias / CalculateLevelOfDetail would see uneven quads. self.uniform_cf = False + self.divergent_branches[off] = base b_target = int(parse(asm)[1][0].split('_')[1], 16) regs, affected = div_targets.get(off, (set(), set())) regs = {r for r in regs if isinstance(r, int)} @@ -3218,6 +3222,12 @@ def translate(self): refusals.append((reason, self.kind)) if self.lines: self.blocks.append((start, self.lines, None)) + for at, reason in self.quad_flow_refusals(branches, targets): + if refusals is None: + error = Unsupported(reason) + error.instruction = names[at] + raise error + refusals.append((reason, self.kind)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) if set(scc_effects.values()) - {'emitted'}: for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): @@ -3457,6 +3467,78 @@ def one(self, name, asm): expr) return term + def quad_flow_straight(self): + """Whether a DPP quad read sits in straight-line code (the quad intrinsics then run in uniform flow).""" + return not getattr(self, 'has_branches', True) and not getattr(self, 'blocks', []) + + def quad_flow_allowed(self): + """Whether a DPP quad read in a pixel program with branches or loops may be lowered now and proven over the + whole program after translation (Stage.quad_flow_refusals). Unit probes without translate() cannot.""" + return getattr(self, 'kind', None) == 'ps' and getattr(self, 'quad_flow_reads', None) is not None + + def note_quad_flow(self, base): + if not self.quad_flow_straight() and getattr(self, 'quad_flow_reads', None) is not None: + self.quad_flow_reads.append((self.pc, base)) + + def quad_flow_refusals(self, branches, targets): + """[(offset, reason)] for DPP quad reads lowered in a pixel program with branches or loops. + + The one-lane model runs each lane as its own HLSL thread through the pc dispatch, so the QuadReadLaneAt / + QuadReadAcross* of a lane reads its neighbours only when all four threads of the quad reach that statement + together (same block, same pass of the dispatch loop) with the word the guest lanes hold. The guest runs + the wave as one: its scalar branches are wave-wide, and the quad is whole when EXEC is the s_wqm mask. A + read is kept when, on every path to it: + - the s_wqm exec, exec that proved whole-quad EXEC ran first: it sits before every branch and target; + - no other instruction that can write EXEC reaches it (so EXEC is still that mask and every VGPR write ran + on all four lanes, helper lanes included); + - every conditional branch that reaches it is wave-uniform (SCC proven uniform by the translator), or an + execz/execnz branch, whose EXEC is the whole-quad mask by the rule above and so never taken. A vccz/vccnz + branch, or SCC from lane data, can split a quad, and the read is refused. + Then the four threads ran the same branch outcomes, so they are in the same block on the same dispatch + pass. No wave size is assumed: the SM 6.0 quad operations need only the 2x2 quad of four lanes.""" + reads = getattr(self, 'quad_flow_reads', []) + if not reads: + return [] + index, block_of, succ, _dom, _writes, _reached = self.flow + after = {} + + def reaches(src, dst): + a, b = index[src], index[dst] + if block_of[a] == block_of[b] and a < b: + return True + start = block_of[a] + if start not in after: + seen, todo = set(), list(succ[start]) + while todo: + blk = todo.pop() + if blk not in seen: + seen.add(blk) + todo += succ[blk] + after[start] = seen + return block_of[b] in after[start] + # No branch or target (a dead read behind an early s_endpgm): nothing for the s_wqm to precede. + first = min([off for off, _ in branches] + list(targets), default=float('inf')) + writers = [off for off, _n, name, asm in self.ins if writes_exec(name, parse(asm)[1]) + and not (re.sub(r'_e(32|64)$', '', name) in ('s_wqm_b32', 's_wqm_b64') + and parse(asm)[1] in (['exec', 'exec'], ['exec_lo', 'exec_lo']))] + out = [] + for at, base in reads: + if self.wqm_set_at is None or self.wqm_set_at >= first: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: the s_wqm exec, exec does not ' + 'run before every branch' % (base, at))) + continue + writer = next((w for w in writers if reaches(w, at)), None) + if writer is not None: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: the EXEC write at +0x%x reaches ' + 'it' % (base, at, writer))) + continue + split = next((b for b, name in sorted(self.divergent_branches.items()) + if name not in ('s_cbranch_execz', 's_cbranch_execnz') and reaches(b, at)), None) + if split is not None: + out.append((at, '%s_dpp quad read at +0x%x in a program with branches: %s at +0x%x is not proven ' + 'wave-uniform' % (base, at, self.divergent_branches[split], split))) + return out + def dpp_pair(self, base, asm, ops, mods): """A DPP16 spelling whose SRC0 is a quad pair broadcast (#2125 item C). @@ -3480,7 +3562,7 @@ def dpp_pair(self, base, asm, ops, mods): perm = tuple(int(c) for c in re.findall(r'\d', perms[0])) if perm not in DPP_PAIR: raise Unsupported('%s_dpp with %s' % (base, perms[0])) - if (self.kind != 'ps' or getattr(self, 'has_branches', True) or not getattr(self, 'exec_known', False) or + if (self.kind != 'ps' or not (self.quad_flow_straight() or self.quad_flow_allowed()) or not getattr(self, 'exec_known', False) or not getattr(self, 'wqm_exec', False) or getattr(self, 'fetched', False)): raise Unsupported('%s_dpp %s outside straight-line pixel code with a whole-quad exec mask (s_wqm exec, exec)' % (base, perms[0])) @@ -3492,6 +3574,7 @@ def dpp_pair(self, base, asm, ops, mods): if not src: raise Unsupported('%s_dpp source %s' % (base, ops[1])) word = self.u('v%s' % src.group(2)) # records the original source as a used VGPR + self.note_quad_flow(base) self.needs_sm6 = True self.used_v.add(DPP_SCRATCH) self.uniform_v.discard(DPP_SCRATCH) @@ -3554,6 +3637,8 @@ 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 + if getattr(self, 'wqm_set_at', False) is None: + self.wqm_set_at = getattr(self, 'pc', None) # where the quad-read flow proof starts if hasattr(self, 'uniform_v'): self.uniform_v.clear() if hasattr(self, 'scc_uniform'): @@ -3793,8 +3878,9 @@ def dpp_broadcast(self, base, ops, mods): if self.kind != 'ps': raise Unsupported('%s_dpp outside a straight-line pixel stage with the entry EXEC mask' % base) # A branch to offset zero also makes the nominal entry block re-entrant. - if (getattr(self, 'past_entry', bool(getattr(self, 'blocks', ()))) or - not getattr(self, 'exec_known', False)): + # The whole-program proof (quad_flow_refusals) replaces the entry-prefix test once translate() runs it. + if (not getattr(self, 'exec_known', False) or + (not self.quad_flow_allowed() and getattr(self, 'past_entry', bool(getattr(self, 'blocks', ()))))): raise Unsupported('%s_dpp outside the entry prefix of a pixel stage with the entry EXEC mask' % base) if not getattr(self, 'wqm_exec', False): # The entry EXEC can leave out lanes of a partly covered quad, and the guest then reads an inactive @@ -3816,6 +3902,7 @@ def dpp_broadcast(self, base, ops, mods): rewritten = 'v%d' % self.DPP_TEMP rewritten = '|%s|' % rewritten if absolute else rewritten rewritten = '-' + rewritten if neg else rewritten + self.note_quad_flow(base) self.needs_sm6 = True self.set_v(self.DPP_TEMP, 'QuadReadLaneAt(%s, %su)' % (self.u(token), lanes.group(1))) operands = [ops[0], rewritten] + ops[2:] @@ -3878,12 +3965,12 @@ def dpp(self, base, ops, mods): src_neg_abs.append((neg, absolute, base_tok)) elif len(ops) != arity + 1 or any(not re.fullmatch(r'v\d+', o) for o in ops): raise Unsupported('%s_dpp needs VGPR operands without modifiers' % base) - if (getattr(self, 'kind', None) != 'ps' or getattr(self, 'has_branches', True) or getattr(self, 'blocks', True) - or not getattr(self, 'exec_known', False)): + if getattr(self, 'kind', None) != 'ps' or not (self.quad_flow_straight() or self.quad_flow_allowed()) or not getattr(self, 'exec_known', False): raise Unsupported('%s_dpp requires a straight-line pixel shader with entry EXEC' % base) if not getattr(self, 'wqm_exec', False): raise Unsupported('%s_dpp requires whole-quad EXEC (s_wqm of exec first): a partly covered quad has ' 'inactive source lanes that the hardware masks and QuadReadAcross does not' % base) + self.note_quad_flow(base) self.needs_sm6 = True # src0 is the exchanged lane; a VOP2 src1 stays this lane's own register. if kind == 'f':