Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -3943,6 +3947,14 @@ if(EXISTS "${INTAKE_PYTHON}")
"$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${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}"
"$<TARGET_FILE:offscreen_check>" ${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")
Expand Down
11 changes: 10 additions & 1 deletion docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
297 changes: 297 additions & 0 deletions tests/startup_gfx2hlsl_dpp_quad_flow_check.py
Original file line number Diff line number Diff line change
@@ -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 <llvm-mc> assemble the fixture sources with LLVM (gfx1013) and compare with the words here
draw <dxc> <offscreen_check> <warp|hardware> [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()
Loading
Loading