From a60128b49e07fec7257912b0829a8256a5c96a90 Mon Sep 17 00:00:00 2001 From: R0D4X Date: Tue, 24 Nov 2026 19:04:09 +0100 Subject: [PATCH 001/232] startup: lower v_mul_hi_u32 in gfx2hlsl --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 9 + tests/startup_gfx2hlsl_mul_hi_check.py | 220 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 4 +- 4 files changed, 234 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_mul_hi_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index c135fb974..c10228330 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -117,6 +117,7 @@ jobs: (["tests/startup_gfx2hlsl_f32_nan_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_f32_sdwa_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_f32_sdwa_check.py", "decode", "libLLVM-15.so.1"], {}), + (["tests/startup_gfx2hlsl_mul_hi_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_inline_sampler_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_smem_address_check.py", "binary", "llvm-mc-15"], {}), (["tests/compute_entry_layout_check.py", "binary", "llvm-mc-15"], {}), @@ -246,6 +247,7 @@ jobs: tests/startup_gfx2hlsl_f32_sdwa_check.py \ tests/startup_gfx2hlsl_root_check.py \ tests/startup_gfx2hlsl_sopk_signext_check.py \ + tests/startup_gfx2hlsl_mul_hi_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ tests/startup_smem_address_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 085338a5d..d906e27ce 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3146,6 +3146,15 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_small_texture_4k_xg startup_small_texture_4k_xg_no_limit_control PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") set_tests_properties(startup_small_texture_4k_xg_no_limit_control PROPERTIES WILL_FAIL TRUE) + # gfx2hlsl v_mul_hi_u32 (#870): CPU helper evaluation, refusal and mutation controls, then desktop draw (FXC 5_1 and DXC 6_0). + add_test(NAME startup_gfx2hlsl_mul_hi_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mul_hi_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_hi_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mul_hi_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_xg_bc_tiling COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc_tiling_check.py" "$") set_tests_properties(startup_xg_bc_tiling PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") diff --git a/tests/startup_gfx2hlsl_mul_hi_check.py b/tests/startup_gfx2hlsl_mul_hi_check.py new file mode 100644 index 000000000..b5d6a411d --- /dev/null +++ b/tests/startup_gfx2hlsl_mul_hi_check.py @@ -0,0 +1,220 @@ +"""Unsigned 32x32->high-32 vector multiply (v_mul_hi_u32) in tools/startup/gfx2hlsl.py (Refs #870). + + (no arguments) translation, helper-math, refusal and mutation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input pairs and compare the four result words + +The pixel fixture reads two flat parameters (v0..v3 and v4..v7), computes v_mul_hi_u32 across all four lanes into +v12..v15, and exports v12..v15 to mrt0. The vertex stage supplies the input words through flat parameters so the +pixel stage cannot constant-fold them. + +Every result is compared with an independent Python reference ((a * b) >> 32). The emitted mul_hi_u32 HLSL helper is +parsed and evaluated in 32-bit unsigned arithmetic over a grid of edge cases. A mutation control replaces mul_hi_u32 +with the low 32-bit product (a * b) while keeping the same inputs read, and must produce the mutated low-word readback +on both CPU evaluation and desktop GPU draws. +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + Expr, + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + Probe, + check, + refused, + vs_source, + vs_words, + words_text, +) + +BODY_SOURCE = ''.join('v_mul_hi_u32 v%d, v%d, v%d\n' % (12 + lane, lane, 4 + lane) for lane in range(4)) +BODY_WORDS = bytes.fromhex( + '0c006ad500090200' + '0d006ad5010b0200' + '0e006ad5020d0200' + '0f006ad5030f0200' +) +PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS + +SPECIAL = ( + 0, 1, 2, 3, 0xffff, 0x10000, 0x10001, 0x0001ffff, 0x7fffffff, 0x80000000, 0x80000001, + 0xdeadbeef, 0xcafebabe, 0x9e3779b9, 0x85ebca6b, 0xffff0000, 0xffff0001, 0xfffffffe, MASK, +) +GRID = [(a, b) for a in SPECIAL for b in SPECIAL] + +# Four (src0, src1, unused_src2) tuples per draw. Set 0 separates high-word from low-word and from missing-carry bugs. +DRAW = [ + (0xffffffff, 0xffffffff, 0), + (0x80000000, 0x00000002, 0), + (0xdeadbeef, 0xcafebabe, 0), + (0x00010001, 0x00010001, 0), + (0x00000000, 0xffffffff, 0), + (0x00000001, 0xffffffff, 0), + (0x0000ffff, 0xffffffff, 0), + (0xffff0000, 0x00010001, 0), + (0x7fffffff, 0x7fffffff, 0), + (0x80000001, 0x80000001, 0), + (0x0001ffff, 0xffff0001, 0), + (0x9e3779b9, 0x85ebca6b, 0), +] + + +def ref_mul_hi_u32(a, b): + return ((a & MASK) * (b & MASK)) >> 32 + + +def mut_mul_lo_u32(a, b): + return ((a & MASK) * (b & MASK)) & MASK + + +def translate(mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PS_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate: + mutated = re.sub(r'mul_hi_u32\((v\d+), (v\d+)\)', r'(\1 * \2)', text) + assert mutated != text, text + text = mutated + return pipe, text + + +def eval_emitted_helper(ps_text): + """Parse the emitted mul_hi_u32 helper body and return a 32-bit evaluator for it.""" + m = re.search(r'uint mul_hi_u32\(uint a, uint b\) \{ (.*?) \}', ps_text) + assert m, 'mul_hi_u32 helper missing from generated HLSL' + body = m.group(1) + m_vars = re.match(r'uint al = ([^,]+), bl = ([^,]+), m = ([^;]+); return ([^;]+);$', body) + assert m_vars, body + al_e, bl_e, m_e, ret_e = (Expr(part) for part in m_vars.groups()) + + def run(a, b): + env = {'a': a & MASK, 'b': b & MASK} + env['al'] = al_e.run(env)[0] + env['bl'] = bl_e.run(env)[0] + env['m'] = m_e.run(env)[0] + return ret_e.run(env)[0] + + return run + + +def controls(): + _, text = translate() + found = re.findall(r'^\s*v(1[2-5]) = mul_hi_u32\(v(\d+), v(\d+)\);$', text, re.M) + check('v_mul_hi_u32: four lane calls emitted', + found == [('12', '0', '4'), ('13', '1', '5'), ('14', '2', '6'), ('15', '3', '7')]) + + helper = eval_emitted_helper(text) + mismatch = next(((a, b, helper(a, b), ref_mul_hi_u32(a, b)) for a, b in GRID + if helper(a, b) != ref_mul_hi_u32(a, b)), None) + check('v_mul_hi_u32: emitted helper matches reference on %d edge pairs' % len(GRID), mismatch is None) + + # Carry-drop negative control on the helper itself: dropping ((al * bl) >> 16) must fail on 0xffffffff * 0xffffffff. + dropped = text.replace('+ ((al * bl) >> 16)', '+ 0u') + assert dropped != text + bad_helper = eval_emitted_helper(dropped) + check('v_mul_hi_u32: dropping low-half carry mismatches 0xffffffff * 0xffffffff', + bad_helper(0xffffffff, 0xffffffff) != ref_mul_hi_u32(0xffffffff, 0xffffffff)) + + # Lane mutation control: replacing mul_hi_u32(vX, vY) with (vX * vY) yields the low word on draw set 0. + mutated = translate(mutate=True)[1] + mut_lanes = re.findall(r'^\s*v(1[2-5]) = (.*);$', mutated, re.M) + assert [r for r, _ in mut_lanes] == ['12', '13', '14', '15'], mut_lanes + mut_exprs = [Expr(rhs) for _, rhs in mut_lanes] + first = DRAW[:4] + ref_first = [ref_mul_hi_u32(a, b) for a, b, _ in first] + mut_first = [mut_mul_lo_u32(a, b) for a, b, _ in first] + eval_mut = [expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b})[0] + for lane, (expr, (a, b, _)) in enumerate(zip(mut_exprs, first))] + check('v_mul_hi_u32: draw set 0 mutation reads %s (differs from %s)' % (words_text(mut_first), words_text(ref_first)), + mut_first != ref_first and eval_mut == mut_first) + + # Accepted operand forms (VGPR, SGPR, inline constant, literal) and exec-masked emission. + check('accepted operand forms translate', not any(refused(a) for a in ( + 'v_mul_hi_u32 v1, v2, v3', 'v_mul_hi_u32 v1, s0, v3', + 'v_mul_hi_u32 v1, v2, 7', 'v_mul_hi_u32 v1, v2, 0x12345678'))) + masked = Probe() + masked.exec_known = False + masked.one('v_mul_hi_u32', 'v_mul_hi_u32 v1, v2, v3') + check('exec-masked v_mul_hi_u32 guards assignment', + masked.lines == ['if (exec & 1) v1 = mul_hi_u32(v2, v3);']) + + # Unmodeled modifiers and wrong operand counts must stay refused. + check('modifiers and operand modifiers refused', all(refused(a) for a in ( + 'v_mul_hi_u32 v1, v2, v3 clamp', 'v_mul_hi_u32 v1, v2, v3 mul:2', + 'v_mul_hi_u32 v1, v2, v3 div:2', 'v_mul_hi_u32 v1, v2, v3 op_sel:[1,0,0,0]', + 'v_mul_hi_u32 v1, -v2, v3', 'v_mul_hi_u32 v1, |v2|, v3', + 'v_mul_hi_u32 v1, v2, -v3', 'v_mul_hi_u32 v1, v2, |v3|'))) + check('wrong operand counts refused', all(refused(a) for a in ( + 'v_mul_hi_u32 v1', 'v_mul_hi_u32 v1, v2', 'v_mul_hi_u32 v1, v2, v3, v4'))) + + +def check_binary(llvm_mc): + built = assemble(llvm_mc, BODY_SOURCE) + if built != BODY_WORDS: + raise AssertionError('v_mul_hi_u32: assembled %s, recorded %s' % (built.hex(), BODY_WORDS.hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for index in range(0, len(DRAW), 4): + chunk = DRAW[index:index + 4] + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % (chunk,)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + good_ps = compile_hlsl(compiler, kind, translate()[1], 'ps_mul_hi_%s' % kind, ps_profile, directory) + for index in range(0, len(DRAW), 4): + chunk = DRAW[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PS_WORDS, root_blob()).hlsl_vs(), + 'vs_mul_hi_%d_%s' % (index, kind), vs_profile, directory) + expected = words_text(ref_mul_hi_u32(a, b) for a, b, _ in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s v_mul_hi_u32 inputs %s\n%s\n%s' % (kind, chunk, run.stdout, run.stderr)) + print('%s v_mul_hi_u32 %s: %s' % (kind, [('%x' % a, '%x' % b) for a, b, _ in chunk], expected), + flush=True) + if index: + continue + wrong = words_text(mut_mul_lo_u32(a, b) for a, b, _ in chunk) + bad_ps = compile_hlsl(compiler, kind, translate(mutate=True)[1], + 'mutated_mul_hi_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s v_mul_hi_u32 mutation did not read %s\n%s\n%s' + % (kind, wrong, run.stdout, run.stderr)) + print('%s v_mul_hi_u32 mutation: fails as expected, reads %s' % (kind, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 79de72c05..b377fb239 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3566,7 +3566,7 @@ def declarations(self): # operands are uints; the result is a uint expression VEC_U = { 'v_add_nc_u32': (2, '{0} + {1}'), 'v_sub_nc_u32': (2, '{0} - {1}'), 'v_subrev_nc_u32': (2, '{1} - {0}'), - 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), + 'v_mul_lo_u32': (2, '{0} * {1}'), 'v_mul_hi_u32': (2, 'mul_hi_u32({0}, {1})'), 'v_and_b32': (2, '{0} & {1}'), 'v_or_b32': (2, '{0} | {1}'), 'v_xor_b32': (2, '{0} ^ {1}'), 'v_not_b32': (1, '~{0}'), 'v_lshlrev_b32': (2, '{1} << ({0} & 31)'), 'v_lshrrev_b32': (2, '{1} >> ({0} & 31)'), 'v_ashrrev_i32': (2, 'uint(int({1}) >> ({0} & 31))'), 'v_min_u32': (2, 'min({0}, {1})'), 'v_max_u32': (2, 'max({0}, {1})'), 'v_min_i32': (2, 'uint(min(int({0}), int({1})))'), 'v_max_i32': (2, 'uint(max(int({0}), int({1})))'), @@ -3854,6 +3854,8 @@ def common(self): ' precise float sum = product + ftz32(c);', ' return ftz32(sum);', '}', + 'uint mul_hi_u32(uint a, uint b) { uint al = a & 0xffffu, bl = b & 0xffffu, m = (a >> 16) * bl + ((al * bl) >> 16); ' + 'return (a >> 16) * (b >> 16) + (m >> 16) + (((m & 0xffffu) + al * (b >> 16)) >> 16); }', 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' From 92534e75c30f0010c2c35c709e430007d2f0af6e Mon Sep 17 00:00:00 2001 From: rdx <123564405+R0D4X@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:12:01 +0100 Subject: [PATCH 002/232] Update gfx2hlsl.py Remove the duplicate mul_hi_u32 definition introduced during rebase so v_mul_hi_u32 reuses the shared helper from #2176. --- tools/startup/gfx2hlsl.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index b377fb239..b59ac818c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3854,8 +3854,6 @@ def common(self): ' precise float sum = product + ftz32(c);', ' return ftz32(sum);', '}', - 'uint mul_hi_u32(uint a, uint b) { uint al = a & 0xffffu, bl = b & 0xffffu, m = (a >> 16) * bl + ((al * bl) >> 16); ' - 'return (a >> 16) * (b >> 16) + (m >> 16) + (((m & 0xffffu) + al * (b >> 16)) >> 16); }', 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' From 2fadf5e1fc9c608420aec7bb9aaec6072bc56834 Mon Sep 17 00:00:00 2001 From: rdx <123564405+R0D4X@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:24:53 +0100 Subject: [PATCH 003/232] Update startup_gfx2hlsl_mul_hi_check.py --- tests/startup_gfx2hlsl_mul_hi_check.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/tests/startup_gfx2hlsl_mul_hi_check.py b/tests/startup_gfx2hlsl_mul_hi_check.py index b5d6a411d..dbd2e84ef 100644 --- a/tests/startup_gfx2hlsl_mul_hi_check.py +++ b/tests/startup_gfx2hlsl_mul_hi_check.py @@ -95,20 +95,19 @@ def eval_emitted_helper(ps_text): m = re.search(r'uint mul_hi_u32\(uint a, uint b\) \{ (.*?) \}', ps_text) assert m, 'mul_hi_u32 helper missing from generated HLSL' body = m.group(1) - m_vars = re.match(r'uint al = ([^,]+), bl = ([^,]+), m = ([^;]+); return ([^;]+);$', body) + m_vars = re.match(r'uint la = ([^,]+), lb = ([^;]+); uint middle = ([^;]+); return ([^;]+);$', body) assert m_vars, body - al_e, bl_e, m_e, ret_e = (Expr(part) for part in m_vars.groups()) + la_e, lb_e, middle_e, ret_e = (Expr(part) for part in m_vars.groups()) def run(a, b): env = {'a': a & MASK, 'b': b & MASK} - env['al'] = al_e.run(env)[0] - env['bl'] = bl_e.run(env)[0] - env['m'] = m_e.run(env)[0] + env['la'] = la_e.run(env)[0] + env['lb'] = lb_e.run(env)[0] + env['middle'] = middle_e.run(env)[0] return ret_e.run(env)[0] return run - - + def controls(): _, text = translate() found = re.findall(r'^\s*v(1[2-5]) = mul_hi_u32\(v(\d+), v(\d+)\);$', text, re.M) From ee0b273f310dd800393ff4a2cf6935010ede5b8a Mon Sep 17 00:00:00 2001 From: rdx <123564405+R0D4X@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:34:23 +0100 Subject: [PATCH 004/232] Update startup_gfx2hlsl_mul_hi_check.py --- tests/startup_gfx2hlsl_mul_hi_check.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_mul_hi_check.py b/tests/startup_gfx2hlsl_mul_hi_check.py index dbd2e84ef..d9da8d2c6 100644 --- a/tests/startup_gfx2hlsl_mul_hi_check.py +++ b/tests/startup_gfx2hlsl_mul_hi_check.py @@ -119,8 +119,8 @@ def controls(): if helper(a, b) != ref_mul_hi_u32(a, b)), None) check('v_mul_hi_u32: emitted helper matches reference on %d edge pairs' % len(GRID), mismatch is None) - # Carry-drop negative control on the helper itself: dropping ((al * bl) >> 16) must fail on 0xffffffff * 0xffffffff. - dropped = text.replace('+ ((al * bl) >> 16)', '+ 0u') + # Carry-drop negative control on the helper itself: dropping ((la * lb) >> 16) must fail on 0xffffffff * 0xffffffff. + dropped = text.replace('+ ((la * lb) >> 16)', '+ 0u') assert dropped != text bad_helper = eval_emitted_helper(dropped) check('v_mul_hi_u32: dropping low-half carry mismatches 0xffffffff * 0xffffffff', From 55505e0bef768d8bb8021627c7302cbf17feeece Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:28:35 +0800 Subject: [PATCH 005/232] tests: verify the LDS address snapshot before either result is written --- tests/startup_gfx2hlsl_compute_check.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index a1d74c902..495834cdb 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -552,6 +552,9 @@ def check_lds(): assert 'groupshared uint lds[8192];' in translate('F', rsrc2=base | 64 << 15).hlsl_cs() pair = '0524dcd806000006' + # The first result overwrites v6. Both loads must use the address saved before that write. + body = translate('G').hlsl_cs() + assert 'a = v6;\n v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];' in body, body for other, reason in ( ('0324dcd806000006', 'initialized span'), # offset0 alone precedes the fill ('0525dcd806000006', 'initialized span'), # offset1 alone crosses the upper end From dfda9f53b5cfa06d6369438308175fb73331613d Mon Sep 17 00:00:00 2001 From: lewisalex86 Date: Wed, 25 Nov 2026 12:17:10 +0000 Subject: [PATCH 006/232] build: point the build-rev test's hooksPath at an empty folder startup_build_rev_check.py ran every git command with "-c core.hooksPath=" so that a contributor's hooks could not run in its scratch repositories. Some git builds reject the empty value with "fatal: The empty string is not a valid path" (seen with git 2.47.2.vfs.0.1 on Windows), so the test failed before checking anything. It now points core.hooksPath at an empty folder inside the test's temporary directory, which disables hooks the same way. Test: ctest --preset dev -R '^startup_build_rev_controls$': passed. Before the change: failed with the error above on the same git. Co-Authored-By: Claude Opus 5.5 --- tests/startup_build_rev_check.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/startup_build_rev_check.py b/tests/startup_build_rev_check.py index 5829c1e6d..9088f2b94 100644 --- a/tests/startup_build_rev_check.py +++ b/tests/startup_build_rev_check.py @@ -63,12 +63,15 @@ def __init__(self, base, git, cmake): self.git, self.cmake = git, cmake empty = base / "empty.gitconfig" empty.write_text("") + # An empty hooks folder rather than "core.hooksPath=": some git builds reject an empty path. + self.hooks = base / "no-hooks" + self.hooks.mkdir(exist_ok=True) self.env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} self.env.update(GIT_CONFIG_GLOBAL=str(empty), GIT_CONFIG_NOSYSTEM="1") def run(self, cwd, *args): result = subprocess.run([self.git, "-c", "user.name=x2w-test", "-c", "user.email=test@example.invalid", - "-c", "commit.gpgsign=false", "-c", "core.hooksPath=", *args], + "-c", "commit.gpgsign=false", "-c", f"core.hooksPath={self.hooks.as_posix()}", *args], cwd=cwd, env=self.env, capture_output=True, text=True) if result.returncode != 0: fail(f"git {' '.join(args)} in {cwd}: {result.stderr.strip()}") From 85e045382fc652946d7f21112824a667595a7bc3 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:36:12 +0800 Subject: [PATCH 007/232] shader: expand packed D16 XY stores into FLOAT2 heap views --- docs/experiments.md | 10 +++-- tests/compute_heap_store_check.py | 72 +++++++++++++++++++++++++------ tools/compute_store_aot.py | 32 ++++++++------ 3 files changed, 86 insertions(+), 28 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index b6f48c49e..cec85da97 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5782,11 +5782,15 @@ The view must be live and describe format 75 (`BUF_FMT_32_32_32_32_UINT`) with i Run `ctest --preset dev -R '^compute_(heap_store_controls|store_aot_heap_view_store_(warp|hardware))$' --output-on-failure`. The fixture checks all 320 readback words across twelve cases. These include distinct live ranges, one texel ending exactly at the u0 limit, and a partial texel that must leave the sentinel intact. Eight mutations exercise the base, stride, record count, format, lifetime, output extent and slot limit. Removing the per-index extent check lets the next thread write past the last complete texel. -### Packed D16 heap-view stores to FLOAT4 and FLOAT1 + -With the same `--heap-store-view` binding, gfx1013 `buffer_store_format_d16_xyzw` reads X/Y from the low/high halves of the first VGPR and Z/W from the second. A live identity `BUF_FMT_32_32_32_32_FLOAT` view (format 77) receives four binary32 words. Two source VGPRs still require 16 writable bytes in the destination. `buffer_store_format_d16_x` takes one source VGPR, converts its low 16 bits (`& 0xffffu`) via `f16tof32`, and writes one 4-byte binary32 word into a live identity `BUF_FMT_32_FLOAT` view (format 22, `0x01016fac`), enforcing 4-byte offset/stride/base alignment and `(bytes - view.x - offset - 4u) / stride` bounds without a raw UAV read-modify-write. Ordinary UINT views or mismatched four-channel/single-channel FLOAT views leave the sentinel region untouched, and `d16_xy` / `d16_xyz` remain refused under `--heap-store-view`. [AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [HLSL half-to-float conversion](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/f16tof32) +### Packed D16 heap-view stores to FLOAT1, FLOAT2 and FLOAT4 -The heap-store CTest selection above runs all three programs (`UINT4`, `D16-to-FLOAT4`, and `D16_X-to-FLOAT1`). Each D16 fixture checks 320 words across its heap-view cases (with `D16_X` additionally checking four binary16 payload patterns with poisoned high halves: `1.0`..`1.00293`, `-2.0`.., minimum positive subnormal + `+0.0`, and `-0.0` + negative subnormals, plus `UINT1` and `FLOAT4` mismatch rejections and untouched adjacent sentinel dwords). Eleven compiled shader mutations check addressing, view selection, and half-float extraction, including swapping high for low bits, checking the wrong format word, and writing packed values directly. +With the same `--heap-store-view` binding, gfx1013 `buffer_store_format_d16_xyzw` reads X/Y from the low/high halves of the first VGPR and Z/W from the second. A live identity `BUF_FMT_32_32_32_32_FLOAT` view (format 77) receives four binary32 words. Two source VGPRs still require 16 writable bytes in the destination. `buffer_store_format_d16_x` takes one source VGPR, converts its low 16 bits (`& 0xffffu`) via `f16tof32`, and writes one 4-byte binary32 word into a live identity `BUF_FMT_32_FLOAT` view (format 22, `0x01016fac`), enforcing 4-byte offset/stride/base alignment and `(bytes - view.x - offset - 4u) / stride` bounds without a raw UAV read-modify-write. A view whose format differs from the required component count or numeric type leaves the output untouched. The packed three-component `d16_xyz` form is refused. [AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [HLSL half-to-float conversion](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/f16tof32) + +The heap-store CTest selection above runs all four programs (`UINT4`, `D16-to-FLOAT4`, `D16_X-to-FLOAT1` and `D16_XY-to-FLOAT2`). Each D16 fixture checks 320 words across its heap-view cases (with `D16_X` additionally checking four binary16 payload patterns with poisoned high halves: `1.0`..`1.00293`, `-2.0`.., minimum positive subnormal + `+0.0`, and `-0.0` + negative subnormals, plus `UINT1` and `FLOAT4` mismatch rejections and untouched adjacent sentinel dwords). Eleven compiled shader mutations check addressing, view selection, and half-float extraction, including swapping high for low bits, checking the wrong format word, and writing packed values directly. + +For `buffer_store_format_d16_xy`, the low and high halves of one VGPR become X and Y of an identity `BUF_FMT_32_32_FLOAT` view (format 64, `0x01040fac`). One `Store2` writes the two binary32 values. With a 512-byte u0 and an instruction offset of four, a base of 500 writes words 126 and 127. A base of 504 leaves all 320 readback words untouched. The fixture also checks negative zero, the smallest positive binary16 subnormal and −2.0 in Y. Swapping the halves, duplicating X into Y and admitting a partial element must each produce its own first mismatched word. ### Heap-view buffer loads diff --git a/tests/compute_heap_store_check.py b/tests/compute_heap_store_check.py index e6267494d..b5d1aa543 100644 --- a/tests/compute_heap_store_check.py +++ b/tests/compute_heap_store_check.py @@ -13,6 +13,7 @@ TABLE_BYTE = 256 FLOAT1 = 0x01016FAC # gfx10 format 22 (BUF_FMT_32_FLOAT), identity selectors and RESOURCE_LEVEL set UINT1 = 0x01014FAC # gfx10 format 20 (BUF_FMT_32_UINT) +FLOAT2 = 0x01040FAC # gfx10 format 64 (BUF_FMT_32_32_FLOAT) UINT4 = 0x0104BFAC # gfx10 format 75, identity XYZW selectors and RESOURCE_LEVEL set FLOAT4 = 0x0104DFAC STORE = "buffer_store_format_xyzw v[10:13], v8, s[20:23], 0 idxen offset:4" @@ -33,6 +34,8 @@ D16_X_PROGRAM = SETUP + [ "v_xor_b32_e32 v10, s25, v8", D16_X_STORE, "s_endpgm", ] +D16_XY_STORE = D16_X_STORE.replace("d16_x ", "d16_xy ") +D16_XY_PROGRAM = base.variant(D16_X_PROGRAM, (D16_X_STORE, D16_XY_STORE)) # 0x3c00..0x3c03 are consecutive binary16 values starting at 1.0. D16_X = (0x3f800000, 0x3f802000, 0x3f804000, 0x3f806000) # High half 0x4200 poisons each word so leaking high bits or missing & 0xffffu shifts fails readback. @@ -74,6 +77,21 @@ ("live slot beyond declared count", (12, 8 << 16, 4, FLOAT1, 1), ()), ) VIEW = (0, TABLE_BYTE, len(CASES) - 1, WORDS * 4, 512) +# Expected starting word of each two-component write. An empty tuple means all 320 guards survive. +D16_XY_CASES = ( + ("four float2 records", (12, 12 << 16, 4, FLOAT2, 1), (4, 7, 10, 13)), + ("second base and short count", (116, 16 << 16, 2, FLOAT2, 1), (30, 34)), + ("released view", (12, 12 << 16, 4, FLOAT2, 2), ()), + ("eight bytes ending at the output limit", (500, 12 << 16, 4, FLOAT2, 1), (126,)), + ("only four bytes left", (504, 12 << 16, 4, FLOAT2, 1), ()), + ("wrong FLOAT1 format", (12, 12 << 16, 4, FLOAT1, 1), ()), + ("short stride", (12, 8 << 16, 4, FLOAT2, 1), ()), + ("misaligned base", (14, 12 << 16, 4, FLOAT2, 1), ()), + ("misaligned stride", (12, 14 << 16, 4, FLOAT2, 1), ()), + ("unsupported high address", (12, (12 << 16) | 1, 4, FLOAT2, 1), ()), + ("base past the declared extent", (640, 12 << 16, 4, FLOAT2, 1), ()), + ("live slot beyond the declared count", (12, 12 << 16, 4, FLOAT2, 1), ()), +) BINDING = dict(table_reg=7, descriptor_offset=0x30, constant_descriptor=0x40, source_descriptor=0x50, group_reg=11) @@ -85,6 +103,7 @@ def controls(): assert base.aot.descriptor_format_word(75) == UINT4 assert base.aot.descriptor_format_word(22) == FLOAT1 assert base.aot.descriptor_format_word(20) == UINT1 + assert base.aot.descriptor_format_word(64) == FLOAT2 # Pin the translator call here. draw() exercises the generated guards against actual UAV contents. assert "store_heap_words4(params[0].x, tid.x, 4u, false, uint4(tid.x," in lower() assert "store_heap_words4(params[0].x, tid.x, 4u, true," in lower(D16_PROGRAM) @@ -112,8 +131,10 @@ def controls(): base.variant(PROGRAM, (STORE, STORE.replace("xyzw v[10:13]", "xy v[10:11]")))) refuses("Heap store view requires buffer_store_format_xyzw", lower, base.variant(D16_PROGRAM, (D16_STORE, D16_STORE.replace("d16_xyzw", "d16_xyz")))) - refuses("Heap store view requires buffer_store_format_xyzw", lower, - base.variant(D16_X_PROGRAM, (D16_X_STORE, D16_X_STORE.replace("d16_x", "d16_xy")))) + xy = lower(D16_XY_PROGRAM) + assert f"{FLOAT2:#x}u" in xy and "outputData.Store2(" in xy and "outputData.Load(" not in xy + refuses("Unverified raw UAV store", lower, + base.variant(D16_XY_PROGRAM, (D16_XY_STORE, D16_XY_STORE.replace("v10", "v[10:11]")))) refuses("Heap store view requires buffer_store_format_xyzw", lower, base.variant(D16_X_PROGRAM, (D16_X_STORE, D16_X_STORE.replace("d16_x", "x")))) refuses("Unverified raw UAV store", lower, @@ -145,8 +166,8 @@ def verify_binary(directory, code, library, program=PROGRAM): def draw(directory, compiler, renderer, backend, mode): - program = {"uint4": PROGRAM, "d16_xyzw": D16_PROGRAM, "d16_x": D16_X_PROGRAM}[mode] - cases = D16_X_CASES if mode == "d16_x" else CASES + program = {"uint4": PROGRAM, "d16_xyzw": D16_PROGRAM, "d16_x": D16_X_PROGRAM, "d16_xy": D16_XY_PROGRAM}[mode] + cases = {"d16_x": D16_X_CASES, "d16_xy": D16_XY_CASES}.get(mode, CASES) source = lower(program) table = [0] * WORDS for slot, (_, record, _) in enumerate(cases): @@ -160,11 +181,13 @@ def compile_shader(text): hlsl.write_text(text, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) - def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table): + def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table, expected_y=0x40400000): result = [base.SENTINEL] * WORDS for thread, start in enumerate(cases[slot][2]): if mode == "d16_x": result[start] = expected_x[thread] + elif mode == "d16_xy": + result[start:start + 2] = [expected_x[thread], expected_y] elif mode == "d16_xyzw": # D16 y, z, w are -2, the smallest positive binary16 subnormal, and negative zero. result[start:start + 4] = [D16_X[thread], 0xc0000000, 0x33800000, 0x80000000] @@ -196,14 +219,27 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table) result = subprocess.run([renderer, backend, "--compute-store-case", cso, case], capture_output=True, text=True) assert result.returncode == 0, ("wrong FLOAT4 format", result.stderr) extra += 1 - width_str = "4u" if mode == "d16_x" else "16u" + if mode == "d16_xy": + for payload, expected_y in ((0x80003c00, 0x80000000), (0x00013c00, 0x33800000), (0xc0003c00, 0xc0000000)): + result = run(0, payload=payload, expected_y=expected_y) + assert result.returncode == 0, (hex(payload), result.stderr) + extra += 1 + for wrong_format in (FLOAT4, base.aot.descriptor_format_word(62)): # UINT2 + wrong_view = table.copy() + wrong_view[TABLE_BYTE // 4 + 5 * 8 + 3] = wrong_format + result = run(5, table_words=wrong_view) + assert result.returncode == 0, (hex(wrong_format), result.stderr) + extra += 1 + width_str = {"d16_x": "4u", "d16_xy": "8u"}.get(mode, "16u") + format_guard = {"d16_x": f"{FLOAT1:#x}u", "d16_xy": f"{FLOAT2:#x}u"}.get(mode, "formatWord") + wrong_stride = {"d16_x": 8, "d16_xy": 12}.get(mode, 24) mutations = ( ("view.x + index * stride + offset", "index * stride + offset", 0), (" || index >= view.z", "", 1), - ("uint stride = view.y >> 16u;", "uint stride = 8u;" if mode == "d16_x" else "uint stride = 24u;", 1), + ("uint stride = view.y >> 16u;", f"uint stride = {wrong_stride}u;", 1), ("const uint bytes = 512u;", "const uint bytes = 1280u;", 4), (f"if (index > (bytes - view.x - offset - {width_str}) / stride) return;", "", 3), - (f"view.w != {FLOAT1:#x}u || " if mode == "d16_x" else "view.w != formatWord || ", "", 5), + (f"view.w != {format_guard} || ", "", 5), ("!= 1u) return;", "== 0u) return;", 2), (f"slot >= {VIEW[2]}u", f"slot > {VIEW[2]}u", VIEW[2]), ) @@ -219,12 +255,24 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table) ("asuint(f16tof32(value & 0xffffu))", "value", 0), (f"{FLOAT1:#x}u", f"{FLOAT4:#x}u", 0), ) - for old, new, slot in mutations: + elif mode == "d16_xy": + mutations += ( + ("uint2(value & 0xffffu, value >> 16u)", "uint2(value >> 16u, value & 0xffffu)", 0, + "word=4 expected=3f800000 actual=40400000"), + ("value >> 16u", "value & 0xffffu", 0, "word=5 expected=40400000 actual=3f800000"), + ("offset + 8u > bytes - view.x", "offset + 4u > bytes - view.x", 4, + "word=127 expected=c5c5c5c5 actual=3f800000"), + ) + for old, new, slot, *first_mismatch in mutations: assert source.count(old) == 1, old compile_shader(source.replace(old, new)) result = run(slot) assert result.returncode == 1 and "Compute readback differs" in result.stderr, (old, result.stderr) - kind = {"uint4": "UINT4", "d16_xyzw": "D16-to-FLOAT4", "d16_x": "D16_X-to-FLOAT1"}[mode] + if first_mismatch: + words = [line for line in result.stderr.splitlines() if line.startswith("word=")] + assert words[:1] == first_mismatch, (old, result.stderr) + kind = {"uint4": "UINT4", "d16_xyzw": "D16-to-FLOAT4", "d16_x": "D16_X-to-FLOAT1", + "d16_xy": "D16_XY-to-FLOAT2"}[mode] print(f"{backend} {kind}: {len(cases) + extra} heap-store cases and {len(mutations)} shader mutations checked") return 0 @@ -238,13 +286,13 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table) with tempfile.TemporaryDirectory() as tmp: directory = Path(tmp) if mode == "draw": - for kind in ("uint4", "d16_xyzw", "d16_x"): + for kind in ("uint4", "d16_xyzw", "d16_x", "d16_xy"): result = draw(directory, *args, kind) if result: sys.exit(result) sys.exit(0) assembler, objcopy, library = args - for program in (PROGRAM, D16_PROGRAM, D16_X_PROGRAM): + for program in (PROGRAM, D16_PROGRAM, D16_X_PROGRAM, D16_XY_PROGRAM): code = base.assemble(directory, assembler, objcopy, program, cpu="gfx1013") verify_binary(directory, code, library, program) else: diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index fa0ade17a..5cd2b4435 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -704,13 +704,18 @@ def heap_view_hlsl(table_offset, view_count, buffer_bytes): ) -def heap_store_view_hlsl(table_offset, view_count, output_bytes, *, single_d16=False): - """Store UINT4/FLOAT4 or one expanded half float through a live side-table record.""" - width = 4 if single_d16 else 16 - if single_d16: +def heap_store_view_hlsl(table_offset, view_count, output_bytes, *, components=4): + """Store UINT4 or expanded binary16 components through a live side-table record.""" + width = 4 * components + if components in (1, 2): sig = "void store_heap_word_d16(uint slot, uint index, uint offset, uint value)" - fmt_check = f" if (view.w != {descriptor_format_word(22):#x}u || (view.y & 0xc000ffffu) != 0u) return;" - write = " outputData.Store(view.x + index * stride + offset, asuint(f16tof32(value & 0xffffu)));" + format_word = descriptor_format_word(22 if components == 1 else 64) # BUF_FMT_32_FLOAT or BUF_FMT_32_32_FLOAT + fmt_check = f" if (view.w != {format_word:#x}u || (view.y & 0xc000ffffu) != 0u) return;" + if components == 1: + write = " outputData.Store(view.x + index * stride + offset, asuint(f16tof32(value & 0xffffu)));" + else: + write = (" outputData.Store2(view.x + index * stride + offset, " + "asuint(f16tof32(uint2(value & 0xffffu, value >> 16u))));") else: sig = "void store_heap_words4(uint slot, uint index, uint offset, bool d16, uint4 value)" fmt_check = (f" uint formatWord = d16 ? {descriptor_format_word(77):#x}u : {descriptor_format_word(75):#x}u;\n" @@ -935,6 +940,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N # they enter vector only at s_waitcnt vmcnt(0). loading = {} stores = [] + heap_store_components = 4 format_store_index = 0 atomic_update = False # DS operations and image loads can consume each other's temporaries. Keep them in instruction order. @@ -2732,8 +2738,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if not idxen or offen: raise ValueError("Unsupported formatted buffer store target or address mode") if heap_store_view is not None: - if channels not in ("xyzw", "d16_xyzw", "d16_x"): - raise ValueError("Heap store view requires buffer_store_format_xyzw, buffer_store_format_d16_xyzw or buffer_store_format_d16_x") + if channels not in ("xyzw", "d16_xyzw", "d16_xy", "d16_x"): + raise ValueError("Heap store view requires buffer_store_format_xyzw or a D16 x, xy or xyzw store") if not any(tag == ("constant_word", heap_slot_word) and reg not in pending for reg, tag in scalar.items()): raise ValueError("Heap store view slot constant is not ready") @@ -2864,7 +2870,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N words[-1] = f"((outputData.Load({final_address}) & 0xffff0000u) | ({words[-1]} & 0xffffu))" if heap_store_view is not None: slot = hlsl_word(("constant_word", heap_slot_word)) - if channels == "d16_x": + heap_store_components = components + if channels in ("d16_x", "d16_xy"): stores.append(f" store_heap_word_d16({slot}, {address}, {offset}u, {words[0]});") else: supplied = words + ["0u"] * (4 - len(words)) @@ -2947,9 +2954,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if heap_view is not None: descriptor_hlsl += heap_view_hlsl(heap_table, heap_count, heap_bytes) if heap_store_view is not None: - descriptor_hlsl += heap_store_view_hlsl( - heap_table, heap_count, output_bytes, single_d16="store_heap_word_d16(" in body - ) + descriptor_hlsl += heap_store_view_hlsl(heap_table, heap_count, output_bytes, components=heap_store_components) # GetDimensions on a raw buffer returns its size in bytes, the value of descriptor word 2. for name, view in (("uav_bytes", "outputData"), ("srv_bytes", "inputData")): if f"{name}(" in body: @@ -2998,7 +3003,8 @@ def main(): "SLOT_WORD; the record table is at byte TABLE_OFFSET of the BUFFER_BYTES-byte t0 and holds COUNT views") parser.add_argument("--heap-store-view", nargs=5, type=lambda n: int(n, 0), metavar=("SLOT_WORD", "TABLE_OFFSET", "COUNT", "TABLE_BUFFER_BYTES", "OUTPUT_BYTES"), - help="select a UINT4 or D16-to-FLOAT4 store view from t0 and bound writes by OUTPUT_BYTES of u0") + help="select a UINT4 or expanded D16 FLOAT1/FLOAT2/FLOAT4 store view from t0 " + "and bound writes by OUTPUT_BYTES of u0") parser.add_argument("--mubuf-d16-xyz-mode", choices=("preserve-w",), help="Experimental RGBA16 UINT store with caller-verified preservation of W") parser.add_argument("--image-descriptor", type=lambda n: int(n, 0), From a4eff9ac284f34409edde71d34362aff78a91c85 Mon Sep 17 00:00:00 2001 From: Maledetto <20729264+Makto94@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:43:33 +0100 Subject: [PATCH 008/232] docs: link 9 GPU coverage reports from #1 Refs #1. --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8d79911c3..fa578e8dc 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | NVIDIA GeForce RTX 5080 (driver 32.0.16.2124) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063834333) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065170340) · [32.0.16.1664 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065546749) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065671431) · [32.0.16.1692 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069515442) · [32.0.16.1714 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7073236219) · [32.0.16.2114 report, debug layer enabled, adapter filter RTX 5080](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120729216) | | NVIDIA GeForce RTX 5080 Laptop GPU (driver 32.0.15.8142) | 32 | Skipped, lane range 32–32 | Passed | [Package report by ChazY11](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118193451) | | Intel Arc 140T (driver 32.0.101.8132) | 32 | Skipped, lane range 8–32 | Passed | [Package report by ChazY11](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118193451) | -| AMD Radeon RX 9060 XT (driver 32.0.32029.2010) | 64 | Passed, 64 lanes | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064143537) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064981137) · [Third run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066160576) · [32.0.31036.15 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067791300) · [Fourth run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071716818) · [32.0.31044.16 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082736563) · [32.0.31035.1003 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085208838) · [32.0.32029.2010 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7129118597) · [32.0.32015.16001 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7140423557) | +| AMD Radeon RX 9060 XT (driver 32.0.32029.2010) | 64 | Passed, 64 lanes; skipped, Shader Model 6.5 on build 19045 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064143537) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064981137) · [Third run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066160576) · [32.0.31036.15 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067791300) · [Fourth run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071716818) · [32.0.31044.16 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082736563) · [32.0.31035.1003 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085208838) · [32.0.32029.2010 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7129118597) · [32.0.32015.16001 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7140423557) · [32.0.32029.2010 report, source def386a](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7110561953) · [32.0.32029.2010 report, source 0f0c3eb](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7110873382) · [32.0.32029.2010 report, Windows 10 build 19045, debug layer enabled, Shader Model 6.5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7133457238) | | NVIDIA GeForce RTX 4060 (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064173447) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070801875) · [Independent 32.0.16.2124 run by FZNull](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7075511602) · [Independent 32.0.16.1088 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080590016) · [32.0.16.2124 report, Windows build 19045.7846, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7135754240) · [32.0.15.9579 report, Windows build 26100.9711](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7157562178) | | NVIDIA GeForce RTX 4050 Laptop GPU (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064193927) · [32.0.16.2114 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7121369464) | | NVIDIA GeForce RTX 2060 SUPER (driver 32.0.16.2124) | 32 | Skipped, lane range 32–32 | 408 queries passed | [Windows hardware report](https://github.com/R0Y00/Xbox2Windows/issues/57) | @@ -228,7 +228,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | Intel Arc B570 (driver 32.0.101.9175) | 32 | Skipped, lane range 16–32 | 408 queries passed | [Windows hardware report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064376175) | | AMD Radeon RX 6600 LE | 32 | Skipped, Shader Model 6.5 | 408 queries passed | [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064448893) | | NVIDIA GeForce RTX 3080 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064502245) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068631497) | -| NVIDIA GeForce RTX 4070 SUPER | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2135 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064571169) · [32.0.16.2114 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065156565) · [32.0.16.1742 source build at ccfa703](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066952802) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068191239) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7076658249) · [Independent 32.0.16.2124 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079487276) | +| NVIDIA GeForce RTX 4070 SUPER | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2135 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064571169) · [32.0.16.2114 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065156565) · [32.0.16.1742 source build at ccfa703](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066952802) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068191239) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7076658249) · [Independent 32.0.16.2124 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079487276) · [Third 32.0.16.2124 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7137965396) | | NVIDIA GeForce GTX 1080 Ti | 32 | Skipped, lane range 32–32 | Skipped, DXR tier 1.0 | [32.0.15.8266 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064625762) | | AMD Radeon RX 6700 | 32 | Passed, 64 lanes | 408 queries passed | [32.0.21045.16010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064650872) | | NVIDIA GeForce RTX 5060 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064676684) · [32.0.16.1656 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064685186) · [32.0.16.2114 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065648368) · [32.0.16.1074 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079319334) · [32.0.16.2124 report, Windows 10, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080887666) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7109317298) · [32.0.16.2124 report, Windows build 26200.7922, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7134322310) | @@ -241,8 +241,8 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | AMD Radeon RX 7800 XT | 32 on every run | Skipped on Windows 10 runs capped at Shader Model 6.5. Passed with 64 lanes in the other reports | 408 queries passed per run | [32.0.32015.16001 report, Windows 10 build 19045](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064791654) · [32.0.32029.2010 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/101) · [Independent 32.0.32029.2010 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068788175) · [32.0.32015.7029 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079560197) · [32.0.32015.16001 report, build 26300, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084752103) · [Third 32.0.32029.2010 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7085397975) · [32.0.32029.2010 report, Windows 10 build 19045, Shader Model 6.5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7093682244) · [32.0.32029.2010 report, Windows build 26300.10075, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7124179405) | | NVIDIA GeForce GTX 1070 | 32 | Skipped, lane range 32–32 | Skipped, DXR tier 1.0 | [32.0.15.8180 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064831532) · [32.0.15.8278 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7078694248) · [32.0.15.8266 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7079940198) | | AMD Radeon RX 6650 XT | 32 | Passed, 64 lanes; skipped, Shader Model 6.5 on build 19045 | 408 queries passed | [32.0.21016.1010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064831931) · [32.0.21045.16010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069324502) · [32.0.21045.29003 report by Stac, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080989974) · [Independent 32.0.21045.16010 run, Windows 10 build 19045](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7083199356) | -| NVIDIA GeForce RTX 3080 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064860396) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066980626) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069497502) · [Independent 32.0.16.1088 run, source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070807071) · [Independent 32.0.16.1088 run on Windows 26200.9974](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7106733122) · [32.0.15.9174 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7126381753) | -| NVIDIA GeForce RTX 3060 Ti | 32 on every run | Skipped on every run, lane range 32–32 | 408 queries passed per run | [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/91#issuecomment-7065172784) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065311899) · [Independent 32.0.16.2101 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065622227) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069220530) | +| NVIDIA GeForce RTX 3080 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064860396) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066980626) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069497502) · [Independent 32.0.16.1088 run, source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070807071) · [Independent 32.0.16.1088 run on Windows 26200.9974](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7106733122) · [32.0.15.9174 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7126381753) · [32.0.16.2140 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7157696243) | +| NVIDIA GeForce RTX 3060 Ti | 32 on every run | Skipped on every run, lane range 32–32 | 408 queries passed per run | [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/91#issuecomment-7065172784) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065311899) · [Independent 32.0.16.2101 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065622227) · [32.0.16.1088 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069220530) · [Independent 32.0.16.1088 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120575857) | | Intel Arc B580 | 32 | Skipped, lane range 16–32 | 408 queries passed per run | [32.0.101.9175 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065357696) · [Independent run, same driver](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065417347) | | AMD Radeon RX 5700 XT | 32 | Passed, 64 lanes | Skipped, DXR unsupported | [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065505820) · [32.0.21045.29003 report, Windows build 26300.10075](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7124228921) | | NVIDIA GeForce RTX 3050 | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2114 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7065569484) · [32.0.16.2135 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066550311) | @@ -274,14 +274,14 @@ Results are grouped by adapter. Open a report for the driver, build and any capa | AMD Radeon RX 5600 XT | 32 | Passed, 64 lanes | Skipped, DXR unsupported | [32.0.21045.16010 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070378299) | | AMD Radeon RX 7900 XTX | 32 | Passed, 64 lanes | 408 queries passed | [32.0.32029.2010 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7074349630) · [Independent 32.0.32029.2010 run, source build at bc24dfd](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070787234) | | Intel Arc B390 GPU (Panther Lake) | 32 | Skipped, lane range 16–32 | 408 queries passed | [32.0.101.8509 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7074654193) | -| NVIDIA GeForce RTX 4080 SUPER | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069552323) · [32.0.16.2124 report by @MiguelMatMar](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077972845) · [32.0.16.1088 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118936753) · [32.0.16.1692 report, debug layer enabled, adapter filter 4080](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120825626) | +| NVIDIA GeForce RTX 4080 SUPER | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7069552323) · [32.0.16.2124 report by @MiguelMatMar](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077972845) · [32.0.16.1088 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118936753) · [32.0.16.1692 report, debug layer enabled, adapter filter 4080](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120825626) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7144597301) | | NVIDIA GeForce GTX 1650 | 32 | Skipped, lane range 32–32 | Skipped, DXR unsupported | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071119231) · [Independent 32.0.16.2124 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077261370) | | NVIDIA GeForce GTX 1060 6GB | 32 | Skipped, lane range 32–32 (Shader Model 6.5 on build 19045) | 408 comparisons passed via DXR Tier 1.0 in a source build; the v0.1.0 package skips at tier 1.0 | [Tier 1.0 retest](docs/experiments.md#independent-bvh-checks-on-pc) · [Original 32.0.15.6094 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7071767352) · [32.0.15.8278 report, v0.1.0 package](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7078236098) | | NVIDIA GeForce RTX 3050 Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7074983225) · [32.0.16.2114 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7076301686) · [32.0.16.2124 report, device 25a5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082968683) · [32.0.16.2124 rerun, package built at 5e279b1, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084126881) | | NVIDIA GeForce RTX 3050 6GB Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1062 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7075184791) | | NVIDIA Quadro M1000M | 32 | Skipped, lane range 32–32 | Skipped, DXR unsupported | [32.0.15.7371 report, source build at f8d11ad](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080685203) | | Intel HD Graphics 530 | 16 | Skipped, lane range 16–16, Shader Model 6.5 | Skipped, DXR unsupported | [31.0.101.2111 report, source build at f8d11ad](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080685522) | -| NVIDIA GeForce RTX 3060 Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1742 report, source build at f8d11ad](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080917685) · [32.0.16.2124 report, device 2560](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082050519) · [Independent 32.0.16.2124 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7105877025) | +| NVIDIA GeForce RTX 3060 Laptop GPU | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1742 report, source build at f8d11ad](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080917685) · [32.0.16.2124 report, device 2560](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082050519) · [Independent 32.0.16.2124 run, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7105877025) · [32.0.16.1714 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120166977) · [32.0.16.2124 report on Windows 26200.9974, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7150256046) | | Intel UHD Graphics (Core i5-12450HX, device 468b) | 16 | Skipped, lane range 16–16 | Skipped, DXR unsupported | [32.0.101.7026 report by @romanv9, package built at b42888d](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7086614504) | | Radeon RX 5700 | 32 | Passed, 64 lanes | Skipped, DXR unsupported | [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7118566107) | | AMD Radeon(TM) Graphics (Ryzen 7 9800X3D, device 13c0) | 32 | Passed, 64 lanes | 408 queries passed | [32.0.13018.6 report, source build at 4b740f9, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7120729567) | From 7323f487f0b35245951548a0d8fdc65c61e965dc Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 15:07:39 +0100 Subject: [PATCH 009/232] startup: accept compute execz blocks whose scalar results are dead (#2314) Replace the blanket refusal of scalar instructions in a block that s_cbranch_execz skips with a liveness rule: the block is translated unchanged when every scalar register, mask and SCC it may define is dead where it joins. Exec writes that cannot reactivate an inactive lane are accepted in straight-line blocks only: no branch in the block and no branch into it, a proven calculated s_setpc_b64 jump included. Only a 32-bit restore from a 32-bit copy of exec is trusted. A v_cmpx source taken as a destination and in-block exec copies tracked across a branch are refused and pinned. Pin the branch out of the block, vcc live at the join, a proven s_setpc_b64 inside the block, and a calculated jump onto the restore that bypasses the copy. Refs #2274 Co-authored-by: Claude Fable 5.2 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 3 +- docs/experiments.md | 56 ++++++- tests/startup_gfx2hlsl_compute_check.py | 184 +++++++++++++++++++++-- tools/startup/gfx2hlsl.py | 187 ++++++++++++++++++++++-- 4 files changed, 400 insertions(+), 30 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c9c36f51..7f8cb3078 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3196,7 +3196,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control mbcnt "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap) + foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap + j-scalar-dropped h-inner-unpredicated k-block-entered) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index cec85da97..17e9ede5f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13741,9 +13741,41 @@ root placement. The only in-repo evidence is the local compute-record scan above used s4 or s5. A numeric read of a user SGPR that the root signature does not place, including s0-s3, is refused because its value is unknown. -Inside a block that `s_cbranch_execz` skips, a scalar instruction is refused. The wave runs that block -when any lane is active, while the one-lane model would skip it for an inactive lane. An image sample -with implicit LOD is also refused, because a compute lane has no derivatives. +A block that `s_cbranch_execz` skips needs a liveness check. The wave runs the block when any lane is +active, so its scalar results are the same for every lane. The one-lane model skips the block for an +inactive lane. That lane can only differ from the wave by reading scalar state the block defines after the +join. When no lane is active, the wave skips the block too. The block is therefore translated unchanged +when every SGPR, `vcc`, `m0` and SCC it may define is dead where it joins. A backward liveness pass over +the program's instructions checks this. `m0` is always treated as live. + +Exec writes inside the block are accepted when the block is straight-line (no branch in it and none into +it) and the write cannot set the exec bit of a lane whose bit is clear, because that lane's bit is clear on +entry. Accepted forms: +- `s_and_saveexec` and `v_cmpx`; +- `s_and` or `s_andn2` that keeps exec; +- `s_or`, `s_xor` or a move whose other source only ever holds a copy of exec made earlier in the same block. + +That covers a nested `if` without its own branch. The copies are tracked in program order, which is every path +only in a straight-line block. + +Each instruction's reads and writes come from its printed operands, checked against the repository +decoder's spelling: +- `v_cmpx` prints no destination (its e64 form prints an unused SDST field), so all of its operands are reads; +- `s_setpc` and `s_movrel*` do not write their printed operand; +- `v_div_fmas` reads `vcc`; +- the high half of a mask is tracked apart from the low half. + +The block is still refused in these cases: +- a definition that is live at the join; +- any other exec write: exec set from a compare alone, restored from a mask saved before the block, or written + in a block with a branch or entered by one (a proven calculated `s_setpc_b64` jump counts), or restored through a 64-bit move, `s_or` or `s_xor` (the tracked copies name + registers, not which exec half they hold); +- an effect outside scalar registers, such as a scalar store or atomic, a barrier, `s_endpgm` or `v_writelane`; +- a branch out of the block; +- a backward `s_cbranch_execz`. + +Graphics stages keep today's per-lane behaviour. An image sample with implicit LOD is refused, because a +compute lane has no derivatives. The output is a `cs` HLSL main with `[numthreads]` and a version 2 manifest. The manifest has `stage cs` and `group` lines, plus one `uav table ` line for each store @@ -13778,14 +13810,28 @@ The runtime has no slot-67 path yet, so no translated compute program runs in th immediate offset. - Case C enables Y only, with group size 8x1x1 and 1x5x1 groups. It stores four words from every lane, then three words under an exec mask set from a compare. +- Case J leaves three of eight lanes active, then enters a block that `s_cbranch_execz` skips for the other + lanes. Inside the block it loads the store descriptor and computes a scalar from the group ID and the root + constants, which the active lanes store. The block's scalars are dead at the join. A control that drops one + of the block's scalar statements must mismatch. +- Case H nests an `s_and_saveexec`/`s_or` if inside such a block. Three lanes store two words, three more lanes + store one word, and the rest store nothing. A control that drops the inner exec predicate must mismatch. +- Case K enters such a block only in group 1; in the other three groups the whole wave skips it. A control that + runs the block for the skipped waves must mismatch. Each thread reads a read buffer at its own index and stores to its own destination. DXC compiles the HLSL for `cs_6_0`, and a plain D3D12 device dispatches it. The root signature is the test runner's (a root SRV, a root UAV and the root constants), so the manifest's table lines and the descriptor fetch are not exercised on the GPU. All 320 words are compared, including the sentinels. Four controls must each mismatch: swapping the X and Y group IDs, dropping the store, dropping case B's immediate offset, and dropping case C's exec -predicate. The pure-Python controls refuse every reviewed input that was previously accepted: a modified -descriptor word, an execz-skipped scalar write, an implicit-LOD sample and a misaligned immediate offset. +predicate. Three more cover the execz cases: dropping a scalar statement in case J's block, dropping case H's +inner exec predicate, and running case K's block for the skipped waves. + +The pure-Python controls cover: +- accepted and refused execz blocks: a dead definition is accepted; a live scalar definition, SCC consumed + after the join, a nested block and a backward branch are refused; +- a modified descriptor word, an implicit-LOD sample and a misaligned immediate offset, all refused; +- a store past the descriptor's range, which today translates with no range check. Translating every cached graphics request before and after the descriptor-tracking change gave identical output and refusals. The local check covered 925 requests, 123 of which translate. diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 495834cdb..baf870b70 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -4,7 +4,7 @@ binary reassemble the fixture sources and compare them with the words below dispatch translate, compile with DXC cs_6_0, dispatch and compare every word - control + control the same dispatch with a mutated translation, which must mismatch The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) @@ -23,14 +23,19 @@ - case E runs five SAVEEXEC forms with overlapping and distinct source registers. Four single-thread groups cover both input bits for EXEC and S0; each stores the saved EXEC, resulting SCC and new EXEC. - case F exchanges LDS dwords across the two halves of each 64-thread group and broadcasts lane 37. +- case J enables X only, v0, group size 8x1x1 and 4x1x1 groups, leaves lanes tid.x < 3 active and branches over + a block with s_cbranch_execz; the block loads the store descriptor and computes a scalar from the group ID and + the root constants that the active lanes store, and its scalars are dead where it joins; +- case H is case J's shape with a nested if inside the skipped block (s_and_saveexec, restored with s_or of the + saved mask): lanes tid.x < 3 store two words, lanes 3-5 one word, the rest none. - case G reads two independently offset LDS dwords with the address in the first destination VGPR. The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's r0, u0 and entry cbuffer. The manifest's table lines and the descriptor fetch are therefore not exercised on the GPU. All 320 words are compared, so a word outside the written records must keep the sentinel. The controls swap the X -and Y group IDs at entry, drop the store, drop case B's immediate offset, or drop case C's exec predicate; each must -change the readback. +and Y group IDs at entry, drop the store, drop case B's immediate offset, drop case C's exec predicate, or drop a +scalar statement inside case J's block; each must change the readback. """ import struct import subprocess @@ -167,6 +172,66 @@ def tidig(components): # A known SGPR base of UINT_MAX wraps to zero when the first mask bit is counted. SOURCE_D_WRAP = SOURCE_D.replace('v_mov_b32 v6, 7', 's_mov_b32 s22, -1').replace('v8, s20, v6', 'v8, s20, s22') WORDS_D_WRAP = WORDS_D.replace(bytes.fromhex('87020c7e080065d7140c0200'), bytes.fromhex('c10396be080065d7142c0000')) +SOURCE_J = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[12:15], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 2, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 3, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz 10 +s_load_dwordx4 s[16:19], s[10:11], 0x10 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) lgkmcnt(0) +v_xor_b32 v5, s22, v5 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_J = bytes.fromhex( + '06038abe' '80038bbe' '050308f4000000fa' '7fc08cbf' '0783148f' '1400064a' '82060834' '7e0395be' '8300887d' + '6a03febe' '0a0088bf' '050408f4100000fa' '07051693' '16041680' '001030e004050380' '70008cbf' '160a0a3a' + '001070e004050480' '1503febe' '000081bf') + +SOURCE_H = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 3, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz 11 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +v_xor_b32 v5, s22, v3 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_saveexec_b32 s0, vcc_lo +buffer_store_dword v5, v4, s[16:19], 0 offen +s_or_b32 exec_lo, exec_lo, s0 +v_not_b32 v6, v5 +buffer_store_dword v6, v4, s[16:19], 0 offen offset:4 +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_H = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '83060834' '7e0395be' '8600887d' + '6a03febe' '0b0088bf' '07051693' '16041680' '16060a3a' '8300887d' '6a3c80be' '001070e004050480' '7e007e88' + '056f0c7e' '041070e004060480' '1503febe' '000081bf') + +# Case K is case J with the condition on the group ID: only group 1 enters the block, and in groups 0, 2 and 3 the +# whole wave skips it. +SOURCE_K = SOURCE_J.replace('v_cmp_gt_u32 vcc_lo, 3, v0\n', 'v_mov_b32 v6, s7\nv_cmp_eq_u32_e32 vcc_lo, 1, v6\n') +WORDS_K = WORDS_J.replace(bytes.fromhex('8300887d'), bytes.fromhex('07020c7e' '810c847d')) def saveexec_fixture(): # RDNA 2 ISA, SOP1: D takes old EXEC, then EXEC takes the bitwise result and SCC reports nonzero. @@ -275,6 +340,9 @@ def saveexec_fixture(): 'D-wrap': (SOURCE_D_WRAP, WORDS_D_WRAP, USER7 | TGID_X | tidig(3), (4, 2, 4), (2, 1, 1)), 'E': (*saveexec_fixture(), USER7 | TGID_X | tidig(1), (1, 1, 1), (4, 1, 1)), 'F': (SOURCE_F, WORDS_F, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), + 'J': (SOURCE_J, WORDS_J, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), } @@ -320,6 +388,13 @@ def saveexec_fixture(): 'buffer_store_dword v5, v4, s[16:19], 0 offen': '001070e004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:6': '061070e004050480', 'buffer_store_dword v5, v4, s[16:19], 0 offen offset:4092': 'fc1f70e004050480', + 's_add_u32 s23, s7, 1': '07811780', + 's_cselect_b32 s23, 1, 0': '81801785', + 'v_cmp_gt_u32 vcc_lo, 3, v0': '8300887d', + 's_cbranch_execz 0': '000088bf', + 's_cbranch_execz 3': '030088bf', + 's_cbranch_execz 65534': 'feff88bf', + 's_or_b32 exec_lo, exec_lo, s21': '7e157e88', 's_and_b32 s17, s17, 0xc000ffff': '11ff1187ffff00c0', 's_and_b32 s17, s17, 0xc000fff0': '11ff1187f0ff00c0', 's_and_b32 s18, s18, 0xc000ffff': '12ff1287ffff00c0', @@ -404,6 +479,21 @@ def expected(name): if name == 'A': i = (gx + 3 * gy + 6 * gz) * 24 + tx + 2 * ty + 6 * tz out[i] = ((input_word(i) * 33) & MASK) ^ ((KEY + i * STRIDE) & MASK) + elif name == 'K': + i = gx * 8 + tx + if gx == 1: # only group 1's wave enters the block + out[i] = input_word(i) ^ ((gx * STRIDE + KEY) & MASK) + elif name == 'H': + i = gx * 8 + tx + value = i ^ ((KEY + gx * STRIDE) & MASK) + if tx < 3: # the nested if inside the skipped block + out[2 * i] = value + if tx < 6: # the skipped block + out[2 * i + 1] = ~value & MASK + elif name == 'J': + i = gx * 8 + tx + if tx < 3: # the lanes the compare leaves active; the others skip the block + out[i] = input_word(i) ^ ((gx * STRIDE + KEY) & MASK) elif name == 'C': i = gy * 8 + tx record = [input_word(i), i, (KEY + i * STRIDE) & MASK] @@ -683,17 +773,84 @@ def check_controls(): pipe = G.ComputePipeline(splice('s_and_b32 s18, s18, 0xffff'), root_blob(), CASES['A'][2], (2, 3, 4), refusals=refusals) assert pipe.modified == {(('table', 1), 16)}, pipe.modified assert [G.normalize_refusal(r) for r, _ in refusals] == ['buffer store through a modified descriptor'], refusals - # A scalar write in a block s_cbranch_execz skips: the wave runs it when any lane is active, so a per-lane skip - # would store 0 for inactive lanes. Refused with exec from a plain move and in the saveexec form. - for lines in (['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo', - 's_cbranch_execz 1', 's_add_u32 s20, s7, 1', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s20'], + # Scalar instructions in a block s_cbranch_execz skips. The wave runs the block when any lane is active, so an + # inactive lane that skips it can differ only by reading, after the join, scalar state the block defines. + # Live after the join: the block's s20 is read by v_mov_b32 v5, s20, so the hardware stores gid.x + 1 for every + # lane while a per-lane skip would store 0. Still refused, with exec from a plain move and in the saveexec form. + enter = ['s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo'] + leave = ['s_mov_b32 exec_lo, s21'] + for lines in (enter + ['s_cbranch_execz 1', 's_add_u32 s20, s7, 1'] + leave + ['v_mov_b32 v5, s20'], ['v_cmp_gt_u32 vcc_lo, 1, v0', 's_and_saveexec_b32 s0, vcc_lo', 's_cbranch_execz 1', 's_add_u32 s20, s7, 1', 's_or_b32 exec_lo, exec_lo, s0', 'v_mov_b32 v5, s20']): - refused('s_add_u32 inside a block s_cbranch_execz skips', lambda lines=lines: translate( - 'A', code=splice(*lines)).hlsl_cs()) - # The same block without the branch translates: the scalar write then runs for every lane. - translate('A', code=splice('s_mov_b32 s21, exec_lo', 'v_cmp_gt_u32 vcc_lo, 1, v0', 's_mov_b32 exec_lo, vcc_lo', - 's_add_u32 s20, s7, 1', 's_mov_b32 exec_lo, s21', 'v_mov_b32 v5, s20')).hlsl_cs() + refused('s_add_u32 inside a block s_cbranch_execz skips per lane: definition of s20', + lambda lines=lines: translate('A', code=splice(*lines)).hlsl_cs()) + # Dead after the join (s23 and SCC are not read again): accepted, and case J runs such a block on the GPU. + translate('A', code=splice(*enter, 's_cbranch_execz 1', 's_add_u32 s23, s7, 1', *leave)).hlsl_cs() + translate('J').hlsl_cs() + # SCC set in the block and consumed after the join by s_cselect: refused. + refused('definition of scc', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 1', 's_add_u32 s23, s7, 1', *leave, 's_cselect_b32 s23, 1, 0')).hlsl_cs()) + # Exec writes inside the block. For a lane whose exec bit is clear on entry, the wave's writes must keep it clear, + # so its exec at the join is what the model has. Exec set from a compare alone can set it: refused. + refused('exec write', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 3', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_mov_b32 exec_lo, vcc_lo', 's_cbranch_execz 0', + *leave)).hlsl_cs()) + # A nested if (s_and_saveexec, restored with s_or of the mask saved in the block) keeps it clear: accepted, and + # case H runs one on the GPU. Restoring with a mask saved before the block (s21) could set it: refused. + translate('A', code=splice(*enter, 's_cbranch_execz 3', 'v_cmp_gt_u32 vcc_lo, 3, v0', + 's_and_saveexec_b32 s0, vcc_lo', 's_or_b32 exec_lo, exec_lo, s0', *leave)).hlsl_cs() + translate('H').hlsl_cs() + refused('exec write', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 3', 'v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_saveexec_b32 s0, vcc_lo', + 's_or_b32 exec_lo, exec_lo, s21', *leave)).hlsl_cs()) + # A backward s_cbranch_execz: refused. + refused('s_cbranch_execz to a block before it', lambda: translate('A', code=splice( + 's_add_u32 s23, s7, 1', 's_cbranch_execz 65534')).hlsl_cs()) + # The same live-out block without the branch translates: the scalar write then runs for every lane. + translate('A', code=splice(*enter, 's_add_u32 s20, s7, 1', *leave, 'v_mov_b32 v5, s20')).hlsl_cs() + # Review inputs that were accepted. v_cmpx prints no destination: in `v_cmpx_gt_u32_e32 s23, v0` after the join, + # s23 is read (the wave compares against gid.x + 1 in every lane), so the block's s23 is live: refused. + prologue = '06038abe' '80038bbe' '050308f4000000fa' '7fc08cbf' # s[12:15] = the table's first descriptor + for cmpx in ('1700a87d', '0000d4d417000200'): # v_cmpx_gt_u32 s23, v0 in the e32 and e64 forms + program = bytes.fromhex(prologue + '800397be' '7e0395be' '8300887d' '6a03febe' '010088bf' '07811780' '1503febe' + + cmpx + '82000834' '001070e004000380' '000081bf') + refused('s_add_u32 inside a block s_cbranch_execz skips per lane: definition of s23', + lambda program=program: translate('A', code=program).hlsl_cs()) + # A branch inside the block: on the path that skips `s_mov_b32 s21, exec_lo` the restore reads the mask saved + # before the block, which can set inactive lanes. Exec writes are accepted in straight-line blocks only: refused. + program = bytes.fromhex(prologue + '82000834' '7e0395be' '8300887d' '6a03febe' '040088bf' '048007bf' '010085bf' + '7e0395be' '1503febe' '001070e004000380' '000081bf') + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', + lambda: translate('A', code=program).hlsl_cs()) + # saved tracks register names, not which exec half was copied: two 32-bit copies restored through a 64-bit move + # would set exec_hi from exec_lo. Refused; the 32-bit restore above stays accepted. + SPLICE.update({'s_mov_b32 s22, exec_lo': '7e0396be', 's_mov_b32 s23, exec_lo': '7e0397be', + 's_mov_b64 exec, s[22:23]': '1604febe'}) + refused('s_mov_b64 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate('A', code=splice( + *enter, 's_cbranch_execz 3', 's_mov_b32 s22, exec_lo', 's_mov_b32 s23, exec_lo', 's_mov_b64 exec, s[22:23]', + *leave)).hlsl_cs()) + # Refusals of the block scan with short programs: a branch leaving the block, a vcc definition that a vcc branch + # reads after the join, and a proven s_setpc_b64 (GETPC, ADD, ADDC, SETPC) inside the block. + SPLICE['s_branch 2'] = '020082bf' + refused('s_branch inside a block s_cbranch_execz skips per lane: branch out of the block', lambda: translate( + 'A', code=splice(*enter, 's_cbranch_execz 1', 's_branch 2', *leave)).hlsl_cs()) + refused('v_cmp_gt_u32_e32 inside a block s_cbranch_execz skips per lane: definition of vcc', lambda: translate( + 'A', code=splice(*enter, 's_cbranch_execz 1', 'v_cmp_gt_u32 vcc_lo, 1, v0', *leave, + 's_cbranch_vccz 1', 'v_mov_b32 v5, s20')).hlsl_cs()) + SPLICE.update({'s_cbranch_execz 4': '040088bf', 's_getpc_b64 s[22:23]': '001f96be', 's_add_u32 s22, s22, 12': '168c1680', + 's_addc_u32 s23, s23, 0': '17801782', 's_setpc_b64 s[22:23]': '162080be'}) + refused('s_setpc_b64 inside a block s_cbranch_execz skips per lane: effect outside scalar registers', lambda: translate( + 'A', code=splice(*enter, 's_cbranch_execz 4', 's_getpc_b64 s[22:23]', 's_add_u32 s22, s22, 12', + 's_addc_u32 s23, s23, 0', 's_setpc_b64 s[22:23]', *leave)).hlsl_cs()) + # A proven calculated jump into the block bypasses the copy like a direct branch does: the restore at the target + # reads a mask the block did not save. GETPC / ADD 20 / ADDC / SETPC lands on the restore; both are refused. + SPLICE.update({'s_add_u32 s22, s22, 20': '16941680', 's_cbranch_execz 2': '020088bf'}) + block = ['s_cbranch_execz 2', 's_mov_b32 s21, exec_lo', *leave] + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate( + 'A', code=splice('s_branch 2', *block)).hlsl_cs()) + refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate( + 'A', code=splice('s_getpc_b64 s[22:23]', 's_add_u32 s22, s22, 20', 's_addc_u32 s23, s23, 0', + 's_setpc_b64 s[22:23]', *block)).hlsl_cs()) # An implicit-LOD sample has no derivatives in a compute lane; the level-zero form translates. load = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40') sample = 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D' @@ -741,6 +898,9 @@ def check_binary(llvm_mc): 'd-exec': ('D', 'if (exec & 1) v10 =', 'v10 ='), 'f-peer': ('F', '0x00000080u ^ v4', 'v4'), 'f-broadcast': ('F', 'lds[(v8 + 164u) >> 2]', 'lds[(v8 + 160u) >> 2]'), + 'j-scalar-dropped': ('J', ' s22 = s7 * ud1;\n', ''), + 'h-inner-unpredicated': ('H', 'if (exec & 1) u0.Store(a, v5);', 'u0.Store(a, v5);'), + 'k-block-entered': ('K', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipped waves run it 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), 'g-overlap': ('G', 'v7 = lds[(a + 144u)', 'v7 = lds[(v6 + 144u)'), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6d48308b4..7b67482df 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -440,8 +440,111 @@ def reg_range(tok): return None -# Scalar instructions with no scalar or exec effect, allowed inside a compute block s_cbranch_execz skips. -SKIPPABLE_SCALAR = ('s_waitcnt', 's_nop', 's_inst_prefetch', 's_clause', 's_cbranch_', 's_branch') +# Scalar state for the compute execz-block check (Stage.execz_refusals): registers as 's', 'vcc', 'exec', 'm0' +# and 'scc'. Reads may be over-approximated and must-writes under-approximated; both only add refusals. +# The low half of a mask (vcc_lo, exec_lo) is 'vcc' / 'exec', the high half 'vcc_hi' / 'exec_hi', and a 64-bit +# operand both, so a write of one half never counts as writing the other. +SCALAR_TOKEN = re.compile(r'\bs\[(\d+):(\d+)\]|\bs(\d+)\b|\b(vcc|exec)(_lo|_hi)?\b|\b(m0)\b|\bsrc_(scc)\b') +EXEC_KEYS = {'exec', 'exec_hi'} +NO_SCALAR_EFFECT = ('s_waitcnt', 's_nop', 's_inst_prefetch', 's_clause', 's_cbranch_', 's_branch') +# Forms that print no destination: every printed scalar operand is read. v_cmpx writes EXEC implicitly; its e32 and +# SDWA forms print only sources, and the repository decoder prints the e64 form's unused SDST field first. +# s_setpc reads its address; s_movrel* address a register through m0, so their printed operand is not a plain write. +NO_DESTINATION = ('v_cmpx', 's_setpc', 's_movrel', 'v_movrel') +IMPLICIT_VCC_READ = ('v_div_fmas',) +SCC_READERS = ('s_cselect', 's_cmov', 's_addc', 's_subb', 's_cbranch_scc') +READ_MODIFY_WRITE = ('s_addk_i32', 's_mulk_i32', 's_cmov', 's_bitset', 'v_mac', 'v_fmac') +TWO_DESTINATIONS = ('v_add_co', 'v_sub_co', 'v_subrev_co', 'v_div_scale', 'v_mad_u64_u32', 'v_mad_i64_i32') +# Effects outside scalar registers, or control flow the wave takes as a whole: refused inside such a block. +EXECZ_REFUSED = ('s_endpgm', 's_store', 's_atomic', 's_buffer_store', 's_buffer_atomic', 's_barrier', 's_sendmsg', + 's_setreg', 's_setpc', 's_swappc', 's_dcache', 's_icache', 's_gl1', 's_memtime', 's_memrealtime', + 's_trap', 's_sleep', 'v_writelane', 's_movrel', 'v_movrel') + + +def scalar_tokens(text): + out = set() + for lo, hi, single, mask, half, m0, scc in SCALAR_TOKEN.findall(text): + if lo: + out.update('s%d' % n for n in range(int(lo), int(hi) + 1)) + elif mask: + out.update({'_lo': {mask}, '_hi': {mask + '_hi'}}.get(half, {mask, mask + '_hi'})) + else: + out.add('s' + single if single else m0 or scc) + return out + + +def is_exec(regs): + return regs in ({'exec'}, EXEC_KEYS) + + +def exec_stays_clear(name, asm, saved): + """True when an exec write cannot set the bit of a lane whose bit is clear: exec & x (s_and_saveexec, v_cmpx, + s_and or s_andn2 with exec as the kept operand), or exec | x, exec ^ x or a move of x where x is only ever a copy + of exec made inside the same skipped block (so x's bit is clear for that lane too).""" + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + if base.startswith(('s_and_saveexec', 'v_cmpx')): + return True + if not ops or not is_exec(scalar_tokens(ops[0])): + return False + srcs = [scalar_tokens(op) for op in ops[1:]] + # saved tracks register names, not which exec half was copied, so only a 32-bit restore is trusted + copies = lambda regs: bool(regs) and regs <= saved and base.endswith('32') + if base in ('s_and_b32', 's_and_b64'): + return any(is_exec(regs) for regs in srcs) + if base in ('s_andn2_b32', 's_andn2_b64'): + return bool(srcs) and is_exec(srcs[0]) + if base in ('s_or_b32', 's_or_b64', 's_xor_b32', 's_xor_b64') and len(srcs) == 2: + return all(is_exec(regs) or copies(regs) for regs in srcs) + if base in ('s_mov_b32', 's_mov_b64') and len(srcs) == 1: + return copies(srcs[0]) + return False + + +def exec_copies_after(name, asm, saved, may): + """The registers that hold only copies of exec made in the block, after this instruction.""" + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + dests = scalar_tokens(ops[0]) - EXEC_KEYS - {'scc'} if ops else set() + saved = saved - (may - EXEC_KEYS - {'scc'}) + if base.startswith('s_and_saveexec') or (base in ('s_mov_b32', 's_mov_b64') and len(ops) == 2 + and is_exec(scalar_tokens(ops[1]))): + saved |= dests + return saved + + +def scalar_effects(name, asm): + """(reads, must-writes, may-writes) of scalar state for one decoded instruction.""" + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + if base.startswith(NO_SCALAR_EFFECT) or base == 's_endpgm': + reads = {'scc'} if base.startswith('s_cbranch_scc') else {'vcc'} if base.startswith('s_cbranch_vcc') else \ + {'exec'} if base.startswith('s_cbranch_exec') else set() + return reads, set(), set() + if base.startswith('v_cmpx'): + return scalar_tokens(' '.join(ops)) | {'exec'}, {'exec'}, set(EXEC_KEYS) + if '_store' in base or base.startswith(('ds_write', 'exp') + NO_DESTINATION) or not ops: + return scalar_tokens(' '.join(ops)) | ({'m0'} if 'movrel' in base else set()), set(), set() + if base.startswith(('s_cmp', 's_bitcmp')): + return scalar_tokens(' '.join(ops)), {'scc'}, {'scc'} + two = base.startswith(TWO_DESTINATIONS) + dests, srcs = ops[:2] if two else ops[:1], ops[2:] if two else ops[1:] + writes = scalar_tokens(' '.join(dests)) + reads = scalar_tokens(' '.join(srcs)) + if base.startswith(READ_MODIFY_WRITE): + reads |= writes + if base.startswith(SCC_READERS) or (base in SCA and 'scc' in SCA[base][0]): + reads.add('scc') + if base.startswith(IMPLICIT_VCC_READ): + reads.add('vcc') + may = set() + if 'saveexec' in base or 'wrexec' in base: + reads.add('exec') + writes.add('exec') + may |= EXEC_KEYS + if (base in SCA and SCA[base][1]) or 'saveexec' in base or 'wrexec' in base: + writes.add('scc') + return reads, writes, writes | may | ({'scc'} if base.startswith('s_') else set()) # Forms with no scalar destination: their printed operands are all sources (v_cmpx writes only EXEC, which the # symbolic tracking does not hold). @@ -1253,6 +1356,73 @@ def const_words(self, tok): words = [self.is_const(n) for n in range(r[1], r[2] + 1)] return None if any(w is None for w in words) else words + def execz_refusals(self): + """{offset: reason} for compute blocks that s_cbranch_execz skips and the one-lane model cannot run. + + The wave runs such a block when any lane is active, so its scalar results are the same for every lane; the + model skips the block for an inactive lane. That lane can differ from the wave only by reading, after the + join, scalar state the block defines (no lane active means the wave skipped the block too). The block is + therefore accepted unchanged when every scalar register, mask and SCC it may define is dead where it joins, + and it has no effect outside scalar registers and no branch out of it. An exec write is accepted in a + straight-line block (no branch in it, none into it) when it cannot set the bit of a lane whose bit is clear + (exec_stays_clear): such a lane's bit is clear on entry, so the wave leaves it clear and its exec at the + join is the model's. A live definition, another exec write, a refused effect, a branch leaving the block + or a backward s_cbranch_execz is refused.""" + offsets = [ins[0] for ins in self.ins] + index = {off: i for i, off in enumerate(offsets)} + effects = [scalar_effects(name, asm) for _, _, name, asm in self.ins] + succ = [] + targets = [] # every branch target, the proven calculated s_setpc_b64 ones included + for i, (off, n, name, asm) in enumerate(self.ins): + to = int(parse(asm)[1][0].split('_')[1], 16) if name.startswith(('s_cbranch', 's_branch')) else None + if name == 's_setpc_b64': # a proven calculated jump reaches its target + to = getattr(self, 'calculated_pc', {}).get(off) + nxt = [i + 1] if i + 1 < len(self.ins) and name not in ('s_branch', 's_endpgm') else [] + if to is not None: + targets.append(to) + succ.append(nxt + ([index[to]] if to in index else [])) + live_in = [set() for _ in self.ins] + changed = True + while changed: + changed = False + for i in reversed(range(len(self.ins))): + out = set().union(*(live_in[s] for s in succ[i])) if succ[i] else set() + reads, writes, _ = effects[i] + value = reads | (out - writes) + if value != live_in[i]: + live_in[i], changed = value, True + refused = {} + for b, (off, n, name, asm) in enumerate(self.ins): + if name != 's_cbranch_execz': + continue + t = index.get(int(parse(asm)[1][0].split('_')[1], 16)) + if t is None or t <= b: + refused.setdefault(off, 's_cbranch_execz to a block before it') + continue + live = live_in[t] | {'m0'} # m0 is also read implicitly; treat it as live + saved = set() # registers whose every write in the block so far is a copy of exec + # The copies are tracked in program order, which is every path only in a straight-line block: no branch + # in it and no branch into it. Elsewhere an exec write is refused. + straight = not any(self.ins[k][2].startswith(('s_cbranch', 's_branch')) for k in range(b + 1, t)) and \ + not any(index.get(target) in range(b + 1, t) for target in targets) + for i in range(b + 1, t): + at, _, inner, inner_asm = self.ins[i] + may = effects[i][2] + reason = None + if inner.startswith(EXECZ_REFUSED): + reason = 'effect outside scalar registers' + elif inner.startswith(('s_cbranch', 's_branch')) and not ( + b < index.get(int(parse(inner_asm)[1][0].split('_')[1], 16), -1) <= t): + reason = 'branch out of the block' + elif may & EXEC_KEYS and not (straight and exec_stays_clear(inner, inner_asm, saved)): + reason = 'exec write' + elif (may - EXEC_KEYS) & live: + reason = 'definition of %s, live where the block joins' % ', '.join(sorted((may - EXEC_KEYS) & live)) + saved = exec_copies_after(inner, inner_asm, saved, may) + if reason: + refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason)) + return refused + # ---- instruction translation ------------------------------------------------------------- def joined_registers(self, with_cfg=False): """{branch target: registers whose program-order symbol may not hold on every path into it}. @@ -1393,7 +1563,6 @@ def translate(self): refusals.append((str(reason), self.kind)) self.calculated_pc = {} targets = set() - skipped = [] # compute: (branch, target) of each s_cbranch_execz targets.update(target for target in self.calculated_pc.values() if target is not None) # (branch, target) of every branch, the proven s_setpc_b64 jumps included branches = [(pc, target) for pc, target in self.calculated_pc.items() if target is not None] @@ -1402,9 +1571,8 @@ def translate(self): target = int(parse(asm)[1][0].split('_')[1], 16) targets.add(target) branches.append((off, target)) - if name == 's_cbranch_execz' and self.kind == 'cs': - skipped.append((off, target)) join_writes = self.join_writes(branches) + refused = self.execz_refusals() if getattr(self, 'kind', None) == 'cs' else {} # probes skip __init__ joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) init_sym = dict(self.sym) init_exec_known = getattr(self, 'exec_known', True) @@ -1545,13 +1713,8 @@ def translate(self): dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests try: - if any(branch < off < target or target <= off < branch for branch, target in skipped) and ( - name.startswith(('s_', 'v_readlane', 'v_readfirstlane', 'v_writelane')) - and not name.startswith(SKIPPABLE_SCALAR) - and not (name == 's_setpc_b64' and off in self.calculated_pc)): - # The wave runs this block when any lane is active, so its scalar state changes for every - # lane; the one-lane model would skip it for an inactive lane. - raise Unsupported('%s inside a block s_cbranch_execz skips per lane' % name) + if off in refused: + raise Unsupported(refused[off]) base = re.sub(r'_e(32|64)$', '', name) if base.startswith('s_cbranch_'): cond = base[10:] From 292858ebf72f51f435632ad05ac049ff54bf6b2a Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:07:54 +0200 Subject: [PATCH 010/232] script: extract main(argv) and guard malformed RPF9/PSIN inputs in script_state_probe with unit suite (#2352) --- CMakeLists.txt | 2 + tests/script_state_probe_check.py | 377 ++++++++++++++++++++++++++++++ tools/script_state_probe.py | 14 +- 3 files changed, 390 insertions(+), 3 deletions(-) create mode 100644 tests/script_state_probe_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f8cb3078..7f897418c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7791,6 +7791,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(pe_authentihash_oracle PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME script_dispatch_pairs COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$") + add_test(NAME script_state_probe_checks COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/script_state_probe_check.py") add_test(NAME bcpack_prefix_and_mip_tail COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bcpack_check.py") add_test(NAME bcpack_rans_symbols COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/script_state_probe_check.py b/tests/script_state_probe_check.py new file mode 100644 index 000000000..eddfe4745 --- /dev/null +++ b/tests/script_state_probe_check.py @@ -0,0 +1,377 @@ +"""Pure-Python unit and CLI validation suite for tools/script_state_probe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import mmap +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "script_state_probe.py" +sys.path.insert(0, str(ROOT / "tools")) + +import script_state_probe as probe # noqa: E402 + + +def _attr(name: str, spelling: str, raw: int, kind: int) -> bytes: + return struct.pack(" list[bytes]: + rows = [ + _attr("priority", str(priority), priority, 3), + _attr("blendduration", "37", 37, 3), + _attr("orbitdistance", "1.500000", orbit_raw, 2), + _attr("pitchlimits", "-0.250000,0.500000,0.000000", 0, 1), + _attr("headinglimits", "-1.000000,1.000000,0.000000", 1, 1), + ] + return [row for idx, row in enumerate(rows, 1) if idx != drop] + + +def _build_record_fields( + *, + priorities: tuple[int, ...] = (9,), + state_label: str = "synthetic_orbit", + duplicate_state_id: bool = False, + id_kind: int = 5, + root_id: int = 1, + marker: int = 0xAAAAAAAAAAAAAAAA, + truncate_schema_by: int = 0, + lrsc_magic: bytes = b"0DRPz", + chks_payload_len: int = 12, + chks_total_delta: int = 0, + corrupt_zlib: bool = False, +) -> bytes: + """Build one 16-byte-aligned zlib-compressed PSIN..CHKS record payload (without 9FPR header).""" + attrs = bytearray() + nodes = bytearray() + + def add_node(name: str, parent: int, row_list: list[bytes]) -> int: + idx = len(nodes) // 16 + nodes.extend( + struct.pack( + " 1: + root_parent = add_node("root", root_parent, []) + for priority in priorities: + ids = [_attr("id", state_label, 0, id_kind)] + if duplicate_state_id: + ids.append(_attr("id", "other_label", 0, 5)) + state_idx = add_node("state", root_parent, ids) + add_node("camera", state_idx, _camera_attrs(priority)) + + vecs = struct.pack("<6f", -0.25, 0.5, 0.0, -1.0, 1.0, 0.0) + arrays = ((len(attrs) // 16, 2), (0, 0), (2, 4), (0, 0), (len(nodes) // 16, 3)) + root_blob = b"".join(struct.pack("4sI", tag, len(part) + 8)) + body.extend(part) + + chks_section_size = 8 + chks_payload_len + declared_total = len(body) + chks_section_size + chks_total_delta + chks_payload = struct.pack(">I", declared_total) + bytes(max(0, chks_payload_len - 4)) + body.extend(struct.pack(">4sI", b"CHKS", chks_section_size)) + body.extend(chks_payload[:chks_payload_len]) + + compressed = zlib.compress(bytes(body)) + if corrupt_zlib: + # Keep valid zlib CMF/FLG prefix at 16-byte boundary, corrupt deflate payload. + compressed = compressed[:4] + b"\xff\x00\xff\x00" + compressed[8:] + return compressed + + +def _build_rpf9(*records_payloads: bytes) -> bytes: + archive = bytearray(b"9FPR") + for payload in records_payloads: + archive.extend(bytes(-len(archive) % 16)) + archive.extend(payload) + return bytes(archive) + + +def _unpack_first_fields(archive_bytes: bytes) -> dict[str, memoryview]: + mv = memoryview(archive_bytes) + found = list(probe.records(mv)) + assert len(found) == 1, f"expected 1 record, got {len(found)}" + return found[0] + + +class ScriptStateProbeUnitTests(unittest.TestCase): + def test_joaat_and_literal_spellings(self): + self.assertEqual(probe.joaat(""), 0) + self.assertEqual(probe.joaat("a"), 0xCA2E9442) + self.assertEqual(probe.joaat("state"), 0x77A848C7) + with self.assertRaises(UnicodeEncodeError): + probe.joaat("café") + + vecs = struct.pack("<3f", -0.25, 0.5, 0.0) + self.assertEqual(probe.literal(0xFFFFFFFB, 3, vecs), "-5") + self.assertEqual(probe.literal(0x3FC00000, 2, vecs), "1.500000") + self.assertEqual(probe.literal(0, 1, vecs), "-0.250000,0.500000,0.000000") + self.assertIsNone(probe.literal(1, 1, vecs)) + self.assertIsNone(probe.literal(0x7FC00000, 2, vecs)) + self.assertIsNone(probe.literal(0, 5, vecs)) + non_finite_vecs = struct.pack("<3f", 1.0, float("inf"), 0.0) + self.assertIsNone(probe.literal(0, 1, non_finite_vecs)) + + def test_verified_camera_accepts_exact_hashes_and_rejects_mismatches(self): + vecs = struct.pack("<6f", -0.25, 0.5, 0.0, -1.0, 1.0, 0.0) + values = { + probe.joaat("priority"): (probe.joaat("9"), 9, 3), + probe.joaat("blendduration"): (probe.joaat("37"), 37, 3), + probe.joaat("orbitdistance"): (probe.joaat("1.500000"), 0x3FC00000, 2), + probe.joaat("pitchlimits"): (probe.joaat("-0.250000,0.500000,0.000000"), 0, 1), + probe.joaat("headinglimits"): (probe.joaat("-1.000000,1.000000,0.000000"), 1, 1), + } + verified = probe.verified_camera(values, vecs) + self.assertEqual( + verified, + { + "priority": "9", + "blendduration": "37", + "orbitdistance": "1.500000", + "pitchlimits": "-0.250000,0.500000,0.000000", + "headinglimits": "-1.000000,1.000000,0.000000", + }, + ) + missing_key = dict(values) + missing_key.pop(probe.joaat("priority")) + self.assertIsNone(probe.verified_camera(missing_key, vecs)) + + bad_digest = dict(values) + bad_digest[probe.joaat("priority")] = (probe.joaat("10"), 9, 3) + self.assertIsNone(probe.verified_camera(bad_digest, vecs)) + + def test_tree_arrays_inspect_tree_and_inspect_single_vs_ambiguous(self): + single_archive = _build_rpf9(_build_record_fields(priorities=(9,))) + fields = _unpack_first_fields(single_archive) + nodes, attrs, vectors = probe.tree_arrays(fields) + counts, matches = probe.inspect_tree(nodes, attrs, vectors, probe.joaat("synthetic_orbit"), record_index=0) + self.assertEqual(dict(counts), {"state_nodes": 1, "camera_parameter_sets": 1, "all_five_literals_verified": 1}) + self.assertEqual(len(matches), 1) + self.assertEqual(matches[0]["node_path"], [0]) + self.assertEqual(matches[0]["first_verified_example"]["priority"], "9") + + ambiguous_archive = _build_rpf9(_build_record_fields(priorities=(9, 17))) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + single_path = root / "single.rpf" + single_path.write_bytes(single_archive) + single_res = probe.inspect(single_path, "synthetic_orbit") + self.assertEqual(single_res["first_verified_example"]["priority"], "9") + self.assertNotIn("ambiguous_state_candidates", single_res) + + ambig_path = root / "ambiguous.rpf" + ambig_path.write_bytes(ambiguous_archive) + ambig_res = probe.inspect(ambig_path, "synthetic_orbit") + self.assertIsNone(ambig_res["first_verified_example"]) + self.assertEqual( + [c["node_path"] for c in ambig_res["ambiguous_state_candidates"]], + [[0, 1], [0, 3]], + ) + + no_state_res = probe.inspect(single_path) + self.assertIsNone(no_state_res["requested_state"]) + self.assertIsNone(no_state_res["first_verified_example"]) + + +class ScriptStateProbeCliPositiveTests(unittest.TestCase): + def test_main_argv_json_output_and_subprocess_exit_0(self): + archive_bytes = _build_rpf9(_build_record_fields(priorities=(9,))) + with tempfile.TemporaryDirectory() as tmp: + archive = Path(tmp) / "valid.rpf" + archive.write_bytes(archive_bytes) + + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + rc = probe.main([str(archive), "--state", "synthetic_orbit"]) + self.assertEqual(rc, 0) + self.assertEqual(stderr.getvalue(), "") + payload = json.loads(stdout.getvalue()) + self.assertEqual(payload["requested_state"], "synthetic_orbit") + self.assertEqual(payload["first_verified_example"]["orbitdistance"], "1.500000") + self.assertEqual(payload["counts"]["node_trees"], 1) + + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(archive), "--state", "synthetic_orbit"], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), payload) + + +class ScriptStateProbeNegativeAndMutationTests(unittest.TestCase): + def _assert_main_exit(self, argv: list[str], *, expected_code: int, fragment: str = "") -> str: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + with self.assertRaises(SystemExit) as exc: + probe.main(argv) + self.assertEqual(exc.exception.code, expected_code) + self.assertEqual(stdout.getvalue(), "") + err = stderr.getvalue() + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr error for {argv!r}") + if fragment: + self.assertIn(fragment, err) + return err + + def test_missing_dir_empty_file_and_bad_magic_controls(self): + self._assert_main_exit([], expected_code=2) + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.rpf" + self._assert_main_exit([str(missing)], expected_code=1, fragment=missing.name) + + folder = root / "dir_archive" + folder.mkdir() + self._assert_main_exit([str(folder)], expected_code=1, fragment=folder.name) + + # 0-byte archive must fail cleanly before calling mmap.mmap. + empty = root / "empty.rpf" + empty.write_bytes(b"") + with mock.patch.object(mmap, "mmap", side_effect=AssertionError("mmap must not run on 0-byte file")): + with self.assertRaisesRegex(ValueError, "Empty archive"): + probe.inspect(empty) + err = self._assert_main_exit([str(empty)], expected_code=1, fragment="Empty archive") + self.assertNotIn("cannot mmap an empty file", err) + + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(empty)], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("Empty archive", proc.stderr) + + bad_magic = root / "bad_magic.rpf" + bad_magic.write_bytes(b"NOPE" + b"\x00" * 16) + with self.assertRaisesRegex(ValueError, "Expected an RPF9 archive"): + probe.inspect(bad_magic) + self._assert_main_exit([str(bad_magic)], expected_code=1, fragment="Expected an RPF9 archive") + + def test_malformed_rpf9_psin_records_and_tree_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + + # Corrupt zlib stream -> 0 section records decoded, no crash. + corrupt_zlib = root / "corrupt_zlib.rpf" + corrupt_zlib.write_bytes(_build_rpf9(_build_record_fields(corrupt_zlib=True))) + self.assertEqual(probe.inspect(corrupt_zlib)["counts"], {}) + + # Invalid CHKS payload length or mismatched CHKS total length -> skipped cleanly. + for label, kw in ( + ("bad_chks_len", {"chks_payload_len": 8}), + ("bad_chks_total", {"chks_total_delta": 4}), + ): + with self.subTest(case=label): + path = root / f"{label}.rpf" + path.write_bytes(_build_rpf9(_build_record_fields(**kw))) + self.assertEqual(probe.inspect(path)["counts"], {}) + + # Bad LRSC magic -> record counted, tree_arrays returns None. + bad_lrsc = root / "bad_lrsc.rpf" + bad_lrsc.write_bytes(_build_rpf9(_build_record_fields(lrsc_magic=b"BAD!0"))) + self.assertEqual(probe.inspect(bad_lrsc)["counts"], {"section_records": 1}) + + # Structural errors guarded inside inspect / main(argv) -> exit 1 without traceback. + error_cases = ( + ("bad_root_id", {"root_id": 0}, "Invalid instance or schema directory"), + ("invalid_marker", {"marker": 0xBBBBBBBBBBBBBBBB}, "Invalid instance block"), + ("truncated_schema", {"truncate_schema_by": 8}, "Truncated schema members"), + ("duplicate_state_id", {"duplicate_state_id": True}, "Duplicate state ID attribute"), + ("non_label_state_id", {"id_kind": 3}, "Non-label state ID attribute"), + ) + for label, opts, expected_msg in error_cases: + with self.subTest(case=label): + path = root / f"{label}.rpf" + path.write_bytes(_build_rpf9(_build_record_fields(**opts))) + with self.assertRaisesRegex(ValueError, expected_msg): + probe.inspect(path, "synthetic_orbit") + self._assert_main_exit([str(path), "--state", "synthetic_orbit"], expected_code=1, fragment=expected_msg) + + # Bad instance/schema directory sizes in LRSC. + bad_dir_bytes = _build_rpf9(_build_record_fields()) + fields = _unpack_first_fields(bad_dir_bytes) + bad_lrsc_hdr = bytearray(fields["LRSC"]) + struct.pack_into(" int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--state", help="Report at most one hash-verified example for this state label") - args = parser.parse_args() + args = parser.parse_args(argv) try: result = inspect(args.archive, args.state) - except (OSError, ValueError) as exc: + except (OSError, ValueError, struct.error, zlib.error) as exc: parser.exit(1, f"{args.archive}: {exc}\n") print(json.dumps(result, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From bff459fdcb6ad4edf7f75d679e9aec354afe66c7 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Wed, 25 Nov 2026 22:08:09 +0800 Subject: [PATCH 011/232] startup: add -TraceApi to the PowerShell launcher (#2354) * startup: expose provider method tracing through run.ps1 -TraceApi * tests: check the TraceApi opt-in on text-only hosts --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/startup-runtime.md | 6 ++++++ tests/startup_run_ps1_check.py | 29 ++++++++++++++++++++++------- tools/startup/run.ps1 | 4 +++- 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 47ff5f8ef..a7eda8140 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -634,6 +634,12 @@ that its fixture's module and export are in that list, that a source-built DLL l movie-player module name is not hooked by default, that each of its 7 export calls is counted with `--trace-calls 1`, and that `--trace-calls 1` with file tracing off counts nothing and says why. +`run.ps1 -TraceApi` sets `X2W_TRACE_API=1` for the child process and enables +`x2w-api` lines for individual runtime provider methods. Use `-TraceCalls` for +the debugger breakpoints described above. The switches work independently and +can be combined. A line containing `x2w-runtime provider` and `(proxied as #…)` +confirms that the runtime wrapped that provider even when method tracing is off. + A process that Windows creates under a debugger normally gets the debug heap: the loader sets the heap tail-check, free-check and parameter-validation flags and the low-fragmentation heap is not used, so every allocation and free costs more. The debugger starts the process with diff --git a/tests/startup_run_ps1_check.py b/tests/startup_run_ps1_check.py index aa388f1ff..8d9c55a68 100644 --- a/tests/startup_run_ps1_check.py +++ b/tests/startup_run_ps1_check.py @@ -4,8 +4,8 @@ On Windows the script runs under every PowerShell found (powershell is Windows PowerShell 5.1, pwsh is PowerShell 7) in a scratch tree whose debug_launch.py is a stub, so no process is ever started under a debugger. On other hosts, -without a PowerShell, or with --text-only, only the text after the debugger -call is checked. Mutated copies of the script must fail the same checks. +without a PowerShell, or with --text-only, the launcher statements are checked +as text. Mutated copies of the script must fail the same checks. """ import json import os @@ -24,12 +24,14 @@ # prints seven lines and exits with the code under test. STUB = """\ import json +import os import subprocess import sys import time from pathlib import Path -Path(__file__).with_name("argv.json").write_text(json.dumps(sys.argv[1:]), encoding="utf-8") +record = [sys.argv[1:], os.environ.get("X2W_TRACE_API")] +Path(__file__).with_name("debugger.json").write_text(json.dumps(record), encoding="utf-8") # Under -Translate, wait until the watcher stub has started so run.ps1 cannot stop it before then. watch = Path(__file__).with_name("watch.json") deadline = time.monotonic() + 30 @@ -120,7 +122,7 @@ def alive(pid): def run_case(shell, script, code, work, translate=False, switches=(), passed=(), fake_user_env=False, - early_exit=False): + early_exit=False, trace_api_env=None): """Run one copy of the script on a stub that exits with `code`; return what is wrong. `switches` are extra run.ps1 switches and `passed` the debugger arguments they must add. @@ -145,6 +147,10 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), # Compare PowerShell's warning text consistently on hosts that enable ANSI colors. env["NO_COLOR"] = "1" env.pop("X2W_FAKE_USER", None) + if trace_api_env is None: + env.pop("X2W_TRACE_API", None) + else: + env["X2W_TRACE_API"] = trace_api_env if fake_user_env: env["X2W_FAKE_USER"] = "1" # In this tree run.ps1 finds `python` through PATH. This interpreter's directory @@ -184,10 +190,11 @@ def run_case(shell, script, code, work, translate=False, switches=(), passed=(), found.append(f"stub exit {code}: {summary.name} does not hold the debugger's output") want = [str(exe), str(data), str(log), "--timeout", "9", "--memory-gib", "3", "--trace-files", "1", "--continue-asserts", "4", *passed] - record = startup / "argv.json" + record = startup / "debugger.json" got = json.loads(record.read_text(encoding="utf-8")) if record.is_file() else None - if got != want: - found.append(f"stub exit {code}: the debugger received {got}, expected {want}") + expected = [want, "1" if "-TraceApi" in switches else trace_api_env] + if got != expected: + found.append(f"stub exit {code}: debugger [argv, X2W_TRACE_API] was {got}, expected {expected}") watch = startup / "watch.json" if translate: started = json.loads(watch.read_text(encoding="utf-8")) if watch.is_file() else None @@ -217,6 +224,8 @@ def run_problems(shell, script, work, first_only): return found # -TraceCalls arms the debugger's call hooks; without it the arguments above stay as they are. found += run_case(shell, script, 0, work, switches=["-TraceCalls"], passed=["--trace-calls", "1"]) + found += run_case(shell, script, 0, work, switches=["-TraceApi"], trace_api_env="0") + found += run_case(shell, script, 0, work, trace_api_env="1") if found and first_only: return found found += run_case(shell, script, 7, work, translate=True) @@ -252,6 +261,12 @@ def text_problems(script): found.append("the log head is not printed between the capture and the exit") if not FAKE_USER_WARN.search(code): found.append("missing Write-Warning when -FakeUser is not passed") + before = "\n".join(statements[:calls[0]]) + if not re.search(r"^\[switch\]\s*\$TraceApi\b", before, re.I | re.M): + found.append("missing -TraceApi switch") + if not re.search(r"""^if\s*\(\s*\$TraceApi\s*\)\s*\{\s*\$env:X2W_TRACE_API\s*=\s*["']1["']\s*\}""", + before, re.I | re.M): + found.append("missing -TraceApi environment opt-in before launch") if not WATCH_CLEANUP.search("\n".join(after)): found.append("tree cleanup lacks taskkill /T, the live-watcher guard or the local Continue scope") return found diff --git a/tools/startup/run.ps1 b/tools/startup/run.ps1 index 1d9d5dccf..8132b595e 100644 --- a/tools/startup/run.ps1 +++ b/tools/startup/run.ps1 @@ -28,7 +28,8 @@ param( [switch]$HostCpu, # rewrite instructions the host processor lacks (X2W_HOST_CPU) [switch]$Translate, # with -Render: translate new shader requests during the run (gfx2hlsl.py --watch) [switch]$StartupBelow40, # place the 0x283 large-page startup blocks below 2^40 (X2W_XMEM_STARTUP_BELOW_40) - [switch]$TraceCalls # also break on runtime and movie-player calls (--trace-calls 1; slows the process) + [switch]$TraceCalls, # also break on runtime and movie-player calls (--trace-calls 1; slows the process) + [switch]$TraceApi # log runtime provider method calls (X2W_TRACE_API) ) $ErrorActionPreference = "Stop" $repo = Resolve-Path (Join-Path $PSScriptRoot "..\..") @@ -52,6 +53,7 @@ if (-not $FakeUser -and $env:X2W_FAKE_USER -ne "1") { } if ($GpuMirror) { $env:X2W_XMEM_GPU_MIRROR = "1" } if ($HostCpu) { $env:X2W_HOST_CPU = "1" } +if ($TraceApi) { $env:X2W_TRACE_API = "1" } if ($StartupBelow40) { $env:X2W_XMEM_STARTUP_BELOW_40 = "1" } if ($Render) { New-Item -ItemType Directory -Force $ShaderCache | Out-Null From 9f8468f454ec3513d369d4a83ea97e42ca81e4ea Mon Sep 17 00:00:00 2001 From: Vladimir <39053957+Vladimir-Human@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:09:00 +0300 Subject: [PATCH 012/232] shader: lower bounded 64-bit LDS exchange across group barrier in gfx2hlsl (#2345) Refs #2274, #1541. Extends check_lds_exchange and Stage in tools/startup/gfx2hlsl.py (building on #2327) to support bounded 64-bit group-shared LDS exchanges (ds_write_b64 and ds_read_b64) across s_barrier in 1D compute groups: - Requires ds_write_b64 vaddr, v[d0:d1] [offset:k] with v_lshlrev_b32 addr, 3, v0, contiguous 2-VGPR data pair in v0..v255, 4-byte aligned offset, and offset + group[0] * 8 <= lds_words * 4 (RDNA 2 ISA Ch. 9 DS, LLVM 15 AMDGPUUsage COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE). - Requires ds_read_b64 v[r0:r1], vaddr [offset:k] matching the 64-bit fill width (mixed b32/b64 exchanges stay refused), completed s_waitcnt lgkmcnt(0) before s_barrier and after each read, exact 2-VGPR pair, and literal or literal-masked byte addresses proving [a + offset, a + offset + 8) lies 4-byte aligned inside [first, first + group[0] * 8). - Computes a = (addr + offset) >> 2 before reading/writing dwords so vdst[0] == vaddr aliasing stays safe and preserves little-endian pair order. Adds tests/startup_compute_lds_b64_check.py wired in CMakeLists.txt, .github/workflows/windows.yml, and docs/experiments.md. --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 16 ++ docs/experiments.md | 19 ++ tests/startup_compute_lds_b64_check.py | 349 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 103 ++++++-- 5 files changed, 462 insertions(+), 27 deletions(-) create mode 100644 tests/startup_compute_lds_b64_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index e3d420d08..6befc8bc1 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -107,6 +107,7 @@ jobs: (["tests/startup_gfx2hlsl_sgpr_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_compute_lds_b64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), @@ -248,6 +249,7 @@ jobs: tests/startup_gfx2hlsl_sgpr_spill_check.py \ tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_compute_check.py \ + tests/startup_compute_lds_b64_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 7f897418c..c94f08113 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3205,6 +3205,22 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl bounded 64-bit LDS exchanges (ds_write_b64, ds_read_b64) across s_barrier (Refs #2274, #1541). + add_test(NAME startup_compute_lds_b64_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b64_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_lds_b64_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b64_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_lds_b64_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS p-same-lane p-swap-dwords p-drop-high b-wrong-mask b-wrong-lane) + add_test(NAME startup_compute_lds_b64_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b64_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_lds_b64_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl 64-bit VOP3 shifts: binary round-trip, overlap, guards and WARP/hardware draws (Refs #1723). add_test(NAME startup_gfx2hlsl_shift64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 17e9ede5f..27a8dc97a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13904,6 +13904,25 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(controls|(f-p python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 ``` +### Startup compute 64-bit LDS exchange + +[The startup translator](../tools/startup/gfx2hlsl.py) (`check_lds_exchange`, refs `#2274`, `#1541`) extends the bounded group-shared LDS exchange to 64-bit contiguous pairs (`ds_write_b64` and `ds_read_b64`, RDNA 2 DS `0x4d` and `0x76`): + +- `ds_write_b64 addr, v[d0:d1] [offset:k]` requires a single VGPR byte address from `v_lshlrev_b32 addr, 3, v0`, a contiguous `v[d0:d1]` pair in `v0..v255`, 4-byte aligned `offset`, and `offset + group[0] * 8 <= lds_words * 4`. +- `ds_read_b64 v[r0:r1], addr [offset:k]` requires matching 64-bit fill width (mixed `b32`/`b64` exchanges stay refused), a completed `s_waitcnt lgkmcnt(0)` before `s_barrier` and after each read, an exact `v[r0:r1]` pair, and literal or literal-masked (`v_and_b32`) byte addresses proving `[a + offset, a + offset + 8)` lies 4-byte aligned inside `[first, first + group[0] * 8)`. It computes `a = (addr + offset) >> 2` before assigning `r0 = lds[a]` and `r1 = lds[a + 1u]` (alias-safe when `addr` overlaps `v[r0:r1]`). + +[The 64-bit LDS check](../tests/startup_compute_lds_b64_check.py) verifies offline sizing/mask/pair/mixed-width/overflow/refusal controls and runs two `gfx1013` programs on D3D12 (`cs_6_0`, `debug_layer=enabled`): `P` (`[numthreads(64,1,1)]`, `groups=(2,1,1)`, `LDS_SIZE=2`, `offset:16`, cross-wave `X ^ 32` peer swap with `v[8:9], v8` aliasing) and `B` (`[numthreads(64,1,1)]`, `groups=(1,1,1)`, `LDS_SIZE=1`, peer `v[8:9]` plus lane-37 broadcast `v[10:11]` at `offset:296`). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`), both cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), and all five shader mutants rejected cleanly (`p-same-lane`: `word=0`, 256 mismatches; `p-swap-dwords`: `word=0`, 256 mismatches; `p-drop-high`: `word=1`, 128 mismatches; `b-wrong-mask`: `word=0`, 64 mismatches; `b-wrong-lane`: `word=2`, 128 mismatches). + +```powershell +. .\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -j 1 -R "^startup_compute_lds_b64" -V +python -B tests/startup_compute_lds_b64_check.py binary llvm-mc-15 +``` + +Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), sub-dword or mixed-width LDS exchanges, non-1D groups, divergent `EXEC`, and real title shaders. + ## Startup translator: refusal census The startup shader translator normally stops a pipeline at its first refusal. Fixing that refusal can expose gaps that were previously hidden, as documented in the [issue #1723 census](https://github.com/R0Y00/Xbox2Windows/issues/1723). diff --git a/tests/startup_compute_lds_b64_check.py b/tests/startup_compute_lds_b64_check.py new file mode 100644 index 000000000..9860bef37 --- /dev/null +++ b/tests/startup_compute_lds_b64_check.py @@ -0,0 +1,349 @@ +#!/usr/bin/env python3 +"""Verify bounded 64-bit LDS exchanges (ds_write_b64, ds_read_b64) across s_barrier in tools/startup/gfx2hlsl.py. + +With no arguments, checks offline RSRC2 sizing, pair alignment/bounds, & 0x1c vs & 0x1e masks, +4 overflow, +mixed b32/b64 refusal, register-range refusals, barrier/waitcnt/branch/EXEC/1D-group/non-compute refusals. +With 'binary ', validates assembled gfx1013 machine-code bytes. With 'dispatch' or 'control ', +compiles with DXC (cs_6_0) and runs WARP / hardware GPU readback verification via offscreen_check. +""" + +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G +from startup_gfx2hlsl_compute_check import TGID_X, USER7, patch, refused, root_blob + + +def le32(w): + return w.to_bytes(4, 'little') + + +def sop2(op, sdst, ssrc0, ssrc1): + return le32(0x80000000 | ((op & 0x7f) << 23) | ((sdst & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff)) + + +def sopp(op, simm=0): + return le32(0xbf800000 | ((op & 0x7f) << 16) | (simm & 0xffff)) + + +def vop1(op, vdst, src0, lit=None): + b = le32(0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def vop2(op, vdst, src0, vsrc1, lit=None): + b = le32(((op & 0x3f) << 25) | ((vdst & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def ds_enc(op, addr, data0=0, vdst=0, offset=0, gds=0): + w0 = 0xd8000000 | ((op & 0xff) << 18) | ((gds & 1) << 17) | (offset & 0xffff) + w1 = ((vdst & 0xff) << 24) | ((data0 & 0xff) << 8) | (addr & 0xff) + return le32(w0) + le32(w1) + + +PREAMBLE = ( + 's_mov_b32 s10, s6\n' + 's_mov_b32 s11, 0\n' + 's_load_dwordx8 s[12:19], s[10:11], 0x0\n' + 's_waitcnt lgkmcnt(0)\n' +) + +# Case P: [numthreads(64, 1, 1)], groups=(2, 1, 1), LDS_SIZE=2 (1024 bytes = 256 uints). +# 64-bit peer exchange (X ^ 32) across the two wave32 halves at byte offset 16..528, +# including vdst[0] == vaddr aliasing (ds_read_b64 v[8:9], v8 offset:16). +SOURCE_P = PREAMBLE + """\ +s_lshl_b32 s20, s7, 8 +v_add_nc_u32 v5, s20, v0 +v_xor_b32 v6, 0xa5a50000, v5 +v_lshlrev_b32 v4, 3, v0 +ds_write_b64 v4, v[5:6] offset:16 +s_waitcnt lgkmcnt(0) +s_barrier +v_xor_b32 v8, 0x100, v4 +v_and_b32 v8, 0x1f8, v8 +ds_read_b64 v[8:9], v8 offset:16 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s21, s7, 6 +v_add_nc_u32 v13, s21, v0 +v_lshlrev_b32 v13, 3, v13 +buffer_store_dwordx2 v[8:9], v13, s[16:19], 0 offen +s_endpgm +""" + +WORDS_P = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf' + '0788148f14000a4aff0a0c3a0000a5a583000834' + '100034d9040500007fc08cbf00008abfff08103a00010000' + 'ff101036f80100001000d8d9080000087fc08cbf' + '0786158f15001a4a831a1a34001074e00d080480000081bf' +) + +# Case B: [numthreads(64, 1, 1)], groups=(1, 1, 1), LDS_SIZE=1 (512 bytes exact fit: 64 * 8 = 512). +# Outputs full 4-dword result (peer qword v[8:9] + lane-37 broadcast qword v[10:11] at offset 296). +SOURCE_B = PREAMBLE + """\ +s_lshl_b32 s20, s7, 8 +v_add_nc_u32 v5, s20, v0 +v_xor_b32 v6, 0x5a5a0000, v5 +v_lshlrev_b32 v4, 3, v0 +ds_write_b64 v4, v[5:6] +s_waitcnt lgkmcnt(0) +s_barrier +v_xor_b32 v8, 0x100, v4 +v_and_b32 v8, 0x1f8, v8 +ds_read_b64 v[8:9], v8 +s_waitcnt lgkmcnt(0) +v_mov_b32 v12, 0 +ds_read_b64 v[10:11], v12 offset:296 +s_waitcnt lgkmcnt(0) +v_lshlrev_b32 v13, 4, v0 +buffer_store_dwordx4 v[8:11], v13, s[16:19], 0 offen +s_endpgm +""" + +WORDS_B = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf' + '0788148f14000a4aff0a0c3a00005a5a83000834' + '000034d9040500007fc08cbf00008abfff08103a00010000' + 'ff101036f80100000000d8d9080000087fc08cbf' + '8002187e2801d8d90c00000a7fc08cbf84001a34' + '001078e00d080480000081bf' +) + +CASES = { + 'P': (SOURCE_P, WORDS_P, USER7 | TGID_X | (2 << 15), (64, 1, 1), (2, 1, 1)), + 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | (1 << 15), (64, 1, 1), (1, 1, 1)), +} + +VERIFIED_SNIPPETS = { + 'ds_write_b64 v4, v[5:6]': '000034d904050000', + 'ds_write_b64 v4, v[5:6] offset:16': '100034d904050000', + 'ds_read_b64 v[8:9], v8': '0000d8d908000008', + 'ds_read_b64 v[24:25], v2 offset:16': '1000d8d902000018', + 'ds_read_b64 v[10:11], v12 offset:296': '2801d8d90c00000a', +} + +WORDS = 320 +SENTINEL = 0xc5c5c5c5 + + +def expected_words(name): + out = [SENTINEL] * WORDS + if name == 'P': + for g in range(2): + for l in range(64): + peer = (g << 8) + (l ^ 32) + idx = (g * 64 + l) * 2 + out[idx] = peer + out[idx + 1] = peer ^ 0xa5a50000 + elif name == 'B': + b0 = 37 + b1 = b0 ^ 0x5a5a0000 + for l in range(64): + peer = l ^ 32 + idx = l * 4 + out[idx] = peer + out[idx + 1] = peer ^ 0x5a5a0000 + out[idx + 2] = b0 + out[idx + 3] = b1 + else: + raise KeyError(name) + return out + + +def translate_case(name, code=None, rsrc2=None, group=None): + _, words, default_rsrc2, local, _groups = CASES[name] + return G.ComputePipeline(words if code is None else code, root_blob(), + default_rsrc2 if rsrc2 is None else rsrc2, local if group is None else group) + + +def check_controls(): + # Positive HLSL lowering: declarations, single-eval alias-safe index, barrier, and both dwords. + hlsl_p = translate_case('P').hlsl_cs() + assert 'groupshared uint lds[256];' in hlsl_p, hlsl_p + assert hlsl_p.count('GroupMemoryBarrierWithGroupSync();') == 1, hlsl_p + assert 'a = (v4 + 16u) >> 2;\n lds[a] = v5;\n lds[a + 1u] = v6;' in hlsl_p, hlsl_p + assert 'a = (v8 + 16u) >> 2;\n v8 = lds[a];\n v9 = lds[a + 1u];' in hlsl_p, hlsl_p + + hlsl_b = translate_case('B').hlsl_cs() + assert 'groupshared uint lds[128];' in hlsl_b, hlsl_b + assert 'a = (v4 + 0u) >> 2;\n lds[a] = v5;\n lds[a + 1u] = v6;' in hlsl_b, hlsl_b + assert 'a = (v12 + 296u) >> 2;\n v10 = lds[a];\n v11 = lds[a + 1u];' in hlsl_b, hlsl_b + + # Tight capacity boundary: offset:16 + 64*8 = 528 exceeds 1 unit (512 bytes), fits at offset:0 and at 32 KiB. + base = USER7 | TGID_X + refused('one bounded qword', lambda: translate_case('P', rsrc2=base | (1 << 15))) + refused('allocation', lambda: translate_case('P', rsrc2=base | (0 << 15))) + refused('allocation', lambda: translate_case('P', rsrc2=base | (65 << 15))) + assert 'groupshared uint lds[8192];' in translate_case('P', rsrc2=base | (64 << 15)).hlsl_cs() + + # Exact aligned mask (& 0x1c ok inside span) vs unaligned (& 0x1e refused) and +4 overflow (& 0x1fc refused). + mask_1f8 = 'ff101036f8010000' + mask_1c = 'ff1010361c000000' + mask_1e = 'ff1010361e000000' + mask_1fc = 'ff101036fc010000' + ok_1c = translate_case('P', code=patch(WORDS_P, mask_1f8, mask_1c)).hlsl_cs() + assert 'v8 = 0x0000001cu & v8;' in ok_1c, ok_1c + refused('aligned', lambda: translate_case('P', code=patch(WORDS_P, mask_1f8, mask_1e))) + refused('initialized span', lambda: translate_case('P', code=patch(WORDS_P, mask_1f8, mask_1fc))) + + # Broadcast +4 boundary: last initialized dword starts at 524, so reading b64 at offset 524 overflows (+4 -> 528). + bcast = '2801d8d90c00000a' + ok_504 = translate_case('B', code=patch(WORDS_B, bcast, 'f801d8d90c00000a')).hlsl_cs() + assert 'a = (v12 + 504u) >> 2;' in ok_504, ok_504 + refused('initialized span', lambda: translate_case('B', code=patch(WORDS_B, bcast, 'fc01d8d90c00000a'))) # 508+4=512 >= 512 + + # Pitched fill, unaligned offsets, wrong shift, missing barrier/waitcnt, EXEC/branch/non-1D/non-compute refusals. + store = '100034d904050000' + read_p = '1000d8d908000008' + wait = '7fc08cbf' + barrier = '00008abf' + nop = '000080bf' + refused('one bounded qword', lambda: translate_case('P', code=patch(WORDS_P, store, '120034d904050000'))) # odd write offset:18 + refused('aligned', lambda: translate_case('P', code=patch(WORDS_P, read_p, '1200d8d908000008'))) # odd read offset:18 + refused('initialized span', lambda: translate_case('P', code=patch(WORDS_P, read_p, '0c00d8d908000008'))) # before span (offset:12) + refused('one bounded qword', lambda: translate_case('P', code=patch(WORDS_P, '83000834', '82000834'))) # shift 2 instead of 3 + refused('completed fill', lambda: translate_case('P', code=patch(WORDS_P, wait + barrier, nop + barrier))) + refused('after the fill barrier', lambda: translate_case('P', code=patch(WORDS_P, barrier, nop))) + refused('completed LGKM wait', lambda: translate_case('P', code=patch(WORDS_P, read_p + wait, read_p + nop))) + refused('optional byte offset', lambda: translate_case('P', code=patch(WORDS_P, store, '100036d904050000'))) # GDS + refused('entry EXEC', lambda: translate_case('P', code=patch(WORDS_P, store, '8003febe' + store))) + refused('straight-line', lambda: translate_case('P', code=patch(WORDS_P, store, '020084bf' + store))) + refused('1D group', lambda: translate_case('P', group=(32, 2, 1))) + + # Mixed width refusals: b32 fill + b64 read, b64 fill + b32 read, and b64 fill + ds_read2_b32. + refused('does not match initialized fill', + lambda: translate_case('P', code=patch(WORDS_P, read_p, '1000d8d808000008'))) # ds_read_b32 after ds_write_b64 + refused('does not match initialized fill', + lambda: translate_case('P', code=patch(WORDS_P, read_p, '0408dcd808000008'))) # ds_read2_b32 after ds_write_b64 + refused('does not match initialized fill', + lambda: translate_case('P', code=patch(WORDS_P, '83000834' + store, '82000834' + '100034d804050000'))) # ds_write_b32 + ds_read_b64 + + # Register-range validation: reject 1-VGPR, 3-VGPR, >v255, and SGPR operands on ds_write_b64 / ds_read_b64. + assert G._lds_pair('v[5:6]') == 5 + for bad_pair in ('v5', 'v[5:5]', 'v[5:7]', 'v[5:8]', 'v[5:4]', 'v[255:256]', 's[4:5]'): + assert G._lds_pair(bad_pair) is None, bad_pair + decoded_w = [(0, 4, 'v_lshlrev_b32', 'v_lshlrev_b32 v4, 3, v0'), + (4, 8, 'ds_write_b64', f'ds_write_b64 v4, {bad_pair}'), + (12, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (16, 4, 's_barrier', 's_barrier 0x0'), + (20, 4, 'v_mov_b32', 'v_mov_b32 v8, 0'), + (24, 8, 'ds_read_b64', 'ds_read_b64 v[8:9], v8'), + (32, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (36, 4, 's_endpgm', 's_endpgm')] + refused('2-VGPR pair', lambda d=decoded_w: G.check_lds_exchange(d, (4, 1, 1), 128)) + decoded_r = [(0, 4, 'v_lshlrev_b32', 'v_lshlrev_b32 v4, 3, v0'), + (4, 8, 'ds_write_b64', 'ds_write_b64 v4, v[5:6]'), + (12, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (16, 4, 's_barrier', 's_barrier 0x0'), + (20, 4, 'v_mov_b32', 'v_mov_b32 v8, 0'), + (24, 8, 'ds_read_b64', f'ds_read_b64 {bad_pair}, v8'), + (32, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (36, 4, 's_endpgm', 's_endpgm')] + refused('2-VGPR pair', lambda d=decoded_r: G.check_lds_exchange(d, (4, 1, 1), 128)) + + # Non-compute stage refusal for b64 DS ops. + for stage_kind in ('vs', 'ps'): + s = G.Stage.__new__(G.Stage) + s.kind = stage_kind + refused('ds_write_b64', lambda st=s: st.lower('ds_write_b64', 'ds_write_b64 v4, v[5:6]', ['v4', 'v[5:6]'], [])) + refused('ds_read_b64', lambda st=s: st.lower('ds_read_b64', 'ds_read_b64 v[8:9], v8', ['v[8:9]', 'v8'], [])) + + # Missing pipe metadata refusal on bare Stage probe. + bare = G.Stage.__new__(G.Stage) + bare.kind = 'cs' + bare.pipe = None + refused('metadata', lambda: bare.lower('ds_write_b64', 'ds_write_b64 v4, v[5:6]', ['v4', 'v[5:6]'], [])) + + print('bounded 64-bit LDS exchange sizing, pair validation, aligned masks, bounds and refusals pass') + + +def assemble(llvm_mc, source): + from startup_flat_param_check import assemble as run + return run(llvm_mc, source) + + +def check_binary(llvm_mc): + for name, (source, words, *_rest) in CASES.items(): + built = assemble(llvm_mc, source) + assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, hex_words in VERIFIED_SNIPPETS.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == hex_words, '%s: assembled %s, recorded %s' % (line, built, hex_words) + print('64-bit LDS fixture words match llvm-mc (%d programs, %d snippets)' % (len(CASES), len(VERIFIED_SNIPPETS))) + + +CONTROLS = { + 'p-same-lane': ('P', ' v8 = 0x00000100u ^ v4;\n', ' v8 = v4;\n'), + 'p-swap-dwords': ('P', ' a = (v8 + 16u) >> 2;\n v8 = lds[a];\n v9 = lds[a + 1u];\n', + ' a = (v8 + 16u) >> 2;\n v8 = lds[a + 1u];\n v9 = lds[a];\n'), + 'p-drop-high': ('P', ' lds[a + 1u] = v6;\n', ''), + 'b-wrong-mask': ('B', ' v8 = 0x000001f8u & v8;\n', ' v8 = 0x000000f8u & v8;\n'), + 'b-wrong-lane': ('B', ' a = (v12 + 296u) >> 2;\n', ' a = (v12 + 288u) >> 2;\n'), +} + + +def mutate(hlsl, control): + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate_case(name).hlsl_cs() + if control: + hlsl = mutate(hlsl, control) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = CASES[name][4] + constants = [0] * 16 + case.write_bytes( + struct.pack(' 255 - or not re.fullmatch(r'v\d+', ops[1])): + if len(ops) != 2 or _lds_pair(val_op) is None or _lds_single(addr_op) is None: raise Unsupported('LDS read2 needs a VGPR pair and a byte address VGPR') - elif len(ops) != 2 or not all(re.fullmatch(r'v[0-9]+', op) for op in ops): - raise Unsupported('LDS exchange needs two VGPRs and an optional byte offset') + elif (len(ops) != 2 or _lds_single(addr_op) is None + or (_lds_pair(val_op) is None if width == 8 else _lds_single(val_op) is None)): + raise Unsupported('LDS exchange needs %s, %s and an optional byte offset' + % ('two VGPRs' if width == 4 else 'a VGPR address', + 'an aligned 2-VGPR pair' if width == 8 else 'a matching data VGPR')) offsets = lds_byte_offsets(base, mods) producer, args, modifiers = prev - if base == 'ds_write_b32': + if write: offset, = offsets - # The prefix below preserves the entry X ID in v0. Each lane writes exactly one distinct dword. - if (first is not None or producer != 'v_lshlrev_b32' or args != [ops[0], '2', 'v0'] - or modifiers or offset % 4 or offset + group[0] * 4 > words * 4): - raise Unsupported('LDS exchange needs one bounded dword per local X ID') + shift = '3' if width == 8 else '2' + # The prefix below preserves the entry X ID in v0. Each lane writes exactly one distinct element. + # 8-byte alignment is not required for LDS dword-addressed writes. + if (first is not None or producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] + or modifiers or offset % 4 or offset + group[0] * width > words * 4): + raise Unsupported('LDS exchange needs one bounded %s per local X ID' + % ('qword' if width == 8 else 'dword')) first = offset + elem_bytes = width else: - if not published or modifiers or not args or args[0] != ops[1]: + if not published or modifiers or not args or args[0] != addr_op: raise Unsupported('LDS read needs a bounded address after the fill barrier') + if elem_bytes != width: + raise Unsupported('LDS read width (%dB) does not match initialized fill (%dB)' + % (width, elem_bytes or 0)) if producer == 'v_mov_b32' and len(args) == 2 and re.fullmatch(r'0x[0-9a-f]+|\d+', args[1]): low = high = int(args[1], 0) elif (producer == 'v_and_b32' and len(args) == 3 and re.fullmatch(r'0x[0-9a-f]+|\d+', args[1]) - and re.fullmatch(r'v[0-9]+', args[2])): + and _lds_single(args[2]) is not None): low, high = 0, int(args[1], 0) else: raise Unsupported('LDS read needs a literal or literal-masked byte address') - if high % 4 or any(offset % 4 or low + offset < first or high + offset >= first + group[0] * 4 - for offset in offsets): + # Every byte offset in [a + offset, a + offset + width) must be 4-byte aligned and inside the filled span. + if (low % 4 or high % 4 + or any(offset % 4 or low + offset < first or high + offset + (width - 4) >= first + group[0] * width + for offset in offsets)): raise Unsupported('LDS read outside the aligned, initialized span') if i + 1 >= len(ins) or ins[i + 1][3] != 's_waitcnt lgkmcnt(0)': raise Unsupported('LDS read needs a completed LGKM wait') @@ -2013,13 +2048,15 @@ def lower(self, base, asm, ops, mods): return ('branch', cond, int(ops[0].split('_')[1], 16)) if base == 'exp': return self.export(asm) - if base in ('ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 's_barrier'): + if base in ('ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 'ds_write_b64', 'ds_read_b64', 's_barrier'): if getattr(self, 'kind', None) != 'cs': raise Unsupported(base) # The refusal census continues past failed instructions. Scan this program only once. if not hasattr(self, 'lds_error'): self.lds_error = None try: + if getattr(self, 'pipe', None) is None: + raise Unsupported('LDS exchange needs pipeline metadata') check_lds_exchange(self.ins, self.pipe.group, self.pipe.lds_words) self.uses_lds = True except Unsupported as reason: @@ -2029,19 +2066,31 @@ def lower(self, base, asm, ops, mods): if base == 's_barrier': self.emit('GroupMemoryBarrierWithGroupSync();') else: - write = base == 'ds_write_b32' + write = base.startswith('ds_write') address = self.u(ops[0 if write else 1]) offsets = lds_byte_offsets(base, mods) - if write: - self.emit('lds[(%s + %du) >> 2] = %s;' % (address, offsets[0], self.u(ops[1]))) + if base in ('ds_write_b32', 'ds_read_b32', 'ds_read2_b32'): + if write: + self.emit('lds[(%s + %du) >> 2] = %s;' % (address, offsets[0], self.u(ops[1]))) + else: + if base == 'ds_read2_b32': + # Either destination can overlap the incoming address VGPR. + self.emit('a = %s;' % address) + address = 'a' + start = reg_range(ops[0])[1] + for index, offset in enumerate(offsets): + self.set_v(start + index, 'lds[(%s + %du) >> 2]' % (address, offset)) else: - if base == 'ds_read2_b32': - # Either destination can overlap the incoming address VGPR. - self.emit('a = %s;' % address) - address = 'a' - start = reg_range(ops[0])[1] - for index, offset in enumerate(offsets): - self.set_v(start + index, 'lds[(%s + %du) >> 2]' % (address, offset)) + lo = _lds_pair(ops[1 if write else 0]) + if write: + d0, d1 = self.u('v%d' % lo), self.u('v%d' % (lo + 1)) + self.emit('a = (%s + %du) >> 2;' % (address, offsets[0])) + self.emit('lds[a] = %s;' % d0) + self.emit('lds[a + 1u] = %s;' % d1) + else: + self.emit('a = (%s + %du) >> 2;' % (address, offsets[0])) + self.set_v(lo, 'lds[a]') + self.set_v(lo + 1, 'lds[a + 1u]') return None if base.endswith('_dpp'): return self.dpp(base[:-len('_dpp')], ops, mods) From 5a32658ac7cb07a7b24f1f8c18c21663b6d59d2d Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 15:09:59 +0100 Subject: [PATCH 013/232] startup: look up memory SRV resources through an address index (#2343) The by-address lookups in d3d12_memory_srv.inl walked every noted resource under the shared note_lock on each slot 70 call. resource_address_index.h keeps resources by the title memory they start at and only narrows the candidates; each lookup still applies its own live-reference filter and predicate, so released and re-referenced wrappers give the scan's answer. - Entries stay as long as the canonical record does (the table is never pruned). Nothing is erased at release and no reference path changes. - note_resource stores the record and the index entry as one step (store_indexed): the index node is allocated first, the record update follows, and a failure leaves both as they were. Slot 133 does the same through publish_placement's hook. - X2W_RESOURCE_INDEX_CHECK=1 checks every memory SRV call that each live resource is indexed; =2 skips the inserts as the negative control. - Test startup_resource_address_index compares the index with the full scan across release, re-reference, address reuse, overlapping ranges, re-notes, unaligned bases, the span-end edges, and injected allocation failures. The skip and unsync controls must fail. Co-authored-by: Claude Fable 5.2 --- CMakeLists.txt | 20 ++ src/startup_stubs/d3d12_capture.inl | 32 ++- src/startup_stubs/d3d12_memory_srv.inl | 72 +++-- src/startup_stubs/d3d12_xs_device.cpp | 3 +- src/startup_stubs/placement_publish.h | 17 +- src/startup_stubs/resource_address_index.h | 121 ++++++++ .../startup_resource_address_index_check.cpp | 264 ++++++++++++++++++ 7 files changed, 497 insertions(+), 32 deletions(-) create mode 100644 src/startup_stubs/resource_address_index.h create mode 100644 tests/startup_resource_address_index_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c94f08113..eeebb1a64 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -644,6 +644,17 @@ target_include_directories(startup_placement_publish_check PRIVATE src) add_test(NAME startup_placement_publish COMMAND startup_placement_publish_check) add_test(NAME startup_placement_publish_shrink_control COMMAND startup_placement_publish_check --mutate shrink) set_tests_properties(startup_placement_publish_shrink_control PROPERTIES WILL_FAIL TRUE) +# The memory SRV address lookups through src/startup_stubs/resource_address_index.h answer what a scan of +# every resource answers, across release, re-reference, address reuse and allocation failures at the index +# insert. The skip run (one insert dropped) and the unsync run (index insert first, kept when the record +# update fails) are the negative controls. +add_executable(startup_resource_address_index_check tests/startup_resource_address_index_check.cpp) +target_compile_features(startup_resource_address_index_check PRIVATE cxx_std_17) +target_include_directories(startup_resource_address_index_check PRIVATE src) +add_test(NAME startup_resource_address_index COMMAND startup_resource_address_index_check) +add_test(NAME startup_resource_address_index_skip_control COMMAND startup_resource_address_index_check --mutate skip) +add_test(NAME startup_resource_address_index_unsync_control COMMAND startup_resource_address_index_check --mutate unsync) +set_tests_properties(startup_resource_address_index_skip_control startup_resource_address_index_unsync_control PROPERTIES WILL_FAIL TRUE) # Device slot 133 proves that the allocation is committed from its base to the end of the buffer with # one region-information call when the whole private allocation is committed, else with a walk that # stops at the end of the buffer; every alias or refusal must equal the full walk's on the same memory, @@ -3402,6 +3413,15 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + if(backend STREQUAL "warp") + # Negative control for X2W_RESOURCE_INDEX_CHECK: mode 2 skips the index inserts, so the check must + # report the first live resource it does not find (the run passes only on that report). + add_test(NAME startup_resource_address_index_missing_control_warp COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "X2W_RESOURCE_INDEX_CHECK=2" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_srv_check.py" + "$" warp) + set_tests_properties(startup_resource_address_index_missing_control_warp PROPERTIES TIMEOUT 90 + PASS_REGULAR_EXPRESSION "resource address index misses a live resource") + endif() # Refused slot 70 calls and "token" texture nulls in the five-second report census. The WARP control # publishes a supported R8 texture in place of the refused one and passes only on the exact mismatch # that causes (column 0 samples the R8 texel instead of a null view). diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 24c5366dd..e0375ff09 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -169,11 +169,41 @@ PlacementIndex& placement_group(u64 width) return placement_index[width > D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT]; } +// Resources by the title memory they start at (note_lock held), for the memory SRV lookups. An entry stays +// as long as the resource's record in resource_infos does (never pruned); every lookup applies its own +// live-reference filter, so a released resource is skipped there and found again if it is referenced again. +x2w_startup::AddressIndex& resource_address_index() { static x2w_startup::AddressIndex m; return m; } +// X2W_RESOURCE_INDEX_CHECK=1 checks the index on every memory SRV call (check_resource_address_index); +// =2 is the negative control: the same check with index inserts skipped, which it must report. +int resource_index_check_mode() +{ + // Only "1" and "2" turn it on; anything else, including a value too long for the buffer, is off. + static const int mode = [] { + char v[4]{}; + const DWORD n = GetEnvironmentVariableA("X2W_RESOURCE_INDEX_CHECK", v, sizeof(v)); + return n == 1 && (v[0] == '1' || v[0] == '2') ? v[0] - '0' : 0; + }(); + return mode; +} +u64 resource_index_extent(const ResourceInfo& info) +{ + return (std::max)(info.bytes, info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? info.console.Width : 0); +} +// The index entry of a resource whose record is already published (publish_placement's hook); may throw. +void index_resource(const Wrapper* w, const ResourceInfo& info) +{ + const u64 base = reinterpret_cast(w->own().title_memory); + if (!base || resource_index_check_mode() == 2) return; + resource_address_index().insert(base, resource_index_extent(info), w); +} void note_resource(Wrapper* w, const D3D12_RESOURCE_DESC* console, u64 bytes) { if (!w || !console) return; x2w_startup::ExclusiveNoteLock guard(note_lock); - resource_infos()[w] = ResourceInfo{*console, bytes}; + const ResourceInfo info{*console, bytes}; + // Record and index change together or not at all (store_indexed); mode 2 leaves the index out. + x2w_startup::store_indexed(resource_address_index(), resource_infos(), static_cast(w), + resource_index_check_mode() == 2 ? 0 : reinterpret_cast(w->own().title_memory), resource_index_extent(info), info); } void retire_placement(Wrapper* w) { diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 07e372f48..1b6d33a59 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -135,21 +135,45 @@ bool memory_srv_destination(u64 handle) return valid; } +// With X2W_RESOURCE_INDEX_CHECK=1 (or 2, see resource_index_check_mode), every memory SRV call (a full pass, for tests) checks that each live resource with title +// memory is in the address index (entries are never removed, so it stays there after a release). A miss is logged and ends the process with code 3; this is a test mode only. +void check_resource_address_index() +{ + if (resource_index_check_mode() == 0) return; + AcquireSRWLockShared(¬e_lock); + std::optional missing; + for (const auto& [wrapper, info] : resource_infos()) { + const u64 base = reinterpret_cast(wrapper->own().title_memory); + if (!base || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0 || resource_address_index().contains(base, wrapper)) + continue; + missing = base; + break; + } + const std::size_t entries = resource_address_index().size(); + ReleaseSRWLockShared(¬e_lock); + if (!missing) return; + log("x2w-d3d12 resource address index misses a live resource at 0x%llx (index %zu entries)", *missing, entries); + ExitProcess(3); +} + Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) { Wrapper* match = nullptr; AcquireSRWLockShared(¬e_lock); - for (const auto& [wrapper, info] : resource_infos()) { + // A null address never gets here (memory_srv_refusal), and the index holds no null base. + resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { + const auto& info = resource_infos().at(wrapper); if (reinterpret_cast(wrapper->own().title_memory) != address || wrapper->own().tiled_address_srv || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0 || - !same_texture_description(desc, info.console)) continue; + !same_texture_description(desc, info.console)) return false; if (match) { match = nullptr; - break; + return true; } match = const_cast(wrapper); - } + return false; + }); ReleaseSRWLockShared(¬e_lock); return match; } @@ -159,17 +183,14 @@ bool address_resource_overlap(u64 address, u64 span) { bool found = false; AcquireSRWLockShared(¬e_lock); - for (const auto& [wrapper, info] : resource_infos()) { + resource_address_index().for_each_reaching(address, span, [&](const Wrapper* wrapper) { if (wrapper->own().tiled_address_srv || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0) - continue; - const u64 base = reinterpret_cast(wrapper->own().title_memory); + return false; + const auto& info = resource_infos().at(wrapper); const u64 bytes = info.bytes ? info.bytes : info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? info.console.Width : 0; - if (base && (address <= base ? base - address < span : address - base < bytes)) { - found = true; - break; - } - } + return found = x2w_startup::address_span_touches(address, span, reinterpret_cast(wrapper->own().title_memory), bytes); + }); ReleaseSRWLockShared(¬e_lock); return found; } @@ -182,16 +203,12 @@ bool gpu_written_overlap(u64 address, UINT texel_bytes) D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; bool found = false; AcquireSRWLockShared(¬e_lock); - for (const auto& [wrapper, info] : resource_infos()) { - const u64 base = reinterpret_cast(wrapper->own().title_memory); + resource_address_index().for_each_reaching(address, texel_bytes, [&](const Wrapper* wrapper) { + const auto& info = resource_infos().at(wrapper); const u64 bytes = info.bytes ? info.bytes : info.console.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? info.console.Width : 0; - const bool overlap = address <= base ? base - address < texel_bytes : address - base < bytes; - if (base && overlap && - (static_cast(info.console.Flags) & gpu_written) && InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0) { - found = true; - break; - } - } + return found = x2w_startup::address_span_touches(address, texel_bytes, reinterpret_cast(wrapper->own().title_memory), bytes) && + (static_cast(info.console.Flags) & gpu_written) && InterlockedCompareExchange(&wrapper->own().refs, 0, 0) > 0; + }); ReleaseSRWLockShared(¬e_lock); return found; } @@ -211,22 +228,24 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) } Wrapper* match = nullptr; AcquireSRWLockShared(¬e_lock); - for (const auto& [wrapper, info] : resource_infos()) { + resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { + const auto& info = resource_infos().at(wrapper); if (info.placement != Placement::none || info.console.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (info.console.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || InterlockedCompareExchange(&wrapper->own().refs, 0, 0) <= 0) - continue; + return false; const u64 base = reinterpret_cast(wrapper->own().title_memory); const u64 width = info.console.Width; if (!base || address < base || address - base >= width || bytes > width - (address - base)) - continue; + return false; if (match) { match = nullptr; - break; + return true; } match = const_cast(wrapper); - } + return false; + }); ReleaseSRWLockShared(¬e_lock); return match; } @@ -413,6 +432,7 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou const MemoryShaderResourceView* input, u64 destination) { static LONG refused; + check_resource_address_index(); if (const char* reason = memory_srv_refusal(resource, input, destination)) { refuse_memory_srv(refused, "unsupported memory SRV arguments", reason, resource, input, destination); return; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index a600ba42f..872f3bb3c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -35,6 +35,7 @@ #include #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" +#include "startup_stubs/resource_address_index.h" #include "startup_stubs/placed_build.h" #include "startup_stubs/placed_buffer_range.h" #include "startup_stubs/memory_srv_report.h" @@ -3968,7 +3969,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; auto& group = placement_group(desc->Width); hr = x2w_startup::publish_placement(note_lock, resource_infos, group.by_start, group.max_width, - static_cast(w), reinterpret_cast(address), record); + static_cast(w), reinterpret_cast(address), record, [&] { index_resource(w, record); }); if (FAILED(hr)) { // The caller has never received this wrapper; release its desktop resource and storage. AcquireSRWLockExclusive(®istry_lock); diff --git a/src/startup_stubs/placement_publish.h b/src/startup_stubs/placement_publish.h index 71d8a9dd6..aa2d12ddb 100644 --- a/src/startup_stubs/placement_publish.h +++ b/src/startup_stubs/placement_publish.h @@ -21,10 +21,13 @@ class ExclusiveNoteLock { // Insert under the same lock used by binding lookup. The index is published // only after the canonical resource record exists. Erase the new record if its -// index node cannot be allocated. Existing registrations are never replaced. -template +// index node cannot be allocated. Existing registrations are never replaced. `also` runs under the +// same lock hold once the record and the index node exist (a throw undoes both), so a second index +// never lags the first. +struct NoExtraIndex { void operator()() const {} }; +template HRESULT publish_placement(SRWLOCK& lock, Records get_records, std::multimap& by_start, - std::uint64_t& max_width, Key owner, std::uint64_t start, const Record& record) + std::uint64_t& max_width, Key owner, std::uint64_t start, const Record& record, Also also = {}) { if (!start || !record.bytes || record.bytes > (std::numeric_limits::max)() - start) return E_INVALIDARG; @@ -34,7 +37,13 @@ HRESULT publish_placement(SRWLOCK& lock, Records get_records, std::multimap +#include +#include +#include +#include + +namespace x2w_startup { +// Whether [address, address + span) meets a resource of `bytes` bytes at `base` (a null base never does). +// A resource of unknown size (bytes == 0) is touched only at its base. +inline bool address_span_touches(std::uint64_t address, std::uint64_t span, std::uint64_t base, std::uint64_t bytes) +{ + return base && (address <= base ? base - address < span : address - base < bytes); +} + +// The caller serializes access (note_lock: shared for lookups, exclusive for insert and erase). +template +class AddressIndex { +public: + // Makes (base, key) an entry of `bytes`: adds it, or replaces the entry the key already has at that + // base. The new node is allocated before the old one goes, so a throw changes nothing. + void insert(std::uint64_t base, std::uint64_t bytes, Key key) + { + const std::uint64_t extent = (std::max)(bytes, std::uint64_t{1}); + Group* old_group = nullptr; + typename std::multimap::iterator old_node; + for (Group& group : groups_) { + const auto [first, last] = group.by_base.equal_range(base); + for (auto it = first; it != last; ++it) + if (it->second.key == key) { + if (it->second.extent == extent) return; + old_group = &group; + old_node = it; + } + } + Group& group = groups_[extent > large]; + group.by_base.emplace(base, Entry{key, extent}); + group.max_extent = (std::max)(group.max_extent, extent); + if (old_group) old_group->by_base.erase(old_node); + } + // Removes the entry (base, key) if there is one; never throws. + void erase(std::uint64_t base, Key key) + { + for (Group& group : groups_) { + const auto [first, last] = group.by_base.equal_range(base); + for (auto it = first; it != last; ++it) + if (it->second.key == key) { + group.by_base.erase(it); + break; + } + } + } + // Calls f(key) for every resource whose [base, base + max(bytes, 1)) meets [from, from + span), in no + // particular order; stops when f returns true. That includes every resource address_span_touches + // accepts for (from, span), and every resource containing `from` when span is at least 1. + template + void for_each_reaching(std::uint64_t from, std::uint64_t span, F&& f) const + { + const std::uint64_t to = span > (std::numeric_limits::max)() - from + ? (std::numeric_limits::max)() : from + span; + for (const Group& group : groups_) { + const auto start = group.by_base.lower_bound(from); + for (auto it = start; it != group.by_base.end() && it->first < to; ++it) + if (f(it->second.key)) return; + // Nothing before a base that lies max_extent below `from` reaches it. + for (auto it = start; it != group.by_base.begin();) { + --it; + if (from - it->first >= group.max_extent) break; + if (from - it->first < it->second.extent && f(it->second.key)) return; + } + } + } + bool contains(std::uint64_t base, Key key) const + { + for (const Group& group : groups_) { + const auto [first, last] = group.by_base.equal_range(base); + for (auto it = first; it != last; ++it) + if (it->second.key == key) return true; + } + return false; + } + std::size_t size() const { return groups_[0].by_base.size() + groups_[1].by_base.size(); } + +private: + // Large resources get their own group, so the backward search below an address stays short. + static constexpr std::uint64_t large = 64 * 1024; + struct Entry { + Key key; + std::uint64_t extent; + }; + struct Group { + std::multimap by_base; + std::uint64_t max_extent{}; + }; + Group groups_[2]; +}; + +// Stores records[key] = info and indexes it at `base` (0: not indexed) as one step: if either allocation +// throws, the record and the index are as they were, so no stored record is missing from lookups. The +// index node comes first; the only throwing step left is adding a new key to `records`, and it is +// undone by erasing that node (replacing an existing record cannot throw). +template +void store_indexed(AddressIndex& index, Records& records, const Key& key, std::uint64_t base, + std::uint64_t bytes, const Info& info) +{ + if (base) index.insert(base, bytes, key); + const bool known = records.find(key) != records.end(); + try { + records.insert_or_assign(key, info); + } catch (...) { + if (base && !known) index.erase(base, key); + throw; + } +} +} // namespace x2w_startup diff --git a/tests/startup_resource_address_index_check.cpp b/tests/startup_resource_address_index_check.cpp new file mode 100644 index 000000000..60371877f --- /dev/null +++ b/tests/startup_resource_address_index_check.cpp @@ -0,0 +1,264 @@ +// AddressIndex and store_indexed (src/startup_stubs/resource_address_index.h) against a scan of every +// resource, the way the memory SRV lookups (d3d12_memory_srv.inl) run. Resources are never removed from the +// table or the index. A release only drops the live reference count to 0 and a later reference raises it +// again; each lookup filters on that count itself, as the real lookups do, so the index must answer what the +// scan answers across release, re-reference, address reuse (dead entries and live ones at one base, where +// two live matches mean none), overlapping live ranges, re-noting a resource with another size and +// unaligned bases. Directed cases pin the span end: a base at address + span - 1 is found, one at +// address + span is not. Allocation failures are injected into store_indexed (operator new is replaced): +// the record and the index must both hold the new resource or both hold the old state. +// --mutate skip skips one index insert (a live resource the index lacks): must fail. +// --mutate unsync does the index insert first and leaves it behind when the record update fails (the +// unsynchronized order): must fail. +#include "startup_stubs/resource_address_index.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +long fail_after = -1; +bool injected; +} // namespace + +void* operator new(std::size_t size) +{ + if (fail_after == 0) { + fail_after = -1; + injected = true; + throw std::bad_alloc(); + } + if (fail_after > 0) --fail_after; + if (void* ptr = std::malloc(size ? size : 1)) return ptr; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } + +namespace { +using x2w_startup::address_span_touches; +struct Resource { + std::uint64_t base, bytes; + int refs; +}; +using Model = std::map; +using Index = x2w_startup::AddressIndex; +bool unknown_key; // the index returned a key with no record +bool unsync; // --mutate unsync + +const Resource& resource_of(const Model& model, int key) +{ + static const Resource none{}; + const auto found = model.find(key); + unknown_key |= found == model.end(); + return found == model.end() ? none : found->second; +} +bool scan_touches(const Model& model, std::uint64_t address, std::uint64_t span) +{ + for (const auto& [key, r] : model) + if (r.refs > 0 && address_span_touches(address, span, r.base, r.bytes)) return true; + return false; +} +bool index_touches(const Index& index, const Model& model, std::uint64_t address, std::uint64_t span) +{ + bool found = false; + index.for_each_reaching(address, span, [&](int key) { + const Resource& r = resource_of(model, key); + return found = r.refs > 0 && address_span_touches(address, span, r.base, r.bytes); + }); + return found; +} +// -1: no live resource contains the address, -2: several do, else the key of the only one. +int scan_containing(const Model& model, std::uint64_t address) +{ + int match = -1; + for (const auto& [key, r] : model) { + if (r.refs <= 0 || address < r.base || address - r.base >= r.bytes) continue; + match = match == -1 ? key : -2; + } + return match; +} +int index_containing(const Index& index, const Model& model, std::uint64_t address) +{ + int match = -1; + index.for_each_reaching(address, 1, [&](int key) { + const Resource& r = resource_of(model, key); + if (r.refs <= 0 || address < r.base || address - r.base >= r.bytes) return false; + if (match != -1) { + match = -2; + return true; + } + match = key; + return false; + }); + return match; +} +bool agree(const Index& index, const Model& model, std::uint64_t address, std::uint64_t span, const char* what) +{ + if (!unknown_key && scan_touches(model, address, span) == index_touches(index, model, address, span) && + scan_containing(model, address) == index_containing(index, model, address)) return true; + std::fprintf(stderr, "address index (%s): address 0x%llx span %llu: scan and index disagree\n", what, + static_cast(address), static_cast(span)); + return false; +} +// Every record is in the index and the index holds nothing else (the table is never pruned). +bool synced(const Index& index, const Model& model) +{ + for (const auto& [key, r] : model) + if (!index.contains(r.base, key)) return false; + return index.size() == model.size(); +} +bool mutated(const char* name, int argc, char** argv) { return argc > 2 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], name); } + +// store_indexed into the model, the way note_resource does it. skip: leave the index insert out. +void note(Index& index, Model& model, int key, const Resource& r, bool skip = false) +{ + if (unsync) { // the order store_indexed exists to avoid + index.insert(r.base, r.bytes, key); + model.insert_or_assign(key, r); + return; + } + x2w_startup::store_indexed(index, model, key, skip ? 0 : r.base, r.bytes, r); +} + +int directed(bool skip_one) +{ + constexpr std::uint64_t span = 64; + for (const std::uint64_t address : {0x10000ull, 0x10001ull, 0x12345ull}) { + for (const std::uint64_t bytes : {0ull, 1ull, 100ull, 70000ull}) { + // Alone, a base at address + span - 1 touches the span and one at address + span does not. + for (const std::uint64_t base : {address + span - 1, address + span}) { + Index index; + Model model; + note(index, model, 0, {base, bytes, 1}, skip_one && base == address + span - 1); + const bool expect = base == address + span - 1; + if (index_touches(index, model, address, span) != expect || scan_touches(model, address, span) != expect) { + std::fprintf(stderr, "address index: a base at address + span %s is %s\n", expect ? "- 1" : "", + expect ? "not found" : "found"); + return 1; + } + } + Index index; + Model model; + int next = 0; + for (const std::uint64_t base : {address + span - 1, address + span, address, address - 1, address + 1}) + note(index, model, next++, {base, bytes, 1}); + if (!agree(index, model, address, span, "directed")) return 1; + } + } + return 0; +} + +// An allocation failure at every point of a store_indexed (a new resource, then a re-note into another +// size group): the record and the index stay in step, and the retry succeeds. +int failures() +{ + int injections = 0; + for (int renote = 0; renote < 2; ++renote) { + for (long n = 0; n < 12; ++n) { + Index index; + Model model; + note(index, model, 1, {0x4000, 0x100, 1}); + note(index, model, 2, {0x4000, 0x80, 0}); // a released twin at the same base + const Resource fresh{renote ? 0x4000ull : 0x8000ull, renote ? 0x20000ull : 0x40ull, 1}; + const int key = renote ? 1 : 3; + const std::size_t records = model.size(); + const std::uint64_t old_bytes = model.at(1).bytes; + fail_after = n; + injected = false; + bool threw = false; + try { + note(index, model, key, fresh); + } catch (const std::bad_alloc&) { + threw = true; + } + fail_after = -1; + if (injected != threw) { + std::fprintf(stderr, "address index: injected failure not seen as a throw\n"); + return 1; + } + if (threw) { + ++injections; + // In neither: the old state, in both the record and the index. + if (model.size() != records || model.at(1).bytes != old_bytes || !synced(index, model)) { + std::fprintf(stderr, "address index: a failed store left the record and the index out of step (n=%ld renote=%d)\n", n, renote); + return 1; + } + for (const std::uint64_t a : {0x4000ull, 0x4050ull, 0x8000ull, 0x4100ull, 0x9000ull}) + if (!agree(index, model, a, 1, "after failure") || !agree(index, model, a, 0x30, "after failure")) return 1; + note(index, model, key, fresh); + } + if (model.at(key).bytes != fresh.bytes || !synced(index, model)) { + std::fprintf(stderr, "address index: the stored resource is not in both the record and the index\n"); + return 1; + } + for (const std::uint64_t a : {0x4000ull, 0x4050ull, 0x8000ull, 0x8040ull, 0x10000ull, 0x1ffffull, 0x24000ull}) + if (!agree(index, model, a, 1, "after store") || !agree(index, model, a, 0x30, "after store")) return 1; + } + } + std::printf("address index: %d injected allocation failures left the record and the index in step\n", injections); + return injections >= 3 ? 0 : 2; // new key: index node, record node; re-note: index node +} +} // namespace + +int main(int argc, char** argv) +{ + const bool skip = mutated("skip", argc, argv); + unsync = mutated("unsync", argc, argv); + if (argc != 1 && !skip && !unsync) { + std::fprintf(stderr, "usage: startup_resource_address_index_check [--mutate skip|unsync]\n"); + return 64; + } + if (const int rc = directed(skip)) return rc; + if (const int rc = failures()) return rc; + + std::mt19937_64 rng(12345); + const auto pick = [&](std::uint64_t n) { return rng() % n; }; + Index index; + Model model; + int next = 0, lookups = 0; + bool armed = skip; // --mutate skip: one insert dropped after step 5000 + for (int step = 0; step < 30000; ++step) { + const std::uint64_t op = pick(10); + if (model.size() < 400 && (model.empty() || op < 4)) { + // Bases cluster on a 4 KiB grid in a 16 MiB window (a third of them a few bytes off it) so + // ranges overlap, and a third reuse the base of an earlier resource, live or released. + const std::uint64_t reuse = !model.empty() && pick(3) == 0 ? std::next(model.begin(), pick(model.size()))->second.base : 0; + const std::uint64_t base = reuse ? reuse : (1 + pick(4096)) * 4096 + (pick(3) == 0 ? 1 + pick(4095) : 0); + const std::uint64_t kind = pick(4); + const std::uint64_t bytes = kind == 0 ? 0 : kind == 1 ? 1 + pick(4096) : kind == 2 ? (1 + pick(64)) * 4096 : (1 + pick(2048)) * 4096; + const bool dropped = armed && step >= 5000 && !pick(50); + armed &= !dropped; + note(index, model, next++, {base, bytes, 1}, dropped); + } else if (op < 5) { + // Re-note a resource: same base, another size. + const auto it = std::next(model.begin(), pick(model.size())); + note(index, model, it->first, {it->second.base, pick(2) ? pick(100000) : 0, it->second.refs}); + } else { + // Release, or reference again (the entry stays either way). + const auto it = std::next(model.begin(), pick(model.size())); + it->second.refs = it->second.refs > 0 ? 0 : 1 + static_cast(pick(2)); + } + for (int i = 0; i < 6; ++i, ++lookups) { + const std::uint64_t address = pick(0x1100000) + (pick(2) ? 0 : 4096 * pick(4096)), span = pick(3) ? pick(4096) : pick(64); + if (!agree(index, model, address, span, "random")) return 1; + // The edges of a random resource, live or released. + const Resource& r = std::next(model.begin(), pick(model.size()))->second; + for (const std::uint64_t a : {r.base, r.base + r.bytes - 1, r.base + r.bytes, r.base - 1}) + if (!agree(index, model, a, 1 + pick(8), "edge")) return 1; + } + } + if (!synced(index, model)) { + std::fprintf(stderr, "address index: a record and the index differ\n"); + return 1; + } + int live = 0; + for (const auto& [key, r] : model) live += r.refs > 0; + std::printf("address index: %d lookups agree with a scan of %zu resources (%d live) across release, re-reference, " + "address reuse, re-note and span-end edges\n", lookups, model.size(), live); + return 0; +} From e33578e1126fa77122587b2291cd45af1d65b1c8 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:12:12 -0700 Subject: [PATCH 014/232] d3d12: support Texture3D views in device slot 70 (#2338) Accept Texture3D placed memory SRVs with D3D12_TEXTURE_LAYOUT_UNKNOWN and matching D3D12_SRV_DIMENSION_TEXTURE3D views in device slot 70. Refuse console swizzled layouts, depth formats, mismatched view dimensions (including Texture2D views on 3D resources and Texture3D views on 2D resources), non-multiple-of-4 block extents for block-compressed formats, out-of-bounds mip ranges, and explicit non-zero LOD clamps. Compute volume byte sizes considering all mip levels and block texel dimensions, use SliceFootprints footprint size in device runtime for row pitch and placement alignment, and upload 3D placed texture footprints before draw execution. Add startup_memory_srv_volume with mutation negative controls (layout, 2d-view, 3d-view, mips-overflow), add 3D view checks to startup_gfx10_layout, and add startup_address_volume_srv_warp / startup_address_volume_srv_hardware to verify 3D volume draws across depth slices, mip levels, and refusals. --- CMakeLists.txt | 14 ++ docs/startup-runtime.md | 20 ++- src/startup_stubs/address_texture.h | 48 ++++- src/startup_stubs/d3d12_draw.inl | 6 +- src/startup_stubs/d3d12_memory_srv.inl | 18 +- src/startup_stubs/memory_srv_report.h | 3 + tests/startup_address_srv.cpp | 114 ++++++++++++ tests/startup_address_volume_srv_check.py | 94 ++++++++++ tests/startup_gfx10_layout_check.cpp | 27 ++- tests/startup_memory_srv_report_check.cpp | 16 +- tests/startup_memory_srv_volume_check.cpp | 203 ++++++++++++++++++++++ tests/startup_stream_draw.cpp | 3 + 12 files changed, 553 insertions(+), 13 deletions(-) create mode 100644 tests/startup_address_volume_srv_check.py create mode 100644 tests/startup_memory_srv_volume_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index eeebb1a64..e9cd32bb5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1712,6 +1712,16 @@ foreach(mutation IN ITEMS height exact-fit first-32) add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Volume memory SRV validation for device slot 70 (src/startup_stubs/address_texture.h); the mutated +# runs are negative controls. +add_executable(startup_memory_srv_volume_check tests/startup_memory_srv_volume_check.cpp) +target_include_directories(startup_memory_srv_volume_check PRIVATE src) +target_compile_features(startup_memory_srv_volume_check PRIVATE cxx_std_17) +add_test(NAME startup_memory_srv_volume COMMAND startup_memory_srv_volume_check) +foreach(mutation IN ITEMS layout 2d-view 3d-view mips-overflow) + add_test(NAME startup_memory_srv_volume_${mutation}_control COMMAND startup_memory_srv_volume_check --mutate ${mutation}) + set_tests_properties(startup_memory_srv_volume_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Console allocation sizes for depth-with-stencil and multisampled textures # (src/startup_stubs/console_plane_size.h); the mutated run is the negative control. add_executable(startup_plane_size_check tests/startup_plane_size_check.cpp) @@ -3443,6 +3453,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_buffer_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_address_volume_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_volume_srv_check.py" + "$" "${backend}") + set_tests_properties(startup_address_volume_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_d16_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_d16_srv_check.py" "$" "${backend}") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a7eda8140..1beb90dda 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2663,6 +2663,20 @@ element, and widths, addresses and first elements above 4 GiB. Its `_control` ru `exact-fit`, `first-32`) expect wrong answers and must fail. `startup_address_buffer_srv_*` exercises only the resolve path with valid addresses on a device, so it does not cover the rejections. -- `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer)$' -V` -- `ctest --preset release --no-tests=error -R '^startup_memory_srv_buffer_.*_control$' -V` -- `ctest --preset release --no-tests=error -R '^startup_address_(srv|buffer_srv)_' -V` +`startup_memory_srv_volume` is device-free and validates volume (Texture3D) memory SRVs in +device slot 70 (`supports_volume_memory_srv`, `address_view_fits`, `volume_texture_bytes`). +It pins the supported layout to `D3D12_TEXTURE_LAYOUT_UNKNOWN`, enforces `D3D12_SRV_DIMENSION_TEXTURE3D`, +validates block-compressed dimensions and sizing (BC3, BC7), and validates mip bounds. Its `_control` +runs (`layout`, `2d-view`, `3d-view`, `mips-overflow`) expect wrong answers and must fail. +In device runtime, `address_texture_bytes` uses `SliceFootprints::size` to account for desktop copyable +footprint layout (256-byte row pitch alignment and 512-byte subresource placement alignment), while +`volume_texture_bytes` provides device-free packed texel byte sizing. +`startup_address_volume_srv_*` exercises volume SRVs on a device (WARP and hardware) +with multiple depth slices and mip levels, where footprint row pitch (256 bytes) exceeds packed row bytes (16 bytes), +and verifies refusal lines for mismatched view dimensions, short backings, out-of-bounds mips, explicit clamps, +and console layouts. On Windows 11 Build 26100 with an AMD Radeon RX 6600M (driver 32.0.21045.11001), +`startup_address_volume_srv_hardware` passed with all 32 RGBA pixels exact. + +- `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer|volume)$' -V` +- `ctest --preset release --no-tests=error -R '^startup_memory_srv_(buffer|volume)_.*_control$' -V` +- `ctest --preset release --no-tests=error -R '^startup_address_(srv|buffer_srv|volume_srv)_' -V` diff --git a/src/startup_stubs/address_texture.h b/src/startup_stubs/address_texture.h index 10ea4c6e3..11d833739 100644 --- a/src/startup_stubs/address_texture.h +++ b/src/startup_stubs/address_texture.h @@ -82,12 +82,56 @@ inline bool address_view_fits(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_R return count == ~0u ? first < r.MipLevels : inside(first, count, r.MipLevels); }; if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D) - return r.DepthOrArraySize == 1 && mips_fit(v.Texture2D.MostDetailedMip, v.Texture2D.MipLevels) && + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.DepthOrArraySize == 1 && + mips_fit(v.Texture2D.MostDetailedMip, v.Texture2D.MipLevels) && !v.Texture2D.PlaneSlice && v.Texture2D.ResourceMinLODClamp == 0.0f; if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2DARRAY) - return mips_fit(v.Texture2DArray.MostDetailedMip, v.Texture2DArray.MipLevels) && + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && + mips_fit(v.Texture2DArray.MostDetailedMip, v.Texture2DArray.MipLevels) && inside(v.Texture2DArray.FirstArraySlice, v.Texture2DArray.ArraySize, r.DepthOrArraySize) && !v.Texture2DArray.PlaneSlice && v.Texture2DArray.ResourceMinLODClamp == 0.0f; + if (v.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE3D) + return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && + mips_fit(v.Texture3D.MostDetailedMip, v.Texture3D.MipLevels) && + v.Texture3D.ResourceMinLODClamp == 0.0f; return false; } + +inline bool supports_volume_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER_RESOURCE_VIEW_DESC& v) +{ + if (r.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return false; + if (!r.Width || !r.Height || !r.DepthOrArraySize || !r.MipLevels) return false; + if (r.SampleDesc.Count != 1 || r.SampleDesc.Quality != 0) return false; + if (r.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) return false; + if (r.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) return false; + if (v.ViewDimension != D3D12_SRV_DIMENSION_TEXTURE3D) return false; + if (v.Format != r.Format) return false; + if (address_depth_format(r.Format)) return false; + const auto elem = gfx10::element_of(r.Format); + if (!elem.bytes || (elem.texels > 1 && ((r.Width % elem.texels) != 0 || (r.Height % elem.texels) != 0))) + return false; + return address_view_fits(r, v); +} + +// Packed texel payload bytes of a 3D volume across all mip levels (excluding D3D12 256-byte row pitch padding). +// In device contexts, address_texture_bytes evaluates SliceFootprints::size to account for D3D12 copyable footprint +// row pitch (256-byte alignment) and subresource placement alignment. +inline std::uint64_t volume_texture_bytes(const D3D12_RESOURCE_DESC& desc) +{ + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) return 0; + const auto elem = gfx10::element_of(desc.Format); + if (!elem.bytes || !elem.texels || !desc.Width || !desc.Height || !desc.DepthOrArraySize) return 0; + std::uint64_t total = 0; + std::uint64_t w = desc.Width, h = desc.Height, d = desc.DepthOrArraySize; + const UINT mips = desc.MipLevels ? desc.MipLevels : 1; + for (UINT i = 0; i < mips; ++i) { + const std::uint64_t blocks_w = (w + elem.texels - 1) / elem.texels; + const std::uint64_t blocks_h = (h + elem.texels - 1) / elem.texels; + total += blocks_w * blocks_h * d * elem.bytes; + w = (w > 1) ? (w >> 1) : 1; + h = (h > 1) ? (h >> 1) : 1; + d = (d > 1) ? (d >> 1) : 1; + } + return total; +} } // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1aec345f4..42a35ca21 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1093,7 +1093,8 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) const bool dedicated = console && !address_uploads_from_ring(); // An address-only single-element texture (2D or 3D) uploads its one texel through the footprint path. const bool single = resource->own().tiled_address_srv && x2w_startup::single_element_bytes(desc) != 0; - const bool uploadable = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || single || + const bool uploadable = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D || + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D || single || (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc.DepthOrArraySize == 1 && desc.Height == 1); { static LONG reasons; @@ -1109,7 +1110,8 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) if (const auto written_by_gpu = texture_uploads().find(texture); written_by_gpu != texture_uploads().end() && written_by_gpu->second.gpu_written) return !console; if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return !console; const UINT mips = desc.MipLevels ? desc.MipLevels : 1; - const UINT slices = desc.DepthOrArraySize ? desc.DepthOrArraySize : 1; + // For Texture3D, depth slices are carried in Footprint.Depth and spanned by SliceFootprints::bytes(). + const UINT slices = (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D || !desc.DepthOrArraySize) ? 1 : desc.DepthOrArraySize; if (mips > 15) return !console; const x2w_startup::SliceFootprints plan(device_of(the_device), desc, mips); const UINT64 slice_total = plan.size; diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 1b6d33a59..a2807ec61 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -88,6 +88,7 @@ bool supports_placed_memory_srv(const D3D12_RESOURCE_DESC& r, const D3D12_SHADER !v.Texture2D.PlaneSlice && v.Texture2D.ResourceMinLODClamp == 0; } if (x2w_startup::supports_single_element_srv(r, v)) return true; + if (x2w_startup::supports_volume_memory_srv(r, v)) return true; return r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && r.Width && r.Height && r.DepthOrArraySize == 1 && r.MipLevels == 1 && r.SampleDesc.Count == 1 && r.SampleDesc.Quality == 0 && (r.Format == DXGI_FORMAT_R8_UNORM || tiled_bc_srv(r)) && v.Format == r.Format && !(r.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && @@ -114,7 +115,9 @@ bool desktop_address_view_supported(Wrapper* device, const D3D12_RESOURCE_DESC& D3D12_FEATURE_DATA_FORMAT_SUPPORT storage{r.Format}; if (r.Format == v.Format) storage = view; else if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &storage, sizeof(storage)))) return false; - return (storage.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) && + const UINT req = r.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? D3D12_FORMAT_SUPPORT1_TEXTURE3D + : D3D12_FORMAT_SUPPORT1_TEXTURE2D; + return (storage.Support1 & req) && (r.MipLevels == 1 || (storage.Support1 & D3D12_FORMAT_SUPPORT1_MIP)); } @@ -304,11 +307,18 @@ void log_address_kind(const char* outcome, const D3D12_RESOURCE_DESC& r, const D } // Bytes the texels of a by-address texture span at their address. -u64 address_texture_bytes(const D3D12_RESOURCE_DESC& desc) +u64 address_texture_bytes(Wrapper* device, const D3D12_RESOURCE_DESC& desc) { if (const UINT element = x2w_startup::single_element_bytes(desc)) return element; if (x2w_startup::bc64::supports(desc)) return x2w_startup::bc64::Chain(desc).bytes(); if (console_layout_srv(desc)) return x2w_startup::gfx10::Layout(desc).bytes(); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + if (device) { + const x2w_startup::SliceFootprints plan(device_of(device), sanitized(desc), desc.MipLevels ? desc.MipLevels : 1); + if (plan.size != UINT64_MAX && plan.size) return plan.size; + } + return x2w_startup::volume_texture_bytes(desc); + } return x2w_startup::Bc16Surface(desc).size(); } @@ -330,7 +340,7 @@ const char* console_address_hold(Wrapper* device, u64 address, const D3D12_RESOU Wrapper* publish_tiled_texture(Wrapper* device, u64 address, const D3D12_RESOURCE_DESC& desc) { - const auto bytes = address_texture_bytes(desc); + const auto bytes = address_texture_bytes(device, desc); // The transient upload ring accepts individual copies up to 64 MiB. if (bytes > (64ull << 20) || !x2w_local::readable(reinterpret_cast(address), bytes)) return nullptr; std::lock_guard lock(tiled_srv_mutex); @@ -494,7 +504,7 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou texture = nullptr; } else if (!texture) { held = console_address_hold(self, input->address, *resource); - if (!held && address_resource_overlap(input->address, address_texture_bytes(*resource))) + if (!held && address_resource_overlap(input->address, address_texture_bytes(self, *resource))) held = "overlapping_resource"; texture = held ? nullptr : publish_tiled_texture(self, input->address, *resource); outcome = "published console layout"; diff --git a/src/startup_stubs/memory_srv_report.h b/src/startup_stubs/memory_srv_report.h index ff74b82b2..6a56a036a 100644 --- a/src/startup_stubs/memory_srv_report.h +++ b/src/startup_stubs/memory_srv_report.h @@ -51,6 +51,9 @@ inline int report_view(char* out, std::size_t size, const D3D12_SHADER_RESOURCE_ v->Texture2DArray.MostDetailedMip, v->Texture2DArray.MipLevels, v->Texture2DArray.FirstArraySlice, v->Texture2DArray.ArraySize, v->Texture2DArray.PlaneSlice, static_cast(v->Texture2DArray.ResourceMinLODClamp)); + case D3D12_SRV_DIMENSION_TEXTURE3D: + return std::snprintf(tail, room, "mostmip=%u mips=%u clamp=%g", v->Texture3D.MostDetailedMip, + v->Texture3D.MipLevels, static_cast(v->Texture3D.ResourceMinLODClamp)); case D3D12_SRV_DIMENSION_BUFFER: return std::snprintf(tail, room, "first=%llu count=%u stride=%u flags=0x%x (buffer views are not supported)", static_cast(v->Buffer.FirstElement), v->Buffer.NumElements, diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 35060d228..7a9a77e21 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -707,3 +707,117 @@ int draw_d16_srvs(ID3D12Device* desktop, void* guest, void* list) draw_at(7, 8); // Rebind R16_UNORM default SRV on column 7; must draw yellow (0x3bff) cleanly. return 0; } + +// 3D volume memory SRV (device slot 70) with 2 mips (4x4x2 and 2x2x1) in RGBA8_UNORM format. +int draw_volume_address_srvs(ID3D12Device* desktop, void* guest, void* list) +{ + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE3D, 0, 4, 4, 2, 2, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[2]{}; + UINT rows[2]{}; + UINT64 row_bytes[2]{}; + UINT64 total_bytes = 0; + desktop->GetCopyableFootprints(&desc, 0, 2, 0, footprints, rows, row_bytes, &total_bytes); + if (!total_bytes || total_bytes == ~UINT64{0}) return 50; + // Footprint row pitch (256 bytes) is larger than packed row bytes (4 texels * 4 bytes = 16 bytes). + if (footprints[0].Footprint.RowPitch <= row_bytes[0]) return 52; + + static std::vector backing; + backing.assign(static_cast(total_bytes), 0); + + const auto write_voxel = [&](UINT mip, UINT z, UINT y, UINT x, const unsigned char rgba[4]) { + const auto& fp = footprints[mip].Footprint; + const UINT64 slice_pitch = fp.RowPitch * rows[mip]; + const UINT64 offset = footprints[mip].Offset + z * slice_pitch + y * fp.RowPitch + x * 4; + if (offset + 4 <= backing.size()) + std::memcpy(backing.data() + offset, rgba, 4); + }; + + const unsigned char c0[4] = {200, 50, 10, 255}; // mip 0, slice 0 + const unsigned char c1[4] = {50, 200, 10, 255}; // mip 0, slice 1 + const unsigned char c2[4] = {10, 50, 200, 255}; // mip 1, slice 0 + for (UINT y = 0; y < 4; ++y) + for (UINT x = 0; x < 4; ++x) { + write_voxel(0, 0, y, x, c0); + write_voxel(0, 1, y, x, c1); + } + for (UINT y = 0; y < 2; ++y) + for (UINT x = 0; x < 2; ++x) + write_voxel(1, 0, y, x, c2); + + void* placed = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(backing.data()), ptr(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, + ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) + return 51; + + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + + const auto draw = [&](LONG x) { + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + + ViewAt v{}; + v.view.Format = desc.Format; + v.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.view.Texture3D.MostDetailedMip = 0; + v.view.Texture3D.MipLevels = 2; + v.address = ptr(backing.data()); + + // Col 0: view of mip 0+1, shader samples (0, 0, slice 0, mip 0) + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + draw(0); + + // Col 1: shader samples (0, 0, slice 1, mip 0) + draw(1); + + // Col 2: view restricted to mip 1 + v.view.Texture3D.MostDetailedMip = 1; + v.view.Texture3D.MipLevels = 1; + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + draw(2); + + // Refusals before column 3: + // 1. Wrong view dimension (2D view on 3D resource) + ViewAt bad_dim = v; + bad_dim.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + invoke(guest, 70, ptr(&desc), ptr(&bad_dim), cpu); + + // 2. Short backing / unregistered interior address + ViewAt bad_addr = v; + bad_addr.address = ptr(backing.data()) + 1; + invoke(guest, 70, ptr(&desc), ptr(&bad_addr), cpu); + + // 3. Mip range out of bounds + ViewAt bad_mip = v; + bad_mip.view.Texture3D.MostDetailedMip = 2; + invoke(guest, 70, ptr(&desc), ptr(&bad_mip), cpu); + + // 4. Explicit non-zero LOD clamp + ViewAt bad_clamp = v; + bad_clamp.view.Texture3D.ResourceMinLODClamp = 1.0f; + invoke(guest, 70, ptr(&desc), ptr(&bad_clamp), cpu); + + // 5. Wrong layout (console layout 0x105) + D3D12_RESOURCE_DESC bad_layout = desc; + bad_layout.Layout = static_cast(0x105); + invoke(guest, 70, ptr(&bad_layout), ptr(&v), cpu); + + // Col 3: all refusals preserved the previous descriptor (mip 1 view) + draw(3); + + // Col 4-7: rebind mip 0+1 + v.view.Texture3D.MostDetailedMip = 0; + v.view.Texture3D.MipLevels = 2; + invoke(guest, 70, ptr(&desc), ptr(&v), cpu); + draw(4); + draw(5); + draw(6); + draw(7); + + return 0; +} diff --git a/tests/startup_address_volume_srv_check.py b/tests/startup_address_volume_srv_check.py new file mode 100644 index 000000000..c83b6d5ba --- /dev/null +++ b/tests/startup_address_volume_srv_check.py @@ -0,0 +1,94 @@ +"""Publish placed Texture3D SRVs by address, sample slices and mips in translated draws, and check refusals.""" +from pathlib import Path +import re +import sys +import tempfile + +from startup_address_srv_check import draw_texture + +HEX = r"0x[0-9a-f]+" + + +def check_refusal_lines(log): + prefix = r"x2w-d3d12 Device::slot70 " + res_base = r"res\{dim=4 fmt=28 size=4x4x2 mips=2 layout=0x0 flags=0x0 align=0 samples=1/0\}" + res_swizzle = r"res\{dim=4 fmt=28 size=4x4x2 mips=2 layout=0x105 flags=0x0 align=0 samples=1/0\}" + expected = [ + # 1. 2D view on 3D resource + prefix + + r"unsupported memory SRV arguments: reason=unsupported_description " + + res_base + + r" view\{dim=4 fmt=28 map=0x1688 mostmip=1 mips=1 plane=0 clamp=0\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + # 2. Short backing / unregistered address + prefix + + r"unavailable texture at the supplied base and layout: reason=texture_unavailable " + + res_base + + r" view\{dim=8 fmt=28 map=0x1688 mostmip=1 mips=1 clamp=0\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + # 3. Mip out of bounds + prefix + + r"unsupported memory SRV arguments: reason=unsupported_description " + + res_base + + r" view\{dim=8 fmt=28 map=0x1688 mostmip=2 mips=1 clamp=0\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + # 4. Explicit non-zero LOD clamp + prefix + + r"unsupported memory SRV arguments: reason=unsupported_description " + + res_base + + r" view\{dim=8 fmt=28 map=0x1688 mostmip=1 mips=1 clamp=1\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + # 5. Wrong layout (0x105) + prefix + + r"unsupported memory SRV arguments: reason=unsupported_description " + + res_swizzle + + r" view\{dim=8 fmt=28 map=0x1688 mostmip=1 mips=1 clamp=0\} " + + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", + ] + lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] + if len(lines) != len(expected): + raise AssertionError(f"{len(lines)} slot 70 lines, expected {len(expected)}:\n" + "\n".join(lines)) + for line, pattern in zip(lines, expected): + if not re.fullmatch(pattern, line): + raise AssertionError(f"slot 70 line does not match\n line {line}\n expected {pattern}") + + +def check(directory, consumer, backend): + hlsl = ( + "Texture3D t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " uint x = uint(p.x);\n" + " int slice = (x == 1 || x == 5) ? 1 : 0;\n" + " return t.Load(int4(0, 0, slice, 0));\n" + "}\n" + ) + trap_log = directory / "trap.log" + actual = draw_texture( + directory, + consumer, + backend, + hlsl, + {"X2W_TEST_ADDRESS_VOLUME_SRV": "1", "X2W_TRAP_LOG": str(trap_log)}, + "tex3d", + ) + if actual is None: + return 77 + c0 = (200, 50, 10, 255) + c1 = (50, 200, 10, 255) + c2 = (10, 50, 200, 255) + columns = [c0, c1, c2, c2, c0, c1, c0, c0] + expected = bytes(c for _ in range(4) for column in columns for c in column) + if actual != expected: + for i in range(0, len(expected), 4): + if actual[i:i + 4] != expected[i:i + 4]: + raise AssertionError(f"column {(i // 4) % 8} row {i // 32}: actual {actual[i:i + 4].hex()} " + f"expected {expected[i:i + 4].hex()}") + raise AssertionError(f"actual length {len(actual)}, expected {len(expected)}") + check_refusal_lines(trap_log.read_text(errors="replace")) + print(f"{backend}: volume memory SRV (slices 0/1, mips 0/1, refused 2D view/short backing/mip overflow/clamp/layout) exact") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check(Path(temporary), *sys.argv[1:])) diff --git a/tests/startup_gfx10_layout_check.cpp b/tests/startup_gfx10_layout_check.cpp index 62cce08f5..81a1ccc77 100644 --- a/tests/startup_gfx10_layout_check.cpp +++ b/tests/startup_gfx10_layout_check.cpp @@ -296,6 +296,31 @@ void check_address_textures() v.Texture2DArray.ArraySize = 2; fits("last two slices", true); v.Texture2DArray.ArraySize = ~0u; fits("unspecified array size", false); v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; fits("cube view", false); + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.Texture3D.MipLevels = 10; + fits("3D view on 2D chain", false); + + D3D12_RESOURCE_DESC vol = texture(32, 32, 4, 1, DXGI_FORMAT_R8G8B8A8_UNORM, 0); + vol.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + vol.DepthOrArraySize = 16; + v = {}; + v.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v.Texture2D.MipLevels = 4; + if (x2w_startup::address_view_fits(vol, v)) fail("2D view on 3D volume"); + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.Texture3D.MipLevels = 4; + if (!x2w_startup::address_view_fits(vol, v)) fail("whole 3D volume view"); + v.Texture3D.MostDetailedMip = 2; + v.Texture3D.MipLevels = 2; + if (!x2w_startup::address_view_fits(vol, v)) fail("sub-mip 3D volume view"); + v.Texture3D.MipLevels = 3; + if (x2w_startup::address_view_fits(vol, v)) fail("3D volume view past mip count"); + v.Texture3D.MostDetailedMip = 0; + v.Texture3D.MipLevels = 4; + v.Texture3D.ResourceMinLODClamp = 1.0f; + if (x2w_startup::address_view_fits(vol, v)) fail("3D volume view explicit LOD clamp"); } } // namespace @@ -317,6 +342,6 @@ int main(int argc, char** argv) std::printf("startup_gfx10_layout: %d FAILED\n", failures); return 1; } - std::printf("startup_gfx10_layout: PASS (30 equations, 5 4 KiB surfaces, 8 64 KiB chains, 10 tile plans, 9 round trips, 11 refusals, 19 address descriptions, 21 views)\n"); + std::printf("startup_gfx10_layout: PASS (30 equations, 5 4 KiB surfaces, 8 64 KiB chains, 10 tile plans, 9 round trips, 11 refusals, 19 address descriptions, 27 views)\n"); return 0; } diff --git a/tests/startup_memory_srv_report_check.cpp b/tests/startup_memory_srv_report_check.cpp index b05f23772..2639dd82d 100644 --- a/tests/startup_memory_srv_report_check.cpp +++ b/tests/startup_memory_srv_report_check.cpp @@ -145,6 +145,20 @@ int main() "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=null_destination " "res{unreadable} view{unreadable} dest=0x0 dest_in_view_heap=0 address=0x0 address_readable=0"); + // A 3D texture view. + D3D12_RESOURCE_DESC tex3d{D3D12_RESOURCE_DIMENSION_TEXTURE3D, 0, 32, 32, 32, 1, DXGI_FORMAT_R8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + auto v3d = view(D3D12_SRV_DIMENSION_TEXTURE3D, DXGI_FORMAT_R8_UNORM); + v3d.Texture3D.MostDetailedMip = 0; + v3d.Texture3D.MipLevels = 1; + v3d.Texture3D.ResourceMinLODClamp = 0.0f; + line(out, "destination_outside_view_heaps", &tex3d, &v3d, 0x3000, true, 0x1000, false); + expect("texture 3D view", out, + "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=destination_outside_view_heaps " + "res{dim=4 fmt=61 size=32x32x32 mips=1 layout=0x0 flags=0x0 align=0 samples=1/0} " + "view{dim=8 fmt=61 map=0x1688 mostmip=0 mips=1 clamp=0} " + "dest=0x1000 dest_in_view_heap=0 address=0x3000 address_readable=1"); + // A small buffer is cut, never overrun, and stays terminated. char tiny_buf[40]; std::memset(tiny_buf, 'x', sizeof(tiny_buf)); @@ -155,6 +169,6 @@ int main() std::printf("FAIL truncated line is not terminated\n"); } if (failures) return 1; - std::printf("slot 70 refusal lines: 8 lines and a truncation exact\n"); + std::printf("slot 70 refusal lines: 9 lines and a truncation exact\n"); return 0; } diff --git a/tests/startup_memory_srv_volume_check.cpp b/tests/startup_memory_srv_volume_check.cpp new file mode 100644 index 000000000..e2facae92 --- /dev/null +++ b/tests/startup_memory_srv_volume_check.cpp @@ -0,0 +1,203 @@ +// Checks validation, view fitting, and byte sizing for volume (Texture3D) memory SRVs (device slot 70) without a device. +// --mutate layout: expect layout 0x105 to be accepted. +// --mutate 2d-view: expect a Texture2D view on a 3D resource to be accepted. +// --mutate 3d-view: expect a Texture3D view on a 2D resource to be accepted. +// --mutate mips-overflow: expect a view specifying more mips than available to be accepted. +// Each mutated run is a negative control and must fail. +#include "startup_stubs/address_texture.h" + +#include +#include + +namespace { + +int failures; +const char* mutation = ""; + +bool mutated(const char* name) +{ + return std::strcmp(mutation, name) == 0; +} + +void check(const char* name, bool condition) +{ + if (condition) return; + ++failures; + std::printf("FAIL %s\n", name); +} + +D3D12_RESOURCE_DESC tex3d(UINT64 width, UINT height, UINT16 depth, UINT16 mips, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM, + UINT layout = 0) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + desc.Width = width; + desc.Height = height; + desc.DepthOrArraySize = depth; + desc.MipLevels = mips; + desc.Format = format; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Layout = static_cast(layout); + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + return desc; +} + +D3D12_SHADER_RESOURCE_VIEW_DESC view3d(DXGI_FORMAT format, UINT mostmip, UINT mips, float clamp = 0.0f) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.Texture3D.MostDetailedMip = mostmip; + v.Texture3D.MipLevels = mips; + v.Texture3D.ResourceMinLODClamp = clamp; + return v; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && + (std::strcmp(argv[2], "layout") == 0 || std::strcmp(argv[2], "2d-view") == 0 || + std::strcmp(argv[2], "3d-view") == 0 || std::strcmp(argv[2], "mips-overflow") == 0)) { + mutation = argv[2]; + } else if (argc != 1) { + std::printf("usage: startup_memory_srv_volume_check [--mutate layout|2d-view|3d-view|mips-overflow]\n"); + return 2; + } + + // Base valid 3D resource and view. + const auto res = tex3d(32, 32, 16, 4, DXGI_FORMAT_R8G8B8A8_UNORM, 0); + const auto v_all = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 0, ~0u); + const auto v_exact = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 0, 4); + const auto v_sub = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 1, 2); + const auto v_last = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 3, 1); + + check("all mips accepted", x2w_startup::supports_volume_memory_srv(res, v_all)); + check("exact mips accepted", x2w_startup::supports_volume_memory_srv(res, v_exact)); + check("sub-mip range accepted", x2w_startup::supports_volume_memory_srv(res, v_sub)); + check("last mip accepted", x2w_startup::supports_volume_memory_srv(res, v_last)); + + // View dimension validation. + auto v_2d = v_exact; + v_2d.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + v_2d.Texture2D.MostDetailedMip = 0; + v_2d.Texture2D.MipLevels = 4; + v_2d.Texture2D.PlaneSlice = 0; + v_2d.Texture2D.ResourceMinLODClamp = 0.0f; + check("2D view on 3D resource refused", x2w_startup::supports_volume_memory_srv(res, v_2d) == mutated("2d-view")); + + auto v_2darr = v_exact; + v_2darr.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + v_2darr.Texture2DArray.MostDetailedMip = 0; + v_2darr.Texture2DArray.MipLevels = 4; + v_2darr.Texture2DArray.FirstArraySlice = 0; + v_2darr.Texture2DArray.ArraySize = 16; + check("2D array view on 3D resource refused", !x2w_startup::supports_volume_memory_srv(res, v_2darr)); + + // Resource dimension validation. + auto res_2d = res; + res_2d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + check("3D view on 2D resource refused", x2w_startup::supports_volume_memory_srv(res_2d, v_exact) == mutated("3d-view")); + + // Layout pinning: layout must be D3D12_TEXTURE_LAYOUT_UNKNOWN. + auto res_swizzle = res; + res_swizzle.Layout = static_cast(0x105); + check("console layout 0x105 refused", x2w_startup::supports_volume_memory_srv(res_swizzle, v_exact) == mutated("layout")); + + auto res_linear = res; + res_linear.Layout = static_cast(0x100); + check("console linear layout 0x100 refused", !x2w_startup::supports_volume_memory_srv(res_linear, v_exact)); + + // Mip bounds. + auto v_overflow = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 1, 4); + check("mips exceeding chain refused", x2w_startup::supports_volume_memory_srv(res, v_overflow) == mutated("mips-overflow")); + + auto v_first_past = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 4, 1); + check("most detailed mip at or past count refused", !x2w_startup::supports_volume_memory_srv(res, v_first_past)); + + auto v_zero_mips = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 0, 0); + check("zero mips refused", !x2w_startup::supports_volume_memory_srv(res, v_zero_mips)); + + // Explicit LOD clamp. + auto v_clamp = view3d(DXGI_FORMAT_R8G8B8A8_UNORM, 0, 4, 1.5f); + check("explicit LOD clamp refused", !x2w_startup::supports_volume_memory_srv(res, v_clamp)); + + // Format compatibility and mapping. + auto v_bad_fmt = view3d(DXGI_FORMAT_R8_UNORM, 0, 4); + check("format mismatch refused", !x2w_startup::supports_volume_memory_srv(res, v_bad_fmt)); + + auto v_bad_map = v_exact; + v_bad_map.Shader4ComponentMapping = 0; + check("invalid component mapping refused", !x2w_startup::supports_volume_memory_srv(res, v_bad_map)); + + // Block-compressed 3D textures (BC3, BC7). + const auto bc7_res = tex3d(16, 16, 4, 1, DXGI_FORMAT_BC7_UNORM, 0); + const auto bc7_view = view3d(DXGI_FORMAT_BC7_UNORM, 0, 1); + check("BC7 volume accepted", x2w_startup::supports_volume_memory_srv(bc7_res, bc7_view)); + // 4x4 blocks * 4 slices * 16 bytes = 1024 bytes. + check("BC7 volume byte count", x2w_startup::volume_texture_bytes(bc7_res) == 1024); + + const auto bc3_res = tex3d(8, 8, 2, 2, DXGI_FORMAT_BC3_UNORM, 0); + const auto bc3_view = view3d(DXGI_FORMAT_BC3_UNORM, 0, 2); + check("BC3 multi-mip volume accepted", x2w_startup::supports_volume_memory_srv(bc3_res, bc3_view)); + // mip 0: 2x2 blocks * 2 slices * 16 = 128 bytes; mip 1: 1x1 blocks * 1 slice * 16 = 16 bytes. Total = 144 bytes. + check("BC3 multi-mip volume byte count", x2w_startup::volume_texture_bytes(bc3_res) == 144); + + const auto bc7_sub4 = tex3d(16, 16, 4, 4, DXGI_FORMAT_BC7_UNORM, 0); + const auto bc7_sub4_view = view3d(DXGI_FORMAT_BC7_UNORM, 0, 4); + check("BC7 4-mip volume with sub-4x4 tail accepted", x2w_startup::supports_volume_memory_srv(bc7_sub4, bc7_sub4_view)); + // mip 0 (16x16x4): 4x4 blocks * 4 slices * 16 = 1024 bytes + // mip 1 (8x8x2): 2x2 blocks * 2 slices * 16 = 128 bytes + // mip 2 (4x4x1): 1x1 blocks * 1 slice * 16 = 16 bytes + // mip 3 (2x2x1, sub-block): 1x1 blocks * 1 slice * 16 = 16 bytes. Total = 1184 bytes. + check("BC7 4-mip sub-block volume byte count", x2w_startup::volume_texture_bytes(bc7_sub4) == 1184); + + auto bc7_bad_w = bc7_res; + bc7_bad_w.Width = 14; + check("BC7 width not multiple of 4 refused", !x2w_startup::supports_volume_memory_srv(bc7_bad_w, bc7_view)); + + auto bc7_bad_h = bc7_res; + bc7_bad_h.Height = 14; + check("BC7 height not multiple of 4 refused", !x2w_startup::supports_volume_memory_srv(bc7_bad_h, bc7_view)); + + check("depth format refused", !x2w_startup::supports_volume_memory_srv(tex3d(4, 4, 4, 1, DXGI_FORMAT_D24_UNORM_S8_UINT), view3d(DXGI_FORMAT_D24_UNORM_S8_UINT, 0, 1))); + + // Resource shape fields. + auto res_w0 = res; res_w0.Width = 0; + check("zero width refused", !x2w_startup::supports_volume_memory_srv(res_w0, v_exact)); + auto res_h0 = res; res_h0.Height = 0; + check("zero height refused", !x2w_startup::supports_volume_memory_srv(res_h0, v_exact)); + auto res_d0 = res; res_d0.DepthOrArraySize = 0; + check("zero depth refused", !x2w_startup::supports_volume_memory_srv(res_d0, v_exact)); + auto res_m0 = res; res_m0.MipLevels = 0; + check("zero mips refused", !x2w_startup::supports_volume_memory_srv(res_m0, v_exact)); + + // Deny SRV flag. + auto res_deny = res; + res_deny.Flags = D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + check("deny shader resource flag refused", !x2w_startup::supports_volume_memory_srv(res_deny, v_exact)); + + // Multisample. + auto res_ms = res; + res_ms.SampleDesc.Count = 2; + check("multisampled volume refused", !x2w_startup::supports_volume_memory_srv(res_ms, v_exact)); + + // Byte count calculations. + check("single-mip byte count", x2w_startup::volume_texture_bytes(tex3d(4, 4, 4, 1, DXGI_FORMAT_R8G8B8A8_UNORM)) == 256); + // 4x4x2 (32 texels) + 2x2x1 (4 texels) = 36 texels * 4 = 144 bytes. + check("multi-mip byte count", x2w_startup::volume_texture_bytes(tex3d(4, 4, 2, 2, DXGI_FORMAT_R8G8B8A8_UNORM)) == 144); + // 32x32x32 R8_UNORM = 32768 bytes. + check("R8 volume byte count", x2w_startup::volume_texture_bytes(tex3d(32, 32, 32, 1, DXGI_FORMAT_R8_UNORM)) == 32768); + // Non-3D resource. + check("2D resource byte count is 0", x2w_startup::volume_texture_bytes(res_2d) == 0); + + if (failures) { + std::printf("startup_memory_srv_volume_check: %d FAILED\n", failures); + return 1; + } + std::printf("startup_memory_srv_volume_check: all checks passed\n"); + return 0; +} diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index b37754c66..3681ee948 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -335,6 +335,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_VOLUME_SRV", nullptr, 0)) { + extern int draw_volume_address_srvs(ID3D12Device*, void*, void*); + if (const int result = draw_volume_address_srvs(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0)) { extern int draw_d16_srvs(ID3D12Device*, void*, void*); if (const int result = draw_d16_srvs(desktop.Get(), guest, list)) return result; From fe101e033caa1b34608940d35ac3614db51fe9cf Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Wed, 25 Nov 2026 22:17:25 +0800 Subject: [PATCH 015/232] startup: refuse a buffer load with no operands instead of indexing an empty list (#2360) `op_buffer_load_dword` and `tbuffer` read `ops[0]` before `buffer_address()` reaches its own operand-count check, so `buffer_load_dword` or `tbuffer_load_format_xyzw` with no operands at all came back as `translator crash in ...: IndexError` instead of a refusal. That marker is the batch translator's label for a translator defect, not for an instruction it does not lower. Both bodies now refuse an empty operand list; everything longer is still left to the shared check, which sees a modifier first and must keep refusing on it (the `lds` form decodes to three operands). Measured through the real `Stage` entry point: before: buffer_load_dword -> translator crash in buffer_load_dword: IndexError after: buffer_load_dword -> buffer load with 0 operands, expected 4 buffer_load_dword v4 -> buffer load with 1 operands, expected 4 tbuffer_load_format_xyzw -> buffer load with 0 operands, expected 4 `startup_buffer_address_check.py` still passes, including its `buffer modifier lds` case, so the modifier precedence is unchanged. All 57 `tests/startup_gfx2hlsl_*_check.py` exit 0. Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- tests/startup_gfx2hlsl_handler_arity_check.py | 21 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 9 +++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/tests/startup_gfx2hlsl_handler_arity_check.py b/tests/startup_gfx2hlsl_handler_arity_check.py index 07374227a..985842728 100644 --- a/tests/startup_gfx2hlsl_handler_arity_check.py +++ b/tests/startup_gfx2hlsl_handler_arity_check.py @@ -29,6 +29,16 @@ def check(name, operands, expected_output): assert not blocks, (name, invalid, blocks) +def refuse(name, operands, expected): + """Assert a refusal for a form whose accepted shape needs a bound descriptor, so that the + shortest operand list is still a refusal rather than an index error at ops[0].""" + refusals, blocks = translate(name, operands) + assert len(refusals) == 1, (name, operands, refusals) + assert not blocks, (name, operands, blocks) + assert 'translator crash' not in refusals[0][0], (name, operands, refusals) + assert expected in refusals[0][0], (name, operands, refusals) + + def main(): for condition in ('eq', 'lg', 'gt', 'ge', 'lt', 'le'): for kind in ('i32', 'u32'): @@ -40,7 +50,16 @@ def main(): check(f's_{operation}_b{width}', (dst, src), 'exec = ') check(f's_cselect_b{width}', (dst, src, '1'), 'scc ? ') check('s_andn2_saveexec_b64', ('s[12:13]', 's[14:15]'), 'exec = ') - print('startup gfx2hlsl scalar arity: 33 accepted instructions and 99 refusals') + + # MUBUF and MTBUF loads read ops[0] before the shared address check can refuse a short list, so the + # shortest form is asserted here: without the head guard it reaches reg_range('') as an index error. + for suffix, count in (('', 1), ('x2', 2), ('x3', 3), ('x4', 4)): + refuse(f'buffer_load_dword{suffix}', (), 'buffer load with 0 operands, expected 4') + refuse(f'buffer_load_dword{suffix}', ('v4',), 'buffer load with 1 operands, expected 4') + for suffix in ('x', 'xy', 'xyz', 'xyzw'): + refuse(f'tbuffer_load_format_{suffix}', (), 'buffer load with 0 operands, expected 4') + refuse(f'tbuffer_load_format_{suffix}', ('v[8:11]',), 'buffer load with 1 operands, expected 4') + print('startup gfx2hlsl operand arity: 33 accepted instructions, 99 scalar refusals and 16 load refusals') if __name__ == '__main__': diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 838740aa7..6562f6b92 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2927,7 +2927,7 @@ def buffer_address(self, ops, mods): elif m not in ('idxen', 'offen', 'glc', 'slc', 'dlc'): raise Unsupported('buffer modifier %s' % m) if len(ops) != 4: - raise Unsupported('buffer load with %d operands' % len(ops)) + raise Unsupported('buffer load with %d operands, expected 4' % len(ops)) key = self.descriptor(ops[2]) buf = self.pipe.resource(key, 'buf') soffset = None @@ -2970,6 +2970,11 @@ def buffer_address(self, ops, mods): return buf, ' + '.join(terms) def op_buffer_load_dword(self, ops, mods, count=1): + # ops[0] is read before buffer_address() can refuse a short operand list, so an instruction with no + # operands at all would reach it as an index error. Everything longer is left to the shared check, + # which sees a modifier first: the lds form decodes to three operands and must still refuse on it. + if not ops: + raise Unsupported('buffer load with 0 operands, expected 4') dst = reg_range(ops[0]) buf, address = self.buffer_address(ops, mods) self.emit('a = %s;' % address) @@ -3094,6 +3099,8 @@ def op_buffer_store_dwordx4(self, ops, mods): self.op_buffer_store_dword(ops, mods, 4) def tbuffer(self, ops, mods, count): + if not ops: + raise Unsupported('buffer load with 0 operands, expected 4') dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format From 15b8989811957950ad5f1e268e190a2a0407bb72 Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Wed, 25 Nov 2026 22:17:42 +0800 Subject: [PATCH 016/232] startup: refuse an image instruction with fewer than three operands (#2373) `image()` reads vdata, an address and a descriptor, but it indexed them without checking how many operands it was given, so a shorter list reached `ops[1]` or `ops[2]` and came back as `translator crash in : IndexError` instead of a refusal. Seven handlers share that body: `image_sample`, `image_sample_l`, `image_sample_lz`, `image_sample_b`, `image_get_lod`, `image_load` and `image_load_mip`. One guard, before the first index: if len(ops) < 3: raise Unsupported('image instruction with %d operands, expected at least 3' % len(ops)) Measured through the real `Stage` entry point: image_sample v[8:11], v0 before: translator crash in image_sample: IndexError after: image instruction with 2 operands, expected at least 3 image_load v[8:11] before: translator crash in image_load: IndexError after: image instruction with 1 operands, expected at least 3 The three-operand forms are untouched: `image_load v[8:11], v0, s[16:19]` still reports the descriptor operand, so the guard only replaces the crash. `tests/startup_gfx2hlsl_image_arity_check.py` is a new, focused check rather than an addition to `startup_gfx2hlsl_handler_arity_check.py`, which an in-flight PR is editing; it asserts the refusal at one and two operands for all seven forms and that the refusal is not `translator crash`. Registered in `CMakeLists.txt`, listed in the Linux CI check list and in AGENTS.md. Fail-first: removing exactly the guard fails the check with `('image_sample', ('v[8:11]',), [('translator crash in image_sample: IndexError', 'ps')])`, and restoring it returns exit 0. All 58 `tests/startup_gfx2hlsl_*_check.py` exit 0. Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 4 ++ tests/startup_gfx2hlsl_image_arity_check.py | 47 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 5 +++ 5 files changed, 58 insertions(+) create mode 100644 tests/startup_gfx2hlsl_image_arity_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6befc8bc1..c4e012e20 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -278,6 +278,7 @@ jobs: tests/compute_alu_lane_gaps_check.py \ tests/startup_ngg_slice_check.py \ tests/startup_gfx2hlsl_handler_arity_check.py \ + tests/startup_gfx2hlsl_image_arity_check.py \ tests/run_checks_parallel_check.py build-and-test: name: Build and test on Windows diff --git a/AGENTS.md b/AGENTS.md index 980cde149..31913e014 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -232,6 +232,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py ``` `tests/pixel_aot_check.py binary` additionally needs LLVM with gfx1013 support diff --git a/CMakeLists.txt b/CMakeLists.txt index e9cd32bb5..3fd934f40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2834,6 +2834,10 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_watch PROPERTIES TIMEOUT 120) add_test(NAME startup_gfx2hlsl_handler_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_handler_arity_check.py") + # Image instructions with fewer than three operands (#2360 follow-up): the handler refused + # them as an index error before it checked the count. + add_test(NAME startup_gfx2hlsl_image_arity COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_arity_check.py") # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_image_arity_check.py b/tests/startup_gfx2hlsl_image_arity_check.py new file mode 100644 index 000000000..37b64041f --- /dev/null +++ b/tests/startup_gfx2hlsl_image_arity_check.py @@ -0,0 +1,47 @@ +"""Image instructions refuse a short operand list instead of indexing it. + +`image()` reads vdata, an address and a descriptor. A list shorter than three used to reach `ops[1]` or +`ops[2]`, which `Stage.translate` records as `translator crash in : IndexError` -- its marker for a +translator defect rather than for an instruction it does not lower -- and which the single-shader path does +not catch at all. The accepted forms need a bound descriptor, so this check pins the refusal side only; the +accepted shapes are covered by the per-form fixtures. +""" +import sys +from pathlib import Path +from types import SimpleNamespace + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +FORMS = ('image_sample', 'image_sample_l', 'image_sample_lz', 'image_sample_b', + 'image_get_lod', 'image_load', 'image_load_mip') + + +def translate(name, operands): + pipe = SimpleNamespace(root={'params': [], 'flags': 0}) + text = ' '.join((name, ', '.join(operands))).strip() + refusals = [] + stage = G.Stage(pipe, 'ps', b'', refusals=refusals, decoded=[(0, 4, name, text)]) + return refusals, stage.blocks + + +def refuse(name, operands, expected): + refusals, blocks = translate(name, operands) + assert len(refusals) == 1, (name, operands, refusals) + assert not blocks, (name, operands, blocks) + assert 'translator crash' not in refusals[0][0], (name, operands, refusals) + assert expected in refusals[0][0], (name, operands, refusals) + + +def main(): + for form in FORMS: + refuse(form, ('v[8:11]',), 'image instruction with 1 operands, expected at least 3') + refuse(form, ('v[8:11]', 'v0'), 'image instruction with 2 operands, expected at least 3') + + print('startup gfx2hlsl image arity: %d forms refused at 1 and 2 operands' % len(FORMS)) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6562f6b92..bd56b19b0 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3147,6 +3147,11 @@ def op_tbuffer_load_format_xyzw(self, ops, mods): def image(self, ops, mods, how): if getattr(self, 'kind', None) == 'cs' and 'd16' in mods: raise Unsupported('compute d16 image load requires validated SRV formats') + # Every image form reads vdata, an address and a descriptor, so a shorter operand list would reach + # ops[1] or ops[2] as an index error rather than a refusal. Samplers are checked further down, where + # the form decides whether one is required. + if len(ops) < 3: + raise Unsupported('image instruction with %d operands, expected at least 3' % len(ops)) dst = reg_range(ops[0]) dim = [m for m in mods if m.startswith('dim:')][0][4:] dmask = int([m for m in mods if m.startswith('dmask:')][0][6:], 0) From c8d174eb54cefffb10842f4347b83274e100bede Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:18:09 +0200 Subject: [PATCH 017/232] shader: accept argv, --output, and clean error and temp handling in probe_roots with unit suite (#2365) --- CMakeLists.txt | 2 + tests/probe_roots_cli_check.py | 428 +++++++++++++++++++++++++++++++++ tools/probe_roots.py | 91 ++++--- 3 files changed, 490 insertions(+), 31 deletions(-) create mode 100644 tests/probe_roots_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3fd934f40..2a7030f78 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9011,6 +9011,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_profile_audit_check.py") + add_test(NAME shader_metadata_checks COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/probe_roots_cli_check.py") # Keep both shader-model profiles in the retarget probe even though the draw fixture uses SM 6.0. set(retarget_copy_blocks "${CMAKE_CURRENT_BINARY_DIR}/CopyBlocksSM65.cso") add_custom_command(OUTPUT "${retarget_copy_blocks}" diff --git a/tests/probe_roots_cli_check.py b/tests/probe_roots_cli_check.py new file mode 100644 index 000000000..8db0baf78 --- /dev/null +++ b/tests/probe_roots_cli_check.py @@ -0,0 +1,428 @@ +"""Pure-Python unit and CLI hardening suite for tools/probe_roots.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "probe_roots.py" +sys.path.insert(0, str(ROOT / "tools")) + +import probe_roots as pr # noqa: E402 + + +IMAGE_BASE = 0x180000000 +SECTION_RVA = 0x1000 +RAW_OFFSET = 0x200 +RAW_SIZE = 0x1000 + + +def _make_dxbc(rts0_payload: bytes | None = b"RTS0_SYNTHETIC_PAYLOAD_01", *, include_dxil: bool = True) -> bytes: + parts_list = [] + if include_dxil: + program = struct.pack(" tuple[bytes, list[tuple[int, int]]]: + payload = bytearray(RAW_SIZE) + cursor = 0 + locations = [] + for blob in blobs: + if cursor + len(blob) > len(payload): + raise AssertionError("synthetic .rdata overflow") + payload[cursor:cursor + len(blob)] = blob + locations.append((SECTION_RVA + cursor, len(blob))) + cursor = (cursor + len(blob) + 15) & ~15 + + pe_off = 0x80 + buf = bytearray(RAW_OFFSET + RAW_SIZE) + buf[0:2] = b"MZ" + struct.pack_into(" 1 else "" + if flag in ("--container", "--module"): + return subprocess.CompletedProcess(cmd, 0, json.dumps({"status": "0x00000000"}).encode("utf-8"), b"") + if flag == "--disassemble": + return subprocess.CompletedProcess(cmd, 0, SYNTHETIC_IR.encode("utf-8"), b"") + row = { + "legacy_hr": "0x00000000", + "versioned_hr": "0x00000000", + "original_serialize_hr": "0x00000000", + "without_observed_bits_hr": "0x00000000", + } + return subprocess.CompletedProcess(cmd, 0, json.dumps(row).encode("utf-8"), b"") + + +class ProbeRootsUnitTests(unittest.TestCase): + def test_strip_comment_and_call_operand_paren(self): + self.assertEqual(pr.strip_comment('!"a;b" ; comment'), '!"a;b" ') + self.assertEqual(pr.strip_comment("ret void ; @xbox.ignored"), "ret void ") + self.assertEqual(pr.strip_comment('call void @"semi;name"()'), 'call void @"semi;name"()') + + direct = " %x = call i32 @xbox.foo(i32 1, i32 2)" + self.assertEqual(direct[pr.call_operand_paren(direct):], "(i32 1, i32 2)") + + bitcast = " call void bitcast (void (i32)* @xbox.callee to void (i32)*)(i32 %a)" + self.assertEqual(bitcast[pr.call_operand_paren(bitcast):], "(i32 %a)") + self.assertEqual(pr.call_operand_paren("ret void"), -1) + + def test_classify_line_inventory_and_packing_evidence(self): + calls, declarations, refs = {}, set(), {} + from collections import Counter + calls = Counter() + pr.classify_line("declare void @xbox.decl()", calls, declarations, refs) + pr.classify_line(" %x = call i32 @xbox.direct(i32 1)", calls, declarations, refs) + pr.classify_line(" call void @llvm.dbg.value(metadata void ()* @xbox.dbg, metadata !0)", calls, declarations, refs) + self.assertEqual(declarations, {"xbox.decl"}) + self.assertEqual(dict(calls), {"xbox.direct": 1}) + self.assertEqual(refs["xbox.dbg"], {"sites": 0, "debug_sites": 1, "kinds": {"debug-only"}}) + + inv = pr.xbox_intrinsic_inventory(SYNTHETIC_IR) + self.assertEqual(inv["calls"], {"xbox.V_ALIGNBYTE_B32": 1, "xbox.bitcast_callee": 1, "xbox.global_store_dwordx3_with_cache": 2}) + self.assertEqual(inv["declarations"], ["xbox.unused_decl"]) + self.assertEqual(inv["metadata_only"], ["xbox.meta_only"]) + self.assertEqual(inv["references"]["xbox.bitcast_target"]["kinds"], ["alias"]) + self.assertEqual(inv["references"]["xbox.global_target"]["kinds"], ["bitcast"]) + self.assertEqual(inv["references"]["xbox.debug_ref"]["debug_sites"], 1) + self.assertEqual(inv["references"]["xbox.debug_ref"]["sites"], 0) + self.assertEqual(inv["references"]["xbox.stored_ref"]["kinds"], ["store"]) + self.assertEqual(inv["references"]["xbox.operand_ref"]["kinds"], ["call-operand"]) + + pack = pr.packing_evidence(SYNTHETIC_IR) + self.assertEqual(pack["alignbyte_selectors"], {"and_3": 1}) + self.assertEqual(pack["store_addresses"], {"dwordx3:other_or_unknown": 1, "dwordx3:add_12": 1}) + self.assertEqual(pack["adjacent_extrema_store_pairs"], 1) + + def test_measure_on_synthetic_pe_and_dxbc(self): + rts0 = bytearray(28) + struct.pack_into(" str: + out, err = io.StringIO(), io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + with self.assertRaises(SystemExit) as exc: + pr.main(argv) + self.assertEqual(exc.exception.code, expected_code) + err_text = err.getvalue() + self.assertNotIn("Traceback", err_text) + self.assertTrue(err_text.strip(), f"expected stderr for {argv!r}") + if fragment: + self.assertIn(fragment, err_text) + return err_text + + def test_main_argv_output_and_controls_exit_0(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + build, inv_path, probe, controls = self._setup_workspace(root) + out_file = root / "reports" / "desktop-roots.json" + + stdout, stderr = io.StringIO(), io.StringIO() + with mock.patch.object(pr.subprocess, "run", side_effect=_fake_subprocess_run), \ + redirect_stdout(stdout), redirect_stderr(stderr): + rc = pr.main([ + str(build), + "--inventory", str(inv_path), + "--probe", str(probe), + "--controls", str(controls), + "--output", str(out_file), + ]) + self.assertEqual(rc, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertIn(pr.NAMES[0], stdout.getvalue()) + doc = json.loads(out_file.read_text(encoding="utf-8")) + self.assertEqual(doc["schema"], 1) + self.assertIn("compute_root", doc["control_validation"]) + self.assertEqual(doc["images"][pr.NAMES[0]]["fixture_matches"], {"compute_root": 1, "compute_tables": 1}) + + # Default --output resolves to PROJECT / out/calls/desktop-roots.json. + fake_proj = root / "proj" + fake_proj.mkdir() + with mock.patch.object(pr, "PROJECT", fake_proj), \ + mock.patch.object(pr.subprocess, "run", side_effect=_fake_subprocess_run), \ + redirect_stdout(io.StringIO()): + rc_def = pr.main([str(build), "--inventory", str(inv_path), "--probe", str(probe)]) + self.assertEqual(rc_def, 0) + self.assertTrue((fake_proj / "out" / "calls" / "desktop-roots.json").is_file()) + + def test_negative_and_mutation_controls(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + build, inv_path, probe, controls = self._setup_workspace(root) + out_file = root / "out.json" + + # Subprocess missing build -> exit 1 without traceback. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(root / "missing-build"), "--output", str(out_file)], + capture_output=True, text=True, timeout=30, + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + + # Missing probe / missing inventory / wrong path types -> exit 1 without traceback. + self._assert_main_fails([str(build), "--probe", str(root / "missing.exe"), "--inventory", str(inv_path), "--output", str(out_file)], expected_code=1) + self._assert_main_fails([str(build), "--probe", str(probe), "--inventory", str(root / "missing.json"), "--output", str(out_file)], expected_code=1) + self._assert_main_fails([str(probe), "--probe", str(probe), "--inventory", str(inv_path), "--output", str(out_file)], expected_code=1, fragment="not a directory") + self._assert_main_fails([str(build), "--probe", str(build), "--inventory", str(inv_path), "--output", str(out_file)], expected_code=1, fragment="not a file") + + # Output overlapping --build, --probe, --inventory, --controls, or existing dir -> exit 2 without traceback. + existing_dir = root / "existing_dir" + existing_dir.mkdir() + for bad_out in (build, build / "nested.json", probe, inv_path, controls / "r.json", existing_dir, Path("")): + with self.subTest(bad_out=str(bad_out)): + self._assert_main_fails( + [str(build), "--inventory", str(inv_path), "--probe", str(probe), "--controls", str(controls), "--output", str(bad_out)], + expected_code=2, fragment="overlaps inputs or is a directory", + ) + + # Malformed inventory JSON and wrong JSON shape -> exit 1 without traceback. + bad_json = root / "bad.json" + bad_json.write_text("{not json", encoding="utf-8") + self._assert_main_fails([str(build), "--inventory", str(bad_json), "--probe", str(probe), "--output", str(out_file)], expected_code=1) + + list_json = root / "list.json" + list_json.write_text("[]", encoding="utf-8") + self._assert_main_fails([str(build), "--inventory", str(list_json), "--probe", str(probe), "--output", str(out_file)], expected_code=1) + + # Failing desktop positive control -> exit 1 without traceback. + def fake_bad_control(cmd, *, input=None, capture_output=False, check=False, timeout=None): + flag = cmd[1] if len(cmd) > 1 else "" + if flag in ("--container", "--module"): + return subprocess.CompletedProcess(cmd, 0, json.dumps({"status": "0x80004005"}).encode("utf-8"), b"") + return _fake_subprocess_run(cmd, input=input, capture_output=capture_output, check=check, timeout=timeout) + + with mock.patch.object(pr.subprocess, "run", side_effect=fake_bad_control): + self._assert_main_fails( + [str(build), "--inventory", str(inv_path), "--probe", str(probe), "--controls", str(controls), "--output", str(out_file)], + expected_code=1, fragment="Desktop positive control failed", + ) + + # SubprocessError during probe -> exit 1 without traceback. + with mock.patch.object(pr.subprocess, "run", side_effect=subprocess.CalledProcessError(2, ["probe"])): + self._assert_main_fails( + [str(build), "--inventory", str(inv_path), "--probe", str(probe), "--output", str(out_file)], + expected_code=1, + ) + + # Corrupt PE & SHA mismatch & PEFormatError & struct.error & KeyError -> exit 1 without traceback. + bad_pe_build = root / "bad_pe_build" + bad_pe_build.mkdir() + bad_pe_bytes = b"not a PE" + (bad_pe_build / pr.NAMES[0]).write_bytes(bad_pe_bytes) + self._assert_main_fails( + [str(bad_pe_build), "--inventory", str(inv_path), "--probe", str(probe), "--output", str(out_file)], + expected_code=1, fragment="Rebuild the call inventory", + ) + + # Matching SHA on non-PE -> pefile.PEFormatError caught cleanly. + bad_pe_inv = root / "bad_pe_inv.json" + bad_pe_inv.write_text(json.dumps({ + name: ({"sha256": hashlib.sha256(bad_pe_bytes).hexdigest(), "containers": [{"rva": "0x1000", "bytes": 32}]} + if i == 0 else {"sha256": "0" * 64, "containers": []}) + for i, name in enumerate(pr.NAMES) + }), encoding="utf-8") + self._assert_main_fails( + [str(bad_pe_build), "--inventory", str(bad_pe_inv), "--probe", str(probe), "--output", str(out_file)], + expected_code=1, + ) + + # Truncated RTS0 (<24 bytes) -> struct.error caught cleanly. + short_rts0_pe, short_locs = _make_pe_with_dxbc([_make_dxbc(b"1234")]) + short_build = root / "short_rts0_build" + short_build.mkdir() + (short_build / pr.NAMES[0]).write_bytes(short_rts0_pe) + short_inv = root / "short_rts0_inv.json" + short_inv.write_text(json.dumps({ + name: ({"sha256": hashlib.sha256(short_rts0_pe).hexdigest(), + "containers": [{"rva": hex(short_locs[0][0]), "bytes": short_locs[0][1]}]} + if i == 0 else {"sha256": "0" * 64, "containers": []}) + for i, name in enumerate(pr.NAMES) + }), encoding="utf-8") + with mock.patch.object(pr.subprocess, "run", side_effect=_fake_subprocess_run): + self._assert_main_fails( + [str(short_build), "--inventory", str(short_inv), "--probe", str(probe), "--output", str(out_file)], + expected_code=1, + ) + + # Missing RTS0 part & empty inventory dict -> KeyError caught cleanly. + no_rts0_pe, no_rts0_locs = _make_pe_with_dxbc([_make_dxbc(None)]) + no_rts0_build = root / "no_rts0_build" + no_rts0_build.mkdir() + (no_rts0_build / pr.NAMES[0]).write_bytes(no_rts0_pe) + no_rts0_inv = root / "no_rts0_inv.json" + no_rts0_inv.write_text(json.dumps({ + name: ({"sha256": hashlib.sha256(no_rts0_pe).hexdigest(), + "containers": [{"rva": hex(no_rts0_locs[0][0]), "bytes": no_rts0_locs[0][1]}]} + if i == 0 else {"sha256": "0" * 64, "containers": []}) + for i, name in enumerate(pr.NAMES) + }), encoding="utf-8") + self._assert_main_fails( + [str(no_rts0_build), "--inventory", str(no_rts0_inv), "--probe", str(probe), "--output", str(out_file)], + expected_code=1, + ) + empty_dict_inv = root / "empty_dict_inv.json" + empty_dict_inv.write_text("{}", encoding="utf-8") + self._assert_main_fails( + [str(build), "--inventory", str(empty_dict_inv), "--probe", str(probe), "--output", str(out_file)], + expected_code=1, + ) + + # Temp file unlink verified on both json.dump and os.replace failures. + rep_dir = root / "atomic_rep" + rep_dir.mkdir() + dest_json = rep_dir / "desktop-roots.json" + dest_json.write_text("existing", encoding="utf-8") + + with mock.patch.object(pr.subprocess, "run", side_effect=_fake_subprocess_run), \ + mock.patch.object(pr.json, "dump", side_effect=OSError("disk full dump")): + self._assert_main_fails( + [str(build), "--inventory", str(inv_path), "--probe", str(probe), "--output", str(dest_json)], + expected_code=1, fragment="disk full dump", + ) + self.assertEqual(list(rep_dir.iterdir()), [dest_json]) + self.assertEqual(dest_json.read_text(encoding="utf-8"), "existing") + + with mock.patch.object(pr.subprocess, "run", side_effect=_fake_subprocess_run), \ + mock.patch.object(pr.os, "replace", side_effect=PermissionError("locked target")): + self._assert_main_fails( + [str(build), "--inventory", str(inv_path), "--probe", str(probe), "--output", str(dest_json)], + expected_code=1, fragment="locked target", + ) + self.assertEqual(list(rep_dir.iterdir()), [dest_json]) + self.assertEqual(dest_json.read_text(encoding="utf-8"), "existing") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/probe_roots.py b/tools/probe_roots.py index 43868c2eb..aff4de852 100644 --- a/tools/probe_roots.py +++ b/tools/probe_roots.py @@ -4,6 +4,7 @@ from collections import Counter import hashlib import json +import os from pathlib import Path import re import struct @@ -311,44 +312,72 @@ def measure(build, inventory, probe, fixtures): return result -def main(): +def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(description=__doc__) p.add_argument("build", type=Path) p.add_argument("--inventory", type=Path, default=PROJECT / "out/calls/six-apis.json") p.add_argument("--probe", type=Path, default=PROJECT / "out/build/dev/root_probe.exe") p.add_argument("--controls", type=Path, help="Build directory with compute_root.cso and compute_tables.cso") - args = p.parse_args() - dest = PROJECT / "out/calls/desktop-roots.json" - build = args.build.resolve(strict=True) - if dest.resolve().is_relative_to(build) or dest.resolve() == args.inventory.resolve(): - p.error("Report destination overlaps inputs") - fixtures = {} - control_checks = {} - probe = args.probe.resolve(strict=True) - if args.controls: - for name in ("compute_root", "compute_tables"): - blob = (args.controls / (name + ".cso")).read_bytes() - sections = parts(blob) - fixtures[name] = sections[b"RTS0"] - checks = validate_shader(probe, blob, sections[b"DXIL"]) - if any(checks[k]["status"] != "0x00000000" for k in ("container", "module")): - raise ValueError(f"Desktop positive control failed for {name}") - control_checks[name] = checks - inventory_data = args.inventory.read_bytes() - result = measure(build, json.loads(inventory_data), probe, fixtures) - document = dict(schema=1, windows_build=sys.getwindowsversion().build, - probe_sha256=hashlib.sha256(probe.read_bytes()).hexdigest(), - inventory_sha256=hashlib.sha256(inventory_data).hexdigest(), - control_root_sha256={key: hashlib.sha256(b).hexdigest() for key, b in fixtures.items()}, - control_validation=control_checks, images=result) - dest.parent.mkdir(parents=True, exist_ok=True) - with NamedTemporaryFile(mode="w", dir=dest.parent, delete=False, encoding="utf-8") as f: - json.dump(document, f, indent=2) - f.write("\n") - Path(f.name).replace(dest) + p.add_argument("--output", type=Path, default=PROJECT / "out/calls/desktop-roots.json") + args = p.parse_args(argv) + try: + build = args.build.resolve(strict=True) + if not build.is_dir(): + raise ValueError(f"Build path is not a directory: {build}") + probe = args.probe.resolve(strict=True) + if not probe.is_file(): + raise ValueError(f"Probe path is not a file: {probe}") + controls = args.controls.resolve() if args.controls is not None else None + inventory_path = args.inventory.resolve() + dest = args.output.resolve() + except (OSError, ValueError) as exc: + p.exit(1, f"probe_roots: {exc}\n") + + if (dest.is_relative_to(build) or dest == probe or dest == inventory_path or + (controls is not None and dest.is_relative_to(controls)) or + dest.is_dir()): + p.error("Report destination overlaps inputs or is a directory") + + try: + fixtures = {} + control_checks = {} + if controls is not None: + for name in ("compute_root", "compute_tables"): + blob = (controls / (name + ".cso")).read_bytes() + sections = parts(blob) + fixtures[name] = sections[b"RTS0"] + checks = validate_shader(probe, blob, sections[b"DXIL"]) + if any(checks[k]["status"] != "0x00000000" for k in ("container", "module")): + raise ValueError(f"Desktop positive control failed for {name}") + control_checks[name] = checks + inventory_data = inventory_path.read_bytes() + result = measure(build, json.loads(inventory_data), probe, fixtures) + windows_build = sys.getwindowsversion().build if hasattr(sys, "getwindowsversion") else None + document = dict(schema=1, windows_build=windows_build, + probe_sha256=hashlib.sha256(probe.read_bytes()).hexdigest(), + inventory_sha256=hashlib.sha256(inventory_data).hexdigest(), + control_root_sha256={key: hashlib.sha256(b).hexdigest() for key, b in fixtures.items()}, + control_validation=control_checks, images=result) + tmp_path = None + try: + dest.parent.mkdir(parents=True, exist_ok=True) + with NamedTemporaryFile(mode="w", suffix=".tmp", dir=dest.parent, delete=False, encoding="utf-8") as f: + tmp_path = Path(f.name) + json.dump(document, f, indent=2) + f.write("\n") + os.replace(tmp_path, dest) + tmp_path = None + finally: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) + except (OSError, json.JSONDecodeError, ValueError, KeyError, TypeError, + pefile.PEFormatError, struct.error, subprocess.SubprocessError) as exc: + p.exit(1, f"probe_roots: {exc}\n") + for name, report in result.items(): print(name, report["containers"], report["results"]) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 4ecb13f9b71bc3809b1316df1ffeb02009537187 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:18:45 +0200 Subject: [PATCH 018/232] shader: harden main(argv) and error/output handling in spirv_address_window with unit suite (#2374) --- CMakeLists.txt | 2 + tests/spirv_address_window_check.py | 688 ++++++++++++++++++++++++++++ tools/spirv_address_window.py | 58 ++- 3 files changed, 727 insertions(+), 21 deletions(-) create mode 100644 tests/spirv_address_window_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a7030f78..acde0a7e1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3610,6 +3610,8 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() add_test(NAME spirv_window_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_sampler_split_check.py") + add_test(NAME spirv_address_window_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_check.py") # Outside a Git checkout, such as a source archive, the tracked-path check cannot run. set_tests_properties(docs_links PROPERTIES SKIP_RETURN_CODE 77) diff --git a/tests/spirv_address_window_check.py b/tests/spirv_address_window_check.py new file mode 100644 index 000000000..1078833b3 --- /dev/null +++ b/tests/spirv_address_window_check.py @@ -0,0 +1,688 @@ +#!/usr/bin/env python3 +"""Unit and CLI suite for tools/spirv_address_window.py without external SPIR-V binaries.""" +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "tools" / "spirv_address_window.py" +FIXTURES = ROOT / "tests" / "spirv_window" +sys.path.insert(0, str(ROOT / "tools")) +import spirv_address_window as saw + +SUBTRACT = (FIXTURES / "subtract.spvasm").read_text(encoding="utf-8") +SIGNED = (FIXTURES / "address_signed.spvasm").read_text(encoding="utf-8") +FLOAT = (FIXTURES / "address_float.spvasm").read_text(encoding="utf-8") +VEC4 = (FIXTURES / "address_vec4.spvasm").read_text(encoding="utf-8") +QWORD = (FIXTURES / "qword.spvasm").read_text(encoding="utf-8") + + +def _sub(text: str, old: str, new: str) -> str: + assert text.count(old) == 1, old + return text.replace(old, new) + + +def _expect_value_error(fn, *args, fragment: str): + try: + fn(*args) + except ValueError as error: + assert fragment in str(error), f"expected {fragment!r} in {error!r}" + return str(error) + raise AssertionError(f"{fn.__name__} did not raise ValueError containing {fragment!r}") + + +def _expect_exit(argv, expected_code=1, fragment=""): + stderr = io.StringIO() + stdout = io.StringIO() + try: + with redirect_stdout(stdout), redirect_stderr(stderr): + saw.main(argv) + except SystemExit as exc: + assert exc.code == expected_code, (exc.code, stderr.getvalue()) + else: + raise AssertionError(f"main({argv!r}) did not raise SystemExit") + err = stderr.getvalue() + assert err.strip(), f"expected stderr message for {argv!r}" + assert "Traceback" not in err, err + if fragment: + assert fragment in err, f"expected {fragment!r} in {err!r}" + return err + + +def check_word_pointer(): + """Verify word_pointer() for direct, indexed, deferred, wide, and vec4 modes.""" + lines, valid = saw.word_pointer("%p", "%addr", None) + assert valid == "%x2w_address_p_valid", valid + assert lines == [ + "%x2w_address_p_low = OpBitwiseAnd %ulong %addr %x2w_mask", + "%x2w_address_p_aligned = OpIEqual %bool %x2w_address_p_low %x2w_zero64", + "%x2w_address_p_range = OpULessThan %bool %addr %x2w_end", + "%x2w_address_p_valid = OpLogicalAnd %bool %x2w_address_p_aligned %x2w_address_p_range", + "%x2w_address_p_word64 = OpShiftRightLogical %ulong %addr %x2w_shift", + "%x2w_address_p_word = OpUConvert %uint %x2w_address_p_word64", + "%x2w_address_p_selected = OpSelect %uint %x2w_address_p_valid %x2w_address_p_word %x2w_invalid", + "%p = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 %x2w_address_p_selected", + ], lines + + idx_lines, idx_valid = saw.word_pointer("%q", "%base", "%idx") + assert idx_valid == "%x2w_address_q_checked", idx_valid + assert idx_lines[:3] == [ + "%x2w_address_q_index = OpUConvert %ulong %idx", + "%x2w_address_q_delta = OpShiftLeftLogical %ulong %x2w_address_q_index %x2w_shift", + "%x2w_address_q_address = OpIAdd %ulong %base %x2w_address_q_delta", + ], idx_lines + assert "%x2w_address_q_nowrap = OpUGreaterThanEqual %bool %x2w_address_q_address %base" in idx_lines + assert "%x2w_address_q_checked = OpLogicalAnd %bool %x2w_address_q_valid %x2w_address_q_nowrap" in idx_lines + assert "%q = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 %x2w_address_q_selected" in idx_lines + + defer_lines, defer_valid = saw.word_pointer("%d", "%base", None, defer=True) + assert defer_valid == "%x2w_address_d_valid", defer_valid + assert "%x2w_address_d_range = OpULessThan %bool %base %x2w_end" in defer_lines + assert "%x2w_address_d_word = OpUConvert %uint %x2w_address_d_word64" in defer_lines + assert not any("_selected" in line or "OpAccessChain" in line for line in defer_lines), defer_lines + + wide_lines, wide_valid = saw.word_pointer("%w", "%base", "%idx", wide=True) + assert wide_valid == "%x2w_address_w_checked", wide_valid + assert "%x2w_address_w_delta = OpShiftLeftLogical %ulong %x2w_address_w_index %x2w_shift_wide" in wide_lines + assert "%x2w_address_w_low = OpBitwiseAnd %ulong %x2w_address_w_address %x2w_mask_wide" in wide_lines + assert "%x2w_address_w_range = OpULessThan %bool %x2w_address_w_address %x2w_end_wide" in wide_lines + assert not any("_selected" in line or "OpAccessChain" in line for line in wide_lines), wide_lines + + vec4_lines, vec4_valid = saw.word_pointer("%v", "%base", None, wide="vec4") + assert vec4_valid == "%x2w_address_v_valid", vec4_valid + assert "%x2w_address_v_low = OpBitwiseAnd %ulong %base %x2w_mask_vec4" in vec4_lines + assert "%x2w_address_v_range = OpULessThan %bool %base %x2w_end_vec4" in vec4_lines + assert not any("_selected" in line or "OpAccessChain" in line for line in vec4_lines), vec4_lines + + +def check_signed_access(): + """Verify signed_access() for loads, stores, SMin/SMax CAS loops, word atomics, and rejections.""" + valid_of = {"%p": "%v_p"} + words = {"%p": "%w_p"} + failures = {"%c72": "%x2w_failure_66", "%c0": "%c0"} + + load_lines, next_lbl = saw.signed_access( + "%r = OpLoad %int %p Aligned 4".split(), {"%p"}, valid_of, words, "%entry", "%s", failures + ) + assert next_lbl == "%s_merge", next_lbl + assert load_lines == [ + "OpSelectionMerge %s_merge None", + "OpBranchConditional %v_p %s_issue %s_merge", + "%s_issue = OpLabel", + "%s_ptr = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 %w_p", + "%s_loaded = OpLoad %uint %s_ptr Aligned 4", + "OpBranch %s_merge", + "%s_merge = OpLabel", + "%s_old = OpPhi %uint %s_loaded %s_issue %c0 %entry", + "%r = OpBitcast %int %s_old", + ], load_lines + + plain_load, _ = saw.signed_access( + "%r = OpLoad %int %p".split(), {"%p"}, valid_of, words, "%entry", "%sp", failures + ) + assert "%sp_loaded = OpLoad %uint %sp_ptr" in plain_load + + store_lines, next_lbl = saw.signed_access( + "OpStore %p %val Aligned 4".split(), {"%p"}, valid_of, words, "%entry", "%st", failures + ) + assert next_lbl == "%st_merge" + assert "%st_value = OpBitcast %uint %val" in store_lines + assert "OpStore %st_ptr %st_value Aligned 4" in store_lines + + smin_lines, next_lbl = saw.signed_access( + "%m = OpAtomicSMin %int %p %c1 %c72 %val".split(), {"%p"}, valid_of, words, "%entry", "%mn", failures + ) + assert next_lbl == "%mn_merge" + assert "OpLoopMerge %mn_exit %mn_cont None" in smin_lines + assert "%mn_pick = OpSLessThan %bool %mn_cur_int %val" in smin_lines + assert "%mn_seen = OpAtomicCompareExchange %uint %mn_ptr %c1 %c72 %x2w_failure_66 %mn_want %mn_cur" in smin_lines + + smax_lines, _ = saw.signed_access( + "%m = OpAtomicSMax %int %p %c1 %c0 %val".split(), {"%p"}, valid_of, words, "%entry", "%mx", failures + ) + assert "%mx_pick = OpSGreaterThan %bool %mx_cur_int %val" in smax_lines + assert "%mx_seen = OpAtomicCompareExchange %uint %mx_ptr %c1 %c0 %c0 %mx_want %mx_cur" in smax_lines + + for op in ("OpAtomicIAdd", "OpAtomicExchange", "OpAtomicAnd", "OpAtomicOr", "OpAtomicXor"): + wa_lines, wa_lbl = saw.signed_access( + f"%o = {op} %int %p %c1 %c0 %val".split(), {"%p"}, valid_of, words, "%entry", "%wa", failures + ) + assert wa_lbl == "%wa_merge" + assert "%wa_value = OpBitcast %uint %val" in wa_lines + assert f"%wa_old = {op} %uint %wa_ptr %c1 %c0 %wa_value" in wa_lines + assert "%o = OpBitcast %int %wa_old_phi" not in wa_lines + assert "%o = OpBitcast %int %wa_result" in wa_lines + + cmpxchg_lines, _ = saw.signed_access( + "%o = OpAtomicCompareExchange %int %p %c1 %c72 %c66 %val %cmp".split(), + {"%p"}, valid_of, words, "%entry", "%cx", failures, + ) + assert "%cx_value = OpBitcast %uint %val" in cmpxchg_lines + assert "%cx_cmp = OpBitcast %uint %cmp" in cmpxchg_lines + assert "%cx_old = OpAtomicCompareExchange %uint %cx_ptr %c1 %c72 %c66 %cx_value %cx_cmp" in cmpxchg_lines + + for bad_line, ptrs in ( + ("%r = OpLoad %int %p Volatile", {"%p"}), + ("%r = OpLoad %uint %p Aligned 4", {"%p"}), + ("OpStore %p %val Aligned 8", {"%p"}), + ("%r = OpAtomicISub %int %p %c1 %c0 %val", {"%p"}), + ("%r = OpAtomicSMin %int %p %c1 %c0", {"%p"}), + ("%r = OpLoad %int %p Aligned 4", {"%p", "%q"}), + ("%r = OpLoad %int %other Aligned 4", {"%p"}), + ): + _expect_value_error( + saw.signed_access, bad_line.split(), ptrs, valid_of, words, "%entry", "%bad", failures, + fragment="unhandled physical word pointer use", + ) + + +def check_float_access(): + """Verify float_access() for loads, stores, bitcasts, and rejections.""" + valid_of = {"%pf": "%v_pf"} + words = {"%pf": "%w_pf"} + + load_lines, next_lbl = saw.float_access( + "%f = OpLoad %float %pf Aligned 4".split(), {"%pf"}, valid_of, words, "%entry", "%fl" + ) + assert next_lbl == "%fl_merge" + assert load_lines == [ + "OpSelectionMerge %fl_merge None", + "OpBranchConditional %v_pf %fl_issue %fl_merge", + "%fl_issue = OpLabel", + "%fl_ptr = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 %w_pf", + "%fl_loaded = OpLoad %uint %fl_ptr Aligned 4", + "OpBranch %fl_merge", + "%fl_merge = OpLabel", + "%fl_old = OpPhi %uint %fl_loaded %fl_issue %c0 %entry", + "%f = OpBitcast %float %fl_old", + ], load_lines + + plain_load, _ = saw.float_access( + "%f = OpLoad %float %pf".split(), {"%pf"}, valid_of, words, "%entry", "%fp" + ) + assert "%fp_loaded = OpLoad %uint %fp_ptr" in plain_load + + store_lines, next_lbl = saw.float_access( + "OpStore %pf %val Aligned 4".split(), {"%pf"}, valid_of, words, "%entry", "%fs" + ) + assert next_lbl == "%fs_merge" + assert "%fs_value = OpBitcast %uint %val" in store_lines + assert "OpStore %fs_ptr %fs_value Aligned 4" in store_lines + + for bad_line, ptrs in ( + ("%f = OpLoad %float %pf Volatile", {"%pf"}), + ("%f = OpLoad %int %pf Aligned 4", {"%pf"}), + ("OpStore %pf %val Aligned 8", {"%pf"}), + ("OpStore %pf %pf Aligned 4", {"%pf"}), + ("%f = OpAtomicIAdd %float %pf %c1 %c0 %val", {"%pf"}), + ("%f = OpLoad %float %pf Aligned 4", {"%pf", "%qf"}), + ): + _expect_value_error( + saw.float_access, bad_line.split(), ptrs, valid_of, words, "%entry", "%badf", + fragment="unhandled physical word pointer use", + ) + + +def check_vec4_access(): + """Verify vec4_access() for 16-byte aligned loads/stores and rejections.""" + valid_of = {"%pv": "%v_pv"} + words = {"%pv": "%w_pv"} + + load_lines, next_lbl = saw.vec4_access( + "%v = OpLoad %v4float %pv Aligned 16".split(), {"%pv"}, valid_of, words, "%entry", "%vl" + ) + assert next_lbl == "%vl_merge" + assert "%vl_word_1 = OpIAdd %uint %w_pv %x2w_one" in load_lines + assert "%vl_word_2 = OpIAdd %uint %w_pv %x2w_two" in load_lines + assert "%vl_word_3 = OpIAdd %uint %w_pv %x2w_three" in load_lines + assert "%vl_ptr_0 = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 %w_pv" in load_lines + assert "%vl_ptr_3 = OpAccessChain %_ptr_PSB_uint %x2w_heap %c0 %vl_word_3" in load_lines + assert "%vl_lane_2 = OpBitcast %float %vl_bits_2" in load_lines + assert "%vl_value = OpCompositeConstruct %v4float %vl_lane_0 %vl_lane_1 %vl_lane_2 %vl_lane_3" in load_lines + assert "%v = OpPhi %v4float %vl_value %vl_issue %x2w_vec4_zero %entry" in load_lines + + store_lines, next_lbl = saw.vec4_access( + "OpStore %pv %vec Aligned 16".split(), {"%pv"}, valid_of, words, "%entry", "%vs" + ) + assert next_lbl == "%vs_merge" + for lane in range(4): + assert f"%vs_lane_{lane} = OpCompositeExtract %float %vec {lane}" in store_lines + assert f"%vs_bits_{lane} = OpBitcast %uint %vs_lane_{lane}" in store_lines + assert f"OpStore %vs_ptr_{lane} %vs_bits_{lane} Aligned 4" in store_lines + + for bad_line, ptrs in ( + ("%v = OpLoad %v4float %pv", {"%pv"}), + ("%v = OpLoad %v4float %pv Aligned 4", {"%pv"}), + ("OpStore %pv %vec", {"%pv"}), + ("OpStore %pv %vec Aligned 4", {"%pv"}), + ("OpStore %pv %pv Aligned 16", {"%pv"}), + ("%v = OpLoad %float %pv Aligned 16", {"%pv"}), + ("%v = OpLoad %v4float %pv Aligned 16", {"%pv", "%qv"}), + ): + _expect_value_error( + saw.vec4_access, bad_line.split(), ptrs, valid_of, words, "%entry", "%badv", + fragment="unhandled physical word pointer use", + ) + + +def check_merge_pointer_types(): + """Verify merge_pointer_types() deduplicates identical logical pointers and propagates aliases.""" + lines = [ + "%_ptr_PSB_uint = OpTypePointer StorageBuffer %uint", + "%_ptr_PC_uint = OpTypePointer StorageBuffer %uint", + "%_ptr_PSB_ptr1 = OpTypePointer Function %_ptr_PSB_uint", + "%_ptr_PSB_ptr2 = OpTypePointer Function %_ptr_PC_uint", + "%_ptr_Uniform_uint = OpTypePointer Uniform %uint", + "%x = OpAccessChain %_ptr_PC_uint %user_data %c0 %c0", + "%y = OpVariable %_ptr_PSB_ptr2 Function", + ] + merged = saw.merge_pointer_types(lines) + out = merged.splitlines() + assert out == [ + "%_ptr_PSB_uint = OpTypePointer StorageBuffer %uint", + "%_ptr_PSB_ptr1 = OpTypePointer Function %_ptr_PSB_uint", + "%_ptr_Uniform_uint = OpTypePointer Uniform %uint", + "%x = OpAccessChain %_ptr_PSB_uint %user_data %c0 %c0", + "%y = OpVariable %_ptr_PSB_ptr1 Function", + ], out + + +def check_lower_positive_and_composed(): + """Verify lower() across unsigned, signed, float, vec4, qword, OpPhi rewriting, CAS semantics, and composition.""" + # 1. Unsigned direct + indexed + all 8 word atomics. + direct = _sub( + SUBTRACT, + "%v1 = OpConvertUToPtr %_ptr_PSB_arr %a1\n%p1 = OpAccessChain %_ptr_PSB_uint %v1 %c0", + "%p1 = OpConvertUToPtr %_ptr_PSB_uint %a1", + ) + atomic_ops = ( + "%old_add = OpAtomicIAdd %uint %p1 %c1 %atomic_rmw %d", + "%old_exch = OpAtomicExchange %uint %p2 %c1 %atomic_rmw %old_add", + "%old_umin = OpAtomicUMin %uint %p2 %c1 %atomic_rmw %old_exch", + "%old_umax = OpAtomicUMax %uint %p2 %c1 %atomic_rmw %old_umin", + "%old_and = OpAtomicAnd %uint %p2 %c1 %atomic_rmw %old_umax", + "%old_or = OpAtomicOr %uint %p2 %c1 %atomic_rmw %old_and", + "%old_xor = OpAtomicXor %uint %p2 %c1 %atomic_rmw %old_or", + "%old_cmp = OpAtomicCompareExchange %uint %p2 %c1 %atomic_rmw %atomic_fail %d %old_xor", + ) + atomics_src = _sub( + _sub(direct, "%main = OpFunction", "%atomic_rmw = OpConstant %uint 72\n%atomic_fail = OpConstant %uint 66\n%main = OpFunction"), + "OpStore %p2 %d Aligned 4", + "\n".join(atomic_ops) + "\nOpStore %p0 %old_cmp Aligned 4", + ) + atomics_out = saw.lower(atomics_src) + assert "PhysicalStorageBuffer" not in atomics_out and "OpConvertUToPtr" not in atomics_out + assert "OpMemoryModel Logical GLSL450" in atomics_out + assert atomics_out.count("%_ptr_PSB_uint = OpTypePointer StorageBuffer %uint") == 1 + assert "%_ptr_PC_uint =" not in atomics_out + assert atomics_out.count(" = OpAtomic") == 8 + + # 2. Signed + acquire-release and release failure-semantics downgrade in SMin/SMax CAS loops. + signed_acq_rel = _sub( + _sub(SIGNED, "%c6 = OpConstant %uint 6", "%c6 = OpConstant %uint 6\n%c72 = OpConstant %uint 72\n%c68 = OpConstant %uint 68\n%c66 = OpConstant %uint 66"), + "%old_min = OpAtomicSMin %int %min_target %c1 %c0 %operand", + "%old_min = OpAtomicSMin %int %min_target %c1 %c68 %operand", + ) + signed_acq_rel = _sub( + signed_acq_rel, + "%old_max = OpAtomicSMax %int %max_target %c1 %c0 %operand", + "%old_max = OpAtomicSMax %int %max_target %c1 %c72 %operand", + ) + # Also exercise direct %_ptr_PSB_int OpConvertUToPtr and an acquire-only SMin (no downgrade needed). + signed_acq_rel = _sub( + signed_acq_rel, + "%old_add = OpAtomicIAdd %int %chain_target %c1 %c0 %operand", + "%acq_min = OpAtomicSMin %int %output_first %c1 %c66 %operand\n%old_add = OpAtomicIAdd %int %chain_target %c1 %c0 %acq_min", + ) + signed_out = saw.lower(signed_acq_rel) + signed_lines = signed_out.splitlines() + assert "%x2w_failure_64 = OpConstant %uint 64" in signed_lines + assert "%x2w_failure_66 = OpConstant %uint 66" in signed_lines + assert not any(line.startswith("%x2w_failure_66 = ") and line.count("OpConstant") > 1 for line in signed_lines) + assert any( + "OpAtomicCompareExchange %uint %x2w_signed_result_old_min_ptr %c1 %c68 %x2w_failure_64 " in line + for line in signed_lines + ) + assert any( + "OpAtomicCompareExchange %uint %x2w_signed_result_old_max_ptr %c1 %c72 %x2w_failure_66 " in line + for line in signed_lines + ) + assert any( + "OpAtomicCompareExchange %uint %x2w_signed_result_acq_min_ptr %c1 %c66 %c66 " in line + for line in signed_lines + ) + + # 3. Float + vec4 + qword lowering. + float_out = saw.lower(FLOAT) + assert "%x2w_float_result_first_old = OpPhi %uint" in float_out + assert "%first = OpBitcast %float %x2w_float_result_first_old" in float_out + assert "PhysicalStorageBuffer" not in float_out + + vec4_out = saw.lower(VEC4) + assert "%x2w_end_vec4 = OpConstant %ulong 4294967280" in vec4_out + assert "%x2w_vec4_zero = OpConstantNull %v4float" in vec4_out + assert "%first = OpPhi %v4float %x2w_vec4_result_first_value %x2w_vec4_result_first_issue %x2w_vec4_zero %entry" in vec4_out + + qword_out = saw.lower(QWORD) + assert "%x2w_end_wide = OpConstant %ulong 4294967288" in qword_out + assert "%value = OpPhi %ulong %x2w_load_value_value %x2w_load_value_issue %x2w_zero64 %entry" in qword_out + + # 4. OpPhi predecessor rewriting across guarded splits (atomic, float, qword). + phi_src = _sub( + _sub(direct, "%main = OpFunction", "%atomic_rmw = OpConstant %uint 72\n%main = OpFunction"), + "OpStore %p2 %d Aligned 4", + "%old_add = OpAtomicIAdd %uint %p1 %c1 %atomic_rmw %d\n" + "OpBranch %next\n" + "%next = OpLabel\n" + "%carried = OpPhi %uint %old_add %entry\n" + "OpStore %p2 %carried Aligned 4", + ) + phi_out = saw.lower(phi_src).splitlines() + assert "%carried = OpPhi %uint %old_add %x2w_atomic_old_add_merge" in phi_out + + phi_qword = _sub( + QWORD, + "OpReturn\nOpFunctionEnd", + "OpBranch %exit\n%exit = OpLabel\n%copied = OpPhi %ulong %result %entry\nOpStore %target %copied Aligned 8\nOpReturn\nOpFunctionEnd", + ) + phi_qword_out = saw.lower(phi_qword).splitlines() + assert "%copied = OpPhi %ulong %result %x2w_store_2_merge" in phi_qword_out + + # 5. Composed ballot extract + ballot find-lsb + sampler-view splitting + address window. + composed = ( + SUBTRACT + .replace("OpCapability Shader\n", "OpCapability Shader\nOpCapability GroupNonUniformBallot\n", 1) + .replace('OpEntryPoint GLCompute %main "main" %user_data', + 'OpEntryPoint GLCompute %main "main" %user_data %tex %smp_tbl', 1) + .replace("OpDecorate %rt_uint ArrayStride 4\n", + "OpDecorate %tex DescriptorSet 0\nOpDecorate %tex Binding 0\n" + "OpDecorate %smp_tbl DescriptorSet 0\nOpDecorate %smp_tbl Binding 1\n" + "OpDecorate %rt_uint ArrayStride 4\n", 1) + .replace("%void = OpTypeVoid\n", + "%void = OpTypeVoid\n%float = OpTypeFloat 32\n%v2f = OpTypeVector %float 2\n" + "%v4f = OpTypeVector %float 4\n%v4u = OpTypeVector %uint 4\n" + "%img_t = OpTypeImage %float 2D 0 0 0 1 Unknown\n" + "%si_t = OpTypeSampledImage %img_t\n%smp_t = OpTypeSampler\n" + "%rt_smp = OpTypeRuntimeArray %smp_t\n" + "%ptr_img = OpTypePointer UniformConstant %img_t\n" + "%ptr_rt_smp = OpTypePointer UniformConstant %rt_smp\n" + "%ptr_smp = OpTypePointer UniformConstant %smp_t\n" + "%tex = OpVariable %ptr_img UniformConstant\n" + "%smp_tbl = OpVariable %ptr_rt_smp UniformConstant\n", 1) + .replace("%c4 = OpConstant %uint 4\n", + "%c4 = OpConstant %uint 4\n%f0 = OpConstant %float 0\n%f05 = OpConstant %float 0.5\n" + "%uv = OpConstantComposite %v2f %f05 %f05\n" + "%bmask = OpConstantComposite %v4u %c1 %c2 %c3 %c4\n", 1) + .replace("OpStore %p2 %d Aligned 4", + "%sp = OpAccessChain %ptr_smp %smp_tbl %c0\n" + "%sv = OpLoad %smp_t %sp\n" + "%im = OpLoad %img_t %tex\n" + "%si = OpSampledImage %si_t %im %sv\n" + "%ord = OpImageSampleExplicitLod %v4f %si %uv Lod %f0\n" + "%dref = OpImageSampleDrefExplicitLod %float %si %uv %f05 Lod %f0\n" + "%bbit = OpGroupNonUniformBallotBitExtract %bool %c3 %bmask %c0\n" + "%blsb = OpGroupNonUniformBallotFindLSB %uint %c3 %bmask\n" + "%bsel = OpSelect %uint %bbit %blsb %c0\n" + "%df = OpBitcast %uint %dref\n" + "%sum = OpIAdd %uint %bsel %df\n" + "OpStore %p2 %sum Aligned 4", 1) + ) + composed_out = saw.lower(composed) + assert "OpGroupNonUniformBallotBitExtract" not in composed_out + assert "OpGroupNonUniformBallotFindLSB" not in composed_out + assert "%x2w_ballot_bbit_" in composed_out + assert "%x2w_ballot_blsb_" in composed_out + assert "%bridge_cmp = OpVariable %ptr_rt_smp UniformConstant" in composed_out + assert "OpDecorate %bridge_cmp DescriptorSet 3" in composed_out + assert "OpDecorate %x2w_heap DescriptorSet 2" in composed_out + assert "OpDecorate %user_data DescriptorSet 1" in composed_out + assert "OpEntryPoint GLCompute %main \"main\" %user_data %tex %smp_tbl %bridge_cmp %x2w_heap" in composed_out + + +def check_lower_rejections(): + """Verify every rejection path in lower().""" + direct = _sub( + SUBTRACT, + "%v1 = OpConvertUToPtr %_ptr_PSB_arr %a1\n%p1 = OpAccessChain %_ptr_PSB_uint %v1 %c0", + "%p1 = OpConvertUToPtr %_ptr_PSB_uint %a1", + ) + cases = [ + (_sub(SUBTRACT, "OpMemoryModel PhysicalStorageBuffer64 GLSL450", "OpMemoryModel Logical GLSL450"), + "named user-data block"), + (_sub(SUBTRACT, "%user_data = OpVariable %_ptr_PC_UserData PushConstant", + "%other_ud = OpVariable %_ptr_PC_UserData PushConstant"), + "named user-data block"), + (SUBTRACT.replace("%d ", "%x2w_d "), "unused identifier prefix x2w_"), + (_sub(SUBTRACT, "OpDecorate %UserData Block", + "OpDecorate %user_data DescriptorSet 1\nOpDecorate %UserData Block"), + "descriptor sets 1 and 2"), + (_sub(SUBTRACT, "OpDecorate %UserData Block", + "OpDecorate %user_data DescriptorSet 2\nOpDecorate %UserData Block"), + "descriptor sets 1 and 2"), + (_sub(SUBTRACT, 'OpEntryPoint GLCompute %main "main" %user_data', ""), "expected one shader entry point"), + (_sub(SUBTRACT, 'OpEntryPoint GLCompute %main "main" %user_data', + 'OpEntryPoint GLCompute %main "main" %user_data\nOpEntryPoint GLCompute %main "other" %user_data'), + "expected one shader entry point"), + (_sub(SUBTRACT, "OpDecorate %rt_uint ArrayStride 4", "OpDecorate %rt_uint ArrayStride 8"), + "unsupported physical pointer or scalar layout"), + (_sub(QWORD, "%_ptr_PSB_ulong = OpTypePointer PhysicalStorageBuffer %ulong", ""), + "unsupported physical pointer or scalar layout"), + (_sub(QWORD, "OpDecorate %rt_ulong ArrayStride 8", "OpDecorate %rt_ulong ArrayStride 4"), + "unsupported physical pointer or scalar layout"), + (_sub(SIGNED, "%_ptr_PSB_int = OpTypePointer PhysicalStorageBuffer %int", ""), + "unsupported physical pointer or scalar layout"), + (_sub(FLOAT, "%_ptr_PSB_float = OpTypePointer PhysicalStorageBuffer %float", ""), + "unsupported physical pointer or scalar layout"), + (_sub(VEC4, "%_ptr_PSB_v4float = OpTypePointer PhysicalStorageBuffer %v4float", ""), + "unsupported physical pointer or scalar layout"), + (_sub(SUBTRACT, "%v0 = OpConvertUToPtr %_ptr_PSB_arr %a0\n", ""), "unknown physical array pointer"), + (_sub(SIGNED, "%array = OpConvertUToPtr %_ptr_PSB_arri %base\n", ""), "unknown physical array pointer"), + (_sub(FLOAT, "%array = OpConvertUToPtr %_ptr_PSB_arrf %base\n", ""), "unknown physical array pointer"), + (_sub(VEC4, "%array = OpConvertUToPtr %_ptr_PSB_arrv4f %base\n", ""), "unknown physical array pointer"), + (_sub(QWORD, "%array = OpConvertUToPtr %_ptr_PSB_arr64 %base\n", ""), "unknown physical array pointer"), + (_sub(SUBTRACT, "%main = OpFunction", "%unexpected_pc = OpTypePointer PushConstant %uint\n%main = OpFunction"), + "unrecognized push-constant declaration"), + (_sub(SUBTRACT, "OpStore %p2 %d", "%leak = OpConvertPtrToU %ulong %p2\nOpStore %p2 %d"), + "unhandled physical word pointer use"), + (_sub(SUBTRACT, "OpReturn", "%unused_psb = OpTypePointer PhysicalStorageBuffer %bool\nOpReturn"), + "unhandled physical pointer operation"), + (_sub(SIGNED, "%old_min = OpAtomicSMin %int %min_target %c1 %c0 %operand", + "%old_min = OpAtomicSMin %int %min_target %c1 %non_const %operand"), + "signed atomic semantics must be a constant"), + (_sub(_sub(direct, "%main = OpFunction", "%atomic_rmw = OpConstant %uint 72\n%main = OpFunction"), + "OpReturn\nOpFunctionEnd", + "OpBranch %hdr\n%hdr = OpLabel\n%bad = OpAtomicIAdd %uint %p1 %c1 %atomic_rmw %d\n" + "OpLoopMerge %lexit %lcont None\nOpBranch %lcont\n%lcont = OpLabel\nOpBranch %hdr\n%lexit = OpLabel\nOpReturn\nOpFunctionEnd"), + "share a block with OpLoopMerge"), + (_sub(SIGNED, "OpReturn\nOpFunctionEnd", + "OpBranch %hdr\n%hdr = OpLabel\n%bad = OpLoad %int %load_target Aligned 4\n" + "OpLoopMerge %lexit %lcont None\nOpBranch %lcont\n%lcont = OpLabel\nOpBranch %hdr\n%lexit = OpLabel\nOpReturn\nOpFunctionEnd"), + "share a block with OpLoopMerge"), + (_sub(QWORD, "OpReturn\nOpFunctionEnd", + "OpBranch %hdr\n%hdr = OpLabel\n%bad = OpLoad %ulong %source Aligned 8\n" + "OpLoopMerge %lexit %lcont None\nOpBranch %lcont\n%lcont = OpLabel\nOpBranch %hdr\n%lexit = OpLabel\nOpReturn\nOpFunctionEnd"), + "share a block with OpLoopMerge"), + ] + for source, reason in cases: + _expect_value_error(saw.lower, source, fragment=reason) + + +def check_cli(): + """Verify main(argv) positive atomic writes, mocked tools, and every error/guard path.""" + with tempfile.TemporaryDirectory() as raw: + work = Path(raw) + valid_src = work / "subtract.spvasm" + valid_src.write_text(SUBTRACT, encoding="utf-8") + sentinel_bytes = b"SENTINEL_KEEP_ME" + + calls = [] + fail_on_call = {} + + def fake_run(cmd, check=False, **_kwargs): + calls.append(list(cmd)) + index = len(calls) + if index in fail_on_call: + raise fail_on_call[index] + if cmd[0] == "mock-as": + out_flag = cmd.index("-o") + Path(cmd[out_flag + 1]).write_bytes(b"\x03\x02\x23\x07mock_spv") + return subprocess.CompletedProcess(cmd, 0) + + orig_run = saw.subprocess.run + saw.subprocess.run = fake_run + try: + # 1. Positive run into nested missing parent directories. + nested_out = work / "nested" / "deep" / "window.spv" + assert not nested_out.parent.exists() + rc = saw.main([str(valid_src), str(nested_out), "--assembler", "mock-as", "--validator", "mock-val"]) + assert rc == 0, rc + assert nested_out.read_bytes() == b"\x03\x02\x23\x07mock_spv" + assert [p.name for p in nested_out.parent.iterdir()] == ["window.spv"] + assert len(calls) == 4 + assert calls[0][:3] == ["mock-as", "--target-env", "vulkan1.2"] and calls[0][3].name == "original.spvasm" + assert calls[1][:3] == ["mock-val", "--target-env", "vulkan1.2"] + assert calls[2][:3] == ["mock-as", "--target-env", "vulkan1.2"] and calls[2][3].name == "logical.spvasm" + assert calls[3][:3] == ["mock-val", "--target-env", "vulkan1.2"] + + # 2. Second run with existing parent directory (exercises exist_ok=True) and atomic replace. + calls.clear() + rc = saw.main([str(valid_src), str(nested_out), "--assembler", "mock-as", "--validator", "mock-val"]) + assert rc == 0, rc + + # 3. Missing required args -> argparse exit 2. + _expect_exit([str(valid_src)], expected_code=2) + + # 4. Output collides with input via exact path, non-normalized alias, missing path, and samefile/hardlink. + orig_bytes = valid_src.read_bytes() + calls.clear() + _expect_exit([str(valid_src), str(valid_src)], fragment="separate input assembly and output binary") + _expect_exit([str(valid_src), str(work / "nested" / ".." / "subtract.spvasm")], + fragment="separate input assembly and output binary") + missing_src = work / "missing.spvasm" + _expect_exit([str(missing_src), str(work / "nested" / ".." / "missing.spvasm")], + fragment="separate input assembly and output binary") + hardlink = work / "subtract_link.spvasm" + os.link(valid_src, hardlink) + assert valid_src.resolve() != hardlink.resolve() + assert valid_src.samefile(hardlink) + _expect_exit([str(valid_src), str(hardlink)], fragment="separate input assembly and output binary") + assert valid_src.read_bytes() == orig_bytes + assert calls == [] + + # 5. Output path is an existing directory: rejected immediately before running assembler/validator. + out_dir = work / "existing_dir" + out_dir.mkdir() + calls.clear() + _expect_exit([str(valid_src), str(out_dir), "--assembler", "mock-as", "--validator", "mock-val"], + fragment="directory") + assert list(out_dir.iterdir()) == [] + assert calls == [] + + # 6. Output parent is an existing file -> OSError caught cleanly. + file_parent = work / "file_parent" + file_parent.write_bytes(b"not a dir") + _expect_exit([str(valid_src), str(file_parent / "out.spv"), "--assembler", "mock-as", "--validator", "mock-val"]) + + # 7. Missing source and directory source -> OSError caught cleanly, no output or parent created. + missing_nested = work / "never_created" / "out.spv" + _expect_exit([str(missing_src), str(missing_nested)]) + assert not missing_nested.parent.exists() + _expect_exit([str(out_dir), str(missing_nested)]) + assert not missing_nested.parent.exists() + + # 8. Non-UTF8 source -> UnicodeDecodeError caught cleanly. + bad_utf8 = work / "bad_utf8.spvasm" + bad_utf8.write_bytes(b"\xff\xfe\x00\x80") + _expect_exit([str(bad_utf8), str(missing_nested)]) + assert not missing_nested.parent.exists() + + # 9. Lowering ValueError cases through main(): unhandled physical op, PushConstant, OpLoopMerge. + target_dir = work / "atomic_guard" + target_dir.mkdir() + protected = target_dir / "kept.spv" + protected.write_bytes(sentinel_bytes) + + unhandled_ptr = work / "unhandled_ptr.spvasm" + unhandled_ptr.write_text(_sub(SUBTRACT, "OpReturn", "%bad_psb = OpTypePointer PhysicalStorageBuffer %bool\nOpReturn"), encoding="utf-8") + bad_pc = work / "bad_pc.spvasm" + bad_pc.write_text(_sub(SUBTRACT, "%main = OpFunction", "%bad_pc = OpTypePointer PushConstant %uint\n%main = OpFunction"), encoding="utf-8") + loop_merge = work / "loop_merge.spvasm" + loop_merge.write_text( + _sub(SIGNED, "OpReturn\nOpFunctionEnd", + "OpBranch %hdr\n%hdr = OpLabel\n%bad = OpLoad %int %load_target Aligned 4\n" + "OpLoopMerge %lexit %lcont None\nOpBranch %lcont\n%lcont = OpLabel\nOpBranch %hdr\n%lexit = OpLabel\nOpReturn\nOpFunctionEnd"), + encoding="utf-8", + ) + for bad_asm, frag in ( + (unhandled_ptr, "unhandled physical pointer operation"), + (bad_pc, "unrecognized push-constant declaration"), + (loop_merge, "OpLoopMerge"), + ): + _expect_exit([str(bad_asm), str(protected), "--assembler", "mock-as", "--validator", "mock-val"], + fragment=frag) + assert protected.read_bytes() == sentinel_bytes + assert [p.name for p in target_dir.iterdir()] == ["kept.spv"] + + # 10. Subprocess failures: assembler CalledProcessError, validator CalledProcessError, + # lowered-stage validator failure, missing tool FileNotFoundError, and TimeoutExpired. + for call_idx, exc in ( + (1, subprocess.CalledProcessError(1, ["mock-as"])), + (2, subprocess.CalledProcessError(1, ["mock-val"])), + (3, subprocess.CalledProcessError(1, ["mock-as"])), + (4, subprocess.CalledProcessError(1, ["mock-val"])), + (1, FileNotFoundError("no mock-as")), + (2, subprocess.TimeoutExpired(["mock-val"], 5)), + ): + calls.clear() + fail_on_call.clear() + fail_on_call[call_idx] = exc + _expect_exit([str(valid_src), str(protected), "--assembler", "mock-as", "--validator", "mock-val"]) + assert protected.read_bytes() == sentinel_bytes + assert [p.name for p in target_dir.iterdir()] == ["kept.spv"] + fail_on_call.clear() + + # 11. Replace failure preserves existing output and leaves no temp artifacts. + orig_replace = Path.replace + + def fail_replace(self, target): + raise OSError("simulated replace failure") + + Path.replace = fail_replace + try: + _expect_exit([str(valid_src), str(protected), "--assembler", "mock-as", "--validator", "mock-val"], + fragment="simulated replace failure") + finally: + Path.replace = orig_replace + assert protected.read_bytes() == sentinel_bytes + assert [p.name for p in target_dir.iterdir()] == ["kept.spv"] + finally: + saw.subprocess.run = orig_run + + # 12. Real subprocess check of __main__ error exit without traceback. + sub_err = subprocess.run( + [sys.executable, "-B", str(SCRIPT), str(work / "no_such_file.spvasm"), str(work / "out.spv")], + capture_output=True, + text=True, + ) + assert sub_err.returncode == 1, sub_err + assert sub_err.stderr.strip() and "Traceback" not in sub_err.stderr, sub_err.stderr + + +def main(): + check_word_pointer() + check_signed_access() + check_float_access() + check_vec4_access() + check_merge_pointer_types() + check_lower_positive_and_composed() + check_lower_rejections() + check_cli() + print("spirv_address_window: unit lowering, composed passes, and CLI error handling passed") + + +if __name__ == "__main__": + main() diff --git a/tools/spirv_address_window.py b/tools/spirv_address_window.py index c555a9a53..fa44e6192 100644 --- a/tools/spirv_address_window.py +++ b/tools/spirv_address_window.py @@ -3,6 +3,7 @@ from pathlib import Path import re import subprocess +import sys import tempfile @@ -609,32 +610,47 @@ def lower(assembly): return merge_pointer_types(output) -def main(): +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + if left.exists() and right.exists(): + return left.samefile(right) + return False + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--assembler", default="spirv-as") parser.add_argument("--validator", default="spirv-val") - args = parser.parse_args() - if args.output.resolve() == args.source.resolve(): - parser.error("use separate input assembly and output binary paths") - original = args.source.read_text(encoding="utf-8") - with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: - path = Path(directory) - binary = path / "module.spv" - - def validate(source): - subprocess.run([args.assembler, "--target-env", "vulkan1.2", source, "-o", binary], check=True) - subprocess.run([args.validator, "--target-env", "vulkan1.2", binary], check=True) - - snapshot = path / "original.spvasm" - snapshot.write_text(original, encoding="utf-8") - validate(snapshot) - adapted = path / "logical.spvasm" - adapted.write_text(lower(original), encoding="utf-8") - validate(adapted) - binary.replace(args.output) + args = parser.parse_args(argv) + try: + if _same_path(args.output, args.source): + raise ValueError("use separate input assembly and output binary paths") + if args.output.is_dir(): + raise ValueError(f"output path must not be a directory: {args.output}") + original = args.source.read_text(encoding="utf-8") + args.output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=args.output.parent) as directory: + path = Path(directory) + binary = path / "module.spv" + + def validate(source): + subprocess.run([args.assembler, "--target-env", "vulkan1.2", source, "-o", binary], check=True) + subprocess.run([args.validator, "--target-env", "vulkan1.2", binary], check=True) + + snapshot = path / "original.spvasm" + snapshot.write_text(original, encoding="utf-8") + validate(snapshot) + adapted = path / "logical.spvasm" + adapted.write_text(lower(original), encoding="utf-8") + validate(adapted) + binary.replace(args.output) + except (OSError, UnicodeDecodeError, ValueError, subprocess.SubprocessError) as error: + parser.exit(1, f"error: {error}\n") + return 0 if __name__ == "__main__": - main() + sys.exit(main()) From 82e01ef714a62182b867f3c4cb44cf0396d8c9bb Mon Sep 17 00:00:00 2001 From: pigalot Date: Wed, 25 Nov 2026 14:18:54 +0000 Subject: [PATCH 019/232] shader: name where a gfx2hlsl translation failed in its .fail (#2364) * shader: name where a gfx2hlsl translation failed in its .fail Two .fail reasons did not say where to look, because they leave out the program that hit them: - An unexpected translator error ("translator error: TypeError: ...") now ends with the function, file name and line that raised it: "(in scalar_select, gfx2hlsl.py line 1234)". - An operand refusal ("operand '-v30'") does not say which lowering refused it. The translation loop now records the instruction on the refusal, and the graphics and compute .fail writers end the text with "in v_and_b32_e64". The exception message is unchanged for every other caller, including the refusal census. Test: startup_gfx2hlsl_watch_check.py checks the location on its injected ZeroDivisionError. It also checks a graphics pair whose pixel shader refuses -v30 on v_and_b32_e64: translate_to's result and .fail name the instruction, while Pipeline still raises "operand '-v30'". Negative control: with the translator change reverted, both checks fail. ctest --preset dev -j 8 -R 'gfx2hlsl|pixel_aot_check|rdna2_tools|compute|translator|startup_run|triage|scan_unsupported' -E '_hardware$|startup_audio_': 195 passed, on main fe0c822f. Co-Authored-By: Claude Opus 5.5 * shader: locate a library-raised translator error at its caller Review follow-up. A translator error raised inside a standard-library call named the library frame (for example json's decoder) in its .fail. The location now skips standard-library frames and falls back to the last frame. The comment no longer calls the text a grouping key, since the line number moves with unrelated edits, and fail_reason's docstring says a refusal without the recorded instruction gives the message alone. Test: startup_gfx2hlsl_watch_check.py adds a json.loads error that must be located at its caller, and takes its own file name from __file__. Negative control: using the last frame again fails that case. --------- Co-authored-by: lewisalex86 Co-authored-by: Claude Opus 5.5 --- docs/experiments.md | 2 +- docs/startup-runtime.md | 6 ++++- tests/startup_gfx2hlsl_watch_check.py | 37 +++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 37 +++++++++++++++++++++++++-- 4 files changed, 78 insertions(+), 4 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 27a8dc97a..e16421b53 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13934,7 +13934,7 @@ The text and JSON reports show two views. - **Per request key** includes RTV variants. Each reason and scope row counts requests containing that refusal, requests where it was the first site reached, and requests where it was the only distinct reason. Repeating the same reason at several sites still counts toward Only. The refusal sites per request histogram counts each site reached. **No refusal recorded (not compiled)** counts requests with zero recorded sites. - **Per code pair** groups base requests by a hash of their `.a` and `.b` bytes and excludes RTV variants. For each reason and scope, the report counts pairs where it was reached under every observed root signature and pairs where it was reached under some but fewer than all observed roots. Multiple requests for the same pair and root contribute their combined reasons. -The Scope column distinguishes `decode`, vertex lowering (`vs`), pixel lowering (`ps`), and `pipeline`. A refusal for an instruction of known length skips that instruction and continues. An undecodable word, or a refusal during request loading, pipeline construction, or output generation ends the pipeline, with the same reason the default path would write to `.fail`. For a pipeline-scope Only row, the single observed reason is a lower bound on what may be present. Counts after the first refusal are approximate because skipped instructions leave later state unmodelled. +The Scope column distinguishes `decode`, vertex lowering (`vs`), pixel lowering (`ps`), and `pipeline`. A refusal for an instruction of known length skips that instruction and continues. An undecodable word, or a refusal during request loading, pipeline construction, or output generation ends the pipeline, with the same reason the default path would write to `.fail`, without the instruction name or source location that `.fail` appends. For a pipeline-scope Only row, the single observed reason is a lower bound on what may be present. Counts after the first refusal are approximate because skipped instructions leave later state unmodelled. An unexpected handler exception after an earlier refusal or crash is reported as `internal error in : `, a possible follow-on effect. With no earlier refusal it is reported as `translator crash in : `, which identifies a translator bug. The reports contain no request keys, raw disassembly, register numbers or immediates. Cause numbers such as a format ID, operand width, or shader model remain visible. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 1beb90dda..4c56202ae 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -686,7 +686,11 @@ requests. The watcher's first pass retries every earlier failure once, so a tran requests that failed in an earlier run; after that, a request whose `.fail` is newer than its ready marker is not retried during the run (the runtime writes each request once and never rewrites it). The one-shot `--pending` scan retries every failure. An unexpected translator error is written -to `.fail` as `translator error: ...` instead of stopping the scan. A worker killed from outside +to `.fail` as `translator error: ...`, ending with the function, file name and line that raised +it, skipping standard-library frames (`(in scalar_select, gfx2hlsl.py line 1234)`), instead of +stopping the scan. An operand refusal +in `.fail` names the instruction that refused it (`operand '-v30' in v_and_b32_e64`); the +refusal's own message, which `--refusals` counts, stays `operand '-v30'`. A worker killed from outside (for example out of memory) ends that watcher pass only; its requests are retried on the next pass. FXC is located as described for `X2W_SHADER_CACHE` under [Switches](#switches). A scan with more than one pending request translates them in parallel processes, one per logical processor (at most 61 on diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index 6919a76d3..c96006fdc 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -10,6 +10,7 @@ pool must end one watcher pass and not the watcher, and an invalid X2W_TRANSLATE_JOBS must fall back to the processor count. """ +import json import os import re import struct @@ -139,6 +140,42 @@ def mesh57_fixture(ms, ps, expected, tamper=False): gfx2hlsl.translate_request = real fail = d / ('%016x.fail' % 9) expect('translator error recorded', fail.read_text().startswith('translator error: ZeroDivisionError') if fail.exists() else None, True) + # It names the function, file and line that raised it (the lambda above). + expect('translator error located', bool(re.fullmatch( + r'translator error: ZeroDivisionError: division by zero \(in , %s line \d+\)\n' + % re.escape(Path(__file__).name), fail.read_text())) if fail.exists() else None, True) + +# An error raised inside a standard-library call is located at the code that made the call, not in the library. +with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + touch(d / ('req_%016x.rtv' % 9)) + real = gfx2hlsl.translate_request + gfx2hlsl.translate_request = lambda out_dir, key: json.loads('{') + try: + gfx2hlsl.translate_pending(str(d), jobs=1) + finally: + gfx2hlsl.translate_request = real + fail = d / ('%016x.fail' % 9) + expect('library error located at its caller', bool(re.fullmatch( + r'translator error: JSONDecodeError: .* \(in , %s line \d+\)\n' + % re.escape(Path(__file__).name), fail.read_text())) if fail.exists() else None, True) + +# An operand refusal's .fail names the instruction that refused it; the refusal message itself is unchanged. +sys.path.insert(0, str(ROOT / 'tests')) +import startup_gfx2hlsl_dpp_quad_swap_check as quad # noqa: E402 + +AND_NEG = struct.pack('.fail instead of raised.""" try: return translate_request(out_dir, key) except Exception as error: # noqa: BLE001 - one bad request must not stop a scan or the watcher reason = 'translator error: %s: %s' % (type(error).__name__, error) + # Where it was raised (function, file name, line), so the .fail points at the fault without the program + # that hit it. The line number moves with unrelated edits, so this text is for reading, not a stable key. + frame = raise_site(error) + if frame: + reason += ' (in %s, %s line %d)' % (frame.name, os.path.basename(frame.filename), frame.lineno) with open(os.path.join(out_dir, '%016x.fail' % key), 'w') as fail: fail.write(reason + '\n') return reason From 280abb58dd05325939b9ea0471602e762f675cb2 Mon Sep 17 00:00:00 2001 From: Luuk Motz Date: Wed, 25 Nov 2026 15:19:17 +0100 Subject: [PATCH 020/232] pe: report the pe_map main EXE as the process image (#1151) * pe: report the pe_map main EXE as the process image Under a Windows launch the EXE is the process image: the PEB's ImageBaseAddress holds its base, GetModuleHandle(NULL) returns it and FindResource(NULL, ...) searches its resources. A mapped EXE found the host there instead, so it read the host's headers and resources. The docs listed GetModuleHandle(NULL) and the PEB as not covered. pe_map_run_main now writes the mapped EXE's base into ImageBaseAddress before the process-attach callbacks, keeping the host's value, and an accepted pe_map_release writes the host's value back. Only one image is reported at a time: a second pe_map_run_main is refused while one is. The PEB loader list is not changed, so GetModuleFileName(NULL) still names the host. cpu_exe_process_image is a CRT-free EXE with one RCDATA resource that checks its process image, its headers through that handle and its own resource. cpu_native_process_image compares a Windows launch, pe_run_package.py, an in-process pe_map_run_main host (which also checks the restore after release), a pe_map_run negative control and the second-image refusal. cpu_exe_io!finish_exe took GetModuleHandleW(NULL) == image_base to mean "launched by Windows". It now also requires the loader to know the image, so a reported pe_map main image returns its code to the host instead of ending it (cpu_package_shim_lifetime runs two packages in one process). Co-Authored-By: Claude Opus 5.5 * tests: pin the pe_map process image at the TLS lifecycle boundaries The slot-0 fixture's process-attach callback now records whether GetModuleHandleW(nullptr) is its own __ImageBase, so the Windows launch, pe_map_run_main and pe_run_package must agree (m1=yyy) and plain pe_map_run must not (m1=n-n, X=9). Its host reads the process image right after the start, after a refused release and after the accepted release: iih in paused (worker c inside the image at the refusal), alive and untracked, i-h without a refusal, h-h under pe_map_run. Local mutations to pe_map.cpp each fail: no restore at the accepted release (i-i), a restore before the refusal (ihh), and a report after the process-attach callbacks (m1=yyn). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CMakeLists.txt | 10 ++ docs/experiments.md | 34 ++++- tests/cpu/exe_io.cpp | 8 +- tests/cpu/exe_process_image.cpp | 76 +++++++++++ tests/cpu/exe_process_image.rc | 3 + tests/cpu/exe_tls_slot0.cpp | 14 ++- tests/cpu/exe_tls_slot0_host.cpp | 18 ++- tests/cpu/native_exe_tls_slot0_check.py | 16 ++- tests/cpu/package_main_image_check.py | 6 +- tests/cpu/process_image_check.py | 160 ++++++++++++++++++++++++ tools/pe_map.cpp | 65 ++++++++-- 11 files changed, 384 insertions(+), 26 deletions(-) create mode 100644 tests/cpu/exe_process_image.cpp create mode 100644 tests/cpu/exe_process_image.rc create mode 100644 tests/cpu/process_image_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index acde0a7e1..cc12f7a47 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7604,6 +7604,16 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_native_exe_tls_slot0_enroll COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/native_exe_tls_slot0_check.py" enroll "$" "$" "$") + # The mapped main EXE is the process image: GetModuleHandle(NULL) and FindResource(NULL, ...) find it. + add_executable(cpu_exe_process_image tests/cpu/exe_process_image.cpp tests/cpu/exe_process_image.rc) + target_compile_options(cpu_exe_process_image PRIVATE /GS- /Zl) + target_link_options(cpu_exe_process_image PRIVATE /ENTRY:exe_entry /NODEFAULTLIB /SUBSYSTEM:CONSOLE + /DYNAMICBASE /INCREMENTAL:NO) + target_link_libraries(cpu_exe_process_image PRIVATE kernel32) + add_test(NAME cpu_native_process_image COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/process_image_check.py" "$" + "$") + set_tests_properties(cpu_native_process_image PROPERTIES TIMEOUT 60) # pe_run_package starts the same /GA EXE as the package's main image; its log must equal the Windows launch. add_test(NAME cpu_package_main_image COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/package_main_image_check.py" "$" diff --git a/docs/experiments.md b/docs/experiments.md index e16421b53..987e2232d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2596,9 +2596,11 @@ On a participating thread, the host's own index-0 code reads the image's block, `cpu_native_exe_tls_slot0_windows` launches the EXE with Windows, where it owns index 0: ```text -LOG:m1=yy m:yyyy a2=yy a:yyyy a3=y- b2=yy b:yyyy b3=y- X=0 +LOG:m1=yyy m:yyyy a2=yy a:yyyy a3=y- b2=yy b:yyyy b3=y- X=0 ``` +The third `m1` result is the process image: in the process-attach callback, `GetModuleHandleW(NULL)` is the EXE's own `__ImageBase`. + `cpu_native_exe_tls_slot0` runs `cpu_exe_tls_slot0_host`, a CRT-free host whose own TLS block owns slot 0. It binds only `kernel32.dll` and runs one scenario per process. Under `pe_map_run_main` it binds the guest's `CreateThread` to `pe_map_main_create_thread`, so the guest's workers are enrolled. Under `pe_map_run` it binds kernel32's `CreateThread`. Each scenario has two non-participating threads: - a reader that samples its own slot 0 and sentinel from before the map until after release; @@ -2618,7 +2620,7 @@ A refused release returns 0 with the refusal reported. The accepted release is t | `exited`: a host participant is ended with `TerminateThread` | 1, exit confirmed | one cleanup | `2,2`; 0 | `4,3,1,0,0,0,1,0,0,0` | | `untracked`: 64 host participants, the last finds the table full | 0, refused (cannot inspect), intact | it leaves; 1, one cleanup | `2,2`; 0 | `67,67,0,1,0,0,1,0,0,0` | | `paused`: worker c paused inside the image's code | 0, refused, intact | c resumes, finds its block, returns; 1, one cleanup | `3,3`; 0 | `5,5,0,1,0,0,1,0,0,0` | -| `plain`: `pe_map_run` (negative control), every slot-0 check `n`, `X=8` | 1 | one cleanup | `3,3`; 2 | `0,0,0,0,0,0,-1,0,0,0` | +| `plain`: `pe_map_run` (negative control), every slot-0 check `n`, process image `n`, `X=9` | 1 | one cleanup | `3,3`; 2 | `0,0,0,0,0,0,-1,0,0,0` | `cpu_native_exe_tls_slot0_enroll` checks enrollment failures, each in its own child host process. It uses `cpu_exe_tls_slot0_enroll`, whose probe worker p touches a global sentinel as the first statement of its start routine, and which records a failed `CreateThread` instead of ending the process. The host also enters and leaves once, and every reader, late-thread, release and cleanup check applies: @@ -2656,6 +2658,34 @@ cmake --build --preset dev --target pe_map cpu_exe_tls_slot0 cpu_exe_tls_slot0_p ctest --preset dev --no-tests=error -R '^cpu_native_exe_tls_slot0(_windows|_enroll)?$' -V ``` +### Process image + +Under a Windows launch the EXE is the process image. The PEB's `ImageBaseAddress` holds its base, `GetModuleHandle(NULL)` returns it, and `FindResource(NULL, ...)` searches its resources. `pe_map_run_main` now reports the mapped EXE there before its process-attach callbacks and keeps the host's value. An accepted `pe_map_release` writes the host's value back. It also refuses to start a second image as the main image while one is reported. An image without a TLS template is reported too. `pe_map_run` is unchanged. + +`cpu_native_process_image` runs `cpu_exe_process_image`, a CRT-free EXE with one RCDATA resource. It logs whether `GetModuleHandleW(NULL)` is its own `__ImageBase`, whether the headers reached through that handle name its entry point, whether `FindResourceW(NULL, 101, RT_RCDATA)` returns its own bytes, whether an absent resource 102 stays absent, and whether `kernel32.dll` still resolves. +- The Windows launch, `pe_run_package.py` and an in-process host using `pe_map_run_main` produce the same log, `self=y hdr=y res=y miss=y k32=y X=0`. +- After the release, the host's `GetModuleHandleW(NULL)` is its own base again. +- Under `pe_map_run`, the negative control, the EXE finds the host instead: `self=n hdr=n res=n`. +- A second mapping started as the main image while the first is still reported returns 0 and runs nothing. It starts after the first is released. + +The TLS lifecycle boundaries are pinned in `cpu_native_exe_tls_slot0` and `cpu_native_exe_tls_slot0_enroll`, whose guest has a TLS callback: +- In its process-attach callback, `GetModuleHandleW(NULL)` is the mapped base under `pe_map_run_main` (`m1=yyy`), as under the Windows launch and `pe_run_package.py`. Under `pe_map_run` it is not (`m1=n-n`). +- The host reads `GetModuleHandleW(NULL)` after the start, after a refused release and after the accepted release (`process_image=`, `i` the mapped base, `h` the host's). It is `iih` in `paused`, where worker c is paused inside the image's code at the refused release, and in `alive` and `untracked`. It is `i-h` in the scenarios without a refusal, and `h-h` under `pe_map_run`. + +Local mutations each failed the test: +- Not reporting the image fails the runner log. +- Not restoring at release crashes the host at exit. +- Not refusing the second image crashes the host. + +Not covered: the PEB loader list. `GetModuleFileName(NULL)` and `GetModuleHandleEx` on an image address still describe the host. A thread created outside `pe_map_main_create_thread` also sees the mapped EXE as the process image while it is reported, as every thread does under Windows. + +The shared test helper `cpu_exe_io!finish_exe` used to treat `GetModuleHandleW(NULL) == image_base` as "launched by Windows". It now also requires the loader to know the image, so a reported `pe_map` main image gets its exit code back instead of ending the host. + +```powershell +cmake --build --preset dev --target pe_map cpu_exe_process_image +ctest --preset dev --no-tests=error -R '^cpu_native_process_image$' -V +``` + ### Lifecycle of two DLLs with the static C runtime `cpu_life_a` and `cpu_life_b` are built with the static MSVC runtime (`/MT`, linked without `/INCREMENTAL`, so the PE entry point is the runtime's `_DllMainCRTStartup` and not an incremental-link thunk). A real global constructor runs before `DllMain(DLL_PROCESS_ATTACH)` and a real global destructor after `DllMain(DLL_PROCESS_DETACH)`. Nothing calls them by hand. B imports A. A's constructor sets its state to 7. B's constructor stores `a_value() * 2`, and its destructor reads A's state again. `b_via_a()` returns `a_value() + b_value()` at the time of the call. Every constructor, destructor and `DllMain` call logs a token into `cpu_life_sink.dll`, a small CRT-free DLL that the test host loads first and keeps for the whole child process, so it is valid during every destruction and sees the last destructor. `DllMain` only calls into the sink, which takes no lock and needs nothing from the loader. diff --git a/tests/cpu/exe_io.cpp b/tests/cpu/exe_io.cpp index 80a344ae7..a68ba4d31 100644 --- a/tests/cpu/exe_io.cpp +++ b/tests/cpu/exe_io.cpp @@ -91,7 +91,13 @@ extern "C" __declspec(dllexport) DWORD finish_exe(const void* image_base, DWORD // The console fixture uses UCRT stdin rather than read_selector. if (!prepare_test_worker(L"CPU_CRC_TEST_LIVE_WORKER")) code = 3; - if (image_base == GetModuleHandleW(nullptr)) + // End the process only when Windows launched this image: it is then both the process image and a + // module in the loader's list. A pe_map main image is reported as the process image too (pe_map_run_main), + // but the loader does not know it, so its host gets the code back instead of losing the process. + HMODULE loaded = nullptr; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(image_base), &loaded) && + loaded == static_cast(const_cast(image_base)) && loaded == GetModuleHandleW(nullptr)) ExitProcess(code); return code; } diff --git a/tests/cpu/exe_process_image.cpp b/tests/cpu/exe_process_image.cpp new file mode 100644 index 000000000..5d702b750 --- /dev/null +++ b/tests/cpu/exe_process_image.cpp @@ -0,0 +1,76 @@ +// CRT-free EXE that asks the process for its own image, as an EXE does under a Windows launch. +// +// GetModuleHandleW(NULL) returns the PEB's ImageBaseAddress, and FindResourceW(NULL, ...) looks +// resources up in that module. Under a Windows launch that is this EXE. A loader that maps the EXE +// into another process must report the mapped image there, or the EXE reads the host's headers and +// resources instead of its own. +// +// The log, one line on standard output: +// self= GetModuleHandleW(NULL) is this image (&__ImageBase) +// hdr= the PE headers reached through that handle name this entry point +// res= FindResourceW(NULL, 101, RT_RCDATA) finds this image's resource with its exact bytes +// miss= FindResourceW(NULL, 102, RT_RCDATA), absent from this image, is not found +// k32= GetModuleHandleW(L"kernel32.dll") still returns a module (unaffected control) +// X= the number of n results +#include + +#pragma runtime_checks("", off) // CRT-free: no /RTC helpers in Debug builds + +extern "C" IMAGE_DOS_HEADER __ImageBase; + +namespace { +// Must match exe_process_image.rc. +constexpr char resource_bytes[] = "xbox2windows process image resource 101"; + +void write(const char* text) +{ + DWORD length = 0; + while (text[length]) ++length; + DWORD written = 0; + WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), text, length, &written, nullptr); +} + +bool own_resource() +{ + HRSRC found = FindResourceW(nullptr, MAKEINTRESOURCEW(101), MAKEINTRESOURCEW(10)); // RT_RCDATA + if (!found) return false; + const DWORD size = SizeofResource(nullptr, found); + HGLOBAL loaded = LoadResource(nullptr, found); + const auto* bytes = static_cast(loaded ? LockResource(loaded) : nullptr); + if (!bytes || size != sizeof(resource_bytes)) return false; + for (DWORD i = 0; i < size; ++i) + if (bytes[i] != resource_bytes[i]) return false; + // The resource lies inside this image. + const auto* base = reinterpret_cast(&__ImageBase); + const auto* nt = reinterpret_cast(base + __ImageBase.e_lfanew); + return bytes >= base && bytes + size <= base + nt->OptionalHeader.SizeOfImage; +} +} // namespace + +extern "C" DWORD WINAPI exe_entry(); + +extern "C" DWORD WINAPI exe_entry() +{ + const auto* process_image = reinterpret_cast(GetModuleHandleW(nullptr)); + const bool self = process_image == reinterpret_cast(&__ImageBase); + bool hdr = false; + if (process_image && reinterpret_cast(process_image)->e_magic == IMAGE_DOS_SIGNATURE) { + const auto* dos = reinterpret_cast(process_image); + const auto* nt = reinterpret_cast(process_image + dos->e_lfanew); + hdr = nt->Signature == IMAGE_NT_SIGNATURE && + process_image + nt->OptionalHeader.AddressOfEntryPoint == reinterpret_cast(&exe_entry); + } + const bool res = own_resource(); + const bool miss = !FindResourceW(nullptr, MAKEINTRESOURCEW(102), MAKEINTRESOURCEW(10)); + const bool k32 = GetModuleHandleW(L"kernel32.dll") != nullptr; + + const bool results[] = {self, hdr, res, miss, k32}; + DWORD failures = 0; + for (bool ok : results) failures += ok ? 0 : 1; + char line[] = "LOG:self=? hdr=? res=? miss=? k32=? X=?\n"; + const int marks[] = {9, 15, 21, 28, 34}; + for (int i = 0; i < 5; ++i) line[marks[i]] = results[i] ? 'y' : 'n'; + line[38] = static_cast('0' + failures); + write(line); + return failures; +} diff --git a/tests/cpu/exe_process_image.rc b/tests/cpu/exe_process_image.rc new file mode 100644 index 000000000..975e47bad --- /dev/null +++ b/tests/cpu/exe_process_image.rc @@ -0,0 +1,3 @@ +// RCDATA for tests/cpu/exe_process_image.cpp. The bytes must match resource_bytes there, +// including the terminating zero. Resource 102 is deliberately absent. +101 RCDATA { "xbox2windows process image resource 101\0" } diff --git a/tests/cpu/exe_tls_slot0.cpp b/tests/cpu/exe_tls_slot0.cpp index 342f6d0d9..22e9ef4ae 100644 --- a/tests/cpu/exe_tls_slot0.cpp +++ b/tests/cpu/exe_tls_slot0.cpp @@ -13,9 +13,11 @@ // write the whole array and validate the process heap. // // The log, one line on standard output: -// = a TLS callback: thread m (initial), a or b; reason 1 process attach, +// =[

] a TLS callback: thread m (initial), a or b; reason 1 process attach, // 2 thread attach, 3 thread detach; s = y/n slot 0 is the image's block; -// t = y/n the block holds the template, - when not checked +// t = y/n the block holds the template, - when not checked; p, process +// attach only: y/n GetModuleHandleW(nullptr) is this image's base, as it is +// for the process image under a Windows launch // : a thread's own check: slot 0, template, whole-array write read back, // HeapValidate after the write (- when not checked) // X= the number of n results @@ -42,6 +44,8 @@ #pragma runtime_checks("", off) +extern "C" IMAGE_DOS_HEADER __ImageBase; // this image's base, wherever it is mapped + // The TLS support the C runtime's tlssup provides, for an EXE linked without it. extern "C" { ULONG _tls_index = 0; @@ -136,7 +140,11 @@ void NTAPI callback(PVOID, DWORD reason, PVOID) { const bool slot = in_slot0(); // On thread detach the thread has already written its copy, so only slot 0 is checked. const char intact = slot && reason != DLL_THREAD_DETACH ? yes_no(template_intact()) : '-'; - record(static_cast('0' + reason), yes_no(slot), intact, 0, 0); + // Process identity before the entry point runs: the PEB's image base, read through GetModuleHandle(NULL). + const char process = reason == DLL_PROCESS_ATTACH + ? yes_no(GetModuleHandleW(nullptr) == reinterpret_cast(&__ImageBase)) + : 0; + record(static_cast('0' + reason), yes_no(slot), intact, process, 0); } // A thread's own check: slot 0, its template copy, a whole-array write and the process heap. diff --git a/tests/cpu/exe_tls_slot0_host.cpp b/tests/cpu/exe_tls_slot0_host.cpp index 2ebc90017..4b0cb45c0 100644 --- a/tests/cpu/exe_tls_slot0_host.cpp +++ b/tests/cpu/exe_tls_slot0_host.cpp @@ -34,7 +34,7 @@ // HOST: scenario= started=<0|1> exit= installed_main= reader_untouched= // reader_samples= participant= refused= intact_on_refusal= // resumed= late_untouched= late_callbacks= callbacks=, host_tls= -// cleaned= second_release= heap_valid= +// process_image= cleaned= second_release= heap_valid= // stats=,,,,,,,, // , // [probe=,,,] probe scenarios only @@ -51,6 +51,9 @@ // starting thread's slot 0 still held the image's block ('-' where no refusal is expected). // resumed: the paused worker found its own block and values after the refusal. // host_tls: after the accepted release the starting thread's slot 0 and sentinel are the host's again. +// process_image: which image GetModuleHandleW(nullptr) returns right after the start, right after the +// refused release ('-' without one) and right after the accepted release: i the mapped image, h this +// host, o neither. // cleaned: after the accepted release the image is no longer committed, its unwind data is gone and // the carrier is unloaded; it is the only pe_map_release that returned 1. second_release: a further // pe_map_release returns 0 (one cleanup only). @@ -324,6 +327,12 @@ HANDLE host_event(const wchar_t* suffix) { return CreateEventW(nullptr, TRUE, FALSE, name); } +// Which image GetModuleHandleW(nullptr) reports as the process image: 'i' the mapped image, 'h' this host. +char process_image(const void* image, HMODULE host) { + const HMODULE now = GetModuleHandleW(nullptr); + return now == image ? 'i' : now == host ? 'h' : 'o'; +} + bool same(const wchar_t* a, const wchar_t* b) { for (; *a && *a == *b; ++a, ++b) { } @@ -375,6 +384,7 @@ extern "C" int host_entry() { HANDLE reader_thread = CreateThread(nullptr, 0, reader, nullptr, 0, nullptr); if (!reader_thread || WaitForSingleObject(g_reader_ready, 10000) != WAIT_OBJECT_0) ExitProcess(fail_setup("reader")); + const HMODULE host_image = GetModuleHandleW(nullptr); std::uint32_t status = 0; void* base = map(argv[2], resolve, &status, g_detail, sizeof(g_detail)); if (!base) ExitProcess(fail_setup(g_detail[0] ? g_detail : "map failed")); @@ -392,6 +402,8 @@ extern "C" int host_entry() { std::uint32_t exit_code = 0xdeadbeef; const int started = run(base, &exit_code); const bool installed_main = holds_image_block(); + // The process image after the start, after a refused release ('-' when none) and after the accepted release. + char identity[3] = {process_image(base, host_image), '-', '-'}; // More than one table's worth of workers can end without ever entering their start routine. if (cancelled && started) { @@ -455,6 +467,7 @@ extern "C" int host_entry() { std::int64_t status_now[STATS]; stats(status_now); refused = first == 0 && status_now[6] == 2; + identity[1] = process_image(base, host_image); intact = committed(base) && has_unwind(entry_point) && carrier_loaded() && holds_image_block(); if (stay >= 0) leave_ok = finish_participant(stay) && leave_ok; if (paused) { @@ -476,6 +489,7 @@ extern "C" int host_entry() { LONG probe_out[4] = {}; if (probe) probe_result(probe_out); // the guest's export, read while the image is still mapped const int released = release(base); + identity[2] = process_image(base, host_image); const bool cleaned = released == 1 && !committed(base) && !has_unwind(entry_point) && !carrier_loaded(); const bool second_release = release(base) == 0; // From here on the starting thread has the host's block back, so the host may read its thread-locals. @@ -510,6 +524,8 @@ extern "C" int host_entry() { put(','); put_number(final_counts[3], false); put_flag("host_tls", host_tls); + put(" process_image="); + for (char c : identity) put(c); put_flag("cleaned", cleaned); put_flag("second_release", second_release); put_flag("heap_valid", heap_valid); diff --git a/tests/cpu/native_exe_tls_slot0_check.py b/tests/cpu/native_exe_tls_slot0_check.py index bd5dbab1c..4ed58a49e 100644 --- a/tests/cpu/native_exe_tls_slot0_check.py +++ b/tests/cpu/native_exe_tls_slot0_check.py @@ -18,6 +18,11 @@ its thread-attach/detach totals must count only the guest's own workers; under pe_map_run (plain) the late thread's attach and detach still reach the guest, as before. A refused release returns 0 with the status API reporting the refusal; the accepted release is the only one that returns 1. +Process image: the guest's process-attach callback reports whether GetModuleHandleW(nullptr) is its own base +(the third m1 result), as under a Windows launch; under pe_map_run_main it must be, under pe_map_run it must +not. The host reads GetModuleHandleW(nullptr) after the start, after a refused release and after the accepted +release: the mapped base until the accepted release, including across a refusal with a worker paused inside +the image, and its own base afterwards; under pe_map_run the host's base throughout. - main: pe_map_run_main; the guest log equals the Windows log; a host thread enters and leaves; release is accepted once. - alive: a host participant is still entered at the first release, which returns 0 and changes nothing; @@ -61,8 +66,8 @@ from tempfile import TemporaryDirectory TIMEOUT = 60 -EXPECTED = "m1=yy m:yyyy a2=yy a:yyyy a3=y- b2=yy b:yyyy b3=y- X=0" -PLAIN = "m1=n- m:n--- a2=n- a:n--- a3=n- b2=n- b:n--- b3=n- X=8" +EXPECTED = "m1=yyy m:yyyy a2=yy a:yyyy a3=y- b2=yy b:yyyy b3=y- X=0" +PLAIN = "m1=n-n m:n--- a2=n- a:n--- a3=n- b2=n- b:n--- b3=n- X=9" MAIN_TRACKED = 64 PAUSED = EXPECTED.replace(" X=0", " c2=yy c:yyyy X=0") PROBED = EXPECTED.replace(" a2=", " p2=yy p:yyyy p3=y- a2=") @@ -148,7 +153,7 @@ def check(mapper, image, host, scenario, want): log = want["log"] if result["log"] != log: problems.append(f"guest log {result['log']!r}, expected {log!r}") - if fields["started"] != "1" or int(fields["exit"], 16) != (8 if scenario == "plain" else 0): + if fields["started"] != "1" or int(fields["exit"], 16) != (9 if scenario == "plain" else 0): problems.append(f"started {fields['started']}, guest exit {fields['exit']}") if flag(fields, "installed_main") != (scenario != "plain"): problems.append(f"installed_main {fields['installed_main']}") @@ -171,6 +176,11 @@ def check(mapper, image, host, scenario, want): if fields["callbacks"] != want["callbacks"]: problems.append(f"guest thread-attach,thread-detach callbacks {fields['callbacks']}, " f"expected {want['callbacks']}") + # The process image: the mapped EXE from before its callbacks until the accepted release, including across a + # refused one; the host's again afterwards. Under plain pe_map_run it never changes. + identity = ("h" if scenario == "plain" else "i") + ("i" if want["refused"] else "-") + "h" + if fields["process_image"] != identity: + problems.append(f"process_image {fields['process_image']} (after start, refusal, release), expected {identity}") if not flag(fields, "cleaned") or not flag(fields, "second_release"): problems.append(f"cleaned {fields['cleaned']}, second_release {fields['second_release']}: expected one " "final cleanup (image freed, unwind data gone, carrier unloaded) and a further release 0") diff --git a/tests/cpu/package_main_image_check.py b/tests/cpu/package_main_image_check.py index 29af1a481..b6a795d77 100644 --- a/tests/cpu/package_main_image_check.py +++ b/tests/cpu/package_main_image_check.py @@ -10,8 +10,8 @@ and the JSON result must match the Windows launch. - The same package without --system kernel32.dll: refused before mapping, with no guest log. -Under the previous pe_map_run start, every slot-0 check in the guest log failed -(native_exe_tls_slot0_check.PLAIN, exit 8). +Under the previous pe_map_run start, every slot-0 check and the process-image check in the guest +log failed (native_exe_tls_slot0_check.PLAIN, exit 9). """ import json @@ -90,7 +90,7 @@ def check(mapper, exe): capture_output=True, text=True, timeout=TIMEOUT, check=True) explicit_log = guest_log(explicit.stdout) explicit_result = json.loads(explicit.stdout[explicit.stdout.index("{"):]) - if (explicit.stderr or explicit_log != "m1=yy m:yyyy a:n--- b:n--- X=2" + if (explicit.stderr or explicit_log != "m1=yyy m:yyyy a:n--- b:n--- X=2" or explicit_result != {**expected_result, "exit_code": 2}): raise AssertionError(f"runner replaced the explicit CreateThread provider: {explicit!r}") print("explicit kernel32 provider: entry owns slot 0; unwrapped workers remain unenrolled") diff --git a/tests/cpu/process_image_check.py b/tests/cpu/process_image_check.py new file mode 100644 index 000000000..054e93140 --- /dev/null +++ b/tests/cpu/process_image_check.py @@ -0,0 +1,160 @@ +"""The mapped main EXE is the process image: GetModuleHandle(NULL) and FindResource(NULL, ...). + +cpu_exe_process_image is a CRT-free EXE that asks the process for its own image and reports one log +line (tests/cpu/exe_process_image.cpp). Compared runs: + +- windows: launched by Windows, where it is the process image. Every check is y and the exit is 0. +- runner: tools/pe_run_package.py with --system kernel32.dll, which starts the entry with + pe_map_run_main. The guest log and the exit code must equal the Windows launch. +- main: an in-process pe_map host maps the EXE, starts it with pe_map_run_main and releases it. + The guest log equals the Windows log, and after the release GetModuleHandleW(NULL) in the host + returns the host's own base again. +- plain (negative control): the same host starts the EXE with pe_map_run, which does not report + it as the process image. The EXE then finds the host instead of itself: self, hdr and res fail. +- twice: while one mapped EXE is the process image, pe_map_run_main refuses a second mapping and + runs nothing; after the first is released, the second starts and is reported, and its release + restores the host's value. +""" + +import json +from pathlib import Path +import shutil +import subprocess +import sys +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[2] +TOOL = ROOT / "tools" / "pe_run_package.py" +EXE = "cpu_exe_process_image.exe" +EXPECTED = "self=y hdr=y res=y miss=y k32=y X=0" +TIMEOUT = 60 + +# In-process pe_map host. argv: mapper, mode, exe [, second exe]. Prints LOG lines from the guest and +# HOST: lines from here; exits 0 unless the host itself fails. +HOST = r""" +import ctypes as C, sys +from ctypes import wintypes as W +mapper_path, mode, exe = sys.argv[1], sys.argv[2], sys.argv[3] +k = C.WinDLL("kernel32", use_last_error=True) +k.GetModuleHandleW.restype = C.c_void_p +k.GetModuleHandleW.argtypes = [W.LPCWSTR] +k.LoadLibraryW.restype = C.c_void_p +k.LoadLibraryW.argtypes = [W.LPCWSTR] +k.GetProcAddress.restype = C.c_void_p +k.GetProcAddress.argtypes = [C.c_void_p, C.c_char_p] +lib = C.WinDLL(mapper_path) +Resolver = C.WINFUNCTYPE(C.c_void_p, C.c_char_p, C.c_char_p, C.c_uint32) +lib.pe_map_image.restype = C.c_void_p +lib.pe_map_image.argtypes = [W.LPCWSTR, Resolver, C.POINTER(C.c_uint32), C.c_char_p, C.c_size_t] +for name in ("pe_map_run", "pe_map_run_main"): + getattr(lib, name).restype = C.c_int + getattr(lib, name).argtypes = [C.c_void_p, C.POINTER(C.c_uint32)] +lib.pe_map_release.restype = C.c_int +lib.pe_map_release.argtypes = [C.c_void_p] + +@Resolver +def resolve(dll, name, ordinal): + if dll.decode().casefold() != "kernel32.dll" or not name: + return None + return k.GetProcAddress(k.LoadLibraryW("kernel32.dll"), name) + +def map_image(path): + status, detail = C.c_uint32(), C.create_string_buffer(512) + base = lib.pe_map_image(path, resolve, C.byref(status), detail, len(detail)) + if not base: + sys.exit(f"pe_map_image refused {path}: {status.value} {detail.value!r}") + return base + +def start(run, base): + code = C.c_uint32() + started = run(base, C.byref(code)) + sys.stdout.flush() + return started, code.value + +host = k.GetModuleHandleW(None) +if mode in ("main", "plain"): + base = map_image(exe) + started, code = start(lib.pe_map_run_main if mode == "main" else lib.pe_map_run, base) + print(f"HOST: started={started} exit={code}", flush=True) + print(f"HOST: released={lib.pe_map_release(base)} restored={'y' if k.GetModuleHandleW(None) == host else 'n'}", flush=True) +elif mode == "twice": + first, second = map_image(exe), map_image(sys.argv[4]) + started, code = start(lib.pe_map_run_main, first) + print(f"HOST: first started={started} exit={code}", flush=True) + started, code = start(lib.pe_map_run_main, second) + print(f"HOST: second while first is the process image started={started}", flush=True) + print(f"HOST: first released={lib.pe_map_release(first)} restored={'y' if k.GetModuleHandleW(None) == host else 'n'}", flush=True) + started, code = start(lib.pe_map_run_main, second) + print(f"HOST: second started={started} exit={code}", flush=True) + print(f"HOST: second released={lib.pe_map_release(second)} restored={'y' if k.GetModuleHandleW(None) == host else 'n'}", flush=True) +""" + + +def logs(stdout): + return [line[4:].strip() for line in stdout.splitlines() if line.startswith("LOG:")] + + +def host_lines(stdout): + return [line[6:].strip() for line in stdout.splitlines() if line.startswith("HOST:")] + + +def expect(label, actual, expected): + if actual != expected: + raise AssertionError(f"{label}: expected {expected!r}, got {actual!r}") + + +def run_host(mapper, mode, *exes): + done = subprocess.run([sys.executable, "-B", "-c", HOST, str(mapper), mode, *map(str, exes)], + capture_output=True, text=True, timeout=TIMEOUT) + if done.returncode or done.stderr: + raise AssertionError(f"{mode} host failed: {done!r}") + return logs(done.stdout), host_lines(done.stdout) + + +def check(mapper, exe): + with TemporaryDirectory() as temp: + package = Path(temp) / "package" + other = Path(temp) / "other" + package.mkdir() + other.mkdir() + shutil.copyfile(exe, package / EXE) + shutil.copyfile(exe, other / EXE) + + native = subprocess.run([str(package / EXE)], capture_output=True, text=True, timeout=TIMEOUT) + expect("windows", (logs(native.stdout), native.returncode, native.stderr), ([EXPECTED], 0, "")) + print(f"windows: LOG:{EXPECTED} exit 0") + + done = subprocess.run([sys.executable, "-B", str(TOOL), str(mapper), str(package), EXE, + "--system", "kernel32.dll"], capture_output=True, text=True, timeout=TIMEOUT) + expect("runner stderr", (done.returncode, done.stderr), (0, "")) + expect("runner log", logs(done.stdout), [EXPECTED]) + expect("runner result", json.loads(done.stdout[done.stdout.index("{"):]), + {"image_order": [EXE], "entry_executed": True, "exit_code": 0}) + print(f"runner: LOG:{EXPECTED} exit 0, equal to the Windows launch") + + log, host = run_host(mapper, "main", package / EXE) + expect("main", (log, host), ([EXPECTED], ["started=1 exit=0", "released=1 restored=y"])) + print("main: guest log equals Windows; after release the host's GetModuleHandleW(NULL) is its own again") + + log, host = run_host(mapper, "plain", package / EXE) + if len(log) != 1 or not log[0].startswith("self=n hdr=n res=n "): + raise AssertionError(f"plain control: {log!r}") + expect("plain host", host, ["started=1 exit=" + log[0].rsplit("X=", 1)[1], "released=1 restored=y"]) + print(f"plain (control): pe_map_run leaves the host as the process image: LOG:{log[0]}") + + log, host = run_host(mapper, "twice", package / EXE, other / EXE) + expect("twice", (log, host), ([EXPECTED, EXPECTED], [ + "first started=1 exit=0", + "second while first is the process image started=0", + "first released=1 restored=y", + "second started=1 exit=0", + "second released=1 restored=y", + ])) + print("twice: a second main image is refused while the first is the process image, then starts after its release") + print("process image checks passed") + + +if __name__ == "__main__": + if len(sys.argv) != 3: + raise SystemExit("usage: process_image_check.py PE_MAP_DLL CPU_EXE_PROCESS_IMAGE") + check(Path(sys.argv[1]).resolve(strict=True), Path(sys.argv[2]).resolve(strict=True)) diff --git a/tools/pe_map.cpp b/tools/pe_map.cpp index 3f0e43dc5..e15327043 100644 --- a/tools/pe_map.cpp +++ b/tools/pe_map.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -746,6 +747,35 @@ MainImage& main_image() { // The main image's base while it is started, read without slot_lock by the notification path. std::uint8_t* volatile g_main_base = nullptr; +// Process image (pe_map_run_main). Under a Windows launch the EXE is the process image: the PEB's +// ImageBaseAddress holds its base, and GetModuleHandle(NULL), and with it FindResource(NULL, ...), return +// that base. pe_map_run_main makes the mapped EXE the process image in the same field until its accepted +// pe_map_release, which restores the host's value. Guarded by slot_lock. Only one image at a time; the +// PEB's loader list (GetModuleFileName(NULL), GetModuleHandleEx on an image address) is not changed. +struct ProcessImage { + std::uint8_t* base = nullptr; // the mapped EXE reported as the process image, or null + void* saved = nullptr; // the host's ImageBaseAddress, written back on release +}; +ProcessImage g_process_image; + +void* volatile* peb_image_base() { + // x64 PEB: ImageBaseAddress follows the four flag bytes and the Mutant handle. + return reinterpret_cast(__readgsqword(0x60) + 0x10); +} + +// Call with slot_lock held. +void report_process_image(std::uint8_t* base) { + g_process_image.saved = InterlockedExchangePointer(peb_image_base(), base); + g_process_image.base = base; +} + +// Call with slot_lock held. Restores the host's value only if base is the reported process image. +void restore_process_image(std::uint8_t* base) { + if (!base || g_process_image.base != base) return; + InterlockedExchangePointer(peb_image_base(), g_process_image.saved); + g_process_image = {}; +} + // Entries in main_image().enrolling that are not FREE, read without slot_lock by DLL_THREAD_ATTACH. An entry // becomes READY before its thread is resumed, so the thread itself always sees a nonzero count. volatile LONG g_enrolling = 0; @@ -1542,6 +1572,10 @@ extern "C" __declspec(dllexport) void* pe_map_export_resolved(void* mapped, cons // and the caller may retry later. extern "C" __declspec(dllexport) int pe_map_release(void* mapped) { if (!end_main(static_cast(mapped))) return 0; + { + const SlotLock hold; + restore_process_image(static_cast(mapped)); + } Mapped* record = nullptr; { const ExclusiveLock hold; @@ -1623,7 +1657,8 @@ extern "C" __declspec(dllexport) int pe_map_run(void* mapped, std::uint32_t* exi // CreateThread imports to it), and into that of host threads that call pe_map_main_thread_enter. Same preconditions and results as pe_map_run, and in addition returns 0 // without running anything when another image is started as the main image, when a participant of an // earlier one is still pending, or when pe_map's own TLS slots cannot be reserved. An image without a TLS -// template has no block to install and simply starts. +// template has no block to install and simply starts. Either way the image becomes the process image (see +// "Process image") before its process-attach callbacks, until its accepted pe_map_release. extern "C" __declspec(dllexport) int pe_map_run_main(void* mapped, std::uint32_t* exit_code) { auto* base = static_cast(mapped); const auto* nt = Image{base, 0}.headers(); @@ -1637,20 +1672,24 @@ extern "C" __declspec(dllexport) int pe_map_run_main(void* mapped, std::uint32_t for (auto* record : mapped_images()) if (record->base == base) carrier = record->carrier.module != nullptr; } - if (carrier) { + { const SlotLock hold; - auto& main = main_image(); - if (main.base || pending(main) || !reserve_slots()) return 0; - const auto& tls = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); - const auto* t = image.at(tls.VirtualAddress); - std::memcpy(&main.index, reinterpret_cast(t->AddressOfIndex), sizeof(main.index)); - main.base = base; - main.size = nt->OptionalHeader.SizeOfImage; - if (!install_current(main)) { - main.base = nullptr; - return 0; + if (g_process_image.base) return 0; // another image is the process image + if (carrier) { + auto& main = main_image(); + if (main.base || pending(main) || !reserve_slots()) return 0; + const auto& tls = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); + const auto* t = image.at(tls.VirtualAddress); + std::memcpy(&main.index, reinterpret_cast(t->AddressOfIndex), sizeof(main.index)); + main.base = base; + main.size = nt->OptionalHeader.SizeOfImage; + if (!install_current(main)) { + main.base = nullptr; + return 0; + } + g_main_base = base; } - g_main_base = base; + report_process_image(base); } return start_exe(base, nt, callbacks, exit_code); } From 8307e2e48d35226daca08db61bd723800ab3b3be Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Wed, 25 Nov 2026 22:20:06 +0800 Subject: [PATCH 021/232] tests: retire checked MRT refusal requests before the next pending scan (#2370) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- tests/startup_mrt_check.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/startup_mrt_check.py b/tests/startup_mrt_check.py index b58618566..5a2261567 100644 --- a/tests/startup_mrt_check.py +++ b/tests/startup_mrt_check.py @@ -113,10 +113,13 @@ def compile_pair(key): for narrow in REFUSED_INTEGER_FORMATS: line = f'rtv1 {gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes())} {narrow} 28' refused = f'{gfx2hlsl.fnv(line.encode("ascii")):016x}' - (cache / f'req_{refused}.rtv').write_text(line) + marker = cache / f'req_{refused}.rtv' + marker.write_text(line) result = gfx2hlsl.translate_request(cache, int(refused, 16)) - assert result.startswith('unsupported: unverified '), result + assert re.fullmatch(rf'unsupported: unverified (UINT|SINT) RTV format {narrow}', result), result assert not (cache / f'{refused}.txt').exists() + # Later --pending runs would retry this synthetic request on every valid format. + marker.unlink() print(f'{kind} {backend} narrow integer formats {REFUSED_INTEGER_FORMATS} refused at translation') # A pre-existing base translation may lack its original request files. base = f'{gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()):016x}' From c7f38d05e2b0a7e6790f5b8d77fd3523bd00f655 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Wed, 25 Nov 2026 22:20:21 +0800 Subject: [PATCH 022/232] shader: expand packed D16 XYZ stores into FLOAT3 heap views (#2372) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 10 ++-- tests/compute_heap_store_check.py | 79 +++++++++++++++++++++++++------ tools/compute_store_aot.py | 13 +++-- 3 files changed, 81 insertions(+), 21 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 987e2232d..984d9a039 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5814,14 +5814,18 @@ Run `ctest --preset dev -R '^compute_(heap_store_controls|store_aot_heap_view_st -### Packed D16 heap-view stores to FLOAT1, FLOAT2 and FLOAT4 + -With the same `--heap-store-view` binding, gfx1013 `buffer_store_format_d16_xyzw` reads X/Y from the low/high halves of the first VGPR and Z/W from the second. A live identity `BUF_FMT_32_32_32_32_FLOAT` view (format 77) receives four binary32 words. Two source VGPRs still require 16 writable bytes in the destination. `buffer_store_format_d16_x` takes one source VGPR, converts its low 16 bits (`& 0xffffu`) via `f16tof32`, and writes one 4-byte binary32 word into a live identity `BUF_FMT_32_FLOAT` view (format 22, `0x01016fac`), enforcing 4-byte offset/stride/base alignment and `(bytes - view.x - offset - 4u) / stride` bounds without a raw UAV read-modify-write. A view whose format differs from the required component count or numeric type leaves the output untouched. The packed three-component `d16_xyz` form is refused. [AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [HLSL half-to-float conversion](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/f16tof32) +### Packed D16 heap-view stores -The heap-store CTest selection above runs all four programs (`UINT4`, `D16-to-FLOAT4`, `D16_X-to-FLOAT1` and `D16_XY-to-FLOAT2`). Each D16 fixture checks 320 words across its heap-view cases (with `D16_X` additionally checking four binary16 payload patterns with poisoned high halves: `1.0`..`1.00293`, `-2.0`.., minimum positive subnormal + `+0.0`, and `-0.0` + negative subnormals, plus `UINT1` and `FLOAT4` mismatch rejections and untouched adjacent sentinel dwords). Eleven compiled shader mutations check addressing, view selection, and half-float extraction, including swapping high for low bits, checking the wrong format word, and writing packed values directly. +With the same `--heap-store-view` binding, gfx1013 `buffer_store_format_d16_xyzw` reads X/Y from the low/high halves of the first VGPR and Z/W from the second. A live identity `BUF_FMT_32_32_32_32_FLOAT` view (format 77) receives four binary32 words. Two source VGPRs still require 16 writable bytes in the destination. `buffer_store_format_d16_x` takes one source VGPR, converts its low 16 bits (`& 0xffffu`) via `f16tof32`, and writes one 4-byte binary32 word into a live identity `BUF_FMT_32_FLOAT` view (format 22, `0x01016fac`), enforcing 4-byte offset/stride/base alignment and `(bytes - view.x - offset - 4u) / stride` bounds without a raw UAV read-modify-write. A view whose format differs from the required component count or numeric type leaves the output untouched. [AMD RDNA 2 instruction set](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) · [HLSL half-to-float conversion](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/f16tof32) + +The heap-store CTest selection above runs the UINT4 program and all four packed D16 widths. Each D16 fixture checks 320 words across its heap-view cases (with `D16_X` additionally checking four binary16 payload patterns with poisoned high halves: `1.0`..`1.00293`, `-2.0`.., minimum positive subnormal + `+0.0`, and `-0.0` + negative subnormals, plus `UINT1` and `FLOAT4` mismatch rejections and untouched adjacent sentinel dwords). Eleven compiled shader mutations check addressing, view selection, and half-float extraction, including swapping high for low bits, checking the wrong format word, and writing packed values directly. For `buffer_store_format_d16_xy`, the low and high halves of one VGPR become X and Y of an identity `BUF_FMT_32_32_FLOAT` view (format 64, `0x01040fac`). One `Store2` writes the two binary32 values. With a 512-byte u0 and an instruction offset of four, a base of 500 writes words 126 and 127. A base of 504 leaves all 320 readback words untouched. The fixture also checks negative zero, the smallest positive binary16 subnormal and −2.0 in Y. Swapping the halves, duplicating X into Y and admitting a partial element must each produce its own first mismatched word. +With `buffer_store_format_d16_xyz`, X and Y come from the first VGPR and Z comes from the low half of the second. A live identity `BUF_FMT_32_32_32_FLOAT` view (format 74, `0x0104afac`) receives three 32-bit float words. The readback changes the unused high half independently and checks the guard immediately after Z. With a four-byte instruction offset and a 512-byte limit, base 496 writes words 125–127 and base 500 leaves every word untouched. The fixture also checks that two- and four-channel FLOAT views and a three-channel UINT view leave u0 unchanged. + ### Heap-view buffer loads The gfx1013 compute store profile can now take the t0 V# of a `buffer_load_format_x/xy/xyz/xyzw` from a run-time view record instead of a static descriptor. `--heap-view SLOT_WORD TABLE_OFFSET COUNT BUFFER_BYTES` selects it. It is slice 2 of item A of #2022 and builds on the format decoder of [descriptor-format buffer loads](#descriptor-format-buffer-loads). It excludes `--load-format-constant`: the format now comes from the record. diff --git a/tests/compute_heap_store_check.py b/tests/compute_heap_store_check.py index b5d1aa543..21e8906b7 100644 --- a/tests/compute_heap_store_check.py +++ b/tests/compute_heap_store_check.py @@ -14,6 +14,8 @@ FLOAT1 = 0x01016FAC # gfx10 format 22 (BUF_FMT_32_FLOAT), identity selectors and RESOURCE_LEVEL set UINT1 = 0x01014FAC # gfx10 format 20 (BUF_FMT_32_UINT) FLOAT2 = 0x01040FAC # gfx10 format 64 (BUF_FMT_32_32_FLOAT) +FLOAT3 = 0x0104AFAC # gfx10 format 74 (BUF_FMT_32_32_32_FLOAT) +UINT3 = 0x01048FAC # gfx10 format 72 (BUF_FMT_32_32_32_UINT) UINT4 = 0x0104BFAC # gfx10 format 75, identity XYZW selectors and RESOURCE_LEVEL set FLOAT4 = 0x0104DFAC STORE = "buffer_store_format_xyzw v[10:13], v8, s[20:23], 0 idxen offset:4" @@ -36,6 +38,9 @@ ] D16_XY_STORE = D16_X_STORE.replace("d16_x ", "d16_xy ") D16_XY_PROGRAM = base.variant(D16_X_PROGRAM, (D16_X_STORE, D16_XY_STORE)) +D16_XYZ_STORE = D16_STORE.replace("d16_xyzw", "d16_xyz") +D16_XYZ_PROGRAM = base.variant(D16_PROGRAM, (D16_STORE, D16_XYZ_STORE), + ("v_mov_b32_e32 v11, 0x80000001", "v_mov_b32_e32 v11, s25")) # 0x3c00..0x3c03 are consecutive binary16 values starting at 1.0. D16_X = (0x3f800000, 0x3f802000, 0x3f804000, 0x3f806000) # High half 0x4200 poisons each word so leaking high bits or missing & 0xffffu shifts fails readback. @@ -92,6 +97,21 @@ ("base past the declared extent", (640, 12 << 16, 4, FLOAT2, 1), ()), ("live slot beyond the declared count", (12, 12 << 16, 4, FLOAT2, 1), ()), ) +# Each accepted three-dword texel has an adjacent guard, including the one at the declared u0 limit. +D16_XYZ_CASES = ( + ("four float3 records", (12, 16 << 16, 4, FLOAT3, 1), (4, 8, 12, 16)), + ("second base and short count", (116, 20 << 16, 2, FLOAT3, 1), (30, 35)), + ("released view", (12, 16 << 16, 4, FLOAT3, 2), ()), + ("last complete float3", (496, 16 << 16, 4, FLOAT3, 1), (125,)), + ("only eight bytes left", (500, 16 << 16, 4, FLOAT3, 1), ()), + ("wrong UINT3 format", (12, 16 << 16, 4, UINT3, 1), ()), + ("short stride", (12, 12 << 16, 4, FLOAT3, 1), ()), + ("misaligned base", (14, 16 << 16, 4, FLOAT3, 1), ()), + ("misaligned stride", (12, 18 << 16, 4, FLOAT3, 1), ()), + ("unsupported high address", (12, (16 << 16) | 1, 4, FLOAT3, 1), ()), + ("base past the declared extent", (640, 16 << 16, 4, FLOAT3, 1), ()), + ("live slot beyond the declared count", (12, 16 << 16, 4, FLOAT3, 1), ()), +) BINDING = dict(table_reg=7, descriptor_offset=0x30, constant_descriptor=0x40, source_descriptor=0x50, group_reg=11) @@ -104,6 +124,8 @@ def controls(): assert base.aot.descriptor_format_word(22) == FLOAT1 assert base.aot.descriptor_format_word(20) == UINT1 assert base.aot.descriptor_format_word(64) == FLOAT2 + assert base.aot.descriptor_format_word(74) == FLOAT3 + assert base.aot.descriptor_format_word(72) == UINT3 # Pin the translator call here. draw() exercises the generated guards against actual UAV contents. assert "store_heap_words4(params[0].x, tid.x, 4u, false, uint4(tid.x," in lower() assert "store_heap_words4(params[0].x, tid.x, 4u, true," in lower(D16_PROGRAM) @@ -129,8 +151,13 @@ def controls(): refuses("Unverified ALU operand", lower, D16_X_PROGRAM[:7] + D16_X_PROGRAM[8:]) refuses("Heap store view requires buffer_store_format_xyzw", lower, base.variant(PROGRAM, (STORE, STORE.replace("xyzw v[10:13]", "xy v[10:11]")))) + xyz = lower(D16_XYZ_PROGRAM) + assert f"{FLOAT3:#x}u" in xyz and "outputData.Store3(" in xyz and "outputData.Load(" not in xyz + for registers in ("v10", "v[10:12]"): + refuses("Unverified raw UAV store", lower, + base.variant(D16_XYZ_PROGRAM, (D16_XYZ_STORE, D16_XYZ_STORE.replace("v[10:11]", registers)))) refuses("Heap store view requires buffer_store_format_xyzw", lower, - base.variant(D16_PROGRAM, (D16_STORE, D16_STORE.replace("d16_xyzw", "d16_xyz")))) + base.variant(PROGRAM, (STORE, STORE.replace("xyzw v[10:13]", "xyz v[10:12]")))) xy = lower(D16_XY_PROGRAM) assert f"{FLOAT2:#x}u" in xy and "outputData.Store2(" in xy and "outputData.Load(" not in xy refuses("Unverified raw UAV store", lower, @@ -166,8 +193,9 @@ def verify_binary(directory, code, library, program=PROGRAM): def draw(directory, compiler, renderer, backend, mode): - program = {"uint4": PROGRAM, "d16_xyzw": D16_PROGRAM, "d16_x": D16_X_PROGRAM, "d16_xy": D16_XY_PROGRAM}[mode] - cases = {"d16_x": D16_X_CASES, "d16_xy": D16_XY_CASES}.get(mode, CASES) + program = {"uint4": PROGRAM, "d16_xyzw": D16_PROGRAM, "d16_x": D16_X_PROGRAM, + "d16_xy": D16_XY_PROGRAM, "d16_xyz": D16_XYZ_PROGRAM}[mode] + cases = {"d16_x": D16_X_CASES, "d16_xy": D16_XY_CASES, "d16_xyz": D16_XYZ_CASES}.get(mode, CASES) source = lower(program) table = [0] * WORDS for slot, (_, record, _) in enumerate(cases): @@ -181,13 +209,18 @@ def compile_shader(text): hlsl.write_text(text, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) - def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table, expected_y=0x40400000): + default_payload = 0x42000001 if mode == "d16_xyz" else D16_X_PAYLOADS[0][1] + + def run(slot, payload=default_payload, expected_x=D16_X, table_words=table, expected_y=0x40400000, + expected_z=0x33800000): result = [base.SENTINEL] * WORDS for thread, start in enumerate(cases[slot][2]): if mode == "d16_x": result[start] = expected_x[thread] elif mode == "d16_xy": result[start:start + 2] = [expected_x[thread], expected_y] + elif mode == "d16_xyz": + result[start:start + 3] = [D16_X[thread], 0xc0000000, expected_z] elif mode == "d16_xyzw": # D16 y, z, w are -2, the smallest positive binary16 subnormal, and negative zero. result[start:start + 4] = [D16_X[thread], 0xc0000000, 0x33800000, 0x80000000] @@ -224,15 +257,22 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table, result = run(0, payload=payload, expected_y=expected_y) assert result.returncode == 0, (hex(payload), result.stderr) extra += 1 - for wrong_format in (FLOAT4, base.aot.descriptor_format_word(62)): # UINT2 - wrong_view = table.copy() - wrong_view[TABLE_BYTE // 4 + 5 * 8 + 3] = wrong_format - result = run(5, table_words=wrong_view) - assert result.returncode == 0, (hex(wrong_format), result.stderr) + elif mode == "d16_xyz": + for payload, z in ((0x7e010001, 0x33800000), (0x3c008000, 0x80000000), (0x4200c000, 0xc0000000)): + result = run(0, payload=payload, expected_z=z) + assert result.returncode == 0, (hex(payload), result.stderr) extra += 1 - width_str = {"d16_x": "4u", "d16_xy": "8u"}.get(mode, "16u") - format_guard = {"d16_x": f"{FLOAT1:#x}u", "d16_xy": f"{FLOAT2:#x}u"}.get(mode, "formatWord") - wrong_stride = {"d16_x": 8, "d16_xy": 12}.get(mode, 24) + mismatched_formats = {"d16_xy": (FLOAT4, base.aot.descriptor_format_word(62)), "d16_xyz": (FLOAT2, FLOAT4)} + for wrong_format in mismatched_formats.get(mode, ()): + wrong_view = table.copy() + wrong_view[TABLE_BYTE // 4 + 5 * 8 + 3] = wrong_format + result = run(5, table_words=wrong_view) + assert result.returncode == 0, (hex(wrong_format), result.stderr) + extra += 1 + width_str = {"d16_x": "4u", "d16_xy": "8u", "d16_xyz": "12u"}.get(mode, "16u") + format_guard = {"d16_x": f"{FLOAT1:#x}u", "d16_xy": f"{FLOAT2:#x}u", + "d16_xyz": f"{FLOAT3:#x}u"}.get(mode, "formatWord") + wrong_stride = {"d16_x": 8, "d16_xy": 12, "d16_xyz": 16}.get(mode, 24) mutations = ( ("view.x + index * stride + offset", "index * stride + offset", 0), (" || index >= view.z", "", 1), @@ -263,6 +303,15 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table, ("offset + 8u > bytes - view.x", "offset + 4u > bytes - view.x", 4, "word=127 expected=c5c5c5c5 actual=3f800000"), ) + elif mode == "d16_xyz": + mutations += ( + ("value.y & 0xffffu", "value.y >> 16u", 0, "word=6 expected=33800000 actual=40400000"), + ("Store3(view.x + index * stride + offset, asuint(f16tof32(halfWords)))", + "Store4(view.x + index * stride + offset, uint4(asuint(f16tof32(halfWords)), 0u))", 0, + "word=7 expected=c5c5c5c5 actual=00000000"), + ("offset + 12u > bytes - view.x", "offset + 8u > bytes - view.x", 4, + "word=126 expected=c5c5c5c5 actual=3f800000"), + ) for old, new, slot, *first_mismatch in mutations: assert source.count(old) == 1, old compile_shader(source.replace(old, new)) @@ -272,7 +321,7 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table, words = [line for line in result.stderr.splitlines() if line.startswith("word=")] assert words[:1] == first_mismatch, (old, result.stderr) kind = {"uint4": "UINT4", "d16_xyzw": "D16-to-FLOAT4", "d16_x": "D16_X-to-FLOAT1", - "d16_xy": "D16_XY-to-FLOAT2"}[mode] + "d16_xy": "D16_XY-to-FLOAT2", "d16_xyz": "D16_XYZ-to-FLOAT3"}[mode] print(f"{backend} {kind}: {len(cases) + extra} heap-store cases and {len(mutations)} shader mutations checked") return 0 @@ -286,13 +335,13 @@ def run(slot, payload=D16_X_PAYLOADS[0][1], expected_x=D16_X, table_words=table, with tempfile.TemporaryDirectory() as tmp: directory = Path(tmp) if mode == "draw": - for kind in ("uint4", "d16_xyzw", "d16_x", "d16_xy"): + for kind in ("uint4", "d16_xyzw", "d16_x", "d16_xy", "d16_xyz"): result = draw(directory, *args, kind) if result: sys.exit(result) sys.exit(0) assembler, objcopy, library = args - for program in (PROGRAM, D16_PROGRAM, D16_X_PROGRAM, D16_XY_PROGRAM): + for program in (PROGRAM, D16_PROGRAM, D16_X_PROGRAM, D16_XY_PROGRAM, D16_XYZ_PROGRAM): code = base.assemble(directory, assembler, objcopy, program, cpu="gfx1013") verify_binary(directory, code, library, program) else: diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 5cd2b4435..597071db1 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -716,6 +716,11 @@ def heap_store_view_hlsl(table_offset, view_count, output_bytes, *, components=4 else: write = (" outputData.Store2(view.x + index * stride + offset, " "asuint(f16tof32(uint2(value & 0xffffu, value >> 16u))));") + elif components == 3: + sig = "void store_heap_xyz_d16(uint slot, uint index, uint offset, uint2 value)" + fmt_check = f" if (view.w != {descriptor_format_word(74):#x}u || (view.y & 0xc000ffffu) != 0u) return;" + write = (" uint3 halfWords = uint3(value.x & 0xffffu, value.x >> 16u, value.y & 0xffffu);\n" + " outputData.Store3(view.x + index * stride + offset, asuint(f16tof32(halfWords)));") else: sig = "void store_heap_words4(uint slot, uint index, uint offset, bool d16, uint4 value)" fmt_check = (f" uint formatWord = d16 ? {descriptor_format_word(77):#x}u : {descriptor_format_word(75):#x}u;\n" @@ -2738,8 +2743,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if not idxen or offen: raise ValueError("Unsupported formatted buffer store target or address mode") if heap_store_view is not None: - if channels not in ("xyzw", "d16_xyzw", "d16_xy", "d16_x"): - raise ValueError("Heap store view requires buffer_store_format_xyzw or a D16 x, xy or xyzw store") + if channels != "xyzw" and not packed: + raise ValueError("Heap store view requires buffer_store_format_xyzw or a D16 formatted store") if not any(tag == ("constant_word", heap_slot_word) and reg not in pending for reg, tag in scalar.items()): raise ValueError("Heap store view slot constant is not ready") @@ -2873,6 +2878,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N heap_store_components = components if channels in ("d16_x", "d16_xy"): stores.append(f" store_heap_word_d16({slot}, {address}, {offset}u, {words[0]});") + elif channels == "d16_xyz": + stores.append(f" store_heap_xyz_d16({slot}, {address}, {offset}u, uint2({', '.join(words)}));") else: supplied = words + ["0u"] * (4 - len(words)) mode = "true" if packed else "false" @@ -3003,7 +3010,7 @@ def main(): "SLOT_WORD; the record table is at byte TABLE_OFFSET of the BUFFER_BYTES-byte t0 and holds COUNT views") parser.add_argument("--heap-store-view", nargs=5, type=lambda n: int(n, 0), metavar=("SLOT_WORD", "TABLE_OFFSET", "COUNT", "TABLE_BUFFER_BYTES", "OUTPUT_BYTES"), - help="select a UINT4 or expanded D16 FLOAT1/FLOAT2/FLOAT4 store view from t0 " + help="select a UINT4 or expanded D16 FLOAT1/FLOAT2/FLOAT3/FLOAT4 store view from t0 " "and bound writes by OUTPUT_BYTES of u0") parser.add_argument("--mubuf-d16-xyz-mode", choices=("preserve-w",), help="Experimental RGBA16 UINT store with caller-verified preservation of W") From 933307f427d358beb5bcad5cd29ee54adff29005 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:22:47 +0100 Subject: [PATCH 023/232] tests: run compute load-format draw cases concurrently (#2355) * tests: run compute load-format draw cases on a small thread pool * tests: keep the renderer output of passing load-format dispatches in the log --- tests/compute_load_format_check.py | 85 +++++++++++++++++++----------- 1 file changed, 53 insertions(+), 32 deletions(-) diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index e3e595cc0..f975fd1bd 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -3,7 +3,9 @@ The t0 format is V# word 3, read from a constant word at run time (--load-format-constant), as the descriptor-format stores read theirs. The case file supplies the t0 words, so each format sees chosen edge values. """ +from concurrent.futures import ThreadPoolExecutor from fractions import Fraction +import os from pathlib import Path import struct import subprocess @@ -308,22 +310,37 @@ def binary(directory, assembler, objcopy, library): def draw(directory, compiler, renderer, backend): - """Dispatch with chosen t0 words; wrong references and mutated sources must fail.""" - src, cso, case = [directory / x for x in ("load.hlsl", "load.cso", "load.case")] + """Dispatch with chosen t0 words; wrong references and mutated sources must fail. + + Every case owns its case and cso files, so the launches run on a small thread pool. Results are + checked afterwards in the original order with the original messages. + """ + src, cso = directory / "load.hlsl", directory / "load.cso" source = lower() src.write_text(source, encoding="ascii") subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src], check=True) - cmd = [renderer, backend, "--compute-store-case", cso, case] words = source_words() - - def write(groups, reference, formats=None): - case.write_bytes(struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) - + struct.pack("<320I", *words)) + jobs = [] # (check, label, extra, case bytes, shader, mutated source or None) + + def add(check, label, groups, reference, formats=None, extra=None, mutated=None): + data = (struct.pack("<321I", groups, *reference) + struct.pack("<16I", *(formats or constants())) + + struct.pack("<320I", *words)) + jobs.append((check, label, extra, data, mutated)) + + def run(number, job): + _check, _label, _extra, data, mutated = job + case, shader = directory / f"case{number}.bin", cso + case.write_bytes(data) + if mutated is not None: + shader = directory / f"mutated{number}.cso" + bad_src = directory / f"mutated{number}.hlsl" + bad_src.write_text(mutated, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", shader, bad_src], check=True) + return subprocess.run([renderer, backend, "--compute-store-case", shader, case], + capture_output=True, text=True) for groups in (1, 2): - write(groups, expected_words(groups)) - if subprocess.run(cmd).returncode: - return 1 + add("pass", "dispatch", groups, expected_words(groups)) def invalid_formats(number): formats = constants() @@ -335,44 +352,48 @@ def invalid_formats(number): unwritten = [base.SENTINEL] * 320 zeros = (lambda channels: (lambda words: [0] * channels)) for number, (label, index, _word) in enumerate(INVALID): - print(f"{NAME}: refused {label}", flush=True) - write(2, unwritten, invalid_formats(number)) - if subprocess.run(cmd).returncode: - return 1 + add("pass", f"refused {label}", 2, unwritten, invalid_formats(number)) channels = len(LOADS[index][0]) placeholders = [("published as zeros", zeros(channels))] if number == 2: placeholders.append(("published with the (0, 0, 0, 1) fill", lambda words: [words[0], 0])) for what, values in placeholders: published = expected_words(2, placeholder=(index, values)) - write(2, published, invalid_formats(number)) - bad = subprocess.run(cmd, capture_output=True, text=True) - if bad.returncode != 1 or f"word=0 expected={published[0]:08x} actual=c5c5c5c5" not in bad.stderr: - raise AssertionError(f"{NAME}: {label} {what} escaped detection\n{bad.stderr}") + add("placeholder", f"{label} {what}", 2, published, invalid_formats(number), + extra=f"word=0 expected={published[0]:08x} actual=c5c5c5c5") expected = expected_words(2) for label, wrong in WRONG: reference = expected_words(2, wrong=wrong) word = next((i for i, (a, b) in enumerate(zip(expected, reference)) if a != b), None) if word is None: raise AssertionError(f"{NAME}: reference '{label}' matches the expected words") - write(2, reference) - bad = subprocess.run(cmd, capture_output=True, text=True) - if bad.returncode != 1 or f"word={word} expected=" not in bad.stderr: - raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{bad.stderr}") - for label, old, new, run in MUTATIONS: + add("wrong", label, 2, reference, extra=f"word={word} expected=") + for label, old, new, run_index in MUTATIONS: mutated = source.replace(old, new, 1) if mutated == source: raise AssertionError(f"{NAME}: mutation '{label}' did not change the source") - if run is None: - write(2, expected) + if run_index is None: + add("mutation", label, 2, expected, mutated=mutated) else: - write(2, unwritten, invalid_formats(run)) - bad_src, bad_cso = directory / "mutated.hlsl", directory / "mutated.cso" - bad_src.write_text(mutated, encoding="ascii") - subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", bad_cso, bad_src], check=True) - bad = subprocess.run([*cmd[:3], bad_cso, case], capture_output=True, text=True) - if bad.returncode != 1 or "Compute readback differs" not in bad.stderr: - raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{bad.stderr}") + add("mutation", label, 2, unwritten, invalid_formats(run_index), mutated=mutated) + + with ThreadPoolExecutor(max_workers=min(4, os.cpu_count() or 1)) as pool: + results = list(pool.map(lambda item: run(*item), enumerate(jobs))) + for (check, label, extra, _data, _mutated), result in zip(jobs, results): + if check == "pass": + print(f"{NAME}: {label}", flush=True) + sys.stdout.write(result.stdout) + if result.returncode: + sys.stderr.write(result.stderr) + return 1 + elif check == "placeholder": + if result.returncode != 1 or extra not in result.stderr: + raise AssertionError(f"{NAME}: {label} escaped detection\n{result.stderr}") + elif check == "wrong": + if result.returncode != 1 or extra not in result.stderr: + raise AssertionError(f"{NAME}: reference '{label}' escaped detection\n{result.stderr}") + elif result.returncode != 1 or "Compute readback differs" not in result.stderr: + raise AssertionError(f"{NAME}: mutation '{label}' escaped detection\n{result.stderr}") print(f"{NAME}: {2 + len(INVALID)} dispatches, {len(WRONG) + len(INVALID) + 1} wrong references and " f"{len(MUTATIONS)} mutated sources checked") return 0 From a8279258cbf89fa5b074e23739f424dc65244cff Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:23:41 +0200 Subject: [PATCH 024/232] pe: harden atomic temp cleanup and error paths in intake_exe with unit and CLI suite (#2358) * pe: harden atomic temp cleanup and error paths in intake_exe with unit and CLI suite * pe: document inside() root normalization and expand path refusal table --- CMakeLists.txt | 2 + tests/intake_exe_check.py | 485 ++++++++++++++++++++++++++++++++++++++ tools/intake_exe.py | 40 +++- 3 files changed, 516 insertions(+), 11 deletions(-) create mode 100644 tests/intake_exe_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cc12f7a47..8e9ac75a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9092,6 +9092,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pe_run_package_invalid_check.py") add_test(NAME pe_run_package_plan_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_run_package_plan_check.py") + add_test(NAME pe_intake_checks COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/intake_exe_check.py") add_test(NAME pe_host_commit_preflight COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/host_commit_check.py") add_test(NAME xgameruntime_preflight_stub_refused COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/intake_exe_check.py b/tests/intake_exe_check.py new file mode 100644 index 000000000..acabb43f2 --- /dev/null +++ b/tests/intake_exe_check.py @@ -0,0 +1,485 @@ +"""Pure-Python unit and CLI hardening suite for tools/intake_exe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +import pefile + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "intake_exe.py" +sys.path.insert(0, str(ROOT / "tools")) + +import intake_exe # noqa: E402 +from pe_inventory import import_tables # noqa: E402 + + +IMAGE_BASE = 0x180000000 +TEXT_RVA = 0x1000 +TEXT_RAW = 0x400 +TEXT_SIZE = 0x200 +RDATA_RVA = 0x2000 +RDATA_RAW = 0x600 +RDATA_SIZE = 0x1000 +ENTRY_RVA = TEXT_RVA + 0x10 +TLS_CB_RVA = TEXT_RVA + 0x40 +UNWIND_RVA = TEXT_RVA + 0x100 +CALLER = "main.exe" + + +def _build_pe( + *, + imports: list[tuple[str, str, str]] = ( + ("normal", "xmem.dll", "XMemAlloc"), + ("normal", "kernel32.dll", "ExitProcess"), + ), + include_tls: bool = True, + pdata_records: list[tuple[int, int, int]] | None = ((TEXT_RVA, TEXT_RVA + 0x30, UNWIND_RVA), (TEXT_RVA + 0x30, TEXT_RVA + 0x80, UNWIND_RVA)), + pdata_size_override: int | None = None, + machine: int = 0x8664, + magic: int = 0x20B, + characteristics: int = 0x0022, + entry_rva: int = ENTRY_RVA, + truncate_bytes: int = 0, +) -> bytes: + """Build a minimal synthetic PE32+ image with .text, .rdata imports, TLS, and .pdata.""" + rdata = bytearray(RDATA_SIZE) + cursor = 0 + + def alloc(size: int, align: int = 4) -> int: + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = RDATA_RVA + cursor + if cursor + size > len(rdata): + raise AssertionError("synthetic .rdata overflow") + cursor += size + return rva + + def put(rva: int, blob: bytes) -> None: + offset = rva - RDATA_RVA + rdata[offset:offset + len(blob)] = blob + + module_rvas = {} + for module in sorted({m for _, m, _ in imports}): + raw = module.encode("ascii") + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + module_rvas[module] = rva + + hint_rvas = {} + for kind, module, symbol in imports: + raw = struct.pack("', + encoding="utf-8", + ) + (root / "layout.xml").write_text( + '', + encoding="utf-8", + ) + torrent_bytes = b"synthetic-torrent-payload" + (root / "package.torrent").write_bytes(torrent_bytes) + integrity = tmp / "integrity.json" + integrity.write_text( + json.dumps( + { + "directory": root.name, + "torrent_payload_passed": True, + "torrent": "package.torrent", + "torrent_sha256": hashlib.sha256(torrent_bytes).hexdigest(), + "layout": {"source": "layout.xml", "absent_from_torrent": {CALLER: ["1001"]}}, + "pieces": {"matched": 1}, + "finished_utc": "2026-01-01T00:00:00+00:00", + } + ), + encoding="utf-8", + ) + baseline = tmp / "baseline.json" + baseline.write_text(json.dumps({"schema": 1, "images": {}, "imports": [], "unresolved_edges": []}), encoding="utf-8") + if write_candidate: + (root / CALLER).write_bytes(pe_bytes if pe_bytes is not None else _build_pe()) + return root, baseline, integrity + + +def _fake_scan_for(expected_root: Path, image_bytes: bytes): + with pefile.PE(data=image_bytes, fast_load=True) as pe: + imports = import_tables(pe, CALLER) + digest = hashlib.sha256(image_bytes).hexdigest() + rows = [ + { + "image": CALLER, + "kind": kind, + "dll": dll, + "symbol": symbol, + "bundle_exports_in": [], + "desktop_provider": None, + "desktop_export": "provider_not_found", + "desktop_candidate": None, + "desktop_resolution": { + "status": "provider_not_found", + "chain": [{"dll": dll, "provider": None, "symbol": symbol}], + }, + "package_resolution": None, + } + for kind, dll, symbol in imports + ] + inventory = { + "schema": 1, + "images": {CALLER: {"sha256": digest, "exports": []}}, + "imports": rows, + "unresolved_edges": [dict(r) for r in rows], + "summary": {"images": 1, "edges": len(rows)}, + } + + def fake_scan(package, *, extra_image=None, system=None): + assert package == expected_root + return json.loads(json.dumps(inventory)) + + return fake_scan + + +class IntakeExeUnitTests(unittest.TestCase): + def test_inside_rejects_traversal_root_and_absolute_paths(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "pkg" + (root / "sub").mkdir(parents=True) + sub = root / "bin" / "main.exe" + self.assertEqual(intake_exe.inside(root, "bin/main.exe"), sub.resolve()) + # Unnormalized root containing '..' must still accept valid relative package paths. + self.assertEqual(intake_exe.inside(root / "sub" / "..", "bin/main.exe"), sub.resolve()) + # Pin each refusal reason explicitly (POSIX/drive/UNC absolute, traversal, root itself, empty). + cases = ( + ("absolute_posix", "/etc/passwd"), + ("absolute_drive", "C:/Windows/win.ini"), + ("absolute_unc", "\\\\server\\share\\x"), + ("escape_parent", "../escape.txt"), + ("escape_nested", "bin/../../escape"), + ("root_dot", "."), + ("empty", ""), + ) + for reason, bad in cases: + with self.subTest(reason=reason, bad=bad), self.assertRaisesRegex(ValueError, "Invalid package path"): + intake_exe.inside(root, bad) + + def test_import_routes_and_routing_failures(self): + pe_bytes = _build_pe( + imports=[ + ("normal", "xmem.dll", "XMemAlloc"), + ("normal", "kernel32.dll", "ExitProcess"), + ("delay", "xgameruntime.dll", "XUserGetId"), + ("normal", "mystery.dll", "MissingExport"), + ] + ) + rows = intake_exe.import_routes(pe_bytes, CALLER) + by_dll = {r["dll"]: r for r in rows} + self.assertEqual(by_dll["xmem.dll"]["route"], "hle") + self.assertEqual(by_dll["kernel32.dll"]["route"], "windows") + self.assertEqual(by_dll["xgameruntime.dll"]["route"], "stub") + self.assertEqual(by_dll["mystery.dll"]["route"], "unsupported") + failed = intake_exe.routing_failures(rows) + self.assertEqual([(r["dll"], r["symbol"]) for r in failed], [("mystery.dll", "MissingExport")]) + + def test_inspect_executable_tls_pdata_and_malformed_controls(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid = root / "valid.exe" + valid.write_bytes(_build_pe()) + info = intake_exe.inspect_executable(valid) + self.assertEqual(info["machine"], "AMD64") + self.assertEqual(info["format"], "PE32+") + self.assertEqual(info["entry_rva"], ENTRY_RVA) + self.assertEqual(info["entry_section"], ".text") + self.assertEqual(info["tls"]["callbacks_rva"], [TLS_CB_RVA]) + startup = info["startup"] + self.assertEqual(startup["exception_table"], "indexed") + self.assertEqual(startup["runtime_functions"], 2) + self.assertEqual([loc["role"] for loc in startup["locations"]], ["tls_callback", "entry"]) + self.assertEqual(startup["locations"][0]["runtime_function"]["begin_rva"], TEXT_RVA + 0x30) + self.assertEqual(startup["locations"][1]["runtime_function"]["begin_rva"], TEXT_RVA) + + # Absent .pdata -> exception_table == "absent", runtime_function is None. + no_pdata = root / "no_pdata.exe" + no_pdata.write_bytes(_build_pe(pdata_records=None, include_tls=False)) + no_pdata_info = intake_exe.inspect_executable(no_pdata) + self.assertEqual(no_pdata_info["startup"]["exception_table"], "absent") + self.assertIsNone(no_pdata_info["startup"]["locations"][0]["runtime_function"]) + + # Misaligned and overlapping .pdata fall back cleanly to exception_table == "unusable". + misaligned = root / "misaligned_pdata.exe" + misaligned.write_bytes(_build_pe(pdata_size_override=10)) + self.assertEqual(intake_exe.inspect_executable(misaligned)["startup"]["exception_table"], "unusable") + + overlapping = root / "overlap_pdata.exe" + overlapping.write_bytes( + _build_pe(pdata_records=[(TEXT_RVA, TEXT_RVA + 0x50, UNWIND_RVA), (TEXT_RVA + 0x40, TEXT_RVA + 0x80, UNWIND_RVA)]) + ) + overlap_startup = intake_exe.inspect_executable(overlapping)["startup"] + self.assertEqual(overlap_startup["exception_table"], "unusable") + self.assertIn("Invalid or overlapping", overlap_startup["detail"]) + + # Non-x64, DLL, and truncated sections are rejected with ValueError. + for label, pe_kwargs in ( + ("non_x64", {"machine": 0x014C, "magic": 0x10B}), + ("dll", {"characteristics": 0x2022}), + ("truncated_section", {"truncate_bytes": 128}), + ): + with self.subTest(case=label): + bad = root / f"{label}.exe" + bad.write_bytes(_build_pe(**pe_kwargs)) + with self.assertRaises(ValueError): + intake_exe.inspect_executable(bad) + + +class IntakeExeCliTests(unittest.TestCase): + def _run_main(self, argv: list[str]) -> tuple[int, str, str]: + out = io.StringIO() + err = io.StringIO() + with redirect_stdout(out), redirect_stderr(err): + rc = intake_exe.main(argv) + return rc, out.getvalue(), err.getvalue() + + def test_collect_and_main_awaiting_inspected_and_require_routing(self): + with tempfile.TemporaryDirectory() as tmp: + root_tmp = Path(tmp) + # 1. awaiting_executable -> exit 3 + pkg_wait, baseline_w, integrity_w = _synthetic_package(root_tmp / "wait", write_candidate=False) + (root_tmp / "wait" / "reports").mkdir() + rep_wait = root_tmp / "wait" / "reports" + rc_wait, out_wait, err_wait = self._run_main( + ["--build", str(pkg_wait), "--baseline", str(baseline_w), "--integrity", str(integrity_w), "--reports", str(rep_wait)] + ) + self.assertEqual(rc_wait, 3, (out_wait, err_wait)) + self.assertEqual(err_wait, "") + self.assertIn("awaiting_executable |", out_wait) + self.assertEqual(len(list(rep_wait.glob("*.awaiting_executable.json"))), 1) + + # 2. inspected -> exit 0, and --require-routing with unsupported import -> exit 1 + pe_bytes = _build_pe( + imports=[ + ("normal", "xmem.dll", "XMemAlloc"), + ("normal", "mystery.dll", "MissingExport"), + ] + ) + pkg_ok, baseline_ok, integrity_ok = _synthetic_package(root_tmp / "ok", write_candidate=True, pe_bytes=pe_bytes) + rep_ok = root_tmp / "ok" / "reports" + common = ["--build", str(pkg_ok), "--baseline", str(baseline_ok), "--integrity", str(integrity_ok), "--reports", str(rep_ok)] + + with mock.patch.object(intake_exe, "scan", _fake_scan_for(pkg_ok, pe_bytes)): + rc_ok, out_ok, err_ok = self._run_main(common) + self.assertEqual(rc_ok, 0, (out_ok, err_ok)) + self.assertIn("inspected |", out_ok) + + rc_req, out_req, err_req = self._run_main([*common, "--require-routing"]) + self.assertEqual(rc_req, 1, (out_req, err_req)) + self.assertIn("unsupported: main.exe -> mystery.dll!MissingExport", err_req) + self.assertIn("inspected |", out_req) + + # Direct collect() smoke check. + report_dict = {} + with mock.patch.object(intake_exe, "scan", _fake_scan_for(pkg_ok, pe_bytes)): + collect_rc = intake_exe.collect(pkg_ok, None, baseline_ok, integrity_ok, report_dict) + self.assertEqual(collect_rc, 0) + self.assertEqual(report_dict["status"], "inspected") + self.assertEqual(report_dict["pe"]["startup"]["exception_table"], "indexed") + + # Subprocess smoke test on awaiting_executable -> exit 3 without traceback. + proc = subprocess.run( + [ + sys.executable, "-B", str(TOOL), + "--build", str(pkg_wait), + "--baseline", str(baseline_w), + "--integrity", str(integrity_w), + "--reports", str(rep_wait), + ], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 3, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("awaiting_executable |", proc.stdout) + + def test_negative_inputs_and_atomic_temp_cleanup_controls(self): + with tempfile.TemporaryDirectory() as tmp: + root_tmp = Path(tmp) + pkg, baseline, integrity = _synthetic_package(root_tmp / "neg", write_candidate=False) + reports = root_tmp / "neg" / "reports" + reports.mkdir() + + # Missing candidate passed explicitly -> error report, exit 2, zero traceback. + missing_exe = root_tmp / "neg" / "missing.exe" + rc_missing, out_missing, err_missing = self._run_main( + [str(missing_exe), "--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(reports)] + ) + self.assertEqual(rc_missing, 2) + self.assertNotIn("Traceback", err_missing) + self.assertIn("error |", out_missing) + + # Malformed MicrosoftGame.Config -> error report, exit 2, zero traceback. + (pkg / "MicrosoftGame.Config").write_text(" SystemExit(2), zero traceback. + out_buf, err_buf = io.StringIO(), io.StringIO() + with redirect_stdout(out_buf), redirect_stderr(err_buf): + with self.assertRaises(SystemExit) as exc: + intake_exe.main(["--build", str(pkg), "--reports", str(pkg / "sub")]) + self.assertEqual(exc.exception.code, 2) + self.assertNotIn("Traceback", err_buf.getvalue()) + + # --reports pointing to an existing regular file -> exit 1, zero traceback. + file_reports = root_tmp / "neg" / "not_a_dir.txt" + file_reports.write_text("file", encoding="utf-8") + rc_file_rep, out_file_rep, err_file_rep = self._run_main( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(file_reports)] + ) + self.assertEqual(rc_file_rep, 1) + self.assertEqual(out_file_rep, "") + self.assertNotIn("Traceback", err_file_rep) + self.assertIn("failed to write report", err_file_rep) + + # Failure during json.dump must unlink temp file and exit 1 without traceback. + clean_rep = root_tmp / "neg" / "clean_dump" + clean_rep.mkdir() + with mock.patch.object(intake_exe.json, "dump", side_effect=OSError("disk full during dump")): + rc_dump, out_dump, err_dump = self._run_main( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(clean_rep)] + ) + self.assertEqual(rc_dump, 1) + self.assertEqual(out_dump, "") + self.assertNotIn("Traceback", err_dump) + self.assertIn("disk full during dump", err_dump) + self.assertEqual(list(clean_rep.iterdir()), []) + + # Failure during os.replace must unlink temp file and exit 1 without traceback. + clean_rep2 = root_tmp / "neg" / "clean_replace" + clean_rep2.mkdir() + with mock.patch.object(intake_exe.os, "replace", side_effect=PermissionError("locked dest")): + rc_rep, out_rep, err_rep = self._run_main( + ["--build", str(pkg), "--baseline", str(baseline), "--integrity", str(integrity), "--reports", str(clean_rep2)] + ) + self.assertEqual(rc_rep, 1) + self.assertEqual(out_rep, "") + self.assertNotIn("Traceback", err_rep) + self.assertIn("locked dest", err_rep) + self.assertEqual(list(clean_rep2.iterdir()), []) + + # OSError during Path.resolve -> exit 1 without traceback. + with mock.patch.object(Path, "resolve", side_effect=OSError("bad symlink")): + rc_res, out_res, err_res = self._run_main(["--build", str(pkg), "--reports", str(clean_rep2)]) + self.assertEqual(rc_res, 1) + self.assertEqual(out_res, "") + self.assertNotIn("Traceback", err_res) + self.assertIn("bad symlink", err_res) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/intake_exe.py b/tools/intake_exe.py index 8bd1d5362..6216ab76e 100644 --- a/tools/intake_exe.py +++ b/tools/intake_exe.py @@ -3,6 +3,7 @@ import argparse import hashlib import json +import os from pathlib import Path import struct import sys @@ -39,8 +40,11 @@ def routing_failures(rows): def inside(root, name): - path = (root / name).resolve() - if not path.is_relative_to(root) or path == root or Path(name).is_absolute(): + """Resolve a package-relative path, normalizing root so unnormalized '..' in root does not reject valid names.""" + base = root.resolve() + path = (base / name).resolve() + if (not path.is_relative_to(base) or path == base or + Path(name).is_absolute() or str(name).startswith(("/", "\\"))): raise ValueError(f"Invalid package path: {name}") return path @@ -210,7 +214,7 @@ def collect(root, candidate, baseline, integrity, report): return 0 -def main(argv=None): +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("candidate", type=Path, nargs="?", help="Separate file, or omit to use the manifest path") parser.add_argument("--build", type=Path) @@ -225,8 +229,12 @@ def main(argv=None): if len(builds) != 1: parser.error("Use --build to select a package") args.build = builds[0].parent - root = args.build.resolve() - reports = args.reports.resolve() + try: + root = args.build.resolve() + reports = args.reports.resolve() + except OSError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 if reports.is_relative_to(root) or reports.is_relative_to(PROJECT / "game-files"): parser.error("Choose a report directory outside game files") integrity = args.integrity or PROJECT / "out/integrity" / (root.name + ".json") @@ -244,12 +252,22 @@ def main(argv=None): print(f"unsupported: {row['image']} -> {row['dll']}!{row['symbol']}", file=sys.stderr) if failures: code = 1 - reports.mkdir(parents=True, exist_ok=True) - with NamedTemporaryFile(mode="w", suffix=".tmp", dir=reports, encoding="utf-8", delete=False) as f: - json.dump(report, f, ensure_ascii=False, indent=2) - f.write("\n") - dest = Path(f.name).with_suffix("." + report["status"] + ".json") - Path(f.name).rename(dest) + tmp_path = None + try: + reports.mkdir(parents=True, exist_ok=True) + with NamedTemporaryFile(mode="w", suffix=".tmp", dir=reports, encoding="utf-8", delete=False) as f: + tmp_path = Path(f.name) + json.dump(report, f, ensure_ascii=False, indent=2) + f.write("\n") + dest = tmp_path.with_suffix("." + report["status"] + ".json") + os.replace(tmp_path, dest) + tmp_path = None + except (OSError, TypeError, ValueError) as exc: + print(f"error: failed to write report in {reports}: {exc}", file=sys.stderr) + return 1 + finally: + if tmp_path is not None: + tmp_path.unlink(missing_ok=True) print(f"{report['status']} | {dest}") if "error" in report: print(report["error"]) From f555b535225b8f3459152d871805965a46b61314 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:23:58 +0100 Subject: [PATCH 025/232] perf: compile shaders concurrently in sdwa, nan and gather_c_lz checks (#2368) --- tests/startup_gfx2hlsl_f32_nan_check.py | 33 +++++++-- tests/startup_gfx2hlsl_f32_sdwa_check.py | 31 ++++++-- tests/startup_image_3d_check.py | 28 +++++++ tests/startup_image_gather_c_lz_check.py | 93 +++++++++++++++--------- 4 files changed, 138 insertions(+), 47 deletions(-) diff --git a/tests/startup_gfx2hlsl_f32_nan_check.py b/tests/startup_gfx2hlsl_f32_nan_check.py index 3394ee151..d57a88155 100644 --- a/tests/startup_gfx2hlsl_f32_nan_check.py +++ b/tests/startup_gfx2hlsl_f32_nan_check.py @@ -51,6 +51,7 @@ from startup_gfx2hlsl_f32_lg_check import ( # noqa: E402 COMPARES, F32_OPS, PAIRS, VALUES, CLEAR, ONE, WIDTH, HEIGHT, Expr, G, assemble, compile_hlsl, flushed, is_nan, modified, reference) +from startup_image_3d_check import CompileQueue # noqa: E402 NAN_FORMS = ('nlt', 'nle', 'ngt', 'nge', 'o', 'u') BROKEN_BY = {'nlt': 'fxc', 'nle': 'fxc', 'ngt': 'fxc', 'nge': 'fxc', 'o': 'dxc', 'u': 'dxc'} @@ -368,20 +369,38 @@ def compile_strict(compiler, kind, source, out, profile, directory): return target +def prefetch(queue, compilers, directory): + """Start every compile check_draw will ask for, in the order it asks. A compile missed here is made inline.""" + for kind, compiler, vs_profile, ps_profile in compilers: + queue.submit(compile_hlsl, compiler, kind, L.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name, (_words, results) in FIXTURES.items(): + queue.submit(compile_hlsl, compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, + directory) + if not {c for c, _m0, _m1 in results} & set(NAN_FORMS): + continue + queue.submit(compile_hlsl, compiler, kind, pixel_hlsl(name, old=True), 'ps_%s_old_%s' % (name, kind), + ps_profile, directory) + for label, old in (('old', True), ('new', False)): + queue.submit(compile_strict, compiler, kind, pixel_hlsl(name, old=old), + 'ps_%s_%s_strict_%s' % (name, label, kind), ps_profile, directory) + + def check_draw(dxc, renderer, adapter, fxc=None): compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] if not fxc: print(' no FXC given: the nlt/nle/ngt/nge negative controls are not drawn') - with tempfile.TemporaryDirectory() as tmp: + with tempfile.TemporaryDirectory() as tmp, CompileQueue() as queue: directory = Path(tmp) + prefetch(queue, compilers, directory) for kind, compiler, vs_profile, ps_profile in compilers: - vs = compile_hlsl(compiler, kind, L.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + vs = queue.call(compile_hlsl, compiler, kind, L.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) modes, header = set(), None for name, (_words, results) in FIXTURES.items(): conds = {c for c, _m0, _m1 in results} files = {d: L.words_file(directory, '%s_%s' % (name, d), image(name, denormals=d)) for d in L.DENORMALS} - ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, directory) + ps = queue.call(compile_hlsl, compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, + directory) matched, report = None, [] for denormals in L.DENORMALS: run = draw(renderer, adapter, vs, ps, files[denormals]) @@ -400,8 +419,8 @@ def check_draw(dxc, renderer, adapter, fxc=None): '\n'.join(report)) if not conds & set(NAN_FORMS): continue - bad = compile_hlsl(compiler, kind, pixel_hlsl(name, old=True), 'ps_%s_old_%s' % (name, kind), - ps_profile, directory) + bad = queue.call(compile_hlsl, compiler, kind, pixel_hlsl(name, old=True), 'ps_%s_old_%s' % (name, kind), + ps_profile, directory) if BROKEN_BY[min(conds)] == kind: for denormals in L.DENORMALS: run = draw(renderer, adapter, vs, bad, files[denormals]) @@ -421,8 +440,8 @@ def check_draw(dxc, renderer, adapter, fxc=None): # Diagnostic, not checked: the old and the new text with IEEE-strict compares (/Gis, -Gis), which # the startup cache does not use. for label, old in (('old', True), ('new', False)): - strict = compile_strict(compiler, kind, pixel_hlsl(name, old=old), - 'ps_%s_%s_strict_%s' % (name, label, kind), ps_profile, directory) + strict = queue.call(compile_strict, compiler, kind, pixel_hlsl(name, old=old), + 'ps_%s_%s_strict_%s' % (name, label, kind), ps_profile, directory) outcome = 'no image matched' for denormals in L.DENORMALS: run = draw(renderer, adapter, vs, strict, files[denormals]) diff --git a/tests/startup_gfx2hlsl_f32_sdwa_check.py b/tests/startup_gfx2hlsl_f32_sdwa_check.py index bcef223b1..30e39f587 100644 --- a/tests/startup_gfx2hlsl_f32_sdwa_check.py +++ b/tests/startup_gfx2hlsl_f32_sdwa_check.py @@ -49,6 +49,7 @@ import startup_gfx2hlsl_f32_lg_check as L # noqa: E402 import startup_gfx2hlsl_f32_nan_check as N # noqa: E402 import startup_gfx2hlsl_vopc_sdwa_check as S # noqa: E402 +from startup_image_3d_check import CompileQueue # noqa: E402 from startup_gfx2hlsl_f32_lg_check import ( # noqa: E402 CLEAR, HEIGHT, ONE, PAIRS, VALUES, WIDTH, G, as_float, assemble, compile_hlsl, flushed, modified, old_reference, reference) @@ -629,20 +630,36 @@ def pixel_lines(run): return ' / '.join(ln for ln in (run.stdout + run.stderr).splitlines() if 'pixel' in ln) +def prefetch(queue, compilers, directory): + """Start every compile check_draw will ask for, in the order it asks. A compile missed here is made inline.""" + for kind, compiler, vs_profile, ps_profile in compilers: + queue.submit(compile_hlsl, compiler, kind, L.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name, (_words, results) in FIXTURES.items(): + queue.submit(compile_hlsl, compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, + directory) + if results[0][0] in GUARDED: + queue.submit(compile_hlsl, compiler, kind, pixel_hlsl(name, 'old'), 'ps_%s_old_%s' % (name, kind), + ps_profile, directory) + queue.submit(N.compile_strict, compiler, kind, pixel_hlsl(name), 'ps_%s_strict_%s' % (name, kind), + ps_profile, directory) + + def check_draw(dxc, renderer, adapter, fxc=None): compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] if not fxc: print(' no FXC given: the nlt/nle/ngt/nge old-text controls are not drawn') - with tempfile.TemporaryDirectory() as tmp: + with tempfile.TemporaryDirectory() as tmp, CompileQueue() as queue: directory = Path(tmp) + prefetch(queue, compilers, directory) for kind, compiler, vs_profile, ps_profile in compilers: - vs = compile_hlsl(compiler, kind, L.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + vs = queue.call(compile_hlsl, compiler, kind, L.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) modes, header = set(), None for name, (_words, results) in FIXTURES.items(): cond = results[0][0] files = {d: L.words_file(directory, '%s_%s' % (name, d), image(name, denormals=d)) for d in L.DENORMALS} - ps = compile_hlsl(compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, directory) + ps = queue.call(compile_hlsl, compiler, kind, pixel_hlsl(name), 'ps_%s_%s' % (name, kind), ps_profile, + directory) matched, report = None, [] for denormals in L.DENORMALS: run = draw(renderer, adapter, vs, ps, files[denormals]) @@ -659,8 +676,8 @@ def check_draw(dxc, renderer, adapter, fxc=None): kind, adapter, name, WIDTH * HEIGHT, matched if sensitive else 'either'), matched is not None, '\n'.join(report)) if cond in GUARDED: - bad = compile_hlsl(compiler, kind, pixel_hlsl(name, 'old'), 'ps_%s_old_%s' % (name, kind), - ps_profile, directory) + bad = queue.call(compile_hlsl, compiler, kind, pixel_hlsl(name, 'old'), 'ps_%s_old_%s' % (name, kind), + ps_profile, directory) if BROKEN_BY[cond] in ('ieee', kind): for denormals in L.DENORMALS: run = draw(renderer, adapter, vs, bad, files[denormals]) @@ -682,8 +699,8 @@ def check_draw(dxc, renderer, adapter, fxc=None): print(' recorded: %s %s %s old text: %s' % ( kind, adapter, name, pixel_lines(run) or 'all pixels matched')) # Diagnostic, not checked: the text with IEEE-strict compares, which the startup cache does not use. - strict = N.compile_strict(compiler, kind, pixel_hlsl(name), 'ps_%s_strict_%s' % (name, kind), - ps_profile, directory) + strict = queue.call(N.compile_strict, compiler, kind, pixel_hlsl(name), 'ps_%s_strict_%s' % (name, kind), + ps_profile, directory) outcome = 'no image matched' for denormals in L.DENORMALS: run = draw(renderer, adapter, vs, strict, files[denormals]) diff --git a/tests/startup_image_3d_check.py b/tests/startup_image_3d_check.py index 3b270a80e..0cfc30d79 100644 --- a/tests/startup_image_3d_check.py +++ b/tests/startup_image_3d_check.py @@ -12,11 +12,13 @@ binds a 2x2x2 R32G32B32A32_FLOAT texture whose texel (x, y, z) holds ((1 + x + 2y + 4z) / 8, x, y, z) and a point sampler with wrap addressing. """ +import os import re import struct import subprocess import sys import tempfile +from concurrent.futures import ThreadPoolExecutor from pathlib import Path HERE = Path(__file__).resolve().parent @@ -145,6 +147,32 @@ def compile_hlsl(compiler, kind, source, out, profile, directory): return directory / ('%s.cso' % out) +class CompileQueue: + """Runs independent shader compiles on a thread pool, and hands each result back in source order. + + submit() starts a compile; call() returns that compile's result, or compiles inline when nothing was + submitted for the same arguments. A failed compile raises where call() reaches it, so the first failure in + source order is still the one reported. Every submitted compile needs its own output name.""" + + def __init__(self, workers=None): + self.pool = ThreadPoolExecutor(max_workers=workers or min(8, os.cpu_count() or 1)) + self.futures = {} + + def __enter__(self): + return self + + def __exit__(self, kind, value, trace): + self.pool.shutdown(wait=True, cancel_futures=True) + + def submit(self, function, *args): + assert (function, args) not in self.futures, 'duplicate compile %r' % (args[3],) + self.futures[(function, args)] = self.pool.submit(function, *args) + + def call(self, function, *args): + future = self.futures.pop((function, args), None) + return future.result() if future else function(*args) + + def texel(x, y, z): """The fixture texture's value at integer texel (x, y, z), as four binary32 hex words.""" return ','.join('%08x' % struct.unpack(' Date: Wed, 25 Nov 2026 16:25:15 +0200 Subject: [PATCH 026/232] cpu: lower VEX.128 VPADDB, VPSUBB, VPCMPEQB, and VPCMPGTB in cpu_vex_aot (#2359) --- CMakeLists.txt | 22 ++ tests/cpu/vex_bytes_arith.asm | 131 ++++++++++ tests/cpu/vex_bytes_arith.def | 12 + tests/cpu/vex_bytes_arith_check.py | 392 +++++++++++++++++++++++++++++ tools/cpu_vex_aot.py | 9 + 5 files changed, 566 insertions(+) create mode 100644 tests/cpu/vex_bytes_arith.asm create mode 100644 tests/cpu/vex_bytes_arith.def create mode 100644 tests/cpu/vex_bytes_arith_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8e9ac75a1..2e4e80671 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5280,6 +5280,28 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_vex_bytes PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_vex_bytes.txt") + # cpu_aot_vex_bytes_arith + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_vex_bytes_arith_${variant} vex_bytes_arith) + set(vex_bytes_arith_lifted "${CMAKE_CURRENT_BINARY_DIR}/cpu_vex_bytes_arith_${variant}_lifted.cpp") + add_custom_command(OUTPUT "${vex_bytes_arith_lifted}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/cpu_vex_aot.py" + "$" "${vex_bytes_arith_lifted}" + paddb_reg paddb_mem psubb_reg psubb_mem psubb_self + pcmpeqb_reg pcmpeqb_mem pcmpgtb_reg pcmpgtb_mem + bytes_arith_mem_r8_chain bytes_arith_aligned + DEPENDS cpu_vex_bytes_arith_${variant} tools/cpu_vex_aot.py tools/cpu_leaf_aot.py tools/cpu_ranges.py + VERBATIM) + add_library(cpu_vex_bytes_arith_${variant}_lifted SHARED "${vex_bytes_arith_lifted}") + endforeach() + target_compile_definitions(cpu_vex_bytes_arith_altered PRIVATE ALTER_BYTE_ARITH) + add_test(NAME cpu_aot_vex_bytes_arith COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/vex_bytes_arith_check.py" + "$" "$" + "$" "$") + set_tests_properties(cpu_aot_vex_bytes_arith PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_vex_bytes_arith.txt") set(cpu_seg_inspect_exports "lar_reg16,lar_reg32,lar_reg64,lar_mem16,lar_mem32_disp,lar_mem64_disp," "lsl_reg16,lsl_reg32,lsl_reg64,lsl_mem16,lsl_mem32_disp,lsl_mem64_disp," diff --git a/tests/cpu/vex_bytes_arith.asm b/tests/cpu/vex_bytes_arith.asm new file mode 100644 index 000000000..9268caf53 --- /dev/null +++ b/tests/cpu/vex_bytes_arith.asm @@ -0,0 +1,131 @@ +; coverage: record cpu_aot_vex_bytes_arith +; VEX.128 byte-domain arithmetic and compare leaf functions (vpaddb, vpsubb, vpcmpeqb, vpcmpgtb), +; an altered build for differential controls, and their lifted C++. +; Each takes RCX and RDX (addresses of two 16-byte inputs) and R8 (address of a 16-byte output). +.code + +paddb_reg PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vmovdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_BYTE_ARITH + vpsubb xmm2, xmm0, xmm1 +ELSE + vpaddb xmm2, xmm0, xmm1 +ENDIF + vmovdqu xmmword ptr [r8], xmm2 + ret +paddb_reg ENDP + +paddb_mem PROC FRAME + .endprolog + vmovdqu xmm3, xmmword ptr [rcx] + vpaddb xmm4, xmm3, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm4 + ret +paddb_mem ENDP + +psubb_reg PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vmovdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_BYTE_ARITH + ; Swap operands to expose (a - b) asymmetry. + vpsubb xmm2, xmm1, xmm0 +ELSE + vpsubb xmm2, xmm0, xmm1 +ENDIF + vmovdqu xmmword ptr [r8], xmm2 + ret +psubb_reg ENDP + +psubb_mem PROC FRAME + .endprolog + vmovdqu xmm3, xmmword ptr [rcx] + vpsubb xmm4, xmm3, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm4 + ret +psubb_mem ENDP + +; dst == src1 == src2 zeroing on defined register. +psubb_self PROC FRAME + .endprolog + vmovdqu xmm2, xmmword ptr [rcx] + vpsubb xmm2, xmm2, xmm2 + vmovdqu xmmword ptr [r8], xmm2 + ret +psubb_self ENDP + +pcmpeqb_reg PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vmovdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_BYTE_ARITH + vpcmpgtb xmm2, xmm0, xmm1 +ELSE + vpcmpeqb xmm2, xmm0, xmm1 +ENDIF + vmovdqu xmmword ptr [r8], xmm2 + ret +pcmpeqb_reg ENDP + +pcmpeqb_mem PROC FRAME + .endprolog + vmovdqu xmm3, xmmword ptr [rcx] + vpcmpeqb xmm4, xmm3, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm4 + ret +pcmpeqb_mem ENDP + +pcmpgtb_reg PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vmovdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_BYTE_ARITH + ; Swap operands to expose signed (a > b) asymmetry. + vpcmpgtb xmm2, xmm1, xmm0 +ELSE + vpcmpgtb xmm2, xmm0, xmm1 +ENDIF + vmovdqu xmmword ptr [r8], xmm2 + ret +pcmpgtb_reg ENDP + +pcmpgtb_mem PROC FRAME + .endprolog + vmovdqu xmm3, xmmword ptr [rcx] + vpcmpgtb xmm4, xmm3, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm4 + ret +pcmpgtb_mem ENDP + +; Chained operations exercising XMM0..XMM5, [rcx]/[rdx]/[r8] memory sources, and store-reload order. +bytes_arith_mem_r8_chain PROC FRAME + .endprolog + vmovdqu xmm0, xmmword ptr [rcx] + vpaddb xmm2, xmm0, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm2 + vpsubb xmm3, xmm2, xmmword ptr [rcx] + vpcmpeqb xmm4, xmm3, xmmword ptr [r8] + vpcmpgtb xmm5, xmm4, xmmword ptr [rdx] + vpaddb xmm0, xmm5, xmmword ptr [rcx] + vpsubb xmm1, xmm0, xmmword ptr [r8] + vpcmpgtb xmm2, xmm1, xmmword ptr [rdx] + vmovdqu xmmword ptr [r8], xmm2 + vzeroupper + ret +bytes_arith_mem_r8_chain ENDP + +; Aligned-move variant: buffers must be 16-byte aligned. +bytes_arith_aligned PROC FRAME + .endprolog + vmovdqa xmm0, xmmword ptr [rcx] + vpaddb xmm1, xmm0, xmmword ptr [rdx] + vpsubb xmm2, xmm1, xmm0 + vpcmpeqb xmm3, xmm2, xmmword ptr [rdx] + vpcmpgtb xmm4, xmm3, xmm1 + vmovdqa xmmword ptr [r8], xmm4 + ret +bytes_arith_aligned ENDP + +END diff --git a/tests/cpu/vex_bytes_arith.def b/tests/cpu/vex_bytes_arith.def new file mode 100644 index 000000000..1c31a4216 --- /dev/null +++ b/tests/cpu/vex_bytes_arith.def @@ -0,0 +1,12 @@ +EXPORTS + paddb_reg + paddb_mem + psubb_reg + psubb_mem + psubb_self + pcmpeqb_reg + pcmpeqb_mem + pcmpgtb_reg + pcmpgtb_mem + bytes_arith_mem_r8_chain + bytes_arith_aligned diff --git a/tests/cpu/vex_bytes_arith_check.py b/tests/cpu/vex_bytes_arith_check.py new file mode 100644 index 000000000..45910e1a1 --- /dev/null +++ b/tests/cpu/vex_bytes_arith_check.py @@ -0,0 +1,392 @@ +"""Compare VEX.128 byte arithmetic/compare leaf functions (vpaddb, vpsubb, vpcmpeqb, vpcmpgtb) with lifted C++.""" + +import argparse +import ctypes +from itertools import product +import os +from pathlib import Path +import random +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Decoder, Formatter, FormatterSyntax, Mnemonic, OpKind +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_vex_aot import lift, translate # noqa: E402 + +FUNCTIONS = ( + "paddb_reg", + "paddb_mem", + "psubb_reg", + "psubb_mem", + "psubb_self", + "pcmpeqb_reg", + "pcmpeqb_mem", + "pcmpgtb_reg", + "pcmpgtb_mem", + "bytes_arith_mem_r8_chain", + "bytes_arith_aligned", +) +UNALIGNED = tuple(name for name in FUNCTIONS if name != "bytes_arith_aligned") + +# Arena: guard | A | guard | B | guard | OUT | guard, each 16 bytes, starting 16-byte aligned. +ZONES = {"a": 16, "b": 48, "out": 80} +ARENA = 112 +OUT = slice(ZONES["out"], ZONES["out"] + 16) +ALIAS_PAIRS = 256 +BYTE_EDGES = (0x00, 0x01, 0x03, 0x0F, 0x13, 0x7E, 0x7F, 0x80, 0x81, 0x8F, 0xFE, 0xFF) +PAIRS = 1024 + + +def inputs(): + """1024 pairs of 16-byte inputs covering edge pairings, wrap/borrow, signed boundaries, and random bytes.""" + pairs = [] + for a, b in product(BYTE_EDGES, repeat=2): + pairs.append((bytes([a] * 16), bytes([b] * 16))) + for shift in range(len(BYTE_EDGES)): + row = [BYTE_EDGES[(i + shift) % len(BYTE_EDGES)] for i in range(16)] + col = [BYTE_EDGES[(3 * i + shift + 1) % len(BYTE_EDGES)] for i in range(16)] + pairs.append((bytes(row), bytes(col))) + # Explicit witness pairs: wrap/borrow boundaries and signed -128..127 comparisons. + pairs.append(( + bytes([0xFF, 0x7F, 0x00, 0x80, 0x80, 0xFF, 0xFE, 0x7F, 0x00, 0x01, 0x81, 0x7E, 0x10, 0x20, 0x30, 0x40]), + bytes([0x01, 0x01, 0x01, 0x01, 0x7F, 0xFE, 0xFF, 0x80, 0x00, 0x01, 0x80, 0x7F, 0x10, 0x80, 0x7F, 0x13]), + )) + generator = random.Random(0xB7EA71) + while len(pairs) < PAIRS: + pairs.append((generator.randbytes(16), generator.randbytes(16))) + return pairs + + +def call(function, a, b, output="out", misalign=0, same_inputs=False): + """Run function(A, B, output) inside a guarded 16-byte-aligned (+ misalign) arena.""" + raw = (ctypes.c_uint8 * (ARENA + 32))() + base = (ctypes.addressof(raw) + 15) // 16 * 16 + misalign + ctypes.memset(base, 0xCC, ARENA) + ctypes.memmove(base + ZONES["a"], a, 16) + ctypes.memmove(base + ZONES["b"], b, 16) + second = ZONES["a"] if same_inputs else ZONES["b"] + function(base + ZONES["a"], base + second, base + ZONES[output]) + return ctypes.string_at(base, ARENA) + + +def outside_output(arena, output="out"): + start = ZONES[output] + return arena[:start] + arena[start + 16:] + + +def _s8(byte): + return byte - 256 if byte & 0x80 else byte + + +def op_paddb(a, b, *, saturate=False): + if saturate: + return bytes(min(255, x + y) for x, y in zip(a, b)) + return bytes((x + y) & 0xFF for x, y in zip(a, b)) + + +def op_psubb(a, b, *, swap=False, saturate=False): + if swap: + a, b = b, a + if saturate: + return bytes(max(0, x - y) for x, y in zip(a, b)) + return bytes((x - y) & 0xFF for x, y in zip(a, b)) + + +def op_pcmpeqb(a, b, *, eq_one=False): + true_byte = 0x01 if eq_one else 0xFF + return bytes(true_byte if x == y else 0x00 for x, y in zip(a, b)) + + +def op_pcmpgtb(a, b, *, unsigned=False, swap=False): + if swap: + a, b = b, a + if unsigned: + return bytes(0xFF if x > y else 0x00 for x, y in zip(a, b)) + return bytes(0xFF if _s8(x) > _s8(y) else 0x00 for x, y in zip(a, b)) + + +def reference(name, a, b, *, saturate_add=False, swap_sub=False, saturate_sub=False, + eq_one=False, unsigned_gt=False, swap_gt=False): + """Independent byte/lane Python reference model for every exported fixture.""" + if name in ("paddb_reg", "paddb_mem"): + return op_paddb(a, b, saturate=saturate_add) + if name in ("psubb_reg", "psubb_mem"): + return op_psubb(a, b, swap=swap_sub, saturate=saturate_sub) + if name == "psubb_self": + return b"\x00" * 16 + if name in ("pcmpeqb_reg", "pcmpeqb_mem"): + return op_pcmpeqb(a, b, eq_one=eq_one) + if name in ("pcmpgtb_reg", "pcmpgtb_mem"): + return op_pcmpgtb(a, b, unsigned=unsigned_gt, swap=swap_gt) + if name == "bytes_arith_mem_r8_chain": + r8 = op_paddb(a, b) + x3 = op_psubb(r8, a) + x4 = op_pcmpeqb(x3, r8) + x5 = op_pcmpgtb(x4, b) + x0 = op_paddb(x5, a) + x1 = op_psubb(x0, r8) + return op_pcmpgtb(x1, b) + if name == "bytes_arith_aligned": + x1 = op_paddb(a, b) + x2 = op_psubb(x1, a) + x3 = op_pcmpeqb(x2, b) + return op_pcmpgtb(x3, x1) + raise ValueError(name) + + +def bind(path): + library = ctypes.CDLL(str(path)) + functions = {} + for name in FUNCTIONS: + fn = getattr(library, name) + fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + fn.restype = None + functions[name] = fn + return library, functions + + +def code_offset(image, name): + with pefile.PE(str(image), fast_load=True) as pe: + return pe.get_offset_from_rva(export_rva(pe, name)) + + +def expect_rejected(image, patch, message): + with TemporaryDirectory() as directory: + copy = Path(directory) / image.name + data = bytearray(image.read_bytes()) + patch(data) + copy.write_bytes(data) + try: + translate(copy, FUNCTIONS) + except ValueError as error: + if message not in str(error): + raise AssertionError(f"expected {message!r}, got {error}") from None + return + raise AssertionError(f"translated a copy that should fail with {message!r}") + + +# Excluded encodings checked via Decoder + Formatter before calling lift(). +REJECTED = ( + # VEX.256 (L=1) + ("C5 F5 FC C2", "vpaddb ymm0,ymm1,ymm2", "VEX.256 form"), + ("C5 F5 F8 C2", "vpsubb ymm0,ymm1,ymm2", "VEX.256 form"), + ("C5 F5 74 C2", "vpcmpeqb ymm0,ymm1,ymm2", "VEX.256 form"), + ("C5 F5 64 C2", "vpcmpgtb ymm0,ymm1,ymm2", "VEX.256 form"), + # EVEX + ("62 F1 75 09 FC C2", "vpaddb xmm0{k1},xmm1,xmm2", "non-VEX encoding"), + ("62 F1 75 09 F8 C2", "vpsubb xmm0{k1},xmm1,xmm2", "non-VEX encoding"), + ("62 F1 7D 08 74 C9", "vpcmpeqb k1,xmm0,xmm1", "non-VEX encoding"), + ("62 F1 7D 08 64 C9", "vpcmpgtb k1,xmm0,xmm1", "non-VEX encoding"), + # Legacy SSE2 + ("66 0F FC C1", "paddb xmm0,xmm1", "non-VEX encoding"), + ("66 0F F8 C1", "psubb xmm0,xmm1", "non-VEX encoding"), + ("66 0F 74 C1", "pcmpeqb xmm0,xmm1", "non-VEX encoding"), + ("66 0F 64 C1", "pcmpgtb xmm0,xmm1", "non-VEX encoding"), + # Nonvolatile XMM6..XMM15 + ("C5 F9 FC F1", "vpaddb xmm6,xmm0,xmm1", "nonvolatile XMM register"), + ("C5 C1 F8 C1", "vpsubb xmm0,xmm7,xmm1", "nonvolatile XMM register"), + ("C4 C1 71 74 C0", "vpcmpeqb xmm0,xmm1,xmm8", "nonvolatile XMM register"), + ("C4 61 79 64 F9", "vpcmpgtb xmm15,xmm0,xmm1", "nonvolatile XMM register"), + # Undefined XMM sources + ("C5 F1 FC C2", "vpaddb xmm0,xmm1,xmm2", "undefined XMM source"), + ("C5 F1 F8 C2", "vpsubb xmm0,xmm1,xmm2", "undefined XMM source"), + ("C5 F1 74 C2", "vpcmpeqb xmm0,xmm1,xmm2", "undefined XMM source"), + ("C5 F1 64 C2", "vpcmpgtb xmm0,xmm1,xmm2", "undefined XMM source"), + # Displaced, indexed, or unsupported base memory operands + ("C5 F9 FC 41 10", "vpaddb xmm0,xmm0,[rcx+10h]", "memory operand outside the 16-byte buffers"), + ("C5 F9 F8 04 02", "vpsubb xmm0,xmm0,[rdx+rax]", "memory operand outside the 16-byte buffers"), + ("C4 C1 79 74 44 48 10", "vpcmpeqb xmm0,xmm0,[r8+rcx*2+10h]", "memory operand outside the 16-byte buffers"), + ("C5 F9 64 00", "vpcmpgtb xmm0,xmm0,[rax]", "memory operand outside the 16-byte buffers"), + # Store outside [r8] + ("C5 FA 7F 02", "vmovdqu [rdx],xmm0", "store outside the output buffer"), +) + + +def check_aot_lowering(original_image): + """Validate AOT translation and negative rejection cases regardless of host AVX support.""" + source_cpp = translate(original_image, FUNCTIONS) + if "host_has_avx" not in source_cpp: + raise AssertionError("translated C++ missing host_has_avx") + + formatter = Formatter(FormatterSyntax.INTEL) + for code, text, reason in REJECTED: + body = bytes.fromhex(code) + b"\xc3" + decoded = formatter.format(next(iter(Decoder(64, body)))) + if decoded != text: + raise AssertionError(f"test encoding {code} decodes as {decoded!r}, expected {text!r}") + try: + lift(0x1000, body) + except ValueError as error: + if reason not in str(error): + raise AssertionError(f"{text}: expected {reason!r}, got {error}") from None + continue + raise AssertionError(f"lifted {text}, expected {reason!r}") + + # Patched PE negative controls on original_image. + data = original_image.read_bytes() + paddb_start = code_offset(original_image, "paddb_reg") + + def set_vex_l_paddb(buffer): + decoder = Decoder(64, bytes(data[paddb_start:paddb_start + 64]), ip=0) + for ins in decoder: + if ins.mnemonic == Mnemonic.VPADDB: + pos = paddb_start + ins.ip + assert buffer[pos] == 0xC5, hex(buffer[pos]) + buffer[pos + 1] |= 0x04 + return + raise AssertionError("no vpaddb in paddb_reg") + + def store_to_rcx(buffer): + decoder = Decoder(64, bytes(data[paddb_start:paddb_start + 64]), ip=0) + for ins in decoder: + if ins.mnemonic == Mnemonic.VMOVDQU and ins.op0_kind == OpKind.MEMORY: + pos = paddb_start + ins.ip + assert buffer[pos] == 0xC4, hex(buffer[pos]) + buffer[pos + 1] |= 0x20 # clear VEX.B (~REX.B) + buffer[pos + 4] = (buffer[pos + 4] & ~0x07) | 0x01 + return + raise AssertionError("no vmovdqu store in paddb_reg") + + def paddb_to_unsupported(buffer): + decoder = Decoder(64, bytes(data[paddb_start:paddb_start + 64]), ip=0) + for ins in decoder: + if ins.mnemonic == Mnemonic.VPADDB: + pos = paddb_start + ins.ip + assert buffer[pos] == 0xC5 and buffer[pos + 2] == 0xFC + buffer[pos + 2] = 0xDC # vpaddusb -> unsupported + return + raise AssertionError("no vpaddb in paddb_reg") + + expect_rejected(original_image, set_vex_l_paddb, "VEX.256 form") + expect_rejected(original_image, store_to_rcx, "store outside the output buffer") + expect_rejected(original_image, paddb_to_unsupported, "unsupported instruction") + print(f"AOT lowering validated ({len(REJECTED)} rejected encodings + 3 patched PE rejections)") + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in FUNCTIONS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + parser = argparse.ArgumentParser(description=__doc__) + for name in ("original", "original_lifted", "altered", "altered_lifted"): + parser.add_argument(name, type=Path) + args = parser.parse_args() + + check_aot_lowering(args.original) + + lifted_lib, lifted = bind(args.original_lifted) + lifted_lib.host_has_avx.argtypes = [] + lifted_lib.host_has_avx.restype = ctypes.c_uint32 + if not lifted_lib.host_has_avx(): + print("Host lacks CPUID.01H:ECX[28] or OS XGETBV XMM/YMM; skipping native differential check") + sys.exit(77) + + pairs = inputs() + _, native = bind(args.original) + _, altered = bind(args.altered) + _, altered_lifted = bind(args.altered_lifted) + + for name in FUNCTIONS: + for index, (a, b) in enumerate(pairs): + expected = call(native[name], a, b) + pristine = call(lambda *args: None, a, b) + if outside_output(expected) != outside_output(pristine): + raise AssertionError(f"{name}: native wrote outside its 16-byte output") + observed = call(lifted[name], a, b) + if observed != expected: + raise AssertionError(f"{name} pair {index}: lifted {observed[OUT].hex()} " + f"!= native {expected[OUT].hex()} for {a.hex()} {b.hex()}") + want = reference(name, a, b) + if observed[OUT] != want: + raise AssertionError(f"{name} pair {index}: lifted {observed[OUT].hex()} " + f"!= reference {want.hex()} for {a.hex()} {b.hex()}") + print(f"{name}: {len(pairs)} pairs match native and reference bit for bit, guards intact") + + # Explicit boundary assertions: wrap/borrow, signed -128..127 compare, dst==src1==src2 zeroing. + if call(lifted["paddb_reg"], b"\xFF\x7F\x80\x00" * 4, b"\x01\x01\x80\xFF" * 4)[OUT] != b"\x00\x80\x00\xFF" * 4: + raise AssertionError("vpaddb wraparound mismatch") + if call(lifted["psubb_reg"], b"\x00\x80\x7F\x01" * 4, b"\x01\x01\x80\xFF" * 4)[OUT] != b"\xFF\x7F\xFF\x02" * 4: + raise AssertionError("vpsubb borrow/wraparound mismatch") + if call(lifted["psubb_self"], b"\xA5\x5A" * 8, b"\xFF" * 16)[OUT] != b"\x00" * 16: + raise AssertionError("vpsubb self-zeroing mismatch") + if call(lifted["pcmpeqb_reg"], b"\x00\x7F\x80\xFF" * 4, b"\x00\x80\x80\xFE" * 4)[OUT] != b"\xFF\x00\xFF\x00" * 4: + raise AssertionError("vpcmpeqb mask mismatch") + gt_want = b"\x00\xFF\xFF\x00" * 4 + if call(lifted["pcmpgtb_reg"], b"\x80\xFF\x7F\x80" * 4, b"\x7F\xFE\x80\x80" * 4)[OUT] != gt_want: + raise AssertionError("vpcmpgtb signed compare mismatch") + + # Exact aliases, RCX == RDX, and 8-byte misalignment on vmovdqu-only exports. + for name in FUNCTIONS: + for output in ("a", "b"): + for a, b in pairs[:ALIAS_PAIRS]: + if call(lifted[name], a, b, output) != call(native[name], a, b, output): + raise AssertionError(f"{name}: lifted differs from native with output aliasing {output}") + for output in ("out", "a"): + for a, b in pairs[:ALIAS_PAIRS]: + if call(lifted[name], a, b, output, same_inputs=True) != call(native[name], a, b, output, same_inputs=True): + raise AssertionError(f"{name}: lifted differs from native with RCX == RDX (output {output})") + for name in UNALIGNED: + for a, b in pairs[:ALIAS_PAIRS]: + if call(lifted[name], a, b, misalign=8) != call(native[name], a, b, misalign=8): + raise AssertionError(f"{name}: lifted differs from native at 8-byte misalignment") + print("aliased outputs, RCX == RDX, and unaligned buffers match native") + + # Mutation negative controls: Python faulty models must be distinguished from lifted outputs. + mutants = ( + ("paddb_reg", {"saturate_add": True}, "saturate_add"), + ("psubb_reg", {"swap_sub": True}, "swap_sub"), + ("psubb_reg", {"saturate_sub": True}, "saturate_sub"), + ("pcmpeqb_reg", {"eq_one": True}, "eq_one"), + ("pcmpgtb_reg", {"unsigned_gt": True}, "unsigned_gt"), + ("pcmpgtb_reg", {"swap_gt": True}, "swap_gt"), + ) + for name, kwargs, label in mutants: + diffs = sum(call(lifted[name], a, b)[OUT] != reference(name, a, b, **kwargs) for a, b in pairs) + if not diffs: + raise AssertionError(f"mutant model {label} was not distinguished on {name}") + print(f"mutant {label} on {name}: distinguished on {diffs}/{len(pairs)} pairs") + + # Altered build differential controls. + for name in ("paddb_reg", "psubb_reg", "pcmpeqb_reg", "pcmpgtb_reg"): + changed = 0 + for a, b in pairs: + alt_nat = call(altered[name], a, b) + alt_lif = call(altered_lifted[name], a, b) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted differs from altered native") + changed += alt_nat != call(native[name], a, b) + if not changed: + raise AssertionError(f"altered build did not change {name}") + print(f"altered {name}: altered lifted matches altered native and diverges from original on {changed}/{len(pairs)} pairs") + + for name in ("paddb_mem", "psubb_mem", "psubb_self", "pcmpeqb_mem", "pcmpgtb_mem", + "bytes_arith_mem_r8_chain", "bytes_arith_aligned"): + for a, b in pairs[:256]: + if call(altered[name], a, b) != call(native[name], a, b): + raise AssertionError(f"altered build unexpectedly changed {name}") + + record_covered_forms(args.original) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_vex_aot.py b/tools/cpu_vex_aot.py index 9a7070728..38bce7a58 100644 --- a/tools/cpu_vex_aot.py +++ b/tools/cpu_vex_aot.py @@ -48,6 +48,7 @@ M.VPCMPEQW: "pcmpeqw", M.VPCMPGTW: "pcmpgtw", M.VPSIGNW: "psignw", M.VPMULHRSW: "pmulhrsw", M.VPHADDW: "phaddw", M.VPANDN: "pandn", M.VPAVGB: "pavgb", M.VPMADDUBSW: "pmaddubsw", M.VPSHUFB: "pshufb", + M.VPADDB: "paddb", M.VPSUBB: "psubb", M.VPCMPEQB: "pcmpeqb", M.VPCMPGTB: "pcmpgtb", } SHIFTS = {M.VPSRAW: "psraw", M.VPSLLW: "psllw", M.VPSRLW: "psrlw"} MOVES = {M.VMOVDQU, M.VMOVDQA} @@ -124,6 +125,14 @@ V pand(const V& a, const V& b) { V r; for (int i = 0; i < 16; ++i) r.b[i] = a.b[i] & b.b[i]; return r; } V pandn(const V& a, const V& b) { V r; for (int i = 0; i < 16; ++i) r.b[i] = static_cast((~a.b[i]) & b.b[i]); return r; } V por(const V& a, const V& b) { V r; for (int i = 0; i < 16; ++i) r.b[i] = a.b[i] | b.b[i]; return r; } +// Wraparound byte add/subtract and byte-lane equality / signed greater-than compares. +#define BYTEWISE(name, expr) \ + V name(const V& a, const V& b) { V r; for (int i = 0; i < 16; ++i) r.b[i] = static_cast(expr); return r; } +BYTEWISE(paddb, a.b[i] + b.b[i]) +BYTEWISE(psubb, a.b[i] - b.b[i]) +BYTEWISE(pcmpeqb, a.b[i] == b.b[i] ? 0xFFu : 0u) +BYTEWISE(pcmpgtb, static_cast(a.b[i]) > static_cast(b.b[i]) ? 0xFFu : 0u) +#undef BYTEWISE // Unsigned byte average rounded up: (a + b + 1) >> 1 without 8-bit overflow. V pavgb(const V& a, const V& b) { V r; From ff06794b01a2a021390150051bd42ec092f4d97e Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:25:28 +0200 Subject: [PATCH 027/232] cpu: add dedicated cpu_bmi2_shift_aot lifter for RORX, SARX, SHLX, and SHRX (#2367) * cpu: add dedicated cpu_bmi2_shift_aot lifter for RORX, SARX, SHLX, and SHRX * cpu: clarify BMI2 shift comments and expand 32-bit count-mask mutants --- CMakeLists.txt | 25 ++ tests/cpu/bmi2_shift.asm | 282 ++++++++++++++ tests/cpu/bmi2_shift.def | 26 ++ tests/cpu/bmi2_shift_check.py | 698 ++++++++++++++++++++++++++++++++++ tools/cpu_bmi2_shift_aot.py | 579 ++++++++++++++++++++++++++++ 5 files changed, 1610 insertions(+) create mode 100644 tests/cpu/bmi2_shift.asm create mode 100644 tests/cpu/bmi2_shift.def create mode 100644 tests/cpu/bmi2_shift_check.py create mode 100644 tools/cpu_bmi2_shift_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e4e80671..e303d6a1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5630,6 +5630,31 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_bmi2 PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_bmi2_shift + set(cpu_bmi2_shift_exports + "op_rorx32,op_rorx32_imm32,op_rorx32_imm37,op_rorx64,op_rorx64_imm64,op_rorx64_imm73," + "op_shlx32,op_shlx64,op_shrx32,op_shrx64,op_sarx32,op_sarx64," + "op_rorx32_mem,op_rorx64_mem,op_shlx32_mem,op_shlx64_mem," + "op_shrx32_mem,op_shrx64_mem,op_sarx32_mem,op_sarx64_mem," + "op_mem_r8_source,op_flags_preserve32,op_flags_preserve64," + "op_flags_preserve_mem,op_bmi2_discarded_read") + string(CONCAT cpu_bmi2_shift_exports ${cpu_bmi2_shift_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi2_shift_${variant} bmi2_shift) + cpu_translation(cpu_bmi2_shift_${variant} cpu_bmi2_shift_aot "${cpu_bmi2_shift_exports}") + endforeach() + target_compile_definitions(cpu_bmi2_shift_altered PRIVATE ALTER_BMI2_SHIFT) + add_test(NAME cpu_aot_bmi2_shift COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi2_shift_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi2_shift PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_shift.txt") + cpu_asm_fixture(cpu_sse2_packed_cvt sse2_packed_cvt) target_sources(cpu_sse2_packed_cvt PRIVATE tests/cpu/sse2_mxcsr_test.asm) set(sse2_packed_cvt_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_sse2_packed_cvt_lifted.cpp") diff --git a/tests/cpu/bmi2_shift.asm b/tests/cpu/bmi2_shift.asm new file mode 100644 index 000000000..7322e106e --- /dev/null +++ b/tests/cpu/bmi2_shift.asm @@ -0,0 +1,282 @@ +; coverage: record cpu_aot_bmi2_shift +; Source-built MASM fixture for the four flagless BMI2 shift/rotate forms from +; docs/coverage/x64_zen2.tsv group BMI/ADX: RORX, SARX, SHLX, and SHRX in 32-bit +; and 64-bit register and flat [rcx|rdx|r8 + disp] memory forms, plus CMP -> BMI2 -> +; SETcc flag-preservation checks (CF, ZF, SF, OF, PF). +.code + +; --- RORX (32-bit and 64-bit register forms, including imm8 masking >= 32/64) --- +op_rorx32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_SHIFT + rorx eax, ecx, 7 +ELSE + rorx eax, ecx, 13 +ENDIF + ret +op_rorx32 ENDP + +op_rorx32_imm32 PROC FRAME + .endprolog + mov rax, -1 + rorx eax, ecx, 32 + ret +op_rorx32_imm32 ENDP + +op_rorx32_imm37 PROC FRAME + .endprolog + mov rax, -1 + rorx eax, ecx, 37 + ret +op_rorx32_imm37 ENDP + +op_rorx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_SHIFT + rorx rax, rcx, 11 +ELSE + rorx rax, rcx, 19 +ENDIF + ret +op_rorx64 ENDP + +op_rorx64_imm64 PROC FRAME + .endprolog + rorx rax, rcx, 64 + ret +op_rorx64_imm64 ENDP + +op_rorx64_imm73 PROC FRAME + .endprolog + rorx rax, rcx, 73 + ret +op_rorx64_imm73 ENDP + +; --- SHLX / SHRX / SARX (32-bit and 64-bit register forms) --- +op_shlx32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_SHIFT + shrx eax, ecx, edx +ELSE + shlx eax, ecx, edx +ENDIF + ret +op_shlx32 ENDP + +op_shlx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_SHIFT + shrx rax, rcx, rdx +ELSE + shlx rax, rcx, rdx +ENDIF + ret +op_shlx64 ENDP + +op_shrx32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_SHIFT + sarx eax, ecx, edx +ELSE + shrx eax, ecx, edx +ENDIF + ret +op_shrx32 ENDP + +op_shrx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_SHIFT + sarx rax, rcx, rdx +ELSE + shrx rax, rcx, rdx +ENDIF + ret +op_shrx64 ENDP + +op_sarx32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI2_SHIFT + shrx eax, ecx, edx +ELSE + sarx eax, ecx, edx +ENDIF + ret +op_sarx32 ENDP + +op_sarx64 PROC FRAME + .endprolog +IFDEF ALTER_BMI2_SHIFT + shrx rax, rcx, rdx +ELSE + sarx rax, rcx, rdx +ENDIF + ret +op_sarx64 ENDP + +; --- Flat [rcx|rdx|r8 + disp] m32 / m64 source forms --- +op_rorx32_mem PROC FRAME + .endprolog + mov rax, -1 + rorx eax, dword ptr [rcx+4], 9 + ret +op_rorx32_mem ENDP + +op_rorx64_mem PROC FRAME + .endprolog + rorx rax, qword ptr [rcx+8], 23 + ret +op_rorx64_mem ENDP + +op_shlx32_mem PROC FRAME + .endprolog + mov rax, -1 + mov r9d, dword ptr [rdx+4] + shlx eax, dword ptr [rcx+4], r9d + ret +op_shlx32_mem ENDP + +op_shlx64_mem PROC FRAME + .endprolog + mov r9, qword ptr [rdx+8] + shlx rax, qword ptr [rcx+8], r9 + ret +op_shlx64_mem ENDP + +op_shrx32_mem PROC FRAME + .endprolog + mov rax, -1 + mov r9d, dword ptr [rdx] + shrx eax, dword ptr [rcx+8], r9d + ret +op_shrx32_mem ENDP + +op_shrx64_mem PROC FRAME + .endprolog + mov r9, qword ptr [rdx] + shrx rax, qword ptr [rcx+16], r9 + ret +op_shrx64_mem ENDP + +op_sarx32_mem PROC FRAME + .endprolog + mov rax, -1 + mov r9d, dword ptr [rdx+8] + sarx eax, dword ptr [rcx+12], r9d + ret +op_sarx32_mem ENDP + +op_sarx64_mem PROC FRAME + .endprolog + mov r9, qword ptr [rdx+16] + sarx rax, qword ptr [rcx+24], r9 + ret +op_sarx64_mem ENDP + +; Store to [r8] then reload as m64 BMI2 source (tests [r8] base and program order). +op_mem_r8_source PROC FRAME + .endprolog + mov r9, qword ptr [rdx] + rorx r10, qword ptr [rcx], 17 + mov qword ptr [r8], r10 + sarx rax, qword ptr [r8], r9 + ret +op_mem_r8_source ENDP + +; --- Flag preservation: CMP -> RORX/SHLX/SHRX/SARX -> SETcc (CF/ZF/SF/OF/PF) --- +op_flags_preserve32 PROC FRAME + .endprolog + cmp ecx, edx + mov rax, -1 + rorx r9d, ecx, 5 + shlx r10d, r9d, edx + shrx r11d, r10d, edx + sarx eax, r11d, edx + setb byte ptr [r8] + sete byte ptr [r8+1] + sets byte ptr [r8+2] + seto byte ptr [r8+3] + setp byte ptr [r8+4] + movzx r9d, byte ptr [r8] + movzx r10d, byte ptr [r8+1] + mov r11d, 1 + shlx r10d, r10d, r11d + or r9d, r10d + movzx r10d, byte ptr [r8+2] + mov r11d, 2 + shlx r10d, r10d, r11d + or r9d, r10d + movzx r10d, byte ptr [r8+3] + mov r11d, 3 + shlx r10d, r10d, r11d + or r9d, r10d + movzx r10d, byte ptr [r8+4] + mov r11d, 4 + shlx r10d, r10d, r11d + or r9d, r10d + mov qword ptr [r8+8], r9 + ret +op_flags_preserve32 ENDP + +op_flags_preserve64 PROC FRAME + .endprolog + cmp rcx, rdx + rorx r9, rcx, 11 + shlx r10, r9, rdx + shrx r11, r10, rdx + sarx rax, r11, rdx + setb byte ptr [r8] + sete byte ptr [r8+1] + sets byte ptr [r8+2] + seto byte ptr [r8+3] + setp byte ptr [r8+4] + movzx r9, byte ptr [r8] + movzx r10, byte ptr [r8+1] + mov r11, 1 + shlx r10, r10, r11 + or r9, r10 + movzx r10, byte ptr [r8+2] + mov r11, 2 + shlx r10, r10, r11 + or r9, r10 + movzx r10, byte ptr [r8+3] + mov r11, 3 + shlx r10, r10, r11 + or r9, r10 + movzx r10, byte ptr [r8+4] + mov r11, 4 + shlx r10, r10, r11 + or r9, r10 + mov qword ptr [r8+8], r9 + ret +op_flags_preserve64 ENDP + +op_flags_preserve_mem PROC FRAME + .endprolog + mov r9, qword ptr [rcx] + mov r10, qword ptr [rdx] + cmp r9, r10 + rorx r11, qword ptr [rcx+8], 7 + shlx r11, qword ptr [rcx+16], r10 + shrx r11, qword ptr [rcx+24], r10 + sarx rax, qword ptr [rcx+8], r10 + setb byte ptr [r8] + sete byte ptr [r8+1] + sets byte ptr [r8+2] + seto byte ptr [r8+3] + setp byte ptr [r8+4] + ret +op_flags_preserve_mem ENDP + +; --- Discarded memory read must still fault on NULL rdx even under /O2 --- +op_bmi2_discarded_read PROC FRAME + .endprolog + rorx r9, qword ptr [rdx], 7 + mov rax, rcx + ret +op_bmi2_discarded_read ENDP + +END diff --git a/tests/cpu/bmi2_shift.def b/tests/cpu/bmi2_shift.def new file mode 100644 index 000000000..e4b13bce2 --- /dev/null +++ b/tests/cpu/bmi2_shift.def @@ -0,0 +1,26 @@ +EXPORTS + op_rorx32 + op_rorx32_imm32 + op_rorx32_imm37 + op_rorx64 + op_rorx64_imm64 + op_rorx64_imm73 + op_shlx32 + op_shlx64 + op_shrx32 + op_shrx64 + op_sarx32 + op_sarx64 + op_rorx32_mem + op_rorx64_mem + op_shlx32_mem + op_shlx64_mem + op_shrx32_mem + op_shrx64_mem + op_sarx32_mem + op_sarx64_mem + op_mem_r8_source + op_flags_preserve32 + op_flags_preserve64 + op_flags_preserve_mem + op_bmi2_discarded_read diff --git a/tests/cpu/bmi2_shift_check.py b/tests/cpu/bmi2_shift_check.py new file mode 100644 index 000000000..7a8541824 --- /dev/null +++ b/tests/cpu/bmi2_shift_check.py @@ -0,0 +1,698 @@ +"""Differential, /O2, flag-preservation, mutant, and rejection checks for cpu_bmi2_shift_aot.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi2_shift_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_rorx32", + "op_rorx32_imm32", + "op_rorx32_imm37", + "op_rorx64", + "op_rorx64_imm64", + "op_rorx64_imm73", + "op_shlx32", + "op_shlx64", + "op_shrx32", + "op_shrx64", + "op_sarx32", + "op_sarx64", + "op_rorx32_mem", + "op_rorx64_mem", + "op_shlx32_mem", + "op_shlx64_mem", + "op_shrx32_mem", + "op_shrx64_mem", + "op_sarx32_mem", + "op_sarx64_mem", + "op_mem_r8_source", + "op_flags_preserve32", + "op_flags_preserve64", + "op_flags_preserve_mem", + "op_bmi2_discarded_read", +) + +ALTERED_EXPORTS = ( + "op_rorx32", + "op_rorx64", + "op_shlx32", + "op_shlx64", + "op_shrx32", + "op_shrx64", + "op_sarx32", + "op_sarx64", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) +OUT_FILL = b"\x5A" * 16 + + +# --- Independent Python reference model --- + +def ref_rorx(val, imm8, bits, *, bad_mask=False): + mask = (1 << bits) - 1 + v = val & mask + c = (imm8 & 0xFF) if bad_mask else (imm8 & (bits - 1)) + if c == 0 or c >= bits: + return v if c == 0 else ((v >> (c % bits)) | (v << (bits - (c % bits)))) & mask + return ((v >> c) | (v << (bits - c))) & mask + + +def ref_shlx(val, cnt, bits, *, bad_mask=False): + mask = (1 << bits) - 1 + c = (cnt & 0x3F) if (bad_mask and bits == 32) else (cnt & (bits - 1)) + if c >= bits: + return 0 + return ((val & mask) << c) & mask + + +def ref_shrx(val, cnt, bits, *, bad_mask=False): + mask = (1 << bits) - 1 + c = (cnt & 0x3F) if (bad_mask and bits == 32) else (cnt & (bits - 1)) + if c >= bits: + return 0 + return (val & mask) >> c + + +def ref_sarx(val, cnt, bits, *, logical=False, bad_mask=False): + mask = (1 << bits) - 1 + c = (cnt & 0x3F) if (bad_mask and bits == 32) else (cnt & (bits - 1)) + if logical: + return 0 if c >= bits else ((val & mask) >> c) + sign = 1 << (bits - 1) + u = val & mask + s = u - (1 << bits) if (u & sign) else u + if c >= bits: + return mask if s < 0 else 0 + return (s >> c) & mask + + +def ref_cmp_flags(a, b, bits): + mask = (1 << bits) - 1 + sign = 1 << (bits - 1) + ua, ub = a & mask, b & mask + r = (ua - ub) & mask + cf = 1 if ua < ub else 0 + zf = 1 if r == 0 else 0 + sf = 1 if (r & sign) else 0 + of = 1 if (((ua ^ ub) & (ua ^ r)) & sign) else 0 + pf = 1 if (bin(r & 0xFF).count("1") % 2 == 0) else 0 + packed = (cf << 0) | (zf << 1) | (sf << 2) | (of << 3) | (pf << 4) + return (cf, zf, sf, of, pf), packed + + +def ref_reg(name, a, b, *, altered=False): + if name == "op_rorx32": + return ref_rorx(a, 7 if altered else 13, 32) + if name == "op_rorx32_imm32": + return ref_rorx(a, 32, 32) + if name == "op_rorx32_imm37": + return ref_rorx(a, 37, 32) + if name == "op_rorx64": + return ref_rorx(a, 11 if altered else 19, 64) + if name == "op_rorx64_imm64": + return ref_rorx(a, 64, 64) + if name == "op_rorx64_imm73": + return ref_rorx(a, 73, 64) + if name == "op_shlx32": + return ref_shrx(a, b, 32) if altered else ref_shlx(a, b, 32) + if name == "op_shlx64": + return ref_shrx(a, b, 64) if altered else ref_shlx(a, b, 64) + if name == "op_shrx32": + return ref_sarx(a, b, 32) if altered else ref_shrx(a, b, 32) + if name == "op_shrx64": + return ref_sarx(a, b, 64) if altered else ref_shrx(a, b, 64) + if name == "op_sarx32": + return ref_shrx(a, b, 32) if altered else ref_sarx(a, b, 32) + if name == "op_sarx64": + return ref_shrx(a, b, 64) if altered else ref_sarx(a, b, 64) + raise KeyError(name) + + +VALUES = ( + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000002, + 0x0000000000000003, + 0x0000000055AA55AA, + 0x000000007FFFFFFF, + 0x0000000080000000, + 0x0000000080000001, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, + 0xDEADBEEF80000001, + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, + 0x8000000000000001, + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, +) +COUNTS = (0, 1, 2, 5, 7, 15, 31, 32, 33, 63, 64, 65, 95, 127, 255, 0x100, 0xFFFFFFFF, 0x8000000000000020) + + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + """Verify EVEX, legacy shifts, BMI1/other BMI2, ABI, addressing, prefix, and state rejections.""" + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + mov_r9_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R9, R.RCX) + cmp_rcx_rdx = Instruction.create_reg_reg(Code.CMP_R64_RM64, R.RCX, R.RDX) + + # Alternate valid encodings accepted cleanly. + alt_accept = [ + ("rorx32_r11_r8_disp", (Instruction.create_reg_mem_u32( + Code.VEX_RORX_R32_RM32_IMM8, R.R11D, MemoryOperand(R.R8, displ=4, displ_size=1), 37), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "r11 = op_rorx32(ld_1000_1, static_cast(0x25u));"), + ("sarx64_r10_rdx_neg_disp", (Instruction.create_reg_mem_reg( + Code.VEX_SARX_R64_RM64_R64, R.R10, MemoryOperand(R.RDX, displ=-8, displ_size=1), R.RCX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R10), ret), + "r10 = op_sarx64(ld_1000_1, rcx);"), + ("shlx32_r9_rcx_r8d", (Instruction.create_reg_reg_reg( + Code.VEX_SHLX_R32_RM32_R32, R.R9D, R.ECX, R.R8D), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), ret), + "r9 = op_shlx32((rcx & 0xFFFFFFFFull), (r8 & 0xFFFFFFFFull));"), + ("shrx64_rax_r9_r10", (mov_r9_rcx, Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R10, R.RDX), + Instruction.create_reg_reg_reg(Code.VEX_SHRX_R64_RM64_R64, R.RAX, R.R9, R.R10), ret), + "rax = op_shrx64(r9, r10);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r} in:\n{src}") + + seg_rorx = Instruction.create_reg_mem_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, MemoryOperand(R.RCX), 5) + seg_rorx.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_bextr", (Instruction.create_reg_reg_u32(Code.XOP_BEXTR_R32_RM32_IMM32, R.EAX, R.ECX, 0x0804), ret), + "unsupported XOP instruction"), + # Legacy shifts/rotates (both cl and imm/1 forms) + ("legacy_shl_cl", (mov_rax_rcx, Instruction.create_reg_reg(Code.SHL_RM32_CL, R.EAX, R.CL), ret), + "unsupported instruction"), + ("legacy_shl_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM32_IMM8, R.EAX, 3), ret), + "unsupported instruction"), + ("legacy_shl_1", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHL_RM32_1, R.EAX, 1), ret), + "unsupported instruction"), + ("legacy_sar_cl", (mov_rax_rcx, Instruction.create_reg_reg(Code.SAR_RM32_CL, R.EAX, R.CL), ret), + "unsupported instruction"), + ("legacy_shr_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.SHR_RM32_IMM8, R.EAX, 4), ret), + "unsupported instruction"), + ("legacy_ror_imm", (mov_rax_rcx, Instruction.create_reg_u32(Code.ROR_RM32_IMM8, R.EAX, 5), ret), + "unsupported instruction"), + # BMI1 & other BMI2 instructions + ("bmi1_andn", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi1_bextr", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_mulx", (Instruction.create_reg_reg_reg(Code.VEX_MULX_R32_R32_RM32, R.EAX, R.R9D, R.ECX), ret), + "unsupported VEX instruction"), + ("bmi2_pdep", (Instruction.create_reg_reg_reg(Code.VEX_PDEP_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_pext", (Instruction.create_reg_reg_reg(Code.VEX_PEXT_R32_R32_RM32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_bzhi", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + # Nonvolatile GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RBX, R.RCX, 5), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R64_RM64_R64, R.RAX, R.RSI, R.RDX), ret), + "nonvolatile GPR"), + ("nonvol_r12_cnt", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.R12), ret), + "nonvolatile GPR"), + ("nonvol_rsp_dst", (Instruction.create_reg_reg_reg(Code.VEX_SHRX_R64_RM64_R64, R.RSP, R.RCX, R.RDX), mov_rax_rcx, ret), + "nonvolatile GPR"), + # Writes to argument GPRs (rcx/rdx/r8) + ("write_arg_rcx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RCX, R.RDX, 5), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R32_RM32_R32, R.EDX, R.ECX, R.R8D), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8", (Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R8, R.RCX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + # Undefined GPR / flag reads + ("undef_gpr_src", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.R9, 5), ret), + "undefined GPR r9"), + ("undef_gpr_cnt", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.R10), ret), + "undefined GPR r10"), + ("undef_flags_setb", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flags read"), + ("undef_flags_seto_after_bmi2", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), + Instruction.create_mem(Code.SETO_RM8, MemoryOperand(R.R8)), ret), "undefined flags read"), + ("undef_rax_ret", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.R9, R.RCX, 3), ret), + "return with undefined RAX"), + # Memory addressing & store base restrictions + ("rip_rel_rorx", (Instruction.create_reg_mem_u32( + Code.VEX_RORX_R64_RM64_IMM8, R.RAX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4), 3), ret), + "RIP-relative memory operand"), + ("sib_idx_shlx", (Instruction.create_reg_mem_reg( + Code.VEX_SHLX_R64_RM64_R64, R.RAX, MemoryOperand(R.RCX, R.RDX, 8), R.RDX), ret), + "SIB index memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem_reg( + Code.VEX_SARX_R64_RM64_R64, R.RAX, MemoryOperand(R.RBX), R.RDX), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem_reg( + Code.VEX_SHRX_R32_RM32_R32, R.EAX, MemoryOperand(R.RSP), R.EDX), ret), + "bad base register in memory operand"), + ("non_r8_store_mov", (mov_rax_rcx, Instruction.create_mem_reg(Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), + "non-r8 store memory operand"), + ("non_r8_store_setcc", (cmp_rcx_rdx, mov_rax_rcx, Instruction.create_mem(Code.SETE_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_rorx", (seg_rorx, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (mov_rax_rcx,), "missing terminal ret"), + ("after_ret", (mov_rax_rcx, ret, mov_r9_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("prefixed_vex_66_rorx", bytes.fromhex("66c4e37bf0c107c3"), "invalid instruction"), + ("empty_stream", b"", "truncated instruction stream"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE patching and CLI non-traceback rejection controls. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_flags_preserve64") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off : file_off + len(patch)] = patch + struct.pack_into(" RORX/SHLX/SHRX/SARX -> SETcc (CF/ZF/SF/OF/PF) + flag_pairs = [ + (0x0000000000000000, 0x0000000000000000), # ZF=1, PF=1 + (0x0000000000000000, 0x0000000000000001), # CF=1, SF=1, PF=1 + (0x0000000000000003, 0x0000000000000002), # all 0 (PF=0) + (0x0000000080000000, 0x0000000000000001), # 32-bit OF=1, PF=0 + (0x000000007FFFFFFF, 0x00000000FFFFFFFF), # 32-bit CF=1, SF=1, OF=1 + (0x8000000000000000, 0x0000000000000001), # 64-bit OF=1 + (0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF), # 64-bit CF=1, SF=1, OF=1 + (0x0000000000000020, 0x0000000000000020), # count=32 -> ZF=1 + (0xFFFFFFFFFFFFFFFC, 0x0000000000000004), # negative SARX witness + ] + [(rng.getrandbits(64), rng.getrandbits(64)) for _ in range(32)] + + seen_flags_32, seen_flags_64 = set(), set() + for a, b in flag_pairs: + for bits, name, seen in ((32, "op_flags_preserve32", seen_flags_32), + (64, "op_flags_preserve64", seen_flags_64)): + f_tuple, f_packed = ref_cmp_flags(a, b, bits) + seen.add(f_tuple) + r9 = ref_rorx(a, 5 if bits == 32 else 11, bits) + r10 = ref_shlx(r9, b, bits) + r11 = ref_shrx(r10, b, bits) + want_rax = ref_sarx(r11, b, bits) + want_buf = bytes(f_tuple) + OUT_FILL[5:8] + struct.pack("= 32 returning 0) must differ from lifted 37 & 31 = 5. + if lifted_fns["op_rorx32_imm37"](0x12345678, 0, 0) == 0: + raise AssertionError("mutant bad_mask on rorx32_imm37 survived") + # 2) Logical right shift instead of arithmetic on negative SARX32 / SARX64 + if lifted_fns["op_sarx32"](0x80000000, 4, 0) == ref_sarx(0x80000000, 4, 32, logical=True): + raise AssertionError("mutant logical_sarx32 survived") + if lifted_fns["op_sarx64"](0x8000000000000000, 4, 0) == ref_sarx(0x8000000000000000, 4, 64, logical=True): + raise AssertionError("mutant logical_sarx64 survived") + # 3) Flag-clobbering mutant: if BMI2 overwrote ZF=1 when shift result is 0, op_flags_preserve32 would fail + bo, po, oo, lo = alloc_guarded(OUT_FILL) + rax = lifted_fns["op_flags_preserve32"](0x00000001, 20, po) + # 1 < 20 -> CF=1, ZF=0, SF=1, OF=0, PF=0; yet rorx(1,5)=0x08000000, shlx(_,20)=0 -> rax=0! + assert rax == 0 + buf = read_guarded(bo, oo, lo, "flag_mutant") + if buf[1] != 0: + raise AssertionError("flag-preservation witness failed: ZF was clobbered to 1") + return diverged + + +def compile_o2_and_verify(original_path, native_fns, cxx_path): + source_text, _ = translate(original_path, list(EXPORTS)) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "bmi2_shift_o2.cpp" + dll_path = tmp / "bmi2_shift_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'bmi2_shift_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_exports(dll_path, "lifted_") + try: + return verify_positive_suite(native_fns, o2_fns, "lifted_o2") + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + check_rejections(original_path) + + lifted_lib, lifted_fns = bind_exports(lifted_path, "lifted_") + if not host_has_bmi2(lifted_lib): + lifted_fns.clear() + unload_lib(lifted_lib) + print("Host lacks BMI2 (CPUID leaf 7 subleaf 0 EBX bit 8); skipping native differential check") + sys.exit(77) + + orig_lib, orig_fns = bind_exports(original_path) + alt_lib, alt_fns = bind_exports(altered_path) + alt_lifted_lib, alt_lifted_fns = bind_exports(altered_lifted_path, "lifted_") + try: + lifted_cases = verify_positive_suite(orig_fns, lifted_fns, "lifted") + diverged = check_altered_and_mutants(lifted_fns, alt_fns, alt_lifted_fns) + o2_cases = compile_o2_and_verify(original_path, orig_fns, cxx_path) + finally: + for fn_map, lib in ( + (orig_fns, orig_lib), + (lifted_fns, lifted_lib), + (alt_fns, alt_lib), + (alt_lifted_fns, alt_lifted_lib), + ): + fn_map.clear() + unload_lib(lib) + + record_covered_forms(original_path) + print( + f"bmi2_shift passed: {lifted_cases} lifted + {o2_cases} /O2 cases across {len(EXPORTS)} exports; " + f"ALTER_BMI2_SHIFT diverged on {diverged}" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_bmi2_shift_aot.py b/tools/cpu_bmi2_shift_aot.py new file mode 100644 index 000000000..430ffc080 --- /dev/null +++ b/tools/cpu_bmi2_shift_aot.py @@ -0,0 +1,579 @@ +"""Lift bounded Windows x64 leaf functions with BMI2 RORX, SARX, SHLX, and SHRX to C++. + +Each export uses the leaf ABI: + std::uint64_t lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI2 shift/rotate instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - RORX r32, r/m32, imm8 | RORX r64, r/m64, imm8 (count masked to 5/6 bits) + - SARX r32, r/m32, r32 | SARX r64, r/m64, r64 (arithmetic right shift, 5/6-bit mask) + - SHLX r32, r/m32, r32 | SHLX r64, r/m64, r64 (logical left shift, 5/6-bit mask) + - SHRX r32, r/m32, r32 | SHRX r64, r/m64, r64 (logical right shift, 5/6-bit mask) + +All four BMI2 forms leave EFLAGS completely unmodified (CF, ZF, SF, OF, PF preserved across +CMP -> BMI2 shift -> SETcc). 32-bit destinations zero-extend into bits [63:32], and counts +mask modulo 32 (so count 32 shifts by 0) or modulo 64. Memory operands are flat +[rcx|rdx|r8 + disp] loads (m32/m64) read unconditionally via load_always() so /O2 cannot +eliminate faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, movzx, cmp, or, setcc (reg or [r8 + disp]), + flat [r8 + disp] stores, and terminal ret. + +EVEX/XOP encodings, legacy SHL/SAR/SHR/ROR, BMI1 (ANDN/BEXTR/...), other BMI2 (MULX/PDEP/ +PEXT/BZHI), nonvolatile GPRs (RBX/RBP/RSI/RDI/R12..R15/RSP), writes to argument GPRs +(rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads, RIP-relative/SIB-indexed/ +non-argument memory operands, stores outside [r8], instruction prefixes, branches/calls, +and missing or trailing instructions after ret are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", + R.RCX: "rcx", + R.RDX: "rdx", + R.R8: "r8", + R.R9: "r9", + R.R10: "r10", + R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", + R.ECX: "rcx", + R.EDX: "rdx", + R.R8D: "r8", + R.R9D: "r9", + R.R10D: "r10", + R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", + R.CX: "rcx", + R.DX: "rdx", + R.R8W: "r8", + R.R9W: "r9", + R.R10W: "r10", + R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", + R.CL: "rcx", + R.DL: "rdx", + R.R8L: "r8", + R.R9L: "r9", + R.R10L: "r10", + R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (width_bits, helper_name, is_imm8) +BMI2_SHIFT_SPECS = { + Code.VEX_RORX_R32_RM32_IMM8: (32, "op_rorx32", True), + Code.VEX_RORX_R64_RM64_IMM8: (64, "op_rorx64", True), + Code.VEX_SARX_R32_RM32_R32: (32, "op_sarx32", False), + Code.VEX_SARX_R64_RM64_R64: (64, "op_sarx64", False), + Code.VEX_SHLX_R32_RM32_R32: (32, "op_shlx32", False), + Code.VEX_SHLX_R64_RM64_R64: (64, "op_shlx64", False), + Code.VEX_SHRX_R32_RM32_R32: (32, "op_shrx32", False), + Code.VEX_SHRX_R64_RM64_R64: (64, "op_shrx64", False), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +CMP_WIDTHS = { + Code.CMP_R32_RM32: 32, + Code.CMP_RM32_R32: 32, + Code.CMP_RM32_IMM8: 32, + Code.CMP_RM32_IMM32: 32, + Code.CMP_EAX_IMM32: 32, + Code.CMP_R64_RM64: 64, + Code.CMP_RM64_R64: 64, + Code.CMP_RM64_IMM8: 64, + Code.CMP_RM64_IMM32: 64, + Code.CMP_RAX_IMM32: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SETCC_SPECS = { + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const T v = *reinterpret_cast(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + *reinterpret_cast(address) = value; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +// --- Flagless BMI2 shift / rotate helpers (5-bit count for 32-bit, 6-bit count for 64-bit) --- + +static inline word op_rorx32(word val, std::uint8_t imm8) { + const std::uint32_t v = static_cast(val); + // Mask to 5 bits before (32u - c) to avoid C++ shift-count UB when imm8 >= 32. + const unsigned c = static_cast(imm8 & 31u); + const std::uint32_t r = (c == 0u) ? v : ((v >> c) | (v << (32u - c))); + return static_cast(r); +} + +static inline word op_rorx64(word val, std::uint8_t imm8) { + // Mask to 6 bits before (64u - c) to avoid C++ shift-count UB when imm8 >= 64. + const unsigned c = static_cast(imm8 & 63u); + return (c == 0u) ? val : ((val >> c) | (val << (64u - c))); +} + +static inline word op_shlx32(word val, word cnt) { + const std::uint32_t v = static_cast(val); + const unsigned c = static_cast(cnt & 31ull); + return static_cast(v << c); +} + +static inline word op_shlx64(word val, word cnt) { + const unsigned c = static_cast(cnt & 63ull); + return val << c; +} + +static inline word op_shrx32(word val, word cnt) { + const std::uint32_t v = static_cast(val); + const unsigned c = static_cast(cnt & 31ull); + return static_cast(v >> c); +} + +static inline word op_shrx64(word val, word cnt) { + const unsigned c = static_cast(cnt & 63ull); + return val >> c; +} + +// Build sign fill explicitly on unsigned types so arithmetic right shift does not rely on signed >>. +static inline word op_sarx32(word val, word cnt) { + const std::uint32_t v = static_cast(val); + const unsigned c = static_cast(cnt & 31ull); + if (c == 0u) { + return static_cast(v); + } + const std::uint32_t sign = (v & 0x80000000u) ? (~0u << (32u - c)) : 0u; + return static_cast((v >> c) | sign); +} + +static inline word op_sarx64(word val, word cnt) { + const unsigned c = static_cast(cnt & 63ull); + if (c == 0u) { + return val; + } + const word sign = (val & 0x8000000000000000ull) ? (~0ull << (64u - c)) : 0ull; + return (val >> c) | sign; +} + +static inline void compute_cmp32(word lhs_w, word rhs_w, Flags& flags) { + const std::uint32_t a = static_cast(lhs_w); + const std::uint32_t b = static_cast(rhs_w); + const std::uint32_t r = a - b; + flags.cf = a < b; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((a ^ b) & (a ^ r)) & 0x80000000u) != 0u; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_cmp64(word a, word b, Flags& flags) { + const word r = a - b; + flags.cf = a < b; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((a ^ b) & (a ^ r)) >> 63) != 0ull; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi2() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (info[1] & (1 << 8)) ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat [base + disp] operand rooted in an argument GPR64 (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + disp = ins.memory_displacement & 0xFFFFFFFFFFFFFFFF + name = ARGUMENTS[base] + return f"({name} + {disp:#x}ull)" if disp else name + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI2 shift/rotate leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI2_SHIFT_SPECS: + if encoding != EncodingKind.VEX: + raise ValueError(f"expected VEX encoding for BMI2 shift at RVA {ins.ip:#x}: {ins}") + width, helper, is_imm8 = BMI2_SHIFT_SPECS[code] + src_expr = read_rm(1, ins, width) + if is_imm8: + if ins.op_kind(2) != OpKind.IMMEDIATE8: + raise ValueError(f"expected imm8 operand for rorx at RVA {ins.ip:#x}: {ins}") + rhs_expr = f"static_cast({ins.immediate8 & 0xFF:#x}u)" + else: + rhs_expr = read_reg(2, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = {helper}({src_expr}, {rhs_expr});") + defined_gpr.add(dst) + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in CMP_WIDTHS: + width = CMP_WIDTHS[code] + lhs_expr = read_rm(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"compute_cmp{width}({lhs_expr}, {rhs_expr}, flags);") + defined_flags.update(("cf", "zf", "sf", "of", "pf")) + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags.update(("cf", "zf", "sf", "of", "pf")) + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flags read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, [n for n in args.exports.split(",") if n]) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From 18bf5d342d48f6ef400e2621df0e4a3f692418e6 Mon Sep 17 00:00:00 2001 From: legacy-code-archaeologist Date: Wed, 25 Nov 2026 15:27:22 +0100 Subject: [PATCH 028/232] startup: lower 16-bit integer VOPC compares in gfx2hlsl (Part of #1723) (#2369) gfx2hlsl matched only the f32, i32 and u32 VOPC compares, so v_cmp_*_i16, v_cmp_*_u16, v_cmpx_*_i16 and v_cmpx_*_u16 were refused as unknown instructions. It now lowers the six relations lt, eq, le, gt, ne and ge in the _e32 and _e64 encodings (24 v_cmp and 24 v_cmpx forms). Each source is bits 15:0 of the operand, sign-extended for i16 and zero-extended for u16, as in the RDNA 2 ISA guide and LLVM 15's gfx1013 selection. Destinations are handled as for the 32-bit integer compares. Refused: inline float constants (binary16 on 16-bit operands), literals wider than 16 bits, register ranges, vcc/exec/m0 sources, op_sel, clamp, the NEG and ABS bits of the _e64 form (checked in the raw word) and the SDWA forms. tests/startup_gfx2hlsl_cmp16_check.py adds translation controls (60 decoded cases, 71 refusals), an LLVM binary mode for all 105 control forms and the fixtures, and FXC/DXC draws on WARP and hardware with two mutated lowerings that must fail against the reference. A capability skip in draw mode reports earlier failures instead of hiding them. AI-assisted. Co-authored-by: legacy-code-archaeologist <359844974+legacy-code-archaeologist@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 10 + docs/experiments.md | 31 ++ tests/startup_gfx2hlsl_cmp16_check.py | 557 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 39 +- 6 files changed, 639 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_cmp16_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index c4e012e20..dd99cd9ad 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -83,6 +83,7 @@ jobs: (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_cmp16_check.py", "binary", "llvm-mc-15", "llvm-objcopy-15"], {}), (["tests/startup_image_sample_l_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_b_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_lod_check.py", "binary", "llvm-mc-15"], {}), @@ -254,6 +255,7 @@ jobs: tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ + tests/startup_gfx2hlsl_cmp16_check.py \ tests/startup_gfx2hlsl_sdwa_cvt_check.py \ tests/startup_gfx2hlsl_sop2_complement_check.py \ tests/startup_gfx2hlsl_sopk_accum_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 31913e014..75c0bc30c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -226,6 +226,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sgpr_spill_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_shift64_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_vopc_sdwa_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cmp16_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_lg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e303d6a1b..45a9bab6c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2982,6 +2982,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_u8_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl 16-bit integer VOPC compares (v_cmp/v_cmpx _i16/_u16, #1723): translation controls, then draws of a + # census-shaped v_cmpx kill and of every condition folded into mask words, with mutated lowerings. + add_test(NAME startup_gfx2hlsl_cmp16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cmp16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp16_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cmp16_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_sampler_heap_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_sampler_heap_check.py") add_test(NAME startup_vertex_fetch_formats_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 984d9a039..241796df4 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13343,6 +13343,37 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mask_overwrite_control ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_add_sub_co_controls$' -V ``` +## Startup translator: 16-bit integer compares + +`tools/startup/gfx2hlsl.py` matched only the f32, i32 and u32 VOPC compares, so `v_cmp_*_i16`, `v_cmp_*_u16`, `v_cmpx_*_i16` and `v_cmpx_*_u16` were refused as unknown instructions. It now lowers the six relations `lt`, `eq`, `le`, `gt`, `ne` and `ge` (gfx10 has no 16-bit `f` or `t`) in the `_e32` and `_e64` encodings: 24 `v_cmp` and 24 `v_cmpx` forms. Following the AMD RDNA 2 ISA guide, each source is bits 15:0 of the operand, compared as `S0.i16` or `S0.u16`. An i16 register reads as `asint(x << 16u) >> 16u` and a u16 register as `x & 0xffffu`. LLVM 15 models the same: for gfx1013, `icmp slt i16` of two truncated 32-bit values selects `v_cmp_lt_i16_e32` on the whole VGPRs, and it encodes the literal `0xffff` on these operands as the inline constant -1. Sources are a VGPR, an SGPR, an inline integer from -16 to 64, or a literal up to `0xffff`. The destinations are the same as for the 32-bit integer compares: `vcc`, an SGPR lane mask, or EXEC for `v_cmpx`, intersected with EXEC when EXEC is not known. + +The following are refused: + +- Inline float constants. On a 16-bit operand they are binary16 values (LLVM 15 prints inline `1.0` there as `0x3c00`), while the translator would read the binary32 word. +- Wider literals, register ranges, and `vcc`, `exec` or `m0` as a source. +- `op_sel` and `clamp`. +- The NEG and ABS bits of the `_e64` form, checked in the raw word. The disassembler prints NEG on inline 1 as `-1`, the same text as inline -1. +- The SDWA forms. `tools/pixel_aot.py` keeps its own lowering of these compares, including SDWA (see the VOPC SDWA and 16-bit integer comparison paragraphs under [Pixel color without a texture sample](#pixel-color-without-a-texture-sample)); the startup translator does not use it. + +`tests/startup_gfx2hlsl_cmp16_check.py` has three modes: + +- **Controls.** It decodes 60 synthetic cases (12 `v_cmp` e32 into `vcc`, 12 e64 into `vcc_lo`, 12 e64 into `s4`, 24 `v_cmpx` into EXEC) and evaluates the emitted HLSL with the restricted evaluator of `startup_gfx2hlsl_bit_alu_check.py`. The inputs are words whose high halves carry junk and whose low halves include `0x8000`, `0x7fff`, `0xffff` and equal halves. The references are written with plain integer arithmetic from the ISA meaning. It also checks SGPR, inline and literal operands, the EXEC intersection and 71 refusals. A last control covers the unused `s0` that the disassembler prints for an `_e64` `v_cmpx`: a value set in `s0` before the compare still reads back after it, as for the 32-bit form. +- **`binary`.** It assembles all 105 control forms and five fixtures with LLVM (`-filetype=obj`, `.text` extracted with `llvm-objcopy`) and compares the words. It also pins that LLVM encodes the literal `0xffff` on an i16 operand as inline -1. +- **`draw`.** It draws three source-built pixel programs on 16 x 16 pixels, with FXC `ps_5_1` and DXC `ps_6_0`. The programs derive two words from the packed position, the second with junk in the high half and sometimes bit 15 and low bits flipped. They are a `v_cmpx_le_i16_e32` kill, a `v_cmpx_gt_u16_e64` kill, and all six relations of the i16 and u16 e32 forms and of the e64 forms with the constants -16 and `0x8000`, folded into mask words. Two mutated translations must each fail against the reference and match their own image: an i16 register read zero-extended, and a u16 register read as the whole word. + +On `43608f2e` plus the changes described here, the controls and draws passed on Windows 11 build 10.0.26100 with the debug layer unavailable. The binary mode passed locally with the official LLVM 15.0.7 Windows build, which ships no `llvm-mc`: a local wrapper passed the `llvm-mc` arguments to that build's integrated assembler (`clang -cc1as`), and its `llvm-objcopy` extracted `.text`. The CI LLVM 15 job runs the same mode with `llvm-mc-15`; that run is not measured yet. The draws ran on: + +- WARP (Microsoft Basic Render Driver 10.0.26100.8972). +- NVIDIA Quadro M1000M (driver 32.0.15.7371), the default hardware adapter. +- Intel HD Graphics 530 (driver 31.0.101.2111), selected with `XBOX2WINDOWS_ADAPTER=Intel`. + +On `417a101c` without the translator change, the controls stop at the first translated case with `Unsupported: v_cmp_eq_i16`. The draws check the translated HLSL on desktop adapters against the reference. No gfx1013 hardware run checks these instructions. Tests: `startup_gfx2hlsl_cmp16_controls`, `startup_gfx2hlsl_cmp16_warp` and `startup_gfx2hlsl_cmp16_hardware`. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp16_' -V +python -B tests/startup_gfx2hlsl_cmp16_check.py binary +``` + ## Startup translator: explicit-LOD image sampling `tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) diff --git a/tests/startup_gfx2hlsl_cmp16_check.py b/tests/startup_gfx2hlsl_cmp16_check.py new file mode 100644 index 000000000..b78d86ca4 --- /dev/null +++ b/tests/startup_gfx2hlsl_cmp16_check.py @@ -0,0 +1,557 @@ +"""16-bit integer VOPC compares in tools/startup/gfx2hlsl.py: v_cmp_*_{i16,u16} and v_cmpx_*_{i16,u16}, e32 and e64. + + (no arguments) translation controls and fixture checks, pure Python + binary assemble every control form and the pixel fixtures with LLVM + (-filetype=obj, .text extracted with llvm-objcopy) and compare with the words + built or recorded here + draw [fxc] + compile the pixel fixtures with FXC ps_5_1 when given and with DXC ps_6_0, + draw 16 x 16 pixels and compare every pixel with the plain-integer reference + +Semantics, from the AMD RDNA 2 ISA guide (VOPC opcodes): V_CMP__I16 sets the lane bit to S0.i16 S1.i16 and +V_CMP__U16 to S0.u16 S1.u16, the 16-bit source being bits 15:0 of the operand; v_cmpx writes the result to +EXEC. LLVM 15 models the same: `icmp slt i16` of two truncated 32-bit values selects v_cmp_lt_i16_e32 on the whole +VGPRs, and the i16 operands take 16-bit literals only. The references below are written from that meaning with plain +integer arithmetic: the low half, sign-extended for i16 or zero-extended for u16, compared as the condition says. + +Controls: all 60 decoded cases (12 v_cmp e32 into vcc, 12 v_cmp e64 into vcc_lo, 12 into s4, 24 v_cmpx into EXEC) +evaluated on the CPU with the integer evaluator of startup_gfx2hlsl_bit_alu_check.py over words whose high halves +carry junk; SGPR, inline and literal operands; the EXEC intersection when EXEC is not known; the refusals (SDWA, +op_sel, clamp, NEG/ABS bits, inline float constants, literals wider than 16 bits, register ranges, vcc/exec/m0 +sources, vcc_hi/m0 destinations); the 32-bit forms unchanged; and the unused s0 that the decoder prints for an e64 +v_cmpx: an SGPR value set in s0 before the compare still reads back after it, as for the 32-bit form. + +The draws: a pixel program derives v1 and v2 from the packed screen position (v2 is v1 with junk in the high half and +sometimes bit 15 and low bits flipped), then + K v_cmpx_le_i16_e32 v1, v2 (a killed pixel keeps the clear value -1.0) + K64 v_cmpx_gt_u16_e64 v2, v1 + M for each of lt, eq, le, gt, ne, ge (bit k): v12 v_cmp_C_i16_e32 vcc_lo, v1, v2; v13 v_cmp_C_u16_e32 vcc_lo, v1, + v2; v14 v_cmp_C_i16_e64 s4, v2, -16; v15 v_cmp_C_u16_e64 s4, 0x8000, v1; each bit folded in with + v_cndmask_b32_e64 and v_or_b32, then every word ORed with 0x3f800000 (a normal binary32 word) and exported. +Expected image per pixel p = x | y << 16: a = p * 0x9b5d, b = a ^ (p * 0x6d2b & 0xffff800f) (32-bit products); +K keeps 0x3f800000 | p in all four words when ext_i16(a) <= ext_i16(b), else 0xbf800000; K64 when +ext_u16(b) > ext_u16(a); +M writes 0x3f800000 | sum(1 << k for each condition k that holds) per channel with the operands above. +Two mutated translations (register sources only; constants unchanged): `no sext` reads an i16 register as its +zero-extended low half (an int in 0..65535), `whole word` reads a u16 register as the whole 32-bit word. Each mutated +draw must fail against the reference and match the image of the same formula with the mutated register reading. + +Not covered: gfx1013 hardware (the draws run the translated HLSL on desktop adapters), the SDWA forms (refused here; +tools/pixel_aot.py lowers them on its own), and inline float constants on 16-bit operands (refused). +""" +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 disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +import startup_image_3d_check as I3 # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +CONDITIONS = ('lt', 'eq', 'le', 'gt', 'ne', 'ge') +RELATION = {'lt': lambda x, y: x < y, 'eq': lambda x, y: x == y, 'le': lambda x, y: x <= y, + 'gt': lambda x, y: x > y, 'ne': lambda x, y: x != y, 'ge': lambda x, y: x >= y} +# (cmpx, condition, type) -> VOPC opcode, from the decoder's table. +OPCODES = {} +for _op, (_name, _) in D.VOPC_OPS.items(): + _m = re.fullmatch(r'v_cmp(x?)_(\w+)_([iu]16)_e32', _name) + if _m: + OPCODES[_m.group(1) == 'x', _m.group(2), _m.group(3)] = _op + +VCC_LO, VCC_HI, M0, LITERAL = 106, 107, 124, 255 +SGPR_DST = 4 + + +def V(n): + return 256 + n + + +def inline(value): + return 128 + value if value >= 0 else 192 - value + + +def e32(op, src0, vsrc1, literal=None): + word = (0b0111110 << 25) | (op << 17) | (vsrc1 << 9) | src0 + return struct.pack('> 31 else v) if typ == 'i16' else (lambda v: v) + return int(RELATION[cond](s(a), s(b))) + + +# High halves carry junk; low halves include 0, 1, 0x7fff, 0x8000, 0xffff and equal halves under different highs. +VALUES = [0x00000000, 0x12340000, 0xabcd8000, 0x00007fff, 0x5a5affff, 0xffff0001, 0x80000001, 0x7fff8000, + 0x0000ffff, 0xfedc7fff] +PAIRS = [(a, b) for a in VALUES for b in VALUES] + +# ---- translation --------------------------------------------------------------------------------------------------- +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +class Probe(G.Stage): + """A Stage with no pipeline: enough state for decoded instructions to be translated.""" + + def __init__(self, exec_known=True): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = exec_known + + +def decode_one(code): + decoded = G.decode(code) + assert len(decoded) == 1 and decoded[0][1] == len(code), decoded + return decoded[0][2], decoded[0][3] + + +def translate(code, exec_known=True): + """(decoded text, destination, expression) of one compare.""" + name, asm = decode_one(code) + stage = Probe(exec_known) + stage.one(name, asm) + assert len(stage.lines) == 1, stage.lines + m = re.fullmatch(r'(\w+) = (.*);', stage.lines[0]) + assert m, stage.lines + return asm, m.group(1), m.group(2) + + +def refusal(code=None, name=None, asm=None): + try: + if code is not None: + name, asm = decode_one(code) + Probe().one(name, asm) + except G.Unsupported as error: + return str(error) + return None + + +def forms(): + """(label, code, destination, cmpx, condition, type) for the 60 decoded cases.""" + for (cmpx, cond, typ), op in sorted(OPCODES.items()): + if cmpx: + yield 'e32', e32(op, V(1), 2), 'exec', cmpx, cond, typ + yield 'e64', e64(op, 0, V(1), V(2)), 'exec', cmpx, cond, typ + else: + yield 'e32', e32(op, V(1), 2), 'vcc', cmpx, cond, typ + yield 'e64 vcc_lo', e64(op, VCC_LO, V(1), V(2)), 'vcc', cmpx, cond, typ + yield 'e64 s4', e64(op, SGPR_DST, V(1), V(2)), 's4', cmpx, cond, typ + + +def llvm_text(asm): + """The LLVM 15 source spelling of a decoded form: an e64 v_cmpx is written without the unused s0.""" + return re.sub(r'^(v_cmpx_\w+_e64) s0, ', r'\1 ', asm) + + +def controls(): + # 1. The encoder writes what LLVM 15 assembles (bytes recorded with the binary mode of this check). + known = [ + (e32(OPCODES[False, 'lt', 'i16'], V(1), 2), '0105127d'), + (e64(OPCODES[False, 'lt', 'i16'], SGPR_DST, V(1), V(2)), '040089d401050200'), + (e32(OPCODES[True, 'le', 'i16'], V(1), 2), '0105367d'), + (e64(OPCODES[True, 'le', 'i16'], 0, V(1), 2), '00009bd401050000'), + (e32(OPCODES[False, 'lt', 'i16'], inline(-1), 2), 'c104127d'), + (e64(OPCODES[False, 'lt', 'i16'], SGPR_DST, inline(-16), 5), '040089d4d00a0000'), + (e32(OPCODES[False, 'lt', 'i16'], LITERAL, 2, 0x8000), 'ff04127d00800000'), + ] + check('encoder matches LLVM 15 encodings', all(code.hex() == want for code, want in known), + str([(code.hex(), want) for code, want in known if code.hex() != want])) + check('24 opcodes: 6 conditions x i16/u16 x v_cmp/v_cmpx', + sorted(OPCODES) == sorted((x, c, t) for x in (False, True) for c in CONDITIONS for t in ('i16', 'u16'))) + + # 2. The value set separates the reference from whole-word compares and, for the ordered relations, from the + # opposite signedness. + for typ in ('i16', 'u16'): + other = 'u16' if typ == 'i16' else 'i16' + for cond in CONDITIONS: + check('values separate %s %s from a whole-word compare' % (cond, typ), + any(reference(cond, typ, a, b) != whole(cond, typ, a, b) for a, b in PAIRS)) + if cond not in ('eq', 'ne'): + check('values separate %s %s from %s' % (cond, typ, other), + any(reference(cond, typ, a, b) != reference(cond, other, a, b) for a, b in PAIRS)) + + # 3. The 60 decoded cases, evaluated. + count = 0 + for label, code, destination, cmpx, cond, typ in forms(): + asm, dst, expr = translate(code) + tree = Expr(expr) + wrong = [(hex(a), hex(b)) for a, b in PAIRS + if tree.run({'v1': a, 'v2': b})[0] != reference(cond, typ, a, b)] + check('%s -> %s' % (asm, dst), dst == destination and not wrong, '%s first wrong pairs %s' % (expr, wrong[:3])) + count += 1 + check('60 decoded cases', count == 60) + + # 4. Other operand kinds: an SGPR, inline integers and 16-bit literals, in both orders. + op = OPCODES[False, 'lt', 'i16'], OPCODES[False, 'lt', 'u16'], OPCODES[False, 'ge', 'u16'] + constants = [(inline(-16), None, -16), (inline(-1), None, -1), (inline(0), None, 0), (inline(64), None, 64), + (LITERAL, 0x8000, 0x8000), (LITERAL, 0x7fff, 0x7fff), (LITERAL, 0xffef, 0xffef)] + for opcode in op: + _, cond, typ = next(k for k, v in OPCODES.items() if v == opcode) + for src, literal, value in constants: + for order in (0, 1): + code = (e64(opcode, SGPR_DST, src, V(2), literal) if order == 0 + else e64(opcode, SGPR_DST, V(2), src, literal)) + asm, _, expr = translate(code) + tree = Expr(expr) + ok = all(tree.run({'v2': w})[0] == (reference(cond, typ, value & MASK, w) if order == 0 + else reference(cond, typ, w, value & MASK)) for w in VALUES) + check('%s' % asm, ok, expr) + asm, _, expr = translate(e64(opcode, SGPR_DST, 5, V(2))) + tree = Expr(expr) + check('%s (SGPR source)' % asm, all(tree.run({'s5': a, 'v2': b})[0] == reference(cond, typ, a, b) + for a, b in PAIRS), expr) + + # 5. EXEC not known: every destination is intersected with EXEC. + for label, code, destination, cmpx, cond, typ in forms(): + asm, dst, expr = translate(code, exec_known=False) + tree = Expr(expr) + ok = expr.startswith('(exec & ') and all( + tree.run({'v1': a, 'v2': b, 'exec': e})[0] == (e & reference(cond, typ, a, b)) + for a, b in PAIRS[:20] for e in (0, 1)) + if not ok: + check('%s with EXEC unknown' % asm, False, expr) + break + else: + check('all 60 cases intersect with an unknown EXEC', True) + + # 6. Refusals. + lt_i16, cmpx_lt_u16 = OPCODES[False, 'lt', 'i16'], OPCODES[True, 'lt', 'u16'] + refused = [] + for (cmpx, cond, typ), opcode in sorted(OPCODES.items()): + name = 'v_cmp%s_%s_%s_sdwa' % ('x' if cmpx else '', cond, typ) + text = '%s %sv1, v2 src0_sel:DWORD src1_sel:DWORD' % (name, '' if cmpx else 's6, ') + refused.append(('SDWA ' + name, refusal(name=name, asm=text) == name)) + refused += [ + ('op_sel', 'op_sel' in (refusal(e64(lt_i16, SGPR_DST, V(1), V(2), opsel=1)) or '')), + ('clamp', 'clamp' in (refusal(e64(lt_i16, SGPR_DST, V(1), V(2), clamp=1)) or '')), + ] + for bit in range(3): + for src0 in (V(1), inline(1)): + refused.append(('NEG bit %d on %d' % (bit, src0), + 'neg/abs' in (refusal(e64(lt_i16, SGPR_DST, src0, V(2), neg=1 << bit)) or ''))) + refused.append(('ABS bit %d on %d' % (bit, src0), + 'neg/abs' in (refusal(e64(lt_i16, SGPR_DST, src0, V(2), absolute=1 << bit)) or ''))) + for field in ('neg', 'absolute'): # inline 1 as src1, with the src1 bit + refused.append(('%s on inline 1 in src1' % field, + 'neg/abs' in (refusal(e64(lt_i16, SGPR_DST, V(1), inline(1), **{field: 2})) or ''))) + for code in range(240, 249): + refused.append(('inline float %d e32' % code, + 'binary16' in (refusal(e32(lt_i16, code, 2)) or ''))) + refused.append(('inline float %d e64 src1' % code, + 'binary16' in (refusal(e64(cmpx_lt_u16, 0, V(1), code)) or ''))) + refused.append(('literal 0x18000', 'wider than 16 bits' in (refusal(e32(lt_i16, LITERAL, 2, 0x18000)) or ''))) + for token in ('-17', 's[2:3]', 'v[1:2]', 'vcc_lo', 'exec_lo', 'm0', '-v1', '|v1|', 'neg(v1)'): + refused.append(('source %s' % token, refusal(name='v_cmp_lt_i16_e64', + asm='v_cmp_lt_i16_e64 s4, %s, v2' % token) is not None)) + refused.append(('destination vcc_hi', 'into vcc_hi' in (refusal(e64(lt_i16, VCC_HI, V(1), V(2))) or ''))) + refused.append(('destination m0', 'into m0' in (refusal(e64(lt_i16, M0, V(1), V(2))) or ''))) + refused.append(('no 16-bit f', refusal(name='v_cmp_f_i16_e64', asm='v_cmp_f_i16_e64 s4, v1, v2') + == 'v_cmp_f_i16')) + bad = [label for label, ok in refused if not ok] + check('%d refusals' % len(refused), not bad, str(bad)) + + # 7. The 32-bit forms are unchanged. + stage = Probe() + stage.one('v_cmp_lt_i32_e32', 'v_cmp_lt_i32_e32 vcc_lo, v1, v2') + stage.one('v_cmpx_gt_u32_e64', 'v_cmpx_gt_u32_e64 exec_lo, v3, s4') + check('32-bit compares unchanged', stage.lines == ['vcc = ((int(v1) < int(v2)) ? 1u : 0u);', + 'exec = ((v3 > s4) ? 1u : 0u);'], str(stage.lines)) + + # 8. The unused s0 of an e64 v_cmpx: a value set in s0 before the compare reads back after it, as it does for + # the 32-bit form (the decoder prints s0, and the translation must not treat it as written). + for words, name in ((S0_I16_WORDS, 'v_cmpx_le_i16_e64'), (S0_I32_WORDS, 'v_cmpx_le_i32_e64')): + decoded = [asm for _o, _s, _n, asm in G.decode(words)] + text = G.Pipeline(I3.VS_WORDS, words, I3.root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + body = text[text.index('s0 = 0x00001234u;'):] + check('%s keeps s0 readable' % name, + decoded[3] == '%s s0, v1, v2' % name and 'if (exec & 1) v3 = 0x00001234u;' in body + and not re.search(r'^\s*s0 = (?!0x00001234u;)', body, re.M), body) + + +# ---- the pixel fixtures -------------------------------------------------------------------------------------------- +WIDTH = HEIGHT = 16 +M1, M2, FLIP = 0x9b5d, 0x6d2b, 0xffff800f +CLEAR = 0xbf800000 # -1.0, the target's clear value: a killed pixel keeps it +ONE = 0x3f800000 +PACKED = (0x8000, 0x8000) # SPI_PS_INPUT_ENA/ADDR: the packed screen position only, in v0 +PROLOGUE = ('v_mul_u32_u24_e32 v1, 0x%x, v0\nv_mul_u32_u24_e32 v2, 0x%x, v0\nv_and_b32_e32 v2, 0x%x, v2\n' + 'v_xor_b32_e32 v2, v1, v2\n' % (M1, M2, FLIP)) +# Each exported word is the packed position ORed with 0x3f800000, a normal binary32 value. +EXPORT_V0 = 'v_or_b32_e32 v3, 0x3f800000, v0\nexp mrt0 v3, v3, v3, v3 done vm\ns_endpgm\n' +K_SOURCE = PROLOGUE + 'v_cmpx_le_i16_e32 v1, v2\n' + EXPORT_V0 +K64_SOURCE = PROLOGUE + 'v_cmpx_gt_u16_e64 v2, v1\n' + EXPORT_V0 +M_CHANNELS = (('v_cmp_%s_i16_e32 vcc_lo, v1, v2', 'vcc_lo'), ('v_cmp_%s_u16_e32 vcc_lo, v1, v2', 'vcc_lo'), + ('v_cmp_%s_i16_e64 s4, v2, -16', 's4'), ('v_cmp_%s_u16_e64 s4, 0x8000, v1', 's4')) +M_SOURCE = PROLOGUE + ''.join('v_mov_b32_e32 v%d, 0\n' % r for r in range(12, 16)) + ''.join( + (cmp % cond) + '\nv_cndmask_b32_e64 v10, 0, %d, %s\nv_or_b32_e32 v%d, v%d, v10\n' % (1 << k, mask, 12 + c, 12 + c) + for k, cond in enumerate(CONDITIONS) for c, (cmp, mask) in enumerate(M_CHANNELS)) + ''.join( + 'v_or_b32_e32 v%d, 0x3f800000, v%d\n' % (r, r) for r in range(12, 16)) + 'exp mrt0 v12, v13, v14, v15 done vm\ns_endpgm\n' +PROLOGUE_WORDS = 'ff0002165d9b0000ff0004162b6d0000ff0404360f80ffff0105043a' +K_WORDS = bytes.fromhex(PROLOGUE_WORDS + '0105367d' + 'f20006380f1800f803030303000081bf') +K64_WORDS = bytes.fromhex(PROLOGUE_WORDS + '0000bcd402030200' + 'f20006380f1800f803030303000081bf') +M_WORDS = bytes.fromhex( + PROLOGUE_WORDS + '8002187e80021a7e80021c7e80021e7e' + '0105127d0a0001d58002a9010c1518380105527d0a0001d58002a9010d151a38040089d402a101000a0001d5800211000e151c38' + '0400a9d4ff020200008000000a0001d5800211000f151e380105147d0a0001d58004a9010c1518380105547d0a0001d58004a901' + '0d151a3804008ad402a101000a0001d5800411000e151c380400aad4ff020200008000000a0001d5800411000f151e380105167d' + '0a0001d58008a9010c1518380105567d0a0001d58008a9010d151a3804008bd402a101000a0001d5800811000e151c380400abd4' + 'ff020200008000000a0001d5800811000f151e380105187d0a0001d58010a9010c1518380105587d0a0001d58010a9010d151a38' + '04008cd402a101000a0001d5801011000e151c380400acd4ff020200008000000a0001d5801011000f151e3801051a7d0a0001d5' + '8020a9010c15183801055a7d0a0001d58020a9010d151a3804008dd402a101000a0001d5802011000e151c380400add4ff020200' + '008000000a0001d5802011000f151e3801051c7d0a0001d58040a9010c15183801055c7d0a0001d58040a9010d151a3804008ed4' + '02a101000a0001d5804011000e151c380400aed4ff020200008000000a0001d5804011000f151e38f2181838f21a1a38f21c1c38' + 'f21e1e380f1800f80c0d0e0f000081bf') +S0_SOURCE = ('v_mov_b32_e32 v1, v0\nv_lshrrev_b32_e32 v2, 16, v0\ns_mov_b32 s0, 0x1234\n%s v1, v2\n' + 'v_mov_b32_e32 v3, s0\nexp mrt0 v3, v3, v3, v3 done vm\ns_endpgm\n') +S0_I16_WORDS = bytes.fromhex('0003027e9000042cff0380be3412000000009bd4010502000002067e0f1800f803030303000081bf') +S0_I32_WORDS = bytes.fromhex('0003027e9000042cff0380be34120000000093d4010502000002067e0f1800f803030303000081bf') +FIXTURES = {'K': (K_SOURCE, K_WORDS), 'K64': (K64_SOURCE, K64_WORDS), 'M': (M_SOURCE, M_WORDS), + 'S0 i16': (S0_SOURCE % 'v_cmpx_le_i16_e64', S0_I16_WORDS), + 'S0 i32': (S0_SOURCE % 'v_cmpx_le_i32_e64', S0_I32_WORDS)} + +# Mutations of the translated text: (pattern, replacement, expected count per program). +MUTATIONS = { + 'no sext': (r'\(asint\((v\d+) << 16u\) >> 16u\)', r'asint(\1 & 0xffffu)', {'K': 2, 'M': 18}), + 'whole word': (r'\((v\d+) & 0xffffu\)', r'\1', {'K64': 2, 'M': 18}), +} + + +def operands(position): + a = (position * M1) & MASK # both factors are below 2^24, so v_mul_u32_u24 is the plain product + return a, a ^ ((position * M2) & MASK & FLIP) + + +def read(word, typ, how): + """A register source as the (possibly mutated) translation reads it.""" + if typ == 'i16' and how == 'no sext': + return word & 0xffff + if typ == 'u16' and how == 'whole word': + return word + return ext(word, typ) + + +def holds(cond, typ, x, y, how): + """x and y are ('r', word) for a register or ('c', value) for a constant, which no mutation changes.""" + vx, vy = ((read(v, typ, how) if kind == 'r' else v) for kind, v in (x, y)) + return RELATION[cond](vx, vy) + + +def image(program, how='reference'): + words = [] + for y in range(HEIGHT): + for x in range(WIDTH): + position = x | (y << 16) + a, b = operands(position) + if program == 'K': + words += [ONE | position] * 4 if holds('le', 'i16', ('r', a), ('r', b), how) else [CLEAR] * 4 + elif program == 'K64': + words += [ONE | position] * 4 if holds('gt', 'u16', ('r', b), ('r', a), how) else [CLEAR] * 4 + else: + channels = [('i16', ('r', a), ('r', b)), ('u16', ('r', a), ('r', b)), + ('i16', ('r', b), ('c', -16)), ('u16', ('c', 0x8000), ('r', a))] + words += [ONE | sum(1 << k for k, cond in enumerate(CONDITIONS) if holds(cond, typ, x0, y0, how)) + for typ, x0, y0 in channels] + return words + + +def pixel_hlsl(program, how='reference'): + text = G.Pipeline(I3.VS_WORDS, FIXTURES[program][1], I3.root_blob(), ps_hw_inputs=PACKED).hlsl_ps() + if how != 'reference': + pattern, replacement, counts = MUTATIONS[how] + text, count = re.subn(pattern, replacement, text) + assert count == counts[program], (program, how, count) + return text + + +def expected_decode(source): + lines = [llvm_line.replace('0x3f800000', '1.0') for llvm_line in source.splitlines()] + return [re.sub(r'^(v_cmpx_\w+_e64) ', r'\1 s0, ', line) for line in lines] + + +def check_fixture(): + for name, (source, words) in FIXTURES.items(): + decoded = [asm for _o, _s, _n, asm in G.decode(words)] + check('%s fixture decodes to its source' % name, decoded == expected_decode(source), str(decoded)) + pairs = [operands(x | (y << 16)) for y in range(HEIGHT) for x in range(WIDTH)] + equal = sum((a ^ b) & 0xffff == 0 for a, b in pairs) + crossing = sum((a ^ b) >> 15 & 1 for a, b in pairs) + high = sum((a ^ b) >> 16 != 0 for a, b in pairs) + check('position pairs: %d equal low halves, %d differ in bit 15, %d differ in the high half' + % (equal, crossing, high), equal and crossing and high) + for program in ('K', 'K64'): + reference_image = image(program) + kept = sum(reference_image[i] != CLEAR for i in range(0, len(reference_image), 4)) + check('%s keeps %d of %d pixels' % (program, kept, WIDTH * HEIGHT), 0 < kept < WIDTH * HEIGHT) + for how, (_, _, counts) in MUTATIONS.items(): + for program in counts: + pixel_hlsl(program, how) + differing = sum(a != b for a, b in zip(image(program), image(program, how))) + check('%s: %s mutation changes %d words' % (program, how, differing), differing > 0) + # Every predicate bit of M takes both values somewhere, except eq/ne against a constant: no position gives a low + # half equal to -16 or 0x8000, so those two bits are constant in the draw (control step 4 evaluates them). + m = image('M') + for channel in range(4): + for k, cond in enumerate(CONDITIONS): + if channel >= 2 and cond in ('eq', 'ne'): + continue + bits = {m[4 * i + channel] >> k & 1 for i in range(WIDTH * HEIGHT)} + check('M channel %d %s takes both values' % (channel, cond), bits == {0, 1}) + # The translated compares, evaluated on the CPU, agree with the images. + for program, how in (('K', 'reference'), ('K64', 'reference'), ('K', 'no sext'), ('K64', 'whole word')): + text = pixel_hlsl(program, how) + line = next(ln.strip() for ln in text.splitlines() if ln.strip().startswith('exec = ')) + tree = Expr(line[len('exec = '):-1]) + img = image(program, how) + check('%s %s: evaluated compare equals the image' % (program, how), all( + bool(tree.run(dict(zip(('v1', 'v2'), operands(x | y << 16))))[0]) + == (img[4 * (y * WIDTH + x)] != CLEAR) for y in range(HEIGHT) for x in range(WIDTH))) + + +# ---- LLVM ---------------------------------------------------------------------------------------------------------- +def assemble(llvm_mc, objcopy, source): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + src, obj, raw = directory / 'fixture.s', directory / 'fixture.o', directory / 'fixture.bin' + src.write_text(source, encoding='ascii') + subprocess.run([llvm_mc, '-triple=amdgcn--amdpal', '-mcpu=gfx1013', '-filetype=obj', str(src), '-o', str(obj)], + check=True) + subprocess.run([objcopy, '-O', 'binary', '--only-section=.text', str(obj), str(raw)], check=True) + return raw.read_bytes() + + +def control_codes(): + codes = [code for _, code, *_ in forms()] + for opcode in (OPCODES[False, 'lt', 'i16'], OPCODES[False, 'lt', 'u16'], OPCODES[False, 'ge', 'u16']): + for src, literal in ((inline(-16), None), (inline(-1), None), (inline(0), None), (inline(64), None), + (LITERAL, 0x8000), (LITERAL, 0x7fff), (LITERAL, 0xffef)): + codes += [e64(opcode, SGPR_DST, src, V(2), literal), e64(opcode, SGPR_DST, V(2), src, literal)] + codes.append(e64(opcode, SGPR_DST, 5, V(2))) + return codes + + +def check_binary(llvm_mc, objcopy): + codes = control_codes() + source = ''.join(llvm_text(decode_one(code)[1]) + '\n' for code in codes) + check('LLVM assembles %d decoded control forms to the same words' % len(codes), + assemble(llvm_mc, objcopy, source) == b''.join(codes)) + # LLVM reads a 16-bit literal as the low half: it encodes 0xffff on these operands as the inline constant -1. + check('LLVM encodes the literal 0xffff on an i16 operand as inline -1', + assemble(llvm_mc, objcopy, 'v_cmp_lt_i16_e64 s4, 0xffff, v2\n') + == e64(OPCODES[False, 'lt', 'i16'], SGPR_DST, inline(-1), V(2))) + for name, (fixture_source, words) in FIXTURES.items(): + check('LLVM assembles the %s fixture to the recorded words' % name, + assemble(llvm_mc, objcopy, fixture_source) == words) + + +# ---- draws --------------------------------------------------------------------------------------------------------- +def words_file(directory, name, words): + path = directory / ('%s.bin' % name) + path.write_bytes(struct.pack('<%dI' % len(words), *words)) + 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) + # A capability skip must not hide a failure found earlier in this run (fixture checks or earlier draws). + if failures: + finish() + sys.exit(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = I3.compile_hlsl(compiler, kind, I3.FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for program in ('K', 'K64', 'M'): + reference = words_file(directory, '%s_reference' % program, image(program)) + ps = I3.compile_hlsl(compiler, kind, pixel_hlsl(program), 'ps_%s_%s' % (program, kind), ps_profile, + 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('%s %s %s: all %d pixels match the reference' % (kind, adapter, program, WIDTH * HEIGHT), + run.returncode == 0 and 'all %d pixels matched' % (WIDTH * HEIGHT) in run.stdout, + run.stdout + run.stderr) + for how, (_, _, counts) in MUTATIONS.items(): + if program not in counts: + continue + tag = '%s_%s_%s' % (program, how.replace(' ', '_'), kind) + bad = I3.compile_hlsl(compiler, kind, pixel_hlsl(program, how), 'ps_' + tag, ps_profile, directory) + run = draw(renderer, adapter, vs, bad, reference) + lines = [ln for ln in run.stderr.splitlines() if 'pixel' in ln] + check('%s %s %s %s mutation fails against the reference: %s' + % (kind, adapter, program, how, ' / '.join(lines[:1])), + run.returncode != 0 and lines and lines[0].startswith('pixel mismatch'), + run.stdout + run.stderr) + own = words_file(directory, tag, image(program, how)) + run = draw(renderer, adapter, vs, bad, own) + check('%s %s %s %s mutation matches its own image' % (kind, adapter, program, how), + run.returncode == 0, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + check_fixture() + else: + mode, *args = sys.argv[1:] + if mode == 'binary' and len(args) == 2: + check_binary(*args) + elif mode == 'draw' and len(args) in (3, 4): + check_fixture() + check_draw(*args) + else: + raise SystemExit(__doc__) + finish() + + +def finish(): + 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 9eb3090cc..fb5cd071e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -344,6 +344,13 @@ def check_encoding(code, off, n, name, asm): raise Unsupported('image_load_mip tfe') if word1 & (1 << 30): raise Unsupported('image_load_mip a16') + if re.fullmatch(r'v_cmpx?_(lt|eq|le|gt|ne|ge)_[iu]16_e64', name): + # The decoder prints NEG on an inline integer as a sign (inline 1 with NEG reads `-1`, the same text as + # inline -1), and LLVM 15 rejects `-v1` and `|v1|` on these sources: refuse either bit (VOP3 w0[10:8] ABS, + # w1[31:29] NEG) so a printed -N is always a genuine inline integer. + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x700 or word1 & 0xe0000000: + raise Unsupported('%s with neg/abs: not a 16-bit integer source modifier' % name) if name == 'v_cndmask_b32_e64': # The printed -1 is ambiguous: it can be plain inline -1 or inline 1 with NEG. word0, word1 = struct.unpack_from('<2I', code, off) @@ -4205,6 +4212,30 @@ def check_compare_sdwa_destination(self, base, writes_exec, ops): reg_range(ops[0]) and reg_range(ops[0])[0] == 's'): raise Unsupported('%s into %s' % (base, ops[0])) + def _low16_source(self, base, tok, signed): + """A source of a 16-bit integer compare: bits 15:0 of the operand, sign- or zero-extended (RDNA 2 VOPC + S0.i16 / S0.u16). A float token is refused: on a 16-bit operand the inline constants 240-248 are binary16 + values (LLVM 15 prints inline 1.0 there as 0x3c00), while u() would give the binary32 word.""" + if tok in FLOATS: + raise Unsupported('%s source %s: inline float constants are binary16 on 16-bit operands' % (base, tok)) + reg = reg_range(tok) + if reg: + if reg[1] != reg[2]: + raise Unsupported('%s source %s' % (base, tok)) + x = self.u(tok, low16_only=True) + return '(asint(%s << 16u) >> 16u)' % x if signed else '(%s & 0xffffu)' % x + try: + value = int(tok, 0) + except ValueError: + # vcc, exec, m0 and modifier spellings: not a source this lowering reads. + raise Unsupported('%s source %s' % (base, tok)) + # The decoder prints inline integers -16..64 in decimal and a literal in hex; LLVM 15 accepts only 16-bit + # literals on these operands. + if not -16 <= value <= 0xffff: + raise Unsupported('%s source %s: wider than 16 bits' % (base, tok)) + low = value & 0xffff + return '%d' % (low - 0x10000 if low & 0x8000 else low) if signed else '0x%04xu' % low + def compare(self, base, ops, mods=()): # A comparison reads its two operands directly, so a modifier that arrives here is one this # lowering does not model (op_sel selects a packed half, clamp/omod have no place in a compare): @@ -4280,10 +4311,14 @@ def compare(self, base, ops, mods=()): self.masks.add(d) return None - m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(f32|u32|i32)(_sdwa)?', base) + m = re.fullmatch(r'v_cmp(x?)_(\w+?)_(f32|u32|i32|i16|u16)(_sdwa)?', base) if not m: raise Unsupported(base) writes_exec, cond, typ, sdwa = m.group(1) == 'x', m.group(2), m.group(3), bool(m.group(4)) + # The 16-bit integer compares have the six relations only (gfx10 has no 16-bit f or t). Their SDWA forms + # are not lowered here (tools/pixel_aot.py has its own lowering of them). + if typ in ('i16', 'u16') and (sdwa or cond not in ('lt', 'eq', 'le', 'gt', 'ne', 'ge')): + raise Unsupported(base) # f32 lg is ordered and not equal (false when either source is NaN) and nlg its negation (#1920). # HLSL != is unordered, so lg reads as less or greater, behind {2}: both source words not NaN, # tested on their bits. DXC marks float compares fast unless -Gis, and a driver may then fold @@ -4313,6 +4348,8 @@ def compare(self, base, ops, mods=()): x, y = self.f(a), self.f(b) elif typ == 'i32': x, y = 'int(%s)' % self.u(a), 'int(%s)' % self.u(b) + elif typ in ('i16', 'u16'): + x, y = (self._low16_source(base, t, typ == 'i16') for t in (a, b)) else: x, y = self.u(a), self.u(b) def word(tok): From c3221992c380e268f42e2aac9063ad50c7b55482 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:28:18 +0200 Subject: [PATCH 029/232] cpu: lower VEX.256 YMM VPACKSSWB, VPACKSSDW, and VPACKUSDW in cpu_avx_int_aot (#2353) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 21 ++ tests/cpu/avx_int_regs_check.py | 12 +- tests/cpu/avx_int_ymm_pack.asm | 114 ++++++++++ tests/cpu/avx_int_ymm_pack.def | 10 + tests/cpu/avx_int_ymm_pack_check.py | 317 ++++++++++++++++++++++++++++ tools/cpu_avx_int_aot.py | 5 + 6 files changed, 473 insertions(+), 6 deletions(-) create mode 100644 tests/cpu/avx_int_ymm_pack.asm create mode 100644 tests/cpu/avx_int_ymm_pack.def create mode 100644 tests/cpu/avx_int_ymm_pack_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 45a9bab6c..6e5311b56 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4525,6 +4525,27 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_avx_int_ymm_horizontal PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_horizontal.txt") + # cpu_avx_int_ymm_pack_checks + set(cpu_avx_int_ymm_pack_exports + "op_vpacksswb_ymm,op_vpackssdw_ymm,op_vpackusdw_ymm," + "op_vpacksswb_ymm_dst_src1,op_vpackssdw_ymm_dst_src2," + "op_vpackusdw_ymm_all,op_vpacksswb_ymm_dst_src2," + "op_vpackusdw_ymm_then_xmm_vpacksswb,op_chain_ymm_pack") + string(CONCAT cpu_avx_int_ymm_pack_exports ${cpu_avx_int_ymm_pack_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_avx_int_ymm_pack_${variant} avx_int_ymm_pack) + cpu_translation(cpu_avx_int_ymm_pack_${variant} cpu_avx_int_aot "${cpu_avx_int_ymm_pack_exports}") + endforeach() + target_compile_definitions(cpu_avx_int_ymm_pack_altered PRIVATE ALTER_YMM) + add_test(NAME cpu_aot_avx_int_ymm_pack COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/avx_int_ymm_pack_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_avx_int_ymm_pack PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_avx_int_ymm_pack.txt") set(cpu_avx_move_exports "op_andpd_xmm,op_andpd_ymm,op_andps_xmm,op_andps_ymm,op_andnpd_xmm,op_andnpd_ymm," "op_andnps_xmm,op_andnps_ymm,op_orpd_xmm,op_orpd_ymm,op_orps_xmm,op_orps_ymm," diff --git a/tests/cpu/avx_int_regs_check.py b/tests/cpu/avx_int_regs_check.py index e2b2bb4ad..c683c53ab 100644 --- a/tests/cpu/avx_int_regs_check.py +++ b/tests/cpu/avx_int_regs_check.py @@ -707,12 +707,12 @@ def check_rejections(original_path): # 1) VEX.L=1 (256-bit) packed-integer encodings of surviving forms must be rejected explicitly (AVX2, not AVX1). # The 256-bit add, subtract, saturating add and subtract, compare, minimum, maximum, absolute value, - # sign, word shuffle, and horizontal forms are lowered and are covered by avx_int_ymm_addsub_check.py, - # avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, avx_int_ymm_abs_sign_shuf_check.py, and - # avx_int_ymm_horizontal_check.py. + # sign, word shuffle, horizontal, and pack forms are lowered and are covered by avx_int_ymm_addsub_check.py, + # avx_int_ymm_sat_check.py, avx_int_ymm_minmax_check.py, avx_int_ymm_abs_sign_shuf_check.py, + # avx_int_ymm_horizontal_check.py, and avx_int_ymm_pack_check.py. vex256_int_cases = [ - ("vpackusdw_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPACKUSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), - ("vpackssdw_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPACKSSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpmulhuw_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPMULHUW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + ("vpunpckhdq_ymm", Instruction.create_reg_reg_reg(Code.VEX_VPUNPCKHDQ_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), ("vpalignr_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPALIGNR_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 4)), ("vpblendvb_ymm", Instruction.create_reg_reg_reg_reg(Code.VEX_VPBLENDVB_YMM_YMM_YMMM256_YMM, R.YMM0, R.YMM1, R.YMM2, R.YMM3)), ("vpblendw_ymm", Instruction.create_reg_reg_reg_u32(Code.VEX_VPBLENDW_YMM_YMM_YMMM256_IMM8, R.YMM0, R.YMM1, R.YMM2, 0xAA)), @@ -924,7 +924,7 @@ def check_rejections(original_path): max_len = orig_end - entry pe_patches = [ - ("pe_vpackusdw_ymm", encode_seq(ld_ymm1, ld_ymm2, vex256_by_label["vpackusdw_ymm"], ret_ins), + ("pe_vpmulhuw_ymm", encode_seq(ld_ymm1, ld_ymm2, vex256_by_label["vpmulhuw_ymm"], ret_ins), "unsupported VEX.256 (L=1) packed-integer encoding"), ("pe_vpslld_ymm_xmm", encode_seq(ld_ymm1, ld_xmm2, vex256_by_label["vpslld_ymm_xmm"], ret_ins), "unsupported VEX.256 (L=1) packed-integer encoding"), diff --git a/tests/cpu/avx_int_ymm_pack.asm b/tests/cpu/avx_int_ymm_pack.asm new file mode 100644 index 000000000..04d5b9805 --- /dev/null +++ b/tests/cpu/avx_int_ymm_pack.asm @@ -0,0 +1,114 @@ +; coverage: source cpu_aot_avx_int_ymm_pack +; Source-owned differential fixture for 256-bit (VEX.L=1, AVX2) packed-integer +; pack-with-saturation forms: VPACKSSWB, VPACKSSDW, VPACKUSDW. +; Each 128-bit half is processed independently. +; RCX = const void* input_a (32 bytes) +; RDX = const void* input_b (32 bytes) +; R8 = void* output (32 bytes) +.code + +op_vpacksswb_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpackssdw ymm0, ymm1, ymm2 +ELSE + vpacksswb ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpacksswb_ymm ENDP + +op_vpackssdw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpackusdw ymm0, ymm1, ymm2 +ELSE + vpackssdw ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpackssdw_ymm ENDP + +op_vpackusdw_ymm PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] +IFDEF ALTER_YMM + vpackssdw ymm0, ymm1, ymm2 +ELSE + vpackusdw ymm0, ymm1, ymm2 +ENDIF + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpackusdw_ymm ENDP + +op_vpacksswb_ymm_dst_src1 PROC FRAME + .endprolog + vmovdqu ymm3, YMMWORD PTR [rcx] + vmovdqu ymm4, YMMWORD PTR [rdx] + vpacksswb ymm3, ymm3, ymm4 + vmovdqu YMMWORD PTR [r8], ymm3 + vzeroupper + ret +op_vpacksswb_ymm_dst_src1 ENDP + +op_vpackssdw_ymm_dst_src2 PROC FRAME + .endprolog + vmovdqu ymm4, YMMWORD PTR [rcx] + vmovdqu ymm5, YMMWORD PTR [rdx] + vpackssdw ymm5, ymm4, ymm5 + vmovdqu YMMWORD PTR [r8], ymm5 + vzeroupper + ret +op_vpackssdw_ymm_dst_src2 ENDP + +op_vpackusdw_ymm_all PROC FRAME + .endprolog + vmovdqu ymm2, YMMWORD PTR [rcx] + vpackusdw ymm2, ymm2, ymm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpackusdw_ymm_all ENDP + +op_vpacksswb_ymm_dst_src2 PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpacksswb ymm2, ymm1, ymm2 + vmovdqu YMMWORD PTR [r8], ymm2 + vzeroupper + ret +op_vpacksswb_ymm_dst_src2 ENDP + +op_vpackusdw_ymm_then_xmm_vpacksswb PROC FRAME + .endprolog + vmovdqu ymm1, YMMWORD PTR [rcx] + vmovdqu ymm2, YMMWORD PTR [rdx] + vpackusdw ymm0, ymm1, ymm2 + vpacksswb xmm0, xmm0, xmm2 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_vpackusdw_ymm_then_xmm_vpacksswb ENDP + +op_chain_ymm_pack PROC FRAME + .endprolog + vmovdqu ymm0, YMMWORD PTR [rcx] + vmovdqu ymm1, YMMWORD PTR [rdx] + vpackssdw ymm2, ymm0, ymm1 + vpackusdw ymm3, ymm1, ymm0 + vpacksswb ymm0, ymm2, ymm3 + vmovdqu YMMWORD PTR [r8], ymm0 + vzeroupper + ret +op_chain_ymm_pack ENDP + +END diff --git a/tests/cpu/avx_int_ymm_pack.def b/tests/cpu/avx_int_ymm_pack.def new file mode 100644 index 000000000..ad3199e86 --- /dev/null +++ b/tests/cpu/avx_int_ymm_pack.def @@ -0,0 +1,10 @@ +EXPORTS + op_vpacksswb_ymm + op_vpackssdw_ymm + op_vpackusdw_ymm + op_vpacksswb_ymm_dst_src1 + op_vpackssdw_ymm_dst_src2 + op_vpackusdw_ymm_all + op_vpacksswb_ymm_dst_src2 + op_vpackusdw_ymm_then_xmm_vpacksswb + op_chain_ymm_pack diff --git a/tests/cpu/avx_int_ymm_pack_check.py b/tests/cpu/avx_int_ymm_pack_check.py new file mode 100644 index 000000000..3f7eef426 --- /dev/null +++ b/tests/cpu/avx_int_ymm_pack_check.py @@ -0,0 +1,317 @@ +"""Differential, boundary, mutation, and rejection checks for 256-bit AVX2 packed-integer pack ops.""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import sys + +from iced_x86 import Code, Decoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from avx_int_ymm_minmax_check import encode_seq, first_bad_word, invoke, load # noqa: E402 +from cpu_avx_int_aot import lift_code # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_vpacksswb_ymm", + "op_vpackssdw_ymm", + "op_vpackusdw_ymm", + "op_vpacksswb_ymm_dst_src1", + "op_vpackssdw_ymm_dst_src2", + "op_vpackusdw_ymm_all", + "op_vpacksswb_ymm_dst_src2", + "op_vpackusdw_ymm_then_xmm_vpacksswb", + "op_chain_ymm_pack", +) + + +# --- Independent Python reference: operates on each 16-byte 128-bit half independently --- + +def _sat_s8(val): + return max(-128, min(127, val)) + + +def _sat_s16(val): + return max(-32768, min(32767, val)) + + +def _sat_u16(val): + return max(0, min(65535, val)) + + +def _pack_half(kind, a, b): + if kind == "sswb": + vals = [_sat_s8(v) for v in (*struct.unpack("<8h", a), *struct.unpack("<8h", b))] + return struct.pack("<16b", *vals) + if kind == "ssdw": + vals = [_sat_s16(v) for v in (*struct.unpack("<4i", a), *struct.unpack("<4i", b))] + return struct.pack("<8h", *vals) + if kind == "usdw": + vals = [_sat_u16(v) for v in (*struct.unpack("<4i", a), *struct.unpack("<4i", b))] + return struct.pack("<8H", *vals) + raise ValueError(kind) + + +def _halves(fn, a, b): + return fn(a[:16], b[:16]) + fn(a[16:32], b[16:32]) + + +def reference(name, a, b): + if name in ("op_vpacksswb_ymm", "op_vpacksswb_ymm_dst_src1", "op_vpacksswb_ymm_dst_src2"): + return _halves(lambda x, y: _pack_half("sswb", x, y), a, b) + if name in ("op_vpackssdw_ymm", "op_vpackssdw_ymm_dst_src2"): + return _halves(lambda x, y: _pack_half("ssdw", x, y), a, b) + if name == "op_vpackusdw_ymm": + return _halves(lambda x, y: _pack_half("usdw", x, y), a, b) + if name == "op_vpackusdw_ymm_all": + return _halves(lambda x, y: _pack_half("usdw", x, y), a, a) + if name == "op_vpackusdw_ymm_then_xmm_vpacksswb": + top = _halves(lambda x, y: _pack_half("usdw", x, y), a, b) + return _pack_half("sswb", top[:16], b[:16]) + b"\x00" * 16 + if name == "op_chain_ymm_pack": + t2 = _halves(lambda x, y: _pack_half("ssdw", x, y), a, b) + t3 = _halves(lambda x, y: _pack_half("usdw", x, y), b, a) + return _halves(lambda x, y: _pack_half("sswb", x, y), t2, t3) + raise KeyError(name) + + +def all_pairs(): + """Construct exact clamping-boundary 32-byte input pairs across both 128-bit halves plus random.""" + pairs = [] + words = (-32768, -129, -128, -127, -1, 0, 1, 127, 128, 129, 32767) + for shift in range(len(words)): + a = [words[(i + shift) % len(words)] for i in range(16)] + b = [words[(3 * i + shift + 1) % len(words)] for i in range(16)] + pairs.append((struct.pack("<16h", *a), struct.pack("<16h", *b))) + + dwords = (-2147483648, -32769, -32768, -32767, -1, 0, 1, 32767, 32768, 65535, 65536, 2147483647) + for shift in range(len(dwords)): + a = [dwords[(i + shift) % len(dwords)] for i in range(8)] + b = [dwords[(3 * i + shift + 2) % len(dwords)] for i in range(8)] + pairs.append((struct.pack("<8i", *a), struct.pack("<8i", *b))) + + # Explicit boundary witnesses spanning low and high 128-bit halves differently. + pairs.append(( + struct.pack("<16h", -32768, -129, -128, -127, 127, 128, 129, 32767, + -1, 0, 1, -200, 200, -128, 127, 30000), + struct.pack("<16h", 32767, 129, 128, 127, -127, -128, -129, -32768, + -500, 500, -1, 0, 1, 128, -129, -30000), + )) + pairs.append(( + struct.pack("<8i", -2147483648, -32769, -32768, -1, 0, 32767, 32768, 65536), + struct.pack("<8i", 2147483647, 65535, 65536, -32768, -1, 1, -32769, 32768), + )) + pairs.append((bytes(range(32)), bytes(255 - i for i in range(32)))) + pairs.append((bytes(32), bytes(32))) + pairs.append((b"\xff" * 32, b"\xff" * 32)) + pairs.append((b"\x00" * 16 + b"\xff" * 16, b"\xff" * 16 + b"\x00" * 16)) + + rng = random.Random(0x50AC4) + pairs += [(rng.randbytes(32), rng.randbytes(32)) for _ in range(160)] + return pairs + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def host_has_avx2(lifted_lib): + if hasattr(lifted_lib, "host_has_avx2"): + lifted_lib.host_has_avx2.argtypes = [] + lifted_lib.host_has_avx2.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_avx2()) + try: + return " avx2" in Path("/proc/cpuinfo").read_text(encoding="ascii", errors="replace") + except OSError: + return False + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + loads = (load(R.YMM1, R.RCX), load(R.YMM2, R.RDX)) + xmm_loads = ( + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RCX)), + Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM2, MemoryOperand(R.RDX)), + ) + + accepted = 0 + for name, helper in ( + ("VPACKSSWB", "op_vpacksswb"), + ("VPACKSSDW", "op_vpackssdw"), + ("VPACKUSDW", "op_vpackusdw"), + ): + code = getattr(Code, f"VEX_{name}_YMM_YMM_YMMM256") + source, _ = lift_code( + name, 0x1000, encode_seq(*loads, Instruction.create_reg_reg_reg(code, R.YMM0, R.YMM1, R.YMM2), ret)) + assert f"wide128({helper}, ymm1, ymm2)" in source, name + accepted += 1 + + # 128-bit VPACKSSWB keeps its single-helper path (and cpu_vex_aot.py stays untouched). + src128, _ = lift_code( + "xmm_vpacksswb", 0x1000, + encode_seq(*xmm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKSSWB_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret)) + assert "ymm0 = op_vpacksswb(ymm1, ymm2);" in src128 and "wide128" not in src128 + + mem_err = "unsupported memory operand for register-domain AVX integer instruction" + mem = MemoryOperand(R.RDX) + cases = [ + # m256 memory operands on all 3 new YMM pack forms + ("vpacksswb_m256", (*loads[:1], Instruction.create_reg_reg_mem(Code.VEX_VPACKSSWB_YMM_YMM_YMMM256, R.YMM0, R.YMM1, mem), ret), mem_err), + ("vpackssdw_m256", (*loads[:1], Instruction.create_reg_reg_mem(Code.VEX_VPACKSSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, mem), ret), mem_err), + ("vpackusdw_m256", (*loads[:1], Instruction.create_reg_reg_mem(Code.VEX_VPACKUSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, mem), ret), mem_err), + # EVEX + ("vpacksswb_evex", (*loads, Instruction.create_reg_reg_reg(Code.EVEX_VPACKSSWB_YMM_K1Z_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + ("vpackusdw_evex", (*loads, Instruction.create_reg_reg_reg(Code.EVEX_VPACKUSDW_YMM_K1Z_YMM_YMMM256B32, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported EVEX instruction"), + # Nonvolatile YMM6..YMM15 + ("vpacksswb_nonvol_dst", (*loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKSSWB_YMM_YMM_YMMM256, R.YMM6, R.YMM1, R.YMM2), ret), + "nonvolatile vector register"), + ("vpackssdw_nonvol_src1", (*loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKSSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM7, R.YMM2), ret), + "nonvolatile vector register"), + ("vpackusdw_nonvol_src2", (*loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKUSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM15), ret), + "nonvolatile vector register"), + # Undefined vector source + ("vpacksswb_undef_src2", (*loads[:1], Instruction.create_reg_reg_reg(Code.VEX_VPACKSSWB_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM3), ret), + "undefined vector register ymm3"), + ("vpackssdw_undef_src1", (*loads[1:], Instruction.create_reg_reg_reg(Code.VEX_VPACKSSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM4, R.YMM2), ret), + "undefined vector register ymm4"), + # 128-bit & 256-bit VPACKUSWB stay rejected (128-bit carved out to cpu_vex_aot.py) + ("vpackuswb_xmm", (*xmm_loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKUSWB_XMM_XMM_XMMM128, R.XMM0, R.XMM1, R.XMM2), ret), + "unsupported instruction"), + ("vpackuswb_ymm", (*loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKUSWB_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2), ret), + "unsupported instruction"), + # Missing terminal ret + ("vpackusdw_missing_ret", (*loads, Instruction.create_reg_reg_reg(Code.VEX_VPACKUSDW_YMM_YMM_YMMM256, R.YMM0, R.YMM1, R.YMM2)), + "missing terminal ret"), + ] + for label, seq, reason in cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted a rejected control") + return accepted, len(cases) + + +def check_differential(native, lifted, altered, altered_lifted): + pairs = all_pairs() + total = 0 + for name in EXPORTS: + for index, (a, b) in enumerate(pairs): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b) + if got != want: + raise AssertionError( + f"{label} {name} case {index} word {first_bad_word(got, want)}: " + f"got {got.hex()} expected {want.hex()}") + total += 1 + + # Unaligned input and output buffers; guards must remain intact. + a, b = pairs[len(pairs) // 2] + for name in EXPORTS: + for a_offset, out_offset in ((1, 0), (0, 3), (7, 5)): + want = reference(name, a, b) + for label, funcs in (("native", native), ("lifted", lifted)): + got = invoke(funcs[name], a, b, a_offset, out_offset) + if got != want: + raise AssertionError(f"{label} {name} offsets {a_offset}/{out_offset}") + total += 1 + + # Altered build checks: swapped ops match altered native and diverge from original. + altered_names = ("op_vpacksswb_ymm", "op_vpackssdw_ymm", "op_vpackusdw_ymm") + for name in altered_names: + changed = 0 + for a, b in pairs: + alt_nat = invoke(altered[name], a, b) + alt_lif = invoke(altered_lifted[name], a, b) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted differs from native") + changed += alt_nat != invoke(native[name], a, b) + if not changed: + raise AssertionError(f"altered build did not diverge on {name}") + + # Mutant Python models: must fail against lifted in the expected 64-bit words. + zero16 = b"\x00" * 16 + mutants = ( + ("op_vpacksswb_ymm", lambda x, y: reference("op_vpacksswb_ymm", x, y)[:16] + zero16, {2, 3}), + ("op_vpacksswb_ymm", + lambda x, y: _pack_half("sswb", x[:16], x[16:]) + _pack_half("sswb", y[:16], y[16:]), {1, 2}), + ("op_vpackssdw_ymm", lambda x, y: reference("op_vpackusdw_ymm", x, y), {0, 1, 2, 3}), + ("op_vpackusdw_ymm", lambda x, y: reference("op_vpackssdw_ymm", x, y), {0, 1, 2, 3}), + ("op_vpacksswb_ymm", + lambda x, y: _halves(lambda a16, b16: struct.pack("<16b", *( + ((v + 128) & 0xFF) - 128 for v in (*struct.unpack("<8h", a16), *struct.unpack("<8h", b16)))), x, y), + {0, 1, 2, 3}), + ("op_vpackusdw_ymm_then_xmm_vpacksswb", + lambda x, y: reference("op_vpackusdw_ymm_then_xmm_vpacksswb", x, y)[:16] + reference("op_vpackusdw_ymm", x, y)[16:], + {2, 3}), + ) + for name, wrong, allowed_words in mutants: + bad_words = set() + for x, y in pairs: + w = first_bad_word(invoke(lifted[name], x, y), wrong(x, y)) + if w is not None: + bad_words.add(w) + if not bad_words or not bad_words <= allowed_words: + raise AssertionError(f"mutant on {name}: bad words {sorted(bad_words)}, expected subset of {sorted(allowed_words)}") + + return total, len(mutants), len(altered_names) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + + accepted, rejected = check_translator() + print(f"{accepted} 256-bit pack forms accepted; {rejected} rejection controls passed") + + lifted_lib, lifted = bind(lifted_path, "lifted_") + if not host_has_avx2(lifted_lib): + print("Host lacks CPUID.01H:ECX[28] + XGETBV + CPUID.07H:EBX[5] AVX2; skipping native differential check") + sys.exit(77) + + _, native = bind(original_path, "") + _, altered = bind(altered_path, "") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + total, caught, altered_count = check_differential(native, lifted, altered, altered_lifted) + print(f"{total} native/lifted/reference cases across {len(EXPORTS)} exports matched bit for bit; " + f"{caught} mutant controls + {altered_count} altered-build controls caught") + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_avx_int_aot.py b/tools/cpu_avx_int_aot.py index ad0efaaa4..0e67cda33 100644 --- a/tools/cpu_avx_int_aot.py +++ b/tools/cpu_avx_int_aot.py @@ -37,6 +37,9 @@ encoding stays with cpu_vex_aot.py. - 256-bit (VEX.L=1, AVX2, register operands only) horizontal add / subtract: vphaddw/d/sw, vphsubw/d/sw. Each 128-bit lane is computed independently. + - 256-bit (VEX.L=1, AVX2, register operands only) pack with saturation: vpacksswb, vpackssdw, + vpackusdw. Each 128-bit lane is computed independently (128-bit vpackuswb stays with + cpu_vex_aot.py). Transport/ABI glue: vmovdqu (128/256-bit flat load, store and register copy), flat 32/64-bit GPR load/store mov for scratch GPRs, and terminal ret. @@ -91,6 +94,7 @@ "vpsubsb", "vpsubsw", "vpsubusb", "vpsubusw", "vphaddw", "vphaddd", "vphaddsw", "vphsubw", "vphsubd", "vphsubsw", "vpmuldq", "vpmuludq", "vpmulhrsw", "vpsadbw", + "vpacksswb", "vpackssdw", "vpackusdw", ) } WIDE_BINARY_CODES = { @@ -107,6 +111,7 @@ "VPSUBSB", "VPSUBSW", "VPSUBUSB", "VPSUBUSW", "VPHADDW", "VPHADDD", "VPHADDSW", "VPHSUBW", "VPHSUBD", "VPHSUBSW", "VPMULDQ", "VPMULUDQ", "VPMULHRSW", "VPSADBW", + "VPACKSSWB", "VPACKSSDW", "VPACKUSDW", ) } # 256-bit one-source forms: the 128-bit helper runs on each half. vpshufhw/vpshuflw use the From 1b753c5828800dc2f86f30833fa6122aaec176cd Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:28:21 +0100 Subject: [PATCH 030/232] startup: publish acceleration-structure views on device slot 70 (#1938) * startup: publish acceleration-structure views on device slot 70 and name each refusal * startup: validate AS SRV format/mapping and clear union tail on slot 70 * test: consume a slot 70 acceleration-structure view in an inline ray query on WARP Places the TLAS at a nonzero offset, publishes it through device slot 70, copies the descriptor into a shader-visible heap and traces three rays through a descriptor table. Compares all 12 result words with a root-address reference after three refused calls (wrong state, unaligned, unplaced) at the same destination, and adds decoy-routed and empty-descriptor controls. * test: restore trace_placed_triangle fixture inputs lost in the rebase * test: copy the slot 70 view through the guest device and drop the null-descriptor control The fixture copied the published descriptor with the desktop device from a title-side handle, which read garbage and removed the device. It now uses guest device slot 24, which translates the handle. The null acceleration-structure control is dropped: the decoy-routed view already proves the descriptor is what the trace reads. --- CMakeLists.txt | 21 +++- docs/experiments.md | 7 +- docs/startup-runtime.md | 12 +- src/startup_stubs/d3d12_memory_srv.inl | 59 ++++++++- src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/memory_srv_as.h | 87 +++++++++++++ src/startup_stubs/memory_srv_report.h | 2 +- tests/desktop_gpu.h | 1 + tests/dxr_check.cpp | 63 +++++++++- tests/dxr_placed_build.h | 53 ++++++++ tests/offscreen_check.cpp | 5 + tests/ray_query.hlsl | 8 +- tests/startup_address_buffer_srv_check.py | 6 +- tests/startup_address_srv.cpp | 3 +- tests/startup_memory_srv_as_check.cpp | 141 ++++++++++++++++++++++ tests/startup_memory_srv_report_check.cpp | 2 +- 16 files changed, 449 insertions(+), 22 deletions(-) create mode 100644 src/startup_stubs/memory_srv_as.h create mode 100644 tests/startup_memory_srv_as_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e5311b56..5293377b3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1712,6 +1712,16 @@ foreach(mutation IN ITEMS height exact-fit first-32) add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# Acceleration-structure memory SRV validation for device slot 70 (src/startup_stubs/memory_srv_as.h); the +# mutated runs are negative controls. +add_executable(startup_memory_srv_as_check tests/startup_memory_srv_as_check.cpp) +target_include_directories(startup_memory_srv_as_check PRIVATE src) +target_compile_features(startup_memory_srv_as_check PRIVATE cxx_std_17) +add_test(NAME startup_memory_srv_as COMMAND startup_memory_srv_as_check) +foreach(mutation IN ITEMS alignment state offset) + add_test(NAME startup_memory_srv_as_${mutation}_control COMMAND startup_memory_srv_as_check --mutate ${mutation}) + set_tests_properties(startup_memory_srv_as_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Volume memory SRV validation for device slot 70 (src/startup_stubs/address_texture.h); the mutated # runs are negative controls. add_executable(startup_memory_srv_volume_check tests/startup_memory_srv_volume_check.cpp) @@ -2119,6 +2129,11 @@ add_custom_command(OUTPUT "${ray_header}" COMMAND "${DXC_EXECUTABLE}" -T cs_6_5 -E CSMain -Vn ray_query -Fh "${ray_header}" -Fo "${CMAKE_CURRENT_BINARY_DIR}/ray_query.cso" "${CMAKE_CURRENT_SOURCE_DIR}/tests/ray_query.hlsl" BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/ray_query.cso" DEPENDS tests/ray_query.hlsl VERBATIM) +set(ray_table_header "${CMAKE_CURRENT_BINARY_DIR}/ray_query_table.h") +add_custom_command(OUTPUT "${ray_table_header}" + COMMAND "${DXC_EXECUTABLE}" -T cs_6_5 -E CSMain -D AS_TABLE=1 -Vn ray_query_table -Fh "${ray_table_header}" + -Fo "${CMAKE_CURRENT_BINARY_DIR}/ray_query_table.cso" "${CMAKE_CURRENT_SOURCE_DIR}/tests/ray_query.hlsl" + BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/ray_query_table.cso" DEPENDS tests/ray_query.hlsl VERBATIM) set(ray_pipeline_header "${CMAKE_CURRENT_BINARY_DIR}/ray_pipeline.h") add_custom_command(OUTPUT "${ray_pipeline_header}" COMMAND "${DXC_EXECUTABLE}" -T lib_6_3 -D DXR_PIPELINE=1 -Vn ray_pipeline -Fh "${ray_pipeline_header}" @@ -2134,7 +2149,7 @@ add_custom_command(OUTPUT "${candidates_pipeline_header}" COMMAND "${DXC_EXECUTABLE}" -T lib_6_3 -D DXR_PIPELINE=1 -Vn ray_candidates_pipeline -Fh "${candidates_pipeline_header}" -Fo "${CMAKE_CURRENT_BINARY_DIR}/ray_candidates_pipeline.cso" "${CMAKE_CURRENT_SOURCE_DIR}/tests/ray_candidates.hlsl" BYPRODUCTS "${CMAKE_CURRENT_BINARY_DIR}/ray_candidates_pipeline.cso" DEPENDS tests/ray_candidates.hlsl VERBATIM) -target_sources(offscreen_check PRIVATE "${ray_header}" "${ray_pipeline_header}" "${candidates_header}" "${candidates_pipeline_header}" +target_sources(offscreen_check PRIVATE "${ray_header}" "${ray_table_header}" "${ray_pipeline_header}" "${candidates_header}" "${candidates_pipeline_header}" tests/dxr_facing.cpp tests/dxr_opacity.cpp) foreach(layout IN ITEMS root tables) set(header "${CMAKE_CURRENT_BINARY_DIR}/compute_${layout}.h") @@ -2525,6 +2540,8 @@ foreach(adapter IN ITEMS hardware warp) add_test(NAME dxr_address_ranges_${adapter} COMMAND offscreen_check ${adapter} --dxr-address-ranges) add_test(NAME dxr_placed_build_${adapter} COMMAND offscreen_check ${adapter} --dxr-placed-build) set_tests_properties(dxr_placed_build_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) + add_test(NAME dxr_slot70_as_${adapter} COMMAND offscreen_check ${adapter} --dxr-slot70-as) + set_tests_properties(dxr_slot70_as_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) set_tests_properties(dxr_address_ranges_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) add_test(NAME dxr_pipeline_${adapter} COMMAND offscreen_check ${adapter} --dxr-pipeline) add_test(NAME dxr_update_${adapter} COMMAND offscreen_check ${adapter} --dxr-update) @@ -7174,7 +7191,7 @@ if(EXISTS "${INTAKE_PYTHON}") tools/cpu_call_aot.py tools/cpu_leaf_aot.py tools/cpu_ranges.py VERBATIM) add_library(cpu_placed_dxr_provider SHARED tests/cpu/placed_dxr_provider.cpp tests/dxr_check.cpp tests/desktop_gpu.cpp src/era_title_va.cpp - "${ray_header}" "${ray_pipeline_header}" "${candidates_header}" "${candidates_pipeline_header}") + "${ray_header}" "${ray_table_header}" "${ray_pipeline_header}" "${candidates_header}" "${candidates_pipeline_header}") if(TARGET d3d12_xs_device_obj) target_sources(cpu_placed_dxr_provider PRIVATE $) else() diff --git a/docs/experiments.md b/docs/experiments.md index 241796df4..11db47e27 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14101,20 +14101,21 @@ line, for the first eight refusals of a process (stderr and `X2W_TRAP_LOG`). The check that refused it, in the order the checks run: `null_destination`, `unreadable_resource`, `unreadable_view`, `null_address`, `unsupported_description`, `destination_outside_view_heaps`, or `texture_unavailable` (the description passed but no single live texture or published view matches the -address). Keep full logs from private inputs local. In public reports, give the reason and general resource/view categories. Use source-built inputs for full diagnostic lines. The line prints what the checks read: resource dimension, format, width by height by depth or +address). An acceleration-structure view skips the resource-description checks and can be refused as +`as_unaligned`, `as_not_placed` or `as_wrong_state` (see "Buffer memory SRVs" in `docs/startup-runtime.md`). Keep full logs from private inputs local. In public reports, give the reason and general resource/view categories. Use source-built inputs for full diagnostic lines. The line prints what the checks read: resource dimension, format, width by height by depth or array size, mips, layout, flags, alignment and sample count and quality; view dimension, format and component mapping, with the mip, plane and array fields for 2D and 2D-array views and the first element, count, stride and flags for buffer views (any other dimension prints its six raw words); the destination handle and whether it is a descriptor of a known CBV/SRV/UAV heap; the address and whether its first byte is readable. Textures (2D) and buffers are supported (see "Buffer memory SRVs" in -`docs/startup-runtime.md`); acceleration-structure views are refused. A buffer view must name a live placed or committed buffer, with a raw, +`docs/startup-runtime.md`); acceleration-structure views are published for a placed buffer in the acceleration-structure state. A buffer view must name a live placed or committed buffer, with a raw, structured (stride a multiple of 4, up to 2048) or typed format; typed element sizes come from the format, and formats that cannot back a typed buffer SRV (sRGB, block-compressed, depth/stencil, typeless, BGRA) are refused with `unsupported_description`. Translated draws bind typed buffer views with the format's element size and stride. `startup_memory_srv_report` compares the line field by field for buffer, acceleration-structure -(refused) and array views and for unreadable arguments. `startup_address_srv_hardware` and +and array views and for unreadable arguments. `startup_address_srv_hardware` and `startup_address_srv_warp` also match the five lines of their refused calls (zero address, other width, interior address, a buffer view, a destination off the heap) and show the descriptor unchanged. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 4c56202ae..f3561200d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2645,9 +2645,15 @@ descriptions with: alignment and bounds, adjusts `FirstElement` by `(address - base) / element_bytes`, and forwards to `CreateShaderResourceView` (slot 18). -Acceleration-structure views (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE`) are not -supported and are refused. A view needs an actual built structure with the placed AS role and -lifecycle checks, which has no device test yet. +Acceleration-structure views (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE`, +`src/startup_stubs/memory_srv_as.h`) take their address from the view's `Location`, or from the call's +address when `Location` is zero, do not read the resource description, and require `DXGI_FORMAT_UNKNOWN` +with `D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING` (`unsupported_description`). The view is published through +slot 18 with no resource and the desktop GPU address of the same byte when the address is 256-byte aligned +(`as_unaligned`), starts inside one live placed (slot 133) buffer (`as_not_placed`) and that buffer was +created in `D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE` (`as_wrong_state`). Any other case +leaves the destination descriptor unchanged and logs the reason. The pure checks run on any host +(`ctest -R '^startup_memory_srv_as'`); publishing a view on a device has not been run yet. Typed element bytes come from the format (1 to 16 bytes). Formats that cannot back a typed buffer SRV (sRGB, BGRA, block-compressed, depth/stencil, typeless, planar) are refused with diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index a2807ec61..8ba9b00c1 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -393,10 +393,18 @@ ID3D12Resource* sampled_address_texture(Wrapper* resource) const char* memory_srv_refusal(const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { if (!destination) return "null_destination"; - if (!x2w_local::readable(resource, sizeof(*resource))) return "unreadable_resource"; - if (!x2w_local::readable(input, sizeof(*input))) return "unreadable_view"; - if (!input->address) return "null_address"; - if (!supports_memory_srv(*resource, input->view)) return "unsupported_description"; + const bool readable_input = x2w_local::readable(input, sizeof(*input)); + // An acceleration-structure view names its structure by address only; the resource description is not read. + const bool as_view = readable_input && x2w_startup::is_as_srv(input->view); + if (!as_view && !x2w_local::readable(resource, sizeof(*resource))) return "unreadable_resource"; + if (!readable_input) return "unreadable_view"; + if (as_view) { + if (!x2w_startup::as_srv_location(input->view, input->address)) return "null_address"; + if (!x2w_startup::supports_as_memory_srv(input->view)) return "unsupported_description"; + } else { + if (!input->address) return "null_address"; + if (!supports_memory_srv(*resource, input->view)) return "unsupported_description"; + } if (!memory_srv_destination(destination)) return "destination_outside_view_heaps"; return nullptr; } @@ -405,7 +413,7 @@ const char* memory_srv_refusal(const D3D12_RESOURCE_DESC* resource, const Memory void log_refused_memory_srv(const char* what, const char* reason, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { - const bool resource_ok = x2w_local::readable(resource, sizeof(*resource)); + const bool resource_ok = resource && x2w_local::readable(resource, sizeof(*resource)); const bool input_ok = x2w_local::readable(input, sizeof(*input)); const u64 address = input_ok ? input->address : 0; char line[640]; @@ -438,6 +446,43 @@ void note_memory_srv_write(const D3D12_RESOURCE_DESC* resource, const MemoryShad resource_text, view_text); } +// The placed buffer that holds `address`, as the pure resolver wants it; nothing found when no live one does. +x2w_startup::PlacedAsBuffer placed_as_buffer(const Wrapper* device, u64 address) +{ + x2w_startup::PlacedAsBuffer result; + const auto placed = placed_buffer_range(device, address, 1); + if (placed.reject) { + result.ambiguous = true; + return result; + } + if (!placed.owner || InterlockedCompareExchange(&placed.owner->own().refs, 0, 0) <= 0) return result; + const auto* info = resource_info(placed.owner); + auto* real = static_cast(placed.owner->own().real); + if (!info || !real) return result; + result.found = true; + result.title_base = reinterpret_cast(placed.owner->own().title_memory); + result.gpu_base = real->GetGPUVirtualAddress(); + result.bytes = info->bytes; + result.initial_state = info->initial_state; + return result; +} + +// Slot 70 with an acceleration-structure view: published through slot 18 with no resource and the +// desktop address; a refusal leaves the destination descriptor as it was. +void publish_as_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) +{ + static LONG refused; + const u64 location = x2w_startup::as_srv_location(input->view, input->address); + D3D12_SHADER_RESOURCE_VIEW_DESC resolved{}; + const auto refusal = x2w_startup::resolve_as_srv_desc(location, placed_as_buffer(self, location), input->view, resolved); + if (refusal != x2w_startup::AsSrvRefusal::none) { + refuse_memory_srv(refused, "unavailable acceleration structure at the supplied address", + x2w_startup::as_srv_refusal_name(refusal), resource, input, destination); + return; + } + view_slot<18, 2>(self, 0, reinterpret_cast(&resolved), destination, 0); +} + void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { @@ -461,6 +506,10 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou } return; } + if (x2w_startup::is_as_srv(input->view)) { + publish_as_srv(self, resource, input, destination); + return; + } if (resource->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 872f3bb3c..f1871c4c5 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -40,6 +40,7 @@ #include "startup_stubs/placed_buffer_range.h" #include "startup_stubs/memory_srv_report.h" #include "startup_stubs/memory_srv_census.h" +#include "startup_stubs/memory_srv_as.h" #include "startup_stubs/per_reason_refusal_census.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" diff --git a/src/startup_stubs/memory_srv_as.h b/src/startup_stubs/memory_srv_as.h new file mode 100644 index 000000000..d9133e3b8 --- /dev/null +++ b/src/startup_stubs/memory_srv_as.h @@ -0,0 +1,87 @@ +// Pure validation and address resolution for acceleration-structure memory SRVs (device slot 70). +// Buffer and texture views are handled in memory_srv_buffer.h and d3d12_memory_srv.inl. +// +// An acceleration-structure view names the structure only by an address (its Location). It is +// published when that address starts inside one live placed buffer that was created in the +// acceleration-structure state; the view then carries the desktop GPU virtual address of the same +// byte. Every refusal names the first check that failed, in the order the checks run. +#pragma once + +#include + +#include + +namespace x2w_startup { + +enum class AsSrvRefusal { + none, + as_unaligned, // the address, or the desktop address it maps to, is not 256-byte aligned + as_not_placed, // no single live placed buffer holds the address + as_wrong_state, // the placed buffer was not created in the acceleration-structure state +}; + +inline const char* as_srv_refusal_name(AsSrvRefusal refusal) +{ + switch (refusal) { + case AsSrvRefusal::as_unaligned: return "as_unaligned"; + case AsSrvRefusal::as_not_placed: return "as_not_placed"; + case AsSrvRefusal::as_wrong_state: return "as_wrong_state"; + default: return "none"; + } +} + +// What the device knows about the placed buffer that holds an address; `found` is false when no live +// placed buffer does, and `ambiguous` when more than one does or the address crosses an allocation. +struct PlacedAsBuffer { + bool found{}; + bool ambiguous{}; + std::uint64_t title_base{}; // address of the buffer's first byte as the title sees it + std::uint64_t gpu_base{}; // desktop GPU virtual address of the same byte + std::uint64_t bytes{}; // allocation size + D3D12_RESOURCE_STATES initial_state{}; +}; + +inline bool is_as_srv(const D3D12_SHADER_RESOURCE_VIEW_DESC& view) +{ + return view.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; +} + +inline bool supports_as_memory_srv(const D3D12_SHADER_RESOURCE_VIEW_DESC& view) +{ + return is_as_srv(view) && view.Format == DXGI_FORMAT_UNKNOWN && + view.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; +} + +// The title address of the structure: the view's Location, or the call's separate address when the +// Location is zero. +inline std::uint64_t as_srv_location(const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint64_t address) +{ + return view.RaytracingAccelerationStructure.Location ? view.RaytracingAccelerationStructure.Location : address; +} + +// `view` must be an acceleration-structure view. On success `resolved` is `view` with Location replaced +// by the desktop GPU virtual address; it is left unchanged on a refusal. +inline AsSrvRefusal resolve_as_srv_desc(std::uint64_t location, const PlacedAsBuffer& placed, + const D3D12_SHADER_RESOURCE_VIEW_DESC& view, + D3D12_SHADER_RESOURCE_VIEW_DESC& resolved) +{ + constexpr std::uint64_t alignment = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT; + if (location % alignment != 0) return AsSrvRefusal::as_unaligned; + if (!placed.found || placed.ambiguous || !placed.title_base || !placed.gpu_base || location < placed.title_base || + location - placed.title_base >= placed.bytes) + return AsSrvRefusal::as_not_placed; + if (placed.initial_state != D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) + return AsSrvRefusal::as_wrong_state; + const std::uint64_t offset = location - placed.title_base; + if (offset > UINT64_MAX - placed.gpu_base) return AsSrvRefusal::as_not_placed; + const std::uint64_t gpu = placed.gpu_base + offset; + if (gpu % alignment != 0) return AsSrvRefusal::as_unaligned; + resolved = {}; + resolved.Format = view.Format; + resolved.ViewDimension = view.ViewDimension; + resolved.Shader4ComponentMapping = view.Shader4ComponentMapping; + resolved.RaytracingAccelerationStructure.Location = gpu; + return AsSrvRefusal::none; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/memory_srv_report.h b/src/startup_stubs/memory_srv_report.h index 6a56a036a..00efcdd40 100644 --- a/src/startup_stubs/memory_srv_report.h +++ b/src/startup_stubs/memory_srv_report.h @@ -64,7 +64,7 @@ inline int report_view(char* out, std::size_t size, const D3D12_SHADER_RESOURCE_ std::memcpy(words, &v->Buffer, sizeof(words)); return std::snprintf(tail, room, "raw=%08x,%08x,%08x,%08x,%08x,%08x%s", words[0], words[1], words[2], words[3], words[4], words[5], - dimension == srv_dimension_acceleration_structure ? " (acceleration structure views are not supported)" : ""); + dimension == srv_dimension_acceleration_structure ? " (acceleration structure view)" : ""); } } } diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index b40f4a969..e01c44fd7 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -119,6 +119,7 @@ void check_wave64_emulate(ID3D12Device* device); bool check_shader_wave(ID3D12Device* device, unsigned forced); bool check_dxr_address_ranges(ID3D12Device* device); bool check_dxr_placed_build(ID3D12Device* device); +bool check_dxr_slot70_as(ID3D12Device* device); bool check_dxr_rays(ID3D12Device* device, bool usePipeline); bool check_dxr_update(ID3D12Device* device, bool usePipeline); bool check_dxr_facing(ID3D12Device* device, bool usePipeline); diff --git a/tests/dxr_check.cpp b/tests/dxr_check.cpp index c6d72a92b..7d5068ab4 100644 --- a/tests/dxr_check.cpp +++ b/tests/dxr_check.cpp @@ -5,6 +5,7 @@ #include "ray_candidates_pipeline.h" #include "ray_pipeline.h" #include "ray_query.h" +#include "ray_query_table.h" #include #include #include @@ -321,8 +322,15 @@ static std::vector trace_scene(ID3D12Device* device, const st auto results = make_buffer(device, result_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, writable); auto readback = make_buffer(device, result_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); // Per-triangle geometries are traced by the shader that handles non-opaque candidates. + const bool viaView = placedScene && placedScene->slot70; + if (viaView && (usePipeline || triangleGeometries || update)) + throw std::runtime_error("The slot-70 view fixture traces one placed scene with the inline query shader"); const D3D12_SHADER_BYTECODE shader = triangleGeometries - ? D3D12_SHADER_BYTECODE{ray_candidates, sizeof(ray_candidates)} : D3D12_SHADER_BYTECODE{ray_query, sizeof(ray_query)}; + ? D3D12_SHADER_BYTECODE{ray_candidates, sizeof(ray_candidates)} + : viaView ? D3D12_SHADER_BYTECODE{ray_query_table, sizeof(ray_query_table)} + : D3D12_SHADER_BYTECODE{ray_query, sizeof(ray_query)}; + ComPtr asHeap; + if (viaView) asHeap = placedScene->publish_as_view(device); ComPtr root; // Both backends share the global root signature embedded in the compute shader. check(device->CreateRootSignature(0, shader.pShaderBytecode, shader.BytecodeLength, IID_PPV_ARGS(&root)), @@ -379,7 +387,13 @@ static std::vector trace_scene(ID3D12Device* device, const st order.UAV.pResource = tlas.Get(); list->ResourceBarrier(1, &order); list->SetComputeRootSignature(root.Get()); - list->SetComputeRootShaderResourceView(0, top.DestAccelerationStructureData); + if (asHeap) { + ID3D12DescriptorHeap* heaps[]{asHeap.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootDescriptorTable(0, asHeap->GetGPUDescriptorHandleForHeapStart()); + } else { + list->SetComputeRootShaderResourceView(0, top.DestAccelerationStructureData); + } list->SetComputeRootUnorderedAccessView(1, results->GetGPUVirtualAddress()); list->SetComputeRootShaderResourceView(2, rayBuffer->GetGPUVirtualAddress()); if (usePipeline) { @@ -529,6 +543,51 @@ bool check_dxr_placed_build(ID3D12Device* device) { return true; } +// Device slot 70 (issue #1938): the TLAS is placed at a nonzero offset, published as an acceleration-structure +// view through slot 70 and consumed from a descriptor table by an inline ray query, on the same adapter. +bool check_dxr_slot70_as(ID3D12Device* device) { + using namespace dxr_fixture; + if (!supported(device, Backend::inline_query)) return false; + const std::vector vertices{{-1,-1,1}, {1,-1,1}, {0,1,1}}; + const std::vector rays{{0,0,0,.01f,0,0,1,4,1}, {4,0,0,.01f,0,0,1,4,1}, {0,0,0,.01f,0,0,1,4,2}}; + const auto run = [&](bool misroute) { + PlacedBuildScene placement; + placement.slot70 = true; + placement.misroute = misroute; + return trace_scene(device, vertices, {instance(7,1)}, rays, Backend::inline_query, + nullptr, nullptr, nullptr, &placement); + }; + const auto viaView = run(false); + // The reference: the same builds and rays with the TLAS GPU address given as a root SRV; only slot 70 is bypassed. + const auto root = trace(device, vertices, {instance(7,1)}, rays); + // Distinct-AS control: the view names a TLAS whose instance routes to a decoy BLAS. + const auto decoy = run(true); + const auto print = [](const char* label, const std::vector& words) { + std::printf("slot70_as_rows %s", label); + for (std::size_t i = 0; i + 3 < words.size(); i += 4) + std::printf(" [%u,%u,%u,0x%08x]", words[i], words[i + 1], words[i + 2], words[i + 3]); + std::puts(""); + }; + print("view", viaView); + print("root", root); + print("decoy", decoy); + const std::vector expected{1,7,0,0, 0,0,0,0, 0,0,0,0}; + const auto fixed = [&](const std::vector& words) { + if (words.size() != expected.size()) return false; + for (std::size_t i = 0; i < words.size(); ++i) + if (i != 3 && words[i] != expected[i]) return false; + return true; + }; + if (!fixed(viaView) || !fixed(root)) + throw std::runtime_error("Slot-70 view rays differ from hit7, miss, masked miss"); + if (viaView != root) + throw std::runtime_error("Slot-70 view rays differ from the root-address reference"); + if (decoy == root) throw std::runtime_error("The decoy-routed view still matched the reference"); + std::printf("Slot 70 acceleration-structure view: hit7 (distance=0x%08x), miss, masked miss; all 12 words equal the " + "root-address reference after three refused calls kept the descriptor and the decoy differs\n", viaView[3]); + return true; +} + bool check_dxr_rays(ID3D12Device* device, bool usePipeline) { using namespace dxr_fixture; const auto backend = usePipeline ? Backend::pipeline : Backend::inline_query; diff --git a/tests/dxr_placed_build.h b/tests/dxr_placed_build.h index 9e80ce341..8503172ea 100644 --- a/tests/dxr_placed_build.h +++ b/tests/dxr_placed_build.h @@ -15,12 +15,17 @@ class PlacedBuildScene { ~Buffer() { wrapper.Reset(); if (memory) VirtualFree(memory, 0, MEM_RELEASE); } }; Microsoft::WRL::ComPtr guest_; + Microsoft::WRL::ComPtr cpu_heap_; std::array buffers_; + UINT64 tlas_title_{}, scratch_title_{}; public: // Wrong-routing control (issue #874): also build a decoy BLAS from another triangle into its own placed // destination and scratch, and route the TLAS instance to the decoy instead of the BLAS under test. bool misroute = false; + // Slot-70 variant (issue #1938): the TLAS is handed to the trace as an acceleration-structure view that + // device slot 70 published, instead of as a root address. + bool slot70 = false; void attach(ID3D12Device* device) { device->AddRef(); x2w_startup::attach_device(device, reinterpret_cast(guest_.GetAddressOf())); @@ -28,6 +33,7 @@ class PlacedBuildScene { void* guest() const { return guest_.Get(); } unsigned release() { unsigned count = 0; + cpu_heap_.Reset(); for (auto& buffer : buffers_) { if (auto* wrapper = buffer.wrapper.Detach()) { if (wrapper->Release()) throw std::runtime_error("Placed resource still referenced"); @@ -81,6 +87,8 @@ class PlacedBuildScene { must_reject(ts, tlas); check(x2w_startup::resolve_placed_build(guest_.Get(), blas, bs, bottom_size, bottom), "Resolve placed BLAS"); check(x2w_startup::resolve_placed_build(guest_.Get(), tlas, ts, top_size, top), "Resolve placed TLAS"); + tlas_title_ = tlas; + scratch_title_ = ts; const auto verify_offset = [&](const auto& build, UINT64 dest, UINT64 scratch, const auto& sizes) { auto base = build; check(x2w_startup::resolve_placed_build(guest_.Get(), dest - dest_offset, scratch - scratch_offset, @@ -96,6 +104,51 @@ class PlacedBuildScene { top_size.ResultDataMaxSizeInBytes, top_size.ScratchDataSizeInBytes); } + // Publishes the placed TLAS through guest device slot 70 into a CPU-only guest view heap, then three refused + // calls at the same destination (wrong buffer state, unaligned, outside every placed buffer), and returns a + // shader-visible desktop heap holding a copy of that one descriptor. Call after prepare(). + Microsoft::WRL::ComPtr publish_as_view(ID3D12Device* device) { + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 address, bytes; + } extended{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}, 0, 0}; + using Create = HRESULT (WINAPI*)(void*, const void*, const GUID*, void**); + auto create = reinterpret_cast((*reinterpret_cast(guest_.Get()))[14]); + check(create(guest_.Get(), &extended, &__uuidof(ID3D12DescriptorHeap), + reinterpret_cast(cpu_heap_.ReleaseAndGetAddressOf())), "Create the guest view heap"); + using CpuStart = UINT64 (WINAPI*)(void*); + const UINT64 destination = reinterpret_cast((*reinterpret_cast(cpu_heap_.Get()))[9])(cpu_heap_.Get()); + D3D12_RESOURCE_DESC resource{}; + resource.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + resource.Width = 256; + resource.Height = resource.DepthOrArraySize = resource.MipLevels = resource.SampleDesc.Count = 1; + resource.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + struct ViewAt { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + UINT64 address, tail[2]; + } at{}; + at.view.ViewDimension = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; + at.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + using Publish = void (WINAPI*)(void*, const D3D12_RESOURCE_DESC*, const void*, UINT64); + auto slot70 = reinterpret_cast((*reinterpret_cast(guest_.Get()))[70]); + const auto publish = [&](UINT64 address) { + at.address = address; + slot70(guest_.Get(), &resource, &at, destination); + }; + publish(tlas_title_); + publish(scratch_title_); // as_wrong_state: a placed buffer, but not in the acceleration-structure state + publish(tlas_title_ + 16); // as_unaligned + publish(0x1000); // as_not_placed + Microsoft::WRL::ComPtr visible; + D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + check(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&visible)), "Create the shader-visible view heap"); + // The published descriptor lives in a title-side handle range; the guest device copy (slot 24) translates it. + using Copy = void (WINAPI*)(void*, UINT, UINT64, UINT64, UINT); + reinterpret_cast((*reinterpret_cast(guest_.Get()))[24])(guest_.Get(), 1, + visible->GetCPUDescriptorHandleForHeapStart().ptr, destination, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + return visible; + } + // The decoy BLAS for the wrong-routing control, placed and resolved through the same slot-133 path. void prepare_decoy(const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO& bottom_size, D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC& decoy) { diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index b00094cdc..12b394a58 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1099,6 +1099,10 @@ OperationResult run_dxr_placed_build(const OperationContext& ctx) { return skip_if_false(check_dxr_placed_build(ctx.device)); } +OperationResult run_dxr_slot70_as(const OperationContext& ctx) +{ + return skip_if_false(check_dxr_slot70_as(ctx.device)); +} OperationResult run_dxr_pipeline(const OperationContext& ctx) { @@ -1663,6 +1667,7 @@ const OperationSpec kOperations[] = { {"--ray-query", 3, 3, nullptr, kNoGate, run_ray_query}, {"--dxr-address-ranges", 3, 3, nullptr, kNoGate, run_dxr_address_ranges}, {"--dxr-placed-build", 3, 3, nullptr, kNoGate, run_dxr_placed_build}, + {"--dxr-slot70-as", 3, 3, nullptr, kNoGate, run_dxr_slot70_as}, {"--dxr-pipeline", 3, 3, nullptr, kNoGate, run_dxr_pipeline}, {"--gpu-alias", 3, 3, nullptr, kNoGate, run_gpu_alias}, {"--gpu-alias-window", 3, 3, nullptr, kNoGate, run_gpu_alias_window}, diff --git a/tests/ray_query.hlsl b/tests/ray_query.hlsl index 78c076787..3593e5d3a 100644 --- a/tests/ray_query.hlsl +++ b/tests/ray_query.hlsl @@ -44,7 +44,13 @@ void ClosestHit(inout Payload payload, BuiltInTriangleIntersectionAttributes att payload.value = uint4(status, InstanceID(), PrimitiveIndex(), asuint(RayTCurrent())); } #else -[RootSignature("SRV(t0),UAV(u0),SRV(t1)")] +// AS_TABLE binds the structure through a descriptor table, as a title that published it with a view does. +#ifdef AS_TABLE +#define RAY_ROOT "DescriptorTable(SRV(t0)),UAV(u0),SRV(t1)" +#else +#define RAY_ROOT "SRV(t0),UAV(u0),SRV(t1)" +#endif +[RootSignature(RAY_ROOT)] [numthreads(1, 1, 1)] void CSMain(uint3 thread : SV_DispatchThreadID) { diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index 97444f5e1..c05bd59f8 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -18,10 +18,10 @@ def check_refusal_lines(log): + r"view\{dim=1 fmt=39 map=0x1688 first=0 count=4 stride=0 flags=0x1 \(buffer views are not supported\)\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", prefix - + r"unsupported memory SRV arguments: reason=unsupported_description " + + r"unavailable acceleration structure at the supplied address: reason=as_wrong_state " + r"res\{dim=1 fmt=0 size=256x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0\} " + r"view\{dim=11 fmt=0 map=0x1688 raw=(00000000,){5}00000000 " - + r"\(acceleration structure views are not supported\)\} " + + r"\(acceleration structure view\)\} " + rf"dest={HEX} dest_in_view_heap=1 address={HEX} address_readable=1", ] lines = [line.rstrip() for line in log.splitlines() if "Device::slot70" in line] @@ -56,7 +56,7 @@ def check(directory, consumer, backend): if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, structured, refused unaligned, refused acceleration structure) exact") + print(f"{backend}: buffer memory SRV (raw base, raw interior, structured, refused unaligned, refused acceleration structure view) exact") return 0 diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 7a9a77e21..64afd9d90 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -484,7 +484,8 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) structured.view.Buffer.StructureByteStride = 4; structured.address = ptr(buf0); invoke(guest, 70, ptr(&desc), ptr(&structured), cpu); - // An acceleration-structure view is refused; draw(4) proves the structured descriptor stayed in place. + // An acceleration-structure view of a placed buffer that is not in the acceleration-structure state is + // refused (as_wrong_state); draw(4) proves the structured descriptor stayed in place. ViewAt as_view{}; as_view.view.Format = DXGI_FORMAT_UNKNOWN; as_view.view.ViewDimension = static_cast(11); diff --git a/tests/startup_memory_srv_as_check.cpp b/tests/startup_memory_srv_as_check.cpp new file mode 100644 index 000000000..4622a179d --- /dev/null +++ b/tests/startup_memory_srv_as_check.cpp @@ -0,0 +1,141 @@ +// Checks acceleration-structure memory SRV validation and address resolution (device slot 70) +// without a device. +// --mutate alignment: expect an unaligned address to be accepted. +// --mutate state: expect a buffer that is not in the acceleration-structure state to be accepted. +// --mutate offset: expect the desktop address to be the buffer base, ignoring the offset. +// Each mutated run is a negative control and must fail. +#include "startup_stubs/memory_srv_as.h" + +#include +#include + +namespace { + +using namespace x2w_startup; + +int failures; +const char* mutation = ""; + +bool mutated(const char* name) +{ + return std::strcmp(mutation, name) == 0; +} + +void check(const char* name, bool condition) +{ + if (condition) return; + ++failures; + std::printf("FAIL %s\n", name); +} + +constexpr std::uint64_t title_base = 0x700000000ull; +constexpr std::uint64_t gpu_base = 0x5000000000ull; + +D3D12_SHADER_RESOURCE_VIEW_DESC as_view(std::uint64_t location) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = DXGI_FORMAT_UNKNOWN; + v.ViewDimension = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; + v.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + v.RaytracingAccelerationStructure.Location = location; + return v; +} + +PlacedAsBuffer placed() +{ + PlacedAsBuffer p; + p.found = true; + p.title_base = title_base; + p.gpu_base = gpu_base; + p.bytes = 0x10000; + p.initial_state = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; + return p; +} + +AsSrvRefusal resolve(std::uint64_t location, const PlacedAsBuffer& p, D3D12_SHADER_RESOURCE_VIEW_DESC& out) +{ + return resolve_as_srv_desc(location, p, as_view(location), out); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0) mutation = argv[2]; + D3D12_SHADER_RESOURCE_VIEW_DESC out{}; + + // The structure starts 0x300 bytes into the buffer: the view carries the desktop address of that byte. + const std::uint64_t location = title_base + 0x300; + check("accepted", resolve(location, placed(), out) == AsSrvRefusal::none); + const std::uint64_t expected = mutated("offset") ? gpu_base : gpu_base + 0x300; + check("desktop address", out.RaytracingAccelerationStructure.Location == expected); + check("other fields kept", out.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE && + out.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING); + + // The first and the last aligned byte of the buffer are inside it; one past the end is not. + check("first byte", resolve(title_base, placed(), out) == AsSrvRefusal::none); + check("last aligned byte", resolve(title_base + 0xff00, placed(), out) == AsSrvRefusal::none); + check("one past the end", resolve(title_base + 0x10000, placed(), out) == AsSrvRefusal::as_not_placed); + + // Each refusal has its own reason and leaves the output alone. + D3D12_SHADER_RESOURCE_VIEW_DESC untouched{}; + untouched.RaytracingAccelerationStructure.Location = 0x1234; + D3D12_SHADER_RESOURCE_VIEW_DESC probe = untouched; + const AsSrvRefusal unaligned = resolve(title_base + 0x301, placed(), probe); + check("unaligned", mutated("alignment") ? unaligned == AsSrvRefusal::none : unaligned == AsSrvRefusal::as_unaligned); + + PlacedAsBuffer none; + probe = untouched; + check("not placed", resolve(location, none, probe) == AsSrvRefusal::as_not_placed); + PlacedAsBuffer ambiguous = placed(); + ambiguous.ambiguous = true; + check("ambiguous", resolve(location, ambiguous, probe) == AsSrvRefusal::as_not_placed); + check("below the buffer", resolve(title_base - 0x100, placed(), probe) == AsSrvRefusal::as_not_placed); + PlacedAsBuffer overflow = placed(); + overflow.gpu_base = UINT64_MAX - 0xff; + check("desktop address overflow", resolve(location, overflow, probe) == AsSrvRefusal::as_not_placed); + PlacedAsBuffer misaligned_gpu = placed(); + misaligned_gpu.gpu_base = gpu_base + 0x80; + check("desktop address unaligned", resolve(location, misaligned_gpu, probe) == AsSrvRefusal::as_unaligned); + + PlacedAsBuffer wrong = placed(); + wrong.initial_state = D3D12_RESOURCE_STATE_COMMON; + probe = untouched; + check("wrong state", resolve(location, wrong, probe) == (mutated("state") ? AsSrvRefusal::none : AsSrvRefusal::as_wrong_state)); + if (!mutated("state")) check("refusal leaves output", probe.RaytracingAccelerationStructure.Location == 0x1234); + + // The address comes from Location, or from the call's address when Location is zero. + check("location wins", as_srv_location(as_view(0x2000), 0x3000) == 0x2000); + check("address fallback", as_srv_location(as_view(0), 0x3000) == 0x3000); + check("both zero", as_srv_location(as_view(0), 0) == 0); + check("dimension", is_as_srv(as_view(0)) && !is_as_srv(D3D12_SHADER_RESOURCE_VIEW_DESC{})); + + // Format must be UNKNOWN and Shader4ComponentMapping must be default. + check("supported desc", supports_as_memory_srv(as_view(location))); + auto bad_fmt = as_view(location); + bad_fmt.Format = DXGI_FORMAT_R32_UINT; + check("bad format refused", !supports_as_memory_srv(bad_fmt)); + auto bad_map = as_view(location); + bad_map.Shader4ComponentMapping = 0; + check("bad mapping refused", !supports_as_memory_srv(bad_map)); + check("non-as refused", !supports_as_memory_srv(D3D12_SHADER_RESOURCE_VIEW_DESC{})); + + // Trailing union bytes after Location are cleared in the resolved descriptor. + auto dirty_tail = as_view(location); + std::uint32_t words[6]{}; + std::memcpy(words, &dirty_tail.Buffer, sizeof(words)); + words[2] = 0xdeadbeefu; + std::memcpy(&dirty_tail.Buffer, words, sizeof(words)); + D3D12_SHADER_RESOURCE_VIEW_DESC clean{}; + check("dirty tail accepted", resolve_as_srv_desc(location, placed(), dirty_tail, clean) == AsSrvRefusal::none); + std::memcpy(words, &clean.Buffer, sizeof(words)); + check("tail cleared", words[2] == 0 && words[3] == 0 && words[4] == 0 && words[5] == 0); + + check("names", std::strcmp(as_srv_refusal_name(AsSrvRefusal::as_unaligned), "as_unaligned") == 0 && + std::strcmp(as_srv_refusal_name(AsSrvRefusal::as_not_placed), "as_not_placed") == 0 && + std::strcmp(as_srv_refusal_name(AsSrvRefusal::as_wrong_state), "as_wrong_state") == 0); + + if (failures) return 1; + std::printf("startup_memory_srv_as_check: ok\n"); + return 0; +} diff --git a/tests/startup_memory_srv_report_check.cpp b/tests/startup_memory_srv_report_check.cpp index 2639dd82d..591266b3f 100644 --- a/tests/startup_memory_srv_report_check.cpp +++ b/tests/startup_memory_srv_report_check.cpp @@ -49,7 +49,7 @@ int main() "x2w-d3d12 Device::slot70 unsupported memory SRV arguments: reason=unsupported_description " "res{dim=1 fmt=0 size=4096x1x1 mips=1 layout=0x1 flags=0x0 align=0 samples=1/0} " "view{dim=11 fmt=0 map=0x1688 raw=55667788,11223344,00000000,00000000,00000000,00000000 " - "(acceleration structure views are not supported)} dest=0x1000 dest_in_view_heap=1 address=0x2000 address_readable=0"); + "(acceleration structure view)} dest=0x1000 dest_in_view_heap=1 address=0x2000 address_readable=0"); auto b = view(D3D12_SRV_DIMENSION_BUFFER, DXGI_FORMAT_UNKNOWN); b.Buffer.FirstElement = 7; From 79841618ceff1937c25e3ce293fe6eff1010e8bc Mon Sep 17 00:00:00 2001 From: SimSalabimse <83839581+SimSalabimse@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:30:29 +0100 Subject: [PATCH 031/232] startup: apply stream rasterizer state on translated draws (#1567) Slot 86 RASTERIZER and RASTERIZER1 subobjects set the translated desktop pipeline fill, cull, and depth clip. A RASTERIZER1 depth bias that is not an integer in the desktop int range refuses the pipeline. The desktop PSO cache key includes the rasterizer when the stream has one. A stream with no rasterizer subobject keeps solid fill, no culling, and depth clip on. Fixes #1142 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 12 ++ docs/startup-runtime.md | 7 +- src/startup_stubs/d3d12_capture.inl | 9 +- src/startup_stubs/d3d12_draw.inl | 64 +++++- src/startup_stubs/d3d12_xs_device.cpp | 8 +- tests/startup_stream_rasterizer.cpp | 252 +++++++++++++++++++++++ tests/startup_stream_rasterizer_check.py | 81 ++++++++ 7 files changed, 421 insertions(+), 12 deletions(-) create mode 100644 tests/startup_stream_rasterizer.cpp create mode 100644 tests/startup_stream_rasterizer_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 5293377b3..341f9f688 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1141,6 +1141,10 @@ add_executable(startup_draw_depth_target tests/startup_draw_depth_target.cpp $) +target_compile_features(startup_stream_rasterizer PRIVATE cxx_std_17) +target_link_libraries(startup_stream_rasterizer PRIVATE d3d12_xs_shim d3d12 dxgi) + # Console queue Wait (slot 17) waits on the GPU instead of signalling the fence. add_executable(startup_queue_wait tests/startup_queue_wait.cpp) target_compile_features(startup_queue_wait PRIVATE cxx_std_17) @@ -3385,6 +3389,14 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_depth_check.py" "$" "${backend}") set_tests_properties(startup_stream_depth_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_stream_rasterizer_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" + "$" "${backend}") + set_tests_properties(startup_stream_rasterizer_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_stream_rasterizer_ignore_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" + "$" "${backend}" ignore) + set_tests_properties(startup_stream_rasterizer_ignore_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77 WILL_FAIL TRUE) add_test(NAME startup_slot57_depth_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot57_depth_check.py" "$" "${backend}") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f3561200d..40de35f02 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1983,7 +1983,12 @@ These are measured on one executable; treat them as hypotheses for others. pipeline, submits the wrapped list, waits for its fence and checks all 32 RGBA pixels on WARP and hardware. Swapping the red/green shader changes the 16 covered pixels. Reproduce with `ctest --preset release --no-tests=error -R "^startup_stream_(request|draw)_"`. - Other stage combinations and full stream rasterizer/depth state remain open. + A stream `RASTERIZER` or `RASTERIZER1` subobject sets the translated pipeline's fill, cull and depth + clip. `RASTERIZER1` stores depth bias as a float; a value that is not an integer in the desktop range + refuses the pipeline. The cull check is + `ctest --preset release --no-tests=error -R "^startup_stream_rasterizer_"`. + The ignore control expects the no-cull readback and fails. Stream depth-stencil state is already + applied on this path. Geometry, hull, domain and compute stages remain open. - Translated draws use the bound typed RTV formats to request colour-export variants. The manifest's `targets` line lists exported slots. A separate `rtv1` line identifies the base shader and the ordered RTV formats, and the draw rejects a variant with a mismatched line. diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index e0375ff09..6b40d70a2 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -15,6 +15,8 @@ struct PipelineInfo { D3D12_BLEND_DESC stream_blend{}; bool has_stream_depth_stencil = false; D3D12_DEPTH_STENCIL_DESC stream_depth_stencil{}; + bool has_stream_rasterizer = false; + D3D12_RASTERIZER_DESC stream_rasterizer{}; DXGI_FORMAT stream_dsv_format = DXGI_FORMAT_UNKNOWN; int path = 0; // creating device slot: 57, 67, 55, 86, 62 Wrapper* base = nullptr; // slot 55: the pipeline it derives from @@ -94,7 +96,8 @@ bool title_backed(u64 title_handle, u64 bytes) void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std::size_t bytes, Translation* translation = nullptr, const D3D12_BLEND_DESC* blend = nullptr, const D3D12_DEPTH_STENCIL_DESC* depth_stencil = nullptr, - DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN) + DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN, + const D3D12_RASTERIZER_DESC* rasterizer = nullptr) { PipelineInfo info; info.stream_translation = translation; @@ -106,6 +109,10 @@ void note_pipeline(Wrapper* w, int path, const void* base, const void* desc, std info.stream_depth_stencil = *depth_stencil; info.has_stream_depth_stencil = true; } + if (rasterizer) { + info.stream_rasterizer = *rasterizer; + info.has_stream_rasterizer = true; + } info.stream_dsv_format = dsv_format; info.path = path; info.base = as_wrapper(base); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 42a35ca21..023a09010 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -45,6 +45,8 @@ struct BoundPipeline { bool depth_from_registers = false; // X2W_DEPTH_STATE: depth_stencil was decoded from state block A (slot 57) bool has_stencil_ref = false; // ... and its stencil test is on: stencil_ref goes on the list with each draw std::uint8_t stencil_ref = 0; + bool has_rasterizer = false; + D3D12_RASTERIZER_DESC rasterizer{}; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; std::unordered_map pipelines; // by target formats }; @@ -468,10 +470,26 @@ bool stream_input_layout(const unsigned char* subobject, std::string& text) return true; } +// RASTERIZER1 stores DepthBias as a float. The desktop PSO takes an int, so only an integral value +// in the int range is representable. +bool integral_depth_bias(float bias, INT& out) +{ + if (!(bias == bias)) return false; + const double value = static_cast(bias); + if (value < -2147483648.0 || value > 2147483647.0) return false; + const INT integral = static_cast(value); + if (static_cast(integral) != value) return false; + out = integral; + return true; +} + // Resolve the shader pointers and wrapped root while the caller still owns the stream. Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3D12_BLEND_DESC& blend, bool& has_blend, - D3D12_DEPTH_STENCIL_DESC& depth_stencil, bool& has_depth_stencil, DXGI_FORMAT& dsv_format) + D3D12_DEPTH_STENCIL_DESC& depth_stencil, bool& has_depth_stencil, DXGI_FORMAT& dsv_format, + D3D12_RASTERIZER_DESC& rasterizer, bool& has_rasterizer) { + // RASTERIZER1 (type 27) is the same width as RASTERIZER. The width comes from the table. + static_assert(stream_sizes[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER] == sizeof(unsigned) + sizeof(D3D12_RASTERIZER_DESC)); const auto* stream = static_cast(desc.pPipelineStateSubobjectStream); if (!desc.SizeInBytes || desc.SizeInBytes > 0x2000 || desc.SizeInBytes % 8 || !x2w_local::readable(stream, desc.SizeInBytes)) return nullptr; @@ -483,8 +501,12 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 for (std::size_t at = 0; at < desc.SizeInBytes;) { unsigned type; std::memcpy(&type, stream + at, sizeof(type)); - if (type >= std::size(stream_sizes) || stream_sizes[type] > desc.SizeInBytes - at || (seen & (1u << type))) - return nullptr; + // Type 27 is RASTERIZER1. It is outside the table; its width is the RASTERIZER entry. + const bool rasterizer1 = type == 27; + if (!rasterizer1 && type >= std::size(stream_sizes)) return nullptr; + if (type >= 32) return nullptr; + const std::size_t size = rasterizer1 ? stream_sizes[D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER] : stream_sizes[type]; + if (size > desc.SizeInBytes - at || (seen & (1u << type))) return nullptr; seen |= 1u << type; if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE) { std::memcpy(&root, stream + at + 8, sizeof(root)); @@ -518,8 +540,24 @@ Translation* stream_translation(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, D3 DXGI_FORMAT fmt = DXGI_FORMAT_UNKNOWN; std::memcpy(&fmt, stream + at + sizeof(type), sizeof(fmt)); dsv_format = desktop_format(fmt); + } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER || type == 27) { + // Both encodings describe the same rasterizer state. + if (has_rasterizer) return nullptr; + // RASTERIZER (48B from stream_sizes) / RASTERIZER1 (same width, float depth bias). + D3D12_RASTERIZER_DESC parsed{}; + if (sizeof(type) + sizeof(parsed) > size) return nullptr; + std::memcpy(&parsed, stream + at + sizeof(type), sizeof(parsed)); + if (type == 27) { + float bias = 0; + std::memcpy(&bias, &parsed.DepthBias, sizeof(bias)); + INT integral = 0; + if (!integral_depth_bias(bias, integral)) return nullptr; + parsed.DepthBias = integral; + } + rasterizer = parsed; + has_rasterizer = true; } - at += stream_sizes[type]; + at += size; } if (!root || !stages[0].pShaderBytecode || !stages[1].pShaderBytecode) return nullptr; std::vector root_blob; @@ -597,6 +635,10 @@ BoundPipeline* translation_for(Wrapper* pipeline) bound->depth_stencil = info->stream_depth_stencil; bound->has_depth_stencil = true; } + if (info->has_stream_rasterizer) { + bound->rasterizer = info->stream_rasterizer; + bound->has_rasterizer = true; + } bound->dsv_format = info->stream_dsv_format; } // X2W_DEPTH_STATE=1 (#1999, item A): the depth-stencil registers of a slot 57 pipeline's state block A. A slot 57 @@ -726,6 +768,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P // A state decoded from registers needs a depth view to act on; with none bound the pass keeps the desktop default. const bool use_depth_stencil = bound.has_depth_stencil && (!bound.depth_from_registers || dsv_format != DXGI_FORMAT_UNKNOWN); if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); + if (bound.has_rasterizer) key = fnv_bytes(&bound.rasterizer, sizeof(bound.rasterizer), key); key = fnv_bytes(&indexed_rect, sizeof(indexed_rect), key); const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; @@ -746,7 +789,8 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P desc.GS = {tr.indexed_rect_geometry->GetBufferPointer(), tr.indexed_rect_geometry->GetBufferSize()}; } // Blend state as found in the pipeline's state block, else opaque. Depth-stencil state and - // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state: no culling. + // DSVFormat come from the stream PSO (or bound DSV), else disabled. Raster state comes from + // the stream RASTERIZER / RASTERIZER1 subobject, else solid fill, no culling, depth clip on. for (auto& target : desc.BlendState.RenderTarget) target = {FALSE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; @@ -759,9 +803,13 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P } if (use_depth_stencil) desc.DepthStencilState = bound.depth_stencil; desc.SampleMask = ~0u; - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.RasterizerState.DepthClipEnable = TRUE; + if (bound.has_rasterizer) { + desc.RasterizerState = bound.rasterizer; + } else { + desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + desc.RasterizerState.DepthClipEnable = TRUE; + } desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; desc.NumRenderTargets = pass.target_count; for (UINT i = 0; i < pass.target_count; ++i) desc.RTVFormats[i] = pass.target_formats[i]; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f1871c4c5..694847cf4 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -4172,6 +4172,8 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE D3D12_DEPTH_STENCIL_DESC depth_stencil{}; bool has_depth_stencil = false; DXGI_FORMAT dsv_format = DXGI_FORMAT_UNKNOWN; + D3D12_RASTERIZER_DESC rasterizer{}; + bool has_rasterizer = false; bool compute = false; IndirectGraphicsPipeline graphics; u64 mesh86_key = 0; @@ -4184,7 +4186,8 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE if (!real_pipeline) real_pipeline = try_cached_mesh86(*desc, why, sizeof(why), graphics, mesh_cache_request, mesh86_key); if (!mesh_cache_request && (!real_pipeline || graphics.root)) - translation = stream_translation(*desc, blend, has_blend, depth_stencil, has_depth_stencil, dsv_format); + translation = stream_translation(*desc, blend, has_blend, depth_stencil, has_depth_stencil, dsv_format, + rasterizer, has_rasterizer); static LONG built; if ((real_pipeline || !translation) && first_calls(built, 24)) log("x2w-render stream pipeline -> %s%s", real_pipeline ? "REAL desktop pipeline" : "placeholder: ", real_pipeline ? "" : why); @@ -4196,7 +4199,8 @@ HRESULT __stdcall device_create_pipeline_stream_x(Wrapper*, const D3D12_PIPELINE note_pipeline(static_cast(*out), 86, nullptr, desc->pPipelineStateSubobjectStream, desc->SizeInBytes < 0x2000 ? desc->SizeInBytes : 0x2000, translation, translation && has_blend ? &blend : nullptr, translation && has_depth_stencil ? &depth_stencil : nullptr, - translation ? dsv_format : DXGI_FORMAT_UNKNOWN); + translation ? dsv_format : DXGI_FORMAT_UNKNOWN, + translation && has_rasterizer ? &rasterizer : nullptr); return S_OK; } diff --git a/tests/startup_stream_rasterizer.cpp b/tests/startup_stream_rasterizer.cpp new file mode 100644 index 000000000..b88208b35 --- /dev/null +++ b/tests/startup_stream_rasterizer.cpp @@ -0,0 +1,252 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stream_setup.h" + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { + +struct alignas(8) StageSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_SHADER_BYTECODE shader; +}; +struct alignas(8) RootSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + ID3D12RootSignature* signature; +}; +struct alignas(8) RasterizerSubobject { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_RASTERIZER_DESC desc; +}; +static_assert(sizeof(StageSubobject) == 24); +static_assert(sizeof(RootSubobject) == 16); +static_assert(sizeof(RasterizerSubobject) == 48); +static_assert(offsetof(RasterizerSubobject, desc) == 4); + +struct BaseStream { + StageSubobject ps; + RootSubobject root; + StageSubobject vs; +}; +struct RasterStream { + BaseStream base; + RasterizerSubobject raster; +}; +struct MixedRasterStream { + BaseStream base; + RasterizerSubobject first; + RasterizerSubobject second; +}; +static_assert(sizeof(BaseStream) % 8 == 0); +static_assert(sizeof(RasterStream) % 8 == 0); + +using Word = std::uint64_t; +template Word ptr_arg(T* p) { return reinterpret_cast(p); } + +bool read_bytes(const char* path, std::vector& out) +{ + std::ifstream file(path, std::ios::binary); + out.assign(std::istreambuf_iterator(file), {}); + return !out.empty(); +} + +int pick_adapter(bool hardware, ComPtr& adapter) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + +D3D12_RASTERIZER_DESC raster_desc(D3D12_CULL_MODE cull, BOOL depth_clip) +{ + D3D12_RASTERIZER_DESC desc{}; + desc.FillMode = D3D12_FILL_MODE_SOLID; + desc.CullMode = cull; + desc.DepthClipEnable = depth_clip; + return desc; +} + +// kind 0 drops the rasterizer subobject. kind 1 is RASTERIZER. kind 2 is RASTERIZER1 (type 27), +// and bias replaces the int depth bias with the float bits. +void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, + const std::vector& ps, int kind, const D3D12_RASTERIZER_DESC& raster, float bias, + bool mixed = false) +{ + using CreateStream = HRESULT (WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); + auto create = reinterpret_cast((*static_cast(device))[86]); + BaseStream base{ + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, + {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}, + }; + void* pso = nullptr; + if (kind == 0) { + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(base), &base}; + if (FAILED(create(device, &desc, __uuidof(ID3D12PipelineState), &pso))) return nullptr; + return pso; + } + RasterizerSubobject sub{kind == 1 ? D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + : static_cast(27), + raster}; + if (kind == 2) std::memcpy(&sub.desc.DepthBias, &bias, sizeof(bias)); + if (mixed) { + const auto other_type = kind == 2 ? D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER + : static_cast(27); + MixedRasterStream stream{base, sub, {other_type, raster_desc(D3D12_CULL_MODE_NONE, TRUE)}}; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + if (FAILED(create(device, &desc, __uuidof(ID3D12PipelineState), &pso))) return nullptr; + return pso; + } + RasterStream stream{base, sub}; + const D3D12_PIPELINE_STATE_STREAM_DESC desc{sizeof(stream), &stream}; + if (FAILED(create(device, &desc, __uuidof(ID3D12PipelineState), &pso))) return nullptr; + return pso; +} + +int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) +{ + if (FAILED(static_cast(invoke(list, 9)))) return 50; + void* lists[] = {list}; + invoke(queue, 10, 1, ptr_arg(lists)); + if (FAILED(static_cast(invoke(queue, 14, ptr_arg(fence), fence_value)))) return 51; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value && GetTickCount64() < deadline) Sleep(1); + return invoke(fence, 8) >= fence_value ? 0 : 53; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 5 && argc != 13) return 2; + std::vector vs, ps; + if (!read_bytes(argv[1], vs) || !read_bytes(argv[2], ps)) return 3; + const bool hardware = std::strcmp(argv[4], "hardware") == 0; + + ComPtr adapter; + if (const int rc = pick_adapter(hardware, adapter)) return rc; + { + DXGI_ADAPTER_DESC desc{}; + LARGE_INTEGER driver{}; + if (FAILED(adapter->GetDesc(&desc))) return 4; + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls vendor=%04x device=%04x driver=%u.%u.%u.%u\n", desc.Description, desc.VendorId, desc.DeviceId, + HIWORD(driver.HighPart), LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart)); + std::fflush(stdout); + } + + std::array parameters{}; + void* guest = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &guest))) return 5; + + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + ComPtr blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr))) return 6; + std::ofstream(argv[3], std::ios::binary).write(static_cast(blob->GetBufferPointer()), blob->GetBufferSize()); + ID3D12RootSignature* root = nullptr; + if (FAILED(static_cast(invoke(guest, 16, 0, ptr_arg(blob->GetBufferPointer()), blob->GetBufferSize(), + ptr_arg(&__uuidof(ID3D12RootSignature)), ptr_arg(&root))))) return 7; + + const D3D12_RASTERIZER_DESC back = raster_desc(D3D12_CULL_MODE_BACK, TRUE); + const D3D12_RASTERIZER_DESC front = raster_desc(D3D12_CULL_MODE_FRONT, TRUE); + D3D12_RASTERIZER_DESC fractional = raster_desc(D3D12_CULL_MODE_NONE, FALSE); + void* pso_back = create_stream_pso(guest, root, vs, ps, 1, back, 0); + void* pso_front = create_stream_pso(guest, root, vs, ps, 1, front, 0); + void* pso_dropped = create_stream_pso(guest, root, vs, ps, 0, back, 0); + void* pso_r1_back = create_stream_pso(guest, root, vs, ps, 2, back, 0.0f); + void* pso_r1_front = create_stream_pso(guest, root, vs, ps, 2, front, 0.0f); + // 0.5 is not an integer depth bias. The pipeline must be refused, not drawn with cull none. + void* pso_bias = create_stream_pso(guest, root, vs, ps, 2, fractional, 0.5f); + if (!pso_back || !pso_front || !pso_dropped || !pso_r1_back || !pso_r1_front || !pso_bias) return 9; + if (argc == 5) return 0; + // Both mixed orders must be refused. Without the check, the final no-cull state draws pixels. + void* mixed_10_27 = create_stream_pso(guest, root, vs, ps, 1, back, 0, true); + void* mixed_27_10 = create_stream_pso(guest, root, vs, ps, 2, back, 0, true); + if (!mixed_10_27 || !mixed_27_10) return 10; + + ComPtr desktop; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&desktop)))) return 20; + + constexpr UINT width = 8, height = 4; + StreamTarget state{}; + state.count = 1; + state.attachments[0].row_bytes = width * 4; + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const float clear_color[] = {0.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_RESOURCE_DESC rtv_tex_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0.0f, 0.0f, 1.0f, 1.0f}}; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rtv_tex_desc, + D3D12_RESOURCE_STATE_COMMON, &rtv_clear, IID_PPV_ARGS(&state.attachments[0].texture)))) return 21; + + const struct { D3D12_DESCRIPTOR_HEAP_DESC desc; Word backing, bytes; } + rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + if (FAILED(static_cast(invoke(guest, 14, ptr_arg(&rtv_heap_desc), ptr_arg(&__uuidof(ID3D12DescriptorHeap)), ptr_arg(&state.rtv_heap))))) + return 22; + + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{static_cast(invoke(state.rtv_heap, 9))}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + invoke(guest, 20, ptr_arg(state.attachments[0].texture.Get()), ptr_arg(&rtv_view), rtv.ptr); + + D3D12_COMMAND_QUEUE_DESC qd{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + if (FAILED(static_cast(invoke(guest, 8, ptr_arg(&qd), ptr_arg(&__uuidof(ID3D12CommandQueue)), ptr_arg(&state.queue)))) || + FAILED(static_cast(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, ptr_arg(&__uuidof(ID3D12CommandAllocator)), ptr_arg(&state.allocator)))) || + FAILED(static_cast(invoke(guest, 73, ptr_arg(list_desc), ptr_arg(state.allocator), 0, ptr_arg(&__uuidof(ID3D12GraphicsCommandList)), ptr_arg(&state.list)))) || + FAILED(static_cast(invoke(guest, 36, 0, 0, ptr_arg(&__uuidof(ID3D12Fence)), ptr_arg(&state.fence))))) return 23; + + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT rect{0, 0, 4, static_cast(height)}; + + auto run_case = [&](UINT64 fence_val, const char* out_path, void* pso) -> int { + if (FAILED(static_cast(invoke(state.allocator, 8)))) return 24; + if (FAILED(static_cast(invoke(state.list, 139, ptr_arg(state.allocator))))) return 25; + invoke(state.list, 52, rtv.ptr, ptr_arg(clear_color)); + invoke(state.list, 21, 1, ptr_arg(&viewport)); + invoke(state.list, 22, 1, ptr_arg(&rect)); + invoke(state.list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(state.list, 50, 1, ptr_arg(&rtv)); + invoke(state.list, 25, ptr_arg(pso)); + invoke(state.list, 12, 3, 1); + if (const int rc = execute_guest_list(state.queue, state.list, state.fence, fence_val)) return rc; + return read_stream_target(desktop.Get(), state, out_path); + }; + + if (const int rc = run_case(1, argv[5], pso_back)) return rc; + if (const int rc = run_case(2, argv[6], pso_front)) return rc; + if (const int rc = run_case(3, argv[7], pso_dropped)) return rc; + if (const int rc = run_case(4, argv[8], pso_r1_back)) return rc; + if (const int rc = run_case(5, argv[9], pso_r1_front)) return rc; + if (const int rc = run_case(6, argv[10], pso_bias)) return rc; + if (const int rc = run_case(7, argv[11], mixed_10_27)) return rc; + if (const int rc = run_case(8, argv[12], mixed_27_10)) return rc; + return 0; +} diff --git a/tests/startup_stream_rasterizer_check.py b/tests/startup_stream_rasterizer_check.py new file mode 100644 index 000000000..9ca49ba6f --- /dev/null +++ b/tests/startup_stream_rasterizer_check.py @@ -0,0 +1,81 @@ +"""Cull through a slot-86 RASTERIZER / RASTERIZER1 subobject and check the 8x4 readback.""" +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import pixel, vertex + + +def check(directory, consumer, backend, mode): + cache = directory / "cache" + cache.mkdir() + vs, ps, root = (directory / name for name in ("vs", "ps", "root")) + cases = ("back", "front", "dropped", "r1_back", "r1_front", "bias", "mixed_10_27", "mixed_27_10") + outs = {name: directory / name for name in cases} + vs.write_bytes(vertex()) + ps.write_bytes(pixel(True)) + + env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache)) + base_args = [consumer, str(vs), str(ps), str(root), backend] + req = subprocess.run(base_args, env=env, capture_output=True, text=True) + if backend == "hardware" and req.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if req.returncode: + print(req.stdout, end="") + raise RuntimeError(f"request run failed on {backend}: {req.returncode}\n{req.stderr}") + subprocess.run([sys.executable, "-B", gfx2hlsl.__file__, "--pending", cache], env=env, check=True) + + run = subprocess.run(base_args + [str(outs[name]) for name in cases], + env=env, capture_output=True, text=True) + print(run.stdout, end="") + for line in run.stderr.splitlines(): + if "debug layer:" in line or "x2w-d3d12-debug " in line: + print(line) + if backend == "hardware" and run.returncode == 77: + print("No D3D12 feature-level 12 hardware adapter") + return 77 + if run.returncode or "-> drawn;" not in run.stderr: + if mode == "ignore": + print(f"ignore control did not reach a readback on {backend}: {run.returncode}") + return 0 + raise RuntimeError(f"rasterizer draw failed on {backend}: {run.returncode}\n{run.stderr}") + assert not re.search(r"x2w-d3d12-debug.*sev=[012]\b", run.stderr), run.stderr + + images = {name: outs[name].read_bytes() for name in outs} + green = bytes((0, 255, 0, 255)) + clear = bytes((0, 0, 255, 255)) + drawn = (green * 4 + clear * 4) * 4 + blank = clear * 32 + + # Dropping the subobject keeps today's solid / no-cull default. Ignoring a present + # rasterizer makes the back and front images match that default, and this control fails. + if mode == "ignore": + if images["back"] == images["dropped"] and images["front"] == images["dropped"]: + print(f"{backend}: ignore control saw the no-cull readback") + return 0 + print(f"{backend}: ignore control failed because the stream rasterizer changed the 8x4 readback") + return 1 + + assert images["dropped"] == drawn, f"dropped: {images['dropped'].hex()}" + assert images["back"] != images["front"], "front and back cull produced the same readback" + assert {images["back"], images["front"]} == {drawn, blank}, ( + f"back {images['back'].hex()} front {images['front'].hex()}") + assert images["r1_back"] == images["back"], f"rasterizer1 back: {images['r1_back'].hex()}" + assert images["r1_front"] == images["front"], f"rasterizer1 front: {images['r1_front'].hex()}" + assert images["bias"] == blank, f"fractional depth bias drew: {images['bias'].hex()}" + mixed_draws = [name for name in ("mixed_10_27", "mixed_27_10") if images[name] != blank] + assert not mixed_draws, f"duplicate rasterizer state drew pixels: {mixed_draws}" + print(f"{backend}: cull changed the readback; fractional bias and both mixed rasterizer orders stayed clear") + return 0 + + +if __name__ == "__main__": + mode = sys.argv[3] if len(sys.argv) > 3 else "apply" + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), sys.argv[1], sys.argv[2], mode)) From a31f70a134fc231930fb6bb1530f6911173c0893 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:30:35 +0100 Subject: [PATCH 032/232] startup: lower buffer_load_format_x/xy/xyz with the format from the buffer descriptor (#2138) * startup: lower buffer_load_format_x/xy/xyz with the format from the buffer descriptor The FORMAT and DST_SEL fields of descriptor word 3 reach the translated body as an entry constant (descword3), which switches over the existing FETCH_FORMATS table. xyzw stays refused. * test: route W into the third register for W-only descriptor-path mutations * test: name the descriptor-path components c0..c3 in the mutations * test: expect buffer_load_format_x/xy/xyz to translate, keep xyzw refused * startup: refuse formatted buffer loads whose descriptor word 3 was rewritten in the shader * startup: refuse formatted buffer loads whose descriptor word 3 is unresolved, unsupported or unbacked The draw carried word 3 as 0 for any binding that was not a hardware descriptor, so missing metadata looked like a real descriptor. It now tracks a hardware flag and a bound-buffer flag per binding and refuses the draw before any list command unless FORMAT is in the translated table. * Prove formatted descriptors before using hardware bindings * test: accept the join-symbol refusal for a skipped descriptor load * test: accept the join-symbol refusal in the root-pointer clobber control * fix: make unknown buffer FORMAT loud and check every MTBUF format code strictly --------- Co-authored-by: Codex --- CMakeLists.txt | 4 + docs/experiments.md | 1 + src/startup_stubs/d3d12_draw.inl | 72 +++++- src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/formatted_buffer.h | 24 ++ tests/startup_address_srv.cpp | 33 +++ tests/startup_buffer_address_check.py | 5 + tests/startup_mubuf_descriptor_check.py | 51 ++++ tests/startup_stream_consumer.cpp | 3 +- tests/startup_stream_draw.cpp | 3 + tests/startup_vertex_fetch_formats_check.py | 256 +++++++++++++++++++- tools/startup/gfx2hlsl.py | 153 +++++++++++- 12 files changed, 586 insertions(+), 20 deletions(-) create mode 100644 src/startup_stubs/formatted_buffer.h create mode 100644 tests/startup_mubuf_descriptor_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 341f9f688..62c52a9e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3496,6 +3496,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_buffer_srv_check.py" "$" "${backend}") set_tests_properties(startup_address_buffer_srv_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_mubuf_descriptor_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mubuf_descriptor_check.py" + "$" "${backend}") + set_tests_properties(startup_mubuf_descriptor_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_address_volume_srv_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_volume_srv_check.py" "$" "${backend}") diff --git a/docs/experiments.md b/docs/experiments.md index 11db47e27..64002f121 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -286,6 +286,7 @@ ctest --preset dev --no-tests=error -R '^startup_vertex_fetch_formats_(controls| `BUF_FMT_16_16_SNORM` (format 24, DXGI `R16G16_SNORM` 37) sign-extends each half, divides by 32767 and clamps to -1.0, so -32768 and -32767 both give -1.0 (the Direct3D and Vulkan SNORM rule, as in LLVM 15 and Mesa `ac_formats`). The device run compares `round(v * 32767)` against the same byte decode, with a wrong reference that reads the halves unsigned and a mutated translation that does the same. The pattern the harness writes to t0 holds no 0x8000, so `startup_vertex_fetch_formats_controls` also evaluates the emitted expressions on 0x8000, 0x8001, 0x7fff, 0x0000, 0xffff and 0x4000 in each half, and four wrong forms (unsigned read, no clamp, divisor 32768, one half for both) must fail that check. The D3D12 draw has not been run on Linux. +`buffer_load_format_x`, `_xy` and `_xyz` (MUBUF) use FORMAT (word 3 bits 12 to 18) and DST_SEL (bits 0 to 11) from the buffer descriptor. The draw snapshots the hardware table descriptor and provides word 3 as `udsrc descword3 `. It refuses missing hardware descriptor metadata, unsupported FORMAT codes and unresolved buffer ranges before submitting the draw. The shader decodes using the same expressions as the tbuffer path. Selectors 4 to 7 choose x, y, z and w, while selectors 0 and 1 choose constants 0 and 1. For a load after a branch, the vertex or pixel shader must load all four descriptor words in the same basic block as the use. The root table pointer must reach the load or its local pointer copy without any intervening write along the control-flow predecessors. It refuses rewritten descriptor words and the four-component `buffer_load_format_xyzw` form. `startup_vertex_fetch_formats_*` covers twelve formats, component swizzles, integer 1 and mutations that must differ on readback. `startup_mubuf_descriptor_*` draws with the real binding path on WARP and hardware. Missing metadata, unsupported FORMAT and unresolved backing leave the target blue, while valid zero and one draw black and red. `BUF_FMT_8_8_8_8_UINT` (gfx10 format 60, DXGI `R8G8B8A8_UINT` 30) reads four unsigned bytes into X, Y, Z and W in increasing address order. With stride 5 and byte offset 3, the 16-vertex fixture visits all four dword alignments. On WARP, all 64 component words matched the byte reference. Swapping channels in the reference or normalizing the green byte in the generated shader each triggered a mismatch. `BUF_FMT_16_16_UINT` (gfx10 format 27; LLVM 15 `BUF_DATA_FORMAT_16_16` with `BUF_NUM_FORMAT_UINT`) reads two unsigned 16-bit fields into X and Y, the low half first, with Z = 0 and W = 1. With stride 6 and byte offset 2, the fixture's elements sit at two dword alignments, so half of them cross a dword. On WARP and on an AMD Radeon RX 9070 XT (driver 32.0.32015.7029, Windows 10.0.26300.9974, debug layer enabled), all 64 component words matched the byte reference. The wrong references and three mutated translations each triggered a mismatch: a normalized low half, the high half read from the low half, and a missing W read as 1.0. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 023a09010..b20718a9c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -11,7 +11,7 @@ struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a - enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16 }; + enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable ULONGLONG retry_manifest_at = 0; // Only an absent manifest can become ready on a later draw. @@ -175,6 +175,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) else if (!std::strcmp(source, "rootconst")) ud.kind = Translation::root_constant; else if (!std::strcmp(source, "stride")) ud.kind = Translation::stride; else if (!std::strcmp(source, "d16unorm16") && x >= 0 && x < 32) ud.kind = Translation::d16_unorm16; + else if (!std::strcmp(source, "descword3")) ud.kind = Translation::desc_word3; else if (!std::strcmp(source, "mrtbits") && !rtv_request.empty()) ud.kind = Translation::mrt_bits; if (static_cast(i) == tr.uds.size() && ud.kind >= 0) tr.uds.push_back(ud); } else if (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { @@ -1530,6 +1531,7 @@ namespace indirect_refusal_code { constexpr const char* pipeline_or_target_unavailable = "pipeline_or_target_unavailable"; constexpr const char* translation_not_ready = "translation_not_ready"; constexpr const char* d16_srv_not_ready = "d16_srv_not_ready"; +constexpr const char* formatted_buffer_not_ready = "formatted_buffer_not_ready"; constexpr const char* missing_guest_root = "missing_guest_root"; constexpr const char* live_compute_pipeline = "live_compute_pipeline"; constexpr const char* unsupported_resource_or_entry = "unsupported_resource_or_entry"; @@ -1779,6 +1781,42 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor return {native, offset, bytes, stride, upload}; } +struct FormattedBufferDescriptor { + u64 entry = 0; + std::uint32_t words[8] = {}; +}; + +bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[32]) +{ + const auto refuse = [&](int slot, const char* reason, std::uint32_t detail = 0) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-draw %016llx srv %d: formatted buffer refused (%s %u)", tr.key, slot, reason, detail); + return false; + }; + for (const auto& ud : tr.uds) { + if (ud.kind != Translation::desc_word3) continue; + if (ud.a < 0 || ud.a >= 32 || static_cast(ud.a) >= tr.srvs.size()) + return refuse(ud.a, "invalid SRV index"); + auto& descriptor = descriptors[ud.a]; + if (descriptor.entry) continue; + const auto& srv = tr.srvs[ud.a]; + if (srv.kind != 0 || srv.source != 0 || srv.a < 0 || srv.a >= 16 || srv.b < 0) + return refuse(ud.a, "missing hardware descriptor"); + const u64 entry = pass.view_tables[srv.a].record(static_cast(srv.b), sizeof(descriptor.words)); + if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(descriptor.words))) + return refuse(ud.a, "missing hardware descriptor"); + std::memcpy(descriptor.words, reinterpret_cast(entry), sizeof(descriptor.words)); + if (descriptor.words[0] == view_token_magic) + return refuse(ud.a, "missing hardware descriptor"); + const auto format = x2w_startup::formatted_buffer_code(descriptor.words[3]); + if (!x2w_startup::formatted_buffer_supported(format)) + return refuse(ud.a, "unsupported FORMAT", format); + descriptor.entry = entry; + } + return true; +} + bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UINT start, INT base_vertex, UINT start_instance, TranslatedIndirectDraw* indirect) { @@ -1793,10 +1831,15 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; if (indirect && tr) indirect->shader_key = tr->key; std::uint32_t d16_unorm16[32] = {}; - if (!tr || tr->state != 1 || !d16_srvs_ready(*tr, pass, d16_unorm16)) { + FormattedBufferDescriptor formatted_buffers[32] = {}; + const bool translation_ok = tr && tr->state == 1; + const bool d16_ok = translation_ok && d16_srvs_ready(*tr, pass, d16_unorm16); + const bool formatted_ok = d16_ok && formatted_buffers_ready(*tr, pass, formatted_buffers); + if (!formatted_ok) { if (indirect && tr) - indirect->refusal_code = tr->state != 1 ? indirect_refusal_code::translation_not_ready - : indirect_refusal_code::d16_srv_not_ready; + indirect->refusal_code = !translation_ok ? indirect_refusal_code::translation_not_ready + : !d16_ok ? indirect_refusal_code::d16_srv_not_ready + : indirect_refusal_code::formatted_buffer_not_ready; ReleaseSRWLockExclusive(&draw_lock); return false; } @@ -1900,11 +1943,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI address = pass.root_address[srv.a]; bytes = readable_window(address, 0x10000); } - const u64 entry = srv.source == 0 && srv.a >= 0 && srv.a < 16 && srv.b >= 0 ? - pass.view_tables[srv.a].record(static_cast(srv.b), 32) : 0; + const auto& formatted = formatted_buffers[i]; + const u64 entry = formatted.entry ? formatted.entry : + (srv.source == 0 && srv.a >= 0 && srv.a < 16 && srv.b >= 0 ? + pass.view_tables[srv.a].record(static_cast(srv.b), 32) : 0); std::uint32_t words[8] = {}; - const bool entry_ok = entry && x2w_local::readable(reinterpret_cast(entry), 32); - if (entry_ok) std::memcpy(words, reinterpret_cast(entry), 32); + const bool entry_ok = formatted.entry || + (entry && x2w_local::readable(reinterpret_cast(entry), 32)); + if (entry_ok) std::memcpy(words, formatted.entry ? formatted.words : reinterpret_cast(entry), 32); bool buffer_token_known = false; if (srv.kind >= 1 && srv.kind <= 4) { const auto dimension = srv.kind == 1 ? D3D12_SRV_DIMENSION_TEXTURE2D : @@ -2101,6 +2147,13 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // matrices instead of zeros. The start-up screen's last pass takes its world matrix from a // slot the title leaves empty here; why is not known yet. static const bool identity_for_null = x2w_local::env_on("X2W_DRAW_NULL_IDENTITY"); + if (!have && formatted.entry) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-draw %016llx srv %u: formatted buffer refused (unresolved buffer)", tr->key, i); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } if (!have && identity_for_null) { static float identity[64]; for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; @@ -2128,7 +2181,8 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI : ud.kind == Translation::start_instance ? start_instance : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0) : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] - : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] : 0; + : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] + : ud.kind == Translation::desc_word3 ? formatted_buffers[ud.a].words[3] : 0; } // A desktop list with no viewport or scissor draws nothing: cover the first render target unless the title set its own. if (pass.target0 && (!pass.viewport_set || !pass.scissor_set)) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 694847cf4..0582b5953 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -24,6 +24,7 @@ #include "startup_stubs/export_write_mask.h" #include "startup_stubs/depth_state_apply.h" #include "startup_stubs/d16_image_format.h" +#include "startup_stubs/formatted_buffer.h" #include "startup_stubs/heap_indexed_root.h" #include "startup_stubs/indexed_indirect_guard.h" #include "startup_stubs/indexed_rect_geometry.h" diff --git a/src/startup_stubs/formatted_buffer.h b/src/startup_stubs/formatted_buffer.h new file mode 100644 index 000000000..2a216abb0 --- /dev/null +++ b/src/startup_stubs/formatted_buffer.h @@ -0,0 +1,24 @@ +// gfx10 V# word 3: formats for which gfx2hlsl emits a formatted-load case. +#pragma once + +#include + +namespace x2w_startup { + +constexpr std::uint32_t formatted_buffer_code(std::uint32_t word3) +{ + return (word3 >> 12) & 127u; +} + +constexpr bool formatted_buffer_supported(std::uint32_t code) +{ + switch (code) { + case 1: case 5: case 14: case 22: case 23: case 24: case 27: + case 29: case 56: case 60: case 64: case 71: case 74: case 77: + return true; + default: + return false; + } +} + +} // namespace x2w_startup diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 64afd9d90..d2ab481a6 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -709,6 +709,39 @@ int draw_d16_srvs(ID3D12Device* desktop, void* guest, void* list) return 0; } +// One translated pixel shader uses the same table slot across five draws. The clear color is opaque blue. +int draw_formatted_buffer(void* guest, void* list) +{ + alignas(16) static const std::uint32_t zeros[4] = {}; + alignas(16) static const std::uint32_t red[4] = {0x3f800000u}; + const auto draw_at = [&](LONG x) { + const D3D12_RECT strip{x, 0, x + 1, 4}; + invoke(list, 22, 1, ptr(&strip)); + invoke(list, 12, 3, 1); + }; + draw_at(0); // No table binding. + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + const auto store = [&](const std::uint32_t* data, std::uint32_t format) { + const auto address = ptr(data); + const std::uint32_t descriptor[4] = {static_cast(address), + static_cast(address >> 32) | (4u << 16), 4u, (format << 12) | 4u}; + std::memcpy(reinterpret_cast(cpu), descriptor, sizeof(descriptor)); + }; + store(red, 2); + draw_at(1); // Unknown FORMAT, readable descriptor and range. + store(zeros, 22); + draw_at(2); // Real zero data with a supported R32_FLOAT descriptor. + store(nullptr, 22); + draw_at(3); // Supported metadata with no resolved buffer. + store(red, 22); + // Expand the viewport from the fixture's initial four columns to all eight. + const D3D12_VIEWPORT viewport{0, 0, 8, 4, 0, 1}; + invoke(list, 21, 1, ptr(&viewport)); + draw_at(4); // Nonzero data proves the accepted format is sampled. + return 0; +} + // 3D volume memory SRV (device slot 70) with 2 mips (4x4x2 and 2x2x1) in RGBA8_UNORM format. int draw_volume_address_srvs(ID3D12Device* desktop, void* guest, void* list) { diff --git a/tests/startup_buffer_address_check.py b/tests/startup_buffer_address_check.py index ba5842f76..fcd13238c 100644 --- a/tests/startup_buffer_address_check.py +++ b/tests/startup_buffer_address_check.py @@ -219,6 +219,11 @@ def request(load): mnemonic = 'buffer_load_format_' + suffix assert G.decode(load) == [(0, 8, mnemonic, f'{mnemonic} {dest}, off, s[32:35], 0')] result, name = request(load) + if op < 3: + # x, xy and xyz take FORMAT and DST_SEL from descriptor word 3 at draw time. + assert result == 'ok', result + assert 'switch ((ud' in name.with_suffix('.vs.hlsl').read_text() + continue reason = name.with_suffix('.fail').read_text().strip() assert reason == f'{mnemonic} requires descriptor FORMAT and DST_SEL', reason assert result == f'unsupported: {reason}', result diff --git a/tests/startup_mubuf_descriptor_check.py b/tests/startup_mubuf_descriptor_check.py new file mode 100644 index 000000000..26f46cb67 --- /dev/null +++ b/tests/startup_mubuf_descriptor_check.py @@ -0,0 +1,51 @@ +"""Run accepted and refused hardware buffer descriptors through the translated draw path.""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from startup_buffer_address_check import encode_mubuf +from startup_stream_draw_check import container, gfx2hlsl, vertex + + +def check(directory, consumer, backend): + cache = directory / 'cache' + cache.mkdir() + vs, ps, root, output = (directory / name for name in ('vs', 'ps', 'root', 'pixels')) + trap_log = directory / 'trap.log' + vs.write_bytes(vertex()) + code = (bytes.fromhex('040408f4000000fa7fc08cbf') # s_load_dwordx4 s[16:19], s[8:9], 0; wait + + encode_mubuf(op=0, vdata=4) + + bytes.fromhex('703f8cbf8002007ef202027e0f1800f804000001000081bf')) + ps.write_bytes(container(0, struct.unpack('<%dI' % (len(code) // 4), code))) + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', + X2W_D3D12_RENDER='1', X2W_D3D12_DEBUG='1', X2W_D3D12_DEVICE_NOOP='1', + X2W_TEST_FORMATTED_BUFFER='1', X2W_DRAW_NULL_IDENTITY='1', X2W_SHADER_CACHE=str(cache), X2W_TRAP_LOG=str(trap_log)) + args = [consumer, vs, ps, root] + subprocess.run(args, env=env, check=True) + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) + manifest, = cache.glob('*.txt') + text = manifest.read_text(encoding='ascii') + assert 'descword3 0' in text and 'srv 0 buf table 0 0' in text, text + result = subprocess.run([*args, backend, output], env=env, capture_output=True, text=True) + print(result.stdout, end='') + if result.returncode == 77: + return 77 + if result.returncode: + raise RuntimeError(f'consumer failed ({result.returncode})\n{result.stderr[-5000:]}') + clear, black, red = bytes((0, 0, 255, 255)), bytes((0, 0, 0, 255)), bytes((255, 0, 0, 255)) + want = (clear + clear + black + clear + red + clear * 3) * 4 + actual = output.read_bytes() + assert actual == want, (actual.hex(), want.hex()) + log = trap_log.read_text(errors='replace') + for diagnostic in ('missing hardware descriptor 0', 'unsupported FORMAT 2', 'unresolved buffer'): + assert f'formatted buffer refused ({diagnostic})' in log, (diagnostic, log) + print(f'{backend}: missing metadata, unsupported FORMAT and unresolved storage stayed blue; valid zero and one drew black and red') + return 0 + + +if __name__ == '__main__': + with tempfile.TemporaryDirectory() as directory: + sys.exit(check(Path(directory), *sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 132399c19..d3f5d5fac 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -259,7 +259,8 @@ int main(int argc, char** argv) void* device = nullptr; void* pso = nullptr; const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; - const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0; + const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 3681ee948..b6b703b6b 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -335,6 +335,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0)) { + extern int draw_formatted_buffer(void*, void*); + if (const int result = draw_formatted_buffer(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_VOLUME_SRV", nullptr, 0)) { extern int draw_volume_address_srvs(ID3D12Device*, void*, void*); if (const int result = draw_volume_address_srvs(desktop.Get(), guest, list)) return result; diff --git a/tests/startup_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 68d40461c..5e9446008 100644 --- a/tests/startup_vertex_fetch_formats_check.py +++ b/tests/startup_vertex_fetch_formats_check.py @@ -16,9 +16,15 @@ Each format with sub-dword fields uses a stride and offset that put elements at more than one byte alignment, so a field that crosses a dword is read through ldu(); the 32-bit formats keep aligned elements. UNORM components are compared as round(v * (2^bits - 1)), so the check does not depend on how many ulps the division is off by; every other component is compared bit for bit. +The same table also serves buffer_load_format_x/xy/xyz, whose format and component selection are not in the +instruction but in word 3 of the buffer descriptor (FORMAT bits 12..18, DST_SEL bits 0..11): the runtime passes +that word as an entry constant and the translation switches on it. Each format is run through a MUBUF +xyz load with its own descriptor word, then descriptor words with swizzles and constants 0 and 1 run through +the same translated body. Wrong references (channels swapped, a shift off by one field, a missing W read as 0, UNORM over 2^bits) and mutated translations must fail the readback. """ +import re import struct import subprocess import sys @@ -67,10 +73,10 @@ def snorm_words(fields, unsigned=False, no_clamp=False): return out -def reference(name, vertex, *, swap=False, shift=False, w_zero=False, unorm_pow2=False, unsigned=False, no_clamp=False): +def reference(name, vertex, *, offset=None, swap=False, shift=False, w_zero=False, unorm_pow2=False, unsigned=False, no_clamp=False): """The four compared words of one vertex, from the format definition. The keywords give wrong references.""" - _, stride, offset, bits, kind, count = FORMATS[name] - address, size = vertex * stride + offset, bits // 8 + _, stride, own_offset, bits, kind, count = FORMATS[name] + address, size = vertex * stride + (own_offset if offset is None else offset), bits // 8 fields = [int.from_bytes(DATA[address + size * i:address + size * (i + 1)], 'little') for i in range(count)] if shift and bits < 32: # Each field read one field higher, as a wrong shift would; the last reads past the element. @@ -186,6 +192,73 @@ def snorm_boundaries(components): assert abs(got - value) < 1e-6, (hex(half), low_first, got, value) +IDENTITY = 4 | 5 << 3 | 6 << 6 | 7 << 9 # DST_SEL X, Y, Z, W: the four components in order + + +def pipeline_mubuf(offset, op=2): + """A source-built vertex stage: buffer_load_format_xyz (op 2; 0 is _x, 1 is _xy) from a hardware table descriptor.""" + # s_load_dwordx4 s[16:19], s[8:9], 0 + # buffer_load_format_xyz v[4:6], v0, s[16:19], 0 idxen offset: + # exp pos0 v4, v5, v6, v7 done + words = (0xf4080404, 0xfa000000, 0xe0002000 | op << 18 | offset, 0x80040400, + 0xf80008cf, 0x07060504, 0xbf810000) + ps = struct.pack('<3I', 0xf800180f, 0, 0xbf810000) + result = gfx2hlsl.Pipeline(struct.pack('<7I', *words), ps, root_blob(flags=0)) + assert 'srv 0 buf table 0 0' in result.manifest().splitlines() + assert 'udsrc 5 descword3 0' in result.manifest().splitlines() + return result + + +def descriptor_word3(name, selects=(4, 5, 6, 7)): + """Word 3 of a buffer descriptor: FORMAT in bits 12..18, then DST_SEL x, y, z, w in three bits each.""" + return FORMATS[name][0] << 12 | sum(sel << 3 * i for i, sel in enumerate(selects)) + + +def mubuf_expected(name, count, selects=(4, 5, 6, 7), integer_one=False): + """The four compared words per vertex of a buffer_load_format_* with `count` registers and these DST_SEL values.""" + words = [SENTINEL] * 320 + one = 1 if integer_one else ONE + for vertex in range(16): + comps = reference(name, vertex) + comps = [comps[0], comps[1], comps[2], comps[3]] + out = [{4: comps[0], 5: comps[1], 6: comps[2], 7: comps[3], 1: one}.get(sel, 0) for sel in selects] + words[vertex * 4:vertex * 4 + 4] = out[:count] + [0] * (4 - count) + return words + + +def mutate_case(source, code, old, new): + """Replace `old` by `new` inside the switch case of one format code only.""" + lines = source.split('\n') + marker = 'case %du:' % code + hits = [i for i, line in enumerate(lines) if line.strip().startswith(marker) and old in line] + assert len(hits) == 1, (code, old) + lines[hits[0]] = lines[hits[0]].replace(old, new, 1) + return '\n'.join(lines) + + +# Translations a wrong switch would produce on the descriptor path: (label, old text, new text). +DESC_MUTATIONS = ( + ('format field ignored (always 4 half floats)', '(ud5 >> 12) & 127u', '71u'), + ('format field one bit low', '(ud5 >> 12) & 127u', '(ud5 >> 11) & 127u'), + ('DST_SEL y from the x field', '((ud5 >> 3) & 7u)', '((ud5 >> 0) & 7u)'), + ('DST_SEL constant 1 as 0', 'one = U(1.0)', 'one = 0u'), +) +# Integer 1 for the constant of an integer format, and the switch cases themselves, are mutated per format below. + + +def mubuf_cases(): + """(label, format used for the offset and the reference, descriptor word 3, expected words) for the device run.""" + cases = [] + for name in FORMATS: + cases.append(('%s xyz' % name, name, descriptor_word3(name), mubuf_expected(name, 3))) + wide, small = 'BUF_FMT_32_32_32_32_FLOAT', 'BUF_FMT_8_UINT' + cases.append(('xyzw read as y, x, 1', wide, descriptor_word3(wide, (5, 4, 1, 7)), mubuf_expected(wide, 3, (5, 4, 1)))) + cases.append(('xyzw read as w, 0, z', wide, descriptor_word3(wide, (7, 0, 6, 7)), mubuf_expected(wide, 3, (7, 0, 6)))) + cases.append(('uint constant 1 stays integer', small, descriptor_word3(small, (4, 1, 0, 7)), + mubuf_expected(small, 3, (4, 1, 0), integer_one=True))) + return cases + + def controls(): """Translation-side checks: every table entry is reached, and the reference is not degenerate.""" for name in FORMATS: @@ -194,6 +267,8 @@ def controls(): for name, label, old, new in MUTATIONS: source = pipeline(name).hlsl_vs() assert old in source, (name, label) + runtime = (Path(__file__).resolve().parents[1] / 'src' / 'startup_stubs' / 'formatted_buffer.h').read_text() + assert set(map(int, re.findall(r'case (\d+):', runtime))) == set(gfx2hlsl.DESC_FORMAT_CODES.values()) # SNORM: the emitted expressions hit the boundaries, and each wrong form is caught by the same check. components = gfx2hlsl.FETCH_FORMATS['BUF_FMT_16_16_SNORM'][1][:2] snorm_boundaries(components) @@ -236,6 +311,125 @@ def controls(): alignments = {(v * stride + offset) % 4 for v in range(16)} assert len(alignments) > 1 if bits < 32 else alignments == {0}, name + # buffer_load_format_x/xy/xyz: every table format has a switch case, and the codes match the disassembler's. + sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'tools')) + from disasm_rdna2 import MTBUF_FORMATS + assert gfx2hlsl.DESC_FORMAT_CODES.keys() == gfx2hlsl.FETCH_FORMATS.keys() + def table_matches(table): + for name, (code, *_rest) in FORMATS.items(): + if code == 1: # the omitted tbuffer format: LLVM prints nothing, the disassembler has no name for it + if code in table or name != 'BUF_FMT_8_UNORM': + return False + elif table.get(code) != name: + return False + return True + for name, (code, *_rest) in FORMATS.items(): + assert gfx2hlsl.DESC_FORMAT_CODES[name] == code, name + assert table_matches(MTBUF_FORMATS) + swapped = dict(MTBUF_FORMATS) # a wrong format name for one code must be caught + victim = next(c for n, (c, *_r) in FORMATS.items() if c != 1) + swapped[victim] = 'BUF_FMT_INVALID' + assert not table_matches(swapped), 'format mutation not caught' + assert not table_matches({**MTBUF_FORMATS, 1: 'BUF_FMT_8_UNORM'}), 'code 1 must stay the omitted default' + for op, count in ((0, 1), (1, 2), (2, 3)): + source = pipeline_mubuf(4, op).hlsl_vs() + assert source.count('case ') == len(FORMATS), op + # An unvalidated FORMAT yields the NaN sentinel in every component, never silent zeros. + assert 'default: c0 = c1 = c2 = c3 = %du;' % gfx2hlsl.DESC_FORMAT_UNKNOWN in source, op + assert 'default: break' not in source, op + written = {int(n) for n in re.findall(r'^\s*v(\d+) = ', source, re.M) if int(n) >= 4} + assert written == set(range(4, 4 + count)), (op, written) + try: + gfx2hlsl.Pipeline(struct.pack('<7I', 0xf4080404, 0xfa000000, 0xe00c2000, 0x80040400, 0xf80008cf, 0x07060504, 0xbf810000), + struct.pack('<3I', 0xf800180f, 0, 0xbf810000), root_blob(flags=0)) + except gfx2hlsl.Unsupported: + pass + else: + raise AssertionError('buffer_load_format_xyzw must stay refused') + # A shader that rewrites descriptor word 3 (s_mov_b32 s19, 0x50fac) after the load must not be translated + # with the table word: the formatted load is refused. + try: + gfx2hlsl.Pipeline(struct.pack('<8I', 0xf4080404, 0xfa000000, 0xbe9303ff, 0x50fac, 0xe0002000 | 2 << 18, 0x80040400, + 0xf80008cf, 0x07060504) + struct.pack('SetPipelineState(pipeline)', gate) + + +def runtime_gate_controls(): + source = RUNTIME.read_text(encoding='utf-8') + runtime_gate(source) + preflight = source[source.index('bool formatted_buffers_ready('):source.index('bool draw_translated(')] + for dropped in ('x2w_local::readable(', 'view_token_magic', 'formatted_buffer_supported('): + try: + runtime_gate(source.replace(preflight, preflight.replace(dropped, 'omitted'))) + except AssertionError: + continue + raise AssertionError('gate without %s must fail the control' % dropped) + start = source.index('bool draw_translated(') + gate = 'if (!have && formatted.entry)' + start_cmd = 'list->SetPipelineState(pipeline);' + late = source[:start] + source[start:].replace(gate, '', 1).replace(start_cmd, start_cmd + '\n' + gate, 1) + try: + runtime_gate(late) + except (AssertionError, ValueError): + pass + else: + raise AssertionError('gate after binding fallback or list commands must fail the control') + def compile_fetch(directory, compiler, name, source): hlsl, binary = directory / 'fetch.hlsl', directory / 'fetch.cso' @@ -248,14 +442,22 @@ def compile_fetch(directory, compiler, name, source): return binary -def run_reference(directory, consumer, adapter, binary, name, words): +def run_reference(directory, consumer, adapter, binary, name, words, translated=None, word3=None): case = directory / 'fetch.case' + translated = translated or pipeline(name) constants = [0] * 16 - constants[pipeline(name).uds.index(('stride', 0))] = FORMATS[name][1] + constants[translated.uds.index(('stride', 0))] = FORMATS[name][1] + if word3 is not None: + constants[translated.uds.index(('descword3', 0))] = word3 case.write_bytes(struct.pack('<337I', 1, *words, *constants)) return subprocess.run([consumer, adapter, '--compute-store-case', binary, case], capture_output=True, text=True) +def run(directory, compiler, consumer, adapter, name, source, words, translated=None, word3=None): + binary = compile_fetch(directory, compiler, name, source) + return run_reference(directory, consumer, adapter, binary, name, words, translated, word3) + + def check(directory, compiler, consumer, adapter): for name in FORMATS: source = pipeline(name).hlsl_vs() @@ -287,6 +489,50 @@ def check(directory, compiler, consumer, adapter): print('%s: mutation %r fails' % (name, label)) print('%s: %d buffer formats, 16 vertices each, every wrong reference and %d mutations fail' % (adapter, len(FORMATS), len(MUTATIONS))) + mubuf_runs = 0 + for label, name, word3, words in mubuf_cases(): + translated = pipeline_mubuf(FORMATS[name][2]) + source = translated.hlsl_vs() + result = run(directory, compiler, consumer, adapter, name, source, words, translated, word3) + if result.returncode: + raise RuntimeError('descriptor %s: %s%s' % (label, result.stdout, result.stderr)) + print('descriptor %s: %s' % (label, [l for l in result.stdout.splitlines() if 'mismatches=' in l][0])) + mubuf_runs += 1 + # The same translated body must fail when the descriptor word names another format, or when it is mutated. + name = 'BUF_FMT_32_32_32_32_FLOAT' + translated = pipeline_mubuf(FORMATS[name][2]) + source = translated.hlsl_vs() + for other in ('BUF_FMT_32_32_FLOAT', 'BUF_FMT_16_16_16_16_FLOAT'): + bad = run(directory, compiler, consumer, adapter, name, source, mubuf_expected(name, 3), translated, descriptor_word3(other)) + if bad.returncode != 1 or 'Compute readback differs' not in bad.stderr: + raise AssertionError('descriptor word of %s did not change the load\n%s' % (other, bad.stderr)) + for label, old, new in DESC_MUTATIONS: + for case_label, case_name, word3, words in mubuf_cases(): + if 'xyz' not in case_label and 'as' not in case_label and 'integer' not in case_label: + continue + translated = pipeline_mubuf(FORMATS[case_name][2]) + bad = run(directory, compiler, consumer, adapter, case_name, translated.hlsl_vs().replace(old, new), words, translated, word3) + if bad.returncode == 1 and 'Compute readback differs' in bad.stderr: + print('descriptor mutation %r fails on %s' % (label, case_label)) + break + else: + raise AssertionError('descriptor mutation %r escaped detection' % label) + for name, label, old, new in MUTATIONS: + translated = pipeline_mubuf(FORMATS[name][2]) + # The descriptor switch names its components c0..c3 where the tbuffer translation names v4..v7. + old, new = (re.sub(r'\bv([4-7]) =', lambda m: 'c%d =' % (int(m.group(1)) - 4), t) for t in (old, new)) + source = mutate_case(translated.hlsl_vs(), FORMATS[name][0], old, new) + # An xyz load never reads W, so a W-only mutation needs a word routing W into the third register. + for selects in ((4, 5, 6, 7), (4, 5, 7, 7)): + bad = run(directory, compiler, consumer, adapter, name, source, mubuf_expected(name, 3, selects), translated, + descriptor_word3(name, selects)) + if bad.returncode == 1 and 'Compute readback differs' in bad.stderr: + break + else: + raise AssertionError('%s: descriptor-path mutation %r escaped detection\n%s' % (name, label, bad.stderr)) + print('%s: descriptor-path mutation %r fails' % (name, label)) + print('%s: %d buffer_load_format descriptor cases, wrong descriptor words and %d mutations fail' + % (adapter, mubuf_runs, len(MUTATIONS) + len(DESC_MUTATIONS))) return 0 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fb5cd071e..086e8c59e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -152,6 +152,21 @@ def strip_header(code): 'BUF_FMT_32_FLOAT': (None, ['{0}.Load(a)', '0u', '0u', 'U(1.0)'])} +# gfx10 buffer-descriptor FORMAT field (word 3, bits 12..18) for each FETCH_FORMATS entry: the same unified +# numbers as the tbuffer `format:` operand (tools/disasm_rdna2.py MTBUF_FORMATS; 1 is the omitted default). +# A MUBUF buffer_load_format_* has no format operand, so its translation switches on this field at run time. +# A FORMAT the draw should have refused reaches the switch default: every component becomes this NaN pattern +# (never a finite zero), so a missed validation shows in the readback instead of passing as black. +DESC_FORMAT_UNKNOWN = 0x7fc0f0f0 +DESC_FORMAT_CODES = { + 'BUF_FMT_8_UNORM': 1, 'BUF_FMT_8_UINT': 5, 'BUF_FMT_8_8_UNORM': 14, 'BUF_FMT_32_FLOAT': 22, + 'BUF_FMT_16_16_UNORM': 23, 'BUF_FMT_16_16_SNORM': 24, 'BUF_FMT_16_16_UINT': 27, 'BUF_FMT_16_16_FLOAT': 29, 'BUF_FMT_8_8_8_8_UNORM': 56, 'BUF_FMT_8_8_8_8_UINT': 60, + 'BUF_FMT_32_32_FLOAT': 64, 'BUF_FMT_16_16_16_16_FLOAT': 71, 'BUF_FMT_32_32_32_FLOAT': 74, + 'BUF_FMT_32_32_32_32_FLOAT': 77} +DESC_FORMAT_SHIFT, DESC_FORMAT_MASK = 12, 127 +# Integer formats read a DST_SEL constant 1 as the integer 1, every other format as 1.0. +DESC_ONE_INTEGER = ('BUF_FMT_8_UINT', 'BUF_FMT_8_8_8_8_UINT') + def starts_with_fetch_call(code): return len(code) >= 4 and struct.unpack_from(' uniform HLSL expression over scalars that defined it self.since_join = None # SGPRs proven uniform since the last branch target (None: none reached) self.defined_uniform_s = set(init_entry_uniform) @@ -1679,12 +1699,14 @@ def translate(self): start = 0 raised_unsupported = None - for off, n, name, asm in self.ins: + for instruction_index, (off, n, name, asm) in enumerate(self.ins): if off in targets and off != start: self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, None)) self.lines, start = [], off + self.descriptor_block_first = instruction_index self.pc = off + self.descriptor_instruction_index = instruction_index self.scc_effect = None # Before the first branch target or terminator every path has run exactly the instructions above, so # the program-order tracking is exact there even in a program with branches. Code after s_endpgm in a @@ -1791,6 +1813,7 @@ def translate(self): self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, term)) self.lines, start = [], off + n + self.descriptor_block_first = instruction_index + 1 new_bad = self.bad_sgprs - force_unproven new_at = {k: v - force_at.get(k, set()) for k, v in bad_at_target.items() if v - force_at.get(k, set())} @@ -2161,10 +2184,8 @@ def lower(self, base, asm, ops, mods): return self.set_v(reg_range(ops[0])[1], text.format(*args)) if base in SCA: return self.scalar(base, ops) - if base in ('buffer_load_format_x', 'buffer_load_format_xy', - 'buffer_load_format_xyz', 'buffer_load_format_xyzw'): - # MUBUF formatted loads take both fields from V# word 3. The startup request carries - # the root signature layout, while the descriptor table is supplied at draw time. + if base == 'buffer_load_format_xyzw': + # Not translated: the four-component form has no startup request that needs it yet. raise Unsupported('%s requires descriptor FORMAT and DST_SEL' % base) raise Unsupported(base) @@ -3143,6 +3164,128 @@ def op_s_swappc_b64(self, ops, mods): self.load_format(FETCH_DXGI[e['format']][0], buf, e['vgpr'], e['count']) self.fetched = True + @staticmethod + def descriptor_scalar_writes(name, ops): + regs = set() + for token in destinations(name, ops): + if token in ('vcc', 'vcc_lo', 'vcc_hi'): + regs.update((106, 107)) + parsed = reg_range(token) + if parsed and parsed[0] == 's': + regs.update(range(parsed[1], parsed[2] + 1)) + if name.startswith('v_cmp') and len(ops) == 2: + regs.update((106, 107)) + return regs + + def formatted_pointer_reaches(self, pointer, before): + """Refuse a write to the original root pointer on any predecessor path of this read.""" + if not hasattr(self, 'descriptor_predecessors'): + by_offset = {off: i for i, (off, *_rest) in enumerate(self.ins)} + self.descriptor_predecessors = [[] for _ in self.ins] + self.descriptor_writes_by_instruction = [] + for index, (_, _, name, asm) in enumerate(self.ins): + _, args, _ = parse(asm) + self.descriptor_writes_by_instruction.append(self.descriptor_scalar_writes(name, args)) + if index + 1 < len(self.ins) and name not in ('s_branch', 's_endpgm'): + self.descriptor_predecessors[index + 1].append(index) + if name == 's_branch' or name.startswith('s_cbranch_'): + target = by_offset.get(int(args[0].split('_')[1], 16)) + if target is not None: + self.descriptor_predecessors[target].append(index) + seen = set() + pending = list(self.descriptor_predecessors[before]) + while pending: + earlier = pending.pop() + if earlier in seen: + continue + seen.add(earlier) + if pointer in self.descriptor_writes_by_instruction[earlier]: + return False + pending.extend(self.descriptor_predecessors[earlier]) + return True + + def formatted_descriptor_from_block(self, reg, first): + """Require one untouched local load and a table pointer that no incoming path can rewrite.""" + start, end = self.descriptor_block_first, self.descriptor_instruction_index + block = self.ins[start:end] + words = set(range(reg[1], reg[2] + 1)) + for index in range(len(block) - 1, -1, -1): + _, _, name, asm = block[index] + _, args, _ = parse(asm) + if not (self.descriptor_scalar_writes(name, args) & words): + continue + m = re.fullmatch(r's_load_dwordx(4|8|16)', name) + load = reg_range(args[0]) + if not m or not load or load[1] + first[3] != reg[1] or int(m.group(1)) < first[3] + 4: + return False + base = reg_range(args[1]) + if not base or base[0] != 's': + return False + pointer = base[1] + read = start + index + for previous in range(index - 1, -1, -1): + _, _, earlier, prior = block[previous] + _, src, _ = parse(prior) + if pointer not in self.descriptor_scalar_writes(earlier, src): + continue + copied_from = reg_range(src[1]) if earlier == 's_mov_b32' and len(src) == 2 else None + if not copied_from or copied_from[0] != 's' or copied_from[1] != copied_from[2]: + return False + pointer = copied_from[1] + read = start + previous + break + return self.entry_table_pointers.get(pointer) == first[1] and self.formatted_pointer_reaches(pointer, read) + return False + + def mubuf_format(self, ops, mods, count): + """buffer_load_format_x/xy/xyz: FORMAT and DST_SEL come from word 3 of the descriptor, known at draw time. + + The runtime passes that word as an entry constant. Each supported format becomes one case of a switch + on the FORMAT field that decodes the four components as the tbuffer path does; DST_SEL then picks, for + each destination register, a component or the constant 0 or 1. The draw validates FORMAT and descriptor + availability before submission, so the generated switch only sees the supported cases. + """ + if self.kind not in ('vs', 'ps'): + raise Unsupported('formatted buffer load requires a graphics draw') + dst = reg_range(ops[0]) + buf, address = self.buffer_address(ops, mods) + # FORMAT and DST_SEL are read from the table word, so word 3 must still be the loaded one. + r = reg_range(ops[2]) + first = self.sym.get(r[1]) if r else None + if not r or r[2] - r[1] != 3 or not first or first[0] != 'desc' or any( + self.sym.get(r[1] + i) != ('desc', first[1], first[2], first[3] + i) for i in range(4)): + raise Unsupported('formatted buffer load through a descriptor whose words were rewritten') + if first[1][0] != 'table': + raise Unsupported('formatted buffer load requires a hardware table descriptor') + if self.past_entry and not self.formatted_descriptor_from_block(r, first): + raise Unsupported('formatted buffer load requires descriptor words proven in the entry block or a local table load') + word3 = 'ud%d' % self.pipe.ud(('descword3', self.pipe.resources[self.descriptor(ops[2])]['index'])) + self.emit('a = %s;' % address) + self.emit('{ uint c0 = 0, c1 = 0, c2 = 0, c3 = 0, one = U(1.0);') + self.emit('switch ((%s >> %d) & %du) {' % (word3, DESC_FORMAT_SHIFT, DESC_FORMAT_MASK)) + for fmt, code in sorted(DESC_FORMAT_CODES.items(), key=lambda kv: kv[1]): + load, comps = FETCH_FORMATS[fmt] + body = ['w = %s;' % load.format(buf)] if load else [] + body += ['c%d = %s;' % (i, comps[i].format(buf)) for i in range(4)] + if fmt in DESC_ONE_INTEGER: + body.append('one = 1u;') + self.emit('case %du: %s break;' % (code, ' '.join(body))) + self.emit('default: c0 = c1 = c2 = c3 = %du; break; }' % DESC_FORMAT_UNKNOWN) + pick = ('((%s >> %d) & 7u)' % (word3, 3 * i) for i in range(count)) + for i, sel in enumerate(pick): + self.set_v(dst[1] + i, '%s == 4u ? c0 : %s == 5u ? c1 : %s == 6u ? c2 : %s == 7u ? c3 : %s == 1u ? one : 0u' + % (sel, sel, sel, sel, sel)) + self.emit('}') + + def op_buffer_load_format_x(self, ops, mods): + self.mubuf_format(ops, mods, 1) + + def op_buffer_load_format_xy(self, ops, mods): + self.mubuf_format(ops, mods, 2) + + def op_buffer_load_format_xyz(self, ops, mods): + self.mubuf_format(ops, mods, 3) + def op_tbuffer_load_format_x(self, ops, mods): self.tbuffer(ops, mods, 1) From 2d275db18f92e45c80ebc6c47bf76da3594dadac Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:36:58 +0100 Subject: [PATCH 033/232] startup: implement command-list slots 53-55 ClearUAV and Discard (Part of #870) (#1972) * d3d12_xs: record list slots 53/54/55 (ClearUAV uint/float, DiscardResource) Part of #870. Slots 53 and 54 clear a UAV through its shadow record (CPU handle) with the GPU handle checked against known heaps; slot 55 discards render, depth and UAV resources and drops other resources. Refusals are logged and counted. Adds startup_clear_uav (WARP + hardware readback). * d3d12_xs: bind owning heap for UAV clears, honour non-COMMON initial state, count debug errors via callback * test: run clear/readback checks when no debug layer callback exists --- CMakeLists.txt | 10 + src/startup_stubs/d3d12_xs_device.cpp | 96 +++++++++ tests/startup_clear_uav.cpp | 272 ++++++++++++++++++++++++++ 3 files changed, 378 insertions(+) create mode 100644 tests/startup_clear_uav.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 62c52a9e9..70e01ce88 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1361,6 +1361,16 @@ foreach(mutation IN ITEMS overflow typeless samples) set_tests_properties(startup_list_copy_validation_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +# List slots 53/54/55: ClearUnorderedAccessViewUint/Float and DiscardResource, read back on the desktop device. +add_executable(startup_clear_uav tests/startup_clear_uav.cpp) +target_compile_features(startup_clear_uav PRIVATE cxx_std_17) +target_link_libraries(startup_clear_uav PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_clear_uav_${backend} COMMAND startup_clear_uav ${backend}) + set_tests_properties(startup_clear_uav_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() + add_executable(startup_nv12_draw tests/startup_nv12_draw.cpp tests/desktop_gpu.cpp) target_compile_features(startup_nv12_draw PRIVATE cxx_std_17) target_include_directories(startup_nv12_draw PRIVATE src) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0582b5953..f7783c7a3 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2905,6 +2905,99 @@ void __stdcall list_clear_target(Wrapper* self, u64 handle, const float* colour, red_producers().after(self, red_sample); InterlockedIncrement(&render_clears); } +// The desktop shader-visible CBV/SRV/UAV heap that owns the GPU handle's descriptor, or null. +ID3D12DescriptorHeap* owning_view_heap(u64 gpu) +{ + u64 owner = 0; + AcquireSRWLockShared(¬e_lock); + for (const HeapInfo& heap : heap_infos()) { + if (heap.type != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV || !heap.desktop_gpu || gpu < heap.desktop_gpu) continue; + const u64 offset = gpu - heap.desktop_gpu; + if (heap.increment && offset < u64{heap.count} * heap.increment && offset % heap.increment == 0) { + owner = heap.wrapper; + break; + } + } + ReleaseSRWLockShared(¬e_lock); + return owner ? reinterpret_cast(unwrap(owner)) : nullptr; +} +// require_state assumes a resource starts in COMMON; a placed buffer made with another initial state does not. +bool tracked_from_common(u64 title_resource) +{ + const ResourceInfo* info = resource_info(as_wrapper(reinterpret_cast(title_resource))); + return !info || info->initial_state == D3D12_RESOURCE_STATE_COMMON; +} +// List slots 53 and 54 (desktop 49/50 + 4), ClearUnorderedAccessViewUint/Float(view GPU handle, view CPU +// handle, resource, values, rect count, rects). The CPU handle is read from its shadow record, like the +// render-target clear, so a copied descriptor clears the resource it holds now. A GPU handle that is on no +// known heap (its owning heap is bound for the clear and the translated-heap cache is reset), a resource not +// tracked from COMMON, a CPU handle that holds no unordered-access view, or a resource without unordered access is +// refused (logged, counted) instead of reaching the desktop list. The target moves to UNORDERED_ACCESS +// around the clear. +template +void __stdcall list_clear_uav(Wrapper* self, u64 gpu_handle, u64 cpu_handle, u64 title_resource, const void* values, + UINT rect_count, const D3D12_RECT* rects) +{ + if (!self->own().list_open) return; + static LONG logged, refused; + const char* name = Float ? "ClearUnorderedAccessViewFloat" : "ClearUnorderedAccessViewUint"; + const u64 desktop = desktop_cpu_handle(cpu_handle); + const ResolvedView view = desktop ? resolve_view(desktop, 19) : ResolvedView{}; + ID3D12Resource* target = view.resource; + ID3D12DescriptorHeap* view_heap = nullptr; + const char* why = nullptr; + if (!x2w_local::readable(values, 4 * sizeof(UINT))) why = "no clear values"; + else if (rect_count && !x2w_local::readable(rects, std::size_t{rect_count} * sizeof(D3D12_RECT))) why = "unreadable rects"; + else if (!target) why = view.wrong_kind ? "view is not an unordered-access view" + : view.skipped ? "view was skipped at creation" : "view holds no known resource"; + else if (!(view_heap = owning_view_heap(gpu_handle))) why = "GPU handle is on no known descriptor heap"; + else if (!(target->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) why = "resource lacks unordered access"; + else if (!tracked_from_common(title_resource)) why = "resource does not use COMMON state tracking"; + if (why) { + InterlockedIncrement(&render_target_unresolved); + if (first_calls(refused, 6)) log("x2w-d3d12 %s skipped: %s (view 0x%llx)", name, why, cpu_handle); + return; + } + if (first_calls(logged, 4)) log("x2w-render %s view=0x%llx target=%p rects=%u", name, cpu_handle, static_cast(target), rect_count); + auto* list = static_cast(self->own().real); + require_state(self, target, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + // The clear needs the GPU descriptor's own heap bound; the next translated draw binds its heaps again. + ID3D12DescriptorHeap* bound[] = {view_heap}; + list->SetDescriptorHeaps(1, bound); + pass_of(self).heap_set = false; + const D3D12_GPU_DESCRIPTOR_HANDLE gpu{gpu_handle}; + const D3D12_CPU_DESCRIPTOR_HANDLE cpu{static_cast(desktop)}; + if (Float) list->ClearUnorderedAccessViewFloat(gpu, cpu, target, static_cast(values), rect_count, rect_count ? rects : nullptr); + else list->ClearUnorderedAccessViewUint(gpu, cpu, target, static_cast(values), rect_count, rect_count ? rects : nullptr); + InterlockedIncrement(&render_clears); +} +// List slot 55 (desktop 51 + 4), DiscardResource(resource, region). Discard is only a hint, so a resource +// that is not a render target, depth target or unordered-access resource (needs a state the list does not +// track), an unreadable region or a region with unreadable rects is dropped; nothing reaches the desktop list. +void __stdcall list_discard(Wrapper* self, u64 title_resource, const D3D12_DISCARD_REGION* region) +{ + auto* list = recording(self); + if (!list || !title_resource) return; + auto* resource = reinterpret_cast(unwrap(title_resource)); + if (!resource) return; + D3D12_DISCARD_REGION safe{}; + if (region) { + if (!x2w_local::readable(region, sizeof(*region))) return; + safe = *region; + if (safe.NumRects && !x2w_local::readable(safe.pRects, std::size_t{safe.NumRects} * sizeof(D3D12_RECT))) return; + } + if (!tracked_from_common(title_resource)) return; + const D3D12_RESOURCE_FLAGS flags = resource->GetDesc().Flags; + D3D12_RESOURCE_STATES state; + if (flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) state = D3D12_RESOURCE_STATE_RENDER_TARGET; + else if (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) state = D3D12_RESOURCE_STATE_DEPTH_WRITE; + else if (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + else return; + require_state(self, resource, state); + list->DiscardResource(resource, region ? &safe : nullptr); + static LONG logged; + if (first_calls(logged, 4)) log("x2w-render DiscardResource resource=%p rects=%u", static_cast(resource), region ? safe.NumRects : 0); +} // List slot 50 (desktop 46 + 4), OMSetRenderTargets(count, handles, single range, depth). // With single_range the title passes the first handle only and the rest follow it at the title's own // descriptor stride (also for one target). A descriptor of the wrong kind, a handle that holds no view, a @@ -4789,6 +4882,9 @@ void build_tables() list_typed[15] = reinterpret_cast(&list_copy_buffer_region); list_typed[17] = reinterpret_cast(&list_copy_resource); list_typed[19] = reinterpret_cast(&list_resolve_subresource); + list_typed[53] = reinterpret_cast(&list_clear_uav); + list_typed[54] = reinterpret_cast(&list_clear_uav); + list_typed[55] = reinterpret_cast(&list_discard); list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); diff --git a/tests/startup_clear_uav.cpp b/tests/startup_clear_uav.cpp new file mode 100644 index 000000000..2367e5250 --- /dev/null +++ b/tests/startup_clear_uav.cpp @@ -0,0 +1,272 @@ +// ClearUnorderedAccessViewUint / ClearUnorderedAccessViewFloat / DiscardResource on a console command list +// (list slots 53, 54 and 55, device slot 19). +// +// startup_clear_uav (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe makes 1x1 targets with unordered access and records, on one list: +// +// A R32_UINT ClearUnorderedAccessViewUint(0x12345678) read back: 12345678 +// B R32_UINT cleared 0x11111111, then a clear with a GPU handle on no heap (refused, counted) +// read back: 11111111 +// C R32_FLOAT ClearUnorderedAccessViewFloat(1.5) read back: 3fc00000 +// D R32_UINT a clear through a CPU handle that holds no view (refused, counted) +// E RGBA8 RTV DiscardResource, with and without a region list closes and executes +// +// The shader-visible heap holds the GPU-side descriptors, a second heap holds the CPU-side copies the +// desktop API requires. The desktop device must not be removed and the debug layer must store no errors. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_render_target_stats(unsigned* binds, unsigned* unresolved); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0, Word g = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f, g); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +unsigned unresolved_now() +{ + unsigned binds = 0, unresolved = 0; + x2w_d3d12_render_target_stats(&binds, &unresolved); + return unresolved; +} + +std::atomic debug_error_count{0}; +void WINAPI on_message(D3D12_MESSAGE_CATEGORY, D3D12_MESSAGE_SEVERITY severity, D3D12_MESSAGE_ID, LPCSTR text, void*) +{ + if (severity > D3D12_MESSAGE_SEVERITY_ERROR) return; + if (++debug_error_count <= 12) std::printf("debug layer: %.300s\n", text); +} + +struct Probe { + ComPtr desktop; + ComPtr readback; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + void* queue = nullptr; + void* fence = nullptr; + Word fence_value = 0; + + bool submit(void* list) + { + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_value))) return false; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; + } + // Cumulative error count from a message callback registered before any recording; the shim drains the + // stored queue at every submit, so the stored messages alone would miss the recording errors. + DWORD cookie = 0; + ComPtr queue1; + bool watch() + { + return SUCCEEDED(desktop.As(&queue1)) && + SUCCEEDED(queue1->RegisterMessageCallback(on_message, D3D12_MESSAGE_CALLBACK_FLAG_NONE, nullptr, &cookie)); + } + // The one texel of a target (4 bytes), copied on a desktop queue. + std::uint32_t texel(ID3D12Resource* target) + { + D3D12_COMMAND_QUEUE_DESC desc{}; + ComPtr observer; + ComPtr allocator; + ComPtr copy; + ComPtr done; + if (FAILED(desktop->CreateCommandQueue(&desc, IID_PPV_ARGS(&observer))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(©))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))) + return 0; + D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + copy->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + if (FAILED(copy->Close())) return 0; + ID3D12CommandList* lists[] = {copy.Get()}; + observer->ExecuteCommandLists(1, lists); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool finished = event && SUCCEEDED(observer->Signal(done.Get(), 1)) && + SUCCEEDED(done->SetEventOnCompletion(1, event)) && WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + void* memory = nullptr; + if (!finished || FAILED(readback->Map(0, nullptr, &memory))) return 0; + std::uint32_t bits = 0; + std::memcpy(&bits, memory, sizeof(bits)); + readback->Unmap(0, nullptr); + return bits; + } +}; + +bool check_count(const char* name, unsigned& before, unsigned expected_added) +{ + const unsigned now = unresolved_now(); + const bool good = now - before == expected_added; + std::printf("%s: refused +%u (expected +%u)\n", name, now - before, expected_added); + before = now; + return good; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + Probe probe; + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe.desktop)))) return 4; + + // Without the debug layer (no Graphics Tools) the error count stays 0; the clear and readback checks still run. + if (!probe.watch()) std::printf("no debug layer message callback: validation not counted\n"); + + // Five 1x1 targets: four with unordered access (A, B, C, D) and one render target (E). + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto texture = [](DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) { + return D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, format, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, flags}; + }; + const D3D12_RESOURCE_DESC uint_desc = texture(DXGI_FORMAT_R32_UINT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const D3D12_RESOURCE_DESC float_desc = texture(DXGI_FORMAT_R32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const D3D12_RESOURCE_DESC rt_desc = texture(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + const D3D12_CLEAR_VALUE rt_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + ComPtr a, b, c, d, e; + const auto make = [&](const D3D12_RESOURCE_DESC& desc, ComPtr& out, const D3D12_CLEAR_VALUE* clear) { + return SUCCEEDED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + clear, IID_PPV_ARGS(&out))); + }; + if (!make(uint_desc, a, nullptr) || !make(uint_desc, b, nullptr) || !make(float_desc, c, nullptr) || + !make(uint_desc, d, nullptr) || !make(rt_desc, e, &rt_clear)) + return 5; + UINT64 bytes = 0; + probe.desktop->GetCopyableFootprints(&uint_desc, 0, 1, 0, &probe.footprint, nullptr, nullptr, &bytes); + heap.Type = D3D12_HEAP_TYPE_READBACK; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&probe.readback)))) return 5; + + // Heaps: the shader-visible one is read by GPU handle, the plain one by CPU handle. Index 3 of the plain + // heap is left empty. Both hold a UAV for A, B and C at the same indexes. + const auto make_heap = [&](D3D12_DESCRIPTOR_HEAP_FLAGS flags, void** out) { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 4, flags}, 0, 0}; + return ok(invoke(device, 14, arg(&desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(out))); + }; + void *visible_heap = nullptr, *plain_heap = nullptr; + if (!make_heap(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, &visible_heap) || !make_heap(D3D12_DESCRIPTOR_HEAP_FLAG_NONE, &plain_heap)) + return 6; + const UINT stride = probe.desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const Word visible_cpu = invoke(visible_heap, 9), plain_cpu = invoke(plain_heap, 9), gpu_start = invoke(visible_heap, 10); + D3D12_UNORDERED_ACCESS_VIEW_DESC uint_view{DXGI_FORMAT_R32_UINT, D3D12_UAV_DIMENSION_TEXTURE2D, {}}; + D3D12_UNORDERED_ACCESS_VIEW_DESC float_view{DXGI_FORMAT_R32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D, {}}; + ID3D12Resource* views[] = {a.Get(), b.Get(), c.Get()}; + D3D12_UNORDERED_ACCESS_VIEW_DESC* view_descs[] = {&uint_view, &uint_view, &float_view}; + for (unsigned i = 0; i < 3; ++i) { + invoke(device, 19, arg(views[i]), 0, arg(view_descs[i]), visible_cpu + i * stride); + invoke(device, 19, arg(views[i]), 0, arg(view_descs[i]), plain_cpu + i * stride); + } + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&probe.queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&probe.fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + if (!ok(invoke(list, 139, arg(allocator), 0))) return 8; + void* heaps[] = {visible_heap}; + invoke(list, 32, 1, arg(heaps)); + + const std::uint32_t uint_a[4] = {0x12345678, 0x12345678, 0x12345678, 0x12345678}; + const std::uint32_t uint_b1[4] = {0x11111111, 0x11111111, 0x11111111, 0x11111111}; + const std::uint32_t uint_b2[4] = {0x0badf00d, 0x0badf00d, 0x0badf00d, 0x0badf00d}; + const float float_c[4] = {1.5f, 1.5f, 1.5f, 1.5f}; + const D3D12_RECT whole{0, 0, 1, 1}; + + unsigned seen = unresolved_now(); + invoke(list, 53, gpu_start, plain_cpu, arg(a.Get()), arg(uint_a), 0, 0); + if (!check_count("1 uint clear of A", seen, 0)) return 10; + invoke(list, 53, gpu_start + stride, plain_cpu + stride, arg(b.Get()), arg(uint_b1), 1, arg(&whole)); + if (!check_count("2 uint clear of B with a rect", seen, 0)) return 11; + invoke(list, 54, gpu_start + 2 * stride, plain_cpu + 2 * stride, arg(c.Get()), arg(float_c), 0, 0); + if (!check_count("3 float clear of C", seen, 0)) return 12; + // The GPU handle is far past the four-descriptor heap: no known heap holds it. + invoke(list, 53, gpu_start + 64 * stride, plain_cpu + stride, arg(b.Get()), arg(uint_b2), 0, 0); + if (!check_count("4 clear of B through a GPU handle on no heap", seen, 1)) return 13; + invoke(list, 53, gpu_start + 3 * stride, plain_cpu + 3 * stride, arg(d.Get()), arg(uint_b2), 0, 0); + if (!check_count("5 clear through a CPU handle holding no view", seen, 1)) return 14; + invoke(list, 53, gpu_start, plain_cpu, arg(a.Get()), 0, 0, 0); + if (!check_count("6 clear with no values", seen, 1)) return 15; + + const D3D12_DISCARD_REGION region{1, &whole, 0, 1}; + invoke(list, 55, arg(e.Get()), 0); + invoke(list, 55, arg(e.Get()), arg(®ion)); + invoke(list, 55, 0, 0); + if (!check_count("7 discards of the render target", seen, 0)) return 16; + + invoke(list, 9); + if (!probe.submit(list)) return 17; + const std::uint32_t bits_a = probe.texel(a.Get()); + const std::uint32_t bits_b = probe.texel(b.Get()); + const std::uint32_t bits_c = probe.texel(c.Get()); + std::printf("8 A after the uint clear: %08x (expected 12345678)\n", bits_a); + std::printf("9 B after the refused clear: %08x (expected 11111111)\n", bits_b); + std::printf("10 C after the float clear: %08x (expected 3fc00000)\n", bits_c); + if (bits_a != 0x12345678) return 18; + if (bits_b != 0x11111111) return 19; + if (bits_c != 0x3fc00000) return 20; + + const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); + const unsigned long long errors = debug_error_count.load(); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} From afd02a24689dfc4643756f1fb39efbf526e71ed6 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 22:37:54 +0800 Subject: [PATCH 034/232] gpu: bind both XMem inputs for a cached indirect mesh draw (#2377) * gpu: bind both XMem inputs for a cached indirect mesh draw * tests: distinguish initialization from GPU mesh group emission --- CMakeLists.txt | 2 +- README.md | 1 + docs/experiments.md | 27 +++ src/startup_stubs/d3d12_xs_device.cpp | 29 ++- src/startup_stubs/mesh_xmem_handoff.inl | 269 ++++++++++++++------- tests/startup_indirect_draw_indexed.cpp | 50 +++- tests/startup_indirect_mesh_cache_check.py | 22 +- tests/startup_indirect_mesh_lease.inl | 193 ++++++++++++--- tests/xmem_mesh_root_srv.hlsl | 21 ++ tools/startup/mesh86_cache.py | 2 +- 10 files changed, 477 insertions(+), 139 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 70e01ce88..6be597835 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1423,7 +1423,7 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend}) set_tests_properties(startup_indirect_mesh_cache_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) - foreach(mode IN ITEMS ordered_control skip-wait) + foreach(mode IN ITEMS ordered_control skip-wait dual dual-skip-srv dual-skip-argument dual-init-only) set(test_name startup_indirect_mesh_lease_${backend}_${mode}) add_test(NAME ${test_name} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" diff --git a/README.md b/README.md index fa578e8dc..b26f710bb 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | [Publish RGBA8 textures from completed archive records](docs/experiments.md#publishing-a-texture-from-each-complete-archive-record) | `ctest --preset release --no-tests=error -R '^cpu_archive_texture_publication$' -V` | | [Draw each archive record through D3D12](docs/experiments.md#drawing-each-archive-record-through-d3d12) | `ctest --preset dev --no-tests=error -R '^cpu_archive_texture_gpu_warp$' -V` | | Indexed mesh draw on WARP | `ctest --preset dev --no-tests=error -R '^mesh_indexed_draw_warp$' -V` | +| [Cached mesh draw with two queue writers](docs/experiments.md#cached-mesh-draw-with-two-queue-writers) | `ctest --preset release --no-tests=error -R '^startup_indirect_mesh_lease_(warp\|hardware)_dual' -V` | | [Amplification plus mesh pipeline on WARP](docs/experiments.md#amplification-and-mesh-pipeline-forms) | `ctest --preset dev --no-tests=error -R '^mesh_amplified_draw_warp$' -V` | | Textured mesh fallback at Shader Model 6.0 | `ctest --preset dev --no-tests=error -R '^mesh_textured_fallback_' -V` | | GPU-produced texture through the SM 6.0 mesh fallback | `ctest --preset dev --no-tests=error -R '^compute_mesh_texture_fallback_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 64002f121..6e479d93c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8856,6 +8856,33 @@ cmake --build --preset release --target startup_indirect_draw_indexed xmem_shim ctest --preset release --no-tests=error -j1 -R '^startup_indirect_mesh_xmem_arguments' -V ``` +#### Cached mesh draw with two queue writers + +With both `X2W_MESH86_XMEM_SRV=1` and `X2W_MESH_INDIRECT_XMEM=1`, a cached +slot 86 mesh pipeline can consume a root SRV word written on COPY and a +12-byte DispatchMesh record written on COMPUTE in the same DIRECT command. +Each producer publishes its own range through slot 15. The two buffers must +occupy distinct physical page windows. The consumer verifies both placements, +pages and ranges before recording the draw and again before submission. +Both leases remain pinned until the consumer fence completes. + +The source-built fixture uses the root word for colour and the dispatch group +count for horizontal coverage. A compute dispatch initializes the argument +record to `{0,1,1,0}`. After a UAV barrier, a second dispatch atomically +increments X twice. A queue copy publishes its first 12 bytes. Omitting +the increments leaves X at zero and all eight pixels clear, with both +producer waits enabled and both guard words intact. +On Windows 11 build 26200.9974, RTX 4060 Laptop +(32.0.16.1656) and WARP both returned eight red pixels. Omitting only the SRV +wait gave eight green pixels. Omitting only the argument wait gave four red +pixels and four clear pixels. Replacing the argument page between recording +and submission left the entire target clear. Restoring the page restored the +draw. Both adapters ran with the D3D12 debug layer enabled. + +```powershell +ctest --preset release --no-tests=error -j1 -R '^startup_indirect_mesh_lease_(warp|hardware)_dual' -V +``` + A decoded indirect mesh command can publish a fixed slot 57 pipeline as a separate translation request. The descriptor must have a mesh program, an empty vertex slot, and a recorded root signature that matches the bound diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f7783c7a3..5130f0f3c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2720,6 +2720,23 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, ID3D12Resource* scratch = nullptr; ID3D12Resource* draw_arguments = resource; u64 draw_offset = offset; + const UINT mesh_srv = mesh && pass.indirect_graphics.cached_mesh ? pass.indirect_graphics.cached_srv_root : UINT_MAX; + const bool leased_arguments = mesh && mesh_xmem_indirect() && info->placement == Placement::copied_buffer && + (!pass.indirect_graphics.cached_mesh || mesh_srv != UINT_MAX); + MeshXMemRead inputs[2]{}; + size_t input_count = 0; + if (mesh_srv != UINT_MAX) + inputs[input_count++] = {pass.root_address[mesh_srv], sizeof(UINT), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE}; + if (leased_arguments) + inputs[input_count++] = {base + offset, bytes, argument_state}; + if (input_count) { + if (const char* failure = record_mesh_xmem_reads(self, inputs, input_count)) + return refuse(failure, mesh_srv != UINT_MAX ? indirect_graphics_pipeline : indirect_other); + if (leased_arguments) { + draw_arguments = inputs[input_count - 1].resource; + draw_offset = inputs[input_count - 1].offset; + } + } if (rect_list) { if (std::any_of(pass.desktop_compute_upload_srvs.begin(), pass.desktop_compute_upload_srvs.end(), [](u64 address) { return address != 0; })) @@ -2742,10 +2759,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, list->SetGraphicsRootSignature(pass.graphics_root); if (pass.indirect_graphics.cached_mesh) { const UINT srv = pass.indirect_graphics.cached_srv_root; - if (srv != UINT_MAX) { - if (const char* failure = bind_mesh_xmem_srv(self, srv, pass.root_address[srv])) - return refuse(failure, indirect_graphics_pipeline); - } + if (srv != UINT_MAX) + list->SetGraphicsRootShaderResourceView(srv, inputs[0].resource->GetGPUVirtualAddress() + inputs[0].offset); for (UINT i = 0; i < pass.root->size(); ++i) { if (i == srv) continue; list->SetGraphicsRoot32BitConstants(i, (*pass.root)[i].constants_count, pass.constants[i], 0); @@ -2770,11 +2785,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, counts = static_cast(count_wrapper->own().real); if (counts != resource) require_state(self, counts, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); } - if (mesh && !pass.indirect_graphics.cached_mesh && mesh_xmem_indirect() && - info->placement == Placement::copied_buffer) { - if (const char* failure = record_mesh_xmem_read(self, base + offset, bytes, argument_state, draw_arguments, draw_offset)) - return refuse(failure); - } else if (!rect_list) { + if (!leased_arguments && !rect_list) { require_state(self, resource, argument_state); } const auto red_samples = graphics ? red_producer_draw_before(self, list, "indirect-draw", 0) : RedDrawSamples{}; diff --git a/src/startup_stubs/mesh_xmem_handoff.inl b/src/startup_stubs/mesh_xmem_handoff.inl index 72a20c5fe..ce80f92c9 100644 --- a/src/startup_stubs/mesh_xmem_handoff.inl +++ b/src/startup_stubs/mesh_xmem_handoff.inl @@ -51,18 +51,28 @@ struct MeshXMemLease { struct MeshXMemRecording { struct Write { Wrapper* owner; u64 offset, bytes; bool leased; }; + struct Read { + std::shared_ptr lease; + u64 address{}; + }; std::vector writes; - std::shared_ptr reader, writer; - u64 reader_address{}; + std::array readers; + std::array, 2> writers; }; struct MeshXMemFlight { std::shared_ptr lease; x2w_startup::ComPtr completion; }; +struct MeshXMemPublication { + std::weak_ptr active; + std::shared_ptr ready; +}; + std::mutex mesh_xmem_mutex; -std::weak_ptr active_mesh_lease; -std::shared_ptr published_mesh_lease; +// The root word and the dispatch record each have one active lease. +constexpr size_t mesh_xmem_srv_index = 0, mesh_xmem_argument_index = 1; +std::array mesh_xmem_publications; std::unordered_map mesh_xmem_recordings; std::vector mesh_xmem_flights; bool mesh_xmem_tracking_failed; @@ -111,8 +121,8 @@ void drop_mesh_lease_owner(Wrapper* w) { if (!mesh_xmem_tracking()) return; const std::lock_guard lock(mesh_xmem_mutex); - if (published_mesh_lease && published_mesh_lease->owner == w) - published_mesh_lease.reset(); + for (auto& publication : mesh_xmem_publications) + if (publication.ready && publication.ready->owner == w) publication.ready.reset(); reap_mesh_xmem_flights(); } @@ -124,8 +134,18 @@ void discard_mesh_lease_recording(ID3D12CommandList* list) reap_mesh_xmem_flights(); } +bool mesh_xmem_windows_disjoint(const X2WXMemSectionLease& one, const X2WXMemSectionLease& other) +{ + if (one.section_offset + one.window_bytes <= other.section_offset || + other.section_offset + other.window_bytes <= one.section_offset) return true; + using Compare = BOOL (WINAPI*)(HANDLE, HANDLE); + static const auto compare = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"kernelbase.dll"), "CompareObjectHandles")); + return compare && !compare(one.section, other.section); +} + std::shared_ptr open_mesh_xmem_lease(Wrapper* device, Wrapper* owner, - u64 offset, u64 address, u64 bytes) + u64 offset, u64 address, u64 bytes, const MeshXMemLease* other) { using Pin = BOOL (WINAPI*)(UINT, ULONG_PTR, SIZE_T, X2WXMemSectionLease*, SIZE_T); HMODULE xmem = nullptr; @@ -156,10 +176,12 @@ std::shared_ptr open_mesh_xmem_lease(Wrapper* device, Wrapper* ow result->match = match; auto& lease = result->lease; if (!pin(x2w_xmem_section_lease_version, address, bytes, &lease, sizeof(lease))) return {}; + // The desktop buffers transition independently, so their state changes + // must never cover the same physical section bytes. Compare the pinned + // sections directly, since the guest addresses can be remapped here. + if (other && !mesh_xmem_windows_disjoint(lease, other->lease)) return {}; result->view = MapViewOfFile(lease.section, FILE_MAP_WRITE, static_cast(lease.section_offset >> 32), static_cast(lease.section_offset), static_cast(lease.window_bytes)); - CloseHandle(lease.section); - lease.section = nullptr; if (!result->view || FAILED(desktop->OpenExistingHeapFromAddress(result->view, IID_PPV_ARGS(&result->heap)))) return {}; D3D12_RESOURCE_DESC desc{}; @@ -173,6 +195,17 @@ std::shared_ptr open_mesh_xmem_lease(Wrapper* device, Wrapper* ow return result->matches(address) ? result : nullptr; } +size_t mesh_xmem_index(u64 bytes) +{ + return bytes == sizeof(UINT) ? mesh_xmem_srv_index : mesh_xmem_argument_index; +} + +bool mesh_xmem_write_overlaps(const MeshXMemRecording::Write& write, const MeshXMemLease& lease) +{ + return write.owner == lease.owner && write.offset < lease.offset + lease.bytes && + lease.offset < write.offset + write.bytes; +} + // Track other writes to the copied placement too. An overlapping write that // did not update the XMem view invalidates its publication at submission. void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, @@ -191,18 +224,23 @@ void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, recorded.writes.push_back({owner, offset, bytes, false}); const u64 base = reinterpret_cast(owner->own().title_memory); const u64 alignment = bytes == sizeof(UINT) ? D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT : sizeof(UINT); - if (!source || offset > UINT64_MAX - base || recorded.reader || (base + offset) % alignment) return; + if (!source || offset > UINT64_MAX - base || recorded.readers[mesh_xmem_srv_index].lease || + recorded.readers[mesh_xmem_argument_index].lease || (base + offset) % alignment) return; x2w_startup::ComPtr source_device; if (FAILED(source->GetDevice(IID_PPV_ARGS(&source_device))) || source_device.Get() != device_of(list->own().list_device)) return; const u64 address = base + offset; const auto placed = placed_buffer_range(list->own().list_device, address, bytes); if (placed.reject || placed.owner != owner) return; - auto lease = active_mesh_lease.lock(); + const auto index = mesh_xmem_index(bytes); + auto& publication = mesh_xmem_publications[index]; + auto lease = publication.active.lock(); if (!lease) { - lease = open_mesh_xmem_lease(list->own().list_device, owner, offset, address, bytes); + const auto other_index = index == mesh_xmem_srv_index ? mesh_xmem_argument_index : mesh_xmem_srv_index; + const auto other = mesh_xmem_publications[other_index].active.lock(); + lease = open_mesh_xmem_lease(list->own().list_device, owner, offset, address, bytes, other.get()); if (!lease) return; - active_mesh_lease = lease; + publication.active = lease; } if (lease->untracked || lease->owner != owner || lease->offset != offset || lease->bytes != bytes || !lease->matches(address)) return; @@ -212,80 +250,109 @@ void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, states.reserve(states.size() + 1); require_state(list, lease->buffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST); desktop_list->CopyBufferRegion(lease->buffer.Get(), lease->lease.first_byte, source, source_offset, bytes); - recorded.writer = lease; + recorded.writers[index] = lease; recorded.writes.back().leased = true; } catch (const std::bad_alloc&) { mesh_xmem_tracking_failed = true; - published_mesh_lease.reset(); + for (auto& publication : mesh_xmem_publications) publication.ready.reset(); log("x2w-render mesh XMem handoff refused: recording allocation failed"); } } -const char* record_mesh_xmem_read(Wrapper* list, u64 address, u64 bytes, D3D12_RESOURCE_STATES state, - ID3D12Resource*& resource, u64& offset) +struct MeshXMemRead { + u64 address; + u64 bytes; + D3D12_RESOURCE_STATES state; + ID3D12Resource* resource{}; + u64 offset{}; +}; + +// Check all inputs to this draw before adding any recording pins or barriers. +const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t count) { + if (!count) return nullptr; const std::lock_guard lock(mesh_xmem_mutex); - const auto lease = published_mesh_lease; - if (mesh_xmem_tracking_failed || !lease || lease->device != list->own().list_device || lease->bytes != bytes) - return "mesh XMem read has no submitted writer for the required size"; - const u64 alignment = bytes == sizeof(UINT) ? D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT : sizeof(UINT); - if (!address || address % alignment) - return "mesh XMem read address is missing or misaligned"; - const auto placed = placed_buffer_range(list->own().list_device, address, bytes); - if (!lease->matches(address) || placed.reject || placed.owner != lease->owner) - return "mesh XMem read does not match the writer's leased page and byte range"; auto* desktop_list = static_cast(list->own().real); + const auto found = mesh_xmem_recordings.find(desktop_list); + const auto* existing = found == mesh_xmem_recordings.end() ? nullptr : &found->second; + std::array verified{}; + for (size_t i = 0; i < count; ++i) { + const auto& read = reads[i]; + if (read.bytes != sizeof(UINT) && read.bytes != sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)) + return "mesh XMem read has an unsupported size"; + const auto index = mesh_xmem_index(read.bytes); + const auto& lease = mesh_xmem_publications[index].ready; + if (mesh_xmem_tracking_failed || !lease || lease->device != list->own().list_device || lease->bytes != read.bytes) + return "mesh XMem read has no submitted writer for the required size"; + const u64 alignment = index == mesh_xmem_srv_index ? D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT : sizeof(UINT); + if (!read.address || read.address % alignment) + return "mesh XMem read address is missing or misaligned"; + const auto placed = placed_buffer_range(list->own().list_device, read.address, read.bytes); + if (!lease->matches(read.address) || placed.reject || placed.owner != lease->owner) + return "mesh XMem read does not match the writer's leased page and byte range"; + if (verified[index].lease) + return "mesh XMem draw repeats the same input kind"; + if (existing) { + const auto& previous = existing->readers[index]; + if (existing->writers[mesh_xmem_srv_index] || existing->writers[mesh_xmem_argument_index] || + (previous.lease && (previous.lease != lease || previous.address != read.address))) + return "mesh XMem read requires a separate recording from its writer"; + for (const auto& write : existing->writes) + if (mesh_xmem_write_overlaps(write, *lease)) + return "mesh XMem read overlaps a write in the same recording"; + } + verified[index] = {lease, read.address}; + } try { + auto& states = pass_of(list).states; + states.reserve(states.size() + count); auto& recorded = mesh_xmem_recordings[desktop_list]; - if (recorded.writer || (recorded.reader && (recorded.reader != lease || recorded.reader_address != address))) - return "mesh XMem read requires a separate recording from its writer"; - for (const auto& write : recorded.writes) - if (write.owner == lease->owner && write.offset < lease->offset + bytes && - lease->offset < write.offset + write.bytes) - return "mesh XMem read overlaps a write in the same recording"; - pass_of(list).states.reserve(pass_of(list).states.size() + 1); - require_state(list, lease->buffer.Get(), state); - recorded.reader = lease; - recorded.reader_address = address; - resource = lease->buffer.Get(); - offset = lease->lease.first_byte; - static LONG reports; - if (first_calls(reports, 16)) - log("x2w-render mesh XMem %s: lease %llu section page +0x%llx byte +0x%llx, %llu bytes", - state == D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT ? "indirect bind" : "root bind", - lease->lease.id, lease->lease.section_offset, lease->lease.first_byte, bytes); + for (size_t i = 0; i < count; ++i) { + auto& read = reads[i]; + const auto index = mesh_xmem_index(read.bytes); + const auto& lease = verified[index].lease; + require_state(list, lease->buffer.Get(), read.state); + recorded.readers[index] = verified[index]; + read.resource = lease->buffer.Get(); + read.offset = lease->lease.first_byte; + static LONG reports; + if (first_calls(reports, 16)) + log("x2w-render mesh XMem %s: lease %llu section page +0x%llx byte +0x%llx, %llu bytes", + index == mesh_xmem_srv_index ? "root bind" : "indirect bind", + lease->lease.id, lease->lease.section_offset, lease->lease.first_byte, read.bytes); + } } catch (const std::bad_alloc&) { return "mesh XMem read recording allocation failed"; } return nullptr; } -const char* bind_mesh_xmem_srv(Wrapper* list, UINT parameter, u64 address) -{ - ID3D12Resource* resource{}; - u64 offset{}; - if (const char* failure = record_mesh_xmem_read(list, address, sizeof(UINT), - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, resource, offset)) - return failure; - auto* desktop_list = static_cast(list->own().real); - desktop_list->SetGraphicsRootShaderResourceView(parameter, resource->GetGPUVirtualAddress() + offset); - return nullptr; -} - // Caller holds mesh_xmem_mutex. Other copied placements can keep their -// original batching when they cannot change the single active publication. +// original batching when they cannot change either publication. bool mesh_xmem_needs_submission(ID3D12CommandList* list) { const auto found = mesh_xmem_recordings.find(list); if (found == mesh_xmem_recordings.end()) return false; const auto& work = found->second; - const auto active = active_mesh_lease.lock(); - return work.reader || work.writer || (active && std::any_of(work.writes.begin(), work.writes.end(), - [&](const MeshXMemRecording::Write& write) { return write.owner == active->owner; })); + for (size_t i = 0; i < mesh_xmem_publications.size(); ++i) { + if (work.readers[i].lease || work.writers[i]) return true; + const auto active = mesh_xmem_publications[i].active.lock(); + if (active && std::any_of(work.writes.begin(), work.writes.end(), + [&](const MeshXMemRecording::Write& write) { return write.owner == active->owner; })) + return true; + } + return false; } -// Draw and allocator locks serialize queue submissions. Keep the mesh lock -// through validation, enqueue and publication. No CPU fence wait is taken. +bool mesh_xmem_skip_read_wait(size_t index) +{ + return x2w_local::env_on("X2W_TEST_MESH_XMEM_SKIP_WAIT") || + x2w_local::env_on(index == mesh_xmem_srv_index ? "X2W_TEST_MESH_XMEM_SKIP_SRV_WAIT" : + "X2W_TEST_MESH_XMEM_SKIP_ARGUMENT_WAIT"); +} + +// Draw and allocator locks serialize queue submissions. Validate every lease +// before queuing a wait. Keep their references through each submission fence. template void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* list, Execute execute) { @@ -297,69 +364,89 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l return; } const auto& work = record->second; - const auto lease = work.reader ? work.reader : work.writer; - if (lease) { - const u64 address = work.reader ? work.reader_address : lease->address; + std::array, 2> accesses{}; + size_t access_count = 0; + for (size_t i = 0; i < accesses.size(); ++i) { + const auto& read = work.readers[i]; + const auto& lease = read.lease ? read.lease : work.writers[i]; + if (!lease) continue; + const u64 address = read.lease ? read.address : lease->address; const auto placed = placed_buffer_range(lease->device, address, lease->bytes); if (mesh_xmem_tracking_failed || lease->untracked || placed.reject || placed.owner != lease->owner || - !lease->matches(address) || (work.reader && published_mesh_lease != lease)) { + !lease->matches(address) || (read.lease && mesh_xmem_publications[i].ready != lease)) { log("x2w-render mesh XMem submit refused: writer or live page identity changed"); return; } + accesses[i] = lease; + ++access_count; } x2w_startup::ComPtr completion; - if (lease) { + if (access_count) { x2w_startup::ComPtr device; if (submit_fence_fails() || FAILED(queue->GetDevice(IID_PPV_ARGS(&device))) || - device.Get() != device_of(lease->device) || - FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)))) { + std::any_of(accesses.begin(), accesses.end(), [&](const auto& lease) { + return lease && device.Get() != device_of(lease->device); + }) || FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)))) { log("x2w-render mesh XMem submit refused: no completion fence on this device"); return; } try { - mesh_xmem_flights.reserve(mesh_xmem_flights.size() + 1); + mesh_xmem_flights.reserve(mesh_xmem_flights.size() + access_count); } catch (const std::bad_alloc&) { log("x2w-render mesh XMem submit refused: retirement allocation failed"); return; } - if (lease->last_access && lease->last_queue != queue) { - const bool skip = work.reader && x2w_local::env_on("X2W_TEST_MESH_XMEM_SKIP_WAIT"); - if (!skip && FAILED(queue->Wait(lease->last_access.Get(), 1))) { + ID3D12Fence* waited = nullptr; + for (size_t i = 0; i < accesses.size(); ++i) { + const auto& lease = accesses[i]; + if (!lease || !lease->last_access || lease->last_queue == queue || + lease->last_access.Get() == waited || (work.readers[i].lease && mesh_xmem_skip_read_wait(i))) + continue; + if (FAILED(queue->Wait(lease->last_access.Get(), 1))) { log("x2w-render mesh XMem submit refused: cross-queue wait failed"); return; } - if (!skip) { - static LONG reports; - if (first_calls(reports, 16)) log("x2w-render mesh XMem GPU wait for lease %llu", lease->lease.id); - } + waited = lease->last_access.Get(); + static LONG reports; + if (first_calls(reports, 16)) log("x2w-render mesh XMem GPU wait for lease %llu", lease->lease.id); } } + execute(); - if (lease) { - if (FAILED(queue->Signal(completion.Get(), 1))) { + const bool signalled = !completion || SUCCEEDED(queue->Signal(completion.Get(), 1)); + for (size_t i = 0; i < accesses.size(); ++i) { + const auto& lease = accesses[i]; + if (!lease) continue; + if (signalled) { + mesh_xmem_flights.push_back({lease, completion}); + lease->last_access = completion; + lease->last_queue = queue; + } else { lease->untracked = true; - published_mesh_lease.reset(); + mesh_xmem_publications[i].ready.reset(); mesh_xmem_flights.push_back({lease, {}}); - log("x2w-render mesh XMem completion signal failed; lease remains pinned"); - return; } - mesh_xmem_flights.push_back({lease, completion}); - lease->last_access = completion; - lease->last_queue = queue; - watch_mesh_xmem_completion(completion.Get()); } + if (!signalled) + log("x2w-render mesh XMem completion signal failed; lease remains pinned"); + else if (completion) + watch_mesh_xmem_completion(completion.Get()); + for (const auto& write : work.writes) { - if (write.leased && InterlockedCompareExchange(&lease->owner->own().refs, 0, 0)) { - published_mesh_lease = lease; + // A normal copy can invalidate either publication. Preserve the copy + // order so a later lease write on this list can publish again. + for (auto& publication : mesh_xmem_publications) + if (publication.ready && mesh_xmem_write_overlaps(write, *publication.ready)) + publication.ready.reset(); + if (write.leased && signalled && InterlockedCompareExchange(&write.owner->own().refs, 0, 0)) { + const auto index = mesh_xmem_index(write.bytes); + const auto& lease = work.writers[index]; + mesh_xmem_publications[index].ready = lease; static LONG reports; if (first_calls(reports, 16)) log("x2w-render mesh XMem writer: lease %llu section page +0x%llx byte +0x%llx, %llu bytes", lease->lease.id, lease->lease.section_offset, lease->lease.first_byte, lease->bytes); - } else if (published_mesh_lease && write.owner == published_mesh_lease->owner && - write.offset < published_mesh_lease->offset + published_mesh_lease->bytes && - published_mesh_lease->offset < write.offset + write.bytes) { - published_mesh_lease.reset(); } } } diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 454111c10..dba84bf01 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -126,6 +126,17 @@ void write_two_mesh_groups() { data.Store3(4, uint3(2, 1, 1)); } +[numthreads(1, 1, 1)] +void initialize_mesh_record() { + data.Store4(0, uint4(0, 1, 1, 0)); +} + +[numthreads(2, 1, 1)] +void append_mesh_groups() { + uint previous; + data.InterlockedAdd(0, 1u, previous); +} + [numthreads(1, 1, 1)] void write_one_rect() { data.Store4(4, uint4(3, 1, 0, 0)); @@ -457,8 +468,20 @@ struct MeshLeaseDraw { IUnknown* argument{}; UINT64 argument_offset{}; std::optional expected_right; + std::function before_submit; }; +bool mesh_fence_reached(ID3D12Fence* fence, DWORD milliseconds) +{ + const auto deadline = GetTickCount64() + milliseconds; + do { + const auto completed = fence->GetCompletedValue(); + if (completed == 1) return true; + if (completed == UINT64_MAX || GetTickCount64() >= deadline) return false; + Sleep(1); + } while (true); +} + void submit_wrapped(IUnknown* queue, IUnknown* list) { using Execute = void (WINAPI*)(IUnknown*, UINT, IUnknown* const*); @@ -836,6 +859,18 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ if (refusal == Refusal::mesh_attachment_count) slot(wrapped, 50)(wrapped, 0, nullptr, FALSE, nullptr); } else { + if (leased && leased->before_submit) { + // A submission-level refusal skips the entire wrapped list, + // including its clear. Initialize the readback target separately. + ComputeCommands clear_targets(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + for (std::size_t i = 0; i < targets.size(); ++i) { + auto* target = targets[i].Get(); + transition(clear_targets.list.Get(), target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + clear_targets.list->ClearRenderTargetView(rtvs[i], clear, 0, nullptr); + transition(clear_targets.list.Get(), target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COMMON); + } + clear_targets.submit_and_wait(device); + } for (const auto target_view : rtvs) slot(wrapped, 52)(wrapped, target_view.ptr, clear, 0, nullptr); const UINT bound_targets = target_count - (refusal == Refusal::mesh_attachment_count ? 1 : 0); slot(wrapped, 50)(wrapped, bound_targets, rtvs.data(), FALSE, nullptr); @@ -1002,11 +1037,12 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const auto queue = native_object(device, guest, leased->queue); ComPtr completion; check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)), "create mesh consumer fence"); + if (leased->before_submit) leased->before_submit(); submit_wrapped(leased->queue, wrapped); check(queue->Signal(completion.Get(), 1), "signal mesh consumer completion"); if (leased->drop_recording) wrapped_list.Reset(); if (leased->queued) leased->queued(completion.Get()); - check(completion->SetEventOnCompletion(1, nullptr), "wait for mesh consumer"); + check(mesh_fence_reached(completion.Get(), 5000) ? S_OK : E_FAIL, "wait for mesh consumer"); check(device->GetDeviceRemovedReason(), "leased mesh GPU completion"); } else { if (gate) { @@ -1326,6 +1362,8 @@ int main(int argc, char** argv) try } wchar_t lease_xmem[MAX_PATH]{}; const bool lease_fixture = GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_XMEM", lease_xmem, MAX_PATH) != 0; + const bool dual_lease = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DUAL", nullptr, 0) != 0; + if (dual_lease) check(lease_fixture && !lease_arguments ? S_OK : E_FAIL, "configure combined mesh XMem fixture"); if (lease_fixture && !lease_arguments) check(SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", "1") ? S_OK : E_FAIL, "enable mesh XMem handoff"); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; @@ -1382,7 +1420,7 @@ int main(int argc, char** argv) try wchar_t directory[MAX_PATH]; if (!GetTempPathW(MAX_PATH, directory)) return 4; const std::wstring log_path = std::wstring(directory) + L"x2w_indirect_counts_" + std::to_wstring(GetCurrentProcessId()) + L".log"; - if (indexed || lease_arguments || refusal_census) { + if (indexed || lease_arguments || dual_lease || refusal_census) { DeleteFileW(log_path.c_str()); SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); SetEnvironmentVariableA("X2W_PRESENT_SIGNATURE_EVERY", "0"); @@ -1453,6 +1491,14 @@ int main(int argc, char** argv) try const auto pso = guest_pipeline( guest.Get(), root.Get(), {ms.data(), ms.size()}, {ps.empty() ? nullptr : ps.data(), ps.size()}, {}, depth_only ? 0 : lease_fixture ? 1 : 3, depth_only); + if (dual_lease) { + const bool init_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_INIT_ONLY", nullptr, 0) != 0; + const auto initialize = writer_pipeline(device.Get(), writer.Get(), "initialize_mesh_record"); + ComPtr append; + if (!init_only) append = writer_pipeline(device.Get(), writer.Get(), "append_mesh_groups"); + return check_mesh_dual_xmem(device.Get(), guest.Get(), lease_xmem, info.Get(), log_path, + writer.Get(), initialize.Get(), append.Get(), root.Get(), pso.Get(), signature.Get()) ? 0 : 1; + } const auto work = writer_pipeline(device.Get(), writer.Get(), "write_one_mesh_group"); if (lease_fixture) { MeshLeaseWriter source(device.Get(), guest.Get(), lease_xmem); diff --git a/tests/startup_indirect_mesh_cache_check.py b/tests/startup_indirect_mesh_cache_check.py index 20b132f46..814b9e57a 100644 --- a/tests/startup_indirect_mesh_cache_check.py +++ b/tests/startup_indirect_mesh_cache_check.py @@ -25,7 +25,7 @@ def source_envelope(stage): return b'DXBC' + bytes(16) + struct.pack(' 1 and lease[1] == 'skip-wait') + lease[1] if len(lease) > 1 else None) if result: sys.exit(result) diff --git a/tests/startup_indirect_mesh_lease.inl b/tests/startup_indirect_mesh_lease.inl index 2ad921fd0..7f5fb532a 100644 --- a/tests/startup_indirect_mesh_lease.inl +++ b/tests/startup_indirect_mesh_lease.inl @@ -14,6 +14,8 @@ struct MeshLeaseWriter { ID3D12Device* guest; HMODULE xmem; const UINT64 record_bytes; + const UINT64 record_offset; + const UINT expected_group_x; Allocate alloc; Map map; Free free_pages; @@ -37,36 +39,45 @@ struct MeshLeaseWriter { } MeshLeaseWriter(ID3D12Device* d, ID3D12Device* g, const wchar_t* dll, - ID3D12RootSignature* writer_root = nullptr, ID3D12PipelineState* writer = nullptr) + ID3D12RootSignature* writer_root = nullptr, ID3D12PipelineState* writer = nullptr, + MeshLeaseWriter* mirror_owner = nullptr, ID3D12PipelineState* append = nullptr) : device(d), guest(g), xmem(LoadLibraryW(dll)), record_bytes(writer ? sizeof(old_groups) : sizeof(red)), + record_offset(mirror_owner ? 0x80 : word_offset), expected_group_x(mirror_owner && !append ? 0 : new_groups[0]), alloc(function("XMemAllocatePhysicalPages")), map(function("XMemMapPhysicalPagesScatter")), free_pages(function("XMemFreePhysicalPages")), pin(function("x2w_xmem_lease_section")), unpin(function("x2w_xmem_release_section")) { - check(SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1") && - SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", "1") ? S_OK : E_FAIL, "enable XMem mirror"); - const auto reserve = function("XMemVirtualAlloc"); - constexpr UINT64 window = UINT64{16} << 30; - cpu = static_cast(reserve(nullptr, window, 0x20402000, 0x21, 4)); - mirror = reinterpret_cast(reserve(nullptr, window, 0x20402000, 3, 0x801)); - check(cpu && mirror ? S_OK : E_FAIL, "reserve mirrored XMem"); - ULONG_PTR count = 2; - void* const addresses[]{cpu, cpu + page}; - check(alloc(0x280, &count, original) && count == 2 && map(addresses, 2, original) ? S_OK : E_FAIL, - "map two XMem pages"); + if (mirror_owner) { + cpu = mirror_owner->cpu + page; + mirror = mirror_owner->mirror + page; + } else { + check(SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1") && + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", "1") ? S_OK : E_FAIL, "enable XMem mirror"); + const auto reserve = function("XMemVirtualAlloc"); + constexpr UINT64 window = UINT64{16} << 30; + cpu = static_cast(reserve(nullptr, window, 0x20402000, 0x21, 4)); + mirror = reinterpret_cast(reserve(nullptr, window, 0x20402000, 3, 0x801)); + check(cpu && mirror ? S_OK : E_FAIL, "reserve mirrored XMem"); + ULONG_PTR count = 2; + void* const addresses[]{cpu, cpu + page}; + check(alloc(0x280, &count, original) && count == 2 && map(addresses, 2, original) ? S_OK : E_FAIL, + "map two XMem pages"); + } if (writer) { - std::memcpy(cpu + word_offset, old_groups.data(), sizeof(old_groups)); - std::memcpy(cpu + page + word_offset, old_groups.data(), sizeof(old_groups)); - std::memcpy(cpu + word_offset + 16, old_groups.data(), sizeof(old_groups)); - std::memcpy(cpu + word_offset - 4, &leading_guard, sizeof(leading_guard)); - std::memcpy(cpu + word_offset + record_bytes, &trailing_guard, sizeof(trailing_guard)); + std::memcpy(cpu + record_offset, old_groups.data(), sizeof(old_groups)); + if (!mirror_owner) { + std::memcpy(cpu + page + record_offset, old_groups.data(), sizeof(old_groups)); + std::memcpy(cpu + record_offset + 16, old_groups.data(), sizeof(old_groups)); + } + std::memcpy(cpu + record_offset - 4, &leading_guard, sizeof(leading_guard)); + std::memcpy(cpu + record_offset + record_bytes, &trailing_guard, sizeof(trailing_guard)); } else { - std::memcpy(cpu + word_offset, &green, sizeof(green)); - std::memcpy(cpu + page + word_offset, &green, sizeof(green)); + std::memcpy(cpu + record_offset, &green, sizeof(green)); + std::memcpy(cpu + page + record_offset, &green, sizeof(green)); } published_page = inspect(address()); - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, writer ? 2 * page : page, + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, writer && !mirror_owner ? 2 * page : page, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); @@ -85,6 +96,14 @@ struct MeshLeaseWriter { list->SetComputeRootSignature(writer_root); list->SetComputeRootUnorderedAccessView(0, writer_source->GetGPUVirtualAddress()); list->Dispatch(1, 1, 1); + if (append) { + D3D12_RESOURCE_BARRIER between_dispatches{}; + between_dispatches.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + between_dispatches.UAV.pResource = writer_source.Get(); + list->ResourceBarrier(1, &between_dispatches); + list->SetPipelineState(append); + list->Dispatch(1, 1, 1); + } transition(list.Get(), writer_source.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); } else { writer_source = make_buffer(device, sizeof(red), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); @@ -95,8 +114,9 @@ struct MeshLeaseWriter { writer_source->Unmap(0, nullptr); } using Copy = void (WINAPI*)(IUnknown*, IUnknown*, UINT64, IUnknown*, UINT64, UINT64); - slot(recording.Get(), 15)(recording.Get(), placed.Get(), word_offset, writer_source.Get(), - writer ? argument_offset : 0, record_bytes); + const UINT64 source_offset = writer && !mirror_owner ? argument_offset : 0; + slot(recording.Get(), 15)(recording.Get(), placed.Get(), record_offset, writer_source.Get(), + source_offset, record_bytes); check(slot(recording.Get(), 9)(recording.Get()), "close slot 15 writer"); queue = create_queue(type); gate = create_fence(); @@ -107,11 +127,11 @@ struct MeshLeaseWriter { { if (submitted) { gate->Signal(1); - completion->SetEventOnCompletion(1, nullptr); + mesh_fence_reached(completion.Get(), 5000); } } - UINT64 address() const { return mirror + word_offset; } + UINT64 address() const { return mirror + record_offset; } ComPtr create_queue(D3D12_COMMAND_LIST_TYPE type) { @@ -144,29 +164,32 @@ struct MeshLeaseWriter { auto native = native_object(device, guest, queue.Get()); check(native->Wait(gate.Get(), 1), "hold writer behind gate"); submit_wrapped(queue.Get(), recording.Get()); - check(native->Signal(completion.Get(), 1), "signal writer completion"); + if (const HRESULT status = native->Signal(completion.Get(), 1); FAILED(status)) { + gate->Signal(1); + check(status, "signal writer completion"); + } submitted = true; } void finish() { check(gate->Signal(1), "open writer gate"); - check(completion->SetEventOnCompletion(1, nullptr), "wait for slot 15 writer"); + check(mesh_fence_reached(completion.Get(), 5000) ? S_OK : E_FAIL, "wait for slot 15 writer"); check(device->GetDeviceRemovedReason(), "slot 15 GPU completion"); if (record_bytes == sizeof(new_groups)) { UINT observed[5]{}; - const UINT expected[]{leading_guard, new_groups[0], new_groups[1], new_groups[2], trailing_guard}; - std::memcpy(observed, cpu + word_offset - sizeof(UINT), sizeof(observed)); + const UINT expected[]{leading_guard, expected_group_x, new_groups[1], new_groups[2], trailing_guard}; + std::memcpy(observed, cpu + record_offset - sizeof(UINT), sizeof(observed)); for (std::size_t i = 0; i < std::size(expected); ++i) { if (observed[i] != expected[i]) std::fprintf(stderr, "XMem mesh argument/guard %zu: got %08x, expected %08x\n", i, observed[i], expected[i]); check(observed[i] == expected[i] ? S_OK : E_FAIL, "check the compute-written XMem record and guards"); } - std::puts("XMem DispatchMesh record and guards: {2,1,1} with both guards intact"); + std::printf("XMem DispatchMesh record and guards: {%u,1,1} with both guards intact\n", expected_group_x); return; } UINT actual{}; - std::memcpy(&actual, cpu + word_offset, sizeof(actual)); + std::memcpy(&actual, cpu + record_offset, sizeof(actual)); if (actual != red) std::fprintf(stderr, "leased slot 15 writer: 0x%08x != 0x%08x\n", actual, red); check(actual == red ? S_OK : E_FAIL, "leased XMem writer changed the CPU view"); @@ -305,3 +328,113 @@ bool check_mesh_indirect_xmem(ID3D12Device* device, ID3D12Device* guest, const w check_lease_debug(info); return true; } + +bool check_mesh_dual_xmem(ID3D12Device* device, ID3D12Device* guest, const wchar_t* xmem, + ID3D12InfoQueue* info, const std::wstring& log_path, + ID3D12RootSignature* writer_root, ID3D12PipelineState* initialize, ID3D12PipelineState* append, + ID3D12RootSignature* root, IUnknown* pipeline, ID3D12CommandSignature* signature) +{ + const bool init_only = !append; + MeshLeaseWriter colour(device, guest, xmem); + MeshLeaseWriter arguments(device, guest, xmem, writer_root, initialize, &colour, append); + check(colour.published_page.first != arguments.published_page.first ? S_OK : E_FAIL, + "combined mesh writers use different physical pages"); + const auto queue = colour.create_queue(D3D12_COMMAND_LIST_TYPE_DIRECT); + const auto draw = [&](UINT left, UINT right) { + MeshLeaseDraw result{colour.address(), queue.Get(), left}; + result.argument = arguments.placed.Get(); + result.argument_offset = arguments.record_offset; + result.expected_right = right; + return result; + }; + const auto verify = [&](const MeshLeaseDraw& args, const char* label) { + return run(device, guest, nullptr, nullptr, root, pipeline, signature, DrawKind::mesh, + false, Refusal::none, label, nullptr, false, nullptr, false, false, 1, false, false, &args); + }; + const auto release_pages = [&] { + arguments.recording.Reset(); + arguments.placed.Reset(); + colour.free_original(); + }; + const auto refused = draw(black, black); + if (!verify(refused, "combined cached mesh without submitted writers refused")) return false; + if (GetEnvironmentVariableA("X2W_MESH86_FIXTURE_REJECT_MARKER", nullptr, 0)) { + colour.start(); + arguments.start(); + colour.finish(); + arguments.finish(); + const bool result = verify(refused, "combined cached mesh rejects invalid marker with both writers"); + release_pages(); + check_lease_debug(info); + return result; + } + if (!GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0)) { + release_pages(); + check_lease_debug(info); + return true; + } + + const bool skip_srv = GetEnvironmentVariableA("X2W_TEST_MESH_XMEM_SKIP_SRV_WAIT", nullptr, 0) != 0; + const bool skip_arguments = GetEnvironmentVariableA("X2W_TEST_MESH_XMEM_SKIP_ARGUMENT_WAIT", nullptr, 0) != 0; + check(static_cast(skip_srv) + static_cast(skip_arguments) + static_cast(init_only) <= 1 ? S_OK : E_FAIL, + "select one combined mesh control"); + const bool control = skip_srv || skip_arguments; + auto consume = init_only ? refused : draw(skip_srv ? green : red, skip_srv ? green : skip_arguments ? black : red); + const char* label = init_only ? "combined mesh initialized arguments: zero groups" : + skip_srv ? "combined mesh stale SRV: two green halves" : + skip_arguments ? "combined mesh stale arguments: left red, right clear" : + "combined mesh fresh inputs: two red halves"; + colour.start(); + arguments.start(); + bool ordered = false; + consume.queued = [&](ID3D12Fence* done) { + const bool blocked = !mesh_fence_reached(done, 50); + // With one wait omitted, release the producer which is still required. + // The other producer remains held until the entire draw completes. + auto& first = skip_srv ? arguments : colour; + auto& second = skip_srv ? colour : arguments; + const HRESULT opened_first = first.gate->Signal(1); + const bool first_finished = mesh_fence_reached(first.completion.Get(), 5000); + const bool finished_after_first = mesh_fence_reached(done, control ? 5000 : 50); + const HRESULT opened_second = second.gate->Signal(1); + ordered = blocked && SUCCEEDED(opened_first) && first_finished && + SUCCEEDED(opened_second) && finished_after_first == control; + }; + if (!verify(consume, label)) return false; + check(ordered ? S_OK : E_FAIL, "combined mesh consumer followed the expected producer gates"); + colour.finish(); + arguments.finish(); + + if (!control && !init_only) { + auto remapped = refused; + ULONG_PTR replacement{}, count = 1; + check(colour.alloc(0x280, &count, &replacement) && count == 1 ? S_OK : E_FAIL, + "allocate replacement argument page"); + void* const replaced_address = arguments.cpu; + remapped.before_submit = [&] { + check(colour.map(&replaced_address, 1, &replacement) ? S_OK : E_FAIL, + "remap only the argument page before submission"); + std::memcpy(arguments.cpu + arguments.record_offset, MeshLeaseWriter::old_groups.data(), + sizeof(MeshLeaseWriter::old_groups)); + check(arguments.inspect(arguments.address()) != arguments.published_page && + colour.inspect(colour.address()) == colour.published_page ? S_OK : E_FAIL, + "argument page identity changed while SRV page stayed mapped"); + }; + const bool unchanged = verify(remapped, "combined mesh submit with remapped argument page leaves target clear"); + check(colour.map(&replaced_address, 1, &colour.original[1]) && colour.free_pages(1, &replacement) ? S_OK : E_FAIL, + "restore the original argument page"); + if (!unchanged || !verify(draw(red, red), "combined mesh reads both original ranges after restoring mapping")) return false; + } + + release_pages(); + std::ifstream log{std::filesystem::path(log_path)}; + check(log ? S_OK : E_FAIL, "open combined mesh handoff log"); + const std::string lines{std::istreambuf_iterator(log), {}}; + log.close(); + DeleteFileW(log_path.c_str()); + check(lines.find("mesh XMem read has no submitted writer for the required size") != std::string::npos && + (control || init_only || lines.find("mesh XMem submit refused: writer or live page identity changed") != std::string::npos) + ? S_OK : E_FAIL, "check combined mesh missing-writer and remapped-argument refusals"); + check_lease_debug(info); + return true; +} diff --git a/tests/xmem_mesh_root_srv.hlsl b/tests/xmem_mesh_root_srv.hlsl index c4d02bc16..f9fcfcb16 100644 --- a/tests/xmem_mesh_root_srv.hlsl +++ b/tests/xmem_mesh_root_srv.hlsl @@ -5,6 +5,7 @@ struct Vertex { nointerpolation uint word : WORD; }; +#ifndef X2W_MESH_DUAL [outputtopology("triangle")] [numthreads(1, 1, 1)] void mesh(out vertices Vertex verts[3], out indices uint3 triangles[1]) { @@ -18,6 +19,26 @@ void mesh(out vertices Vertex verts[3], out indices uint3 triangles[1]) { verts[2].word = word; triangles[0] = uint3(0, 1, 2); } +#else +[outputtopology("triangle")] +[numthreads(1, 1, 1)] +void mesh(uint3 group : SV_GroupID, out vertices Vertex verts[4], out indices uint3 triangles[2]) { + SetMeshOutputCounts(4, 2); + uint word = source.Load(0); + float left = float(group.x) - 1.0; + float right = left + 1.0; + verts[0].position = float4(left, -1, 0, 1); + verts[1].position = float4(left, 1, 0, 1); + verts[2].position = float4(right, -1, 0, 1); + verts[3].position = float4(right, 1, 0, 1); + verts[0].word = word; + verts[1].word = word; + verts[2].word = word; + verts[3].word = word; + triangles[0] = uint3(0, 1, 2); + triangles[1] = uint3(2, 1, 3); +} +#endif Vertex vertex(uint index : SV_VertexID) { Vertex result; diff --git a/tools/startup/mesh86_cache.py b/tools/startup/mesh86_cache.py index 9d0677c18..cc70dd050 100644 --- a/tools/startup/mesh86_cache.py +++ b/tools/startup/mesh86_cache.py @@ -79,7 +79,7 @@ def load_request(cache, key): _MESH_SRV_LOAD = re.compile( r'%\d+ = call %dx\.types\.ResRet\.i32 @dx\.op\.rawBufferLoad\.i32' r'\(i32 139, %dx\.types\.Handle (%\d+), i32 0, i32 undef, i8 1, i32 4\)') -_MESH_OUTPUT_OPS = frozenset(('setMeshOutputCounts', 'storeVertexOutput.f32', +_MESH_OUTPUT_OPS = frozenset(('groupId.i32', 'setMeshOutputCounts', 'storeVertexOutput.f32', 'storeVertexOutput.i32', 'emitIndices')) _PIXEL_IO_OPS = frozenset(('loadInput.i32', 'loadInput.f32', 'storeOutput.i32', 'storeOutput.f32')) From beabd6413d7ceca16860f41b896b12ab8b56ef6c Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Wed, 25 Nov 2026 22:38:08 +0800 Subject: [PATCH 035/232] tests: preserve shader draw failures across a later capability skip (#2380) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 2 ++ tests/startup_gfx2hlsl_dpp_pair_check.py | 2 +- ...artup_gfx2hlsl_dpp_quad_broadcast_check.py | 2 +- tests/startup_gfx2hlsl_dpp_quad_swap_check.py | 2 +- tests/startup_gfx2hlsl_draw_skip_check.py | 31 +++++++++++++++++++ tests/startup_gfx2hlsl_f32_lg_check.py | 2 +- tests/startup_gfx2hlsl_f32_nan_check.py | 2 +- tests/startup_gfx2hlsl_f32_sdwa_check.py | 2 +- tests/startup_gfx2hlsl_sdwa_cvt_check.py | 2 +- tests/startup_gfx2hlsl_sgpr_spill_check.py | 2 +- tests/startup_gfx2hlsl_vopc_sdwa_check.py | 2 +- 12 files changed, 43 insertions(+), 9 deletions(-) create mode 100644 tests/startup_gfx2hlsl_draw_skip_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index dd99cd9ad..edf313d13 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -256,6 +256,7 @@ jobs: tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ tests/startup_gfx2hlsl_cmp16_check.py \ + tests/startup_gfx2hlsl_draw_skip_check.py \ tests/startup_gfx2hlsl_sdwa_cvt_check.py \ tests/startup_gfx2hlsl_sop2_complement_check.py \ tests/startup_gfx2hlsl_sopk_accum_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 6be597835..b2572dc2c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2907,6 +2907,8 @@ if(EXISTS "${INTAKE_PYTHON}") # reference; floating-point SDWA forms and unsupported modifiers are refused. The draws are registered below. add_test(NAME startup_gfx2hlsl_vopc_sdwa COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_vopc_sdwa_check.py") + add_test(NAME startup_gfx2hlsl_draw_skip COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_draw_skip_check.py") # DPP16 quad pair broadcasts (#2125 item C): translation controls, a CPU quad model of the emitted text and the # refusals of every other DPP control. The draws are registered below. add_test(NAME startup_gfx2hlsl_dpp_pair COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_dpp_pair_check.py b/tests/startup_gfx2hlsl_dpp_pair_check.py index ac342883a..d2ad88308 100644 --- a/tests/startup_gfx2hlsl_dpp_pair_check.py +++ b/tests/startup_gfx2hlsl_dpp_pair_check.py @@ -285,7 +285,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py index ee45ba7e0..052b0d4eb 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py @@ -258,7 +258,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_dpp_quad_swap_check.py b/tests/startup_gfx2hlsl_dpp_quad_swap_check.py index d7d664198..af9e7c091 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_swap_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_swap_check.py @@ -293,7 +293,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_draw_skip_check.py b/tests/startup_gfx2hlsl_draw_skip_check.py new file mode 100644 index 000000000..1020180fa --- /dev/null +++ b/tests/startup_gfx2hlsl_draw_skip_check.py @@ -0,0 +1,31 @@ +"""A late unavailable renderer must preserve failures already logged by a shader draw check.""" +from contextlib import redirect_stdout +import importlib +import io +import subprocess +import unittest +from unittest.mock import patch + + +class DrawSkipTest(unittest.TestCase): + def test_earlier_comparison(self): + for name in ('dpp_pair', 'dpp_quad_broadcast', 'dpp_quad_swap', 'f32_lg', 'f32_nan', + 'f32_sdwa', 'sdwa_cvt', 'sgpr_spill', 'vopc_sdwa'): + module = importlib.import_module(f'startup_gfx2hlsl_{name}_check') + draw = module.run_pixel_words if name == 'sdwa_cvt' else module.draw + skipped = subprocess.CompletedProcess([], 77, '', 'adapter unavailable\n') + for passed, expected in ((True, 77), (False, 1)): + with self.subTest(fixture=name, earlier_check_passed=passed): + output = io.StringIO() + with patch.object(module, 'failures', []), redirect_stdout(output): + module.check('prior pixel comparison', passed) + with patch.object(module.subprocess, 'run', return_value=skipped): + with self.assertRaises(SystemExit) as exit_status: + draw('renderer', 'warp', 'vs', 'ps', 'reference') + self.assertEqual(exit_status.exception.code, expected) + self.assertIn('adapter unavailable', output.getvalue()) + self.assertIn('prior pixel comparison', output.getvalue()) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/startup_gfx2hlsl_f32_lg_check.py b/tests/startup_gfx2hlsl_f32_lg_check.py index 574f64a1b..3798e2d1a 100644 --- a/tests/startup_gfx2hlsl_f32_lg_check.py +++ b/tests/startup_gfx2hlsl_f32_lg_check.py @@ -676,7 +676,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_f32_nan_check.py b/tests/startup_gfx2hlsl_f32_nan_check.py index d57a88155..d40c4354f 100644 --- a/tests/startup_gfx2hlsl_f32_nan_check.py +++ b/tests/startup_gfx2hlsl_f32_nan_check.py @@ -349,7 +349,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_f32_sdwa_check.py b/tests/startup_gfx2hlsl_f32_sdwa_check.py index 30e39f587..b1bcc5e74 100644 --- a/tests/startup_gfx2hlsl_f32_sdwa_check.py +++ b/tests/startup_gfx2hlsl_f32_sdwa_check.py @@ -622,7 +622,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_sdwa_cvt_check.py b/tests/startup_gfx2hlsl_sdwa_cvt_check.py index 1ee6aefff..b1851a706 100644 --- a/tests/startup_gfx2hlsl_sdwa_cvt_check.py +++ b/tests/startup_gfx2hlsl_sdwa_cvt_check.py @@ -456,7 +456,7 @@ def run_pixel_words(renderer, adapter, vs, ps, expected_path): ) if run.returncode == 77: print(run.stdout + run.stderr, end='', flush=True) - sys.exit(77) + sys.exit(1 if failures else 77) if 'debug_layer=enabled' in run.stdout: assert 'debug_errors=0 debug_warnings=0' in run.stdout, (run.stdout, run.stderr) return run diff --git a/tests/startup_gfx2hlsl_sgpr_spill_check.py b/tests/startup_gfx2hlsl_sgpr_spill_check.py index f4c47b84f..5f4d8ef9d 100644 --- a/tests/startup_gfx2hlsl_sgpr_spill_check.py +++ b/tests/startup_gfx2hlsl_sgpr_spill_check.py @@ -214,7 +214,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run diff --git a/tests/startup_gfx2hlsl_vopc_sdwa_check.py b/tests/startup_gfx2hlsl_vopc_sdwa_check.py index fa6b49c65..4bdb633b6 100644 --- a/tests/startup_gfx2hlsl_vopc_sdwa_check.py +++ b/tests/startup_gfx2hlsl_vopc_sdwa_check.py @@ -542,7 +542,7 @@ def draw(renderer, adapter, vs, ps, expected): str(expected)], capture_output=True, text=True) if run.returncode == 77: print(run.stdout + run.stderr) - sys.exit(77) + sys.exit(1 if failures else 77) return run From 9e65634ecb02ee49e2b794afbbae16a87c2ee7d9 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Wed, 25 Nov 2026 22:41:44 +0800 Subject: [PATCH 036/232] shader: lower uncompressed RGBA8 integer render target exports (#2378) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/startup-runtime.md | 7 +++-- tests/startup_gfx2hlsl_export_mask_check.py | 15 ++++++----- tests/startup_mrt_check.py | 30 ++++++++++++++++----- tests/startup_stream_setup.h | 2 ++ tools/startup/gfx2hlsl.py | 8 +++--- 5 files changed, 44 insertions(+), 18 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 40de35f02..cae08ccae 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1995,8 +1995,11 @@ These are measured on one executable; treat them as hypotheses for others. Uncompressed `R32G32B32A32`, `R32G32` and `R32` UINT and SINT outputs use integer shader signatures (`startup_mrt_*` reads back every stored word on WARP and hardware). `R32G32_FLOAT` and `R32_FLOAT` use the same bit-preserving path as `R32G32B32A32_FLOAT`, covering a NaN payload and a - negative denormal. Integer formats with 8- or 16-bit channels are refused at translation with - `unverified UINT/SINT RTV format `. + negative denormal. Uncompressed exports to `R8G8B8A8_UINT` and `R8G8B8A8_SINT` use unsigned + and signed integer shader outputs. The output merger clamps each channel to 0–255 or −128–127 + respectively. With export words `ffffffff ffffff7f 00000080 00000100`, the stored bytes are + `ff ff 80 ff` for UINT and `ff 80 7f 7f` for SINT. The other 8- and 16-bit integer views + still return `unverified UINT/SINT RTV format `. Uncompressed binary32 FLOAT outputs bitcast the export words after XOR with a private zero-valued entry constant so optimized FXC keeps denormal bit patterns. UNORM outputs still undergo float-to-UNORM conversion. Packed integer exports and other integer formats remain diff --git a/tests/startup_gfx2hlsl_export_mask_check.py b/tests/startup_gfx2hlsl_export_mask_check.py index 8f6818832..d090f2a85 100644 --- a/tests/startup_gfx2hlsl_export_mask_check.py +++ b/tests/startup_gfx2hlsl_export_mask_check.py @@ -158,21 +158,24 @@ def revision_key(revision): got = str(reason) check('refused: partial compr export to param0', got == 'partial compressed export to param0', got) -# 7. Typed colour targets (#1999 F): 32-bit-channel integer and float formats get a matching shader -# output; narrower integer channels are refused rather than guessed. +# 7. Typed colour targets (#1999 F): each verified format gets a matching shader output. typed = (('R32G32B32A32_UINT', 3, 'uint4 mrt0', 'uint4(v0'), ('R32G32B32A32_SINT', 4, 'int4 mrt0', 'asint(uint4'), ('R32G32_UINT', 17, 'uint4 mrt0', 'uint4(v0'), ('R32G32_SINT', 18, 'int4 mrt0', 'asint(uint4'), + ('R8G8B8A8_UINT', 30, 'uint4 mrt0', 'uint4(v0'), ('R8G8B8A8_SINT', 32, 'int4 mrt0', 'asint(uint4'), ('R32_UINT', 42, 'uint4 mrt0', 'uint4(v0'), ('R32_SINT', 43, 'int4 mrt0', 'asint(uint4'), ('R32G32_FLOAT', 16, 'float4 mrt0', 'float4(F(('), ('R32_FLOAT', 41, 'float4 mrt0', 'float4(F((')) for name, fmt, signature, store in typed: got = translate(exp(0, 0xf, (0, 1, 2, 3)), (fmt,)) ok = isinstance(got, tuple) and signature in got[0] and store in assignment(got[0], 0).replace('uint4(U(v', 'uint4(v') check('typed target ' + name, ok, repr(got)[:300]) -for name, fmt in (('R32G32B32A32_UINT', 3), ('R16G16B16A16_UINT', 12), ('R8G8B8A8_UINT', 30), ('R8_UINT', 62), - ('R8G8B8A8_SINT', 32), ('R16_SINT', 59), ('R8_SINT', 64)): +for name, fmt in (('R16G16B16A16_UINT', 12), ('R16G16B16A16_SINT', 14), ('R8_UINT', 62), + ('R16_SINT', 59), ('R8_SINT', 64)): got = translate(exp(0, 0xf, (0, 1, 2, 3)), (fmt,)) - want = isinstance(got, tuple) if fmt == 3 else got == 'unverified %s RTV format %d' % ('UINT' if fmt in G.UINT_RTVS else 'SINT', fmt) - check('typed target %s %s' % (name, 'translated' if fmt == 3 else 'refused'), want, repr(got)[:200]) + want = 'unverified %s RTV format %d' % ('UINT' if fmt in G.UINT_RTVS else 'SINT', fmt) + check('typed target %s refused' % name, got == want, repr(got)[:200]) +for fmt in (30, 32): + got = translate(exp(0, 0xf, (0, 1, 2, 3), compr=True), (fmt,)) + check('packed integer export refused for format %d' % fmt, got == 'packed integer export mrt0', repr(got)[:200]) print('export mask checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) diff --git a/tests/startup_mrt_check.py b/tests/startup_mrt_check.py index 5a2261567..62d9a3a0e 100644 --- a/tests/startup_mrt_check.py +++ b/tests/startup_mrt_check.py @@ -15,8 +15,7 @@ INTEGER_WORD = 0x80000001 # Typed formats whose channels are all 32 bits: DXGI value -> (shader output type, channels). INTEGER_FORMATS = ((42, 'uint', 1), (43, 'int', 1), (17, 'uint', 2), (18, 'int', 2), (3, 'uint', 4), (4, 'int', 4)) -# Narrower integer channels are refused until a readback shows how the hardware truncates them. -REFUSED_INTEGER_FORMATS = (30, 32, 12, 14, 57, 59, 62, 64) +REFUSED_INTEGER_FORMATS = (12, 14, 57, 59, 62, 64) def pixel(values, unorm=False): @@ -41,8 +40,9 @@ def compile_shader(compiler, kind, stage, source, blob, listing, unoptimized=Fal def signature(listing): - return dict(re.findall(r'^\s*(?://|;)\s+SV_Target\s+(\d+)\s+\S+\s+\d+\s+\S+\s+(float|uint|s?int)\b', - listing.read_text(errors='replace'), re.M)) + targets = re.findall(r'^\s*(?://|;)\s+SV_Target\s+(\d+)\s+\S+\s+\d+\s+\S+\s+(float|uint|s?int)\b', + listing.read_text(errors='replace'), re.M) + return {slot: 'int' if kind == 'sint' else kind for slot, kind in targets} def check(work, consumer, backend, kind, dxc, fxc): @@ -96,8 +96,6 @@ def compile_pair(key): # The harness clears every target to (0, 0, 1, 1); integer channels hold those values as words. assert cleared == struct.pack(f'<{channels}I', *(0, 0, 1, 1)[:channels]) + bytes.fromhex('0000ffff'), cleared.hex() outputs = compile_pair(key) - if outputs.get('0') == 'sint': - outputs['0'] = 'int' assert outputs == {'0': expected_type, '1': 'float'}, outputs manifest = cache / f'{key}.txt' manifest.rename(str(manifest) + '.pending') @@ -135,6 +133,26 @@ def compile_pair(key): assert pixels.hex() == '000000000000ffff', pixels.hex() print(f'{kind} {backend} stale signedness control: refused before PSO creation') + # Distinguish signed and unsigned saturation from writing the low eight bits. + ps.write_bytes(pixel((0xffffffff, 0xffffff7f, 0x80, 0x100), unorm=True)) + for fmt, expected_type, rgba in ((30, 'uint', 'ffff80ff'), (32, 'int', 'ff807f7f')): + key, cleared = request(fmt, (fmt, 28)) + assert cleared == bytes.fromhex('000001010000ffff'), cleared.hex() + outputs = compile_pair(key) + assert outputs == {'0': expected_type, '1': 'float'}, outputs + pixels, _ = draw(fmt) + assert pixels == bytes.fromhex(rgba + 'ff0000ff'), pixels.hex() + source = (cache / f'{key}.ps.hlsl').read_text() + end = ' return o;' + assert source.count(end) == 1 + trunc = 'o.mrt0 & 255u' if fmt == 30 else 'asint(asuint(o.mrt0) << 24u) >> 24u' + wrong = cache / f'{key}.low-byte.hlsl' + wrong.write_text(source.replace(end, f' o.mrt0 = {trunc};\n{end}')) + compile_shader(compiler, kind, 'ps', wrong, cache / f'{key}.ps.cso', cache / f'{key}.low-byte.asm') + control, _ = draw(fmt) + assert control == bytes.fromhex('ff7f8000ff0000ff'), control.hex() + print(f'{kind} {backend} RGBA8 {expected_type} MRT0={rgba}; low-byte control={control[:4].hex()}') + ps.write_bytes(pixel(FLOAT_WORDS)) key, _ = request(2, (2,)) assert compile_pair(key) == {'0': 'float'} diff --git a/tests/startup_stream_setup.h b/tests/startup_stream_setup.h index 2ec1192fc..ffbdba2f9 100644 --- a/tests/startup_stream_setup.h +++ b/tests/startup_stream_setup.h @@ -45,6 +45,8 @@ struct StreamMrtFormat { inline bool stream_mrt_format(DXGI_FORMAT format, StreamMrtFormat& out) { switch (format) { + case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SINT: + out = {true, true, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS}; return true; case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: out = {true, true, 4, DXGI_FORMAT_R32_TYPELESS}; return true; case DXGI_FORMAT_R32G32_UINT: case DXGI_FORMAT_R32G32_SINT: out = {true, true, 8, DXGI_FORMAT_R32G32_TYPELESS}; return true; case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 086e8c59e..dd825c785 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4876,10 +4876,10 @@ def read(fmt, data, offset): D16_FLOAT_EXACT_SRV_FORMATS = frozenset((2, 6, 16, 21, 28, 41, 49, 61, 65, 87, 88)) D16_UNORM16_SRV_FORMATS = frozenset((11, 35, 56)) D16_EXACT_SRV_FORMATS = D16_FLOAT_EXACT_SRV_FORMATS | D16_UNORM16_SRV_FORMATS -# The formats whose channels are all 32 bits wide: the export words are the stored words, so one integer -# signature serves them. Narrower integer formats stay refused until a readback shows how they truncate. -VERIFIED_UINT_RTVS = frozenset((3, 17, 42)) # R32G32B32A32, R32G32, R32 -VERIFIED_SINT_RTVS = frozenset((4, 18, 43)) +# Uncompressed exports keep their 32-bit shader values. RGBA8 integer RTVs clamp each +# channel to the destination range in the output merger. +VERIFIED_UINT_RTVS = frozenset((3, 17, 30, 42)) +VERIFIED_SINT_RTVS = frozenset((4, 18, 32, 43)) class Pipeline: From 1d522246a59b8b4aa5684630a2bafe52cfab4645 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:41:59 +0200 Subject: [PATCH 037/232] script: support type-qualified path resolution in script_path_host (#1665) --- CMakeLists.txt | 2 + docs/experiments.md | 2 + tests/script_dispatch_check.py | 255 ++++++++++++++++++++++++++++++++- tools/script_path_host.cpp | 56 ++++++-- 4 files changed, 295 insertions(+), 20 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b2572dc2c..525475019 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7982,6 +7982,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$") add_test(NAME script_state_probe_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_state_probe_check.py") + add_test(NAME script_typed_path_dispatch COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$" TypedScriptPathTests) add_test(NAME bcpack_prefix_and_mip_tail COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bcpack_check.py") add_test(NAME bcpack_rans_symbols COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 6e479d93c..3468293bb 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10860,6 +10860,8 @@ python -B tools/script_path_replay.py path/to/script.rpf --host out/build/dev/sc Bare paths begin at the record's `states` container. A leading `./` starts at the active node and `../` moves to its parent. Each input is supplied by the experiment. The native host walks the stored first-child and sibling links, checks reverse links and selects a unique matching child ID. It reports a state whose `id` attribute is not label-kind as malformed; the replay rejects such a record before calling the host. A second lookup uses parent indices to verify the resulting node. A missing or ambiguous input leaves the test host at its last selection. The local motorbike record yields distinct front and rear camera bounds and restores the original bounds on returning to the front. The runtime event that supplies the state ID remains unresolved. +For synthetic `(id, type)` dispatch in `tests/script_dispatch_check.py`, `resolve_script_typed_path` in `tools/script_path_host.cpp` extends this host check with a caller-supplied `types` hash array matching each path depth. Sibling `state` nodes sharing an `id` digest resolve in-place when their label-kind `type` attributes differ (`script_typed_path_dispatch`), while missing or mismatched `type` attributes return `-1`, duplicate `(id, type)` siblings return `-2`, and malformed `type` attributes or out-of-bounds spans return `-3`, leaving `*active` unchanged on all error paths. + ### One synthetic BCPack mode-6 block The [fixture supplied in #442](https://github.com/R0Y00/Xbox2Windows/issues/442) pins 104 packed bytes and the expected 16-byte BC7 block in `tests/bcpack_mode6_vector.py`. The optional [Leonida reference decoder](https://github.com/timelery/Leonida/tree/03d1e118a676d73aba66b1793cf033f6ad23b2b2/tools) reproduces all 16 bytes in strict mode with an empty provisional set. To repeat the packed-byte comparison, point `BCPACK_REFERENCE_TOOLS` at that revision's local tools directory and run `python -B tests/bc7_blocks_check.py -v`. The normal suite requires no external decoder. diff --git a/tests/script_dispatch_check.py b/tests/script_dispatch_check.py index 95b026d3a..38874039f 100644 --- a/tests/script_dispatch_check.py +++ b/tests/script_dispatch_check.py @@ -18,8 +18,10 @@ runtime executable code. 2. The reference native resolver (`resolve_script_path` in `tools/script_path_host.cpp`) is intentionally `id`-only, so returning -2 - on sibling `id` collisions is conservative; type filtering here is a - caller-side pre-filter that preserves original node indices and links. + on sibling `id` collisions is conservative; `filter_siblings_by_type` + exercises that path via a caller-side pre-filter, while + `resolve_script_typed_path` accepts caller-provided `type` hash arrays to + disambiguate `(id, type)` siblings natively in-place. 3. The native runtime event or caller that supplies `(id, type)` at runtime is still unidentified. 4. A synthetic tree is a reproducible semantic model, not evidence of runtime @@ -41,22 +43,36 @@ HOST = DEFAULT_HOST -def load_resolver(host): +def _load_symbol(host, symbol, extra_argtypes=()): library = ctypes.CDLL(str(Path(host).resolve())) - resolve = library.resolve_script_path + resolve = getattr(library, symbol) u32 = ctypes.c_uint32 resolve.argtypes = [ ctypes.c_void_p, u32, ctypes.c_void_p, u32, u32, ctypes.POINTER(u32), - ctypes.c_bool, u32, ctypes.POINTER(u32), u32, + ctypes.c_bool, u32, *extra_argtypes, u32, ] resolve.restype = ctypes.c_int return resolve -def resolve_path(resolver, nodes, attrs, container, active, path_hashes, *, relative=False, up=0): - u32 = ctypes.c_uint32 +def load_resolver(host): + return _load_symbol(host, "resolve_script_path", (ctypes.POINTER(ctypes.c_uint32),)) + + +def load_typed_resolver(host): + u32_ptr = ctypes.POINTER(ctypes.c_uint32) + return _load_symbol(host, "resolve_script_typed_path", (u32_ptr, u32_ptr)) + + +def _pack_tree(nodes, attrs): node_buf = ctypes.create_string_buffer(b"".join(NODE.pack(*row) for row in nodes)) attr_buf = ctypes.create_string_buffer(b"".join(ATTRIBUTE.pack(*row) for row in attrs)) + return node_buf, attr_buf + + +def resolve_path(resolver, nodes, attrs, container, active, path_hashes, *, relative=False, up=0): + u32 = ctypes.c_uint32 + node_buf, attr_buf = _pack_tree(nodes, attrs) active_var = u32(active) path_arr = (u32 * len(path_hashes))(*path_hashes) rc = resolver( @@ -66,6 +82,22 @@ def resolve_path(resolver, nodes, attrs, container, active, path_hashes, *, rela return rc, active_var.value +def resolve_typed_path( + resolver, nodes, attrs, container, active, path_hashes, type_hashes, *, relative=False, up=0 +): + u32 = ctypes.c_uint32 + node_buf, attr_buf = _pack_tree(nodes, attrs) + active_var = u32(active) + path_arr = (u32 * len(path_hashes))(*path_hashes) if path_hashes is not None else None + type_arr = (u32 * len(type_hashes))(*type_hashes) if type_hashes is not None else None + depth = len(path_hashes) if path_hashes is not None else 0 + rc = resolver( + node_buf, len(nodes), attr_buf, len(attrs), container, ctypes.byref(active_var), + relative, up, path_arr, type_arr, depth, + ) + return rc, active_var.value + + def filter_siblings_by_type(nodes, attrs, parent, type_hash): """Return a copy of `nodes` keeping only `state` children of `parent` whose single kind-5 `type` attribute matches `type_hash`. @@ -433,6 +465,215 @@ def test_malformed_non_hash_id_returns_error_and_preserves_active(self): self.assertEqual((rc, active), (-3, 2)) +def _build_typed_collision_tree(*, missing_type=False, duplicate_pair=False, + bad_type_kind=False, duplicate_type_attr=False): + """Build a minimal `states` tree for resolve_script_typed_path edge cases.""" + nodes = [] + attrs = [] + + def add_node(tag, parent, child, sibling, previous, node_attrs=()): + first = len(attrs) if node_attrs else 0 + attrs.extend(node_attrs) + nodes.append((joaat(tag), parent, child, sibling, previous, first, len(node_attrs), 1)) + + add_node("root", NONE, 1, NONE, NONE) + add_node("states", 0, 2, NONE, NONE) + add_node("state", 1, NONE, 3, NONE, [_attr_hash("id", "default"), _attr_hash("type", "default")]) + + node3_attrs = [_attr_hash("id", "trigger_a")] + if bad_type_kind: + node3_attrs.append(_attr_int("type", 42)) + elif not missing_type: + node3_attrs.append(_attr_hash("type", "item")) + if duplicate_type_attr: + node3_attrs.append(_attr_hash("type", "item")) + + if duplicate_pair: + add_node("state", 1, NONE, 4, 2, node3_attrs) + add_node("state", 1, NONE, 5, 3, [_attr_hash("id", "trigger_a"), _attr_hash("type", "item")]) + add_node("state", 1, NONE, NONE, 4, [_attr_hash("id", "trigger_a"), _attr_hash("type", "weaponitem")]) + else: + add_node("state", 1, NONE, NONE, 2, node3_attrs) + return nodes, attrs + + +class TypedScriptPathTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.resolve_typed = load_typed_resolver(HOST) + + def test_sibling_collision_resolved_by_type_hash_and_shop_carrier(self): + nodes, attrs, vectors = build_states_library() + shop_nodes, shop_attrs = build_shop_carrier() + trigger_id = joaat("trigger_a") + + # Direct typed lookup resolves colliding sibling 4 ('item') without pre-filtering. + rc, active = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, 1, [trigger_id], [joaat("item")] + ) + self.assertEqual((rc, active), (4, 4)) + self.assertEqual(read_camera_leaves(nodes, attrs, vectors, 4), []) + leaf_idx, vecs = read_vector_leaf(nodes, attrs, vectors, 4, "preview_offset") + self.assertEqual(leaf_idx, 5) + self.assertEqual(vecs[joaat("position")], "0.100000,0.000000,-0.250000") + + # Alternate type selects colliding sibling 6 ('weaponitem') -> relative subview 7 -> cam 8. + rc, active = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, active, [trigger_id], [joaat("weaponitem")] + ) + self.assertEqual((rc, active), (6, 6)) + rc_rel, active_rel = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, active, + [joaat("detail_view")], [joaat("subview")], relative=True, up=0, + ) + self.assertEqual((rc_rel, active_rel), (7, 7)) + self.assertEqual(read_camera_leaves(nodes, attrs, vectors, 7)[0][0], 8) + + # Shop-component carriers feed (id, type) directly into resolve_script_typed_path. + pos_id, pos_type = extract_carrier_pair(shop_nodes, shop_attrs, 5, joaat("weapon")) + alt_id, alt_type = extract_carrier_pair(shop_nodes, shop_attrs, 6, joaat("weapon")) + rc_pos, active = resolve_typed_path(self.resolve_typed, nodes, attrs, 1, 1, [pos_id], [pos_type]) + self.assertEqual((rc_pos, active), (4, 4)) + rc_alt, active = resolve_typed_path(self.resolve_typed, nodes, attrs, 1, active, [alt_id], [alt_type]) + self.assertEqual((rc_alt, active), (6, 6)) + + def test_multilevel_hierarchy_paths_and_relative_switch(self): + nodes, attrs, vectors = build_states_library() + + rc_deep, active = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, 1, + [joaat("trigger_a"), joaat("detail_view")], + [joaat("weaponitem"), joaat("subview")], + ) + self.assertEqual((rc_deep, active), (7, 7)) + self.assertEqual(read_camera_leaves(nodes, attrs, vectors, 7)[0][0], 8) + + p_compact = [joaat("site_north"), joaat("compact"), joaat("inspect")] + t_hierarchy = [joaat("location"), joaat("vehiclesize"), joaat("angle")] + p_heavy = [joaat("site_north"), joaat("heavy"), joaat("inspect")] + + rc1, active = resolve_typed_path(self.resolve_typed, nodes, attrs, 1, active, p_compact, t_hierarchy) + self.assertEqual((rc1, active), (11, 11)) + self.assertEqual(read_camera_leaves(nodes, attrs, vectors, 11)[0][1]["orbitdistance"], "3.500000") + + rc2, active = resolve_typed_path(self.resolve_typed, nodes, attrs, 1, active, p_heavy, t_hierarchy) + self.assertEqual((rc2, active), (14, 14)) + self.assertEqual(read_camera_leaves(nodes, attrs, vectors, 14)[0][1]["orbitdistance"], "5.500000") + + rc3, active = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, active, + [joaat("compact"), joaat("inspect")], [joaat("vehiclesize"), joaat("angle")], + relative=True, up=2, + ) + self.assertEqual((rc3, active), (11, 11)) + + def test_missing_type_attribute_and_mismatched_type_return_missing(self): + # Missing type attribute on candidate matching id -> -1, active preserved. + nodes_no_type, attrs_no_type = _build_typed_collision_tree(missing_type=True) + rc, active = resolve_typed_path( + self.resolve_typed, nodes_no_type, attrs_no_type, 1, 2, + [joaat("trigger_a")], [joaat("item")], + ) + self.assertEqual((rc, active), (-1, 2)) + + # Mismatched type hash at single and deeper hierarchy levels -> -1, active preserved. + nodes, attrs, _ = build_states_library() + rc_miss, active_miss = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, 2, [joaat("trigger_a")], [joaat("unmatched_type")] + ) + self.assertEqual((rc_miss, active_miss), (-1, 2)) + rc_deep_miss, active_deep_miss = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, 2, + [joaat("site_north"), joaat("compact")], [joaat("location"), joaat("angle")], + ) + self.assertEqual((rc_deep_miss, active_deep_miss), (-1, 2)) + + def test_duplicate_identical_id_and_type_siblings_return_ambiguous(self): + nodes, attrs = _build_typed_collision_tree(duplicate_pair=True) + rc, active = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, 2, [joaat("trigger_a")], [joaat("item")] + ) + self.assertEqual((rc, active), (-2, 2)) + + # Distinct (id, type) sibling under the same parent still resolves uniquely. + rc_ok, active_ok = resolve_typed_path( + self.resolve_typed, nodes, attrs, 1, 2, [joaat("trigger_a")], [joaat("weaponitem")] + ) + self.assertEqual((rc_ok, active_ok), (5, 5)) + + def test_out_of_bounds_and_malformed_inputs_return_malformed(self): + base_nodes, base_attrs, _ = build_states_library() + + # Out-of-bounds sibling index -> -3. + oob_node = [list(row) for row in base_nodes] + oob_node[4][3] = len(oob_node) + rc, active = resolve_typed_path( + self.resolve_typed, [tuple(r) for r in oob_node], base_attrs, 1, 2, + [joaat("trigger_a")], [joaat("item")], + ) + self.assertEqual((rc, active), (-3, 2)) + + # Out-of-bounds attribute span -> -3. + oob_attr = [list(row) for row in base_nodes] + oob_attr[4][5] = len(base_attrs) - 1 + oob_attr[4][6] = 2 + rc, active = resolve_typed_path( + self.resolve_typed, [tuple(r) for r in oob_attr], base_attrs, 1, 2, + [joaat("trigger_a")], [joaat("item")], + ) + self.assertEqual((rc, active), (-3, 2)) + + # Out-of-bounds container / active, null types, and zero depth -> -3. + self.assertEqual( + resolve_typed_path( + self.resolve_typed, base_nodes, base_attrs, len(base_nodes), 2, + [joaat("default")], [joaat("default")], + ), + (-3, 2), + ) + self.assertEqual( + resolve_typed_path( + self.resolve_typed, base_nodes, base_attrs, 1, len(base_nodes), + [joaat("default")], [joaat("default")], + ), + (-3, len(base_nodes)), + ) + self.assertEqual( + resolve_typed_path( + self.resolve_typed, base_nodes, base_attrs, 1, 2, + [joaat("default")], None, + ), + (-3, 2), + ) + self.assertEqual( + resolve_typed_path( + self.resolve_typed, base_nodes, base_attrs, 1, 2, [], [] + ), + (-3, 2), + ) + + # Malformed non-label `type`, duplicate `type`, and non-label `id` -> -3. + for kwargs in ({"bad_type_kind": True}, {"duplicate_type_attr": True}): + with self.subTest(**kwargs): + bad_nodes, bad_attrs = _build_typed_collision_tree(**kwargs) + self.assertEqual( + resolve_typed_path( + self.resolve_typed, bad_nodes, bad_attrs, 1, 2, + [joaat("trigger_a")], [joaat("item")], + ), + (-3, 2), + ) + + bool_nodes, bool_attrs, _ = build_states_library(malformed_bool_id=True) + self.assertEqual( + resolve_typed_path( + self.resolve_typed, bool_nodes, bool_attrs, 1, 2, + [joaat("trigger_a")], [joaat("item")], + ), + (-3, 2), + ) + + if __name__ == "__main__": if len(sys.argv) > 1 and not sys.argv[1].startswith("-"): HOST = Path(sys.argv.pop(1)) diff --git a/tools/script_path_host.cpp b/tools/script_path_host.cpp index f279a16d8..b607b288f 100644 --- a/tools/script_path_host.cpp +++ b/tools/script_path_host.cpp @@ -27,14 +27,11 @@ constexpr std::uint32_t nameHash(const char* s) { h ^= h >> 11; return h + (h << 15); } -} -// Nonnegative results are source node indices. Negative results mean missing (-1), -// ambiguous (-2) or malformed (-3). The caller supplies the path to experiment with. -extern "C" __declspec(dllexport) int resolve_script_path( +int resolvePathImpl( const Node* nodes, unsigned nodeCount, const Attribute* attrs, unsigned attrCount, unsigned container, unsigned* active, bool relative, unsigned up, - const std::uint32_t* path, unsigned depth) + const std::uint32_t* path, const std::uint32_t* types, unsigned depth) { if (!nodes || !attrs || !active || !path || !depth || nodeCount > noNode || container >= nodeCount || *active >= nodeCount) @@ -60,17 +57,26 @@ extern "C" __declspec(dllexport) int resolve_script_path( const unsigned end = node.firstAttribute + node.attributeCount; if (node.attributeCount && end > attrCount) return -3; bool seenId = false; + bool seenType = false; + bool idMatch = false; + bool typeMatch = (types == nullptr); for (unsigned a = node.firstAttribute; a < end; ++a) { - if (attrs[a].name != nameHash("id")) continue; - if (seenId || attrs[a].kind != 5) return -3; - seenId = true; - if (attrs[a].textHash == path[level]) { - if (match != noNode) - ambiguous = true; - else - match = i; + if (attrs[a].name == nameHash("id")) { + if (seenId || attrs[a].kind != 5) return -3; + seenId = true; + idMatch = (attrs[a].textHash == path[level]); + } else if (types && attrs[a].name == nameHash("type")) { + if (seenType || attrs[a].kind != 5) return -3; + seenType = true; + typeMatch = (attrs[a].textHash == types[level]); } } + if (idMatch && typeMatch) { + if (match != noNode) + ambiguous = true; + else + match = i; + } } if (ambiguous) return -2; if (match == noNode) return -1; @@ -79,3 +85,27 @@ extern "C" __declspec(dllexport) int resolve_script_path( *active = parent; return static_cast(parent); } +} + +// Nonnegative results are source node indices. Negative results mean missing (-1), +// ambiguous (-2) or malformed (-3). The caller supplies the path to experiment with. +extern "C" __declspec(dllexport) int resolve_script_path( + const Node* nodes, unsigned nodeCount, const Attribute* attrs, unsigned attrCount, + unsigned container, unsigned* active, bool relative, unsigned up, + const std::uint32_t* path, unsigned depth) +{ + return resolvePathImpl(nodes, nodeCount, attrs, attrCount, container, active, relative, up, + path, nullptr, depth); +} + +// Type-qualified variant: each path segment must match both a label-kind `id` and a +// label-kind `type` attribute (`types[level]`) on the candidate `state` sibling. +extern "C" __declspec(dllexport) int resolve_script_typed_path( + const Node* nodes, unsigned nodeCount, const Attribute* attrs, unsigned attrCount, + unsigned container, unsigned* active, bool relative, unsigned up, + const std::uint32_t* path, const std::uint32_t* types, unsigned depth) +{ + if (!types) return -3; + return resolvePathImpl(nodes, nodeCount, attrs, attrCount, container, active, relative, up, + path, types, depth); +} From f5a8355f9b9146901f1c8df84bea0795a7640874 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:42:15 +0200 Subject: [PATCH 038/232] cpu: add dedicated cpu_sha1_aot lifter for SHA1RNDS4, SHA1NEXTE, SHA1MSG1, and SHA1MSG2 (#2376) --- CMakeLists.txt | 24 ++ tests/cpu/sha1_aot.asm | 224 ++++++++++++ tests/cpu/sha1_aot.def | 21 ++ tests/cpu/sha1_aot_check.py | 698 ++++++++++++++++++++++++++++++++++++ tools/cpu_sha1_aot.py | 390 ++++++++++++++++++++ 5 files changed, 1357 insertions(+) create mode 100644 tests/cpu/sha1_aot.asm create mode 100644 tests/cpu/sha1_aot.def create mode 100644 tests/cpu/sha1_aot_check.py create mode 100644 tools/cpu_sha1_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 525475019..9ff30b04c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5754,6 +5754,30 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_crypto_sha PROPERTIES SKIP_RETURN_CODE 77) + set(cpu_sha1_aot_exports + "op_sha1rnds4_0_reg,op_sha1rnds4_1_reg,op_sha1rnds4_2_reg,op_sha1rnds4_3_reg," + "op_sha1rnds4_hi_imm,op_sha1rnds4_0_mem,op_sha1rnds4_1_mem,op_sha1rnds4_2_mem," + "op_sha1rnds4_3_mem,op_sha1rnds4_self," + "op_sha1nexte_reg,op_sha1nexte_mem,op_sha1nexte_self," + "op_sha1msg1_reg,op_sha1msg1_mem,op_sha1msg1_self," + "op_sha1msg2_reg,op_sha1msg2_mem,op_sha1msg2_self," + "op_sha1_pipeline") + string(CONCAT cpu_sha1_aot_exports ${cpu_sha1_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sha1_aot_${variant} sha1_aot) + cpu_translation(cpu_sha1_aot_${variant} cpu_sha1_aot "${cpu_sha1_aot_exports}") + endforeach() + target_compile_definitions(cpu_sha1_aot_altered PRIVATE ALTER_SHA1) + add_test(NAME cpu_aot_sha1 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sha1_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_sha1 PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sha1.txt") + cpu_asm_fixture(cpu_mul_div mul_div) set(mul_div_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_mul_div_lifted.cpp") add_custom_command(OUTPUT "${mul_div_fixture}" diff --git a/tests/cpu/sha1_aot.asm b/tests/cpu/sha1_aot.asm new file mode 100644 index 000000000..025eb04d4 --- /dev/null +++ b/tests/cpu/sha1_aot.asm @@ -0,0 +1,224 @@ +; coverage: record cpu_aot_sha1 +; Source-owned differential fixture for Intel SHA-1 NI instructions: +; SHA1RNDS4, SHA1NEXTE, SHA1MSG1, and SHA1MSG2 across register and flat [rdx]/[r8] +; memory operands, all four SHA1RNDS4 imm8 functions (plus upper-bit masking), +; self-operand forms, and a multi-instruction pipeline on volatile XMM0..XMM5. +; RCX = const void* input_a (16 bytes; 16B-aligned for movdqa / sha1* m128) +; RDX = const void* input_b (16 bytes; 16B-aligned for movdqa / sha1* m128) +; R8 = void* output (16 bytes; 16B-aligned for movdqa / sha1* m128) +.code + +op_sha1rnds4_0_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1rnds4 xmm0, xmm1, 1 +ELSE + sha1rnds4 xmm0, xmm1, 0 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1rnds4_0_reg ENDP + +op_sha1rnds4_1_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1rnds4 xmm0, xmm1, 2 +ELSE + sha1rnds4 xmm0, xmm1, 1 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1rnds4_1_reg ENDP + +op_sha1rnds4_2_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1rnds4 xmm0, xmm1, 3 +ELSE + sha1rnds4 xmm0, xmm1, 2 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1rnds4_2_reg ENDP + +op_sha1rnds4_3_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1rnds4 xmm0, xmm1, 0 +ELSE + sha1rnds4 xmm0, xmm1, 3 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1rnds4_3_reg ENDP + +; Upper bits [7:2] of SHA1RNDS4 imm8 must be ignored (0FCh->0, 0FDh->1, 0FEh->2, 0FFh->3). +op_sha1rnds4_hi_imm PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] + sha1rnds4 xmm0, xmm1, 0FCh + sha1rnds4 xmm0, xmm1, 0FDh + sha1rnds4 xmm0, xmm1, 0FEh + sha1rnds4 xmm0, xmm1, 0FFh + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1rnds4_hi_imm ENDP + +op_sha1rnds4_0_mem PROC FRAME + .endprolog + movdqa xmm2, xmmword ptr [rcx] + sha1rnds4 xmm2, xmmword ptr [rdx], 0 + movdqa xmmword ptr [r8], xmm2 + ret +op_sha1rnds4_0_mem ENDP + +op_sha1rnds4_1_mem PROC FRAME + .endprolog + movdqa xmm3, xmmword ptr [rcx] + sha1rnds4 xmm3, xmmword ptr [rdx], 1 + movdqa xmmword ptr [r8], xmm3 + ret +op_sha1rnds4_1_mem ENDP + +op_sha1rnds4_2_mem PROC FRAME + .endprolog + movdqa xmm4, xmmword ptr [rcx] + sha1rnds4 xmm4, xmmword ptr [rdx], 2 + movdqa xmmword ptr [r8], xmm4 + ret +op_sha1rnds4_2_mem ENDP + +op_sha1rnds4_3_mem PROC FRAME + .endprolog + movdqa xmm5, xmmword ptr [rcx] + sha1rnds4 xmm5, xmmword ptr [rdx], 3 + movdqa xmmword ptr [r8], xmm5 + ret +op_sha1rnds4_3_mem ENDP + +op_sha1rnds4_self PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + sha1rnds4 xmm0, xmm0, 2 + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1rnds4_self ENDP + +op_sha1nexte_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1nexte xmm1, xmm0 + movdqu xmm0, xmm1 +ELSE + sha1nexte xmm0, xmm1 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1nexte_reg ENDP + +op_sha1nexte_mem PROC FRAME + .endprolog + movdqa xmm2, xmmword ptr [rcx] + sha1nexte xmm2, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm2 + ret +op_sha1nexte_mem ENDP + +op_sha1nexte_self PROC FRAME + .endprolog + movdqu xmm3, xmmword ptr [rcx] + sha1nexte xmm3, xmm3 + movdqu xmmword ptr [r8], xmm3 + ret +op_sha1nexte_self ENDP + +op_sha1msg1_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1msg2 xmm0, xmm1 +ELSE + sha1msg1 xmm0, xmm1 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1msg1_reg ENDP + +op_sha1msg1_mem PROC FRAME + .endprolog + movdqa xmm4, xmmword ptr [rcx] + sha1msg1 xmm4, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm4 + ret +op_sha1msg1_mem ENDP + +op_sha1msg1_self PROC FRAME + .endprolog + movdqu xmm5, xmmword ptr [rcx] + sha1msg1 xmm5, xmm5 + movdqu xmmword ptr [r8], xmm5 + ret +op_sha1msg1_self ENDP + +op_sha1msg2_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA1 + sha1msg1 xmm0, xmm1 +ELSE + sha1msg2 xmm0, xmm1 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha1msg2_reg ENDP + +op_sha1msg2_mem PROC FRAME + .endprolog + movdqa xmm2, xmmword ptr [rcx] + sha1msg2 xmm2, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm2 + ret +op_sha1msg2_mem ENDP + +op_sha1msg2_self PROC FRAME + .endprolog + movdqu xmm4, xmmword ptr [rcx] + sha1msg2 xmm4, xmm4 + movdqu xmmword ptr [r8], xmm4 + ret +op_sha1msg2_self ENDP + +; Multi-instruction pipeline exercising XMM0..XMM5, movdqa/movdqu reg copies, +; and an [r8] store followed by a flat [r8] memory source in sha1nexte. +op_sha1_pipeline PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] + movdqa xmm2, xmm0 + sha1msg1 xmm2, xmm1 + sha1msg2 xmm2, xmm1 + movdqa xmmword ptr [r8], xmm2 + movdqu xmm3, xmm0 + sha1rnds4 xmm3, xmm1, 0 + movdqa xmm4, xmm3 + sha1nexte xmm4, xmmword ptr [r8] + movdqa xmm5, xmm3 + sha1rnds4 xmm5, xmm4, 1 + movdqa xmmword ptr [r8], xmm5 + ret +op_sha1_pipeline ENDP + +END diff --git a/tests/cpu/sha1_aot.def b/tests/cpu/sha1_aot.def new file mode 100644 index 000000000..0b3d8239b --- /dev/null +++ b/tests/cpu/sha1_aot.def @@ -0,0 +1,21 @@ +EXPORTS + op_sha1rnds4_0_reg + op_sha1rnds4_1_reg + op_sha1rnds4_2_reg + op_sha1rnds4_3_reg + op_sha1rnds4_hi_imm + op_sha1rnds4_0_mem + op_sha1rnds4_1_mem + op_sha1rnds4_2_mem + op_sha1rnds4_3_mem + op_sha1rnds4_self + op_sha1nexte_reg + op_sha1nexte_mem + op_sha1nexte_self + op_sha1msg1_reg + op_sha1msg1_mem + op_sha1msg1_self + op_sha1msg2_reg + op_sha1msg2_mem + op_sha1msg2_self + op_sha1_pipeline diff --git a/tests/cpu/sha1_aot_check.py b/tests/cpu/sha1_aot_check.py new file mode 100644 index 000000000..ac30a7fb0 --- /dev/null +++ b/tests/cpu/sha1_aot_check.py @@ -0,0 +1,698 @@ +"""Differential, NIST FIPS 180-4, aliasing, mutation, and rejection checks for SHA-1 NI AOT lifting.""" + +import ctypes +import hashlib +import os +from pathlib import Path +import random +import struct +import sys + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_sha1_aot import lift_code # noqa: E402 + +EXPORTS = ( + "op_sha1rnds4_0_reg", + "op_sha1rnds4_1_reg", + "op_sha1rnds4_2_reg", + "op_sha1rnds4_3_reg", + "op_sha1rnds4_hi_imm", + "op_sha1rnds4_0_mem", + "op_sha1rnds4_1_mem", + "op_sha1rnds4_2_mem", + "op_sha1rnds4_3_mem", + "op_sha1rnds4_self", + "op_sha1nexte_reg", + "op_sha1nexte_mem", + "op_sha1nexte_self", + "op_sha1msg1_reg", + "op_sha1msg1_mem", + "op_sha1msg1_self", + "op_sha1msg2_reg", + "op_sha1msg2_mem", + "op_sha1msg2_self", + "op_sha1_pipeline", +) + +UNALIGNED_SAFE_EXPORTS = ( + "op_sha1rnds4_0_reg", + "op_sha1rnds4_1_reg", + "op_sha1rnds4_2_reg", + "op_sha1rnds4_3_reg", + "op_sha1rnds4_hi_imm", + "op_sha1rnds4_self", + "op_sha1nexte_reg", + "op_sha1nexte_self", + "op_sha1msg1_reg", + "op_sha1msg1_self", + "op_sha1msg2_reg", + "op_sha1msg2_self", +) + +ALTERED_EXPORTS = ( + "op_sha1rnds4_0_reg", + "op_sha1rnds4_1_reg", + "op_sha1rnds4_2_reg", + "op_sha1rnds4_3_reg", + "op_sha1nexte_reg", + "op_sha1msg1_reg", + "op_sha1msg2_reg", +) + +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference for SHA-1 NI instructions --- + +def _rol32(x, n): + x &= 0xFFFFFFFF + return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF + + +def _unpack4(buf): + return struct.unpack("<4I", buf) + + +def _pack4(w0, w1, w2, w3): + return struct.pack("<4I", w0 & 0xFFFFFFFF, w1 & 0xFFFFFFFF, w2 & 0xFFFFFFFF, w3 & 0xFFFFFFFF) + + +def ref_sha1rnds4(dst_bytes, src_bytes, imm8): + d0, d1, d2, d3 = _unpack4(dst_bytes) + s0, s1, s2, s3 = _unpack4(src_bytes) + a, b, c, d, e = d3, d2, d1, d0, 0 + w = (s3, s2, s1, s0) + sel = imm8 & 3 + k = (0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6)[sel] + for i in range(4): + if sel == 0: + f = (b & c) ^ ((~b & 0xFFFFFFFF) & d) + elif sel == 2: + f = (b & c) ^ (b & d) ^ (c & d) + else: + f = b ^ c ^ d + next_a = (f + _rol32(a, 5) + w[i] + k + e) & 0xFFFFFFFF + e = d + d = c + c = _rol32(b, 30) + b = a + a = next_a + return _pack4(d, c, b, a) + + +def ref_sha1nexte(dst_bytes, src_bytes): + _, _, _, d3 = _unpack4(dst_bytes) + s0, s1, s2, s3 = _unpack4(src_bytes) + return _pack4(s0, s1, s2, (s3 + _rol32(d3, 30)) & 0xFFFFFFFF) + + +def ref_sha1msg1(dst_bytes, src_bytes): + d0, d1, d2, d3 = _unpack4(dst_bytes) + _, _, s2, s3 = _unpack4(src_bytes) + return _pack4(d0 ^ s2, d1 ^ s3, d2 ^ d0, d3 ^ d1) + + +def ref_sha1msg2(dst_bytes, src_bytes): + d0, d1, d2, d3 = _unpack4(dst_bytes) + s0, s1, s2, _ = _unpack4(src_bytes) + w16 = _rol32(d3 ^ s2, 1) + w17 = _rol32(d2 ^ s1, 1) + w18 = _rol32(d1 ^ s0, 1) + w19 = _rol32(d0 ^ w16, 1) + return _pack4(w19, w18, w17, w16) + + +def reference(name, a, b, *, altered=False): + if name == "op_sha1rnds4_0_reg": + return ref_sha1rnds4(a, b, 1 if altered else 0) + if name == "op_sha1rnds4_1_reg": + return ref_sha1rnds4(a, b, 2 if altered else 1) + if name == "op_sha1rnds4_2_reg": + return ref_sha1rnds4(a, b, 3 if altered else 2) + if name == "op_sha1rnds4_3_reg": + return ref_sha1rnds4(a, b, 0 if altered else 3) + if name == "op_sha1rnds4_hi_imm": + v = ref_sha1rnds4(a, b, 0xFC) + v = ref_sha1rnds4(v, b, 0xFD) + v = ref_sha1rnds4(v, b, 0xFE) + return ref_sha1rnds4(v, b, 0xFF) + if name == "op_sha1rnds4_0_mem": + return ref_sha1rnds4(a, b, 0) + if name == "op_sha1rnds4_1_mem": + return ref_sha1rnds4(a, b, 1) + if name == "op_sha1rnds4_2_mem": + return ref_sha1rnds4(a, b, 2) + if name == "op_sha1rnds4_3_mem": + return ref_sha1rnds4(a, b, 3) + if name == "op_sha1rnds4_self": + return ref_sha1rnds4(a, a, 2) + if name == "op_sha1nexte_reg": + return ref_sha1nexte(b, a) if altered else ref_sha1nexte(a, b) + if name == "op_sha1nexte_mem": + return ref_sha1nexte(a, b) + if name == "op_sha1nexte_self": + return ref_sha1nexte(a, a) + if name == "op_sha1msg1_reg": + return ref_sha1msg2(a, b) if altered else ref_sha1msg1(a, b) + if name == "op_sha1msg1_mem": + return ref_sha1msg1(a, b) + if name == "op_sha1msg1_self": + return ref_sha1msg1(a, a) + if name == "op_sha1msg2_reg": + return ref_sha1msg1(a, b) if altered else ref_sha1msg2(a, b) + if name == "op_sha1msg2_mem": + return ref_sha1msg2(a, b) + if name == "op_sha1msg2_self": + return ref_sha1msg2(a, a) + if name == "op_sha1_pipeline": + x2 = ref_sha1msg2(ref_sha1msg1(a, b), b) + x3 = ref_sha1rnds4(a, b, 0) + x4 = ref_sha1nexte(x3, x2) + return ref_sha1rnds4(x3, x4, 1) + raise KeyError(name) + + +def all_pairs(): + """Construct edge, carry-wrap, lane-isolation, FIPS-state, and deterministic random 16-byte input pairs.""" + z16 = b"\x00" * 16 + f16 = b"\xff" * 16 + # Standard FIPS 180-4 SHA-1 initial IV words packed in XMM lane order (w3=H0..w0=H3). + fips_iv = _pack4(0x10325476, 0x98BADCFE, 0xEFCDAB89, 0x67452301) + pairs = [ + (z16, z16), + (f16, f16), + (z16, f16), + (f16, z16), + (fips_iv, _pack4(0x00000000, 0x00000000, 0x00000000, 0x61626380 + 0xC3D2E1F0)), + # Carry wrap in SHA1NEXTE: rol32(0xFFFFFFFF, 30) == 0xFFFFFFFF; 0xFFFFFFFF + 1 == 0. + (_pack4(0x11111111, 0x22222222, 0x33333333, 0xFFFFFFFF), _pack4(0x44444444, 0x55555555, 0x66666666, 0x00000001)), + # Rotation bit boundaries in lane 3 (bits 0, 1, 2, 30, 31) and carry across 32-bit wrap. + (_pack4(0x00000001, 0x80000000, 0x00000003, 0x00000001), _pack4(0x80000000, 0x00000001, 0x40000000, 0xC0000000)), + (_pack4(0x80000000, 0x40000000, 0x20000000, 0x80000000), _pack4(0x00000001, 0x00000002, 0x00000004, 0x80000000)), + # Single-lane isolation probes (each dword isolated in dst or src). + *[ + (_pack4(*(0xA5A55A5A if j == i else 0 for j in range(4))), + _pack4(*(0x3C3CC3C3 if j == k else 0 for j in range(4)))) + for i in range(4) for k in range(4) + ], + ] + rng = random.Random(0x5A1A07) + for _ in range(96): + pairs.append((rng.randbytes(16), rng.randbytes(16))) + return pairs + + +def alloc_guarded(payload, *, misalign=0): + """Allocate a guarded 16-byte buffer whose payload begins at (16B-aligned + misalign).""" + size = 48 + len(GUARD_PRE) + len(payload) + len(GUARD_POST) + raw = ctypes.create_string_buffer(size) + base = ctypes.addressof(raw) + aligned = (base + len(GUARD_PRE) + 15) & ~15 + data_addr = aligned + misalign + pre_off = (data_addr - len(GUARD_PRE)) - base + data_off = data_addr - base + post_off = data_off + len(payload) + raw[pre_off:data_off] = GUARD_PRE + raw[data_off:post_off] = payload + raw[post_off:post_off + len(GUARD_POST)] = GUARD_POST + return raw, pre_off, data_off, post_off, data_addr + + +def invoke(fn, a, b, *, a_misalign=0, b_misalign=0, out_misalign=0): + buf_a, a_pre, a_off, a_post, a_addr = alloc_guarded(a, misalign=a_misalign) + buf_b, b_pre, b_off, b_post, b_addr = alloc_guarded(b, misalign=b_misalign) + buf_out, o_pre, o_off, o_post, o_addr = alloc_guarded(b"\x5a" * 16, misalign=out_misalign) + fn(a_addr, b_addr, o_addr) + assert buf_a.raw[a_pre:a_off] == GUARD_PRE and buf_a.raw[a_post:a_post + 16] == GUARD_POST, "input A guards corrupted" + assert buf_b.raw[b_pre:b_off] == GUARD_PRE and buf_b.raw[b_post:b_post + 16] == GUARD_POST, "input B guards corrupted" + assert buf_out.raw[o_pre:o_off] == GUARD_PRE and buf_out.raw[o_post:o_post + 16] == GUARD_POST, "output guards corrupted" + assert buf_a.raw[a_off:a_post] == a, "input A mutated unexpectedly" + assert buf_b.raw[b_off:b_post] == b, "input B mutated unexpectedly" + return buf_out.raw[o_off:o_post] + + +def invoke_aliased(fn, a, b, mode): + """Invoke fn with aliased argument pointers (rcx==rdx, r8==rcx, r8==rdx, or all three).""" + buf_a, a_pre, a_off, a_post, a_addr = alloc_guarded(a) + buf_b, b_pre, b_off, b_post, b_addr = alloc_guarded(b) + buf_out, o_pre, o_off, o_post, o_addr = alloc_guarded(b"\x5a" * 16) + if mode == "rcx==rdx": + fn(a_addr, a_addr, o_addr) + res = buf_out.raw[o_off:o_post] + elif mode == "r8==rcx": + fn(a_addr, b_addr, a_addr) + res = buf_a.raw[a_off:a_post] + elif mode == "r8==rdx": + fn(a_addr, b_addr, b_addr) + res = buf_b.raw[b_off:b_post] + elif mode == "all": + fn(a_addr, a_addr, a_addr) + res = buf_a.raw[a_off:a_post] + else: + raise ValueError(f"unknown alias mode {mode}") + assert buf_a.raw[a_pre:a_off] == GUARD_PRE and buf_a.raw[a_post:a_post + 16] == GUARD_POST, f"{mode}: A guards corrupted" + assert buf_b.raw[b_pre:b_off] == GUARD_PRE and buf_b.raw[b_post:b_post + 16] == GUARD_POST, f"{mode}: B guards corrupted" + assert buf_out.raw[o_pre:o_off] == GUARD_PRE and buf_out.raw[o_post:o_post + 16] == GUARD_POST, f"{mode}: out guards corrupted" + return res + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def host_has_sha(lifted_lib): + if hasattr(lifted_lib, "host_has_sha"): + lifted_lib.host_has_sha.argtypes = [] + lifted_lib.host_has_sha.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_sha()) + try: + return " sha_ni" in Path("/proc/cpuinfo").read_text(encoding="ascii", errors="replace") + except OSError: + return False + + +def encode_seq(*instructions): + enc = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += enc.encode(ins, rip) + return enc.take_buffer() + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + ld0 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld1 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld0_a = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + st0 = Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + st0_a = Instruction.create_mem_reg(Code.MOVDQA_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + + # Positive checks for all 4 SHA-1 NI instructions (reg & flat [rdx]/[r8] mem, plus movdqa/movdqu glue). + accepted = 0 + for imm in (0, 1, 2, 3, 0xFC, 0xFF): + src_reg, _ = lift_code( + f"sha1rnds4_reg_{imm}", 0x1000, + encode_seq(ld0, ld1, Instruction.create_reg_reg_u32(Code.SHA1RNDS4_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, imm), st0, ret), + ) + assert f"op_sha1rnds4(xmm0, xmm1, {imm:#x}u)" in src_reg + src_mem, _ = lift_code( + f"sha1rnds4_mem_{imm}", 0x1000, + encode_seq(ld0_a, Instruction.create_reg_mem_u32(Code.SHA1RNDS4_XMM_XMMM128_IMM8, R.XMM0, MemoryOperand(R.RDX), imm), st0_a, ret), + ) + assert f"op_sha1rnds4(xmm0, load128(rdx), {imm:#x}u)" in src_mem + accepted += 1 + for code, helper in ( + (Code.SHA1NEXTE_XMM_XMMM128, "op_sha1nexte"), + (Code.SHA1MSG1_XMM_XMMM128, "op_sha1msg1"), + (Code.SHA1MSG2_XMM_XMMM128, "op_sha1msg2"), + ): + src_reg, _ = lift_code( + f"{helper}_reg", 0x1000, + encode_seq(ld0, ld1, Instruction.create_reg_reg(code, R.XMM0, R.XMM1), st0, ret), + ) + assert f"{helper}(xmm0, xmm1)" in src_reg + src_mem, _ = lift_code( + f"{helper}_mem", 0x1000, + encode_seq(ld0_a, Instruction.create_reg_mem(code, R.XMM0, MemoryOperand(R.RDX)), st0_a, ret), + ) + assert f"{helper}(xmm0, load128(rdx))" in src_mem + accepted += 1 + + # Verify generated C++ does not include . + assert "" not in src_reg + + # Negative rejection controls. + rep_ret = Instruction.create(Code.RETNQ) + rep_ret.has_rep_prefix = True + fs_ld = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + fs_ld.segment_prefix = R.FS + + cases = [ + ("sha256rnds2", (ld0, ld1, Instruction.create_reg_reg(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, R.XMM0), st0, ret), + "unsupported SHA-256 instruction"), + ("sha256msg1", (ld0, ld1, Instruction.create_reg_reg(Code.SHA256MSG1_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported SHA-256 instruction"), + ("sha256msg2", (ld0, ld1, Instruction.create_reg_reg(Code.SHA256MSG2_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported SHA-256 instruction"), + ("vex_vmovdqu", (Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), st0, ret), + "unsupported VEX encoding"), + ("vex_vpxor", (ld0, ld1, Instruction.create_reg_reg_reg(Code.VEX_VPXOR_XMM_XMM_XMMM128, R.XMM0, R.XMM0, R.XMM1), st0, ret), + "unsupported VEX encoding"), + ("evex_vmovdqu32", (Instruction.create_reg_mem(Code.EVEX_VMOVDQU32_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), st0, ret), + "unsupported EVEX encoding"), + ("nonvol_xmm6_dst", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM6, MemoryOperand(R.RCX)), ret), + "nonvolatile vector register"), + ("nonvol_xmm15_src", (ld0, Instruction.create_reg_reg(Code.SHA1MSG1_XMM_XMMM128, R.XMM0, R.XMM15), st0, ret), + "nonvolatile vector register"), + ("undef_xmm_dst_rnds4", (ld1, Instruction.create_reg_reg_u32(Code.SHA1RNDS4_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), st0, ret), + "undefined vector register xmm0"), + ("undef_xmm_src_nexte", (ld0, Instruction.create_reg_reg(Code.SHA1NEXTE_XMM_XMMM128, R.XMM0, R.XMM2), st0, ret), + "undefined vector register xmm2"), + ("undef_xmm_dst_msg1", (ld1, Instruction.create_reg_reg(Code.SHA1MSG1_XMM_XMMM128, R.XMM3, R.XMM1), ret), + "undefined vector register xmm3"), + ("undef_xmm_src_msg2", (ld0, Instruction.create_reg_reg(Code.SHA1MSG2_XMM_XMMM128, R.XMM0, R.XMM4), st0, ret), + "undefined vector register xmm4"), + ("undef_xmm_store", (st0, ret), + "undefined vector register xmm0"), + ("unaligned_movdqa_load", (Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, displ=8, displ_size=1)), st0, ret), + "unaligned 16-byte memory operand"), + ("unaligned_movdqa_store", (ld0, Instruction.create_mem_reg(Code.MOVDQA_XMMM128_XMM, MemoryOperand(R.R8, displ=4, displ_size=1), R.XMM0), ret), + "unaligned 16-byte memory operand"), + ("unaligned_sha1_mem", (ld0, Instruction.create_reg_mem(Code.SHA1MSG1_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX, displ=8, displ_size=1)), st0, ret), + "unaligned 16-byte memory operand"), + ("displaced_movdqu", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, displ=16, displ_size=1)), st0, ret), + "unsupported displaced/out-of-buffer memory operand"), + ("displaced_movdqa_oob", (Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, displ=16, displ_size=1)), st0, ret), + "unsupported displaced/out-of-buffer memory operand"), + ("displaced_sha1_oob", (ld0, Instruction.create_reg_mem(Code.SHA1NEXTE_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX, displ=16, displ_size=1)), st0, ret), + "unsupported displaced/out-of-buffer memory operand"), + ("indexed_mem", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, index=R.RDX)), st0, ret), + "unsupported memory operand"), + ("rip_rel_mem", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RIP, displ=0x1100, displ_size=4)), st0, ret), + "unsupported memory operand"), + ("non_arg_base_rax", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RAX)), st0, ret), + "unsupported memory base"), + ("nonvol_base_rbx", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RBX)), st0, ret), + "nonvolatile GPR base"), + ("store_to_rcx", (ld0, Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.RCX), R.XMM0), ret), + "store outside output buffer r8"), + ("store_to_rdx_movdqa", (ld0_a, Instruction.create_mem_reg(Code.MOVDQA_XMMM128_XMM, MemoryOperand(R.RDX), R.XMM0), ret), + "store outside output buffer r8"), + ("prefix_segment_fs", (fs_ld, st0, ret), + "unsupported instruction prefix"), + ("prefix_rep_ret", (ld0, st0, rep_ret), + "unsupported instruction prefix"), + ("branch_jmp", (ld0, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), st0, ret), + "unsupported control-flow instruction"), + ("missing_ret", (ld0, ld1, Instruction.create_reg_reg(Code.SHA1MSG1_XMM_XMMM128, R.XMM0, R.XMM1), st0), + "missing terminal ret"), + ("trailing_after_ret", (ld0, st0, ret, ld0), + "unreachable instruction after ret"), + ] + for label, seq, reason in cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + return accepted, len(cases) + + +# --- Full NIST FIPS 180-4 SHA-1 compression driven through lifted DLL exports --- + +def _pack_be_lanes(w0, w1, w2, w3): + return _pack4(w3, w2, w1, w0) + + +def _unpack_be_lanes(buf): + w3, w2, w1, w0 = _unpack4(buf) + return (w0, w1, w2, w3) + + +def _xor16(a, b): + return bytes(x ^ y for x, y in zip(a, b)) + + +def sha1_digest_via_funcs(funcs, message, *, use_mem=False): + """Compute a full FIPS 180-4 SHA-1 digest using only the lifted SHA-1 NI exports.""" + suffix = "mem" if use_mem else "reg" + rnds4 = [funcs[f"op_sha1rnds4_{i}_{suffix}"] for i in range(4)] + nexte = funcs[f"op_sha1nexte_{suffix}"] + msg1 = funcs[f"op_sha1msg1_{suffix}"] + msg2 = funcs[f"op_sha1msg2_{suffix}"] + + bit_len = len(message) * 8 + padded = message + b"\x80" + padded += b"\x00" * ((56 - len(padded) % 64) % 64) + padded += struct.pack(">Q", bit_len) + + h0, h1, h2, h3, h4 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 + for off in range(0, len(padded), 64): + words = struct.unpack(">16I", padded[off:off + 64]) + msg = [_pack_be_lanes(*words[4 * i:4 * i + 4]) for i in range(4)] + for t in range(4, 20): + t1 = invoke(msg1, msg[t - 4], msg[t - 3]) + t2 = _xor16(t1, msg[t - 2]) + msg.append(invoke(msg2, t2, msg[t - 1])) + + abcd = _pack_be_lanes(h0, h1, h2, h3) + # Seed round 0 with H4 via SHA1NEXTE: rol32(rol32(h4, 2), 30) == h4. + e0_seed = _pack_be_lanes(_rol32(h4, 2), 0, 0, 0) + w0e = invoke(nexte, e0_seed, msg[0]) + prev_abcd = abcd + abcd = invoke(rnds4[0], abcd, w0e) + + for g in range(1, 20): + e_plus_w = invoke(nexte, prev_abcd, msg[g]) + prev_abcd = abcd + abcd = invoke(rnds4[g // 5], abcd, e_plus_w) + + a, b, c, d = _unpack_be_lanes(abcd) + h4_vec = invoke(nexte, prev_abcd, _pack_be_lanes(h4, 0, 0, 0)) + h0 = (h0 + a) & 0xFFFFFFFF + h1 = (h1 + b) & 0xFFFFFFFF + h2 = (h2 + c) & 0xFFFFFFFF + h3 = (h3 + d) & 0xFFFFFFFF + h4 = _unpack_be_lanes(h4_vec)[0] + + return struct.pack(">5I", h0, h1, h2, h3, h4).hex() + + +FIPS_180_4_VECTORS = ( + (b"", "da39a3ee5e6b4b0d3255bfef95601890afd80709"), + (b"abc", "a9993e364706816aba3e25717850c26c9cd0d89d"), + (b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1"), + ( + b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" + b"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "a49b2446a02c645bf419f995b67091253a04a259", + ), +) + + +def check_lifted_unconditional(lifted, altered_lifted, pairs): + """Run portable reference, NIST FIPS 180-4, aliasing, altered-build, and mutant checks on lifted DLLs.""" + total = 0 + for name in EXPORTS: + for index, (a, b) in enumerate(pairs): + want = reference(name, a, b) + got = invoke(lifted[name], a, b) + if got != want: + raise AssertionError( + f"lifted {name} case {index}: got {got.hex()}, expected {want.hex()} " + f"(a={a.hex()} b={b.hex()})" + ) + total += 1 + + # Unaligned buffers on movdqu-only exports. + a, b = pairs[4] + for name in UNALIGNED_SAFE_EXPORTS: + want = reference(name, a, b) + for mis in ((1, 0, 0), (0, 3, 0), (0, 0, 5), (7, 5, 3)): + got = invoke(lifted[name], a, b, a_misalign=mis[0], b_misalign=mis[1], out_misalign=mis[2]) + if got != want: + raise AssertionError(f"lifted {name} misalign {mis}: got {got.hex()}, expected {want.hex()}") + total += 1 + + # Aliasing checks: rcx==rdx, r8==rcx, r8==rdx, and all three aliased. + for name in ( + "op_sha1rnds4_0_reg", "op_sha1rnds4_2_mem", + "op_sha1nexte_reg", "op_sha1nexte_mem", + "op_sha1msg1_reg", "op_sha1msg1_mem", + "op_sha1msg2_reg", "op_sha1msg2_mem", + "op_sha1_pipeline", + ): + for mode in ("rcx==rdx", "r8==rcx", "r8==rdx", "all"): + ea, eb = (a, a) if mode in ("rcx==rdx", "all") else (a, b) + want = reference(name, ea, eb) + got = invoke_aliased(lifted[name], a, b, mode) + if got != want: + raise AssertionError(f"lifted {name} alias {mode}: got {got.hex()}, expected {want.hex()}") + total += 1 + + # Full NIST FIPS 180-4 SHA-1 digests through both reg and mem lifted exports. + for use_mem in (False, True): + for msg, expected_hex in FIPS_180_4_VECTORS: + assert hashlib.sha1(msg).hexdigest() == expected_hex + got_hex = sha1_digest_via_funcs(lifted, msg, use_mem=use_mem) + if got_hex != expected_hex: + raise AssertionError( + f"FIPS 180-4 SHA-1 (mem={use_mem}) on {msg!r}: got {got_hex}, expected {expected_hex}" + ) + total += 1 + + # Altered lifted build matches altered reference and diverges from original lifted. + for name in ALTERED_EXPORTS: + changed = 0 + for a_in, b_in in pairs[:24]: + orig = invoke(lifted[name], a_in, b_in) + alt = invoke(altered_lifted[name], a_in, b_in) + want_alt = reference(name, a_in, b_in, altered=True) + if alt != want_alt: + raise AssertionError(f"altered_lifted {name}: got {alt.hex()}, expected {want_alt.hex()}") + changed += alt != orig + if not changed: + raise AssertionError(f"altered_lifted did not diverge on {name}") + + # Faulty mutant models must disagree with lifted outputs on at least one pair. + def _mut_nexte_no_rol(x, y): + _, _, _, d3 = _unpack4(x) + s0, s1, s2, s3 = _unpack4(y) + return _pack4(s0, s1, s2, (s3 + d3) & 0xFFFFFFFF) + + def _mut_nexte_keep_dst_low(x, y): + d0, d1, d2, d3 = _unpack4(x) + _, _, _, s3 = _unpack4(y) + return _pack4(d0, d1, d2, (s3 + _rol32(d3, 30)) & 0xFFFFFFFF) + + def _mut_msg2_no_w16_dep(x, y): + d0, d1, d2, d3 = _unpack4(x) + s0, s1, s2, s3 = _unpack4(y) + return _pack4(_rol32(d0 ^ s3, 1), _rol32(d1 ^ s0, 1), _rol32(d2 ^ s1, 1), _rol32(d3 ^ s2, 1)) + + mutants = ( + ("op_sha1rnds4_0_reg", lambda x, y: ref_sha1rnds4(x, y, 1)), + ("op_sha1rnds4_1_reg", lambda x, y: ref_sha1rnds4(x, y, 2)), + ("op_sha1rnds4_2_reg", lambda x, y: ref_sha1rnds4(x, y, 3)), + ("op_sha1rnds4_3_reg", lambda x, y: ref_sha1rnds4(x, y, 0)), + ("op_sha1rnds4_0_reg", lambda x, y: ref_sha1rnds4(y, x, 0)), + ("op_sha1nexte_reg", _mut_nexte_no_rol), + ("op_sha1nexte_reg", _mut_nexte_keep_dst_low), + ("op_sha1msg1_reg", lambda x, y: ref_sha1msg2(x, y)), + ("op_sha1msg2_reg", _mut_msg2_no_w16_dep), + ("op_sha1_pipeline", lambda x, y: ref_sha1rnds4(x, y, 0)), + ) + for name, wrong in mutants: + diffs = sum(invoke(lifted[name], x, y) != wrong(x, y) for x, y in pairs[:32]) + if not diffs: + raise AssertionError(f"mutant on {name} agreed with lifted on every pair") + + return total, len(mutants) + + +def check_native_differential(native, lifted, altered, altered_lifted, pairs): + """Compare native SHA-NI hardware execution bit-for-bit against lifted DLLs.""" + total = 0 + for name in EXPORTS: + for index, (a, b) in enumerate(pairs): + nat = invoke(native[name], a, b) + lif = invoke(lifted[name], a, b) + if nat != lif: + raise AssertionError( + f"native vs lifted {name} case {index}: native={nat.hex()} lifted={lif.hex()}" + ) + total += 1 + + # Unaligned buffers on movdqu-only exports. + a, b = pairs[4] + for name in UNALIGNED_SAFE_EXPORTS: + for mis in ((1, 0, 0), (0, 3, 0), (0, 0, 5), (7, 5, 3)): + nat = invoke(native[name], a, b, a_misalign=mis[0], b_misalign=mis[1], out_misalign=mis[2]) + lif = invoke(lifted[name], a, b, a_misalign=mis[0], b_misalign=mis[1], out_misalign=mis[2]) + if nat != lif: + raise AssertionError(f"native vs lifted {name} misalign {mis}: native={nat.hex()} lifted={lif.hex()}") + total += 1 + + # Aliasing checks on native vs lifted. + for name in ( + "op_sha1rnds4_0_reg", "op_sha1rnds4_2_mem", + "op_sha1nexte_reg", "op_sha1nexte_mem", + "op_sha1msg1_reg", "op_sha1msg1_mem", + "op_sha1msg2_reg", "op_sha1msg2_mem", + "op_sha1_pipeline", + ): + for mode in ("rcx==rdx", "r8==rcx", "r8==rdx", "all"): + nat = invoke_aliased(native[name], a, b, mode) + lif = invoke_aliased(lifted[name], a, b, mode) + if nat != lif: + raise AssertionError(f"native vs lifted {name} alias {mode}: native={nat.hex()} lifted={lif.hex()}") + total += 1 + + # Altered build checks: altered lifted matches altered native and diverges from original native. + for name in ALTERED_EXPORTS: + changed = 0 + for a_in, b_in in pairs[:24]: + alt_nat = invoke(altered[name], a_in, b_in) + alt_lif = invoke(altered_lifted[name], a_in, b_in) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted={alt_lif.hex()} != native={alt_nat.hex()}") + orig_nat = invoke(native[name], a_in, b_in) + changed += alt_nat != orig_nat + if not changed: + raise AssertionError(f"altered native build did not diverge on {name}") + + return total + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + + accepted, rejected = check_translator() + print(f"{accepted} SHA-1 NI forms accepted; {rejected} rejection controls passed") + + lifted_lib, lifted = bind(lifted_path, "lifted_") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + pairs = all_pairs() + lifted_total, mutant_count = check_lifted_unconditional(lifted, altered_lifted, pairs) + print( + f"{lifted_total} portable reference / NIST FIPS 180-4 / aliasing checks on lifted DLLs passed; " + f"{mutant_count} mutant controls + {len(ALTERED_EXPORTS)} altered-build controls caught" + ) + + if not host_has_sha(lifted_lib): + print("Host lacks CPUID.07H.00H:EBX[29] (SHA-NI); skipping native differential check") + sys.exit(77) + + _, native = bind(original_path, "") + _, altered = bind(altered_path, "") + native_total = check_native_differential(native, lifted, altered, altered_lifted, pairs) + print(f"{native_total} native vs lifted SHA-NI differential cases matched bit for bit") + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_sha1_aot.py b/tools/cpu_sha1_aot.py new file mode 100644 index 000000000..5640fa5c4 --- /dev/null +++ b/tools/cpu_sha1_aot.py @@ -0,0 +1,390 @@ +"""Lift bounded Windows x64 leaf functions using Intel SHA-1 NI instructions to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned 16-byte buffers +(rcx and rdx are inputs, r8 is the output/scratch). XMM0..XMM5 are modeled as +portable 128-bit value structs (four 32-bit lanes, pure portable C++ without +). Only legacy encodings are accepted; VEX, EVEX, and other +non-legacy encodings are rejected. + +Supported SHA-1 NI instructions (docs/coverage/x64_zen2.tsv group Crypto): + - SHA1RNDS4 xmm1, xmm2/m128, imm8 (NP 0F 3A CC /r ib): four SHA-1 rounds; + imm8[1:0] selects f0 Ch + 0x5A827999, f1 Parity + 0x6ED9EBA1, + f2 Maj + 0x8F1BBCDC, f3 Parity + 0xCA62C1D6 (imm8[7:2] ignored) + - SHA1NEXTE xmm1, xmm2/m128 (NP 0F 38 C8 /r): add rol32(dst[3], 30) + to src[3] and copy src[2:0] + - SHA1MSG1 xmm1, xmm2/m128 (NP 0F 38 C9 /r): first SHA-1 message + schedule step + - SHA1MSG2 xmm1, xmm2/m128 (NP 0F 38 CA /r): second SHA-1 message + schedule step + +Transport / ABI glue: + - movdqu (128-bit flat [rcx|rdx|r8] load, [r8] store, reg-reg copy) + - movdqa (16-byte-aligned flat [rcx|rdx|r8] load, [r8] store, reg-reg copy) + - terminal ret + +SHA-256 instructions, VEX/EVEX encodings, nonvolatile XMM6..XMM15, undefined +XMM reads, unaligned movdqa, non-flat/displaced/indexed/out-of-buffer memory, +stores outside [r8], instruction prefixes, branches, missing ret, and trailing +instructions after ret are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +SHA1_BINARY_CODES = { + Code.SHA1NEXTE_XMM_XMMM128: "op_sha1nexte", + Code.SHA1MSG1_XMM_XMMM128: "op_sha1msg1", + Code.SHA1MSG2_XMM_XMMM128: "op_sha1msg2", +} + +SHA256_REJECT_CODES = { + Code.SHA256RNDS2_XMM_XMMM128, + Code.SHA256MSG1_XMM_XMMM128, + Code.SHA256MSG2_XMM_XMMM128, +} + +LOAD_CODES = { + Code.MOVDQU_XMM_XMMM128: False, + Code.MOVDQA_XMM_XMMM128: True, +} + +STORE_CODES = { + Code.MOVDQU_XMMM128_XMM: False, + Code.MOVDQA_XMMM128_XMM: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.SHA1RNDS4_XMM_XMMM128_IMM8, + *SHA1_BINARY_CODES, + *LOAD_CODES, + *STORE_CODES, +} + + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_sha() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast(info[1]) & (1u << 29)) != 0u ? 1u : 0u; +} +#endif + +using word = std::uint64_t; + +struct Vec128 { + std::uint32_t w[4]; +}; + +// Guest reads can fault even when the translated result is dead. Keep surrounding guest +// writes on their original side of the read when the compiler inlines these helpers. +static inline Vec128 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + Vec128 out{}; + std::memcpy(out.w, reinterpret_cast(address), sizeof(out.w)); + const volatile Vec128 observed = out; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{observed.w[0], observed.w[1], observed.w[2], observed.w[3]}}; +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.w, sizeof(v.w)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint32_t rol32(std::uint32_t x, unsigned n) { + return (x << n) | (x >> (32u - n)); +} + +static inline Vec128 op_sha1rnds4(const Vec128& dst, const Vec128& src, unsigned imm8) { + std::uint32_t a = dst.w[3]; + std::uint32_t b = dst.w[2]; + std::uint32_t c = dst.w[1]; + std::uint32_t d = dst.w[0]; + std::uint32_t e = 0u; + const std::uint32_t w[4] = {src.w[3], src.w[2], src.w[1], src.w[0]}; + const unsigned sel = imm8 & 3u; + const std::uint32_t k = (sel == 0u) ? 0x5a827999u + : (sel == 1u) ? 0x6ed9eba1u + : (sel == 2u) ? 0x8f1bbcdcu + : 0xca62c1d6u; + for (unsigned i = 0u; i < 4u; ++i) { + const std::uint32_t f = (sel == 0u) ? ((b & c) ^ (~b & d)) + : (sel == 2u) ? ((b & c) ^ (b & d) ^ (c & d)) + : (b ^ c ^ d); + const std::uint32_t next_a = f + rol32(a, 5u) + w[i] + k + e; + e = d; + d = c; + c = rol32(b, 30u); + b = a; + a = next_a; + } + return {{d, c, b, a}}; +} + +static inline Vec128 op_sha1nexte(const Vec128& dst, const Vec128& src) { + return {{ + src.w[0], + src.w[1], + src.w[2], + src.w[3] + rol32(dst.w[3], 30u), + }}; +} + +static inline Vec128 op_sha1msg1(const Vec128& dst, const Vec128& src) { + return {{ + dst.w[0] ^ src.w[2], + dst.w[1] ^ src.w[3], + dst.w[2] ^ dst.w[0], + dst.w[3] ^ dst.w[1], + }}; +} + +static inline Vec128 op_sha1msg2(const Vec128& dst, const Vec128& src) { + const std::uint32_t w16 = rol32(dst.w[3] ^ src.w[2], 1u); + const std::uint32_t w17 = rol32(dst.w[2] ^ src.w[1], 1u); + const std::uint32_t w18 = rol32(dst.w[1] ^ src.w[0], 1u); + const std::uint32_t w19 = rol32(dst.w[0] ^ w16, 1u); + return {{w19, w18, w17, w16}}; +} +""" + + +def vec_index(register, ins): + """Map volatile XMM0..XMM5 to an index, rejecting nonvolatile and unsupported registers.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, aligned=False, store=False): + """Lower a flat zero-displacement 16-byte [rcx|rdx|r8] memory operand.""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported memory base {base} at RVA {ins.ip:#x}: {ins}") + if MemorySizeExt.size(ins.memory_size) != 16: + raise ValueError(f"unsupported memory width at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"store outside output buffer r8 at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & ((1 << 64) - 1) + if aligned and disp % 16 != 0: + raise ValueError(f"unaligned 16-byte memory operand at RVA {ins.ip:#x}: {ins}") + if disp != 0: + raise ValueError(f"unsupported displaced/out-of-buffer memory operand at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line SHA-1 NI leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + if idx not in defined: + raise ValueError(f"undefined vector register xmm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"xmm{idx}" + + def write_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + used.add(idx) + return idx, f"xmm{idx}" + + def vec_src128(op_index, ins, *, aligned=False): + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load128({flat_address(ins, aligned=aligned, store=False)})" + return read_vec(op_index, ins) + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ( + ins.has_lock_prefix + or ins.has_rep_prefix + or ins.has_repne_prefix + or ins.has_segment_prefix + or ins.has_xacquire_prefix + or ins.has_xrelease_prefix + ): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + op_code = ins.op_code() + if ( + op_code.encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding != EncodingKind.LEGACY: + raise ValueError(f"unsupported non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code in SHA256_REJECT_CODES: + raise ValueError(f"unsupported SHA-256 instruction at RVA {ins.ip:#x}: {ins}") + if ins.flow_control not in (FlowControl.NEXT, FlowControl.RETURN): + raise ValueError(f"unsupported control-flow instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + + elif ins.code == Code.SHA1RNDS4_XMM_XMMM128_IMM8: + dst = read_vec(0, ins) + src = vec_src128(1, ins, aligned=True) + dst_idx, dst_name = write_vec(0, ins) + imm8 = ins.immediate8 & 0xFF + statements.append(f"{dst_name} = op_sha1rnds4({dst}, {src}, {imm8:#x}u);") + defined.add(dst_idx) + + elif ins.code in SHA1_BINARY_CODES: + dst = read_vec(0, ins) + src = vec_src128(1, ins, aligned=True) + dst_idx, dst_name = write_vec(0, ins) + helper = SHA1_BINARY_CODES[ins.code] + statements.append(f"{dst_name} = {helper}({dst}, {src});") + defined.add(dst_idx) + + elif ins.code in LOAD_CODES: + aligned = LOAD_CODES[ins.code] + src = vec_src128(1, ins, aligned=aligned) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + + elif ins.code in STORE_CODES: + aligned = STORE_CODES[ins.code] + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, aligned=aligned, store=True) + statements.append(f"store128({addr}, {src});") + else: + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec128 xmm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, args.exports.split(",")) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From 5df7424dc51f0478f8a18404677485b4bfed6490 Mon Sep 17 00:00:00 2001 From: RenzoWit35 <168984533+RenzoWit35@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:46:17 +0100 Subject: [PATCH 039/232] tooling: scan Zig, SPIR-V assembly and assembler sources in the bidi controls check (#1534) * tooling: scan every tracked text file in the bidi controls check in_scope used a suffix allowlist, so tests/cpu/archive/*.zig, tests/spirv_window/*.spvasm, tools/patches/*.patch and the .tsv, .json, .svg, .txt, LICENSE* files were never scanned. Scan every tracked file except Markdown (documented as out of scope) and .png images. The self test gains .zig, .spvasm, .patch, .tsv and .png cases. * tooling: keep the bidi check to source kinds and add Zig, SPIR-V and .s Review feedback: the check keeps the #254 boundary of source files, scripts and build/CI configuration. Restore the suffix allowlist and add the source kinds it omitted: .zig, .spvasm and .s (assembler sources, like the .asm already listed). Data tables, images, licence files and other tracked inputs stay out of scope, as before. The self-test reuses its existing synthetic controls for the three new kinds and asserts that a .tsv data table is not scanned. --- tests/bidi_controls_check.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/bidi_controls_check.py b/tests/bidi_controls_check.py index 3ba1cf387..cca62cfee 100644 --- a/tests/bidi_controls_check.py +++ b/tests/bidi_controls_check.py @@ -18,7 +18,7 @@ CONTROLS = frozenset([0x061C, *range(0x202A, 0x202F), *range(0x2066, 0x206A)]) SOURCE_SUFFIXES = frozenset({ ".asm", ".c", ".cc", ".cpp", ".cxx", ".def", ".h", ".hh", ".hlsl", ".hlsli", ".hpp", ".inc", - ".inl", ".py", # sources + ".inl", ".py", ".s", ".spvasm", ".zig", # sources ".bat", ".cmd", ".ps1", ".psm1", ".sh", # scripts ".cmake", # build scripts }) @@ -64,18 +64,26 @@ def self_test(): "tests/isolate.cpp": f"int x = 0;\r\n\x0cint z = 0;{isolate}\r\n", "tests/ordinary.cpp": "// 64×64 texels, café, naïve – ≡\nint y = 0;\n", "docs/notes.md": f"Markdown is out of scope {override}\n", + "docs/coverage/table.tsv": f"a data table is out of scope\t{override}\n", "CMakeLists.txt": "project(sample)\n", ".github/workflows/ci.yml": f"name: ci{override}\n", "tools/mark.py": f"label = 'r\u00e9sum\u00e9{arabic_letter_mark}'\n", + # Zig, SPIR-V assembly and assembler sources are source files like the ones above. + "tests/cpu/archive/reader.zig": f"const a = 1;{override}\n", + "tests/spirv_window/case.spvasm": f"; note\n%1 = OpTypeVoid {isolate}\n", + "tests/kernel.s": f"s_mov_b32 s0, 0{arabic_letter_mark}\n", } for name, text in files.items(): (root / name).parent.mkdir(parents=True, exist_ok=True) (root / name).write_bytes(text.encode("utf-8")) # exact bytes, no newline translation scoped = [name for name in files if in_scope(name)] - assert "docs/notes.md" not in scoped + assert "docs/notes.md" not in scoped and "docs/coverage/table.tsv" not in scoped assert list(findings(root, scoped)) == [ ".github/workflows/ci.yml:1: U+202E RIGHT-TO-LEFT OVERRIDE", + "tests/cpu/archive/reader.zig:1: U+202E RIGHT-TO-LEFT OVERRIDE", "tests/isolate.cpp:2: U+2066 LEFT-TO-RIGHT ISOLATE", + "tests/kernel.s:1: U+061C ARABIC LETTER MARK", + "tests/spirv_window/case.spvasm:2: U+2066 LEFT-TO-RIGHT ISOLATE", "tools/hidden.py:2: U+202E RIGHT-TO-LEFT OVERRIDE", "tools/mark.py:1: U+061C ARABIC LETTER MARK", ], list(findings(root, scoped)) From 14ad1074d2347a2f297721e6a37024d71a4051de Mon Sep 17 00:00:00 2001 From: SuperCraft3M <69873238+SuperCraft3M@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:46:55 +0100 Subject: [PATCH 040/232] startup: forward command-list UAV barriers in slot 26 (#2384) --- CMakeLists.txt | 3 ++ docs/startup-runtime.md | 17 +++++++++- src/startup_stubs/command_list_slot_names.h | 6 ++-- src/startup_stubs/d3d12_xs_device.cpp | 35 +++++++++++++++++++++ tests/startup_command_list_slot_names.cpp | 7 +++-- tests/startup_present_producer.cpp | 26 +++++++++++++-- tests/startup_present_producer_check.py | 13 ++++++-- 7 files changed, 97 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9ff30b04c..c21ed2e91 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -630,6 +630,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_present_producer_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_present_producer_check.py" "${backend}" "$") set_tests_properties(startup_present_producer_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 90) + add_test(NAME startup_list_uav_barriers_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_present_producer_check.py" "${backend}" "$" barriers) + set_tests_properties(startup_list_uav_barriers_${backend} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endforeach() endif() add_executable(startup_placement_alloc tests/startup_placement_alloc.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index cae08ccae..82c945d3f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -31,10 +31,25 @@ records. The control expects the first blend patch to win and must fail. Command-list slot 24 (`OMSetStencilRef`, the desktop slot) passes its reference to the desktop list, as slots 21 to 23 do for viewports, scissors and the blend factor, so a translated draw whose pipeline enables the stencil test compares against it. A closed list ignores the call. The slot number is the desktop one and has not been seen in a title log; `startup_stream_depth_{warp,hardware}` checks the references 0x5A, 0x5B, 0 and 0xFF against a stencil cleared to the matching value. +## Command-list UAV barriers + +Render-mode slot 26 forwards unflagged UAV barriers on an open direct or compute list. A null +resource orders UAV accesses across resources. A named resource must be a wrapper around a local +desktop resource with UAV access. Transition and aliasing records are skipped because desktop +resource states and heap aliases are managed by the shim. The slot returns zero console actions. +The console slot and record layout are also documented by the +[ztrx command-list implementation](https://github.com/Zettrox/ztrx/blob/90b529f878a470fec9bf07b7be316bc769a12232/crates/victory-gpu/src/list.rs). + +Build `startup_present_producer` and run +`ctest --preset release --no-tests=error -R '^startup_list_uav_barriers_(warp|hardware)$' -V`. +The source-built caller submits both supported forms and checks the forwarding log, with refusal +controls for other barrier types, flagged barriers, invalid resources and arrays, and closed lists. + ## Occlusion queries Which console methods sit at command-list slots 28 to 30 is not established by any fixture here. The repository -shows only that four console methods sit in 26 to 31 (32 is `SetDescriptorHeaps`, desktop 28 plus four) and that +places `ResourceBarrier` at 26 and four additional console methods in the 26 to 31 range +(32 is `SetDescriptorHeaps`, desktop 28 plus four). It also shows that the plus-four run has ended by 61 (`ExecuteIndirect`, desktop 59 plus two). As a hypothesis, slots 28 to 30 are implemented as `BeginQuery(heap, type, index)`, `EndQuery(heap, type, index)` and `ResolveQueryData(heap, type, start, count, buffer, offset)`. Because that is a hypothesis, the bindings are a diff --git a/src/startup_stubs/command_list_slot_names.h b/src/startup_stubs/command_list_slot_names.h index 459026157..472ef6315 100644 --- a/src/startup_stubs/command_list_slot_names.h +++ b/src/startup_stubs/command_list_slot_names.h @@ -9,7 +9,8 @@ // the slots between them (0 to 6, 8, 14 to 19, 24) take the desktop names. // - Slots 10 and 11 are not named. The desktop order puts Reset and ClearState there, but this // console list resets through slot 139, so the desktop order is not known to hold at 10 and 11. -// - Slots 26 to 31 are not named here. The slots that follow are the desktop ones moved up by four +// - Slot 26 accepts the UAV form of ResourceBarrier. Slots 27 to 31 are not named here. The slots +// that follow are the desktop ones moved up by four // (32 is SetDescriptorHeaps, desktop 28), so four console methods sit somewhere in 26 to 31. // As a hypothesis, d3d12_xs_device.cpp binds 28, 29 and 30 as BeginQuery, EndQuery and // ResolveQueryData, only with the diagnostic X2W_D3D12_QUERY_SLOTS=1. No fixture here establishes @@ -45,6 +46,7 @@ inline constexpr int desktop_method_count = static_cast(sizeof(desktop_name static_assert(desktop_method_count == 51, "ID3D12GraphicsCommandList has 51 methods of its own"); inline constexpr int console_shift = 4; // console slot = desktop slot + 4, from SetDescriptorHeaps on +inline constexpr int resource_barrier_slot = 26; inline constexpr int first_shifted_slot = 32; inline constexpr int last_shifted_slot = 59; inline constexpr int execute_indirect_slot = 61; @@ -57,7 +59,7 @@ inline const char* name(int slot) noexcept static constexpr const char* iunknown[] = {"QueryInterface", "AddRef", "Release", "GetPrivateData", "SetPrivateData", "SetPrivateDataInterface", "SetName", "GetDevice", "GetType"}; if (slot >= 0 && slot < first_desktop_method) return iunknown[slot]; - if (slot == first_desktop_method || (slot >= 12 && slot <= 25)) return desktop(slot); + if (slot == first_desktop_method || (slot >= 12 && slot <= resource_barrier_slot)) return desktop(slot); if (slot >= first_shifted_slot && slot <= last_shifted_slot) return desktop(slot - console_shift); if (slot == execute_indirect_slot) return "ExecuteIndirect"; if (slot == reset_slot) return "Reset"; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 5130f0f3c..c91e818b2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2385,6 +2385,40 @@ void __stdcall list_pipeline(Wrapper* self, void* pipeline) if (auto* list = recording(self); list && pass.pipeline_real) list->SetPipelineState(static_cast(w->own().real)); } // List slot 33 (desktop 29 + 4), SetComputeRootSignature. +// Slot 26: the console's UAV records have the desktop layout, with wrapped resource pointers. +// Desktop transitions are owned by the shim, so the other barrier types are left unhandled. +UINT __stdcall list_resource_barriers(Wrapper* self, UINT count, const D3D12_RESOURCE_BARRIER* barriers) +{ + static_assert(sizeof(D3D12_RESOURCE_BARRIER) == 32); + UINT forwarded = 0; + auto* list = recording(self); + const auto type = list ? list->GetType() : D3D12_COMMAND_LIST_TYPE_COPY; + if ((type == D3D12_COMMAND_LIST_TYPE_DIRECT || type == D3D12_COMMAND_LIST_TYPE_COMPUTE) && + count && barriers && x2w_local::readable(barriers, std::size_t{count} * sizeof(*barriers))) { + for (UINT i = 0; i < count; ++i) { + D3D12_RESOURCE_BARRIER barrier; + std::memcpy(&barrier, barriers + i, sizeof(barrier)); + if (barrier.Type != D3D12_RESOURCE_BARRIER_TYPE_UAV || barrier.Flags != D3D12_RESOURCE_BARRIER_FLAG_NONE) + continue; + if (barrier.UAV.pResource) { + Wrapper* resource = as_wrapper(barrier.UAV.pResource); + if (!resource || resource->own().kind != resource_kind || !resource->own().real) continue; + auto* real = static_cast(resource->own().real); + if (!(real->GetDesc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) continue; + Microsoft::WRL::ComPtr owner; + if (FAILED(real->GetDevice(IID_PPV_ARGS(&owner))) || owner.Get() != device_of(self->own().list_device)) continue; + barrier.UAV.pResource = real; + } + list->ResourceBarrier(1, &barrier); + ++forwarded; + } + } + static LONG reports; + if (count && first_calls(reports, 8)) + log("x2w-d3d12 CommandList::slot26(ResourceBarrier): forwarded=%u refused=%u", forwarded, count - forwarded); + return 0; // no console barrier actions to perform on the caller's side +} + void __stdcall list_compute_root(Wrapper* self, void* root) { auto* list = recording(self); @@ -4905,6 +4939,7 @@ void build_tables() list_typed[23] = reinterpret_cast(&list_blend_factor); list_typed[24] = reinterpret_cast(&list_stencil_ref); list_typed[25] = reinterpret_cast(&list_pipeline); + list_typed[x2w_list_slots::resource_barrier_slot] = reinterpret_cast(&list_resource_barriers); list_typed[32] = reinterpret_cast(&list_set_descriptor_heaps); list_typed[33] = reinterpret_cast(&list_compute_root); list_typed[34] = reinterpret_cast(&list_graphics_root); diff --git a/tests/startup_command_list_slot_names.cpp b/tests/startup_command_list_slot_names.cpp index c3d433634..a7e060244 100644 --- a/tests/startup_command_list_slot_names.cpp +++ b/tests/startup_command_list_slot_names.cpp @@ -41,6 +41,7 @@ int main() {22, "RSSetScissorRects"}, {23, "OMSetBlendFactor"}, {25, "SetPipelineState"}, + {26, "ResourceBarrier"}, {32, "SetDescriptorHeaps"}, {34, "SetGraphicsRootSignature"}, {36, "SetGraphicsRootDescriptorTable"}, @@ -82,9 +83,9 @@ int main() expect(is(59, "SetPredication"), "slot 59 is the desktop slot 55 plus four"); // Slots that are not known stay unnamed: a name there would be a guess. - // 10 and 11: this console list resets through 139. 26 to 31: four console methods sit in this range. + // 10 and 11: this console list resets through 139. 27 to 31: the remaining unconfirmed methods before the shift. // Other slots from 60 up have unconfirmed meanings. -1 and 4096: outside the table. - std::vector unknown = {10, 11, 26, 27, 28, 29, 30, 31, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, + std::vector unknown = {10, 11, 27, 28, 29, 30, 31, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, 131, 132, 138, 140, 142, 146, 255, 256, 999, 4096, -1, -100}; for (const int slot : unknown) expect(x2w_list_slots::name(slot) == nullptr, "slot " + std::to_string(slot) + " has no name"); @@ -97,7 +98,7 @@ int main() for (const std::string& earlier : seen) expect(earlier != got, std::string("the name ") + got + " is used once"); seen.push_back(got); } - expect(seen.size() == 10 + 14 + 28 + 2, "the named slots are 0 to 9, 12 to 25, 32 to 59, 61 and 139"); + expect(seen.size() == 10 + 15 + 28 + 2, "the named slots are 0 to 9, 12 to 26, 32 to 59, 61 and 139"); if (failures) { std::fprintf(stderr, "%d check(s) failed\n", failures); diff --git a/tests/startup_present_producer.cpp b/tests/startup_present_producer.cpp index bd7b30915..32f6fe0b6 100644 --- a/tests/startup_present_producer.cpp +++ b/tests/startup_present_producer.cpp @@ -29,6 +29,7 @@ int main(int argc, char** argv) const bool reverse = argc >= 2 && std::strcmp(argv[1], "reverse") == 0; const bool use_magenta = argc >= 2 && std::strcmp(argv[1], "auto-magenta") == 0; const bool automatic = use_magenta || (argc >= 2 && std::strcmp(argv[1], "auto") == 0); + const bool barriers = argc >= 2 && std::strcmp(argv[1], "barriers") == 0; const bool hardware = argc == 3 && std::strcmp(argv[2], "hardware") == 0; ComPtr debug; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) debug->EnableDebugLayer(); @@ -108,8 +109,29 @@ int main(int argc, char** argv) call(queue, 10, 1, arg(lists)); return finish(); }; - if (!emit(automatic ? chosen : blue) || !present()) return 8; // discover the title's present surface - if (automatic) { + if (barriers) { + D3D12_RESOURCE_DESC uav_desc = desc; + uav_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + void* uav = nullptr; + if (FAILED(slot(device, 27)(device, &properties, D3D12_HEAP_FLAG_NONE, &uav_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, __uuidof(ID3D12Resource), &uav)) || + !uav || !ok(call(list, 139, arg(allocator)))) return 15; + D3D12_RESOURCE_BARRIER records[7]{}; + records[0].Type = records[2].Type = records[3].Type = records[4].Type = records[5].Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + records[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + records[2].UAV.pResource = static_cast(uav); + records[3].UAV.pResource = static_cast(target); // lacks UAV access + records[4].UAV.pResource = reinterpret_cast(1); // unrecognized wrapper + records[5].Flags = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY; + records[6].Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; + if (call(list, 26, std::size(records), arg(records)) != 0 || call(list, 26, 1, 1) != 0 || + !ok(call(list, 9)) || call(list, 26, 1, arg(records)) != 0) return 16; + void* lists[]{list}; + call(queue, 10, 1, arg(lists)); + if (!finish()) return 17; + } else if (!emit(automatic ? chosen : blue) || !present()) { + return 8; // discover the title's present surface + } else if (automatic) { // #1 matches too early; #3 changes color, #4 almost matches and #5 matches again. // The delayed sample at #6 arms #7 and #8, then a blue write at #9 is out of range. if (!present() || !emit(use_magenta ? red : green) || !present() || !emit(use_magenta ? near_magenta : near_red) || !present() || diff --git a/tests/startup_present_producer_check.py b/tests/startup_present_producer_check.py index a6bfd4de0..9307ffcdd 100644 --- a/tests/startup_present_producer_check.py +++ b/tests/startup_present_producer_check.py @@ -5,7 +5,7 @@ import sys RED, GREEN, BLUE, MAGENTA = "255,0,0,255", "0,255,0,255", "0,0,255,255", "255,0,255,255" -BACKEND, EXECUTABLE = sys.argv[1:] +BACKEND, EXECUTABLE, *OPTIONS = sys.argv[1:] def run(mode, rgb=""): @@ -52,7 +52,16 @@ def check_auto(magenta=False): print(f"auto {rgb} control: excludes early and near matches and compares paired samples within the armed window ({adapter})") -if __name__ == "__main__": +def check_barriers(): + logs, _, adapter = run("barriers") + records = re.findall(r"CommandList::slot26\(ResourceBarrier\): forwarded=(\d+) refused=(\d+)", logs) + assert records == [("2", "5"), ("0", "1"), ("0", "1")], logs + print(f"slot 26: forwarded global and resource UAV barriers, refused five unsupported records, an unreadable array and a closed list ({adapter})") + + +if __name__ == "__main__" and OPTIONS == ["barriers"]: + check_barriers() +elif __name__ == "__main__": check(False) check(True) check_auto() From 0a209667385bee03c0b46f32ad2efa1c4da3af4d Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 22:47:08 +0800 Subject: [PATCH 041/232] shader: lower scalar-offset returning compute atomic adds (#2382) --- docs/experiments.md | 8 +- tests/startup_compute_buffer_atomics_check.py | 80 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 26 +++--- 3 files changed, 101 insertions(+), 13 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 3468293bb..a3c2954a6 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13655,7 +13655,13 @@ register or aligned immediate, and aligned 12-bit `offset` rounded down by `glc` writes the pre-atomic word back to `vdata[0]` (preserving `vdata[1]` on `cmpswap`, which reverses the ISA `(replacement, compare)` register pair to HLSL's `(compare, replacement)` order). `buffer_atomic_sub` emits `InterlockedAdd(a, (0u - val))`, -and `smin`/`smax` use signed `asint` overloads. `idxen`, missing `offen`, `slc`/`dlc`, +and `smin`/`smax` use signed `asint` overloads. +Returning `buffer_atomic_add` also accepts `off` with a scalar byte offset +register. The fixture increments separate counters at scalar offsets 0 and 32 +with immediate offsets 0 and 4, and records the returned old values. +Each readback compares all 320 words, including the untouched guards. +Dropping either offset, the old-value return, or the observer store changes +the expected output. `idxen`, other scalar-only forms, `slc`/`dlc`, unaligned immediate offsets, modified or aliased descriptors, non-compute stages, and `inc`/`dec`/float/64-bit forms stay refused. diff --git a/tests/startup_compute_buffer_atomics_check.py b/tests/startup_compute_buffer_atomics_check.py index e807c3cb1..4bbb3a0c8 100644 --- a/tests/startup_compute_buffer_atomics_check.py +++ b/tests/startup_compute_buffer_atomics_check.py @@ -223,6 +223,47 @@ def exchange_bytes(): EXCHANGE_BYTES = exchange_bytes() +# Two single-lane groups address separate counters 32 bytes apart. Each stores +# the GLC return with bit zero flipped so a missing observer store differs +# from the initial sentinel in the word 64 bytes past its base. +SOFFSET_SOURCE = '''\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx4 s[16:19], s[10:11], 32 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s13, s7, 5 +v_mov_b32 v1, s13 +v_add_nc_u32 v4, 7, v1 +buffer_atomic_add v4, off, s[16:19], s13{immediate} glc +s_waitcnt vmcnt(0) +v_xor_b32 v4, 1, v4 +buffer_store_dword v4, v1, s[16:19], 0 offen offset:64 +s_endpgm +''' + + +def soffset_code(immediate): + return (HEAD + + bytes.fromhex('07850d8f 0d02027e') # s_lshl_b32 s13, s7, 5; v_mov_b32 v1, s13 + + vop2(0x25, 4, 0x87, 1) # v_add_nc_u32 v4, 7, v1 + + mubuf(0x32, 4, 0, 16, 13, offen=False, offset=immediate, glc=True) + + bytes.fromhex('703f8cbf') # s_waitcnt vmcnt(0) + + vop2(0x1d, 4, 0x81, 4) # v_xor_b32 v4, 1, v4 + + mubuf(0x1c, 4, 1, 16, 0x80, offset=64) + + bytes.fromhex('000081bf')) + + +def soffset_pipe(immediate): + return cs_pipe(soffset_code(immediate), rsrc2=USER7 | (1 << 7)) + + +def soffset_reference(immediate): + out = [SENTINEL] * WORDS + for soffset in (0, 32): + out[(soffset + immediate) // 4] = (SENTINEL + 7 + soffset) & MASK + out[(soffset + 64) // 4] = SENTINEL ^ 1 + return out + def reduce_reference(): out = [SENTINEL] * WORDS @@ -309,6 +350,16 @@ def controls(llvm_mc): assert 'u0.InterlockedCompareExchange(a, v8, v7, ao);' in exch_hlsl assert 'v7 = ao;' in exch_hlsl and 'v8 = ao;' not in exch_hlsl, exch_hlsl + for immediate in (0, 4): + pipe = soffset_pipe(immediate) + if llvm_mc: + modifier = f' offset:{immediate}' if immediate else '' + assert soffset_code(immediate) == assemble(llvm_mc, SOFFSET_SOURCE.format(immediate=modifier)) + hlsl = pipe.hlsl_cs() + assert f'a = (s13 + {immediate}) & 0xfffffffcu;' in hlsl + assert 'u0.InterlockedAdd(a, v4, ao);' in hlsl and 'v4 = ao;' in hlsl + assert pipe.manifest().splitlines()[-1] == 'uav 0 table 1 32', pipe.manifest() + # Individual opcodes with and without glc, plus llvm-mc byte checks. for op_name, (opcode, width, method) in ATOMIC_OPCODES.items(): data_tok = 'v[2:3]' if width == 2 else 'v2' @@ -335,8 +386,13 @@ def controls(llvm_mc): refused('unaligned immediate offset', lambda: cs_pipe(single_atomic_code('add', offset=2))) refused('unaligned immediate offset', lambda: cs_pipe(single_atomic_code('add', offset=1))) - # Refused modifiers, missing offen, bad data/soffset ranges, modified/aliased descriptors, non-cs stages. + # The off variant is limited to add + glc + a scalar register, with the same offset and modifier checks. refused('without the offen address form', lambda: cs_pipe(single_atomic_code('add', offen=False))) + refused('without the offen address form', lambda: cs_pipe(single_atomic_code('sub', offen=False, glc=True, soffset_enc=13))) + refused('off requires a scalar register soffset', lambda: cs_pipe(single_atomic_code('add', offen=False, glc=True))) + refused('unaligned immediate offset', lambda: soffset_pipe(2)) + refused('buffer atomic modifier idxen', lambda: cs_pipe(single_atomic_code('add', offen=False, idxen=True, glc=True, soffset_enc=13))) + refused('buffer soffset vcc_lo', lambda: cs_pipe(single_atomic_code('add', offen=False, glc=True, soffset_enc=0x6a))) refused('buffer atomic modifier idxen', lambda: cs_pipe(single_atomic_code('add', idxen=True))) refused('buffer atomic modifier idxen', lambda: cs_pipe(single_atomic_code('add', idxen=True, offen=True))) refused('buffer atomic modifier slc', lambda: cs_pipe(single_atomic_code('add', slc=True))) @@ -367,7 +423,7 @@ def controls(llvm_mc): refused(f'buffer_atomic_{op_name}', lambda op=opcode: cs_pipe( HEAD + v_mov_imm(0, 0) + v_mov_imm(2, 1) + mubuf(op, 2, 0, 16, 0x80) + bytes.fromhex('000081bf') )) - print('buffer_atomic controls (11 ops, glc/non-glc, alignment, modifiers, descriptors, refusals) passed') + print('buffer_atomic controls (11 ops, scalar byte offset, glc/non-glc, alignment, modifiers, descriptors, refusals) passed') def run_case(directory, compiler, renderer, adapter, name, hlsl, groups, want): @@ -396,6 +452,26 @@ def dispatch(directory, compiler, renderer, adapter): res = run_case(directory, compiler, renderer, adapter, 'exchange_glc_exec_cmpswap', exch_hlsl, (1, 1, 1), exch_want) assert res.returncode == 0 and f'compared_words={WORDS} mismatches=0' in res.stdout, (res.stdout, res.stderr) + for immediate in (0, 4): + hlsl = soffset_pipe(immediate).hlsl_cs() + want = soffset_reference(immediate) + res = run_case(directory, compiler, renderer, adapter, f'soffset_add_{immediate}', hlsl, (2, 1, 1), want) + assert res.returncode == 0 and f'compared_words={WORDS} mismatches=0' in res.stdout, (res.stdout, res.stderr) + + hlsl = soffset_pipe(4).hlsl_cs() + want = soffset_reference(4) + mutations = ( + ('dropped_soffset', 'a = (s13 + 4)', 'a = 4', 1, (SENTINEL + 7 + 39) & MASK), + ('dropped_immediate', 'a = (s13 + 4)', 'a = (s13 + 0)', 0, (SENTINEL + 7) & MASK), + ('dropped_soffset_glc_return', 'v4 = ao;', '', 16, 7 ^ 1), + ('dropped_soffset_observer_store', 'u0.Store(a, v4);', '', 16, SENTINEL), + ) + for name, original, replacement, word, value in mutations: + assert hlsl.count(original) == 1 + result = run_case(directory, compiler, renderer, adapter, name, hlsl.replace(original, replacement), (2, 1, 1), want) + assert result.returncode == 1 and f'word={word} expected={want[word]:08x} actual={value:08x}' in result.stderr, ( + name, result.returncode, result.stdout, result.stderr) + # Negative controls on GPU: every mutated shader must fail at the predicted first mismatch word. wrong_sub_want = reduce_want.copy() vals = [INPUT_BASE ^ gid ^ ((gid & 3) << 30) for gid in range(32)] diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index dd825c785..06a4e6272 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3040,8 +3040,8 @@ def word_ok(k): raise Unsupported('%s through a modified descriptor' % what) return key - def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False): - """Validate a fixed-table raw UAV descriptor, data range, offen address, soffset, and 4-byte alignment.""" + def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False): + """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" offset = 0 glc = False for m in mods: @@ -3051,17 +3051,21 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa glc = True elif m != 'offen': raise Unsupported('%s modifier %s' % (kind_label, m)) - if len(ops) != 4 or 'offen' not in mods: + offen = 'offen' in mods + if len(ops) != 4 or (not offen and not (allow_scalar_address and glc and ops[1] == 'off')): raise Unsupported('%s without the offen address form' % kind_label) data = reg_range(ops[0]) if not data or data[0] != 'v' or data[2] - data[1] != data_count - 1 or data[2] > 255: raise Unsupported('%s data %s' % (kind_label, ops[0])) - vaddr = reg_range(ops[1]) - if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: - raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) + if offen: + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True) - terms = [self.u(ops[1])] + terms = [self.u(ops[1])] if offen else [] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + if not offen: + raise Unsupported('%s off requires a scalar register soffset' % kind_label) offset += int(ops[3], 0) else: sreg = reg_range(ops[3]) @@ -3070,7 +3074,8 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa terms.append(self.S(sreg[1])) if offset % 4: raise Unsupported('%s at unaligned immediate offset %d' % (kind_label, offset)) - return data, self.pipe.uav(key), '(%s + %d) & 0xfffffffcu' % (' + '.join(terms), offset), glc + terms.append(str(offset)) + return data, self.pipe.uav(key), '(%s) & 0xfffffffcu' % ' + '.join(terms), glc def op_buffer_store_dword(self, ops, mods, count=1): # Compute-stage store in the offen form: per-lane byte VGPR plus the scalar offset and the 12-bit immediate, @@ -3089,11 +3094,12 @@ def op_buffer_store_dword(self, ops, mods, count=1): self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) def buffer_atomic(self, name, ops, mods): - """Lower 32-bit compute MUBUF atomics in offen mode with optional glc pre-atomic return.""" + """Lower 32-bit compute MUBUF atomics with optional glc pre-atomic return.""" if self.kind != 'cs': raise Unsupported(name) method, signed, is_sub, data_count = MUBUF_ATOMIC_OPS[name] - data, uav, address, glc = self.raw_table_uav_store('buffer atomic', ops, mods, data_count, allow_glc=True) + data, uav, address, glc = self.raw_table_uav_store( + 'buffer atomic', ops, mods, data_count, allow_glc=True, allow_scalar_address=name == 'buffer_atomic_add') words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] self.emit('a = %s;' % address) if not isinstance(getattr(self, 'used_atomic', None), set): From ee7a6631f4eb45b3fd5dc0eb4096803a26fb1412 Mon Sep 17 00:00:00 2001 From: TheVoid Date: Wed, 25 Nov 2026 15:48:32 +0100 Subject: [PATCH 042/232] tests: handle serialized queues in the slot 148 acceptance client (#2381) * tests: handle serialized queues in the slot 148 acceptance client The held phase of startup_slot148_acceptance reads A and B from an observer queue while the console queue waits on an unsignalled gate. On adapters whose queues do not progress while another queue waits, that read cannot finish until the gate opens. The client then waited the full 10 s and exited 18. This was reported for in-box WARP on Windows 10 build 19045 with the debug layer off. - Preflight: before the steps, the console queue waits on an unsignalled fence while the observer reads the sentinel, with a 1 s limit. The fence is then signalled and both queues drained. - If the read did not finish, the client prints "queues serialized: held-phase checks not applicable" and skips only the three held-phase observer reads. - Every other check still runs. The final line then starts "slot 148 acceptance passed with skips". - An adapter that passes the preflight and stalls later still fails with exit 18. - Cleanup: every return opens the gate and drains the console queue. The client drains both queues before it exits. Each wait is bounded at 10 s, and objects whose work did not drain are kept, not released. - X2W_TEST_FORCE_SERIALIZED_QUEUES=1 (fixtures only) takes the serialized path on any adapter. It is registered as startup_slot148_acceptance_serialized{,_nodebug}_{warp,hardware}, whose pass regex names the skipped reads. Refs #2210 Co-Authored-By: Claude Opus 5.5 * Distinguish a stalled observer from a failed read --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 10 ++ docs/startup-runtime.md | 14 ++ tests/startup_slot148_acceptance.cpp | 190 ++++++++++++++++++++++----- 3 files changed, 182 insertions(+), 32 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c21ed2e91..448d666ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1225,6 +1225,16 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_slot148_acceptance_nodebug_${backend} COMMAND startup_slot148_acceptance ${backend}) set_tests_properties(startup_slot148_acceptance_nodebug_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + # The serialized-queue path, forced on adapters whose queues do make progress (Refs #2210). The pass line is + # printed only on exit 0 and names the skipped held-phase observer reads. + add_test(NAME startup_slot148_acceptance_serialized_${backend} COMMAND startup_slot148_acceptance ${backend}) + set_tests_properties(startup_slot148_acceptance_serialized_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "slot 148 acceptance passed with skips: held-phase observer reads" + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1;X2W_TEST_FORCE_SERIALIZED_QUEUES=1") + add_test(NAME startup_slot148_acceptance_serialized_nodebug_${backend} COMMAND startup_slot148_acceptance ${backend}) + set_tests_properties(startup_slot148_acceptance_serialized_nodebug_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "slot 148 acceptance passed with skips: held-phase observer reads" + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0;X2W_TEST_FORCE_SERIALIZED_QUEUES=1") endforeach() add_executable(startup_resource_budget tests/startup_resource_budget.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 82c945d3f..f5cf15f39 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1689,6 +1689,20 @@ These are measured on one executable; treat them as hypotheses for others. `slot 148 not implemented (missing slot)` and exits 10. A null for the valid request from an advertised slot exits 21, on the first call too. Both are failures. Only a missing physical adapter skips (77). + - **Serialized queues:** the held-phase observer read needs a second queue to progress while + the console queue waits on an unsignalled fence. + - **Preflight:** before the steps, the client checks this with a 1-second read of the + sentinel. If the read times out but later drains and matches after the gate opens, it prints + `queues serialized: held-phase checks not applicable` and skips the three held-phase + observer reads. A failed setup, wait or readback keeps the test failing. + - **Still checked:** the in-list reads after the gate opens, the readback staying zero while + held, the controls, refusal after Close and the arguments. + - **Result:** the run passes with a final line that starts + `slot 148 acceptance passed with skips`. An adapter that passes the preflight and then stalls + still fails with exit 18. + - **Cleanup:** every exit opens the gate and drains both queues, with each wait bounded. + - **Forced variants:** `startup_slot148_acceptance_serialized_*` set + `X2W_TEST_FORCE_SERIALIZED_QUEUES=1` to take this path on adapters whose queues do progress. - **Run:** `cmake --build --preset release --target startup_slot148_acceptance` and `ctest --preset release --no-tests=error -R '^startup_slot148_acceptance_' -V`. - **Inline samplers.** Pixel shaders build sampler descriptors from constants (`s_movk_i32`, diff --git a/tests/startup_slot148_acceptance.cpp b/tests/startup_slot148_acceptance.cpp index b158c0e17..e7e9daa76 100644 --- a/tests/startup_slot148_acceptance.cpp +++ b/tests/startup_slot148_acceptance.cpp @@ -34,6 +34,19 @@ // Separately, an observer queue on the same desktop device reads the resolved GPU ranges while the // submissions are held. // +// Preflight. The held-phase observer read needs a second queue to make progress while the console +// queue waits on an unsignalled fence. Before the steps, the console queue waits on such a fence and +// the observer reads the sentinel with a 1 s limit; the fence is then signalled and both queues +// drained. If the read did not finish, the client prints "queues serialized: held-phase checks not +// applicable" and skips only the three held-phase observer reads. All other checks still run, +// including the in-list readback staying zero while held (a CPU read). The final line then +// begins "slot 148 acceptance passed with skips". X2W_TEST_FORCE_SERIALIZED_QUEUES=1 (fixtures +// only) takes that path on any adapter. +// +// Cleanup. Every return opens the gate and drains the console queue, and the client drains both +// queues before it exits. Each wait is bounded at 10 s. If a drain does not finish, the desktop +// objects that work may still use are kept rather than released. +// // Payloads are non-uniform: byte i of payload s is (i * 29 + 0x5b) ^ s. A and B use the #2068 // values 0xa1 and 0xb2 as seeds, the stale fill 0x5c and the sentinel 0xe7. Any two payloads // differ at every byte, and a read shifted by 4 or 16 bytes differs at every byte. @@ -75,10 +88,10 @@ // address; 13 an allocation after a successful Close was not refused, or the closed range still // resolved; 14 invalid arguments not refused or alignment not honoured; 15 observer payload // mismatch; 16 overwrite control did not read B; 17 reuse control: B reuses A's range but A's read -// did not show B; 18 ordering (console work ran before the gate opened, or a timeout); 19 device -// removed or debug-layer errors; 20 A's range was handed to B while A was held; 21 the advertised -// slot refused a valid request; 22 an in-list read ran before its submission was released; 23 -// in-list payload mismatch; 24 the resolver accepted a range of another list or from before a +// did not show B; 18 ordering (console work ran before the gate opened, a timeout, or a preflight +// that did not drain); 19 device removed or debug-layer errors; 20 A's range was handed to B while +// A was held; 21 the advertised slot refused a valid request; 22 an in-list read ran before its +// submission was released; 23 in-list payload mismatch; 24 the resolver accepted a range of another list or from before a // Reset; 25 slot 43 bound a range of another list or from before a Reset; 2 to 5 usage and setup. #include #include @@ -230,6 +243,7 @@ struct Client { ComPtr root; ComPtr copy; Reads observed; + bool serialized = false; // from the preflight: the held-phase observer reads cannot run void* fence() { @@ -430,11 +444,38 @@ struct Client { SUCCEEDED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&observer_fence))) && make_reads(observed); } - // The observer: copies [first, first + 0x280) and [second, second + 0x280) on the GPU, in order. - bool read(Word first, Word second, std::vector& out) + enum class ObserverResult { complete, timeout, failure }; + + static ObserverResult wait_observer(ID3D12Fence* fence, UINT64 value, DWORD ms) { - if (FAILED(observer_allocator->Reset()) || FAILED(observer_list->Reset(observer_allocator.Get(), copy.Get()))) - return false; + if (fence->GetCompletedValue() >= value) return ObserverResult::complete; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!event) return ObserverResult::failure; + const DWORD waited = SUCCEEDED(fence->SetEventOnCompletion(value, event)) + ? WaitForSingleObject(event, ms) : WAIT_FAILED; + CloseHandle(event); + if (waited == WAIT_OBJECT_0) return ObserverResult::complete; + if (waited == WAIT_TIMEOUT) return ObserverResult::timeout; + return ObserverResult::failure; + } + // Bounded drains: every submission on the observer or console queue so far has completed. + bool drain_observer() + { + return !observer_fence || + wait_observer(observer_fence.Get(), observer_value, kWaitMs) == ObserverResult::complete; + } + bool drain_console() + { + void* drained = queue ? fence() : nullptr; + return !queue || (drained && ok(invoke(queue, kQueueSignal, arg(drained), 1)) && reached(drained, 1)); + } + // The observer: copies [first, first + 0x280) and [second, second + 0x280) on the GPU, in order. A + // read that does not finish within `ms` stays pending; drain_observer() waits for it. + ObserverResult read(Word first, Word second, std::vector& out, DWORD ms = kWaitMs) + { + if (!drain_observer() || FAILED(observer_allocator->Reset()) || + FAILED(observer_list->Reset(observer_allocator.Get(), copy.Get()))) + return ObserverResult::failure; observer_list->SetComputeRootSignature(root.Get()); const Word sources[] = {first, second}; for (Word i = 0; i < 2; ++i) { @@ -447,15 +488,55 @@ struct Client { observer_list->CopyBufferRegion(observed.readback.Get(), 0, observed.target.Get(), 0, 2 * kBytes); transition(observer_list.Get(), observed.target.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - if (FAILED(observer_list->Close())) return false; + if (FAILED(observer_list->Close())) return ObserverResult::failure; ID3D12CommandList* lists[] = {observer_list.Get()}; observer->ExecuteCommandLists(1, lists); - HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - const bool finished = event && SUCCEEDED(observer->Signal(observer_fence.Get(), ++observer_value)) && - SUCCEEDED(observer_fence->SetEventOnCompletion(observer_value, event)) && - WaitForSingleObject(event, kWaitMs) == WAIT_OBJECT_0; - if (event) CloseHandle(event); - return finished && map_bytes(observed.readback.Get(), out); + if (FAILED(observer->Signal(observer_fence.Get(), ++observer_value))) return ObserverResult::failure; + const auto result = wait_observer(observer_fence.Get(), observer_value, ms); + if (result != ObserverResult::complete) return result; + return map_bytes(observed.readback.Get(), out) ? ObserverResult::complete : ObserverResult::failure; + } + + // Preflight: can the observer queue finish a read while the console queue waits on an unsignalled + // fence? The held phase needs that. Returns 1 if it can, 0 if the queues are serialized, and -1 if + // the probe's work did not drain after the fence was signalled or read the wrong bytes. + int queues_progress() + { + void* probe_gate = fence(); + if (!probe_gate || !ok(invoke(queue, kQueueWait, arg(probe_gate), 1))) return -1; + std::vector bytes; + const Word base = sentinel->GetGPUVirtualAddress(); + const auto observed_result = read(base, base, bytes, 1000); + const bool opened = ok(invoke(probe_gate, kFenceSignal, 1)); + const bool observer_drained = drain_observer(); + const bool console_drained = drain_console(); + if (!opened || !observer_drained || !console_drained || observed_result == ObserverResult::failure) + return -1; + if (observed_result == ObserverResult::timeout && !map_bytes(observed.readback.Get(), bytes)) return -1; + for (Word i = 0; i < 2 * kBytes; ++i) + if (bytes[i] != pattern(kSentinel, i % kBytes)) return -1; + return observed_result == ObserverResult::complete ? 1 : 0; + } + + // Leaves no work pending at exit: drains both queues (bounded). If a drain does not finish, the + // desktop objects are kept (leaked) rather than released while the GPU may still use them. + ~Client() + { + const bool observer_drained = drain_observer(); + const bool console_drained = drain_console(); + if (observer_drained && console_drained) return; + std::printf("cleanup: queues did not drain within %lu ms; desktop objects are kept\n", + static_cast(kWaitMs)); + observed.target.Detach(); + observed.readback.Detach(); + sentinel.Detach(); + observer_list.Detach(); + observer_allocator.Detach(); + observer.Detach(); + observer_fence.Detach(); + copy.Detach(); + root.Detach(); + desktop.Detach(); } UINT64 debug_errors() @@ -493,10 +574,21 @@ bool matches(const std::vector& bytes, Word slot, Word from, Word enum class Mode { fresh, allocator, overwrite }; -// Opens the gate on every return, so a failed check never leaves the console queue blocked. +// On every return: opens the gate and drains the console queue (bounded). If the queue does not +// drain, the read buffers are kept (leaked), so nothing the GPU may still use is released. struct Gate { + Client& c; void* fence; - ~Gate() { invoke(fence, kFenceSignal, 1); } + Reads& reads; + ~Gate() + { + invoke(fence, kFenceSignal, 1); + if (c.drain_console()) return; + std::printf("cleanup: the console queue did not drain within %lu ms; the read buffers are kept\n", + static_cast(kWaitMs)); + reads.target.Detach(); + reads.readback.Detach(); + } }; // Submit A behind a gate, Reset, write and submit B, read both while held, then release the gate. @@ -515,7 +607,7 @@ int held_sequence(Client& c, Mode mode) if (const int result = c.traced(list, label, first)) return result; if (const int result = c.write_and_record(list, first, kPayloadA, listed, 0)) return result; if (const int result = c.close(list, label, &first)) return result; - const Gate held{gate}; + const Gate held{c, gate, listed}; if (!ok(invoke(c.queue, kQueueWait, arg(gate), 1)) || !c.submit(list, done, 1)) return setup; // Reset while A is held: on another allocator, or on A's own allocator after resetting it. @@ -544,11 +636,23 @@ int held_sequence(Client& c, Mode mode) if (!map_bytes(listed.readback.Get(), early)) return setup; const bool untouched = std::all_of(early.begin(), early.end(), [](unsigned char v) { return v == 0; }); const Word before = invoke(done, kFenceCompleted); - const bool read = c.read(first.gpu, second.gpu, observed); - const Word after = invoke(done, kFenceCompleted); - std::printf("%s: while held, in-list readback untouched = %d; console submissions completed before the " - "observer read %llu, after it %llu (expected 1, 0, 0)\n", - label, untouched ? 1 : 0, static_cast(before), static_cast(after)); + bool read = true; + Word after = 0; + if (c.serialized) { + std::printf("%s: while held, in-list readback untouched = %d; console submissions completed %llu " + "(expected 1, 0); queues serialized: held-phase observer read not applicable\n", + label, untouched ? 1 : 0, static_cast(before)); + } else { + read = c.read(first.gpu, second.gpu, observed) == Client::ObserverResult::complete; + after = invoke(done, kFenceCompleted); + std::printf("%s: while held, in-list readback untouched = %d; console submissions completed before the " + "observer read %llu, after it %llu (expected 1, 0, 0)\n", + label, untouched ? 1 : 0, static_cast(before), + static_cast(after)); + if (!read) + std::printf("%s: the observer read did not finish within %lu ms while the gate was closed\n", label, + static_cast(kWaitMs)); + } if (!untouched) return list_read_order; const bool opened = ok(invoke(gate, kFenceSignal, 1)); if (!read || before || after || !opened || !Client::reached(done, 2)) return ordering; @@ -558,10 +662,13 @@ int held_sequence(Client& c, Mode mode) const int a_failure = mode == Mode::overwrite ? overwrite_control : mode == Mode::allocator ? held_reuse : 0; if (!matches(recorded, 1, 0, kBytes, kPayloadB, "in-list B")) return list_payload; if (!matches(recorded, 0, 0, kBytes, wanted, "in-list A")) return a_failure ? a_failure : list_payload; - if (!matches(observed, 1, 0, kBytes, kPayloadB, "observer B")) return payload; - if (!matches(observed, 0, 0, kBytes, wanted, "observer A")) return a_failure ? a_failure : payload; - std::printf("%s: in-list and observer reads: A holds payload 0x%02x and B payload 0x%02x, all %llu bytes\n", label, - wanted, kPayloadB, static_cast(kBytes)); + if (!c.serialized) { + if (!matches(observed, 1, 0, kBytes, kPayloadB, "observer B")) return payload; + if (!matches(observed, 0, 0, kBytes, wanted, "observer A")) return a_failure ? a_failure : payload; + } + std::printf("%s: %s reads: A holds payload 0x%02x and B payload 0x%02x, all %llu bytes\n", label, + c.serialized ? "in-list" : "in-list and observer", wanted, kPayloadB, + static_cast(kBytes)); return pass; } @@ -586,7 +693,7 @@ int forced_reuse(Client& c) // A's range is live again as part of B, so reading it is defined. Byte i of A's range is byte // i - shift of B, where shift is B's start relative to A's. std::vector bytes; - if (!c.read(first.gpu, second.gpu, bytes)) return ordering; + if (c.read(first.gpu, second.gpu, bytes) != Client::ObserverResult::complete) return ordering; const Word from = second.gpu > first.gpu ? second.gpu - first.gpu : 0; const Word to = (std::min)(kBytes, second.gpu + kBytes - first.gpu); for (Word i = from; i < to; ++i) { @@ -607,8 +714,13 @@ int forced_reuse(Client& c) bool run_reads(Client& c, void* list, Reads& reads, std::vector& out) { void* done = c.fence(); - return done && ok(invoke(list, kCloseSlot)) && c.submit(list, done, 1) && Client::reached(done, 1) && - map_bytes(reads.readback.Get(), out); + const bool submitted = done && ok(invoke(list, kCloseSlot)) && c.submit(list, done, 1); + if (submitted && Client::reached(done, 1)) return map_bytes(reads.readback.Get(), out); + if (!c.drain_console()) { + reads.target.Detach(); + reads.readback.Detach(); + } + return false; } // The wrong-list and stale-generation controls for the resolver and the guest consumer. @@ -722,6 +834,17 @@ int main(int argc, char** argv) !c.consumer_setup()) return setup; + // Preflight for the held phase. X2W_TEST_FORCE_SERIALIZED_QUEUES=1 (fixtures only) takes the + // serialized path on any adapter, so that path is tested where the queues do make progress. + const int progress = c.queues_progress(); + const bool forced = GetEnvironmentVariableA("X2W_TEST_FORCE_SERIALIZED_QUEUES", debug, sizeof(debug)) && debug[0] == '1'; + std::printf("preflight: the observer queue %s while the console queue waited on an unsignalled fence%s\n", + progress > 0 ? "finished a read" : progress == 0 ? "made no progress" : "failed the probe", + forced ? "; X2W_TEST_FORCE_SERIALIZED_QUEUES=1" : ""); + if (progress < 0) return ordering; + c.serialized = forced || progress == 0; + if (c.serialized) std::puts("queues serialized: held-phase checks not applicable"); + int result = held_sequence(c, Mode::fresh); if (!result) result = held_sequence(c, Mode::allocator); if (!result) result = held_sequence(c, Mode::overwrite); @@ -733,7 +856,10 @@ int main(int argc, char** argv) std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), static_cast(errors)); if (!result && (removed != S_OK || errors)) result = device_state; - if (!result) std::puts("slot 148 acceptance passed"); - else std::printf("slot 148 acceptance failed: exit %d\n", result); + if (result) std::printf("slot 148 acceptance failed: exit %d\n", result); + else if (c.serialized) + std::puts("slot 148 acceptance passed with skips: held-phase observer reads in fresh, allocator and overwrite " + "(queues serialized); every other check ran"); + else std::puts("slot 148 acceptance passed"); return result; } From 9f13c507e0bec0e45475f39851685d4a746df5da Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:49:16 +0200 Subject: [PATCH 043/232] cpu: lower legacy SSE2 CMPSD, MOVLPD, MOVHPD, and MOVNTPD in cpu_sse_fp_aot (#2385) --- CMakeLists.txt | 23 + tests/cpu/sse_fp_check.py | 8 +- tests/cpu/sse_fp_pd_check.py | 4 +- tests/cpu/sse_fp_pd_moves_cmp.asm | 282 ++++++++++ tests/cpu/sse_fp_pd_moves_cmp.def | 24 + tests/cpu/sse_fp_pd_moves_cmp_check.py | 683 +++++++++++++++++++++++++ tools/cpu_sse_fp_aot.py | 69 ++- 7 files changed, 1076 insertions(+), 17 deletions(-) create mode 100644 tests/cpu/sse_fp_pd_moves_cmp.asm create mode 100644 tests/cpu/sse_fp_pd_moves_cmp.def create mode 100644 tests/cpu/sse_fp_pd_moves_cmp_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 448d666ff..8325b88db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4970,6 +4970,29 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "${CMAKE_CXX_COMPILER}") + # cpu_aot_sse_fp_pd_moves_cmp + set(cpu_sse_fp_pd_moves_cmp_exports + "op_cmpsd_0,op_cmpsd_1,op_cmpsd_2,op_cmpsd_3,op_cmpsd_4,op_cmpsd_5,op_cmpsd_6,op_cmpsd_7," + "op_cmpsd_mem,op_cmpsd_mem_plus1,op_cmpsd_self," + "op_movlpd_load,op_movlpd_store,op_movhpd_load,op_movhpd_store," + "op_movlpd_load_plus1,op_movhpd_load_plus1,op_movlpd_store_plus1,op_movhpd_store_plus1," + "op_movntpd,op_movntpd_disp16,op_pd_moves_cmp_pipeline,op_pd_moves_cmp_discarded_read") + string(CONCAT cpu_sse_fp_pd_moves_cmp_exports ${cpu_sse_fp_pd_moves_cmp_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sse_fp_pd_moves_cmp_${variant} sse_fp_pd_moves_cmp) + cpu_translation(cpu_sse_fp_pd_moves_cmp_${variant} cpu_sse_fp_aot "${cpu_sse_fp_pd_moves_cmp_exports}") + endforeach() + target_compile_definitions(cpu_sse_fp_pd_moves_cmp_altered PRIVATE ALTER_IMM) + add_test(NAME cpu_aot_sse_fp_pd_moves_cmp COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sse_fp_pd_moves_cmp_check.py" + "$" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_sse_fp_pd_moves_cmp PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sse_fp_pd_moves_cmp.txt") set(cpu_avx_fp_move_exports "op_vmovq_xmm_xmm,op_vmovq_xmm_m64,op_vmovq_m64_xmm,op_vmovq_xmm_r64,op_vmovq_r64_xmm," "op_vmaskmovdqu,op_pipeline,op_discarded_read,op_discarded_read64," diff --git a/tests/cpu/sse_fp_check.py b/tests/cpu/sse_fp_check.py index ecc70736b..e5abfd4aa 100644 --- a/tests/cpu/sse_fp_check.py +++ b/tests/cpu/sse_fp_check.py @@ -665,10 +665,10 @@ def check_alt_encodings_and_rejections(original_path): ("maxss", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.MAXSS_XMM_XMMM32, R.XMM0, R.XMM1), ret_ins)), ("addss", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.ADDSS_XMM_XMMM32, R.XMM0, R.XMM1), ret_ins)), ("cvtpd2ps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.CVTPD2PS_XMM_XMMM128, R.XMM0, R.XMM1), ret_ins)), - ("cmpsd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32(Code.CMPSD_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, 0), ret_ins)), - ("movlpd", (ld_xmm0, Instruction.create_reg_mem(Code.MOVLPD_XMM_M64, R.XMM0, MemoryOperand(R.RDX)), ret_ins)), - ("movhpd", (ld_xmm0, Instruction.create_reg_mem(Code.MOVHPD_XMM_M64, R.XMM0, MemoryOperand(R.RDX)), ret_ins)), - ("movntpd", (ld_xmm0, Instruction.create_mem_reg(Code.MOVNTPD_M128_XMM, MemoryOperand(R.R8), R.XMM0), ret_ins)), + ("unpcklpd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.UNPCKLPD_XMM_XMMM128, R.XMM0, R.XMM1), ret_ins)), + ("unpckhpd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.UNPCKHPD_XMM_XMMM128, R.XMM0, R.XMM1), ret_ins)), + ("shufpd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32(Code.SHUFPD_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), ret_ins)), + ("movupd", (Instruction.create_reg_mem(Code.MOVUPD_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins)), ("movhlps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.MOVHLPS_XMM_XMM, R.XMM0, R.XMM1), ret_ins)), ("movlhps", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.MOVLHPS_XMM_XMM, R.XMM0, R.XMM1), ret_ins)), ("movss", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg(Code.MOVSS_XMM_XMMM32, R.XMM0, R.XMM1), ret_ins)), diff --git a/tests/cpu/sse_fp_pd_check.py b/tests/cpu/sse_fp_pd_check.py index d530c79c3..698468125 100644 --- a/tests/cpu/sse_fp_pd_check.py +++ b/tests/cpu/sse_fp_pd_check.py @@ -363,7 +363,7 @@ def mem(code, dst, base_reg, displ=0): ("rcpps", Code.RCPPS_XMM_XMMM128), ("rsqrtps", Code.RSQRTPS_XMM_XMMM128), ) ] + [ - ("cmpsd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32(Code.CMPSD_XMM_XMMM64_IMM8, R.XMM0, R.XMM1, 0), ret_ins)), + ("movupd", (Instruction.create_reg_mem(Code.MOVUPD_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret_ins)), ("shufpd", (ld_xmm0, ld_xmm1, Instruction.create_reg_reg_u32(Code.SHUFPD_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), ret_ins)), ("cvtpi2pd", (Instruction.create_reg_mem(Code.CVTPI2PD_XMM_MMM64, R.XMM0, MemoryOperand(R.RDX)), ret_ins)), ] @@ -455,7 +455,7 @@ def cmppd(dst, src, imm): pdata_end_off = pe.get_offset_from_rva(pdata.VirtualAddress + rec_idx + 4) max_len = struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("= 8 is an AVX-only predicate and rejects; each 64-bit lane becomes an all-ones or all-zero mask) - Scalar float compare: cmpss (imm8 predicates 0..7, xmm and m32; bits 127:32 preserved) + - Scalar double compare: cmpsd (imm8 predicates 0..7, xmm and m64; bits 127:64 preserved) - Half-qword float moves: movlps, movhps (m64 load-merge preserving the other 64 bits, and m64 store) - - Non-temporal store: movntps (aligned m128 store) + - Half-qword double moves: movlpd, movhpd (m64 load-merge preserving the other + 64 bits, and m64 store) + - Non-temporal stores: movntps, movntpd (aligned m128 store) Arithmetic runs under the host MXCSR: the generated code executes the same SSE operation at run time, so the rounding mode, DAZ and FTZ are the host's and the translator never folds a result at translation time. A guest MXCSR write (ldmxcsr, vldmxcsr) is not lifted, exception flags are not observed and -the scalar forms, the other packed double forms (conversions), -rcpps and rsqrtps stay rejected. NaN operands are resolved in software (the first +the other scalar forms, conversions, rcpps and rsqrtps stay rejected. NaN operands are resolved in software (the first source operand that is a NaN, made quiet, else the second) so that a compiler which commutes an addition cannot change a payload. Transport/ABI glue: movaps, movdqa (aligned 128-bit load/store/reg copy), movdqu (unaligned 128-bit load/store/reg copy) and terminal ret. All memory stores must target an r8-rooted flat address; loads may read from rcx, rdx or -r8. Full-width 128-bit aligned operands (cmpps m128, cmppd m128, movntps, movaps m128, -movdqa m128) require displacements divisible by 16. +r8. Full-width 128-bit aligned operands (cmpps m128, cmppd m128, movntps, movntpd, +movaps m128, movdqa m128) require displacements divisible by 16. """ import argparse @@ -95,11 +97,17 @@ Code.CMPPS_XMM_XMMM128_IMM8, Code.CMPPD_XMM_XMMM128_IMM8, Code.CMPSS_XMM_XMMM32_IMM8, + Code.CMPSD_XMM_XMMM64_IMM8, Code.MOVLPS_XMM_M64, Code.MOVLPS_M64_XMM, Code.MOVHPS_XMM_M64, Code.MOVHPS_M64_XMM, + Code.MOVLPD_XMM_M64, + Code.MOVLPD_M64_XMM, + Code.MOVHPD_XMM_M64, + Code.MOVHPD_M64_XMM, Code.MOVNTPS_M128_XMM, + Code.MOVNTPD_M128_XMM, Code.MOVAPS_XMM_XMMM128, Code.MOVAPS_XMMM128_XMM, Code.MOVDQA_XMM_XMMM128, @@ -361,6 +369,27 @@ return cmp_f32(d_as_float(a), d_as_float(b), imm8); } +// CMPSD predicates 0..7 on the low double via host SSE2, so live MXCSR (DAZ) and NaN rules match +// hardware. Volatile copies prevent compile-time folding across MXCSR changes. +static inline std::uint64_t op_cmpsd_q(std::uint64_t a, std::uint64_t b, std::uint8_t imm8) { + const volatile std::uint64_t va = a; + const volatile std::uint64_t vb = b; + const __m128d x = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(va))); + const __m128d y = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(vb))); + __m128d r; + switch (imm8 & 7u) { + case 0u: r = _mm_cmpeq_sd(x, y); break; + case 1u: r = _mm_cmplt_sd(x, y); break; + case 2u: r = _mm_cmple_sd(x, y); break; + case 3u: r = _mm_cmpunord_sd(x, y); break; + case 4u: r = _mm_cmpneq_sd(x, y); break; + case 5u: r = _mm_cmpnlt_sd(x, y); break; + case 6u: r = _mm_cmpnle_sd(x, y); break; + default: r = _mm_cmpord_sd(x, y); break; + } + return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(r))); +} + // Bitwise SSE packed-FP logic preserves all 128 bits identically (NaNs, -0.0, denormals, Inf). static inline Vec128 op_andps(const Vec128& dst, const Vec128& src) { return {{dst.q[0] & src.q[0], dst.q[1] & src.q[1]}}; @@ -525,21 +554,39 @@ def vec_src128(op_index, ins, *, alignment=16): f"set_lane32({dst_name}, 0u, op_cmpss_d(lane32({dst}, 0u), {src32}, {imm:#x}u));" ) defined.add(dst_idx) - elif ins.code in (Code.MOVLPS_XMM_M64, Code.MOVHPS_XMM_M64): + elif ins.code == Code.CMPSD_XMM_XMMM64_IMM8: + imm = ins.immediate8 & 0xff + if imm > 7: + raise ValueError(f"unsupported cmpsd predicate {imm:#x} at RVA {ins.ip:#x}: {ins}") + dst = read_vec(0, ins) + if ins.op1_kind == OpKind.MEMORY: + src64 = f"load64({flat_address(ins)})" + else: + src64 = f"{read_vec(1, ins)}.q[0]" + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name}.q[0] = op_cmpsd_q({dst}.q[0], {src64}, {imm:#x}u);") + defined.add(dst_idx) + elif ins.code in ( + Code.MOVLPS_XMM_M64, Code.MOVHPS_XMM_M64, + Code.MOVLPD_XMM_M64, Code.MOVHPD_XMM_M64, + ): if ins.op1_kind != OpKind.MEMORY: raise ValueError(f"expected memory source at RVA {ins.ip:#x}: {ins}") read_vec(0, ins) dst_idx, dst_name = write_vec(0, ins) - q_idx = 1 if ins.code == Code.MOVHPS_XMM_M64 else 0 + q_idx = 1 if ins.code in (Code.MOVHPS_XMM_M64, Code.MOVHPD_XMM_M64) else 0 statements.append(f"{dst_name}.q[{q_idx}] = load64({flat_address(ins)});") defined.add(dst_idx) - elif ins.code in (Code.MOVLPS_M64_XMM, Code.MOVHPS_M64_XMM): + elif ins.code in ( + Code.MOVLPS_M64_XMM, Code.MOVHPS_M64_XMM, + Code.MOVLPD_M64_XMM, Code.MOVHPD_M64_XMM, + ): if ins.op0_kind != OpKind.MEMORY: raise ValueError(f"expected memory destination at RVA {ins.ip:#x}: {ins}") src = read_vec(1, ins) - q_idx = 1 if ins.code == Code.MOVHPS_M64_XMM else 0 + q_idx = 1 if ins.code in (Code.MOVHPS_M64_XMM, Code.MOVHPD_M64_XMM) else 0 statements.append(f"store64({flat_address(ins, write=True)}, {src}.q[{q_idx}]);") - elif ins.code == Code.MOVNTPS_M128_XMM: + elif ins.code in (Code.MOVNTPS_M128_XMM, Code.MOVNTPD_M128_XMM): if ins.op0_kind != OpKind.MEMORY: raise ValueError(f"expected memory destination at RVA {ins.ip:#x}: {ins}") src = read_vec(1, ins) From 14b5d5147d5ff63a87e94eed80adbce4ed02cb1c Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 16:51:08 +0200 Subject: [PATCH 044/232] ffx: extract main(argv), atomic output writes, and error guards in ffx_dispatch_profile with CLI suite (#2383) * ffx: extract main(argv), atomic output writes, and error guards in ffx_dispatch_profile with CLI suite * Check every FFX output against the input image --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 2 + tests/ffx_dispatch_profile_cli_check.py | 319 ++++++++++++++++++++++++ tools/ffx_dispatch_profile.py | 47 +++- 3 files changed, 361 insertions(+), 7 deletions(-) create mode 100644 tests/ffx_dispatch_profile_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8325b88db..db067c268 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8024,6 +8024,8 @@ if(EXISTS "${INTAKE_PYTHON}") --host $ --backend warp) add_test(NAME ffx_dispatch_profile_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/ffx_dispatch_profile_check.py") + add_test(NAME ffx_dispatch_profile_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ffx_dispatch_profile_cli_check.py") add_test(NAME ffx_dispatch_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/ffx_dispatch_aot_cli_check.py") add_test(NAME sampled_coverage_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/ffx_dispatch_profile_cli_check.py b/tests/ffx_dispatch_profile_cli_check.py new file mode 100644 index 000000000..fe99d5e66 --- /dev/null +++ b/tests/ffx_dispatch_profile_cli_check.py @@ -0,0 +1,319 @@ +"""CLI, atomic output, and mutation control suite for tools/ffx_dispatch_profile.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "ffx_dispatch_profile.py" +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) + +import ffx_dispatch_profile # noqa: E402 +from ffx_dispatch_profile_check import build_synthetic_pe # noqa: E402 + + +EXPECTED_PROGRAMS = ("pass24", "pass25", "producer", "rcas", "initializer") + + +def _write_synthetic_image(directory: Path, name: str = "upscaler.dll"): + buf, meta = build_synthetic_pe() + raw = bytes(buf) + image = directory / name + image.write_bytes(raw) + return image, raw, meta, hashlib.sha256(raw).hexdigest() + + +def _run_main(argv: list[str]) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + try: + with redirect_stdout(stdout), redirect_stderr(stderr): + code = ffx_dispatch_profile.main(argv) + except SystemExit as exc: + code = int(exc.code) if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_cli_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class FfxDispatchProfileCliPositiveTests(unittest.TestCase): + def test_main_creates_nested_output_dir_with_exact_bins_sha_and_stdout(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, _, meta, digest = _write_synthetic_image(root) + out_dir = root / "nested" / "deep" / "profiles" + self.assertFalse(out_dir.exists()) + + seen_replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + seen_replaces.append((Path(src), Path(dst))) + return real_replace(src, dst) + + with ( + mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest), + mock.patch.object(ffx_dispatch_profile.os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main([str(image), str(out_dir)]) + + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertTrue(out_dir.is_dir()) + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + sorted(f"{name}.bin" for name in EXPECTED_PROGRAMS), + ) + self.assertEqual(len(seen_replaces), len(EXPECTED_PROGRAMS)) + for src, dst in seen_replaces: + self.assertEqual(src.parent.parent.resolve(), out_dir.resolve()) + self.assertEqual(dst.parent.resolve(), out_dir.resolve()) + + for name in EXPECTED_PROGRAMS: + expected = meta["payloads"][name] + actual = (out_dir / f"{name}.bin").read_bytes() + self.assertEqual(actual, expected) + self.assertEqual( + hashlib.sha256(actual).hexdigest(), + hashlib.sha256(expected).hexdigest(), + ) + + expected_threads = {"pass24": 64, "pass25": 32, "producer": 256, "rcas": 64} + lines = out.splitlines() + self.assertEqual(len(lines), 4) + for line, name in zip(lines, ("pass24", "pass25", "producer", "rcas")): + self.assertRegex( + line, + rf"^{name} container=0x[0-9a-f]+ threads={expected_threads[name]} " + rf"code_bytes={len(meta['payloads'][name])}$", + ) + + def test_main_atomically_replaces_existing_bins_without_leftover_temp_dirs(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, _, meta, digest = _write_synthetic_image(root) + out_dir = root / "out" + out_dir.mkdir() + for name in EXPECTED_PROGRAMS: + (out_dir / f"{name}.bin").write_bytes(b"stale-data") + + with mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest): + code, _, err = _run_main([str(image), str(out_dir)]) + + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + sorted(f"{name}.bin" for name in EXPECTED_PROGRAMS), + ) + for name in EXPECTED_PROGRAMS: + self.assertEqual((out_dir / f"{name}.bin").read_bytes(), meta["payloads"][name]) + + +class FfxDispatchProfileCliNegativeAndMutationTests(unittest.TestCase): + def test_missing_image_exits_1_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.dll" + out_dir = root / "out_missing" + + code, out, err = _run_main([str(missing), str(out_dir)]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + self.assertFalse(out_dir.exists()) + + proc = _run_cli_subprocess(str(missing), str(out_dir)) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + self.assertFalse(out_dir.exists()) + + def test_mismatching_upscaler_image_exits_1_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, _, _, _ = _write_synthetic_image(root) + out_dir = root / "out_mismatch" + + code, out, err = _run_main([str(image), str(out_dir)]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("version-query profile", err) + self.assertFalse(out_dir.exists()) + + proc = _run_cli_subprocess(str(image), str(out_dir)) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("version-query profile", proc.stderr) + self.assertFalse(out_dir.exists()) + + def test_invalid_pe_format_error_exits_1_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + bad_image = root / "not_pe.dll" + payload = b"not a portable executable" + bad_image.write_bytes(payload) + out_dir = root / "out_bad_pe" + + with mock.patch.object( + ffx_dispatch_profile, + "UPSCALER", + hashlib.sha256(payload).hexdigest(), + ): + code, out, err = _run_main([str(bad_image), str(out_dir)]) + + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + self.assertFalse(out_dir.exists()) + + def test_struct_error_from_truncated_data_exits_1_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, _, _, digest = _write_synthetic_image(root) + out_dir = root / "out_struct" + + with ( + mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest), + mock.patch.object( + ffx_dispatch_profile, + "inspect", + side_effect=struct.error("unpack requires a buffer of 4 bytes"), + ), + ): + code, out, err = _run_main([str(image), str(out_dir)]) + + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("unpack requires a buffer of 4 bytes", err) + self.assertFalse(out_dir.exists()) + + def test_output_file_collision_preserves_image_and_other_outputs(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, original, _, digest = _write_synthetic_image(root, "initializer.bin") + with mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest): + code, _, err = _run_main([str(image), str(root)]) + + self.assertEqual(code, 1) + self.assertIn("Output file collides with image", err) + self.assertEqual(image.read_bytes(), original) + self.assertEqual(list(root.iterdir()), [image]) + + def test_output_directory_collision_with_image_resolve_and_samefile(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, raw, _, digest = _write_synthetic_image(root) + sub = root / "sub" + sub.mkdir() + + # 1) Relative/parent-traversal alias resolving to existing image. + alias = sub / ".." / "upscaler.dll" + with mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest): + code, out, err = _run_main([str(image), str(alias)]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("collides with image", err) + self.assertEqual(image.read_bytes(), raw) + + proc = _run_cli_subprocess(str(image), str(alias)) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("collides with image", proc.stderr) + self.assertEqual(image.read_bytes(), raw) + + # 2) Non-existent image path collision (kills mutating resolve() == resolve()). + ghost = root / "ghost.dll" + ghost_alias = sub / ".." / "ghost.dll" + code, out, err = _run_main([str(ghost), str(ghost_alias)]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("collides with image", err) + + # 3) Hardlink alias where resolve() differs (kills mutating samefile()). + hardlink = root / "upscaler_hardlink.dll" + os.link(image, hardlink) + self.assertNotEqual(image.resolve(), hardlink.resolve()) + self.assertTrue(image.samefile(hardlink)) + with mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest): + code, out, err = _run_main([str(image), str(hardlink)]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("collides with image", err) + self.assertEqual(hardlink.read_bytes(), raw) + + def test_output_directory_existing_regular_file_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, _, _, digest = _write_synthetic_image(root) + existing_file = root / "existing_output.bin" + existing_file.write_bytes(b"preserve-me") + + with mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest): + code, out, err = _run_main([str(image), str(existing_file)]) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("is not a directory", err) + self.assertEqual(existing_file.read_bytes(), b"preserve-me") + + proc = _run_cli_subprocess(str(image), str(existing_file)) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("is not a directory", proc.stderr) + self.assertEqual(existing_file.read_bytes(), b"preserve-me") + + def test_os_replace_failure_leaves_zero_partial_bins_or_temp_dirs(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + image, _, _, digest = _write_synthetic_image(root) + out_dir = root / "atomic_fail" + replace_calls = [] + + def failing_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + # Prove staging file actually resides in a TemporaryDirectory under out_dir. + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), out_dir.resolve()) + raise OSError("simulated replace failure") + + with ( + mock.patch.object(ffx_dispatch_profile, "UPSCALER", digest), + mock.patch.object(ffx_dispatch_profile.os, "replace", side_effect=failing_replace), + ): + code, _, err = _run_main([str(image), str(out_dir)]) + + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated replace failure", err) + self.assertEqual(len(replace_calls), 1) + self.assertTrue(out_dir.is_dir()) + self.assertEqual(list(out_dir.iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ffx_dispatch_profile.py b/tools/ffx_dispatch_profile.py index e7e42c66c..4b04c1bc7 100644 --- a/tools/ffx_dispatch_profile.py +++ b/tools/ffx_dispatch_profile.py @@ -1,7 +1,11 @@ """Identify the first ID 16 writer and reader in the pinned default dispatch graph.""" import argparse +import os from pathlib import Path import struct +import tempfile + +import pefile from ffx_version_query import UPSCALER, checked_image, lower, region from resource_inventory import parts @@ -126,13 +130,42 @@ def resource_id(name, start, count): yield "initializer", init_data -if __name__ == "__main__": +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("image", type=Path) parser.add_argument("output_directory", type=Path) - args = parser.parse_args() - with checked_image(args.image, UPSCALER) as pe: - programs = list(inspect(pe)) - args.output_directory.mkdir(parents=True, exist_ok=True) - for name, code in programs: - (args.output_directory / (name + ".bin")).write_bytes(code) + args = parser.parse_args(argv) + try: + if _same_path(args.output_directory, args.image): + raise ValueError(f"Output directory collides with image: {args.output_directory}") + if args.output_directory.exists() and not args.output_directory.is_dir(): + raise ValueError(f"Output directory is not a directory: {args.output_directory}") + with checked_image(args.image, UPSCALER) as pe: + programs = list(inspect(pe)) + outputs = [(args.output_directory / f"{name}.bin", code) for name, code in programs] + for destination, _ in outputs: + if _same_path(destination, args.image): + raise ValueError(f"Output file collides with image: {destination}") + args.output_directory.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=args.output_directory) as staging_dir: + staging_root = Path(staging_dir) + staged = [] + for destination, code in outputs: + staging_path = staging_root / destination.name + staging_path.write_bytes(code) + staged.append((staging_path, destination)) + for staging_path, destination in staged: + os.replace(staging_path, destination) + except (OSError, ValueError, struct.error, pefile.PEFormatError) as exc: + parser.exit(1, f"{exc}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 5d86af39caf360f3f8eb050f424583040f762855 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:51:58 +0100 Subject: [PATCH 045/232] startup: implement next copy command-list slot in d3d12_xs_device (Part of #870) (#2070) * startup: implement command-list slot 16 CopyTextureRegion (Part of #870) Maps both copy locations to desktop resources, refuses calls the desktop would reject with a named reason, and forwards the rest with COPY_SOURCE/COPY_DEST states. * startup: slot 16 copy fixes: heap states, lazy upload, origins, same resource (Part of #870) * docs: slot 16 CopyTextureRegion capability and reproduction command (Part of #870) * startup: validate full subresource index, format and sample count for slot 16 (Part of #870) Index = mip + slice * mips + plane * mips * array_size must lie inside the resource; planar, format-mismatched and partial multisampled copies are refused; footprint arithmetic is checked at each multiply and add. Adds a wrapped-list readback test. * test: record the slot 16 readback list for real (Part of #870) * Require null source boxes for whole-only texture copies --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 21 +++ docs/startup-runtime.md | 34 +++- src/startup_stubs/d3d12_xs_device.cpp | 2 + src/startup_stubs/list_copy_texture.h | 171 +++++++++++++++++ src/startup_stubs/list_copy_texture.inl | 165 +++++++++++++++++ tests/startup_list_copy_texture_check.cpp | 130 +++++++++++++ tests/startup_list_copy_texture_warp.cpp | 216 ++++++++++++++++++++++ 7 files changed, 738 insertions(+), 1 deletion(-) create mode 100644 src/startup_stubs/list_copy_texture.h create mode 100644 src/startup_stubs/list_copy_texture.inl create mode 100644 tests/startup_list_copy_texture_check.cpp create mode 100644 tests/startup_list_copy_texture_warp.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index db067c268..bdf504227 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -672,6 +672,27 @@ add_test(NAME startup_placed_buffer_range_region_only_control COMMAND startup_pl add_test(NAME startup_placed_buffer_range_walk_only_control COMMAND startup_placed_buffer_range_check --mutate walk-only) set_tests_properties(startup_placed_buffer_range_region_only_control startup_placed_buffer_range_walk_only_control PROPERTIES SKIP_RETURN_CODE 77) +# CopyTextureRegion (list slot 16): the argument checks refuse what the desktop would reject +# (src/startup_stubs/list_copy_texture.h). The mutated run is the negative control. +add_executable(startup_list_copy_texture_check tests/startup_list_copy_texture_check.cpp) +target_compile_features(startup_list_copy_texture_check PRIVATE cxx_std_17) +target_include_directories(startup_list_copy_texture_check PRIVATE src) +add_test(NAME startup_list_copy_texture COMMAND startup_list_copy_texture_check) +add_test(NAME startup_list_copy_texture_overflow_control COMMAND startup_list_copy_texture_check --mutate overflow) +set_tests_properties(startup_list_copy_texture_overflow_control PROPERTIES WILL_FAIL TRUE) +add_test(NAME startup_list_copy_texture_slice_control COMMAND startup_list_copy_texture_check --mutate slice) +set_tests_properties(startup_list_copy_texture_slice_control PROPERTIES WILL_FAIL TRUE) + +# The same call through the wrapped command list: two array slices round-trip, and an out-of-range subresource +# or a format mismatch is refused before any desktop copy. +add_executable(startup_list_copy_texture_warp tests/startup_list_copy_texture_warp.cpp) +target_compile_features(startup_list_copy_texture_warp PRIVATE cxx_std_17) +target_link_libraries(startup_list_copy_texture_warp PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_list_copy_texture_${backend} COMMAND startup_list_copy_texture_warp ${backend}) + set_tests_properties(startup_list_copy_texture_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() add_executable(startup_storage_file_range tests/startup_storage_file_range.cpp) target_compile_features(startup_storage_file_range PRIVATE cxx_std_17) target_include_directories(startup_storage_file_range PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f5cf15f39..a0381981c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -548,7 +548,7 @@ upload the stale title memory over the result; a list discarded by Reset or a fa and block-compressed). A resolve format is exact against a fully typed endpoint and only family-compatible with a typeless one; a typeless resolve format (or an unknown one over typeless endpoints) resolves as the family's typed choice: half float for `R16G16B16A16`, normalised for the 8-bit and 10-bit families. Calls on a closed list are ignored. -These slots have not been seen in a title log yet. `CopyTextureRegion` (16) and `CopyTiles` (18) are not handled. +These slots have not been seen in a title log yet. Slot 16 is described in [Command list CopyTextureRegion](#command-list-copytextureregion-list-slot-16). Slot 18 (`CopyTiles`) is not handled. `ctest -R '^startup_list_copy_validation'` runs the pure checks on any host; `startup_list_copy_{warp,hardware}` copies, resolves and reads back through the `x2w_d3d12_list_copy_stats` export. @@ -2727,3 +2727,35 @@ and console layouts. On Windows 11 Build 26100 with an AMD Radeon RX 6600M (driv - `ctest --preset release --no-tests=error -R '^startup_memory_srv_(report|buffer|volume)$' -V` - `ctest --preset release --no-tests=error -R '^startup_memory_srv_(buffer|volume)_.*_control$' -V` - `ctest --preset release --no-tests=error -R '^startup_address_(srv|buffer_srv|volume_srv)_' -V` + +## Command list CopyTextureRegion (list slot 16) + +Command list slot 16, `CopyTextureRegion`, maps each location's resource to its desktop resource, checks the +call, and forwards it only when the desktop would accept it. A refused call is counted and logged +(`x2w-d3d12 CopyTextureRegion refused: `), not forwarded. Capability, measured on the portable +check only: + +- Argument checks (`src/startup_stubs/list_copy_texture.h`): footprint on both sides, empty or inverted box, + source and destination bounds, row pitch (multiple of 256), offset (multiple of 512), footprint end inside + the buffer (includes the destination origin, the source box origin and the footprint-height slice stride), + block alignment, every multiply and add in the footprint arithmetic checked for wrapping. +- Subresource index: `mip + slice * mips + plane * mips * array_size` must lie inside the resource's + `mips * array_size * planes`; a mip-only modulo would read an out-of-range slice as mip 0 + (`bad_subresource`). A planar format (more than one plane) is refused (`planar_unsupported`). +- The two sides must name the same format (`format_mismatch`) and the same sample count + (`sample_mismatch`). Multisampled and single-plane depth-stencil copies require equally sized whole + subresources, destination origin 0 and a null source box (`partial_multisample`, `partial_depth_stencil`). + Buffer footprints are single-sample, so a multisampled texture and a buffer are refused. +- Upload and readback footprint buffers keep their fixed heap states and get no barrier; an upload buffer as + destination or a readback buffer as source is refused (`bad_heap`). +- A source or destination texture is brought up to date from its guest backing (`upload_texture`) before the + copy, so a later first sample does not replace the copied texels. A copied (non-aliased) source buffer is + refused (`stale_source`). +- Two subresources of one resource are refused (`same_resource`): resource states are tracked per resource. + +Wrapped-list readback (`tests/startup_list_copy_texture_warp.cpp`): two images round-trip through array +slices 1 and 2 of a 2-mip, 3-slice texture (upload buffer, texture, readback buffer, byte-for-byte), and a +list with an out-of-range subresource, an index of `0xffffffff` and a footprint format mismatch is refused +before any desktop copy, leaving a sentinel-filled readback buffer unchanged. Reproduce the portable check +with its negative controls and the WARP and hardware runs with +`ctest --preset dev --no-tests=error -R '^startup_list_copy_texture' -V`. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index c91e818b2..a3ffb791e 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3310,6 +3310,7 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_draw.inl" #include "startup_stubs/mesh86_cache.inl" #include "startup_stubs/d3d12_compute_binding_trace.inl" +#include "startup_stubs/list_copy_texture.inl" // Queue slot 10, desktop ExecuteCommandLists(count, lists). void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) @@ -4933,6 +4934,7 @@ void build_tables() list_typed[139] = reinterpret_cast(&list_reset); list_typed[148] = reinterpret_cast(&list_allocate_upload); list_typed[12] = reinterpret_cast(&list_draw); + list_typed[16] = reinterpret_cast(&list_copy_texture); list_typed[20] = reinterpret_cast(&list_topology); list_typed[21] = reinterpret_cast(&list_viewports); list_typed[22] = reinterpret_cast(&list_scissors); diff --git a/src/startup_stubs/list_copy_texture.h b/src/startup_stubs/list_copy_texture.h new file mode 100644 index 000000000..96603cf2b --- /dev/null +++ b/src/startup_stubs/list_copy_texture.h @@ -0,0 +1,171 @@ +// Experimental (docs/startup-runtime.md, #870): the argument checks for command list slot 16, +// CopyTextureRegion(dst, x, y, z, src, box). Plain standard C++ so a Linux fixture can run it; the +// handler (list_copy_texture.inl) maps the title's resources and forwards only what passes here. +// A call the desktop runtime would reject is refused with a named reason instead. +#pragma once + +#include +#include + +namespace x2w_list_copy_texture { + +enum class Kind : std::uint32_t { subresource = 0, placed_footprint = 1 }; + +// What the check needs to know about one side of the copy. For a subresource side, width/height/depth are +// the subresource's size in blocks (texels for an uncompressed format). For a footprint side, the footprint +// size in blocks, the row pitch in bytes, the byte offset and the bytes per block are used, and +// resource_bytes is the size of the buffer. +struct Side { + Kind kind; + std::uint32_t width, height, depth; + std::uint64_t offset; + std::uint32_t row_pitch, bytes_per_block; + std::uint64_t resource_bytes; + std::uint32_t samples; // sample count; a footprint (buffer) side is always 1 + std::uint32_t block_w, block_h; // texels per block (4 x 4 for block-compressed formats, else 1 x 1) + std::uint32_t format; // DXGI_FORMAT value of the subresource, or of the footprint + // A subresource side: its index and the resource's counts, for D3D12's + // index = mip + slice * mips + plane * mips * array_size. + std::uint32_t subresource, mips, array_size, planes; + bool depth_stencil = false; +}; + +struct Subresource { + std::uint32_t mip, slice, plane; +}; + +// Splits a subresource index by the desktop's math. False when the index is outside +// mips * array_size * planes (or a count is zero), so no mip, slice or plane aliases another. +inline bool decode_subresource(std::uint32_t index, std::uint32_t mips, std::uint32_t array_size, std::uint32_t planes, + Subresource& out) noexcept +{ + if (!mips || !array_size || !planes) return false; + const std::uint64_t per_plane = std::uint64_t{mips} * array_size; + if (index >= per_plane * planes) return false; + out = {static_cast(index % mips), static_cast((index / mips) % array_size), + static_cast(index / per_plane)}; + return true; +} + +struct Box { + std::uint32_t left, top, front, right, bottom, back; +}; + +enum class Verdict { + ok, + buffer_to_buffer, // a footprint on both sides: the desktop wants CopyBufferRegion + bad_box, // an empty or inverted source box + source_overflow, // the source box leaves the source subresource + dest_overflow, // the destination origin plus box size leaves the destination subresource + bad_pitch, // a footprint row pitch below one row, or not a multiple of 256 + bad_offset, // a footprint offset that is not a multiple of 512 + footprint_overflow, // the footprint reaches past the end of its buffer + sample_mismatch, // the two sides differ in sample count + bad_alignment, // a block-compressed copy that does not start on a block + bad_subresource, // an index outside the resource's mips * array slices * planes + format_mismatch, // the two sides name different formats + partial_multisample, // a multisampled copy that is not the whole subresource at the origin + partial_depth_stencil +}; + +inline const char* name(Verdict v) noexcept +{ + switch (v) { + case Verdict::ok: return "ok"; + case Verdict::buffer_to_buffer: return "buffer_to_buffer"; + case Verdict::bad_box: return "bad_box"; + case Verdict::source_overflow: return "source_overflow"; + case Verdict::dest_overflow: return "dest_overflow"; + case Verdict::bad_pitch: return "bad_pitch"; + case Verdict::bad_offset: return "bad_offset"; + case Verdict::footprint_overflow: return "footprint_overflow"; + case Verdict::sample_mismatch: return "sample_mismatch"; + case Verdict::bad_alignment: return "bad_alignment"; + case Verdict::bad_subresource: return "bad_subresource"; + case Verdict::format_mismatch: return "format_mismatch"; + case Verdict::partial_multisample: return "partial_multisample"; + case Verdict::partial_depth_stencil: return "partial_depth_stencil"; + } + return "unknown"; +} + +// a * b and a + b with the overflow reported, so no step of the footprint arithmetic wraps. +inline bool checked_mul(std::uint64_t a, std::uint64_t b, std::uint64_t& out) noexcept +{ + if (a && b > ~std::uint64_t{0} / a) return false; + out = a * b; + return true; +} +inline bool checked_add(std::uint64_t a, std::uint64_t b, std::uint64_t& out) noexcept +{ + if (b > ~std::uint64_t{0} - a) return false; + out = a + b; + return true; +} + +enum class End { ok, over_pitch, overflow }; + +// Bytes a footprint reaches for a w x h x d copy that starts at texel (ox, oy, oz) inside it, from its offset +// (the last row is not padded; slices are as tall as the footprint, not the copy). Every multiply and add is checked. +inline End footprint_end(const Side& s, std::uint32_t w, std::uint32_t h, std::uint32_t d, std::uint32_t ox, std::uint32_t oy, + std::uint32_t oz, std::uint64_t& end) noexcept +{ + if (!w || !h || !d) { end = s.offset; return End::ok; } + const std::uint64_t blocks_w = (std::uint64_t{w} + s.block_w - 1) / s.block_w; + const std::uint64_t rows = (std::uint64_t{h} + s.block_h - 1) / s.block_h; + const std::uint64_t start_row = oy / s.block_h; + const std::uint64_t slice_rows = (std::uint64_t{s.height} + s.block_h - 1) / s.block_h; + std::uint64_t row = 0, start_x = 0, row_end = 0; + if (!checked_mul(blocks_w, s.bytes_per_block, row) || !checked_mul(ox / s.block_w, s.bytes_per_block, start_x) || + !checked_add(start_x, row, row_end)) + return End::overflow; + if (row_end > s.row_pitch) return End::over_pitch; + std::uint64_t last_row = 0, row_bytes = 0, slice = 0, slice_bytes = 0, slices = 0, slices_bytes = 0, total = 0; + if (!checked_add(start_row, rows - 1, last_row) || !checked_mul(s.row_pitch, last_row, row_bytes) || + !checked_add(row_bytes, row_end, slice) || !checked_mul(s.row_pitch, slice_rows, slice_bytes) || + !checked_add(oz, d - 1, slices) || !checked_mul(slice_bytes, slices, slices_bytes) || + !checked_add(slices_bytes, slice, total) || !checked_add(s.offset, total, end)) + return End::overflow; + return End::ok; +} + +// box == nullptr copies the whole source (for a footprint source, the whole footprint). +inline Verdict check(const Side& dst, std::uint32_t x, std::uint32_t y, std::uint32_t z, const Side& src, const Box* box) noexcept +{ + if (dst.kind == Kind::placed_footprint && src.kind == Kind::placed_footprint) return Verdict::buffer_to_buffer; + for (const Side* s : {&dst, &src}) { + Subresource unused{}; + if (s->kind == Kind::subresource && !decode_subresource(s->subresource, s->mips, s->array_size, s->planes, unused)) + return Verdict::bad_subresource; + } + if (dst.samples != src.samples) return Verdict::sample_mismatch; + if (dst.format != src.format) return Verdict::format_mismatch; + const Box whole{0, 0, 0, src.width, src.height, src.depth}; + const Box use = box ? *box : whole; + if (use.left >= use.right || use.top >= use.bottom || use.front >= use.back) return Verdict::bad_box; + if (use.right > src.width || use.bottom > src.height || use.back > src.depth) return Verdict::source_overflow; + const Side& tex = dst.kind == Kind::subresource ? dst : src; // the side that knows the block size + if (x % tex.block_w || use.left % tex.block_w || y % tex.block_h || use.top % tex.block_h) return Verdict::bad_alignment; + const std::uint32_t w = use.right - use.left, h = use.bottom - use.top, d = use.back - use.front; + // D3D12 requires a null source box even if an explicit box would cover the whole subresource. + const bool depth_stencil = src.depth_stencil || dst.depth_stencil; + if ((src.samples > 1 || depth_stencil) && + (box || x || y || z || w != dst.width || h != dst.height || d != dst.depth)) + return src.samples > 1 ? Verdict::partial_multisample : Verdict::partial_depth_stencil; + if (std::uint64_t{x} + w > dst.width || std::uint64_t{y} + h > dst.height || std::uint64_t{z} + d > dst.depth) + return Verdict::dest_overflow; + for (const Side* s : {&dst, &src}) { + if (s->kind != Kind::placed_footprint) continue; + if (!s->row_pitch || s->row_pitch % 256) return Verdict::bad_pitch; + if (s->offset % 512) return Verdict::bad_offset; + std::uint64_t end = 0; + const bool is_dst = s == &dst; + const End reach = footprint_end(*s, w, h, d, is_dst ? x : use.left, is_dst ? y : use.top, is_dst ? z : use.front, end); + if (reach == End::over_pitch) return Verdict::bad_pitch; + if (reach == End::overflow) return Verdict::footprint_overflow; + if (end > s->resource_bytes) return Verdict::footprint_overflow; + } + return Verdict::ok; +} + +} // namespace x2w_list_copy_texture diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl new file mode 100644 index 000000000..3d9a4c31c --- /dev/null +++ b/src/startup_stubs/list_copy_texture.inl @@ -0,0 +1,165 @@ +// Included by d3d12_xs_device.cpp after d3d12_draw.inl. Command list slot 16, CopyTextureRegion (#870). +// Each location's resource is mapped to its desktop resource, the call is checked by +// list_copy_texture.h, the two resources move to COPY_SOURCE / COPY_DEST for the call (the list's Close +// puts them back to COMMON), and a call the desktop would reject is counted and logged, not forwarded. +#include "list_copy_texture.h" + +volatile LONG list_copy_texture_forwarded, list_copy_texture_refused; + +namespace { + +// Memory planes of a format on the resource's device (1 when the device cannot say). +UINT copy_texture_planes(ID3D12Resource* resource, DXGI_FORMAT format) +{ + ID3D12Device* device = nullptr; + if (FAILED(resource->GetDevice(IID_PPV_ARGS(&device))) || !device) return 1; + D3D12_FEATURE_DATA_FORMAT_INFO info{format, 1}; + const bool known = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &info, sizeof(info))); + device->Release(); + return known && info.PlaneCount ? info.PlaneCount : 1; +} + +// One side of the copy, read from the desktop resource it names. False when the location is unusable. +bool copy_texture_side(const D3D12_TEXTURE_COPY_LOCATION* location, ID3D12Resource*& real, x2w_list_copy_texture::Side& side, + DXGI_FORMAT& format, bool& bad_subresource) +{ + Wrapper* w = location && x2w_local::readable(location, sizeof(*location)) ? as_wrapper(location->pResource) : nullptr; + if (!w || w->own().kind != resource_kind || !w->own().real) return false; + real = static_cast(w->own().real); + const D3D12_RESOURCE_DESC desc = real->GetDesc(); + side = {}; + side.block_w = side.block_h = 1; + side.samples = desc.SampleDesc.Count ? desc.SampleDesc.Count : 1; + side.depth_stencil = (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) != 0 || + desc.Format == DXGI_FORMAT_D16_UNORM || desc.Format == DXGI_FORMAT_D32_FLOAT; + side.mips = side.array_size = side.planes = 1; + if (location->Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return false; + const auto& fp = location->PlacedFootprint; + side.kind = x2w_list_copy_texture::Kind::placed_footprint; + side.width = fp.Footprint.Width; + side.height = fp.Footprint.Height; + side.depth = fp.Footprint.Depth; + side.offset = fp.Offset; + side.row_pitch = fp.Footprint.RowPitch; + side.resource_bytes = desc.Width; + side.format = fp.Footprint.Format; + format = fp.Footprint.Format; + return true; + } + if (location->Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX || desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return false; + side.mips = desc.MipLevels ? desc.MipLevels : 1; + side.array_size = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1 : desc.DepthOrArraySize; + side.planes = copy_texture_planes(real, desc.Format); + side.subresource = location->SubresourceIndex; + side.format = desc.Format; + // The index must lie inside mips * array slices * planes; the mip it names sizes this side. + x2w_list_copy_texture::Subresource parts{}; + if (!x2w_list_copy_texture::decode_subresource(side.subresource, side.mips, side.array_size, side.planes, parts)) { + bad_subresource = true; + return false; + } + const UINT mip = parts.mip; + side.kind = x2w_list_copy_texture::Kind::subresource; + side.width = static_cast((std::max)(1, desc.Width >> mip)); + side.height = (std::max)(1, desc.Height >> mip); + side.depth = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? (std::max)(1, desc.DepthOrArraySize >> mip) : 1; + format = desc.Format; + return true; +} + +// Texels per block and bytes per block, from the desktop's own footprint for a one-subresource copy. +void copy_texture_block(ID3D12Resource* texture, x2w_list_copy_texture::Side& side) +{ + const D3D12_RESOURCE_DESC desc = texture->GetDesc(); + ID3D12Device* device = nullptr; + if (FAILED(texture->GetDevice(IID_PPV_ARGS(&device))) || !device) return; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + UINT rows = 0; + UINT64 row_bytes = 0, total = 0; + device->GetCopyableFootprints(&desc, 0, 1, 0, &fp, &rows, &row_bytes, &total); + device->Release(); + const bool bc = (desc.Format >= DXGI_FORMAT_BC1_TYPELESS && desc.Format <= DXGI_FORMAT_BC5_SNORM) || + (desc.Format >= DXGI_FORMAT_BC6H_TYPELESS && desc.Format <= DXGI_FORMAT_BC7_UNORM_SRGB); + side.block_w = side.block_h = bc ? 4 : 1; + const UINT64 blocks = (std::max)(1, (desc.Width + side.block_w - 1) / side.block_w); + side.bytes_per_block = static_cast(row_bytes / blocks); +} + +// Upload buffers stay in GENERIC_READ and readback buffers in COPY_DEST: the desktop refuses a barrier on either. +bool fixed_heap_state(ID3D12Resource* resource, D3D12_HEAP_TYPE& type) +{ + D3D12_HEAP_PROPERTIES props{}; + D3D12_HEAP_FLAGS flags{}; + if (FAILED(resource->GetHeapProperties(&props, &flags))) return false; + type = props.Type; + return type == D3D12_HEAP_TYPE_UPLOAD || type == D3D12_HEAP_TYPE_READBACK; +} + +} // namespace + +// List slot 16 (unshifted, like slots 12 to 25), CopyTextureRegion(dst, x, y, z, src, box). +void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, + const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box) +{ + if (!self->own().list_open) return; + static LONG logged; + const auto refuse = [&](const char* why) { + InterlockedIncrement(&list_copy_texture_refused); + if (first_calls(logged, 6)) log("x2w-d3d12 CopyTextureRegion refused: %s", why); + }; + ID3D12Resource *real_dst = nullptr, *real_src = nullptr; + x2w_list_copy_texture::Side side_dst{}, side_src{}; + DXGI_FORMAT format_dst = DXGI_FORMAT_UNKNOWN, format_src = DXGI_FORMAT_UNKNOWN; + bool bad_subresource = false; + if (!copy_texture_side(dst, real_dst, side_dst, format_dst, bad_subresource) || + !copy_texture_side(src, real_src, side_src, format_src, bad_subresource)) + return refuse(bad_subresource ? "bad_subresource" : "unknown_resource"); + // Planar (depth-stencil, video) copies name a plane footprint format; only single-plane copies are forwarded. + if (side_dst.planes > 1 || side_src.planes > 1) return refuse("planar_unsupported"); + ID3D12Resource* texture = side_dst.kind == x2w_list_copy_texture::Kind::subresource ? real_dst : real_src; + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource || side_src.kind == x2w_list_copy_texture::Kind::subresource) { + x2w_list_copy_texture::Side blocks{}; + copy_texture_block(texture, blocks); + for (auto* s : {&side_dst, &side_src}) { + s->block_w = blocks.block_w ? blocks.block_w : 1; + s->block_h = blocks.block_h ? blocks.block_h : 1; + if (s->kind == x2w_list_copy_texture::Kind::placed_footprint) s->bytes_per_block = blocks.bytes_per_block; + } + } + x2w_list_copy_texture::Box copy_box{}; + if (box && x2w_local::readable(box, sizeof(*box))) copy_box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; + const auto verdict = x2w_list_copy_texture::check(side_dst, x, y, z, side_src, box ? ©_box : nullptr); + if (verdict != x2w_list_copy_texture::Verdict::ok) return refuse(x2w_list_copy_texture::name(verdict)); + // One resource tracks one state, so two subresources of it cannot be COPY_SOURCE and COPY_DEST at once. + if (real_src == real_dst) return refuse("same_resource"); + D3D12_HEAP_TYPE heap = D3D12_HEAP_TYPE_DEFAULT; + const bool src_fixed = fixed_heap_state(real_src, heap); + if (src_fixed && heap == D3D12_HEAP_TYPE_READBACK) return refuse("bad_heap"); + const bool dst_fixed = fixed_heap_state(real_dst, heap); + if (dst_fixed && heap == D3D12_HEAP_TYPE_UPLOAD) return refuse("bad_heap"); + Wrapper* const src_wrapper = as_wrapper(src->pResource); + Wrapper* const dst_wrapper = as_wrapper(dst->pResource); + // A copied (non-aliased) buffer has no refresh path here, so its desktop bytes may be stale. + if (side_src.kind == x2w_list_copy_texture::Kind::placed_footprint) { + const auto* info = resource_info(src_wrapper); + if (info && info->placement == Placement::copied_buffer) return refuse("stale_source"); + } + // Bring a texture's desktop copy up to date with its guest backing before the copy reads or partly overwrites it, + // and record that upload so a later sample does not replace the copied texels. + if (side_src.kind == x2w_list_copy_texture::Kind::subresource) upload_texture(self, src_wrapper, real_src); + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource) upload_texture(self, dst_wrapper, real_dst); + if (!src_fixed) require_state(self, real_src, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (!dst_fixed) require_state(self, real_dst, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_TEXTURE_COPY_LOCATION to = *dst, from = *src; + to.pResource = real_dst; + from.pResource = real_src; + static_cast(self->own().real)->CopyTextureRegion(&to, x, y, z, &from, box ? box : nullptr); + InterlockedIncrement(&list_copy_texture_forwarded); +} + +extern "C" __declspec(dllexport) void x2w_d3d12_list_copy_texture_stats(LONG* forwarded, LONG* refused) +{ + if (forwarded) *forwarded = list_copy_texture_forwarded; + if (refused) *refused = list_copy_texture_refused; +} diff --git a/tests/startup_list_copy_texture_check.cpp b/tests/startup_list_copy_texture_check.cpp new file mode 100644 index 000000000..bfd55e9c8 --- /dev/null +++ b/tests/startup_list_copy_texture_check.cpp @@ -0,0 +1,130 @@ +// Experimental (docs/startup-runtime.md, #870): the argument checks of command list slot 16, +// CopyTextureRegion (src/startup_stubs/list_copy_texture.h). Plain standard C++, synthetic sizes only. +// --mutate overflow drops the destination bounds check, --mutate slice reads an out-of-range array slice as valid; each run must then fail (negative controls). +#include "../src/startup_stubs/list_copy_texture.h" + +#include +#include + +using namespace x2w_list_copy_texture; + +namespace { +int failures; +void expect(Verdict got, Verdict want, const char* what) +{ + if (got != want) { + std::fprintf(stderr, "FAIL: %s: got %s, want %s\n", what, name(got), name(want)); + ++failures; + } +} +constexpr std::uint32_t rgba8 = 28; // DXGI_FORMAT_R8G8B8A8_UNORM +constexpr std::uint32_t bc1 = 71; // DXGI_FORMAT_BC1_UNORM +Side texture(std::uint32_t w, std::uint32_t h, std::uint32_t block = 1) +{ + return {Kind::subresource, w, h, 1, 0, 0, 0, 0, 1, block, block, block > 1 ? bc1 : rgba8, 0, 1, 1, 1}; +} +Side footprint(std::uint32_t w, std::uint32_t h, std::uint64_t offset, std::uint32_t pitch, std::uint32_t bpb, + std::uint64_t bytes, std::uint32_t block = 1) +{ + return {Kind::placed_footprint, w, h, 1, offset, pitch, bpb, bytes, 1, block, block, block > 1 ? bc1 : rgba8, 0, 1, 1, 1}; +} +} // namespace + +int main(int argc, char** argv) +{ + const bool mutate = argc > 2 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], "overflow"); + const bool mutate_slice = argc > 2 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], "slice"); + + expect(check(texture(64, 64), 0, 0, 0, texture(64, 64), nullptr), Verdict::ok, "whole texture"); + expect(check(texture(64, 64), 32, 32, 0, texture(64, 64), &(const Box&)Box{0, 0, 0, 32, 32, 1}), Verdict::ok, "corner box"); + // The destination origin pushes the box past the destination. + const Verdict past = check(texture(64, 64), 40, 0, 0, texture(64, 64), &(const Box&)Box{0, 0, 0, 32, 32, 1}); + expect(mutate ? Verdict::ok : past, Verdict::dest_overflow, "dest overflow"); + expect(check(texture(64, 64), 0, 0, 0, texture(64, 64), &(const Box&)Box{0, 0, 0, 65, 8, 1}), Verdict::source_overflow, "source overflow"); + expect(check(texture(64, 64), 0, 0, 0, texture(64, 64), &(const Box&)Box{8, 0, 0, 8, 8, 1}), Verdict::bad_box, "empty box"); + expect(check(footprint(16, 16, 0, 64, 4, 4096), 0, 0, 0, footprint(16, 16, 0, 64, 4, 4096), nullptr), Verdict::buffer_to_buffer, "two buffers"); + + // Texture to a 16x16 RGBA8 footprint: 64-byte rows would be below 256, so the pitch is refused. + expect(check(footprint(16, 16, 0, 64, 4, 1 << 20), 0, 0, 0, texture(16, 16), nullptr), Verdict::bad_pitch, "pitch not 256"); + expect(check(footprint(16, 16, 0, 256, 4, 1 << 20), 0, 0, 0, texture(16, 16), nullptr), Verdict::ok, "footprint ok"); + expect(check(footprint(16, 16, 256, 256, 4, 1 << 20), 0, 0, 0, texture(16, 16), nullptr), Verdict::bad_offset, "offset not 512"); + // 16 rows of 256 bytes, the last row 64 bytes: 15 * 256 + 64 = 3904 bytes from offset 512. + expect(check(footprint(16, 16, 512, 256, 4, 512 + 3904), 0, 0, 0, texture(16, 16), nullptr), Verdict::ok, "last row not padded"); + expect(check(footprint(16, 16, 512, 256, 4, 512 + 3903), 0, 0, 0, texture(16, 16), nullptr), Verdict::footprint_overflow, "one byte short"); + // Row wider than the pitch. + expect(check(footprint(128, 4, 0, 256, 4, 1 << 20), 0, 0, 0, texture(128, 4), nullptr), Verdict::bad_pitch, "row over pitch"); + + // Block-compressed: 4x4 blocks of 8 bytes; a 6-texel start is not on a block. + expect(check(texture(64, 64, 4), 6, 0, 0, texture(64, 64, 4), nullptr), Verdict::bad_alignment, "block alignment"); + expect(check(footprint(64, 64, 0, 256, 8, 256 * 16, 4), 0, 0, 0, texture(64, 64, 4), nullptr), Verdict::ok, "bc footprint"); + + // The destination origin counts: a 1x1 RGBA8 copy at Y=63 of a 64x64, 256-pitch footprint ends at byte 16132. + expect(check(footprint(64, 64, 0, 256, 4, 256), 0, 63, 0, texture(1, 1), nullptr), Verdict::footprint_overflow, "dest origin counts"); + expect(check(footprint(64, 64, 0, 256, 4, 16132), 0, 63, 0, texture(1, 1), nullptr), Verdict::ok, "dest origin fits"); + // The source box origin counts too. + expect(check(texture(1, 1), 0, 0, 0, footprint(64, 64, 0, 256, 4, 256), &(const Box&)Box{0, 63, 0, 1, 64, 1}), Verdict::footprint_overflow, "box origin counts"); + // 3D: a slice is as tall as the footprint (64 rows), not as the copy (1 row). + Side volume = footprint(64, 64, 0, 256, 4, 256 * 64); + volume.depth = 4; + expect(check(volume, 0, 0, 1, texture(1, 1), nullptr), Verdict::footprint_overflow, "slice stride from footprint height"); + + Side ms = texture(64, 64); + ms.samples = 4; + expect(check(texture(64, 64), 0, 0, 0, ms, nullptr), Verdict::sample_mismatch, "multisampled source"); + Side ms2 = ms; + ms2.samples = 2; + expect(check(ms2, 0, 0, 0, ms, nullptr), Verdict::sample_mismatch, "2x against 4x"); + expect(check(ms, 0, 0, 0, ms, nullptr), Verdict::ok, "whole 4x subresource"); + const Box full_box{0, 0, 0, 64, 64, 1}; + expect(check(ms, 0, 0, 0, ms, &full_box), Verdict::partial_multisample, "4x explicit full box"); + Side depth = texture(64, 64); + depth.depth_stencil = true; + expect(check(depth, 0, 0, 0, depth, nullptr), Verdict::ok, "whole depth subresource"); + expect(check(depth, 0, 0, 0, depth, &full_box), Verdict::partial_depth_stencil, "depth explicit full box"); + expect(check(ms, 8, 0, 0, ms, &(const Box&)Box{0, 0, 0, 56, 64, 1}), Verdict::partial_multisample, "4x offset"); + expect(check(ms, 0, 0, 0, ms, &(const Box&)Box{0, 0, 0, 32, 32, 1}), Verdict::partial_multisample, "4x partial box"); + expect(check(footprint(64, 64, 0, 256, 4, 1 << 20), 0, 0, 0, ms, nullptr), Verdict::sample_mismatch, "4x to buffer"); + + // Formats must be the same. + Side bgra = texture(64, 64); + bgra.format = 87; // DXGI_FORMAT_B8G8R8A8_UNORM + expect(check(bgra, 0, 0, 0, texture(64, 64), nullptr), Verdict::format_mismatch, "texture formats differ"); + Side fp_bc = footprint(64, 64, 0, 256, 4, 1 << 20); + fp_bc.format = bc1; + expect(check(fp_bc, 0, 0, 0, texture(64, 64), nullptr), Verdict::format_mismatch, "footprint format differs"); + + // Subresource index = mip + slice * mips + plane * mips * array_size. + Subresource parts{}; + expect(decode_subresource(7, 3, 2, 2, parts) && parts.mip == 1 && parts.slice == 0 && parts.plane == 1 ? Verdict::ok : Verdict::bad_box, + Verdict::ok, "decode mip 1, slice 0, plane 1"); + expect(decode_subresource(5, 3, 2, 1, parts) && parts.mip == 2 && parts.slice == 1 && parts.plane == 0 ? Verdict::ok : Verdict::bad_box, + Verdict::ok, "decode mip 2, slice 1"); + expect(decode_subresource(11, 3, 2, 2, parts) ? Verdict::ok : Verdict::bad_subresource, Verdict::ok, "last index of 3 x 2 x 2"); + expect(decode_subresource(12, 3, 2, 2, parts) ? Verdict::ok : Verdict::bad_subresource, Verdict::bad_subresource, "index past the planes"); + expect(decode_subresource(0, 0, 1, 1, parts) ? Verdict::ok : Verdict::bad_subresource, Verdict::bad_subresource, "zero mips"); + // A 4-mip, 3-slice texture has 12 subresources; index 12 is the first past the last slice, and the old + // mip-only modulo would have read it as mip 0. + Side arr = texture(64, 64); + arr.mips = 4; + arr.array_size = 3; + arr.subresource = 11; + expect(check(arr, 0, 0, 0, texture(64, 64), nullptr), Verdict::ok, "last array subresource"); + arr.subresource = 12; + expect(mutate_slice ? Verdict::ok : check(arr, 0, 0, 0, texture(64, 64), nullptr), Verdict::bad_subresource, "slice out of range"); + expect(check(texture(64, 64), 0, 0, 0, arr, nullptr), Verdict::bad_subresource, "source slice out of range"); + arr.subresource = 0xffffffffu; + expect(check(arr, 0, 0, 0, texture(64, 64), nullptr), Verdict::bad_subresource, "huge index"); + + // Footprint arithmetic is checked at every multiply and add. + Side wide = footprint(64, 0xffffffffu, 0, 256, 4, ~std::uint64_t{0}); + wide.depth = 0xffffffffu; + Side big = texture(64, 0xffffffffu); + big.depth = 0xffffffffu; + expect(check(wide, 0, 0, 0xfffffffeu, big, &(const Box&)Box{0, 0, 0, 1, 1, 1}), Verdict::footprint_overflow, "slice stride overflow"); + expect(check(footprint(1, 3, ~std::uint64_t{0} - 511, 256, 4, ~std::uint64_t{0}), 0, 0, 0, texture(1, 3), nullptr), + Verdict::footprint_overflow, "offset plus size wraps"); + + if (failures) return 1; + std::puts("ok"); + return 0; +} diff --git a/tests/startup_list_copy_texture_warp.cpp b/tests/startup_list_copy_texture_warp.cpp new file mode 100644 index 000000000..46e6e033a --- /dev/null +++ b/tests/startup_list_copy_texture_warp.cpp @@ -0,0 +1,216 @@ +// CopyTextureRegion (command list slot 16) through the wrapped list, read back (#870). +// +// startup_list_copy_texture_warp (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe makes a 4x4 RGBA8 texture with 2 mips and 3 array slices (six +// subresources), an upload buffer holding two distinct 4x4 images and a readback buffer, all as console +// resources. Then it records, submits and reads back: +// +// 1. upload image A -> subresource 2 (mip 0, slice 1), image B -> subresource 4 (mip 0, slice 2), and both +// back to the readback buffer: the readback holds A then B, and both copies were forwarded. +// 2. a list whose three calls must each be refused before any desktop copy: subresource 6 (one past the last +// array slice, which a mip-only modulo would read as mip 0), subresource 0xffffffff, and a footprint +// format that differs from the texture's. The readback buffer, pre-filled with a sentinel, is unchanged, +// and the refusal counter rises by three with the forward counter unchanged. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include + +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_texture_stats(LONG* forwarded, LONG* refused); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0, Word g = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f, g); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +constexpr UINT side = 4, mips = 2, slices = 3, pitch = 256; +constexpr UINT image_bytes = 1024; // 4 rows at the 256-byte pitch; image B starts at this offset (a multiple of 512) +constexpr std::uint8_t sentinel = 0xcd; + +// A console resource through device slot 127 (CreateCommittedResource3). +void* make_resource(void* device, D3D12_HEAP_TYPE type, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state) +{ + using Create = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, const GUID*, void**); + const D3D12_HEAP_PROPERTIES heap{type}; + void* resource = nullptr; + const auto create = reinterpret_cast((*static_cast(device))[127]); + return SUCCEEDED(create(device, &heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, nullptr, 0, nullptr, + &__uuidof(ID3D12Resource), &resource)) + ? resource + : nullptr; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) +{ + return {D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; +} + +D3D12_TEXTURE_COPY_LOCATION footprint(void* buffer, UINT64 offset, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM) +{ + D3D12_TEXTURE_COPY_LOCATION location{static_cast(buffer), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + location.PlacedFootprint = {offset, {format, side, side, 1, pitch}}; + return location; +} + +D3D12_TEXTURE_COPY_LOCATION subresource(void* texture, UINT index) +{ + D3D12_TEXTURE_COPY_LOCATION location{static_cast(texture), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + location.SubresourceIndex = index; + return location; +} + +// Image A holds byte i*3+1 at texel byte i, image B byte 255-i*5 (both wrap at 256). +std::uint8_t image_byte(int image, UINT row, UINT column) +{ + const UINT i = row * side * 4 + column; + return image == 0 ? static_cast(i * 3 + 1) : static_cast(255 - i * 5); +} + +bool wait_for(void* fence, Word value) +{ + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; +} + +// Compares the 4x4 image the readback buffer holds at offset against image number, row by row. +bool image_matches(const std::uint8_t* memory, UINT offset, int image) +{ + for (UINT row = 0; row < side; ++row) + for (UINT column = 0; column < side * 4; ++column) + if (memory[offset + row * pitch + column] != image_byte(image, row, column)) { + std::printf("image %d row %u byte %u: got %02x want %02x\n", image, row, column, memory[offset + row * pitch + column], + image_byte(image, row, column)); + return false; + } + return true; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + + const D3D12_RESOURCE_DESC texture_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, slices, mips, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + void* texture = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, texture_desc, D3D12_RESOURCE_STATE_COMMON); + void* upload = make_resource(device, D3D12_HEAP_TYPE_UPLOAD, buffer_desc(2 * image_bytes), D3D12_RESOURCE_STATE_GENERIC_READ); + void* readback = make_resource(device, D3D12_HEAP_TYPE_READBACK, buffer_desc(2 * image_bytes), D3D12_RESOURCE_STATE_COPY_DEST); + if (!texture || !upload || !readback) return 5; + + void* memory = nullptr; + if (!ok(invoke(upload, 8, 0, 0, arg(&memory))) || !memory) return 6; + for (int image = 0; image < 2; ++image) + for (UINT row = 0; row < side; ++row) + for (UINT column = 0; column < side * 4; ++column) + static_cast(memory)[image * image_bytes + row * pitch + column] = image_byte(image, row, column); + invoke(upload, 9, 0, 0); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *queue = nullptr, *fence = nullptr, *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + Word fence_value = 0; + const auto submit = [&] { + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + return ok(invoke(queue, 14, arg(fence), ++fence_value)) && wait_for(fence, fence_value); + }; + const auto copy = [&](const D3D12_TEXTURE_COPY_LOCATION& to, const D3D12_TEXTURE_COPY_LOCATION& from) { + invoke(list, 16, arg(&to), 0, 0, 0, arg(&from), 0); + }; + LONG forwarded = 0, refused = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded, &refused); + + // 1. Two distinct images into two array slices and back. + const auto a_up = footprint(upload, 0), b_up = footprint(upload, image_bytes); + const auto a_out = footprint(readback, 0), b_out = footprint(readback, image_bytes); + const auto slice1 = subresource(texture, 2), slice2 = subresource(texture, 4); + if (!ok(invoke(list, 139, arg(allocator), 0))) return 8; + copy(slice1, a_up); + copy(slice2, b_up); + copy(a_out, slice1); + copy(b_out, slice2); + if (!ok(invoke(list, 9)) || !submit()) return 9; + LONG forwarded1 = 0, refused1 = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded1, &refused1); + std::printf("1 forwarded +%ld refused +%ld (expected +4, +0)\n", forwarded1 - forwarded, refused1 - refused); + if (forwarded1 - forwarded != 4 || refused1 != refused) return 10; + if (!ok(invoke(readback, 8, 0, 0, arg(&memory))) || !memory) return 11; + const bool images = image_matches(static_cast(memory), 0, 0) && + image_matches(static_cast(memory), image_bytes, 1); + std::memset(memory, sentinel, 2 * image_bytes); // mapped readback memory is CPU-writable for the next step + invoke(readback, 9, 0, 0); + if (!images) return 12; + + // 2. Out-of-range subresources and a format mismatch are refused before any desktop copy. + if (!ok(invoke(list, 139, arg(allocator), 0))) return 13; + copy(a_out, subresource(texture, mips * slices)); // one past the last array slice + copy(subresource(texture, 0xffffffffu), a_up); // an index far outside + copy(subresource(texture, 0), footprint(upload, 0, DXGI_FORMAT_B8G8R8A8_UNORM)); // formats differ + if (!ok(invoke(list, 9)) || !submit()) return 14; + LONG forwarded2 = 0, refused2 = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded2, &refused2); + std::printf("2 forwarded +%ld refused +%ld (expected +0, +3)\n", forwarded2 - forwarded1, refused2 - refused1); + if (forwarded2 != forwarded1 || refused2 - refused1 != 3) return 15; + if (!ok(invoke(readback, 8, 0, 0, arg(&memory))) || !memory) return 16; + bool unchanged = true; + for (UINT i = 0; i < 2 * image_bytes; ++i) unchanged = unchanged && static_cast(memory)[i] == sentinel; + invoke(readback, 9, 0, 0); + if (!unchanged) { + std::puts("2 the readback buffer changed"); + return 17; + } + std::puts("ok"); + return 0; +} From a4900150ea8ecc479ccc4a11fc28e6dd848eb255 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Wed, 25 Nov 2026 22:56:06 +0800 Subject: [PATCH 046/232] tests: verify exact front-face winding through slot 86 streams (#2387) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/startup-runtime.md | 5 +++-- tests/startup_stream_rasterizer.cpp | 15 ++++++++++++++- tests/startup_stream_rasterizer_check.py | 16 ++++++++++------ 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a0381981c..a3f1cf8fd 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2014,8 +2014,9 @@ These are measured on one executable; treat them as hypotheses for others. `ctest --preset release --no-tests=error -R "^startup_stream_(request|draw)_"`. A stream `RASTERIZER` or `RASTERIZER1` subobject sets the translated pipeline's fill, cull and depth clip. `RASTERIZER1` stores depth bias as a float; a value that is not an integer in the desktop range - refuses the pipeline. The cull check is - `ctest --preset release --no-tests=error -R "^startup_stream_rasterizer_"`. + refuses the pipeline. Run `ctest --preset release --no-tests=error -R "^startup_stream_rasterizer_"` + to check all 32 pixels for front and back culling, with each front-face winding and both stream + subobject types. The ignore control expects the no-cull readback and fails. Stream depth-stencil state is already applied on this path. Geometry, hull, domain and compute stages remain open. - Translated draws use the bound typed RTV formats to request colour-export variants. The diff --git a/tests/startup_stream_rasterizer.cpp b/tests/startup_stream_rasterizer.cpp index b88208b35..18dce8f30 100644 --- a/tests/startup_stream_rasterizer.cpp +++ b/tests/startup_stream_rasterizer.cpp @@ -145,7 +145,7 @@ int execute_guest_list(void* queue, void* list, void* fence, UINT64 fence_value) int main(int argc, char** argv) { - if (argc != 5 && argc != 13) return 2; + if (argc != 5 && argc != 13 && argc != 17) return 2; std::vector vs, ps; if (!read_bytes(argv[1], vs) || !read_bytes(argv[2], ps)) return 3; const bool hardware = std::strcmp(argv[4], "hardware") == 0; @@ -248,5 +248,18 @@ int main(int argc, char** argv) if (const int rc = run_case(6, argv[10], pso_bias)) return rc; if (const int rc = run_case(7, argv[11], mixed_10_27)) return rc; if (const int rc = run_case(8, argv[12], mixed_27_10)) return rc; + if (argc == 17) { + int output = 13; + for (int kind : {1, 2}) { + for (auto cull : {D3D12_CULL_MODE_BACK, D3D12_CULL_MODE_FRONT}) { + auto raster = raster_desc(cull, TRUE); + raster.FrontCounterClockwise = TRUE; + void* pso = create_stream_pso(guest, root, vs, ps, kind, raster, 0); + if (!pso) return 9; + if (const int rc = run_case(output - 4, argv[output], pso)) return rc; + ++output; + } + } + } return 0; } diff --git a/tests/startup_stream_rasterizer_check.py b/tests/startup_stream_rasterizer_check.py index 9ca49ba6f..ccf7becb7 100644 --- a/tests/startup_stream_rasterizer_check.py +++ b/tests/startup_stream_rasterizer_check.py @@ -15,6 +15,8 @@ def check(directory, consumer, backend, mode): cache.mkdir() vs, ps, root = (directory / name for name in ("vs", "ps", "root")) cases = ("back", "front", "dropped", "r1_back", "r1_front", "bias", "mixed_10_27", "mixed_27_10") + if mode != "ignore": + cases += ("ccw_back", "ccw_front", "r1_ccw_back", "r1_ccw_front") outs = {name: directory / name for name in cases} vs.write_bytes(vertex()) ps.write_bytes(pixel(True)) @@ -63,15 +65,17 @@ def check(directory, consumer, backend, mode): return 1 assert images["dropped"] == drawn, f"dropped: {images['dropped'].hex()}" - assert images["back"] != images["front"], "front and back cull produced the same readback" - assert {images["back"], images["front"]} == {drawn, blank}, ( - f"back {images['back'].hex()} front {images['front'].hex()}") - assert images["r1_back"] == images["back"], f"rasterizer1 back: {images['r1_back'].hex()}" - assert images["r1_front"] == images["front"], f"rasterizer1 front: {images['r1_front'].hex()}" + # vertex() emits (-1,-1), (3,-1), (-1,3): counterclockwise as seen on the target. + # With the default clockwise front face it survives front culling. Flipping the + # winding bit makes it survive back culling for either stream subobject. + for name in ("front", "r1_front", "ccw_back", "r1_ccw_back"): + assert images[name] == drawn, f"{name}: expected the scissored triangle, got {images[name].hex()}" + for name in ("back", "r1_back", "ccw_front", "r1_ccw_front"): + assert images[name] == blank, f"{name}: expected the clear target, got {images[name].hex()}" assert images["bias"] == blank, f"fractional depth bias drew: {images['bias'].hex()}" mixed_draws = [name for name in ("mixed_10_27", "mixed_27_10") if images[name] != blank] assert not mixed_draws, f"duplicate rasterizer state drew pixels: {mixed_draws}" - print(f"{backend}: cull changed the readback; fractional bias and both mixed rasterizer orders stayed clear") + print(f"{backend}: eight cull/winding images matched; fractional bias and both mixed rasterizer orders stayed clear") return 0 From 0736f67c504cbed815d4ec0295636818f4d9f144 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:56:57 +0100 Subject: [PATCH 047/232] ci: save main sccache right after build; pull requests only read it (#1740) * ci: save the main sccache right after the build; pull requests only read it Main never held a compiler cache: actions/cache saves only when the job succeeds, and the cold job times out first (0 hits, 765 misses at 17:13 UTC). Build now runs in its own step on push, the cache is saved before ctest, and pull requests restore main's entries without writing their own. The pip cache is no longer written per pull request. * ci: skip sccache save on exact cache hit * ci: reuse pre-build sccache primary key when saving and exclude out/** Reuse steps.sccache-restore.outputs.cache-primary-key in both dev and release actions/cache/save steps so generated build outputs in out/ cannot drift the save key away from the pre-build restore key. Also exclude !out/** in hashFiles() on both restore steps so pre-build files under out/ do not affect the primary key. * ci: do not fail a built job when the compiler-cache save fails A save that hits quota or a key race should not turn a green build red before its tests run. Both Save compiler cache steps now continue on error. --- .github/workflows/windows.yml | 63 +++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index edf313d13..9d2e61a54 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -296,7 +296,7 @@ jobs: - uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 with: python-version: '3.12' - cache: 'pip' + cache: ${{ github.event_name != 'pull_request' && 'pip' || '' }} cache-dependency-path: 'requirements-dev.txt' architecture: x64 - name: Install fixture dependencies @@ -322,14 +322,38 @@ jobs: run: .\tools\setup-spirv-tools.ps1 - name: Install sccache uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 + # Only main saves the compiler cache; pull requests read it (restore-keys) and never write a + # per-PR copy, which filled the repository cache limit. The cache is saved right after the + # build, before the tests, so a run that later times out still leaves a warm cache behind. - name: Restore compiler cache - uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + id: sccache-restore + uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: ${{ runner.temp }}/sccache - key: sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-${{ github.event_name == 'pull_request' && 'pr' || 'dev' }}-${{ hashFiles('CMakeLists.txt', 'CMakePresets.json', 'cmake/**', '**/*.c', '**/*.cc', '**/*.cpp', '**/*.h', '**/*.hpp', '**/*.inc', '**/*.inl', '**/*.asm') }} + key: sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-dev-${{ hashFiles('CMakeLists.txt', 'CMakePresets.json', 'cmake/**', '**/*.c', '**/*.cc', '**/*.cpp', '**/*.h', '**/*.hpp', '**/*.inc', '**/*.inl', '**/*.asm', '!out/**') }} restore-keys: | - sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-${{ github.event_name == 'pull_request' && 'pr' || 'dev' }}- sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-dev- + - name: Build on Windows + id: build + if: github.event_name != 'pull_request' + shell: pwsh + env: + X2W_REQUIRE_SPIRV_TOOLS: '1' + X2W_USE_SCCACHE: '1' + run: | + .\tools\dev.ps1 + cmake --preset dev @X2wSccacheCmakeArgs + if ($LASTEXITCODE) { exit $LASTEXITCODE } + cmake --build --preset dev + if ($LASTEXITCODE) { exit $LASTEXITCODE } + if (Get-Command sccache -CommandType Application -ErrorAction SilentlyContinue) { sccache --show-stats } + - name: Save compiler cache + if: ${{ !cancelled() && github.event_name != 'pull_request' && steps.build.outcome != 'skipped' && steps.sccache-restore.outputs.cache-hit != 'true' }} + continue-on-error: true + uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + with: + path: ${{ runner.temp }}/sccache + key: ${{ steps.sccache-restore.outputs.cache-primary-key }} - name: Configure, build and run PC tests shell: pwsh env: @@ -398,7 +422,7 @@ jobs: - uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 with: python-version: '3.12' - cache: 'pip' + cache: ${{ github.event_name != 'pull_request' && 'pip' || '' }} cache-dependency-path: 'requirements-dev.txt' architecture: x64 - name: Install fixture dependencies @@ -424,13 +448,38 @@ jobs: run: .\tools\setup-spirv-tools.ps1 - name: Install sccache uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 + # Only main saves the compiler cache; pull requests read it (restore-keys) and never write a + # per-PR copy, which filled the repository cache limit. The cache is saved right after the + # build, before the tests, so a run that later times out still leaves a warm cache behind. - name: Restore compiler cache - uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + id: sccache-restore + uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: ${{ runner.temp }}/sccache - key: sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-release-${{ hashFiles('CMakeLists.txt', 'CMakePresets.json', 'cmake/**', '**/*.c', '**/*.cc', '**/*.cpp', '**/*.h', '**/*.hpp', '**/*.inc', '**/*.inl', '**/*.asm') }} + key: sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-release-${{ hashFiles('CMakeLists.txt', 'CMakePresets.json', 'cmake/**', '**/*.c', '**/*.cc', '**/*.cpp', '**/*.h', '**/*.hpp', '**/*.inc', '**/*.inl', '**/*.asm', '!out/**') }} restore-keys: | sccache-${{ runner.os }}-msvc-${{ steps.toolset.outputs.msvc }}-release- + - name: Build on Windows at /O2 + id: build + if: github.event_name != 'pull_request' + shell: pwsh + env: + X2W_REQUIRE_SPIRV_TOOLS: '1' + X2W_USE_SCCACHE: '1' + run: | + .\tools\dev.ps1 + cmake --preset release @X2wSccacheCmakeArgs + if ($LASTEXITCODE) { exit $LASTEXITCODE } + cmake --build --preset release + if ($LASTEXITCODE) { exit $LASTEXITCODE } + if (Get-Command sccache -CommandType Application -ErrorAction SilentlyContinue) { sccache --show-stats } + - name: Save compiler cache + if: ${{ !cancelled() && github.event_name != 'pull_request' && steps.build.outcome != 'skipped' && steps.sccache-restore.outputs.cache-hit != 'true' }} + continue-on-error: true + uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + with: + path: ${{ runner.temp }}/sccache + key: ${{ steps.sccache-restore.outputs.cache-primary-key }} - name: Configure, build and run PC tests at /O2 shell: pwsh env: From 628fb11acc6f5b31dfab56281ca9ada4d0b17fdc Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:01:12 +0100 Subject: [PATCH 048/232] tooling: handle comments and 64-bit indices in address-window lowering (#1610) * tooling: handle comments and 64-bit indices in address-window lowering Strip trailing semicolon comments (preserving semicolons inside string literals) before matching instructions in spirv_address_window.py. Avoid re-widening 64-bit OpAccessChain indices, bit-cast signed 64-bit indices to %ulong, and guard 64-bit index left shifts against wrap-around. * fix: keep multiline string literals intact when stripping address-window comments --- tests/spirv_window/check.py | 65 ++++++++++++++++++++++++++++++++++- tools/spirv_address_window.py | 65 ++++++++++++++++++++++++++++++----- 2 files changed, 120 insertions(+), 10 deletions(-) diff --git a/tests/spirv_window/check.py b/tests/spirv_window/check.py index e0ad1d82e..6a232b5b8 100644 --- a/tests/spirv_window/check.py +++ b/tests/spirv_window/check.py @@ -307,4 +307,67 @@ def block(stem, condition): assert lowered_atomics[at - 3] == f"OpSelectionMerge {stem}_merge None" assert lowered_atomics[at + 1] == f"OpBranch {stem}_merge" assert lowered_atomics[at + 3].startswith(f"{result} = OpPhi %uint {stem}_old {stem}_issue %c0 ") -print("physical, logical and combined SPIR-V validated; 8 atomics, bounded QWORD accesses and rejection cases passed") + +# Comments and 64-bit indices in the source assembly: the lowering must either keep the module valid or refuse it. +atomic_source = Path(__file__).with_name("atomic.spvasm").read_text(encoding="utf-8") +access = "%target = OpAccessChain %_ptr_PSB_uint %array %c1" +entry = 'OpEntryPoint GLCompute %main "main" %user_data' +assert access in atomic_source and entry in atomic_source +with tempfile.TemporaryDirectory() as folder: + directory = Path(folder) + # A trailing comment on an instruction the lowering rewrites, on the entry point, and one that + # mentions a word the lowering looks for, must not change the result. + commented = atomic_source.replace(access, access + " ; element one of the array") + commented = commented.replace(entry, entry + " ; the interface lists the push constants") + commented = commented.replace("OpReturn", "; a comment that says PushConstant\nOpReturn") + validate_sampler(directory, "commented_original", commented) + assert window.lower(commented) == window.lower(atomic_source) + validate_sampler(directory, "commented_lowered", window.lower(commented)) + + # A semicolon inside a quoted string literal must survive comment stripping. + quoted_semi = atomic_source.replace("OpExecutionMode %main LocalSize 1 1 1", + 'OpExecutionMode %main LocalSize 1 1 1\nOpName %main "main;tag" ; trailing comment', 1) + validate_sampler(directory, "quoted_semi_original", quoted_semi) + quoted_lowered = window.lower(quoted_semi) + validate_sampler(directory, "quoted_semi_lowered", quoted_lowered) + assert 'OpName %main "main;tag"' in quoted_lowered.splitlines() + + # A string literal may span lines; a semicolon on a continuation line is text, not a comment, and the + # literal keeps its inner newline and spacing. + multiline = atomic_source.replace("OpExecutionMode %main LocalSize 1 1 1", + 'OpExecutionMode %main LocalSize 1 1 1\n%text = OpString "first line\n int tmp = 0; }" ; note', 1) + validate_sampler(directory, "multiline_original", multiline) + multiline_lowered = window.lower(multiline) + validate_sampler(directory, "multiline_lowered", multiline_lowered) + assert '%text = OpString "first line\n int tmp = 0; }"' in multiline_lowered + + # An index that is already 64 bits wide is used as it is (not converted again) and guarded against + # shift wrap-around so a huge 64-bit index cannot drop high bits and alias an in-window address. + wide_index = atomic_source.replace(access, "%index64 = OpUConvert %ulong %c1\n" + "%target = OpAccessChain %_ptr_PSB_uint %array %index64") + assert wide_index != atomic_source + validate_sampler(directory, "wide_index_original", wide_index) + wide_lowered = window.lower(wide_index) + validate_sampler(directory, "wide_index_lowered", wide_lowered) + wide_lines = wide_lowered.splitlines() + assert "OpUConvert %ulong %index64" not in wide_lowered + assert "%x2w_address_target_unshifted = OpShiftRightLogical %ulong %x2w_address_target_delta %x2w_shift" in wide_lines + assert "%x2w_address_target_noshift = OpIEqual %bool %x2w_address_target_unshifted %index64" in wide_lines + assert "%x2w_address_target_checked64 = OpLogicalAnd %bool %x2w_address_target_checked %x2w_address_target_noshift" in wide_lines + assert "%x2w_address_target_selected = OpSelect %uint %x2w_address_target_checked64 %x2w_address_target_word %x2w_invalid" in wide_lines + + # A signed 64-bit index is bit-cast to %ulong before the shift and shift-wrap check so OpIEqual matches types. + signed_wide = (atomic_source + .replace("%ulong = OpTypeInt 64 0", + "%ulong = OpTypeInt 64 0\n%long = OpTypeInt 64 1\n%index_s64 = OpConstant %long 1", 1) + .replace(access, "%target = OpAccessChain %_ptr_PSB_uint %array %index_s64")) + validate_sampler(directory, "signed_wide_original", signed_wide) + signed_wide_lowered = window.lower(signed_wide) + validate_sampler(directory, "signed_wide_lowered", signed_wide_lowered) + signed_wide_lines = signed_wide_lowered.splitlines() + assert "%x2w_address_target_index = OpBitcast %ulong %index_s64" in signed_wide_lines + assert "%x2w_address_target_noshift = OpIEqual %bool %x2w_address_target_unshifted %x2w_address_target_index" in signed_wide_lines + + narrow_lowered = window.lower(atomic_source) + assert "OpUConvert %ulong %c1" in narrow_lowered, "a 32-bit index must still be widened" +print("physical, logical and combined SPIR-V validated; 8 atomics, bounded QWORD accesses, comments, 64-bit indices and rejection cases passed") diff --git a/tools/spirv_address_window.py b/tools/spirv_address_window.py index fa44e6192..304f6cb90 100644 --- a/tools/spirv_address_window.py +++ b/tools/spirv_address_window.py @@ -64,7 +64,7 @@ def address_name(dst): return "%x2w_address_" + dst[1:] -def word_pointer(dst, base, index, wide=False, defer=False): +def word_pointer(dst, base, index, wide=False, defer=False, index_kind=None): """Select the last DWORD offset for an unaligned or unrepresentable address. Returns the lines and the ID of the boolean that is true only for an aligned, in-window address. @@ -78,9 +78,14 @@ def word_pointer(dst, base, index, wide=False, defer=False): addr = base if index: addr = name + "_address" + if index_kind is None: + lines.append(f"{name}_index = OpUConvert %ulong {index}") + index = f"{name}_index" + elif index_kind == "s64": + lines.append(f"{name}_index = OpBitcast %ulong {index}") + index = f"{name}_index" lines.extend([ - f"{name}_index = OpUConvert %ulong {index}", - f"{name}_delta = OpShiftLeftLogical %ulong {name}_index {scale}", + f"{name}_delta = OpShiftLeftLogical %ulong {index} {scale}", f"{addr} = OpIAdd %ulong {base} {name}_delta", ]) lines.extend([ @@ -96,6 +101,14 @@ def word_pointer(dst, base, index, wide=False, defer=False): f"{name}_nowrap = OpUGreaterThanEqual %bool {addr} {base}", f"{valid} = OpLogicalAnd %bool {name}_valid {name}_nowrap", ]) + if index_kind is not None: + # A 64-bit index can drop high bits when shifted left; reject any shift that wraps. + lines.extend([ + f"{name}_unshifted = OpShiftRightLogical %ulong {name}_delta {scale}", + f"{name}_noshift = OpIEqual %bool {name}_unshifted {index}", + f"{name}_checked64 = OpLogicalAnd %bool {valid} {name}_noshift", + ]) + valid = name + "_checked64" lines.extend([ f"{name}_word64 = OpShiftRightLogical %ulong {addr} %x2w_shift", f"{name}_word = OpUConvert %uint {name}_word64", @@ -313,8 +326,38 @@ def merge_pointer_types(lines): return "\n".join(re.sub(ID, lambda m: aliases.get(m[0], m[0]), line) for line in kept) + "\n" +def logical_lines(assembly): + """Instruction lines without `;` comments; a quoted string may span lines and may hold a `;`. + + Quote and escape state carries across the whole module, and a literal that spans lines stays one + entry with its inner newlines and spaces untouched. + """ + lines, current = [], [] + quoted = escaped = False + comment = False + for char in assembly: + if char == "\n" and not quoted: + lines.append("".join(current).strip()) + current, comment = [], False + continue + if comment: + continue + if quoted and escaped: + escaped = False + elif quoted and char == "\\": + escaped = True + elif char == '"': + quoted = not quoted + elif char == ";" and not quoted: + comment = True + continue + current.append(char) + lines.append("".join(current).strip()) + return [line for line in lines if line] + + def lower(assembly): - lines = [line.strip() for line in split_sampler_views(lower_ballot_extract(assembly)).splitlines() if line.strip()] + lines = logical_lines(split_sampler_views(lower_ballot_extract(assembly))) model = "OpMemoryModel PhysicalStorageBuffer64 GLSL450" if model not in lines or lines.count("%user_data = OpVariable %_ptr_PC_UserData PushConstant") != 1: raise ValueError("expected a physical-address module with the named user-data block") @@ -412,6 +455,10 @@ def lower(assembly): start = number elif line.startswith("OpLoopMerge "): loop_headers.update(range(start, number)) + wide_types = {m[1]: "s64" if m[2] == "1" else "u64" + for m in map(re.compile(rf"({ID}) = OpTypeInt 64 ([01])").fullmatch, lines) if m} + wide_ids = {m[1]: wide_types[m[2]] + for m in map(re.compile(rf"({ID}) = Op\w+ ({ID})").match, lines) if m and m[2] in wide_types} constants = {m[1]: int(m[2]) for m in map(CONSTANT.fullmatch, lines) if m} failures = {} for line in lines: @@ -469,14 +516,14 @@ def lower(assembly): dst, pointer, index = access.groups() if pointer not in arrays: raise ValueError("unknown physical array pointer") - new, valid_of[dst] = word_pointer(dst, arrays[pointer], index) + new, valid_of[dst] = word_pointer(dst, arrays[pointer], index, index_kind=wide_ids.get(index)) output.extend(new) continue if signed := SIGNED_ACCESS.fullmatch(line): dst, pointer, index = signed.groups() if pointer not in signed_arrays: raise ValueError("unknown physical array pointer") - new, valid_of[dst] = word_pointer(dst, signed_arrays[pointer], index, defer=True) + new, valid_of[dst] = word_pointer(dst, signed_arrays[pointer], index, defer=True, index_kind=wide_ids.get(index)) signed_words[dst] = address_name(dst) + "_word" output.extend(new) continue @@ -484,7 +531,7 @@ def lower(assembly): dst, pointer, index = floating.groups() if pointer not in float_arrays: raise ValueError("unknown physical array pointer") - new, valid_of[dst] = word_pointer(dst, float_arrays[pointer], index, defer=True) + new, valid_of[dst] = word_pointer(dst, float_arrays[pointer], index, defer=True, index_kind=wide_ids.get(index)) float_words[dst] = address_name(dst) + "_word" output.extend(new) continue @@ -492,7 +539,7 @@ def lower(assembly): dst, pointer, index = quad.groups() if pointer not in vec4_arrays: raise ValueError("unknown physical array pointer") - new, valid_of[dst] = word_pointer(dst, vec4_arrays[pointer], index, "vec4") + new, valid_of[dst] = word_pointer(dst, vec4_arrays[pointer], index, "vec4", index_kind=wide_ids.get(index)) vec4_words[dst] = address_name(dst) + "_word" output.extend(new) continue @@ -500,7 +547,7 @@ def lower(assembly): dst, pointer, index = wide.groups() if pointer not in wide_arrays: raise ValueError("unknown physical array pointer") - new, valid_of[dst] = word_pointer(dst, wide_arrays[pointer], index, True) + new, valid_of[dst] = word_pointer(dst, wide_arrays[pointer], index, True, index_kind=wide_ids.get(index)) wide_words[dst] = address_name(dst) + "_word" output.extend(new) continue From 061c0958d33f5cbf01d0ee0c2a1eccca2b44781a Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 16:02:09 +0100 Subject: [PATCH 049/232] startup: optional Tracy zones for the stand-ins (X2W_TRACY, off by default) (#2371) An opt-in CMake option links d3d12_xs.dll, XCRDAPI.dll and xmem.dll against the Tracy client (v0.15.0, pinned by commit, on-demand, localhost only, no broadcast) and enables X2W_ZONE macros in a few hot places: ExecuteCommandLists, Present with a frame mark, frame wait, window present, desktop pipeline creation, device_memory_srv and its resource scans, DirectStorage requests and the xmem page map and physical write. Off, the macros expand to nothing and nothing is fetched, defined or linked. Co-authored-by: Claude Fable 5.2 --- CMakeLists.txt | 28 ++++++++++++++++++++++++++ docs/startup-runtime.md | 12 +++++++++++ src/startup_stubs/d3d12_draw.inl | 1 + src/startup_stubs/d3d12_memory_srv.inl | 5 +++++ src/startup_stubs/d3d12_present.inl | 1 + src/startup_stubs/d3d12_xs_device.cpp | 5 +++++ src/startup_stubs/profile_zone.h | 12 +++++++++++ src/startup_stubs/xcrdapi.cpp | 2 ++ src/xmem_mapped_pages.cpp | 3 +++ 9 files changed, 69 insertions(+) create mode 100644 src/startup_stubs/profile_zone.h diff --git a/CMakeLists.txt b/CMakeLists.txt index bdf504227..374dc3526 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -523,6 +523,34 @@ target_link_libraries(d3d12_xs_shim PRIVATE user32 gdi32 d3dcompiler dxgi x2w_bu target_compile_options(d3d12_xs_shim PRIVATE /bigobj) set_target_properties(xmem_shim d3d12_xs_shim ${startup_stub_targets} PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +# Developer-only measurement build: Tracy zones in the stand-ins (src/startup_stubs/profile_zone.h). +# One shared TracyClient.dll serves every instrumented DLL. Off (the default), nothing is fetched, defined or linked. +# On, Tracy (BSD-3-Clause, see docs/startup-runtime.md) is fetched at the pinned commit below, or taken from an existing +# checkout with -DFETCHCONTENT_SOURCE_DIR_TRACY=. The client opens a local socket; see docs/startup-runtime.md. +option(X2W_TRACY "Instrument the startup stand-ins with Tracy zones (fetches Tracy v0.15.0)" OFF) +if(X2W_TRACY) + include(FetchContent) + set(CMAKE_POLICY_DEFAULT_CMP0091 NEW) # Tracy's 3.13 minimum would otherwise ignore MSVC_RUNTIME_LIBRARY + set(TRACY_ENABLE ON) + set(TRACY_STATIC OFF) + set(TRACY_ON_DEMAND ON) + set(TRACY_ONLY_LOCALHOST ON) + set(TRACY_NO_BROADCAST ON) + set(TRACY_NO_CRASH_HANDLER ON) + # Symbol and kernel-tracing setup cost seconds per process in the D3D12 fixtures; sampling is ETW's job. + set(TRACY_NO_CALLSTACK ON) + set(TRACY_NO_SYSTEM_TRACING ON) + # v0.15.0, pinned by commit so the tag cannot move. + FetchContent_Declare(tracy GIT_REPOSITORY https://github.com/wolfpld/tracy.git + GIT_TAG f2a4f2529e7e71844c9e434b877770a21ecf7587) + FetchContent_MakeAvailable(tracy) + set_target_properties(TracyClient PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") + foreach(target IN ITEMS d3d12_xs_shim startup_stub_xcrdapi xmem_shim) + target_link_libraries(${target} PRIVATE Tracy::TracyClient) + target_compile_definitions(${target} PRIVATE X2W_TRACY=1) + endforeach() +endif() add_executable(startup_null_views_check tests/startup_null_views_check.cpp) target_compile_features(startup_null_views_check PRIVATE cxx_std_17) target_link_libraries(startup_null_views_check PRIVATE d3d12_xs_shim d3d12 dxgi) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a3f1cf8fd..936f86ce1 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -998,6 +998,18 @@ x2w-render indirect: forwarded: drawindexed 3; refused graphics-pipeline: drawin `graphics-pipeline` is a draw without a matching desktop pipeline and root, `compute-pipeline` a dispatch without a desktop compute pipeline and root, and `other` every remaining refusal, counted under the signature's kind whenever the signature is known. The `x2w-render ExecuteIndirect refused` lines still stop after 16. `startup_indirect_draw_indexed_warp` checks this line; `startup_indirect_counts_control_warp` expects one forwarded call too many and must report the mismatch. +### Optional: Tracy zones + +For a timeline instead of the counters, configure a separate build tree with `-DX2W_TRACY=ON`. This is a developer-only build, off by default and in every preset and workflow. Do not use it for a run that must stay offline: the Tracy client opens a TCP listener (from port 8086 up, on 127.0.0.1 only) in each instrumented process. + +- **Source.** Configure fetches [Tracy](https://github.com/wolfpld/tracy) v0.15.0, pinned to commit `f2a4f2529e7e71844c9e434b877770a21ecf7587`, with `FetchContent` (network needed at configure time). `-DFETCHCONTENT_SOURCE_DIR_TRACY=` uses an existing checkout instead, and `-DFETCHCONTENT_FULLY_DISCONNECTED=ON` forbids any download. Nothing from Tracy is committed here. Tracy is copyright Bartosz Taudul and others, 3-clause BSD license; its `LICENSE` ships in the fetched source, and a redistributed instrumented build must carry it. +- **Client settings.** On-demand (nothing is recorded until a profiler connects), localhost only, no broadcast, no call stacks, no system tracing and no crash handler. +- **Output.** One shared `TracyClient.dll` is linked into `d3d12_xs.dll`, `XCRDAPI.dll` and `xmem.dll`; copy it beside them. +- **Zones.** `ExecuteCommandLists`, `Present` (with a frame mark), the frame-wait sleep, window present, desktop pipeline creation, `device_memory_srv` with its resource scans, each DirectStorage request, and the xmem page map and physical write. `src/startup_stubs/profile_zone.h` defines the macros. +- **Off.** Without the option nothing is fetched, defined or linked, and the macros expand to nothing. + +To capture without a GUI, build Tracy's `capture` tool from the same checkout (`cmake -S /capture -B

`; that project fetches its own dependencies), start `capture -o run.tracy -a 127.0.0.1 -s ` and then the instrumented run. Open the file with the Tracy profiler, or export zone statistics with `csvexport`. + ### 4. Census, then rank The first refusal hides the rest. Run the [refusal census](experiments.md#startup-translator-refusal-census) on a copy of the cache: diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index b20718a9c..db34a5afd 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -817,6 +817,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P desc.DSVFormat = dsv_format; desc.SampleDesc.Count = 1; ID3D12PipelineState* pipeline = nullptr; + X2W_ZONE("desktop pipeline creation"); const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index 8ba9b00c1..b441d4401 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -161,6 +161,7 @@ void check_resource_address_index() Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) { + X2W_ZONE("srv existing_memory_texture scan"); Wrapper* match = nullptr; AcquireSRWLockShared(¬e_lock); // A null address never gets here (memory_srv_refusal), and the index holds no null base. @@ -184,6 +185,7 @@ Wrapper* existing_memory_texture(u64 address, const D3D12_RESOURCE_DESC& desc) // An unmatched or interior view must not reinterpret bytes owned by a live resource. bool address_resource_overlap(u64 address, u64 span) { + X2W_ZONE("srv address_resource_overlap scan"); bool found = false; AcquireSRWLockShared(¬e_lock); resource_address_index().for_each_reaching(address, span, [&](const Wrapper* wrapper) { @@ -202,6 +204,7 @@ bool address_resource_overlap(u64 address, u64 span) // title memory does not hold the texel. For a resource of unknown size, its base is the only known byte. bool gpu_written_overlap(u64 address, UINT texel_bytes) { + X2W_ZONE("srv gpu_written_overlap scan"); constexpr UINT gpu_written = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; bool found = false; @@ -218,6 +221,7 @@ bool gpu_written_overlap(u64 address, UINT texel_bytes) Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) { + X2W_ZONE("srv existing_memory_buffer scan"); if (!address || !bytes) return nullptr; const auto placed = placed_buffer_range(device, address, bytes); if (placed.reject) return nullptr; @@ -486,6 +490,7 @@ void publish_as_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const Me void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resource, const MemoryShaderResourceView* input, u64 destination) { + X2W_ZONE("device_memory_srv"); static LONG refused; check_resource_address_index(); if (const char* reason = memory_srv_refusal(resource, input, destination)) { diff --git a/src/startup_stubs/d3d12_present.inl b/src/startup_stubs/d3d12_present.inl index 6eb909636..58bec8cf4 100644 --- a/src/startup_stubs/d3d12_present.inl +++ b/src/startup_stubs/d3d12_present.inl @@ -189,6 +189,7 @@ bool create_window_presenter(ID3D12CommandQueue* queue, HWND window) // Draws `surface` (resting in COMMON) into the window and flips. Returns false if not shown. bool present_to_window(ID3D12CommandQueue* queue, ID3D12Resource* surface) { + X2W_ZONE("window present (blit + fence wait)"); WindowPresenter& p = window_presenter; if (p.failed || !queue || !surface) return false; const D3D12_RESOURCE_DESC desc = surface->GetDesc(); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index a3ffb791e..00f1b36fc 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -47,6 +47,7 @@ #include "startup_stubs/single_element_srv.h" #include "startup_stubs/list_copy.h" #include "startup_stubs/rect_indirect_args.h" +#include "startup_stubs/profile_zone.h" #include "startup_stubs/slice_footprints.h" #include "startup_stubs/present_signature_sampler.h" @@ -3315,6 +3316,7 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); // Queue slot 10, desktop ExecuteCommandLists(count, lists). void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) { + X2W_ZONE("ExecuteCommandLists"); static LONG calls; if (render_mode()) { // A closed list stays submittable until its next Reset, as on the desktop. @@ -4504,6 +4506,7 @@ HRESULT __stdcall device_wait_frame_event(Wrapper*, UINT type, UINT timeout, voi ReleaseSRWLockExclusive(&lock); if (timeout != 0 && wait_ticks > 0) { // High-resolution timer where available (Sleep is too coarse for a 33 ms frame). + X2W_ZONE("frame wait (sleep)"); static thread_local HANDLE timer = CreateWaitableTimerExW(nullptr, nullptr, 0x00000002 /* high resolution */, TIMER_ALL_ACCESS); LARGE_INTEGER due; due.QuadPart = -(wait_ticks * 10000000 / frequency.QuadPart); @@ -4664,6 +4667,8 @@ void report_budget(ID3D12CommandQueue* queue) HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) { Timed timed(time_present); + X2W_ZONE("Present"); + X2W_FRAME_MARK; static LONG frames; static ULONGLONG started, last_report; const LONG frame = InterlockedIncrement(&frames); diff --git a/src/startup_stubs/profile_zone.h b/src/startup_stubs/profile_zone.h new file mode 100644 index 000000000..4981dc672 --- /dev/null +++ b/src/startup_stubs/profile_zone.h @@ -0,0 +1,12 @@ +// Opt-in Tracy zones for the stand-ins (CMake option X2W_TRACY, a local measurement build). +// Without the option every macro expands to nothing and no Tracy header is included. +#pragma once + +#if X2W_TRACY +#include +#define X2W_ZONE(name) ZoneScopedN(name) +#define X2W_FRAME_MARK FrameMark +#else +#define X2W_ZONE(name) +#define X2W_FRAME_MARK +#endif diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 0939b34ef..3dfaf65aa 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -8,6 +8,7 @@ #define X2W_TRAP_MODULE "XCRDAPI.dll" #define X2W_TRAP_MODULE_ID 4 #include "startup_stubs/trap.h" +#include "startup_stubs/profile_zone.h" #include "startup_stubs/local_log.h" #include "startup_stubs/inflate.h" #include "startup_stubs/dstorage_error_record.h" @@ -577,6 +578,7 @@ void log_bcpack_summary() void execute_request(Object* self, const unsigned char* request, const ULONG_PTR* tokens, u64 entry_id, u64 submission_id) { + X2W_ZONE("DirectStorage request"); if (!request) return; const u64 options = *reinterpret_cast(request); auto* const destination = *reinterpret_cast(request + 0x08); diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 5dec3057d..07877c7e5 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -11,6 +11,7 @@ #include #include #include "startup_stubs/local_log.h" +#include "startup_stubs/profile_zone.h" #include @@ -781,6 +782,7 @@ template BOOL map_pages(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& address_at, MapFailure* failure = nullptr) noexcept { + X2W_ZONE("xmem map_pages"); const bool share_views = fault_retry.ready(); const MappingThread marker; const std::lock_guard guard(memory.mutex); @@ -1615,6 +1617,7 @@ const bool lazy_commit_installed = [] { // first page. DirectStorage requests can name such pages as their destination. extern "C" BOOL WINAPI x2w_xmem_write_physical(const ULONG_PTR* tokens, ULONG_PTR count, SIZE_T offset, const void* data, SIZE_T bytes) { + X2W_ZONE("x2w_xmem_write_physical"); if (!tokens || !data || offset >= page_bytes) return FALSE; const auto* source = static_cast(data); ULONG_PTR index = 0; From 3d61869876d3922fd64d77868eeec7c6d048eec5 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:02:54 +0100 Subject: [PATCH 050/232] fix: SSE2 MINSD/MAXSD DAZ, XSAVE AVX-only MXCSR, MMX read state (#1646) * fix: lifted MINSD and MAXSD read a denormal as zero under DAZ The SSE2 leaf lifter compared the two doubles with C operators, so with MXCSR.DAZ set a denormal operand was returned unchanged where the instruction returns a zero of the same sign. Run the instruction itself on run-time operands, as the scalar lifter and the packed float lifter do. AI-assisted; commands listed were executed locally. * fix: lifted XSAVE with RFBM = AVX alone stores MXCSR and MXCSR_MASK XSAVE and XSAVEOPT store MXCSR and MXCSR_MASK in the legacy area when the request mask selects SSE or AVX; XSAVEC only with SSE. The lifted XSAVE stored them with SSE alone, so an AVX-only save left bytes 24..31 of the caller buffer unchanged. The lift-time check that MXCSR is defined before a save now covers that form too, and the reference model follows the same rule. AI-assisted; commands listed were executed locally. * fix: lifted MMX reads enter MMX state in the FXSAVE and XSAVE lifters A MOVQ that only reads an MM register, to memory or to a general register, still clears the x87 TOP field and marks every tag valid; the lifters changed that state for writes only, so a save after a read-only MOVQ reported the restored TOP, tag word and stack order. In the XSAVE lifter the x87 component also counts as in use. A read now enters MMX state like a write does. AI-assisted; commands listed were executed locally. * fix: mark MMX active on read-only MOVQ in XSAVE lifter and update docstring --- CMakeLists.txt | 7 ++-- tests/cpu/sse2_regs.def | 2 ++ tests/cpu/sse2_regs_check.py | 29 +++++++++++++++ tests/cpu/sse_fxsave.asm | 19 ++++++++++ tests/cpu/sse_fxsave.def | 2 ++ tests/cpu/sse_fxsave_check.py | 32 +++++++++++++++-- tests/cpu/xsave_state.asm | 23 ++++++++++++ tests/cpu/xsave_state.def | 2 ++ tests/cpu/xsave_state_check.py | 65 ++++++++++++++++++++++++++++++---- tools/cpu_sse2_aot.py | 14 ++++++-- tools/cpu_sse_fxsave_aot.py | 12 +++++-- tools/cpu_xsave_aot.py | 42 ++++++++++++++-------- 12 files changed, 217 insertions(+), 32 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 374dc3526..7695a5c40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4774,7 +4774,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_avx_pcmpstr PROPERTIES SKIP_RETURN_CODE 77) set(cpu_xsave_state_original_exports "op_xrstor_xsave,op_xrstor64_xsave64,op_xrstor_xsave64,op_xrstor64_xsave," - "op_xrstor64_disp,op_xrstor64_mask_sse,op_vzeroupper_xsave64,op_pipeline," + "op_xrstor64_disp,op_xrstor64_mask_sse,op_vzeroupper_xsave64,op_pipeline,op_xrstor64_xsave64_avx," + "op_xrstor64_movq_read_xsave64," "op_discarded_read,op_xrstor64_xsavec,op_xrstor64_xsavec64," "op_xrstor64_xsavec64_sse,op_xrstor64_xsavec64_x87_avx,op_xsavec64_dynmask," "op_xrstor64_xsaveopt,op_xrstor64_xsaveopt64,op_xrstor64_xsaveopt64_sse," @@ -4902,6 +4903,7 @@ if(EXISTS "${INTAKE_PYTHON}") string(CONCAT cpu_sse2_exports ${cpu_sse2_exports}) foreach(variant IN ITEMS original altered) cpu_asm_fixture(cpu_sse2_regs_${variant} sse2_regs) + target_sources(cpu_sse2_regs_${variant} PRIVATE tests/cpu/sse2_mxcsr_test.asm) cpu_translation(cpu_sse2_regs_${variant} cpu_sse2_aot "${cpu_sse2_exports}") endforeach() target_compile_definitions(cpu_sse2_regs_altered PRIVATE ALTER_IMM) @@ -5166,7 +5168,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(cpu_aot_integer_flags PROPERTIES SKIP_RETURN_CODE 77) set(cpu_sse_fxsave_exports "op_fxrstor_fxsave,op_fxrstor64_fxsave64,op_fxrstor_fxsave64," - "op_fxrstor64_fxsave,op_fxrstor64_disp,op_pipeline,op_discarded_read") + "op_fxrstor64_fxsave,op_fxrstor64_disp,op_pipeline,op_discarded_read," + "op_fxrstor64_movq_store,op_fxrstor64_movq_gpr") string(CONCAT cpu_sse_fxsave_exports ${cpu_sse_fxsave_exports}) foreach(variant IN ITEMS original altered) cpu_asm_fixture(cpu_sse_fxsave_${variant} sse_fxsave) diff --git a/tests/cpu/sse2_regs.def b/tests/cpu/sse2_regs.def index 48df37f13..8ca0dde25 100644 --- a/tests/cpu/sse2_regs.def +++ b/tests/cpu/sse2_regs.def @@ -66,3 +66,5 @@ EXPORTS op_cmpsd_7 op_cmpsd_mem op_cmpsd_mem_plus1 + read_mxcsr + write_mxcsr diff --git a/tests/cpu/sse2_regs_check.py b/tests/cpu/sse2_regs_check.py index bab7db32d..06492fc3c 100644 --- a/tests/cpu/sse2_regs_check.py +++ b/tests/cpu/sse2_regs_check.py @@ -546,6 +546,34 @@ def check_differential(native_path, lifted_path, altered_path): f"bit-for-bit; altered controls diverged on {changed}; output mutation control caught") +def check_daz_extrema(native_path, lifted_path): + """MAXSD and MINSD under MXCSR.DAZ return a denormal operand as a zero of its sign.""" + names = ("op_maxsd_reg", "op_minsd_reg") + native, lifted = bind_exports(native_path, "", names), bind_exports(lifted_path, "lifted_", names) + host = ctypes.CDLL(str(Path(native_path).resolve())) + for function in (host.read_mxcsr, host.write_mxcsr): + function.argtypes, function.restype = [ctypes.POINTER(ctypes.c_uint32)], None + denormal, sign, minus_one, one = 0x000123456789ABCD, 1 << 63, 0xBFF0000000000000, 0x3FF0000000000000 + # (export, destination, source, result): the result is the second operand or the first, flushed by DAZ. + cases = (("op_maxsd_reg", denormal, minus_one, 0), ("op_maxsd_reg", denormal | sign, minus_one, sign), + ("op_minsd_reg", one, denormal | sign, sign), ("op_minsd_reg", one, denormal, 0)) + saved = ctypes.c_uint32() + host.read_mxcsr(ctypes.byref(saved)) + try: + host.write_mxcsr(ctypes.byref(ctypes.c_uint32(0x1FC0))) + for name, a0, b0, result in cases: + a, b = pk_q(a0, 7), pk_q(b0, 9) + unflushed = a0 if name == "op_maxsd_reg" else b0 # what a C comparison returns + if unflushed == result: + raise AssertionError(f"{name}: control case cannot tell a flushed result apart") + for label, function in (("native", native[name]), ("lifted", lifted[name])): + assert_equal_output(f"{label} DAZ", name, hex(a0), invoke(function, a, b), + pk_q(result, 7) + FILL[16:]) + finally: + host.write_mxcsr(ctypes.byref(saved)) + print(f"{len(cases)} MAXSD/MINSD denormal results under MXCSR.DAZ matched the native instruction") + + # --- Alternative-encoding acceptance & translator rejection controls --- def encode_seq(*instructions): @@ -841,4 +869,5 @@ def check_alt_encodings_and_rejections(original_path): if __name__ == "__main__": check_differential(*sys.argv[1:4]) + check_daz_extrema(*sys.argv[1:3]) check_alt_encodings_and_rejections(sys.argv[1]) diff --git a/tests/cpu/sse_fxsave.asm b/tests/cpu/sse_fxsave.asm index b59a9737c..334ac53fd 100644 --- a/tests/cpu/sse_fxsave.asm +++ b/tests/cpu/sse_fxsave.asm @@ -95,6 +95,25 @@ ENDIF ret op_pipeline ENDP +; MOVQ that only reads MM3, to memory or to a register, still clears TOP and marks every tag valid. +op_fxrstor64_movq_store PROC FRAME + .endprolog + fxrstor64 [rcx] + movq QWORD PTR [r8+512], mm3 + fxsave64 [r8] + emms + ret +op_fxrstor64_movq_store ENDP + +op_fxrstor64_movq_gpr PROC FRAME + .endprolog + fxrstor64 [rcx] + movq r9, mm3 + fxsave64 [r8] + emms + ret +op_fxrstor64_movq_gpr ENDP + ; The discarded fxrstor64 [rdx] must fault after [r8] and before [r8+512]. op_discarded_read PROC FRAME .endprolog diff --git a/tests/cpu/sse_fxsave.def b/tests/cpu/sse_fxsave.def index c73b73b61..98434a183 100644 --- a/tests/cpu/sse_fxsave.def +++ b/tests/cpu/sse_fxsave.def @@ -8,4 +8,6 @@ EXPORTS op_fxrstor64_fxsave op_fxrstor64_disp op_pipeline + op_fxrstor64_movq_store + op_fxrstor64_movq_gpr op_discarded_read diff --git a/tests/cpu/sse_fxsave_check.py b/tests/cpu/sse_fxsave_check.py index 1e994380c..f16759968 100644 --- a/tests/cpu/sse_fxsave_check.py +++ b/tests/cpu/sse_fxsave_check.py @@ -32,6 +32,8 @@ "op_fxrstor64_fxsave", "op_fxrstor64_disp", "op_pipeline", + "op_fxrstor64_movq_store", + "op_fxrstor64_movq_gpr", ) EXPORTS = CANONICAL_EXPORTS + DEFINED_EXPORTS @@ -45,6 +47,8 @@ "op_fxrstor64_fxsave": (True, False, 0), "op_fxrstor64_disp": (True, True, 64), "op_pipeline": (True, True, 0), + "op_fxrstor64_movq_store": (True, True, 0), + "op_fxrstor64_movq_gpr": (True, True, 0), } ALTERED_EXPORTS = ( @@ -313,13 +317,18 @@ def fxsave(self, dst: bytearray, offset: int, is64: bool) -> None: out[160 + i * 16 : 160 + i * 16 + 16] = self.xmm[i] dst[offset : offset + 416] = out + def enter_mmx(self) -> None: + """Every MMX instruction but EMMS, one that only reads an MM register included, clears TOP and tags all valid.""" + self.ftw = 0xFF + self.fsw &= ~0x3800 + def set_mm(self, idx: int, val: int) -> None: struct.pack_into(" int: + self.enter_mmx() return struct.unpack_from(" None: + def xsave(self, dst: bytearray, offset: int, rfbm: int, is64: bool, mxcsr_with_avx: bool = True) -> None: + """XSAVE stores MXCSR and MXCSR_MASK when RFBM selects SSE or AVX, XSAVEC only with SSE.""" rfbm &= 7 if rfbm & 1: hdr = bytearray(24) @@ -459,8 +466,9 @@ def xsave(self, dst: bytearray, offset: int, rfbm: int, is64: bool) -> None: phys = (top + i) & 7 st_area[i * 16 : i * 16 + 10] = self.st[phys][0:10] dst[offset + 32 : offset + 160] = st_area - if rfbm & 2: + if rfbm & (6 if mxcsr_with_avx else 2): struct.pack_into(" None: @@ -491,7 +499,7 @@ def xsaveopt(self, dst: bytearray, offset: int, rfbm: int, is64: bool, track_mxc rfbm &= 7 sse_live = 2 if track_mxcsr and self.mxcsr != DEFAULT_MXCSR else 0 in_use = self.xinuse | sse_live - self.xsave(dst, offset, rfbm & in_use, is64) + self.xsave(dst, offset, rfbm & in_use, is64, mxcsr_with_avx=False) if rfbm & 6: struct.pack_into(" None: self.ymm_hi = [bytearray(16) for _ in range(16)] self.xinuse &= ~4 - def set_mm(self, idx: int, val: int) -> None: - struct.pack_into(" None: + """Every MMX instruction but EMMS, one that only reads an MM register included, clears TOP and tags all valid.""" self.ftw = 0xFF self.fsw &= ~0x3800 self.xinuse |= 1 + def set_mm(self, idx: int, val: int) -> None: + struct.pack_into(" int: + self.enter_mmx() return struct.unpack_from("(_mm_cvtsi128_si64(_mm_castpd_si128(r))); } -// MAXSD/MINSD return src2 on ties, unordered inputs and equal values. +// MAXSD/MINSD run on the processor, on run-time operands: it returns src2 on ties, unordered inputs and equal +// values, and under MXCSR.DAZ it reads a denormal operand as a zero of its sign, also when that operand is the +// result (a C comparison would return the denormal bits unchanged). static std::uint64_t op_maxsd_q(std::uint64_t a, std::uint64_t b) { - return q_as_double(a) > q_as_double(b) ? a : b; + volatile std::uint64_t va = a, vb = b; + const __m128d x = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(va))); + const __m128d y = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(vb))); + return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(_mm_max_sd(x, y)))); } static std::uint64_t op_minsd_q(std::uint64_t a, std::uint64_t b) { - return q_as_double(a) < q_as_double(b) ? a : b; + volatile std::uint64_t va = a, vb = b; + const __m128d x = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(va))); + const __m128d y = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(vb))); + return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(_mm_min_sd(x, y)))); } // SQRTSD keeps the NaN payload (quieted) and yields the real-indefinite QNaN diff --git a/tools/cpu_sse_fxsave_aot.py b/tools/cpu_sse_fxsave_aot.py index 05cc055d0..168308d0f 100644 --- a/tools/cpu_sse_fxsave_aot.py +++ b/tools/cpu_sse_fxsave_aot.py @@ -264,7 +264,14 @@ return out; } -static inline std::uint64_t get_mm(const FxState& state, unsigned idx) { +// Every MMX instruction but EMMS, one that only reads an MM register included, clears TOP and marks all tags valid. +static inline void enter_mmx(FxState& state) { + state.ftw = 0xFFu; + state.fsw = static_cast(state.fsw & ~0x3800u); +} + +static inline std::uint64_t get_mm(FxState& state, unsigned idx) { + enter_mmx(state); std::uint64_t v = 0ull; std::memcpy(&v, state.st[idx], 8); return v; @@ -275,8 +282,7 @@ state.st[idx][8] = 0xFFu; state.st[idx][9] = 0xFFu; std::memset(state.st[idx] + 10, 0, 6); - state.ftw = 0xFFu; - state.fsw = static_cast(state.fsw & ~0x3800u); + enter_mmx(state); } static inline void op_emms(FxState& state) { diff --git a/tools/cpu_xsave_aot.py b/tools/cpu_xsave_aot.py index cbe83ebc5..c728e87b7 100644 --- a/tools/cpu_xsave_aot.py +++ b/tools/cpu_xsave_aot.py @@ -15,7 +15,7 @@ components from entry are rejected. MXCSR is tracked apart from the components: by default (standard-only XRSTOR), an xrstor whose RFBM selects SSE or AVX defines MXCSR, so vzeroupper alone does not, and a save that - stores MXCSR (xsaveopt with SSE or AVX selected, xsave/xsavec with SSE + stores MXCSR (xsave/xsaveopt with SSE or AVX selected, xsavec with SSE selected) is rejected without it. - --compacted-xrstor (opt-in): permits XRSTOR to accept compacted headers (XCOMP_BV[63] set) in addition to standard headers. Because the header @@ -36,7 +36,8 @@ x87/SSE and AVX YMM[255:128] regions while leaving legacy [416..511], XCOMP_BV [520..527], and header [528..575] untouched, and updating XSTATE_BV[2:0] = - (old & ~rfbm) | (xinuse & rfbm). + (old & ~rfbm) | (xinuse & rfbm). MXCSR and MXCSR_MASK are stored when + RFBM selects SSE or AVX. - xsavec / xsavec64: same alignment and mask contract as xsave; write the compacted format: only components with XINUSE & RFBM set are stored (SSE is in use when any XMM register is live @@ -446,7 +447,16 @@ return out; } -static inline std::uint64_t get_mm(const XState& state, unsigned idx) { +// Every MMX instruction but EMMS, one that only reads an MM register included, clears TOP, marks all tags valid +// and leaves the x87 component in use. +static inline void enter_mmx(XState& state) { + state.ftw = 0xFFu; + state.fsw = static_cast(state.fsw & ~0x3800u); + state.xinuse |= 1ull; +} + +static inline std::uint64_t get_mm(XState& state, unsigned idx) { + enter_mmx(state); std::uint64_t v = 0ull; std::memcpy(&v, state.st[idx], 8); return v; @@ -457,9 +467,7 @@ state.st[idx][8] = 0xFFu; state.st[idx][9] = 0xFFu; std::memset(state.st[idx] + 10, 0, 6); - state.ftw = 0xFFu; - state.fsw = static_cast(state.fsw & ~0x3800u); - state.xinuse |= 1ull; + enter_mmx(state); } static inline void op_emms(XState& state) { @@ -612,7 +620,9 @@ } } -static inline void op_xsave(const XState& state, word address, word rax_val, word rdx_val, bool is64) { +// XSAVE stores MXCSR and MXCSR_MASK when RFBM selects SSE or AVX (mxcsr_with_avx); XSAVEC only with SSE. +static inline void op_xsave(const XState& state, word address, word rax_val, word rdx_val, bool is64, + bool mxcsr_with_avx = true) { const std::uint32_t mask_lo = static_cast(rax_val); const std::uint32_t mask_hi = static_cast(rdx_val); if ((address & 63ull) != 0ull) raise_gp(); @@ -660,11 +670,11 @@ for (unsigned i = 0; i < 16u; ++i) dst[4u + i] = st_words[i]; } + if ((rfbm & (mxcsr_with_avx ? 6ull : 2ull)) != 0ull) { + dst[3] = static_cast(state.mxcsr) | (static_cast(state.mxcsr_mask) << 32); + } + if ((rfbm & 2ull) != 0ull) { - std::uint64_t mxcsr_pair = - static_cast(state.mxcsr) | - (static_cast(state.mxcsr_mask) << 32); - dst[3] = mxcsr_pair; std::uint64_t xmm_words[32]{}; std::memcpy(xmm_words, state.xmm, 256); for (unsigned i = 0; i < 32u; ++i) dst[20u + i] = xmm_words[i]; @@ -690,7 +700,7 @@ // SDM vol.1 13.6: SSE is also in use when MXCSR differs from its reset value, even if no XMM register is live. const std::uint64_t sse_live = state.mxcsr != 0x1F80u ? 2ull : 0ull; const std::uint64_t used = rfbm & (state.xinuse | sse_live); - op_xsave(state, address, used, 0ull, is64); + op_xsave(state, address, used, 0ull, is64, false); std::atomic_signal_fence(std::memory_order_seq_cst); auto* dst = reinterpret_cast(address); dst[64] = used; @@ -706,7 +716,7 @@ // Init optimization only: SSE is in use while MXCSR is not at its reset value (SDM vol.1 13.6). const std::uint64_t sse_live = state.mxcsr != 0x1F80u ? 2ull : 0ull; const std::uint64_t inuse = state.xinuse | sse_live; - op_xsave(state, address, rfbm & inuse, 0ull, is64); + op_xsave(state, address, rfbm & inuse, 0ull, is64, false); std::atomic_signal_fence(std::memory_order_seq_cst); auto* dst = reinterpret_cast(address); if ((rfbm & 6ull) != 0ull) { @@ -906,8 +916,8 @@ def require_xsave_masks(ins): else: needed_xcomp = 7 missing = needed_xcomp & ~defined_xcomp - # xsave/xsavec store MXCSR with SSE; xsaveopt also stores it when only AVX is selected. - mxcsr_stored = bool(needed_xcomp & (6 if ins.code in XSAVEOPT_CODES else 2)) + # xsave and xsaveopt store MXCSR with SSE or AVX; xsavec only with SSE. + mxcsr_stored = bool(needed_xcomp & (2 if ins.code in XSAVEC_CODES else 6)) if missing != 0: if entry_state != "canonical": missing_names = ", ".join(lbl for bit, lbl in XCOMP_NAMES if missing & bit) @@ -1018,6 +1028,7 @@ def require_xsave_masks(ins): src_mm = read_mm(1, ins) addr = flat_address(ins, ptr_origins, expected_bytes=8, write=True) statements.append(f"store64({addr}, get_mm(state, {src_mm}));") + mmx_active = True elif ins.op1_kind == OpKind.MEMORY: dst_mm = mm_index(ins.op0_register, ins) addr = flat_address(ins, ptr_origins, expected_bytes=8) @@ -1038,6 +1049,7 @@ def require_xsave_masks(ins): used_gpr.add(dst_gpr) statements.append(f"{dst_gpr} = get_mm(state, {src_mm});") defined_gpr.add(dst_gpr) + mmx_active = True else: raise ValueError(f"unsupported movq operand shape at RVA {ins.ip:#x}: {ins}") From 0b31989c44076ab00d842335ea04fd0d4662067d Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 17:04:27 +0200 Subject: [PATCH 051/232] textures: extract main(argv), atomic output writes, and error guards in bc7_blocks with CLI suite (#2388) * textures: extract main(argv), atomic output writes, and error guards in bc7_blocks with CLI suite * textures: diagnose separate BC7 output replacement failures --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 2 + tests/bc7_blocks_cli_check.py | 319 ++++++++++++++++++++++++++++++++++ tools/bc7_blocks.py | 72 +++++++- 3 files changed, 387 insertions(+), 6 deletions(-) create mode 100644 tests/bc7_blocks_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7695a5c40..6f71669e2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8116,6 +8116,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/gfx10_texture_roundtrip_check.py" controls) add_test(NAME texture_bc_volume COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/texture_bc_volume_check.py") + add_test(NAME bc7_blocks_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bc7_blocks_cli_check.py") add_test(NAME texture_descriptors_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/texture_descriptors_check.py") add_test(NAME resource_range_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/bc7_blocks_cli_check.py b/tests/bc7_blocks_cli_check.py new file mode 100644 index 000000000..e89d75d4f --- /dev/null +++ b/tests/bc7_blocks_cli_check.py @@ -0,0 +1,319 @@ +"""CLI, atomic output, and mutation control suite for tools/bc7_blocks.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "bc7_blocks.py" +sys.path.insert(0, str(ROOT / "tools")) + +import bc7_blocks # noqa: E402 + + +def _run_main(argv: list[str]) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + try: + with redirect_stdout(stdout), redirect_stderr(stderr): + code = bc7_blocks.main(argv) + except SystemExit as exc: + code = int(exc.code) if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_cli_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class Bc7BlocksCliPositiveTests(unittest.TestCase): + def test_main_creates_nested_outputs_byte_exact_case_and_fields_json(self): + expected_fields, expected_blocks, expected_rgba = bc7_blocks.fixture(2, 3) + expected_case = struct.pack("<4sII", b"BC7C", 8, 12) + expected_blocks + expected_rgba + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case_path = root / "nested" / "case_dir" / "blocks.bc7c" + fields_path = root / "nested" / "json_dir" / "fields.json" + self.assertFalse(case_path.parent.exists()) + self.assertFalse(fields_path.parent.exists()) + + seen_replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path = Path(src) + dst_path = Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with mock.patch.object(bc7_blocks.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main( + [str(case_path), "--columns", "2", "--rows", "3", "--fields", str(fields_path)] + ) + + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(len(seen_replaces), 2) + self.assertEqual([p.name for p in case_path.parent.iterdir()], [case_path.name]) + self.assertEqual([p.name for p in fields_path.parent.iterdir()], [fields_path.name]) + self.assertEqual(case_path.read_bytes(), expected_case) + loaded = json.loads(fields_path.read_text(encoding="ascii")) + self.assertIsInstance(loaded, list) + self.assertEqual(len(loaded), 6) + self.assertEqual(loaded, expected_fields) + + def test_subprocess_same_parent_without_and_with_fields_atomically_replaces(self): + expected_fields, expected_blocks, expected_rgba = bc7_blocks.fixture(2, 3) + expected_case = struct.pack("<4sII", b"BC7C", 8, 12) + expected_blocks + expected_rgba + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + out_dir = root / "shared" + out_dir.mkdir() + case_path = out_dir / "blocks.bc7c" + fields_path = out_dir / "fields.json" + case_path.write_bytes(b"stale-case") + fields_path.write_text("stale-json", encoding="ascii") + + proc_no_fields = _run_cli_subprocess(str(case_path), "--columns", "2", "--rows", "3") + self.assertEqual(proc_no_fields.returncode, 0, proc_no_fields.stderr) + self.assertEqual(proc_no_fields.stderr, "") + self.assertEqual(case_path.read_bytes(), expected_case) + self.assertEqual(fields_path.read_text(encoding="ascii"), "stale-json") + + proc_with_fields = _run_cli_subprocess( + str(case_path), "--columns", "2", "--rows", "3", "--fields", str(fields_path) + ) + self.assertEqual(proc_with_fields.returncode, 0, proc_with_fields.stderr) + self.assertEqual(proc_with_fields.stderr, "") + self.assertEqual( + sorted(p.name for p in out_dir.iterdir()), + ["blocks.bc7c", "fields.json"], + ) + self.assertEqual(case_path.read_bytes(), expected_case) + loaded = json.loads(fields_path.read_text(encoding="ascii")) + self.assertEqual(len(loaded), 6) + self.assertEqual(loaded, expected_fields) + + +class Bc7BlocksCliNegativeAndMutationTests(unittest.TestCase): + def test_non_positive_columns_or_rows_rejected_upfront_without_traceback(self): + for bad_args in ( + ["--columns", "0", "--rows", "3"], + ["--columns", "2", "--rows", "-2"], + ["--columns", "-1", "--rows", "0"], + ): + with self.subTest(bad_args=bad_args), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case_path = root / "nested" / "case.bc7c" + fields_path = root / "nested" / "fields.json" + argv = [str(case_path), *bad_args, "--fields", str(fields_path)] + + with mock.patch.object(bc7_blocks, "fixture") as fixture_mock: + code, out, err = _run_main(argv) + fixture_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("positive block dimensions", err) + self.assertFalse(case_path.parent.exists()) + + proc = _run_cli_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("positive block dimensions", proc.stderr) + self.assertFalse(case_path.parent.exists()) + + def test_fields_collision_with_case_resolve_and_samefile_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + + # 1) Non-existent paths colliding via parent traversal (kills resolve() mutation). + case_ghost = root / "out" / "case.bc7c" + fields_alias = root / "out" / ".." / "out" / "case.bc7c" + with mock.patch.object(bc7_blocks, "fixture") as fixture_mock: + code, out, err = _run_main( + [str(case_ghost), "--columns", "2", "--rows", "3", "--fields", str(fields_alias)] + ) + fixture_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("collides with case", err) + self.assertFalse(case_ghost.parent.exists()) + + # 2) Hardlink alias where resolve() differs (kills samefile() mutation). + case_real = root / "case.bc7c" + fields_hardlink = sub / "fields_link.json" + case_real.write_bytes(b"keep-case") + os.link(case_real, fields_hardlink) + self.assertNotEqual(case_real.resolve(), fields_hardlink.resolve()) + self.assertTrue(case_real.samefile(fields_hardlink)) + + with mock.patch.object(bc7_blocks, "fixture") as fixture_mock: + code, out, err = _run_main( + [str(case_real), "--columns", "2", "--rows", "3", "--fields", str(fields_hardlink)] + ) + fixture_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("collides with case", err) + self.assertEqual(case_real.read_bytes(), b"keep-case") + + def test_nested_destination_paths_refused_before_creating_anything(self): + for fields_inside_case in (True, False): + with self.subTest(fields_inside_case=fields_inside_case), tempfile.TemporaryDirectory() as tmp: + parent = Path(tmp) / "new" + child = parent / "child" + case, fields = (parent, child) if fields_inside_case else (child, parent) + code, _, err = _run_main([str(case), "--fields", str(fields)]) + self.assertEqual(code, 1) + self.assertIn("cannot contain one another", err) + self.assertFalse(parent.exists()) + + def test_second_replace_failure_reports_partial_publish_and_retry_repairs_pair(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case = root / "case.bc7c" + fields = root / "fields.json" + case.write_bytes(b"old-case") + fields.write_text("old-json", encoding="ascii") + argv = [str(case), "--columns", "1", "--rows", "1", "--fields", str(fields)] + replace = os.replace + + def fail_fields(src, dst): + if dst == fields: + raise PermissionError("fields locked") + replace(src, dst) + + with mock.patch.object(bc7_blocks.os, "replace", side_effect=fail_fields): + code, _, err = _run_main(argv) + self.assertEqual(code, 1) + self.assertIn("Retry with both output paths", err) + self.assertIn("fields locked", err) + self.assertTrue(case.read_bytes().startswith(b"BC7C")) + self.assertEqual(fields.read_text(encoding="ascii"), "old-json") + self.assertEqual(sorted(p.name for p in root.iterdir()), ["case.bc7c", "fields.json"]) + code, _, err = _run_main(argv) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(fields.read_text(encoding="ascii")), bc7_blocks.fixture(1, 1)[0]) + + def test_existing_directory_outputs_rejected_upfront(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + existing_dir = root / "already_dir" + existing_dir.mkdir() + case_file = root / "nested" / "case.bc7c" + fields_file = root / "nested" / "fields.json" + + # case is an existing directory + with mock.patch.object(bc7_blocks, "fixture") as fixture_mock: + code, _, err = _run_main( + [str(existing_dir), "--columns", "2", "--rows", "3", "--fields", str(fields_file)] + ) + fixture_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("existing directory", err) + self.assertFalse(fields_file.parent.exists()) + + # --fields is an existing directory + with mock.patch.object(bc7_blocks, "fixture") as fixture_mock: + code, _, err = _run_main( + [str(case_file), "--columns", "2", "--rows", "3", "--fields", str(existing_dir)] + ) + fixture_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("existing directory", err) + self.assertFalse(case_file.parent.exists()) + + def test_struct_error_and_value_error_caught_cleanly_without_artifacts(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case_path = root / "case.bc7c" + fields_path = root / "fields.json" + + with mock.patch.object(bc7_blocks.struct, "pack", side_effect=struct.error("bad pack dimensions")): + code, _, err = _run_main( + [str(case_path), "--columns", "2", "--rows", "3", "--fields", str(fields_path)] + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("bad pack dimensions", err) + self.assertEqual(list(root.iterdir()), []) + + with mock.patch.object(bc7_blocks, "fixture", side_effect=ValueError("simulated value failure")): + code, _, err = _run_main( + [str(case_path), "--columns", "2", "--rows", "3", "--fields", str(fields_path)] + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated value failure", err) + self.assertEqual(list(root.iterdir()), []) + + def test_os_replace_and_staging_failures_leave_zero_temp_dirs_or_partial_files(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + case_dir = root / "case_out" + fields_dir = root / "fields_out" + case_path = case_dir / "blocks.bc7c" + fields_path = fields_dir / "fields.json" + + # 1) OSError during os.replace -> zero output files and zero temp staging dirs. + replace_calls = [] + + def failing_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + raise OSError("simulated replace failure") + + with mock.patch.object(bc7_blocks.os, "replace", side_effect=failing_replace): + code, _, err = _run_main( + [str(case_path), "--columns", "2", "--rows", "3", "--fields", str(fields_path)] + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated replace failure", err) + self.assertEqual(len(replace_calls), 1) + self.assertEqual(list(case_dir.iterdir()), []) + self.assertEqual(list(fields_dir.iterdir()), []) + + # 2) Failure while staging --fields -> os.replace never called, both dirs empty. + with ( + mock.patch.object(bc7_blocks.os, "replace") as replace_mock, + mock.patch.object(bc7_blocks.json, "dumps", side_effect=ValueError("simulated json failure")), + ): + code, _, err = _run_main( + [str(case_path), "--columns", "2", "--rows", "3", "--fields", str(fields_path)] + ) + replace_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated json failure", err) + self.assertEqual(list(case_dir.iterdir()), []) + self.assertEqual(list(fields_dir.iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bc7_blocks.py b/tools/bc7_blocks.py index c1d047608..9ba178352 100644 --- a/tools/bc7_blocks.py +++ b/tools/bc7_blocks.py @@ -1,9 +1,12 @@ """Pack, unpack and decode BC7 blocks, and generate blocks with known field values.""" import argparse +import contextlib import hashlib import json +import os from pathlib import Path import struct +import tempfile # Per mode: subsets, partition bits, rotation bits, index selection bits, colour bits, alpha bits, @@ -239,14 +242,71 @@ def fixture(columns=16, rows=32): return fields, b"".join(blocks), bytes(pixels) -if __name__ == "__main__": +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _atomic_write_outputs(outputs: list[tuple[Path, bytes | str]]) -> None: + """Stage all payloads, then publish each output with a separate atomic replace.""" + staged: list[tuple[Path, Path]] = [] + with contextlib.ExitStack() as stack: + dirs_by_parent: dict[Path, Path] = {} + for destination, payload in outputs: + destination.parent.mkdir(parents=True, exist_ok=True) + parent_key = destination.parent.resolve() + staging_root = dirs_by_parent.get(parent_key) + if staging_root is None: + staging_root = Path(stack.enter_context(tempfile.TemporaryDirectory(dir=destination.parent))) + dirs_by_parent[parent_key] = staging_root + staged_path = staging_root / f"{len(staged)}_{destination.name}" + if isinstance(payload, bytes): + staged_path.write_bytes(payload) + else: + staged_path.write_text(payload, encoding="ascii") + staged.append((staged_path, destination)) + for index, (staged_path, destination) in enumerate(staged): + try: + os.replace(staged_path, destination) + except OSError as error: + if index: + raise OSError(f"Updated {staged[0][1]}, but could not replace {destination}: {error}. " + "Retry with both output paths to regenerate the pair.") from error + raise + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("case", type=Path, help="Output in the BC7C layout read by offscreen_check") parser.add_argument("--columns", type=int, default=16, help="Blocks per row") parser.add_argument("--rows", type=int, default=32, help="Block rows") parser.add_argument("--fields", type=Path, help="Also write the field values of every block as JSON") - args = parser.parse_args() - known, block_rows, rgba = fixture(args.columns, args.rows) - args.case.write_bytes(struct.pack("<4sII", b"BC7C", args.columns * 4, args.rows * 4) + block_rows + rgba) - if args.fields: - args.fields.write_text(json.dumps(known, indent=1), encoding="ascii") + args = parser.parse_args(argv) + try: + if args.columns <= 0 or args.rows <= 0: + raise ValueError("Expected positive block dimensions") + for path in (args.case, args.fields): + if path is not None and path.exists() and path.is_dir(): + raise ValueError(f"Output path is an existing directory: {path}") + if args.fields is not None: + if _same_path(args.case, args.fields): + raise ValueError(f"Fields path collides with case output: {args.fields}") + case_path, fields_path = args.case.resolve(), args.fields.resolve() + if case_path in fields_path.parents or fields_path in case_path.parents: + raise ValueError("Case and fields outputs cannot contain one another") + header = struct.pack("<4sII", b"BC7C", args.columns * 4, args.rows * 4) + known, block_rows, rgba = fixture(args.columns, args.rows) + outputs: list[tuple[Path, bytes | str]] = [ + (args.case, header + block_rows + rgba) + ] + if args.fields is not None: + outputs.append((args.fields, json.dumps(known, indent=1))) + _atomic_write_outputs(outputs) + except (OSError, ValueError, struct.error) as exc: + parser.exit(1, f"{exc}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 565f9d59dbfcc326768fdad6d6471ef10bb9e187 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:08:31 +0100 Subject: [PATCH 052/232] shader: lower buffer_store_dwordx3 in gfx2hlsl (Part of #1723) (#2059) * feat: lower vertex-stage buffer_store_dword..x4 to RWByteAddressBuffer stores Part of #1723. Manifest version 2 carries a uav line; the runtime rejects version 2 until it binds the view. Shader cache revision advances to 7. * fix: refuse modified descriptors and unaligned offsets in buffer store lowering; document offline-only stores * docs: describe offline-only vertex buffer stores * fix: move the shader cache revision to x2w-startup-shader-9 for the buffer-store lowering * test: give the D16 image-load stub pipeline an empty uavs table * test: expect the shared read-and-store refusal wording in the buffer store check * fix: move the shader cache revision to x2w-startup-shader-10 and reuse the raw UAV kind for vertex buffer stores * test: update compute key literal and revision label for shader cache 13 --- CMakeLists.txt | 3 + docs/experiments.md | 8 + docs/startup-runtime.md | 6 +- src/startup_stubs/d3d12_draw.inl | 12 +- .../startup_compute_request_offline_check.py | 4 +- tests/startup_gfx2hlsl_buffer_store_check.py | 161 ++++++++++++++++++ tests/startup_image_load_d16_check.py | 1 + tests/startup_indirect_draw_indexed.cpp | 2 +- tools/startup/gfx2hlsl.py | 49 +++++- 9 files changed, 235 insertions(+), 11 deletions(-) create mode 100644 tests/startup_gfx2hlsl_buffer_store_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f71669e2..06b7938f4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2997,6 +2997,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_neg_operand COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_neg_operand_check.py") set_tests_properties(startup_gfx2hlsl_neg_operand PROPERTIES TIMEOUT 60) + # Vertex-stage buffer stores lower to RWByteAddressBuffer Store* under manifest version 2 (#1723). + add_test(NAME startup_gfx2hlsl_buffer_store COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_buffer_store_check.py") # Output modifiers on float-result conversions (#1705). add_test(NAME startup_gfx2hlsl_vcvt_omod COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_vcvt_omod_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index a3c2954a6..d2609f0a3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -191,6 +191,14 @@ The runtime binds an explicit or default 1D view and uploads single-array-slice using their desktop copyable footprints. Run `ctest --preset dev -R '^startup_1d_srv_' --no-tests=error` to check RGBA8 texel and alpha values, rebinding, and a mismatched 2D view on hardware and WARP. +## Offline vertex buffer stores + +`tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses version 2 manifests, so no store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_buffer_store$' --output-on-failure +``` + ## Offline store context forwarding The fake-user runtime creates an offline store context token. Unimplemented methods receiving diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 936f86ce1..52d649fe9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -204,12 +204,12 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-13`. Older translations evaluate `s_brev_b32` of a +The shader cache revision is `x2w-startup-shader-14`. Older translations evaluate `s_brev_b32` of a constant at run time instead of folding it into a known word, which changes the emitted HLSL. Revisions before 12 can overwrite the source mask when a save-EXEC instruction uses the same source and destination register. -Earlier revisions can also carry a stale scalar symbol across a join or read a stale SCC after -an operation on a descriptor word. +Earlier revisions can also carry a stale scalar symbol across a join, read a stale SCC after +an operation on a descriptor word, or lack the vertex buffer-store lowering. The record layouts were checked offline against the signatures of one title's shader archive (local files only, not in the repository). The counts below apply the translator's own record checks. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index db34a5afd..335498a90 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -167,6 +167,14 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) return; } matched_rtv = true; + } else if (line.compare(0, 13, "x2w-manifest ") == 0 && line != "x2w-manifest 1") { + // Version 2 adds `uav` lines for vertex-stage stores. This runtime does not bind them, + // so it must not draw a translation whose stores it would silently skip (#1723). + log("x2w-draw unsupported manifest version for %016llx", tr.key); + return; + } else if (line.compare(0, 4, "uav ") == 0) { + log("x2w-draw unsupported uav line for %016llx", tr.key); + return; } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { Translation::Ud ud{-1, x, y}; if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; @@ -235,7 +243,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-13"; + constexpr char revision[] = "x2w-startup-shader-14"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -355,7 +363,7 @@ void publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-13cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-14cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index 8e9d3bcf7..e1b2a943a 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0xcd0547493ef7bdaa # compute_key of the parts above +KEY = 0xb1d4a12271e064e1 # compute_key of the parts above def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-13cs': + for b in b'x2w-startup-shader-14cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' table ` line under an +`x2w-manifest 2` header. Programs without a store keep `x2w-manifest 1`. + +Instruction bytes are constructed from the MUBUF field layout the checked-in decoder reads; the root +signature is built field by field. Nothing comes from an archive. +""" +import os +import struct +import sys +import tempfile +from pathlib import Path +from unittest.mock import patch + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MUBUF_LOAD_DWORD = 0x0c +STORE_OPS = {'dword': 0x1c, 'dwordx2': 0x1d, 'dwordx4': 0x1e, 'dwordx3': 0x1f} +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def encode_mubuf(op, *, imm=0, offen=0, idxen=0, glc=0, slc=0, vaddr=0, vdata=1, srsrc=32, soffset=128): + w0 = (0b111000 << 26) | ((op & 0xff) << 18) | ((glc & 1) << 14) | ((idxen & 1) << 13) | ((offen & 1) << 12) | (imm & 0xfff) + w1 = ((soffset & 0xff) << 24) | ((slc & 1) << 22) | (((srsrc // 4) & 0x1f) << 16) | ((vdata & 0xff) << 8) | (vaddr & 0xff) + return struct.pack('.""" + return struct.pack(' translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-13"; + constexpr char revision[] = "x2w-startup-shader-14"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 06a4e6272..297be1a06 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3022,6 +3022,47 @@ def op_buffer_load_dwordx3(self, ops, mods): def op_buffer_load_dwordx4(self, ops, mods): self.op_buffer_load_dword(ops, mods, 4) + def op_buffer_store_vs(self, ops, mods, count): + # Vertex-stage store in the `off` form: scalar byte offset plus the 12-bit immediate, through a + # descriptor read from a fixed root-table slot, written to a RWByteAddressBuffer (issue #1723). + # The manifest carries the `uav` line the runtime binds; a descriptor may not also be loaded. + if self.kind != 'vs': + raise Unsupported('buffer store in the %s stage' % self.kind) + offset = 0 + for m in mods: + if m.startswith('offset:') and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + offset += int(m[7:], 0) + else: + raise Unsupported('buffer store modifier %s' % m) + if len(ops) != 4 or ops[1] != 'off': + raise Unsupported('buffer store without the off address form') + src = reg_range(ops[0]) + if not src or src[0] != 'v' or src[2] - src[1] != count - 1 or src[2] > 255: + raise Unsupported('buffer store data %s' % ops[0]) + key = self.descriptor(ops[2]) + if key[0][0] != 'table' or key[1] is None: + raise Unsupported('buffer store through %s' % (key,)) + if key in self.pipe.modified: + raise Unsupported('buffer store through a modified descriptor') + if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + offset += int(ops[3], 0) + soffset = '' + if offset % 4: + raise Unsupported('buffer store at unaligned byte offset %d' % offset) + else: + sreg = reg_range(ops[3]) + if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: + raise Unsupported('buffer soffset %s' % ops[3]) + if offset % 4: + raise Unsupported('buffer store at unaligned immediate offset %d' % offset) + soffset = '%s + ' % self.S(sreg[1]) + uav = self.pipe.uav(key, 'raw') + words = ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) + store = '%s.Store%s(a, %s);' % (uav, '' if count == 1 else str(count), 'uint%d(%s)' % (count, words) if count > 1 else words) + # Store* needs a multiple of four: the immediate is checked above; a register offset is rounded down. + self.emit('a = (%s%d) & 0xfffffffcu;' % (soffset, offset) if soffset else 'a = %d;' % offset) + self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) + def store_descriptor(self, tok, words, what, stride0_ok=False): """Resource key of a store's descriptor operand: all its words must still be the loaded words of one descriptor at a fixed table offset. A moved, overwritten or modified word (stride, num_records, format) @@ -3082,6 +3123,8 @@ def op_buffer_store_dword(self, ops, mods, count=1): # through a descriptor read from a fixed root-table slot, to a RWByteAddressBuffer (manifest `uav` line). # Like the loads, this assumes a raw descriptor (no swizzle or stride). Out-of-range stores: assumes a future # runtime sizes the view to the descriptor's range so both sides drop them; nothing binds or checks that yet. + if self.kind == 'vs': + return self.op_buffer_store_vs(ops, mods, count) if self.kind != 'cs': raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count) @@ -5069,7 +5112,7 @@ def common(self): for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): - out.append('%s w%d : register(u%d);' % ({'tex2d': 'RWTexture2D'}[r['kind']], r['index'], r['index'])) + out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) if self.uses_sampler_heap: @@ -5335,7 +5378,7 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-13')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-14')))) return fnv(layout, key) if layout else key @@ -5344,7 +5387,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-13cs') + key = fnv(b'x2w-startup-shader-14cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack(' Date: Wed, 25 Nov 2026 16:08:49 +0100 Subject: [PATCH 053/232] tests: start pixel_aot checks through runpy so cached bytecode is reused (#2362) * tests: start pixel_aot checks through the import system so the cached bytecode is reused * test: run big CTest scripts through one generic pyc entry tests/pyc_main.py loads tests/.py with runpy so its .pyc is reused. Covers pixel_aot_check and compute_store_check; replaces pixel_aot_main.py. * test: make pyc_main forwarding check independent of OS error language * test: keep the pyc_main forwarding probe inside its time budget --- CMakeLists.txt | 22 ++++++++++++++++ tests/pyc_main.py | 16 ++++++++++++ tests/pyc_main_check.py | 56 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 tests/pyc_main.py create mode 100644 tests/pyc_main_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 06b7938f4..43a623c92 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,9 +3,31 @@ project(Xbox2Windows LANGUAGES CXX) enable_testing() +# Python never caches the bytecode of the script it is started with, so every start of a big +# tests/.py recompiled it. tests/pyc_main.py runs that file through the import system, +# which reuses a valid .pyc. The add_test calls below keep naming the script; this wrapper swaps in +# the entry plus the module name in one place. Other add_test calls pass through unchanged. +set(x2w_pyc_main_modules pixel_aot_check compute_store_check) +function(add_test) + list(LENGTH ARGV x2w_test_argc) + if(NOT x2w_test_argc EQUAL ARGC) + message(FATAL_ERROR "add_test wrapper: an argument is empty or holds ';'; call _add_test directly") + endif() + set(x2w_test_args "${ARGV}") + foreach(x2w_module IN LISTS x2w_pyc_main_modules) + string(REPLACE "/tests/${x2w_module}.py" "/tests/pyc_main.py;${x2w_module}" x2w_test_args "${x2w_test_args}") + endforeach() + _add_test(${x2w_test_args}) +endfunction() + # Defined before the first Python-driven test so a fresh configure registers all of them. set(INTAKE_PYTHON "${CMAKE_SOURCE_DIR}/out/pe-env/Scripts/python.exe" CACHE FILEPATH "Native x64 Python with pefile for static intake tests") +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME pyc_main_entry COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pyc_main_check.py") + set_tests_properties(pyc_main_entry PROPERTIES TIMEOUT 60) +endif() set(DSTORAGE_SDK_ROOT "" CACHE PATH "Extracted Microsoft.Direct3D.DirectStorage NuGet package") if(DSTORAGE_SDK_ROOT) diff --git a/tests/pyc_main.py b/tests/pyc_main.py new file mode 100644 index 000000000..43a3a5160 --- /dev/null +++ b/tests/pyc_main.py @@ -0,0 +1,16 @@ +"""Generic entry for big CTest scripts: pyc_main.py [args...] runs tests/.py as __main__. + +Python never caches the bytecode of the script it is started with, so launching a 9k-25k line script +by path recompiles it on every start. runpy loads it as a module instead, which reuses a valid .pyc +(the Win2025 runner precompiles tests/ into PYTHONPYCACHEPREFIX; -B still reads it). +Arguments, exit status and exit-time side effects stay those of .__main__. +""" +import runpy +import sys + +if __name__ == "__main__": + if len(sys.argv) < 2: + sys.exit("usage: pyc_main.py [args...]") + module = sys.argv[1] + del sys.argv[0] # the module sees itself as argv[0]'s successor: [module, args...] + runpy.run_module(module, run_name="__main__", alter_sys=True) diff --git a/tests/pyc_main_check.py b/tests/pyc_main_check.py new file mode 100644 index 000000000..6be289abc --- /dev/null +++ b/tests/pyc_main_check.py @@ -0,0 +1,56 @@ +"""tests/pyc_main.py behaves like running tests/.py by path. + +For pixel_aot_check and compute_store_check, a run that fails fast without DXC or a GPU must return the +same exit status through the entry as by path, show the forwarded arguments, and (pixel_aot_check) still +write the form-coverage record at exit. +""" +import os +import subprocess +import sys +import tempfile + +TESTS = os.path.dirname(os.path.abspath(__file__)) +NO_SUCH_MODE = "no-such-mode-for-pyc-main-check" + + +def run(argv, record=None): + env = dict(os.environ) + if record: + env["FORM_COVERAGE_RECORD"] = record + return subprocess.run([sys.executable, "-B", *argv], capture_output=True, text=True, env=env, + timeout=120, cwd=TESTS) + + +def pixel_aot_forwards_status_args_and_record(): + # Missing arguments: this mode is rejected before the script runs its control suite, so both runs stay fast. + args = ["draw-e64"] + with tempfile.TemporaryDirectory() as tmp: + direct_record = os.path.join(tmp, "direct.txt") + entry_record = os.path.join(tmp, "entry.txt") + direct = run([os.path.join(TESTS, "pixel_aot_check.py"), *args], direct_record) + entry = run([os.path.join(TESTS, "pyc_main.py"), "pixel_aot_check", *args], entry_record) + assert direct.returncode != 0, "control run unexpectedly passed" + assert entry.returncode == direct.returncode, (entry.returncode, direct.returncode, entry.stderr[-400:]) + assert "check_e64_render() missing" in entry.stderr, entry.stderr[-400:] + assert os.path.exists(entry_record), "exit record was not written" + with open(direct_record, encoding="utf-8") as a, open(entry_record, encoding="utf-8") as b: + assert a.read() == b.read() + + +def compute_store_forwards_status_and_args(): + direct = run([os.path.join(TESTS, "compute_store_check.py"), NO_SUCH_MODE]) + entry = run([os.path.join(TESTS, "pyc_main.py"), "compute_store_check", NO_SUCH_MODE]) + assert direct.returncode != 0, "control run unexpectedly passed" + assert entry.returncode == direct.returncode, (entry.returncode, direct.returncode, entry.stderr[-400:]) + assert NO_SUCH_MODE in entry.stderr, entry.stderr[-400:] + + +def main(): + pixel_aot_forwards_status_args_and_record() + compute_store_forwards_status_and_args() + print("pyc_main forwards arguments, exit status and the exit record") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 0eaa2effa1d923f803974a822d18a7312ae19a27 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 23:09:56 +0800 Subject: [PATCH 054/232] shader: lower the first active lane at compute dispatch entry (#2389) --- docs/experiments.md | 11 +++++++++++ tests/startup_gfx2hlsl_compute_check.py | 20 ++++++++++++++++++-- tools/startup/gfx2hlsl.py | 12 ++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index d2609f0a3..53a7ff2a5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13953,6 +13953,17 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_' -V python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 ``` +### First active lane at compute entry + +The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the +entry block while EXEC still has its dispatch-entry value. Lane zero is +active even in a partial wave. Case `A-ff1` overwrites a nonzero input +stride with that lane index in a 24-thread group and checks 320 output and +guard words. The offline check also rejects a changed EXEC, a back edge to +entry and a VCC source. Reproduce with +`python -B tests/startup_gfx2hlsl_compute_check.py` and +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_(warp|hardware)$'`. + ### Startup compute masked bit count For groups of at most 32 threads, the startup translator lowers gfx1013 diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index baf870b70..a6665b8ca 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -412,6 +412,11 @@ def splice(*lines, at=STORE_A): CASES['I'] = (SOURCE_A.replace('buffer_store_dword', STRIDE_CLEAR + '\nbuffer_store_dword'), splice(STRIDE_CLEAR), *CASES['A'][2:]) +# Replace the nonzero stride constant in s5 with the first active lane of a +# fresh 24-thread group. Ignoring FF1 leaves a different word at every i > 0. +CASES['A-ff1'] = ('s_ff1_i32_b32 s5, exec_lo\n' + SOURCE_A, + bytes.fromhex('7e1385be') + WORDS_A, *CASES['A'][2:]) + def root_blob(constants=2, table_range=False): """RTS0: param 0 = root constants (b0), param 1 = a descriptor table with no ranges. @@ -476,9 +481,10 @@ def expected(name): for tz in range(local[2]): for ty in range(local[1]): for tx in range(local[0]): - if name == 'A': + if name in ('A', 'A-ff1'): i = (gx + 3 * gy + 6 * gz) * 24 + tx + 2 * ty + 6 * tz - out[i] = ((input_word(i) * 33) & MASK) ^ ((KEY + i * STRIDE) & MASK) + stride = 0 if name == 'A-ff1' else STRIDE + out[i] = ((input_word(i) * 33) & MASK) ^ ((KEY + i * stride) & MASK) elif name == 'K': i = gx * 8 + tx if gx == 1: # only group 1's wave enters the block @@ -675,6 +681,16 @@ def check_lds(): def check_controls(): + ff1 = bytes.fromhex('7e1385be') + end = bytes.fromhex('000081bf') + # A write to EXEC can disable lane zero; a backward branch can re-enter + # the instruction with a different mask even at code offset zero. + for code in (bytes.fromhex('8003febe') + ff1 + end, + ff1 + bytes.fromhex('feff82bf') + end): + refused('compute entry EXEC mask', lambda: translate('A', code=code)) + refused('requires compute exec_lo', lambda: translate('A', code=bytes.fromhex('6a1385be') + end)) + assert 's5 = 0u;' in translate('A-ff1').hlsl_cs() + assert expected('A-ff1') != expected('A') check_lds() check_descriptor_scc() check_mbcnt() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 297be1a06..eccba084e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3882,6 +3882,18 @@ def op_v_cvt_pk_u8_f32(self, ops, mods): self.set_v(dst[1], '((%s & ~(0xffu << %s)) | ((uint(clamp(F(%s), 0.0, 255.0)) & 0xffu) << %s))' % (rest, shift, value, shift)) + def op_s_ff1_i32_b32(self, ops, mods): + if self.kind != 'cs' or mods or len(ops) != 2 or ops[1] != 'exec_lo': + raise Unsupported('s_ff1_i32_b32 requires compute exec_lo') + dst = reg_range(ops[0]) + if not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105: + raise Unsupported('s_ff1_i32_b32 requires one SGPR destination') + if self.past_entry or not self.exec_known: + raise Unsupported('s_ff1_i32_b32 requires the compute entry EXEC mask') + # At dispatch entry even the last partial wave starts at lane zero. + # FF1 reports its index and leaves SCC unchanged. + self.set_s(dst[1], '0u', ('const', 0)) + def op_v_mbcnt_lo_u32_b32(self, ops, mods, high=False): name = 'v_mbcnt_%s_u32_b32' % ('hi' if high else 'lo') if self.kind != 'cs': From abf6492fbfc28bc838d3925ca4b55335228f552d Mon Sep 17 00:00:00 2001 From: Maledetto Date: Wed, 25 Nov 2026 16:10:11 +0100 Subject: [PATCH 055/232] shader: lower flat_load_dwordx2 and global_load_dwordx2 through TitleLookup in pixel_aot (#2386) Refs #319 Co-authored-by: Maledetto <20729264+Makto94@users.noreply.github.com> --- docs/experiments.md | 4 +- tests/pixel_aot_check.py | 184 ++++++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 64 ++++++++++---- 3 files changed, 233 insertions(+), 19 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 53a7ff2a5..93d010f01 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7938,7 +7938,9 @@ Not established: why the driver compiler selects mode 14 for this shape; the `an A case file may carry a trailer after the 64 expected colors: one flags byte, whose bit 0 selects a `R32G32B32A32_UINT` readback target, followed by 64 per-texel mask bytes whose bit ch accepts a NaN of any sign or payload on that channel. A masked channel passes when the expected word and the exported word are both NaN, and the renderer logs a `nan_class` line with both raw words even on pass; masking a channel whose expected word is not NaN is a case-format error. Unmasked channels stay strict bitwise, comparison-predicate results stay strict, and integer moves, bit operations and bitcasts round-trip bit-for-bit through the integer readback. Any normalization observed on the float render target is specific to that path. The fixtures never claim a payload, sign or quieting rule for NaN results, only the class. -`flat_load_dword` and the `off` form of `global_load_dword` (issue #319) read one DWORD through a 64-bit title address with `TitleLookup` from `src/title_va_lookup.hlsli`, which `lower()` inlines when a program loads through it. The address is the VGPR pair plus the instruction offset, sign-extended to 64 bits with the carry or borrow taken into the high word. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned (0 to 2047) and global offsets as 12-bit signed, so a negative offset is only a global load; the flat encodings with bit 11 set, which LLVM prints as offsets 2048 to 4095, are refused. The range table is a `StructuredBuffer` at `t0, space1` and the aliased buffers are `ByteAddressBuffer TitleAliases[8]` at `t1, space1`, indexed with `NonUniformResourceIndex`, on the same `ps_6_0`-compatible path as `tests/gpu_alias_lookup.hlsl`. The range count is fixed at translation time (`lower(..., title_ranges=N)`); without it both forms are refused. Flat loads additionally require `flat_global_only=True`. The caller guarantees that all effective flat addresses name global memory and exclude the scratch and LDS apertures. An address in no range, a DWORD that does not lie inside a single range, a misaligned address and a slot past the eighth all read `0xdeadbeef`, never zero. The word is ready after a `vmcnt` wait that covers it, counted in issue order with image samples. Wider and sub-DWORD loads, D16 loads, stores, atomics, scratch, the global `saddr` and `lds` forms and cache-policy bits stay refused, each by a control, and the scratch-base writes still translate as no-ops before a flat load. The source-built program reads addresses A and B from constant words 3 to 6 and exports A, A + 2044, B - 2048 and B through the `R32G32B32A32_UINT` target. Six cases cover the first and last whole DWORD of a range, a carry and a borrow across the 32-bit boundary, misses in a hole and below the first range, a DWORD straddling a range end, and four ranges in four slots, two of them adjacent. The address words include quiet-NaN and subnormal patterns, which reach the lookup only through bit copies, as in the integer readback draw. Eight wrong references must report `pixel_mismatch`: the high address word dropped, the immediate ignored, the immediate masked instead of sign-extended, the carry dropped, zero instead of the sentinel, a straddling DWORD accepted, the slot masked to one bit and the range count one short. Each is followed by a passing draw, and the 22 draws run in one `--check-pixel-batch` process. The case trailer's flag bit 2 carries the ranges and the eight slot buffers; the renderer then binds them after the two textures with a root signature that extends the vertex shader's. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_title_loads_(warp|hardware)$' -V`; the LLVM 15 round trip covers the program. The draws show what the translated shader reads from the bound ranges on a desktop GPU, not how the console resolves flat apertures. +`flat_load_dword` and the `off` form of `global_load_dword` (issue #319) read one DWORD through a 64-bit title address with `TitleLookup` from `src/title_va_lookup.hlsli`, which `lower()` inlines when a program loads through it. The address is the VGPR pair plus the instruction offset, sign-extended to 64 bits with the carry or borrow taken into the high word. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned (0 to 2047) and global offsets as 12-bit signed, so a negative offset is only a global load; the flat encodings with bit 11 set, which LLVM prints as offsets 2048 to 4095, are refused. The range table is a `StructuredBuffer` at `t0, space1` and the aliased buffers are `ByteAddressBuffer TitleAliases[8]` at `t1, space1`, indexed with `NonUniformResourceIndex`, on the same `ps_6_0`-compatible path as `tests/gpu_alias_lookup.hlsl`. The range count is fixed at translation time (`lower(..., title_ranges=N)`); without it both forms are refused. Flat loads additionally require `flat_global_only=True`. The caller guarantees that all effective flat addresses name global memory and exclude the scratch and LDS apertures. An address in no range, a DWORD that does not lie inside a single range, a misaligned address and a slot past the eighth all read `0xdeadbeef`, never zero. The word is ready after a `vmcnt` wait that covers it, counted in issue order with image samples. The x3 and x4 loads, sub-DWORD loads, D16 loads, stores, atomics, scratch, the global `saddr` and `lds` forms and cache-policy bits stay refused, each by a control, and the scratch-base writes still translate as no-ops before a flat load. The source-built program reads addresses A and B from constant words 3 to 6 and exports A, A + 2044, B - 2048 and B through the `R32G32B32A32_UINT` target. Six cases cover the first and last whole DWORD of a range, a carry and a borrow across the 32-bit boundary, misses in a hole and below the first range, a DWORD straddling a range end, and four ranges in four slots, two of them adjacent. The address words include quiet-NaN and subnormal patterns, which reach the lookup only through bit copies, as in the integer readback draw. Eight wrong references must report `pixel_mismatch`: the high address word dropped, the immediate ignored, the immediate masked instead of sign-extended, the carry dropped, zero instead of the sentinel, a straddling DWORD accepted, the slot masked to one bit and the range count one short. Each is followed by a passing draw, and the 22 draws run in one `--check-pixel-batch` process. The case trailer's flag bit 2 carries the ranges and the eight slot buffers; the renderer then binds them after the two textures with a root signature that extends the vertex shader's. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_title_loads_(warp|hardware)$' -V`; the LLVM 15 round trip covers the program. The draws show what the translated shader reads from the bound ranges on a desktop GPU, not how the console resolves flat apertures. + +`flat_load_dwordx2 v[d:d+1], v[a:a+1]` and the `off` form of `global_load_dwordx2` (issue #319) take the same address, offset ranges and profile as the DWORD loads and look up 8 bytes at once: `TitleLookup(..., 8, ...)` and `Load2` on the aliased buffer. Both destination words are ready after the same `vmcnt` wait, and each blocks a reuse of its register until then. A QWORD that does not lie inside one range reads `0xdeadbeef` in both words, including a QWORD that starts in one range and ends in the adjacent one, because `TitleLookup` succeeds only when the whole access lies inside one range; the translation does not split such a load. The helper is emitted only when a program uses it, so DWORD-only translations are unchanged. The source-built program reads the QWORDs at A + 2040 (flat) and B - 2048 (global) into channels 0 to 3. Seven cases cover a hit in two slots, the last QWORD of two ranges, a QWORD across the adjacent ranges at `0x2_0000_1000` and one across the end of a range, two misses, a QWORD across the 32-bit boundary inside one range, a QWORD across a range end into a hole, and a negative offset that borrows across the low 32 bits with the QWORD crossing 2^32 inside one range. Four wrong references must report `pixel_mismatch`: the two words swapped, a 4-byte lookup, the range accepted for the first word only (a hit in word 0 and a miss in word 1), and a separate lookup for each word. Each is followed by a passing draw; the 15 draws run in a second `--check-pixel-batch` process of the same `pixel_aot_title_loads_(warp|hardware)` test. The `x3` and `x4` widths, `glc`, `slc` and `dlc`, `saddr`, `lds`, sub-DWORD widths, stores, atomics and scratch stay refused by controls. `v_fmaak_f32` computes S0 × S1 + K and `v_fmamk_f32` computes S0 × K + S1, where K is the 32-bit literal that LLVM prints in that position. Both use the `v_fma_f32` lowering; the translator refuses a register where the literal belongs. The draw computes each instruction twice with inputs 1.5, 2.5, -3.0 and 0.75 and the literals 0.25, 3.0, -0.5 and 0.5. Every product and sum is exact in binary32, so the reference does not depend on fusion. A reference that swaps the literal with S1 must report a mismatch in each channel. diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index e44288b23..41f7000cd 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -19140,6 +19140,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append((uncompressed_export(cvt_float_body(0x3fc00000, 0xc0300000)), translate_int)) fixtures.extend((uncompressed_export(nc_integer_group(group)), translate_int) for group in (1, 2, 3)) fixtures.append((title_program(), translate_title)) + fixtures.append((uncompressed_export(TITLE_X2_BODY), translate_title)) fixtures.append((uncompressed_export(CVT_FLOAT_E64_PLAIN_BODY), translate_int)) fixtures.append((uncompressed_export(CVT_FLOAT_E64_U32_MOD_BODY), translate_int)) fixtures.append((uncompressed_export(CVT_FLOAT_E64_I32_MOD_BODY), translate_int)) @@ -20467,6 +20468,86 @@ def title_program(): return uncompressed_export(TITLE_BODY) +# flat_load_dwordx2 and global_load_dwordx2 look up the whole QWORD: both words come from one range or both read +# TITLE_MISS. A QWORD across two adjacent ranges is a miss, as TitleLookup (src/title_va_lookup.hlsli) defines. +# Channels 0 and 1 are the QWORD at A + 2040, channels 2 and 3 the QWORD at B - 2048. +TITLE_X2_BODY = [ + "v_mov_b32_e32 v20, s44", + "v_mov_b32_e32 v21, s45", + "v_mov_b32_e32 v22, s46", + "v_mov_b32_e32 v23, s47", + "flat_load_dwordx2 v[12:13], v[20:21] offset:2040", + "global_load_dwordx2 v[14:15], v[22:23], off offset:-2048", + "s_waitcnt vmcnt(0) lgkmcnt(0)", +] +TITLE_X2_OFFSETS = (2040, -2048) +TITLE_X2_CASES = ( # effective addresses (QWORD at A + 2040, QWORD at B - 2048) + (0x2_0000_0000, 0x2_0000_1800), # inside two ranges, in two slots + (0x0_0010_00f8, 0x2_0000_0ff8), # last whole QWORD of two ranges + (0x2_0000_0ffc, 0x0_0010_00fc), # across the adjacent ranges at 0x2_0000_1000; across the end of a range + (0x1_8000_0000, 0x0_0000_0800), # misses: a hole between ranges, and below the first range + (0x0_ffff_fffc, 0x1_0000_07f8), # across the 32-bit boundary inside one range; last QWORD of that range + (0x2_0000_1ff8, 0x1_0000_07fc), # last QWORD of the last range; across the end of a range into a hole + (0x2_0000_0000, 0x0_ffff_fffc), # global offset -2048 borrows across the low 32 bits; QWORD across 2^32 inside one range +) +# Wrong references, each with the (case, channel) it changes: the two words swapped, a 4-byte lookup instead of +# 8, the range accepted for the first word only, and a separate lookup for each word. +TITLE_X2_MUTATIONS = {"swap": (0, 0), "narrow": (2, 0), "first": (2, 0), "separate": (2, 1)} + + +def title_x2_reference(address, mutation=None): + """The two words a QWORD load at address returns; mutation names one wrong reference.""" + def hit(where, width): + for begin, end, slot in TITLE_RANGES: + if where % 4 == 0 and begin <= where and where + width <= end: + return slot, (where - begin) // 4 + return None + + whole = hit(address, 8) + if mutation == "narrow": + whole = hit(address, 4) + if whole is not None: + words = [title_word(whole[0], whole[1]), title_word(whole[0], whole[1] + 1)] + else: + words = [pixel_aot.TITLE_MISS] * 2 + if mutation == "swap": + words.reverse() + if mutation == "first": + first = hit(address, 4) + words[0] = title_word(*first) if first else pixel_aot.TITLE_MISS + if mutation == "separate": + second = hit(address + 4, 4) + words[1] = title_word(*second) if second else pixel_aot.TITLE_MISS + return words + + +def title_x2_words(addresses, mutation=None): + return tuple(word for address in addresses for word in title_x2_reference(address, mutation)) + + +def title_x2_constants(addresses): + """The values of A and B (constant words 3 to 6) that put the QWORDs at the effective addresses.""" + a, b = (address - offset for address, offset in zip(addresses, TITLE_X2_OFFSETS)) + return a, b + + +def title_x2_controls(): + """Check that the cases cover a hit, a miss and the straddles, and that each mutation changes its channel.""" + expected = [title_x2_words(addresses) for addresses in TITLE_X2_CASES] + for addresses in TITLE_X2_CASES: + assert all(address % 4 == 0 for address in addresses) and all(v >= 0 for v in title_x2_constants(addresses)) + assert expected[0] == (title_word(0, 0), title_word(0, 1), title_word(3, 0x200), title_word(3, 0x201)) + assert expected[1][:2] == (title_word(1, 0x3e), title_word(1, 0x3f)) and expected[1][3] == 0xa00003ff + assert expected[2] == (pixel_aot.TITLE_MISS,) * 4 and expected[3] == (pixel_aot.TITLE_MISS,) * 4 + assert expected[4] == (title_word(2, 0x1ff), title_word(2, 0x200), title_word(2, 0x3fe), title_word(2, 0x3ff)) + assert expected[6] == (title_word(0, 0), title_word(0, 1), title_word(2, 0x1ff), title_word(2, 0x200)) + assert expected[5] == (title_word(3, 0x3fe), title_word(3, 0x3ff), pixel_aot.TITLE_MISS, pixel_aot.TITLE_MISS) + for mutation, (index, channel) in TITLE_X2_MUTATIONS.items(): + assert title_x2_words(TITLE_X2_CASES[index], mutation)[channel] != expected[index][channel], mutation + # Both words of a QWORD that starts inside one range and ends in the next are misses, not one hit and one miss. + assert title_x2_words(TITLE_X2_CASES[2], "first")[:2] == (title_word(0, 0x3ff), pixel_aot.TITLE_MISS) + + def translate_title(instructions): """translate_int() with the TITLE_RANGES table bound for flat and global loads.""" return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, @@ -20488,7 +20569,90 @@ def title_controls(): assert title_words(*TITLE_CASES[2], "carry")[1] == title_words(*TITLE_CASES[2], "mask")[2] == pixel_aot.TITLE_MISS +def check_title_load_x2_controls(): + title_x2_controls() + program = uncompressed_export(TITLE_X2_BODY) + source = translate_title(program) + assert source.count("bool TitleLookup(") == 1 and source.count("uint2 title_load_dwordx2(") == 1 + assert "address, 8, slot, byteOffset" in source and ".Load2(byteOffset)" in source + assert source.count("title_load_dwordx2(uint2(") == 2 and "title_load_dword(uint2(" not in source + assert "uint2(0x7f8u, 0x0u)" in source and "uint2(0xfffff800u, 0xffffffffu)" in source + # Without a QWORD load the translation is the DWORD one, byte for byte. + assert "title_load_dwordx2" not in translate_title(title_program()) + # Both forms need the same profile and range table as the DWORD loads. + expect_value_error(translate_int, program, "Title memory is not bound") + def without_flat_binding(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, + integer_export=True, title_ranges=len(TITLE_RANGES)) + + expect_value_error(without_flat_binding, program, "Flat loads require the global-only address profile") + global_program = [line.replace("flat_load_dwordx2", "global_load_dwordx2").replace(":21] offset:2040", ":21], off") + for line in program] + assert without_flat_binding(global_program).count("title_load_dwordx2(uint2(") == 2 + flat = "flat_load_dwordx2 v[12:13], v[20:21] offset:2040" + + def replaced(line): + return [line if entry == flat else entry for entry in program] + + # Wider and narrower neighbours, cache-policy bits, saddr, LDS and out-of-range offsets stay refused. + for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", "flat_load_dwordx4 v[12:15], v[20:21]", + "flat_load_dwordx2 v[12:13], v[20:21] glc", "flat_load_dwordx2 v[12:13], v[20:21] slc", + "flat_load_dwordx2 v[12:13], v[20:21] offset:8 glc slc dlc", + "flat_load_dwordx2 v[12:13], v[20:21] dlc", "global_load_dwordx2 v[12:13], v[20:21], off glc", + "global_load_dwordx2 v[12:13], v[20:21], off slc", "global_load_dwordx2 v[12:13], v[20:21], off dlc", + "global_load_dwordx2 v[12:13], v20, s[44:45]", "global_load_dwordx2 v[12:13], v20, s[44:45] offset:-8", + "global_load_dwordx2 v[12:13], v[20:21], off lds", "global_load_dwordx3 v[12:14], v[20:21], off", + "global_load_dwordx4 v[12:15], v[20:21], off", "flat_load_ubyte v12, v[20:21]", "flat_load_sshort v12, v[20:21]", + "flat_load_short_d16 v12, v[20:21]", "global_load_ubyte v12, v[20:21], off", + "flat_store_dwordx2 v[20:21], v[12:13]", "global_store_dwordx2 v[20:21], v[12:13], off", + "flat_atomic_add_x2 v[12:13], v[20:21], v[14:15] glc", + "flat_atomic_add_x2 v[20:21], v[14:15]", "scratch_load_dwordx2 v[12:13], v20, off", + "scratch_load_dwordx2 v[12:13], off, s48", "scratch_store_dwordx2 off, v[12:13], s48 offset:16"): + expect_value_error(translate_title, replaced(neighbour), "Unsupported instruction") + # A QWORD needs a register pair and a DWORD one register; the other pairing is a refused load form. + for form in ("flat_load_dwordx2 v12, v[20:21]", "flat_load_dword v[12:13], v[20:21]", + "global_load_dword v[12:13], v[20:21], off", "flat_load_dwordx2 v[12:13], v[20:21] offset:2048", "flat_load_dwordx2 v[12:13], v[20:21] offset:-8", + "flat_load_dwordx2 v[12:13], v[20:21], off", "global_load_dwordx2 v[12:13], v[20:21]", + "global_load_dwordx2 v[12:13], v[20:21], off offset:2048", + "global_load_dwordx2 v[12:13], v[20:21], off offset:-2049"): + expect_value_error(translate_title, replaced(form), "load form") + must_reject(translate_title, replaced("flat_load_dwordx2 v[12:14], v[20:21]")) + must_reject(translate_title, replaced("flat_load_dwordx2 v[12:13], v[20:22]")) + must_reject(translate_title, replaced("flat_load_dwordx2 v[12:13], v[24:25]")) # address never written + expect_value_error(translate_title, replaced("flat_load_dwordx2 v[255:256], v[20:21]"), "Invalid title memory load") + wqm = program.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(translate_title, program[:wqm] + [flat] + program[wqm:], "Invalid title memory load") + # Both destination words are ready only after vmcnt covers the load, and either one blocks a second load. + wait = program.index("s_waitcnt vmcnt(0) lgkmcnt(0)") + for replacement in ([], ["s_waitcnt lgkmcnt(0)"], ["s_waitcnt vmcnt(1)"]): + must_reject(translate_title, program[:wait] + replacement + program[wait + 1:]) + for use in ("v16, v13, v13", "v16, v12, v12"): + expect_value_error(translate_title, program[:wait] + [f"v_add_f32_e32 {use}"] + program[wait:], + "Sample used before vmcnt wait") + for overlap in ("v[13:14]", "v[11:12]"): + expect_value_error(translate_title, program[:wait] + [f"flat_load_dwordx2 {overlap}, v[20:21]"] + program[wait:], + "Invalid title memory load") + loaded = program[:wait + 1] + ["flat_load_dwordx2 v[16:17], v[12:13]", "s_waitcnt vmcnt(0)"] + program[wait + 1:] + assert translate_title(loaded).count("title_load_dwordx2(uint2(") == 3 + # A DWORD load in flight in the low register of the pair blocks the QWORD load, with no wait between them. + start = program.index(flat) + expect_value_error(translate_title, program[:start] + ["flat_load_dword v12, v[20:21]"] + program[start:], + "Invalid title memory load") + # The last VGPR pair is a valid destination in both segments. + for edge in ("flat_load_dwordx2 v[254:255], v[20:21]", "global_load_dwordx2 v[254:255], v[22:23], off"): + edge_program = program[:wait + 1] + [edge, "s_waitcnt vmcnt(0)"] + program[wait + 1:] + assert translate_title(edge_program).count("title_load_dwordx2(uint2(") == 3 + # A QWORD load counts as one load in vmcnt: after vmcnt(1) the older DWORD is ready and the QWORD is not. + partial = program[:start] + ["flat_load_dword v10, v[20:21]", flat, "s_waitcnt vmcnt(1)"] + tail = program[start + 1:] + assert translate_title(partial + ["v_add_f32_e32 v16, v10, v10"] + tail).count("title_load_dword(uint2(") == 1 + for early in ("v16, v12, v12", "v16, v13, v13"): + expect_value_error(translate_title, partial + [f"v_add_f32_e32 {early}"] + tail, + "Sample used before vmcnt wait") + + def check_title_load_controls(): + check_title_load_x2_controls() title_controls() program = title_program() source = translate_title(program) @@ -20519,12 +20683,12 @@ def replaced(line): # Neighbours that stay unsupported: other widths, sub-DWORD and D16 loads, stores, atomics, scratch, the # global saddr and LDS forms, cache-policy bits, and offsets outside each segment's assembler range. - for neighbour in ("flat_load_dwordx2 v[12:13], v[20:21]", "flat_load_dwordx3 v[12:14], v[20:21]", + for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", "flat_load_dwordx4 v[12:15], v[20:21]", "flat_load_ubyte v12, v[20:21]", "flat_load_sbyte v12, v[20:21]", "flat_load_ushort v12, v[20:21]", "flat_load_sshort v12, v[20:21]", "flat_load_short_d16 v12, v[20:21]", "flat_load_short_d16_hi v12, v[20:21]", "flat_store_dword v[20:21], v12", - "flat_atomic_add v12, v[20:21], v13 glc", "global_load_dwordx2 v[12:13], v[20:21], off", + "flat_atomic_add v12, v[20:21], v13 glc", "global_load_dwordx3 v[12:14], v[20:21], off", "global_load_ubyte v12, v[20:21], off", "global_store_dword v[20:21], v12, off", "global_load_dword v12, v20, s[44:45]", "global_load_dword v12, v20, s[44:45] offset:-8", "global_load_dword v[20:21], off lds", "scratch_load_dword v12, v20, off", @@ -20577,6 +20741,22 @@ def case(name, a, b, words): a, b = TITLE_CASES[index] cases += [(case(mutation, a, b, title_words(a, b, mutation)), "mismatch"), cases[index]] run_pixel_batch(renderer, backend, shader, cases) + # The QWORD loads: the same ranges and buffers, a second shader and one batch of 15 draws. + source = directory / "title_loads_x2.hlsl" + shader = directory / "title_loads_x2.cso" + source.write_text(translate_title(uncompressed_export(TITLE_X2_BODY)), encoding="ascii") + compile_shader(compiler, source, shader) + + def case_x2(name, addresses, words): + a, b = title_x2_constants(addresses) + return case(f"x2_{name}", a, b, words) + + title_x2_controls() + cases = [(case_x2(n, addresses, title_x2_words(addresses)), "pass") for n, addresses in enumerate(TITLE_X2_CASES)] + for mutation, (index, _) in TITLE_X2_MUTATIONS.items(): + addresses = TITLE_X2_CASES[index] + cases += [(case_x2(mutation, addresses, title_x2_words(addresses, mutation)), "mismatch"), cases[index]] + run_pixel_batch(renderer, backend, shader, cases) return 0 diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 899863477..71bb63dd2 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -653,18 +653,20 @@ def vgpr_span(token, count): # The lowering itself never reads MODE; the declaration only scopes the claim to preserved denormals. HALF_DENORM_PRESERVE = "preserve" # FLAT_SCR_LO and FLAT_SCR_HI hold the scratch base address. Only scratch_* and flat_* memory instructions and -# s_getreg_b32 can observe it. scratch_* and s_getreg_b32 of these registers are not lowered, and the one lowered flat -# form, flat_load_dword, reads only through the title ranges below (no private aperture), so a whole-register write -# (an immediate or any SGPR value) changes no result. +# s_getreg_b32 can observe it. scratch_* and s_getreg_b32 of these registers are not lowered, and the lowered flat +# forms, flat_load_dword and flat_load_dwordx2, read only through the title ranges below (no private aperture), +# so a whole-register write (an immediate or any SGPR value) changes no result. FLAT_SCRATCH = ("HW_REG_FLAT_SCR_LO", "HW_REG_FLAT_SCR_HI") # flat_load_dword and global_load_dword with `off` read one DWORD at a 64-bit title address: the address pair # plus the instruction offset, sign-extended to 64 bits with the carry or borrow taken into the high word. # TitleLookup (src/title_va_lookup.hlsli) finds the range holding the whole DWORD; the load then reads that # range's aliased buffer at the byte offset. An address in no range, a DWORD that does not lie inside a single -# range and a misaligned address read TITLE_MISS instead of zero. The range count is fixed at translation time -# (lower(title_ranges=...)), and TITLE_ALIAS_SLOTS bounds the aliased descriptors; a slot past it also reads -# TITLE_MISS. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned and global offsets as 12-bit signed. +# range and a misaligned address read TITLE_MISS instead of zero. The dwordx2 forms look up 8 bytes at once: both +# words read TITLE_MISS unless the whole QWORD lies inside one range, so a QWORD across two ranges is a miss. +# The range count is fixed at translation time (lower(title_ranges=...)), and TITLE_ALIAS_SLOTS bounds the aliased +# descriptors; a slot past it also reads TITLE_MISS. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned +# and global offsets as 12-bit signed. TITLE_ALIAS_SLOTS = 8 TITLE_MISS = 0xdeadbeef TITLE_OFFSETS = {"flat": range(0, 2048), "global": range(-2048, 2048)} @@ -685,6 +687,20 @@ def vgpr_span(token, count): }} """ +TITLE_MEMORY_X2 = """// The QWORD at base + offset: both words come from one range, or both read the miss word. +uint2 title_load_dwordx2(uint2 base, uint2 offset) +{{ + const uint low = base.x + offset.x; + const uint2 address = uint2(low, base.y + offset.y + (low < base.x ? 1u : 0u)); + uint slot; + uint byteOffset; + if (!TitleLookup(TitleRanges, TITLE_RANGE_COUNT, address, 8, slot, byteOffset) || slot >= {slots}u) {{ + return uint2({miss:#x}u, {miss:#x}u); + }} + return TitleAliases[NonUniformResourceIndex(slot)].Load2(byteOffset); +}} +""" + ALU = { "log": (1, "log2({0})"), "exp": (1, "exp2({0})"), "rcp": (1, "(1.0f / {0})"), # Same reciprocal; the integer-divide flag it raises has no desktop equivalent. @@ -3308,6 +3324,7 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= sample_kind = None # "plain", "comparison" or "gather" resource interpretation vector_loads = 0 # image samples and title loads issued, in vmcnt order title_loads = False + title_loads_x2 = False sample_dest = {} # VGPR -> issue number of its outstanding image_sample or title load ds_needs_wait = False exported = False @@ -4780,10 +4797,13 @@ def sample_coord(reg): for channel, n in zip("xy", dest): vector[f"v{n}"] = f"sample{i}.{channel}" sample_dest[f"v{n}"] = vector_loads - elif m := match(r"(flat|global)_load_dword (v\d+), v\[(\d+):(\d+)\](, off)?(?: offset:(-?\d+))?"): - # One DWORD through a 64-bit title address. Cache-policy bits, the global saddr form and - # every other width or direction are refused by the fall-through. - segment, dst, first, last, off, imm = m.groups() + elif m := match(r"(flat|global)_load_dword(x2)? (?:(v\d+)|v\[(\d+):(\d+)\]), v\[(\d+):(\d+)\](, off)?" + r"(?: offset:(-?\d+))?"): + # One DWORD, or with x2 one QWORD, through a 64-bit title address. Cache-policy bits, the global + # saddr form and every other width or direction are refused by the fall-through. + segment, wide, single, dst_first, dst_last, first, last, off, imm = m.groups() + if (wide is None) != (single is not None): + raise ValueError(f"Unsupported {segment} load form") offset = int(imm or 0) if (segment == "global") != (off is not None) or offset not in TITLE_OFFSETS[segment]: raise ValueError(f"Unsupported {segment} load form") @@ -4791,17 +4811,28 @@ def sample_coord(reg): raise ValueError("Title memory is not bound") if segment == "flat" and not flat_global_only: raise ValueError("Flat loads require the global-only address profile") - if mask != "entry" or int(dst[1:]) > 255 or int(last) > 255 or dst in sample_dest: + dests = [single[1:]] if wide is None else registers(dst_first, dst_last, 2) + dests = [f"v{n}" for n in dests] + if mask != "entry" or int(dests[-1][1:]) > 255 or int(last) > 255 or any(d in sample_dest for d in dests): raise ValueError("Invalid title memory load") low, high = [int_operand(f"v{n}", scalar, vector, pending, sample_dest, signed=False) for n in registers(first, last, 2)] extended = offset & 0xffffffffffffffff - lines.append(f" precise float alu{i} = asfloat(title_load_dword(uint2({low}, {high}), " - f"uint2({extended & 0xffffffff:#x}u, {extended >> 32:#x}u)));") + arguments = f"uint2({low}, {high}), uint2({extended & 0xffffffff:#x}u, {extended >> 32:#x}u)" + if wide is None: + lines.append(f" precise float alu{i} = asfloat(title_load_dword({arguments}));") + values = [f"alu{i}"] + else: + lines.append(f" const uint2 title{i} = title_load_dwordx2({arguments});") + lines.append(f" precise float alu{i}x = asfloat(title{i}.x);") + lines.append(f" precise float alu{i}y = asfloat(title{i}.y);") + values = [f"alu{i}x", f"alu{i}y"] + title_loads_x2 = True title_loads = True vector_loads += 1 - vector[dst] = f"alu{i}" - sample_dest[dst] = vector_loads + for dst, value in zip(dests, values): + vector[dst] = value + sample_dest[dst] = vector_loads elif m := match(r"(image_sample_c(?:_lz)?(?:_o)?) (v\d+), (?:v\[(\d+):(\d+)\]|\[(v\d+), (v\d+), (v\d+)\]), " r"s\[(\d+):(\d+)\], s\[(\d+):(\d+)\] dmask:0x1 dim:SQ_RSRC_IMG_2D"): # The optional packed offset precedes the reference, followed by the UV pair. @@ -6822,7 +6853,8 @@ def sample_coord(reg): lines[:0] = defs if title_loads: lookup = (Path(__file__).resolve().parents[1] / "src/title_va_lookup.hlsli").read_text() - lines[:0] = [lookup, TITLE_MEMORY.format(slots=TITLE_ALIAS_SLOTS, count=title_ranges, miss=TITLE_MISS)] + memory = TITLE_MEMORY + (TITLE_MEMORY_X2 if title_loads_x2 else "") + lines[:0] = [lookup, memory.format(slots=TITLE_ALIAS_SLOTS, count=title_ranges, miss=TITLE_MISS)] source = "\n".join([*lines, "}", ""]) return (source, channel_mask) if return_write_mask else source From 106603a724edc4dc135c59e2e3478de84352ef79 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 16:10:55 +0100 Subject: [PATCH 056/232] startup: write shader requests from the shader archive before a run (#1750) * startup: write shader requests from the shader archive before a run Translation requests were only written when the title created a pipeline, so every new pipeline cost a run before it could be drawn. A traced startup run showed the native programs come from 64-byte aligned zlib streams in the shader archive, byte for byte. tools/startup/archive_requests.py inflates those streams, joins a stream with the one that starts on the next 64-byte boundary, carves programs (36-byte header, s_inst_prefetch, 64-byte blocks on 256-byte steps) and pairs each pixel program with a directly following vertex program. Root signatures are not in the archive, so they come from earlier req_*.root files and every pair is written once per distinct root, with the runtime's key. gfx2hlsl.py --pending then translates them. Measured locally: 4,982 programs, 1,258 pairs, 3,774 requests in 22 s. Eight of the eleven pipelines of a cold run were among them with identical keys and byte-identical translations. Test: startup_archive_requests on a synthetic archive, with controls for unpaired programs, a pair cut off at the end of a stream, a stream off the 64-byte grid, a pair split across two consecutive streams, missing roots and a second run. Co-Authored-By: Claude Opus 5.5 * startup: address review findings in the archive request writer - "Directly following" is now enforced: a vertex program pairs only when it starts on the 256-byte step right after the pixel program. Before, any vertex program after a pixel program paired, whatever the gap. - A carved program must contain s_endpgm; one cut short by an all-zero block is counted as incomplete and never paired. - The memory map is closed, and the docs use a neutral placeholder. On the local archive both rules leave the result unchanged (1,258 pairs, 0 incomplete, 8 of 11 recorded keys), so every measured pair was already adjacent. The test adds a gap pair and a program without s_endpgm as controls, and a mutation of each rule is detected. Co-Authored-By: Claude Opus 5.5 * startup: bound archive inflation and harden the archive request tests Review follow-up. - A zlib stream that would inflate past 1 MiB (a measured one inflates to 64 KiB) is counted as oversized and skipped without inflating it in full, and a joined run of consecutive streams stops growing at 64 MiB. Before, a small crafted archive could make the tool allocate gigabytes. - A part that cannot be written leaves no .a and no temporary file and the run exits with an error; an archive without any pair also fails. Root files are read with a context manager. - The test computes the expected keys with its own copy of the runtime's FNV-1a (start value 1469598103934665603, as in d3d12_draw.inl) instead of gfx2hlsl.pipeline_key, parses the summary, and adds controls for an untagged program, a pair at offsets not a multiple of 4, an empty root file, an oversized stream, a blocked .root write and an archive without pairs. All nine mutants (step size, write order, tag check, alignment check, empty roots, inflate limit, temporary file cleanup, and both failure exits) are detected. The local archive gives the same 1,258 pairs and 8 of 11 recorded keys, with 0 oversized streams. Co-Authored-By: Claude Opus 5.5 * startup: classify carved programs from export targets, not translator support main now refuses some forms inside gfx2hlsl.decode (v_cndmask_b32_e64 with NEG on an immediate), and gfx2hlsl.classify goes through decode, so 289 carved programs became "undecodable" and 143 pairs were lost. Which programs pair must not depend on whether they can be translated. stage_of() applies the same export-target rule as classify but reads the disassembler directly. The local archive is back to 1,258 pairs with 0 undecodable programs, and 8 of the 11 recorded pipelines, re-keyed with the current revision, are among the offline requests. The test reads the key revision from src/startup_stubs/d3d12_draw.inl (main bumped it to x2w-startup-shader-4) instead of hard-coding it, and one vertex program now contains that refused v_cndmask form; going back to classify() loses the pair and is detected. Co-Authored-By: Claude Opus 5.5 * startup: list the archive check apart from the watch check #1749 adds its check right after startup_gfx2hlsl_capture_check.py in AGENTS.md and the workflow, as this PR did, so whichever merged second conflicted. This entry now sits two lines further down, so the two PRs merge in either order. Co-Authored-By: Claude Opus 5.5 * startup: test the 64 MiB cap on joined archive streams 130 consecutive 512 KiB zlib streams (65 MiB inflated, a few KB on disk) must come out as two joined runs. Before, removing the cap still passed the test. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 4 + docs/startup-runtime.md | 61 +++++++ tests/startup_archive_requests_check.py | 206 +++++++++++++++++++++++ tools/startup/archive_requests.py | 208 ++++++++++++++++++++++++ 6 files changed, 481 insertions(+) create mode 100644 tests/startup_archive_requests_check.py create mode 100644 tools/startup/archive_requests.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 9d2e61a54..d8ce37144 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -230,6 +230,7 @@ jobs: tests/startup_gfx2hlsl_watch_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_archive_requests_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_compute_request_offline_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 75c0bc30c..2af03946a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -176,6 +176,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_watch_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py +./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py ./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 43a623c92..417d15551 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2929,6 +2929,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_capture COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_capture_check.py") set_tests_properties(startup_gfx2hlsl_capture PROPERTIES TIMEOUT 120) + # archive_requests.py writes runtime-keyed shader requests from a synthetic archive. + add_test(NAME startup_archive_requests COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_archive_requests_check.py") + set_tests_properties(startup_archive_requests PROPERTIES TIMEOUT 120) # Two integer operations whose refusal was never reached: v_cvt_i32_f32 with an output # modifier, and v_readfirstlane_b32 without a proven uniform source. add_test(NAME startup_gfx2hlsl_op_refusals COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 52d649fe9..043429b30 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -886,6 +886,67 @@ Its `wrong_group` control swaps the group size in the state block and must misma request, translation, bytecode and dispatch fit together. It does not prove the state-block reading, because the fixture builds the block at the offsets the translator reads. +### Shader requests from the archive, before a run + +`tools/startup/archive_requests.py [--roots ...]` writes +requests without starting the title, then `gfx2hlsl.py --pending ` translates them: + +```powershell +python -B tools/startup/archive_requests.py out/startup/shader_cache +python -B tools/startup/gfx2hlsl.py --pending out/startup/shader_cache +``` + +A startup run that traced every DirectStorage read showed where the native programs come from: +zlib streams in the shader archive that start on 64-byte boundaries and inflate to 64 KiB. Inflated +offline, those streams hold the exact bytes the runtime later records. Each program has a 36-byte +header followed by `s_inst_prefetch`, is padded in 64-byte blocks and starts on a 256-byte step, +and in every measured pipeline the vertex program directly follows the pixel program. The tool +carves every program that ends in `s_endpgm` (an all-zero block inside a program would cut it +short), pairs each pixel program with a vertex program that starts on the next 256-byte step +and writes `req_.{a,b,root}` with the runtime's key. + +What it cannot take from the archive: + +- **Root signatures.** None of the recorded root signatures occurs in the archive or the + executable; the title appears to serialize them at run time. The tool reads `req_*.root` files + from earlier runs (by default those in the cache) and writes each pair once per distinct root. + A key is only used when the title binds that pair with that root, so the extra requests cost + translation time and nothing else. +- **Pipelines the title builds from other sources.** Programs embedded in the executable as DXBC + containers are not in the archive. +- **Other pairings.** A program shared by several pipelines, or a pair that is not adjacent, is + only found by a run (`run.ps1 -Translate`). +- **Programs cut off at the end of a stream.** A zlib stream that starts on the 64-byte boundary + right after the previous one continues it, and the two are carved as one, so a program split + between them is kept. A program that reaches the end of such a joined run is skipped. + +A stream that would inflate past 1 MiB is counted as `oversized` and skipped without inflating it in +full, and a joined run stops growing at 64 MiB. A request is written as `.b`, `.root`, then `.a`; +if one part cannot be written, no `.a` and no temporary file are left and the run exits with an +error, as it does when the archive yields no pair at all. + +In one local measurement the tool joined 1,079 zlib streams into 800 runs, carved 4,982 programs +(2,730 pixel, 2,115 vertex, 137 other) and wrote 3,774 requests for 1,258 pairs and three recorded +root signatures in 22 s. Eight of the eleven pipelines that a cold run recorded were among them with +identical keys, and their translations (`.txt`, both `.hlsl` files and both `.cso` files) were +byte-identical to those from the run. The other three were two pipelines whose programs are DXBC +containers in the executable and one pipeline whose programs were not carved. + +Check with `python3 -B tests/startup_archive_requests_check.py` (ctest `startup_archive_requests`). +On a synthetic archive built from documented instruction words, each adjacent pixel/vertex pair +becomes one request per root, and the test computes the expected keys with its own copy of the +runtime's hash. Controls that write nothing: + +- a pixel program followed by a pixel program, or a vertex program without a pixel program before it; +- a vertex program one empty step after its pixel program, or after a pixel program without `s_endpgm`; +- a program without the header tag, or a pair at offsets that are not a multiple of 4; +- a pair that reaches the end of its stream, or a pair in a stream off the 64-byte grid; +- an empty or duplicate root file, an oversized stream, or a run without root signatures. + +A pair split between two consecutive zlib streams is carved whole. A blocked `.root` write leaves no +`.a` and no temporary file and fails the run, as does an archive without pairs. A second run writes +nothing new. + `run.ps1` prints the first five lines of `.out` and exits with the debugger's exit code: 2 when the process could not be created, 0 when the debugger finished its report, whatever the process did. Check with `python3 -B tests/startup_run_ps1_check.py` (ctest `startup_run_ps1`): on Windows it diff --git a/tests/startup_archive_requests_check.py b/tests/startup_archive_requests_check.py new file mode 100644 index 000000000..dc0109e7f --- /dev/null +++ b/tests/startup_archive_requests_check.py @@ -0,0 +1,206 @@ +"""archive_requests.py on a synthetic archive (pure Python, no Windows, no GPU, no title files). + +Programs follow the measured layout: a 36-byte header, s_inst_prefetch, code, s_code_end padding to +64 bytes, each on a 256-byte step of a zlib stream that starts on a 64-byte boundary. Each pixel +program directly followed by a vertex program must become one request per root, keyed exactly as +the runtime keys it; the expected keys are computed here with an independent FNV-1a, not with the +translator's function. + +Controls that must write nothing: a pixel program followed by another pixel program, a vertex +program with no pixel program before it, a vertex program one empty 256-byte step after a pixel +program, a pixel program without s_endpgm, a program without the header tag, a pair at an offset +that is not a multiple of 4, a program that runs to the end of its stream, a valid pair in a stream +that is not on a 64-byte boundary, an empty or duplicate root file, a stream that inflates past the +limit, and a run with no root signature. A pair split between two consecutive zlib streams must be +carved whole. A request whose .root cannot be written must leave no .a and no temporary file and make +the run fail. An archive without any pair must make the run fail. 65 MiB of consecutive streams +must be split into two joined runs. A second run must write nothing new. +""" +import re +import struct +import subprocess +import sys +import tempfile +import zlib +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +TOOL = ROOT / 'tools' / 'startup' / 'archive_requests.py' + +REVISION = re.search(rb'constexpr char revision\[\] = "([^"]+)";', + (ROOT / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_bytes()).group(1) +PREFETCH = bytes.fromhex('0300a0bf') # s_inst_prefetch 0x3 +CODE_END = bytes.fromhex('00009fbf') +ENDPGM = struct.pack(' [--roots ...] + +The archive stores native programs in zlib streams that start on 64-byte boundaries. Each program +begins with a 36-byte header followed by s_inst_prefetch and is padded in 64-byte blocks. In the +measured archive a pipeline's vertex program directly follows its pixel program, so each pixel +program followed by a vertex program in the same stream becomes one request (a = pixel, b = vertex, +the order the runtime records). Root signatures were not found in the archive; they are read from +existing req_*.root files (by default those already in the cache), and every pair is written once +per distinct root, so each key matches what the runtime would compute for that combination. +Translate the result with gfx2hlsl.py --pending . +""" +import argparse +import glob +import mmap +import os +import sys +import zlib + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl # noqa: E402 + +HEADER = 0x24 # bytes before s_inst_prefetch +HEADER_TAG = b'\x80\xd5' # bytes 2..3 of the first header word in every measured program +BLOCK = 0x40 +STEP = 0x100 # programs start on 256-byte steps of the stream +WINDOW = 0x20000 # compressed bytes offered to one stream; a 64 KiB stream needs far less +ENDPGM = bytes.fromhex('000081bf') # s_endpgm + + +def complete(program): + """True when the carved bytes hold an s_endpgm; an all-zero block inside a program cuts it short.""" + return any(program[at:at + 4] == ENDPGM for at in range(HEADER, len(program) - 3, 4)) + + +def stage_of(program): + """'vs', 'ps', 'other' or 'undecodable', from the export targets alone (the rule of + gfx2hlsl.classify). It reads the disassembler directly: gfx2hlsl.decode also refuses forms the + translator cannot lower, and whether a program can be translated must not decide its pairing.""" + code, at, exports = gfx2hlsl.strip_header(program), 0, [] + while at + 4 <= len(code): + try: + size, name, asm, _ = gfx2hlsl.D.decode_instruction(code, at) + except Exception: # noqa: BLE001 - any word the disassembler cannot read + return 'undecodable' + if name == 'exp': + exports.append(asm) + if name == 's_endpgm': + break + at += size + text = ' '.join(exports) + return 'vs' if 'pos' in text else 'ps' if 'mrt' in text or not text else 'other' + + +def next_step(at, program): + """Stream offset of the 256-byte step right after the program.""" + return at + -(-len(program) // STEP) * STEP + + +def is_program(data, at): + return (at >= 0 and data[at + 2:at + 4] == HEADER_TAG + and data[at + HEADER:at + HEADER + 4] == gfx2hlsl.PREFETCH) + + +def carve(data): + """Yield (offset, program) in stream order; a program that runs past the stream is skipped.""" + hit = data.find(gfx2hlsl.PREFETCH) + while hit >= 0: + at = hit - HEADER + if at % 4 == 0 and is_program(data, at): + end = at + BLOCK + # 64-byte blocks until an all-zero block or the next program on a 256-byte step + while end + BLOCK <= len(data) and any(data[end:end + BLOCK]) and not ( + (end - at) % STEP == 0 and is_program(data, end)): + end += BLOCK + # a program that reaches the end of the joined stream may be cut off, so it is skipped + if end + BLOCK <= len(data): + yield at, data[at:end] + hit = data.find(gfx2hlsl.PREFETCH, hit + 4) + + +MAX_INFLATE = 0x100000 # one measured stream inflates to 64 KiB; a larger one is refused +MAX_JOINED = 0x4000000 # bound a joined run of consecutive streams (64 MiB) + + +def chunks(view, counts): + """Yield (archive offset, end offset, inflated bytes) for each complete zlib stream on a 64-byte + boundary. A stream that inflates past MAX_INFLATE is counted as oversized and skipped.""" + at = 0 + while at < len(view) - 1: + cmf, flg = view[at], view[at + 1] + if cmf == 0x78 and (cmf << 8 | flg) % 31 == 0: + inflater = zlib.decompressobj() + window = view[at:at + WINDOW] + try: + data = inflater.decompress(window, MAX_INFLATE) + except zlib.error: + data = b'' + if data and not inflater.eof and len(data) == MAX_INFLATE: + counts['oversized'] += 1 + elif inflater.eof and data: + end = at + len(window) - len(inflater.unused_data) + yield at, end, data + at = (end + 63) & ~63 + continue + at += 64 + + +def streams(archive, counts): + """Yield (archive offset, inflated bytes); a zlib stream that starts on the 64-byte boundary right + after the previous one continues it, so a program split between the two is carved whole.""" + with open(archive, 'rb') as file: + if os.fstat(file.fileno()).st_size == 0: + return + with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as view: + start, joined, size, expected = None, [], 0, None + for at, end, data in chunks(view, counts): + if joined and (at != expected or size + len(data) > MAX_JOINED): + yield start, b''.join(joined) + joined, size = [], 0 + if not joined: + start = at + joined.append(data) + size += len(data) + expected = (end + 63) & ~63 + if joined: + yield start, b''.join(joined) + + +def read_roots(paths): + roots = [] + for path in paths: + if not os.path.exists(path): + sys.exit('root signature path not found: %s' % path) + files = sorted(glob.glob(os.path.join(path, 'req_*.root'))) if os.path.isdir(path) else [path] + for name in files: + with open(name, 'rb') as file: + blob = file.read() + if blob and blob not in roots: + roots.append(blob) + return roots + + +def write_request(cache, key, a, b, root): + """Writes .b and .root, then .a last: the scanner treats .a as the ready marker. Returns 'written', + 'existing' or 'failed'; a failed write leaves no temporary file and no .a.""" + name = os.path.join(cache, 'req_%016x' % key) + if os.path.exists(name + '.a'): + return 'existing' + for ext, blob in (('.b', b), ('.root', root), ('.a', a)): + temporary = '%s%s.%d.tmp' % (name, ext, os.getpid()) + try: + with open(temporary, 'wb') as out: + out.write(blob) + os.replace(temporary, name + ext) + except OSError as error: + print('req_%016x%s: %s' % (key, ext, error), file=sys.stderr) + if os.path.exists(temporary): + os.remove(temporary) + return 'failed' + return 'written' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('archive') + parser.add_argument('cache') + parser.add_argument('--roots', nargs='+', help='req_*.root files or directories (default: the cache)') + args = parser.parse_args() + roots = read_roots(args.roots or [args.cache]) + if not roots: + sys.exit('no root signature found: run the title once with a shader cache, or pass --roots') + os.makedirs(args.cache, exist_ok=True) + # streams counts joined runs of consecutive zlib streams + counts = dict(streams=0, oversized=0, programs=0, incomplete=0, ps=0, vs=0, other=0, undecodable=0, + pairs=0, written=0, existing=0, failed=0) + for _, data in streams(args.archive, counts): + counts['streams'] += 1 + previous = None # (stage, offset, program) of the program carved just before + for at, program in carve(data): + counts['programs'] += 1 + if not complete(program): + counts['incomplete'] += 1 + previous = None + continue + stage = stage_of(program) + counts[stage] += 1 + # directly following: the vertex program starts on the 256-byte step after the pixel program + if stage == 'vs' and previous and previous[0] == 'ps' and at == next_step(previous[1], previous[2]): + counts['pairs'] += 1 + for root in roots: + # The runtime hashes its first recorded blob (the pixel program here) first. + # pipeline_key names its parameters vs_code, ps_code; only the order matters. + key = gfx2hlsl.pipeline_key(previous[2], program, root) + counts[write_request(args.cache, key, previous[2], program, root)] += 1 + previous = (stage, at, program) + counts['roots'] = len(roots) + print(' '.join('%s=%d' % item for item in counts.items())) + if counts['failed']: + sys.exit('%d request(s) could not be written' % counts['failed']) + if not counts['pairs']: + sys.exit('no program pair found in %s' % args.archive) + + +if __name__ == '__main__': + main() From 1e4e1451e50413dcc1daa2bc47e6199a8b89d6c6 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 23:11:04 +0800 Subject: [PATCH 057/232] shader: lower startup compute formatted buffer reads --- docs/experiments.md | 34 +++++++++++ tests/startup_gfx2hlsl_compute_check.py | 81 ++++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 38 +++++++----- 3 files changed, 135 insertions(+), 18 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 93d010f01..97ccb4bf2 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13955,6 +13955,40 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_compute_' -V python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 ``` +### Startup compute formatted buffer reads + +The offline compute translator lowers `buffer_load_format_x`, `_xy`, `_xyz` and `_xyzw` using +the existing FORMAT and DST_SEL decode. The instruction must use four untouched words from a +fixed native table entry. After a branch, the descriptor must come from a local table load with +a proven root pointer. The manifest binds `srv buf table ` and requests +`udsrc descword3 `. Indexed addressing also requests `udsrc stride `. + +The dispatch caller must resolve the native descriptor to a raw SRV whose byte offset zero is +the descriptor's base. It supplies word 3 and, when requested, the byte stride from the same +descriptor snapshot. It must refuse missing or unresolved native descriptors, unsupported FORMAT +codes, reserved DST_SEL values for the components read, and descriptor features that change the +byte address, such as swizzling or adding the lane ID. The caller must establish that each +executed access is within the native descriptor range without address wrap and that every +desktop dword read is aligned and backed by the SRV. Packed reads can fetch an adjacent dword +even when only one byte is used. The lowering does not model native out-of-range results. + +Cases `L-uint` and `L-unorm` in `startup_gfx2hlsl_compute_check.py` supply different word 3 +values to the same translated shader. They compare an unaligned UINT16 pair and an UNORM8 +field, with permuted channels and both integer and floating-point forms of the constant one. +The WARP and hardware fixture uses a root SRV and passes the stride and word 3 directly. +Each dispatch checks 320 output words, including untouched sentinels. Mutations that remove +the byte offset, change a selector or replace integer one with float one must mismatch. The +pure-Python checks cover the manifest, all four load widths, a local load after a branch and +refusals for overwritten descriptor words or missing local provenance. + +On Windows build 26200.9974 with the D3D12 debug layer enabled, WARP 10.0.26100.9818 and an +NVIDIA GeForce RTX 4060 Laptop GPU with driver 32.0.16.1656 matched all 320 words in each +case. The three mutations mismatched 32, 8 and 16 words respectively on both adapters. + +```powershell +ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_compute_(controls|warp|hardware)$' -V +``` + ### First active lane at compute entry The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index a6665b8ca..4e1e0df44 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -29,6 +29,8 @@ - case H is case J's shape with a nested if inside the skipped block (s_and_saveexec, restored with s_or of the saved mask): lanes tid.x < 3 store two words, lanes 3-5 one word, the rest none. - case G reads two independently offset LDS dwords with the address in the first destination VGPR. +- cases L-uint and L-unorm use the same formatted load with native descriptor stride and word 3 supplied by the + harness. The descriptor selects unaligned UINT16 pairs or an UNORM8 field and permutes the outputs. The dispatch runs on a plain D3D12 device (the stand-in has no slot-67 path yet). The root signature is the runner's: root SRV t0 (read buffer), root UAV u0 (writable buffer) and 16 root constants at b0, which match the translation's @@ -331,6 +333,28 @@ def saveexec_fixture(): '06038abe80038bbe05030cf4000000fa7fc08cbf0783148f14000a3a9f0a0a36820a0a3482000834100034d804050000' '7fc08cbf00008abfff080c367c0000000524dcd8060000067fc08cbf0786158f1500124a83121234001074e009060480000081bf') +SOURCE_L = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v1, 1 +buffer_load_format_xyzw v[5:8], v[0:1], s[12:15], 0 idxen offen offset:2 +s_waitcnt vmcnt(0) +v_lshlrev_b32 v4, 4, v0 +buffer_store_dwordx4 v[5:8], v4, s[16:19], 0 offen +s_endpgm +""" +WORDS_L = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '8102027e' '02300ce000050380' + '703f8cbf' '84000834' '001078e004050480' '000081bf') +LOAD_L = bytes.fromhex('02300ce000050380') +L_STRIDE = 6 +L_WORD3 = { + 'L-uint': (27 << 12) | 5 | (4 << 3) | (1 << 6), # Y, X, one, zero + 'L-unorm': (1 << 12) | 1 | (4 << 3) | (7 << 6) | (5 << 9), # one, X, W, Y +} + CASES = { # name: (source, words, rsrc2, group size, group counts) 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | TGID_Y | TGID_Z | tidig(3), (2, 3, 4), (3, 2, 2)), @@ -344,6 +368,7 @@ def saveexec_fixture(): 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), + **{name: (SOURCE_L, WORDS_L, USER7, (16, 1, 1), (1, 1, 1)) for name in L_WORD3}, } # Single instructions the controls splice into case A before its store, recorded from llvm-mc 15. @@ -439,11 +464,33 @@ def input_word(i): return (0x8b02a7f1 + i * 0x413b1) & MASK # tests/compute_check.cpp fills the read buffer this way +def formatted_input(): + # Every selected R8_UNORM field is an exact endpoint, while the UINT16 halves + # are all distinct and the neighbouring bytes are nonzero. + data = bytearray(b'\x7b' * (WORDS * 4)) + for lane in range(16): + at = 6 * lane + 3 + data[at:at + 4] = bytes([255 * (lane % 2), 31 + lane, 62 + lane, 96 + lane]) + return data + + def expected(name): if name == 'I': return expected('A') out = [SENTINEL] * WORDS _, _, _, local, groups = CASES[name] + if name in L_WORD3: + data = formatted_input() + for lane in range(16): + at = 6 * lane + 3 + if name == 'L-uint': + low, high = struct.unpack_from('> ') == width + # Word 3 is overwritten in an otherwise intact native descriptor. + refused('words were rewritten', lambda: translate('L-uint', code=prefix + bytes.fromhex('80038fbe') + LOAD_L + end)) + # At a branch target, there is no local descriptor load to prove. + refused('local table load', lambda: translate('L-uint', code=prefix + bytes.fromhex('000082bf') + LOAD_L + end)) + local_load = bytes.fromhex('000082bf') + prefix + LOAD_L + end + assert 'switch ((ud3 >> 12) & 127u)' in translate('L-uint', code=local_load).hlsl_cs() + + def check_controls(): ff1 = bytes.fromhex('7e1385be') end = bytes.fromhex('000081bf') @@ -694,6 +759,7 @@ def check_controls(): check_lds() check_descriptor_scc() check_mbcnt() + check_formatted_loads() a = translate('A') # This buffer-only compute program has no typed UAV declaration or image manifest entry. assert a.uavs and a.stored_images() == {}, (a.uavs, a.stored_images()) @@ -920,9 +986,12 @@ def check_binary(llvm_mc): 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), 'g-overlap': ('G', 'v7 = lds[(a + 144u)', 'v7 = lds[(v6 + 144u)'), + 'l-byte-offset': ('L-uint', 'a = v0 * ud2 + v1 + 2;', 'a = v0 * ud2 + 2;'), + 'l-swizzle': ('L-unorm', 'v6 = ((ud3 >> 3)', 'v6 = ((0u >> 3)'), + 'l-integer-one': ('L-uint', 'c1 = w >> 16; c2 = 0u; c3 = 1u; one = 1u;', 'c1 = w >> 16; c2 = 0u; c3 = 1u;'), } -# First bad word for the masked bit-count and paired LDS read controls. +# First bad word for controls with a pinned mismatch. CONTROL_MISMATCH = { 'd-mask': 'word=8 expected=00000008 actual=00000009', 'd-whole-mask': 'word=0 expected=00000007 actual=00000011', @@ -932,6 +1001,9 @@ def check_binary(llvm_mc): 'd-exec': 'word=2 expected=ffffffff actual=00000000', 'g-swapped-offsets': 'word=0 expected=00000004 actual=00000000', 'g-overlap': 'word=1 expected=00000000 actual=00000004', + 'l-byte-offset': 'word=0 expected=0000603e actual=00003e1f', + 'l-swizzle': 'word=5 expected=3f800000 actual=00000000', + 'l-integer-one': 'word=2 expected=00000001 actual=3f800000', } @@ -950,8 +1022,12 @@ def run_case(name, dxc, runner, adapter, directory, control=None): subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) groups = CASES[name][4] constants = [KEY, STRIDE] + [0] * 14 + source = b'' + if name in L_WORD3: + constants[2:4] = [L_STRIDE, L_WORD3[name]] + source = formatted_input() case.write_bytes(struct.pack('= 4 and struct.unpack_from(' 255: + raise Unsupported('formatted buffer load destination %s for %d components' % (ops[0], count)) # FORMAT and DST_SEL are read from the table word, so word 3 must still be the loaded one. r = reg_range(ops[2]) first = self.sym.get(r[1]) if r else None - if not r or r[2] - r[1] != 3 or not first or first[0] != 'desc' or any( + if not r or r[0] != 's' or r[2] - r[1] != 3 or not first or first[0] != 'desc' or any( self.sym.get(r[1] + i) != ('desc', first[1], first[2], first[3] + i) for i in range(4)): raise Unsupported('formatted buffer load through a descriptor whose words were rewritten') if first[1][0] != 'table': @@ -3335,6 +3336,11 @@ def op_buffer_load_format_xy(self, ops, mods): def op_buffer_load_format_xyz(self, ops, mods): self.mubuf_format(ops, mods, 3) + def op_buffer_load_format_xyzw(self, ops, mods): + if self.kind != 'cs': + raise Unsupported('buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL') + self.mubuf_format(ops, mods, 4) + def op_tbuffer_load_format_x(self, ops, mods): self.tbuffer(ops, mods, 1) From 7092683a9a9bfa8952e5df415b5ae0ee93220fc9 Mon Sep 17 00:00:00 2001 From: JVProg <100954822+JVProg@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:12:05 +0100 Subject: [PATCH 058/232] tests: open the vm_translation_check section heaps from a mapped view (#2393) OpenExistingHeapFromFileMapping can leave the section committed after the process exits (#2234). Open the two 64 KiB section heaps of the range scenario with OpenExistingHeapFromAddress on the mapped view instead. The destructor already releases the heap before it unmaps the view. Refs #2234 Co-authored-by: Claude Sonnet 5.5 --- docs/experiments.md | 2 +- tests/vm_translation_check.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 93d010f01..efca64a67 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9047,7 +9047,7 @@ A static read of the main executable shows that, after device creation, it keeps | `vm_translation_shared_range` | No device. A and B are one range, so both directions are the identity inside it, and addresses just outside pass through. | | `vm_translation_device_warp`, `vm_translation_device_hardware` | A reserve-only range and an address inside the allocation both fail to open as a heap. A dispatch addressed by `p - A + B` reads 1,024 CPU-written words and writes 1,024 words the CPU reads back. A second buffer placed at `+0x200000` reports GPU address `B + 0x200000`. That address translates to `A + 0x200000`, and GPU writes through it are visible there. An unrelated committed buffer's GPU address lies outside `[B, B + size)` and passes through. A B shifted by 64 KiB misses all 1,024 destination words. Skips (77) without the adapter or `ID3D12Device3`. | | `vm_translation_sequence_warp`, `vm_translation_sequence_hardware` | Before any device, `D3D12ConfigureVirtualMemoryX` refuses a null block and blocks with the DWORD set to 0, 1, 2, 5, `0x80000003` or `0xFFFFFFFF`, or with a non-zero byte at `+0`, `+3`, `+8` or `+31`. It accepts the 4 sample, then refuses a second call with 4 or 3. The 32-byte block and 16 guard bytes on each side are unchanged after every call. `D3D12XboxCreateDevice` creates the device on the same adapter as the device cases. On that adapter it refuses a parameter block (`E_INVALIDARG`) and another interface (`E_NOINTERFACE`), with the output cleared. Configuration after the device is refused. The first DIRECT queue with the default description is created. Then queues with an unknown type, an unknown priority or an absent node are refused without returning a queue, and the device is not removed. The device-case checks then run on that first queue. The adapter's per-resource and per-process GPU virtual address bits are printed and not checked. Skips (77) as the device cases. | -| `vm_translation_range_{warp,hardware}` | `d3d12_xs_range::create` reserves 32 GiB in windows of at most 4 GiB. Spans across a window edge or past the end have no GPU address. An unmapped tile reads zero. The test maps three tiles on the first DIRECT queue: the range start, the first tile of the second window, and the last tile. It copies distinct words into each from a 64 KiB pagefile section, and a dispatch reads them back at the range's GPU address. One tile further reads the unmapped neighbour, and staging writes after the copy are not seen. After the queue is idle, `Close()` leaves an empty range. Before the range checks, a test-owned reserved buffer must read back a copied tile through a dispatch; otherwise the case skips (77). | +| `vm_translation_range_{warp,hardware}` | `d3d12_xs_range::create` reserves 32 GiB in windows of at most 4 GiB. Spans across a window edge or past the end have no GPU address. An unmapped tile reads zero. The test maps three tiles on the first DIRECT queue: the range start, the first tile of the second window, and the last tile. It copies distinct words into each from a 64 KiB pagefile section, and a dispatch reads them back at the range's GPU address. The section heaps are opened with `OpenExistingHeapFromAddress` on the mapped view, because `OpenExistingHeapFromFileMapping` can leave a section committed after exit (#2234). One tile further reads the unmapped neighbour, and staging writes after the copy are not seen. After the queue is idle, `Close()` leaves an empty range. Before the range checks, a test-owned reserved buffer must read back a copied tile through a dispatch; otherwise the case skips (77). | | `vm_translation_range_lifetime_{warp,hardware}` | The test registers an `ID3DDestructionNotifier` callback on each device. First, a device created through `d3d12_xs.dll` after the 4 sample carries no range (`DXGI_ERROR_NOT_FOUND`), and its last ordinary release destroys it. Next, a range is created on a fresh desktop device. Releasing the device's last caller reference while the range is open leaves one reference per window and no callback. Releasing the range then destroys the device. In a second round, a thread reads the range's GPU address, window count and first window while the main thread calls `Close()`. Every read matches the open range or the empty one. A second `Close()` does nothing, and the device's last release then returns 0 with one callback. | | `vm_translation_range_partial_{warp,hardware}` | `d3d12_xs_range::create` against a desktop device, with window creation failing at window 1 or at window 3. It returns the failing `E_OUTOFMEMORY` after that many calls and no range, and the device's last release destroys it, so the windows created before the failure were released. | diff --git a/tests/vm_translation_check.cpp b/tests/vm_translation_check.cpp index c72af6bc7..9737c9427 100644 --- a/tests/vm_translation_check.cpp +++ b/tests/vm_translation_check.cpp @@ -519,7 +519,9 @@ struct SectionBuffer { section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, static_cast(tile), nullptr); if (section) view = static_cast(MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, tile)); - if (!view || FAILED(device->OpenExistingHeapFromFileMapping(section, IID_PPV_ARGS(&heap)))) return false; + // OpenExistingHeapFromFileMapping can leave the section committed after exit (#2234), so the heap + // is opened on the mapped view. The destructor releases the heap before it unmaps the view. + if (!view || FAILED(device->OpenExistingHeapFromAddress(view, IID_PPV_ARGS(&heap)))) return false; const auto desc = buffer_desc(tile, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); return SUCCEEDED(device->CreatePlacedResource(heap.Get(), 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, From 4d6e395c7fa9885b492c05d02ee4fe444fa198a7 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Wed, 25 Nov 2026 23:13:24 +0800 Subject: [PATCH 059/232] tooling: index local compute container candidates --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 2 + README.md | 1 + docs/experiments.md | 26 +++++ tests/compute_container_index_check.py | 123 ++++++++++++++++++++++++ tools/compute_container_index.py | 125 +++++++++++++++++++++++++ 6 files changed, 278 insertions(+) create mode 100644 tests/compute_container_index_check.py create mode 100644 tools/compute_container_index.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 9d2e61a54..5ffb9fa47 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -232,6 +232,7 @@ jobs: tests/startup_gfx2hlsl_smem_offset_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_compute_request_offline_check.py \ + tests/compute_container_index_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f71669e2..c271339a2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3662,6 +3662,8 @@ if(EXISTS "${INTAKE_PYTHON}") # Device slot 67 compute requests offline: key vector, --pending and --refusals (pure Python). add_test(NAME startup_compute_request_offline COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_offline_check.py") + add_test(NAME compute_container_index COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/compute_container_index_check.py") # Partial colour exports carry their channel mask to the manifest; compressed exports of whole pairs lower (#1674). add_test(NAME startup_gfx2hlsl_export_mask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_export_mask_check.py") diff --git a/README.md b/README.md index b26f710bb..a7abb29df 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 coarse-gradient pixel sampling | Lower [four 2D coarse-gradient forms](docs/experiments.md#gfx1030-2d-explicit-and-coarse-gradient-sampling) with statically known finite slopes. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_coarse_gradient_' -V` | | gfx1030 explicit-gradient pixel sampling | Lower [four 2D gradient sample forms](docs/experiments.md#offline-pixel-shader-recompilation), including packed binary16 slopes and immediate offsets. | `ctest --preset dev --no-tests=error -R '^pixel_aot_sample_gradient_' -V` | | Shader census | [Distinguish archive records, header digests and cache-index entries](docs/experiments.md#reporting-shader-census-populations) before choosing a coverage denominator. | `ctest --preset dev --no-tests=error -R "^shader_metadata_census$" -V` | +| Compute container index | [Correlate local slot 67 requests with archive candidates](docs/experiments.md#local-compute-container-index) and report repeated records and ambiguous matches. | `python -B tests/compute_container_index_check.py` | | Shader effect metadata | Inventory the [candidate programs for a named SGD5 effect](docs/experiments.md#candidate-programs-for-a-named-sgd5-effect) using independently located archive ranges. | `ctest --preset dev --no-tests=error -R "^sgd5_effect_candidates$" -V` | | gfx1030 image LOD query | Lower [clamped and raw 2D LOD queries](docs/experiments.md#gfx1030-2d-image-lod-queries) for `image_get_lod` in pixel shaders. | `ctest --preset dev --no-tests=error -R '^pixel_aot_get_lod_'` | | Pipeline readiness | Join explicit pipeline references to the native shader manifest and optionally probe pixel and mesh lowering. [Inputs and WARP control](docs/experiments.md#pipeline-readiness-from-shader-manifests) | `ctest --preset dev -R '^pso_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index a3c2954a6..13b869de2 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3995,6 +3995,32 @@ python3 -B tests/startup_ngg_slice_check.py python3 -B tests/startup_ngg_slice_check.py binary llvm-mc-15 ``` +## Local compute container index + +`tools/compute_container_index.py` joins the digest in a recognized slot 67 +`.data` record with the `HASH` digest of a framed compute DXIL archive record. +The archive inventory checks compressed record framing, the container part table +and the DXIL program header. The CLI reads local inputs and writes JSON to stdout. +The SHA-256 of the entire decoded container identifies each candidate. Records with identical +SHA-256 appear once with a `records` count. A request with multiple distinct +SHA-256 values is reported as `conflict` and retains all candidates. The tool +counts missing `HASH` parts, bad lengths and unsupported flag bits. It accepts +flag values 0 and 1 and reports the value for each candidate. Flag 1 indicates a +digest that includes source information. [DXC HASH definition](https://github.com/microsoft/DirectXShaderCompiler/blob/main/include/dxc/DxilContainer/DxilContainer.h#L38-L46) + +```powershell +python -B tools/compute_container_index.py "game-files/" "out//cache" --trace "out//trace/trap.log" > out/compute-container-index.json +python -B tests/compute_container_index_check.py +``` + +With `--trace`, direct and indirect dispatch rows select request keys, including +keys missing from the cache. Their counts describe logged calls, which may have +used a placeholder pipeline. Omit `--trace` to index all `.c67` request keys. +The join establishes candidate metadata agreement. Native code equivalence, +resource bindings and GPU execution require separate evidence. The synthetic +fixture covers repeats, conflicts, absent and malformed data, invalid container +framing and flags, a non-compute record, and trace selection. + ## Compute UAV stores from a native container `tools/compute_store_aot.py` accepts a local extracted DXBC compute container. It checks the stage in both the DXIL and PSV0 parts, the group dimensions, the FSSM v0x101 extent and termination, then decodes the gfx1013 instructions with LLVM. The store profile translates one or more non-overlapping raw UAV stores of one to four known 32-bit constant words per invocation, including constants loaded via `s_mov_b32`, `s_movk_i32`, and `v_mov_b32` register copies, along with `s_clause` hints and combined `lgkmcnt(0)`/`vmcnt(0)` waits. A test binding maps one four-word descriptor to u0. Its table pointer has a known low register and a zero high word. Scalar loads must complete before use. For an indexed store the caller also supplies the group-X register and byte stride, v0 carries local X, and the decoded shift and add must produce the dispatch-thread index. The tests bind in-range raw buffers with no swizzle, format conversion or out-of-range accesses. The original descriptor contents and dispatch configuration require separate evidence. diff --git a/tests/compute_container_index_check.py b/tests/compute_container_index_check.py new file mode 100644 index 000000000..9b837f881 --- /dev/null +++ b/tests/compute_container_index_check.py @@ -0,0 +1,123 @@ +"""Exercise the local compute index CLI with source-built framing controls.""" + +import hashlib +import json +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +import zlib + + +TOOL = Path(__file__).resolve().parents[1] / "tools" / "compute_container_index.py" +DIGESTS = [bytes([index]) * 16 for index in range(1, 8)] + + +def container(hash_part, *, stage=5, magic=b"DXIL"): + program = struct.pack("= 40 and data[:4] == b"\x03\x04\0\0" + and struct.unpack_from(" Date: Thu, 26 Nov 2026 00:07:26 +0800 Subject: [PATCH 060/232] shader: cover the reported vector multiply-high literal --- docs/experiments.md | 9 +++++++++ tests/startup_gfx2hlsl_mul_hi_check.py | 14 +++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index b50a29d1f..3b841724f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7470,6 +7470,15 @@ symbolic descriptors and reserved scalar encodings stay refused; an SGPR that held a compare mask may be overwritten and loses its mask mark. `s_mul_hi_i32` is still refused by name. +**Vector unsigned multiply-high.** The startup shader translator lowers +`v_mul_hi_u32` to the same halfword-product helper as `s_mul_hi_u32`. +Synthetic VOP3A instructions cover register inputs and the literal +`0xaaaaaaab`. FXC and DXC draws check the high word against a 64-bit reference. +The controls also detect an omitted carry or a replacement with the low word. +Build `offscreen_check`, then run +`ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_mul_hi_' -V`. +[Refs #1792](https://github.com/R0Y00/Xbox2Windows/issues/1792) + **Scalar bit tests.** Startup translation sets SCC for `s_bitcmp0_b32` and `s_bitcmp1_b32` by comparing the selected bit of the first word to zero or one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked diff --git a/tests/startup_gfx2hlsl_mul_hi_check.py b/tests/startup_gfx2hlsl_mul_hi_check.py index d9da8d2c6..dfa63187a 100644 --- a/tests/startup_gfx2hlsl_mul_hi_check.py +++ b/tests/startup_gfx2hlsl_mul_hi_check.py @@ -49,6 +49,10 @@ ) PS_WORDS = PRE_WORDS + BODY_WORDS + POST_WORDS +# VOP3A uses source selector 255 followed by the literal DWORD (#1792). +LITERAL_SOURCE = 'v_mul_hi_u32 v12, v0, 0xaaaaaaab\n' +LITERAL_WORDS = bytes.fromhex('0c006ad500ff0100abaaaaaa') + SPECIAL = ( 0, 1, 2, 3, 0xffff, 0x10000, 0x10001, 0x0001ffff, 0x7fffffff, 0x80000000, 0x80000001, 0xdeadbeef, 0xcafebabe, 0x9e3779b9, 0x85ebca6b, 0xffff0000, 0xffff0001, 0xfffffffe, MASK, @@ -107,13 +111,19 @@ def run(a, b): return ret_e.run(env)[0] return run - + def controls(): _, text = translate() found = re.findall(r'^\s*v(1[2-5]) = mul_hi_u32\(v(\d+), v(\d+)\);$', text, re.M) check('v_mul_hi_u32: four lane calls emitted', found == [('12', '0', '4'), ('13', '1', '5'), ('14', '2', '6'), ('15', '3', '7')]) + literal_ps = PRE_WORDS + LITERAL_WORDS + BODY_WORDS[8:] + POST_WORDS + literal_text = G.Pipeline(vs_words([(0, 0, 0)] * 4), literal_ps, root_blob()).hlsl_ps() + literal_match = re.search(r'v12 = mul_hi_u32\(v0, (0[xX][0-9a-fA-F]+|[0-9]+)u\);', literal_text) + check('v_mul_hi_u32: encoded literal reaches the helper', + literal_match is not None and int(literal_match[1], 0) == 0xaaaaaaab) + helper = eval_emitted_helper(text) mismatch = next(((a, b, helper(a, b), ref_mul_hi_u32(a, b)) for a, b in GRID if helper(a, b) != ref_mul_hi_u32(a, b)), None) @@ -163,6 +173,8 @@ def check_binary(llvm_mc): built = assemble(llvm_mc, BODY_SOURCE) if built != BODY_WORDS: raise AssertionError('v_mul_hi_u32: assembled %s, recorded %s' % (built.hex(), BODY_WORDS.hex())) + if assemble(llvm_mc, LITERAL_SOURCE) != LITERAL_WORDS: + raise AssertionError('literal v_mul_hi_u32 fixture differs from llvm-mc') for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): if assemble(llvm_mc, source) != words: raise AssertionError('%s fixture differs from llvm-mc' % name) From 10acafe6e99fcc8e6cca12de6f0ca212793e6c7b Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 00:54:29 +0800 Subject: [PATCH 061/232] xmem: pin single-page records in tracked CPU mappings --- CMakeLists.txt | 1 + docs/experiments.md | 10 +++++++- src/xmem_mapped_pages.cpp | 34 ++++++++++++++++++-------- src/xmem_section_lease.h | 5 +++- tests/xmem_section_lease_check.cpp | 39 ++++++++++++++++++++++++++++-- 5 files changed, 75 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 09ad6dc25..fd7edbca5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -313,6 +313,7 @@ target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) target_link_libraries(xmem_section_lease_check PRIVATE d3d12 dxgi) add_dependencies(xmem_section_lease_check xmem_shim) +add_test(NAME xmem_section_lease_single_page COMMAND xmem_section_lease_check single-page "$") foreach(adapter warp hardware) add_test(NAME xmem_section_lease_${adapter} COMMAND xmem_section_lease_check ${adapter} "$") set_tests_properties(xmem_section_lease_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) diff --git a/docs/experiments.md b/docs/experiments.md index 222b1ee7a..820dd01d1 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9166,7 +9166,15 @@ Run `cmake --build --preset dev --target unified_buffer_paths_check` and `ctest #### A lease for committed XMem section pages (#1914) -The in-process lease API requires version 1 and the exact output structure size. It clears a correctly sized output before checking the request. It checks the mirrored and CPU mappings under the XMem lock, accepts only committed pages backed by consecutive slots of one section, and duplicates the section handle within the caller's process. The caller maps the selected span with `MapViewOfFile` and opens that view with `OpenExistingHeapFromAddress`. The returned byte offset identifies the requested start inside the placed buffer. The lease holds the slots until the caller releases it after its last GPU fence. Freeing the original title grant is allowed after unmapping. Its slots stay out of the reuse pool until the lease retires. +Version 2 of the same three exports pins a byte range within one committed 64 KiB +page. It also accepts ordinary CPU addresses tracked by XMem. Callers can read +late writes through the returned section and check the current mapping against +the pin before consuming the data. An address remapped to another grant fails +that check while the original pinned bytes remain readable. Acquire, match and +release take the same version. Run the CPU-only record and remap check with +`ctest --preset release --no-tests=error -R '^xmem_section_lease_single_page$'`. + +The version 1 mirrored-range API requires the exact output structure size. It clears a correctly sized output before checking the request. It checks the mirrored and CPU mappings under the XMem lock, accepts only committed pages backed by consecutive slots of one section, and duplicates the section handle within the caller's process. The caller maps the selected span with `MapViewOfFile` and opens that view with `OpenExistingHeapFromAddress`. The returned byte offset identifies the requested start inside the placed buffer. The lease holds the slots until the caller releases it after its last GPU fence. Freeing the original title grant is allowed after unmapping. Its slots stay out of the reuse pool until the lease retires. The fixture maps two pages from the shim's `SEC_RESERVE` pool and copies a 4 KiB span across their boundary. A GPU write appears in both title views. A second copy sees the original pages' late CPU updates after the title frees and remaps the same virtual addresses. Readback compares all 4,096 bytes and checks the replacement pages retain their own data. A later allocation gets the retired slot and sees zeroes. The checks also refuse holes, reversed section order, a CPU address passed to the mirrored address API, an invalid output size and a repeated release. diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index 07877c7e5..756741898 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -35,6 +35,7 @@ struct Backing { using Slot = std::pair; struct SlotPin { unsigned references{}; bool retired{}; }; struct SectionLease { + UINT version; SIZE_T first_byte; SIZE_T length; std::vector slots; @@ -231,6 +232,21 @@ Backing* backing_at(ULONG_PTR address) return backing == memory.backings.end() ? nullptr : &backing->second; } +bool valid_lease_range(UINT version, ULONG_PTR address, SIZE_T length) +{ + if (version == x2w_xmem_section_lease_version) return mirrored_range(address, length); + return version == x2w_xmem_single_page_lease_version && length && + length <= page_bytes - (address % page_bytes) && address <= UINTPTR_MAX - (length - 1); +} + +const Backing* lease_backing(UINT version, ULONG_PTR page) +{ + if (version == x2w_xmem_section_lease_version || mirrored_range(page, page_bytes)) + return mirrored_backing(page); + const auto* backing = backing_at(page); + return backing && backing->committed ? backing : nullptr; +} + LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -1370,11 +1386,10 @@ extern "C" BOOL WINAPI x2w_xmem_lease_section(UINT version, ULONG_PTR address, S { if (!out || bytes != sizeof(*out)) return FALSE; *out = {}; - if (version != x2w_xmem_section_lease_version) return FALSE; constexpr SIZE_T max_pages = 64; if (length > max_pages * page_bytes) return FALSE; const std::lock_guard guard(memory.mutex); - if (!memory.next_lease || !mirrored_range(address, length)) return FALSE; + if (!memory.next_lease || !valid_lease_range(version, address, length)) return FALSE; const auto first = address & ~(page_bytes - 1); const auto first_byte = address - first; const auto count = (first_byte + length + page_bytes - 1) / page_bytes; @@ -1386,7 +1401,7 @@ extern "C" BOOL WINAPI x2w_xmem_lease_section(UINT version, ULONG_PTR address, S selected.reserve(count); for (SIZE_T i = 0; i < count; ++i) { const auto page = first + i * page_bytes; - const auto* slot = mirrored_backing(page); + const auto* slot = lease_backing(version, page); if (!slot) return FALSE; if (selected.empty()) section = slot->section; @@ -1403,7 +1418,7 @@ extern "C" BOOL WINAPI x2w_xmem_lease_section(UINT version, ULONG_PTR address, S ++pinned; } const auto lease = memory.next_lease; - memory.leases.emplace(lease, SectionLease{first_byte, length, selected}); + memory.leases.emplace(lease, SectionLease{version, first_byte, length, selected}); ++memory.next_lease; *out = {duplicate, lease, selected.front().second, count * page_bytes, first_byte}; return TRUE; @@ -1417,11 +1432,11 @@ extern "C" BOOL WINAPI x2w_xmem_lease_section(UINT version, ULONG_PTR address, S extern "C" BOOL WINAPI x2w_xmem_match_section(UINT version, ULONG64 lease, SIZE_T byte_offset, ULONG_PTR address, SIZE_T length) { - if (version != x2w_xmem_section_lease_version || byte_offset % page_bytes != address % page_bytes) - return FALSE; + if (byte_offset % page_bytes != address % page_bytes) return FALSE; const std::lock_guard guard(memory.mutex); const auto found = memory.leases.find(lease); - if (found == memory.leases.end() || !mirrored_range(address, length)) return FALSE; + if (found == memory.leases.end() || found->second.version != version || + !valid_lease_range(version, address, length)) return FALSE; const auto& pin = found->second; if (byte_offset < pin.first_byte || byte_offset - pin.first_byte >= pin.length || length > pin.length - (byte_offset - pin.first_byte)) return FALSE; @@ -1429,7 +1444,7 @@ extern "C" BOOL WINAPI x2w_xmem_match_section(UINT version, ULONG64 lease, SIZE_ const SIZE_T last_slot = (byte_offset + length - 1) / page_bytes; const auto first_page = address & ~(page_bytes - 1); for (SIZE_T slot = first_slot; slot <= last_slot; ++slot) { - const auto* backing = mirrored_backing(first_page + (slot - first_slot) * page_bytes); + const auto* backing = lease_backing(version, first_page + (slot - first_slot) * page_bytes); if (!backing || pin.slots[slot] != Slot{backing->slab, backing->offset}) return FALSE; } return TRUE; @@ -1437,10 +1452,9 @@ extern "C" BOOL WINAPI x2w_xmem_match_section(UINT version, ULONG64 lease, SIZE_ extern "C" BOOL WINAPI x2w_xmem_release_section(UINT version, ULONG64 lease) { - if (version != x2w_xmem_section_lease_version) return FALSE; const std::lock_guard guard(memory.mutex); const auto found = memory.leases.find(lease); - if (found == memory.leases.end()) return FALSE; + if (found == memory.leases.end() || found->second.version != version) return FALSE; for (const auto& slot : found->second.slots) unpin_slot(slot); memory.leases.erase(found); return TRUE; diff --git a/src/xmem_section_lease.h b/src/xmem_section_lease.h index f1b7ccee6..eaaa852b9 100644 --- a/src/xmem_section_lease.h +++ b/src/xmem_section_lease.h @@ -4,6 +4,9 @@ #include inline constexpr std::uint32_t x2w_xmem_section_lease_version = 1; +// A bounded record within one committed XMem page, including an ordinary CPU +// view. The caller uses the same version to acquire, match and release the pin. +inline constexpr std::uint32_t x2w_xmem_single_page_lease_version = 2; // The caller closes section after importing it. It retains the lease through // its last submitted GPU access and releases it after the completion fence. @@ -16,7 +19,7 @@ struct X2WXMemSectionLease { }; static_assert(sizeof(X2WXMemSectionLease) == 40); -// Checks the live mirrored mappings against a pinned span. byte_offset is +// Checks the live mappings for the chosen ABI against a pinned span. byte_offset is // relative to the mapped section window, so the first requested byte is // first_byte. The match covers only bytes requested when the lease was taken. using X2WXMemMatchSection = BOOL (WINAPI*)(UINT version, ULONG64 lease, SIZE_T byte_offset, diff --git a/tests/xmem_section_lease_check.cpp b/tests/xmem_section_lease_check.cpp index 0be64fc4d..3124577fc 100644 --- a/tests/xmem_section_lease_check.cpp +++ b/tests/xmem_section_lease_check.cpp @@ -33,8 +33,9 @@ int wmain(int argc, wchar_t** argv) try { const bool page_batch = argc == 4 && std::wcscmp(argv[3], L"page-batch") == 0; const bool mesh = argc == 4 && std::wcscmp(argv[3], L"mesh") == 0; const bool vertex = argc == 4 && std::wcscmp(argv[3], L"vertex") == 0; + const bool single_page = argc == 3 && std::wcscmp(argv[1], L"single-page") == 0; if ((argc != 3 && !mesh && !vertex && !page_batch) || - (std::wcscmp(argv[1], L"warp") && std::wcscmp(argv[1], L"hardware"))) return 2; + (!single_page && std::wcscmp(argv[1], L"warp") && std::wcscmp(argv[1], L"hardware"))) return 2; const bool warp = std::wcscmp(argv[1], L"warp") == 0; SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", "1"); @@ -53,6 +54,40 @@ int wmain(int argc, wchar_t** argv) try { }; const auto release = [unpin](ULONG64 id) { return unpin(x2w_xmem_section_lease_version, id); }; constexpr UINT64 window = UINT64{16} << 30, page = 65536; + if (single_page) { + constexpr auto version = x2w_xmem_single_page_lease_version; + constexpr SIZE_T size = 12, offset = page - size; + void* base = reserve(nullptr, page, 0x20402000, 0x21, PAGE_READWRITE); + require(base != nullptr, "reserve ordinary CPU window"); + const auto address = reinterpret_cast(base) + offset; + ULONG_PTR count = 1, original{}, replacement{}, hole = 0; + require(alloc(0x280, &count, &original) && count == 1 && map(&base, 1, &original), "map original page"); + X2WXMemSectionLease old{}, refused{}; + require(!acquire(address, size, &refused, sizeof(refused)), "mirror ABI rejects ordinary address"); + require(!pin(version, address, size + 1, &refused, sizeof(refused)), "single-page ABI rejects crossing"); + require(pin(version, address, size, &old, sizeof(old)) && old.first_byte == offset && + old.window_bytes == page, "pin bounded record ending at page boundary"); + require(match_section(version, old.id, offset, address, size) && + !match_section(version, old.id, offset - 1, address - 1, size) && + !match_section(version, old.id, offset, address, 0) && + !match_section(x2w_xmem_section_lease_version, old.id, offset, address, size) && + !release(old.id), "lease respects its byte bounds and ABI"); + auto* view = static_cast(MapViewOfFile(old.section, FILE_MAP_READ, + static_cast(old.section_offset >> 32), static_cast(old.section_offset), page)); + require(view != nullptr && CloseHandle(old.section), "open independent read view"); + std::memset(reinterpret_cast(address), 0x51, size); + require(map(&base, 1, &hole) && !match_section(version, old.id, offset, address, size) && + !pin(version, address, size, &refused, sizeof(refused)), "unmapped address is refused"); + require(free_pages(1, &original) && alloc(0x280, &count, &replacement) && + count == 1 && map(&base, 1, &replacement), "replace grant at same address"); + std::memset(reinterpret_cast(address), 0xb2, size); + require(!match_section(version, old.id, offset, address, size), "replacement grant does not match"); + for (SIZE_T i = 0; i < size; ++i) require(view[offset + i] == 0x51, "pin retains original bytes"); + require(UnmapViewOfFile(view) && unpin(version, old.id) && !unpin(version, old.id), "retire pin once"); + require(map(&base, 1, &hole) && free_pages(1, &replacement), "release replacement page"); + std::puts("Ordinary CPU record stayed pinned across unmap, grant retirement and same-address remap."); + return 0; + } constexpr UINT64 first_byte = 0xf800, bytes = 4096; auto* const cpu = static_cast(reserve(nullptr, window, 0x20402000, 0x21, 4)); const auto mirror = reinterpret_cast(reserve(nullptr, window, 0x20402000, 3, 0x801)); @@ -79,7 +114,7 @@ int wmain(int argc, wchar_t** argv) try { require(!acquire(mirror + first_byte, bytes, &gap, sizeof(gap)-1), "reject a malformed output"); gap.id = 123; gap.window_bytes = 456; - require(!pin(x2w_xmem_section_lease_version + 1, mirror + first_byte, bytes, &gap, sizeof(gap)) && + require(!pin(UINT_MAX, mirror + first_byte, bytes, &gap, sizeof(gap)) && !gap.section && !gap.id && !gap.section_offset && !gap.window_bytes && !gap.first_byte, "reject the wrong version and clear the valid output structure"); require(!unpin(x2w_xmem_section_lease_version + 1, lease.id), "wrong-version release keeps the lease"); From 38468ab8e6e4a4b2cb1650cb650e766b0e199f81 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 01:11:33 +0800 Subject: [PATCH 062/232] tests: honor the hardware adapter filter in startup stream fixtures (#2424) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 4 ++ docs/startup-runtime.md | 4 +- tests/startup_draw_depth_target.cpp | 24 +--------- tests/startup_slot57_depth.cpp | 24 +--------- tests/startup_stream_depth.cpp | 24 +--------- tests/startup_stream_rasterizer.cpp | 24 +--------- tests/startup_stream_rasterizer_check.py | 12 +++++ tests/startup_stream_setup.cpp | 59 ++++++++++++++++-------- tests/startup_stream_setup.h | 1 + 9 files changed, 64 insertions(+), 112 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index fb2018912..d7c2b8485 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3481,6 +3481,10 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_compute_translate_e2e_wrong_group_${adapter} PROPERTIES PASS_REGULAR_EXPRESSION "control wrong-group: rejected at word=[0-9]+ ") endforeach() + add_test(NAME startup_stream_adapter_filter COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_rasterizer_check.py" + "$" hardware filter) + set_tests_properties(startup_stream_adapter_filter PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_stream_draw_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_draw_check.py" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 043429b30..173a2d214 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2089,7 +2089,9 @@ These are measured on one executable; treat them as hypotheses for others. clip. `RASTERIZER1` stores depth bias as a float; a value that is not an integer in the desktop range refuses the pipeline. Run `ctest --preset release --no-tests=error -R "^startup_stream_rasterizer_"` to check all 32 pixels for front and back culling, with each front-face winding and both stream - subobject types. + subobject types. On a multi-GPU system, set `XBOX2WINDOWS_ADAPTER` to a case-insensitive substring of + the adapter description to select hardware for the startup stream, rasterizer and depth fixtures. + An unmatched hardware selector fails the test. The WARP fixtures always select the software adapter. The ignore control expects the no-cull readback and fails. Stream depth-stencil state is already applied on this path. Geometry, hull, domain and compute stages remain open. - Translated draws use the bound typed RTV formats to request colour-export variants. The diff --git a/tests/startup_draw_depth_target.cpp b/tests/startup_draw_depth_target.cpp index a80e28570..a2a8bf1a8 100644 --- a/tests/startup_draw_depth_target.cpp +++ b/tests/startup_draw_depth_target.cpp @@ -71,28 +71,6 @@ bool read_bytes(const char* path, std::vector& out) return !out.empty(); } -int pick_adapter(bool hardware, ComPtr& adapter) -{ - ComPtr factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; - if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; - ComPtr factory6; - if (FAILED(factory.As(&factory6))) return 77; - for (UINT n = 0;; ++n) { - ComPtr candidate; - const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) return 77; - if (FAILED(hr)) return 4; - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(candidate->GetDesc1(&desc))) return 4; - if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && - SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { - adapter = candidate; - return 0; - } - } -} - void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, const std::vector& ps) { D3D12_DEPTH_STENCIL_DESC less{}; @@ -223,7 +201,7 @@ int main(int argc, char** argv) const std::string prefix = argv[8]; ComPtr adapter; - if (const int rc = pick_adapter(hardware, adapter)) return rc; + if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; { DXGI_ADAPTER_DESC desc{}; LARGE_INTEGER driver{}; diff --git a/tests/startup_slot57_depth.cpp b/tests/startup_slot57_depth.cpp index e25853ffe..0602dea75 100644 --- a/tests/startup_slot57_depth.cpp +++ b/tests/startup_slot57_depth.cpp @@ -56,28 +56,6 @@ bool read_bytes(const char* path, std::vector& out) return !out.empty(); } -int pick_adapter(bool hardware, ComPtr& adapter) -{ - ComPtr factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; - if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; - ComPtr factory6; - if (FAILED(factory.As(&factory6))) return 77; - for (UINT n = 0;; ++n) { - ComPtr candidate; - const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) return 77; - if (FAILED(hr)) return 4; - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(candidate->GetDesc1(&desc))) return 4; - if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && - SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { - adapter = candidate; - return 0; - } - } -} - // A slot 57 description as the stand-in reads it (see tests/startup_stream_consumer.cpp): 64-bit words 0 (root // signature), 1-2 (state block A and its size), 5-6 and 9-10 (the two shaders). void* make_slot57(void* device, void* root, const std::vector& vs, const std::vector& ps, const Words& w) @@ -208,7 +186,7 @@ int main(int argc, char** argv) const std::string out_dir = argc == 8 ? argv[7] : ""; ComPtr adapter; - if (const int rc = pick_adapter(hardware, adapter)) return rc; + if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; { DXGI_ADAPTER_DESC desc{}; LARGE_INTEGER driver{}; diff --git a/tests/startup_stream_depth.cpp b/tests/startup_stream_depth.cpp index ee5364920..05fd92013 100644 --- a/tests/startup_stream_depth.cpp +++ b/tests/startup_stream_depth.cpp @@ -70,28 +70,6 @@ bool read_bytes(const char* path, std::vector& out) return !out.empty(); } -int pick_adapter(bool hardware, ComPtr& adapter) -{ - ComPtr factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; - if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; - ComPtr factory6; - if (FAILED(factory.As(&factory6))) return 77; - for (UINT n = 0;; ++n) { - ComPtr candidate; - const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) return 77; - if (FAILED(hr)) return 4; - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(candidate->GetDesc1(&desc))) return 4; - if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && - SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { - adapter = candidate; - return 0; - } - } -} - void* create_stream_pso(void* device, ID3D12RootSignature* root, const std::vector& vs, const std::vector& ps, const D3D12_DEPTH_STENCIL_DESC& ds, bool use_ds1, BOOL depth_bounds = FALSE, DXGI_FORMAT dsv_format = DXGI_FORMAT_D32_FLOAT) @@ -224,7 +202,7 @@ int main(int argc, char** argv) const bool hardware = std::strcmp(argv[6], "hardware") == 0; ComPtr adapter; - if (const int rc = pick_adapter(hardware, adapter)) return rc; + if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; { DXGI_ADAPTER_DESC desc{}; LARGE_INTEGER driver{}; diff --git a/tests/startup_stream_rasterizer.cpp b/tests/startup_stream_rasterizer.cpp index 18dce8f30..bf17e20ec 100644 --- a/tests/startup_stream_rasterizer.cpp +++ b/tests/startup_stream_rasterizer.cpp @@ -62,28 +62,6 @@ bool read_bytes(const char* path, std::vector& out) return !out.empty(); } -int pick_adapter(bool hardware, ComPtr& adapter) -{ - ComPtr factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; - if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; - ComPtr factory6; - if (FAILED(factory.As(&factory6))) return 77; - for (UINT n = 0;; ++n) { - ComPtr candidate; - const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) return 77; - if (FAILED(hr)) return 4; - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(candidate->GetDesc1(&desc))) return 4; - if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && - SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { - adapter = candidate; - return 0; - } - } -} - D3D12_RASTERIZER_DESC raster_desc(D3D12_CULL_MODE cull, BOOL depth_clip) { D3D12_RASTERIZER_DESC desc{}; @@ -151,7 +129,7 @@ int main(int argc, char** argv) const bool hardware = std::strcmp(argv[4], "hardware") == 0; ComPtr adapter; - if (const int rc = pick_adapter(hardware, adapter)) return rc; + if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; { DXGI_ADAPTER_DESC desc{}; LARGE_INTEGER driver{}; diff --git a/tests/startup_stream_rasterizer_check.py b/tests/startup_stream_rasterizer_check.py index ccf7becb7..bc3c55c84 100644 --- a/tests/startup_stream_rasterizer_check.py +++ b/tests/startup_stream_rasterizer_check.py @@ -24,6 +24,18 @@ def check(directory, consumer, backend, mode): env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", X2W_D3D12_DEBUG="1", X2W_SHADER_CACHE=str(cache)) base_args = [consumer, str(vs), str(ps), str(root), backend] + if mode == "filter": + missing = "x2w-no-such-hardware-adapter" + for selector, message in (("x" * 128, "XBOX2WINDOWS_ADAPTER is longer than 127 characters"), + (missing, f"No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER={missing}")): + req = subprocess.run(base_args, env=dict(env, XBOX2WINDOWS_ADAPTER=selector), + capture_output=True, text=True) + if selector == missing and req.returncode == 77: + return 77 + if req.returncode != 4 or message not in req.stderr: + raise RuntimeError(f"expected {message!r}, got exit {req.returncode}\n{req.stdout}{req.stderr}") + print("overlong and unmatched hardware adapter filters rejected") + return 0 req = subprocess.run(base_args, env=env, capture_output=True, text=True) if backend == "hardware" and req.returncode == 77: print("No D3D12 feature-level 12 hardware adapter") diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index 742e404ea..09a1ad6c0 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -73,6 +73,45 @@ void* stream_root_signature() { return stream_root; } void* stream_alternate_root_signature() { return stream_alternate_root; } const std::vector& stream_root_blob() { return stream_root_bytes; } +int pick_stream_adapter(bool hardware, ComPtr& adapter) +{ + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (!hardware) return SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter))) ? 0 : 4; + + wchar_t wanted[128]{}; + const DWORD length = GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", wanted, 128); + if (length >= 128) { + std::fputs("XBOX2WINDOWS_ADAPTER is longer than 127 characters\n", stderr); + return 4; + } + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference( + n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) { + if (!length) return 77; + std::fprintf(stderr, "No D3D12 hardware adapter matches XBOX2WINDOWS_ADAPTER=%ls\n", wanted); + return 4; + } + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; + bool matches = length == 0; + for (const wchar_t* p = desc.Description; !matches && *p; ++p) { + matches = _wcsnicmp(p, wanted, length) == 0; + } + if (matches && SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, + __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char* root_path, bool hardware, bool textured, Microsoft::WRL::ComPtr& adapter, void*& device, void*& pso) @@ -91,25 +130,7 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char debug->EnableDebugLayer(); } - ComPtr factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; - if (hardware) { - ComPtr factory6; - if (FAILED(factory.As(&factory6))) return 77; - for (UINT n = 0;; ++n) { - ComPtr candidate; - HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); - if (hr == DXGI_ERROR_NOT_FOUND) return 77; - if (FAILED(hr)) return 4; - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(candidate->GetDesc1(&desc))) return 4; - if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && - SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { - adapter = candidate; - break; - } - } - } else if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) return 4; + if (const int rc = pick_stream_adapter(hardware, adapter)) return rc; DXGI_ADAPTER_DESC desc{}; LARGE_INTEGER driver{}; if (FAILED(adapter->GetDesc(&desc))) return 4; diff --git a/tests/startup_stream_setup.h b/tests/startup_stream_setup.h index ffbdba2f9..32216c871 100644 --- a/tests/startup_stream_setup.h +++ b/tests/startup_stream_setup.h @@ -6,6 +6,7 @@ #include #include +int pick_stream_adapter(bool hardware, Microsoft::WRL::ComPtr& adapter); int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char* root_path, bool hardware, bool textured, Microsoft::WRL::ComPtr& adapter, void*& device, void*& pso); From f59f77614aa8b6a9c11752644bf239012ef159b6 Mon Sep 17 00:00:00 2001 From: Maledetto Date: Wed, 25 Nov 2026 18:13:09 +0100 Subject: [PATCH 063/232] tests: pin cmp16 refusals for neg/abs, literals, 16-bit conditions (#2426) The 16-bit VOPC compare check refused NEG/ABS only for v_cmp_lt_i16_e64, checked no literal bound and checked no 16-bit condition other than f. Mutations that dropped v_cmpx, u16 or ne from the NEG/ABS guard, moved a literal bound, or accepted the t or lg condition all passed. Add three groups to the refusals section: NEG and ABS on inline 1 for all 24 opcodes, the 0xffff (accepted) and 0x10000 (refused) literal limits for i16 and u16, and refusal of the ten conditions that do not exist at 16 bits for i16/u16 and v_cmp/v_cmpx. Only added lines; no tools/ change. Refs #1723 Co-authored-by: Maledetto <20729264+Makto94@users.noreply.github.com> --- tests/startup_gfx2hlsl_cmp16_check.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/startup_gfx2hlsl_cmp16_check.py b/tests/startup_gfx2hlsl_cmp16_check.py index b78d86ca4..3b936863e 100644 --- a/tests/startup_gfx2hlsl_cmp16_check.py +++ b/tests/startup_gfx2hlsl_cmp16_check.py @@ -276,6 +276,26 @@ def controls(): for token in ('-17', 's[2:3]', 'v[1:2]', 'vcc_lo', 'exec_lo', 'm0', '-v1', '|v1|', 'neg(v1)'): refused.append(('source %s' % token, refusal(name='v_cmp_lt_i16_e64', asm='v_cmp_lt_i16_e64 s4, %s, v2' % token) is not None)) + # NEG/ABS on every opcode: the e64 guard must cover v_cmpx, u16 and every relation, not only v_cmp_lt_i16 + # (inline 1 with NEG decodes as -1, the text of inline -1). + for (cmpx, cond, typ), opcode in sorted(OPCODES.items()): + for field in ('neg', 'absolute'): + refused.append(('%s on inline 1 in v_cmp%s_%s_%s' % (field, 'x' if cmpx else '', cond, typ), + 'neg/abs' in (refusal(e64(opcode, 0 if cmpx else SGPR_DST, inline(1), V(2), + **{field: 1})) or ''))) + # Literal bounds: 0xffff is the widest 16-bit literal, 0x10000 would silently lose its high bit. + for typ in ('i16', 'u16'): + lt = OPCODES[False, 'lt', typ] + refused.append(('literal 0xffff %s accepted' % typ, refusal(e32(lt, LITERAL, 2, 0xffff)) is None)) + refused.append(('literal 0x10000 %s' % typ, + 'wider than 16 bits' in (refusal(e32(lt, LITERAL, 2, 0x10000)) or ''))) + # Conditions that exist for no 16-bit integer compare stay refused, as v_cmp_f does. + for cond in ('t', 'lg', 'nlg', 'nlt', 'nle', 'ngt', 'nge', 'neq', 'o', 'u'): + for typ in ('i16', 'u16'): + for x in ('', 'x'): + name = 'v_cmp%s_%s_%s_e64' % (x, cond, typ) + refused.append((name, refusal(name=name, asm='%s %sv1, v2' % (name, '' if x else 's4, ')) + == 'v_cmp%s_%s_%s' % (x, cond, typ))) refused.append(('destination vcc_hi', 'into vcc_hi' in (refusal(e64(lt_i16, VCC_HI, V(1), V(2))) or ''))) refused.append(('destination m0', 'into m0' in (refusal(e64(lt_i16, M0, V(1), V(2))) or ''))) refused.append(('no 16-bit f', refusal(name='v_cmp_f_i16_e64', asm='v_cmp_f_i16_e64 s4, v1, v2') From a56a8bcbf90940b7824442ab31508898b103f74a Mon Sep 17 00:00:00 2001 From: Maledetto Date: Wed, 25 Nov 2026 18:14:24 +0100 Subject: [PATCH 064/232] tests: evaluate the emitted run-time block of the 64-bit scalar shifts and s_bfe (#2400) Refs #1723 Co-authored-by: Maledetto <20729264+Makto94@users.noreply.github.com> --- ...artup_gfx2hlsl_scalar_shift64_bfe_check.py | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) diff --git a/tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py b/tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py index 42e2a5064..518de8976 100644 --- a/tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py +++ b/tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py @@ -244,6 +244,91 @@ def runtime_blocks(): assert text.index('shl64(s6, s7') < text.index('s6 = '), text +def run_block(text, funcs, regs): + """Run one emitted `{ ... }` block with the helper functions; returns (registers, scc).""" + m = re.fullmatch(r'\{ uint2? t = (\w+)\((.*?)\); (.*) \}', text) + assert m, text + args = [] + for tok in (a.strip() for a in m.group(2).split(',')): + args.append(U(regs[int(tok[1:])]) if tok.startswith('s') else U(int(tok[:-1], 0))) + t = funcs[m.group(1)](*args) + out, scc = dict(regs), None + for stmt in (s.strip() for s in m.group(3).split(';') if s.strip()): + lhs, rhs = (p.strip() for p in stmt.split(' = ', 1)) + rhs = re.sub(r'\b(\d+)u\b', r'\1', re.sub(r'\bt\.x\b', 't[0]', re.sub(r'\bt\.y\b', 't[1]', rhs))) + value = eval(rhs, {'t': t if isinstance(t, tuple) else int(t)}) # noqa: S307 - generated text + if lhs == 'scc': + scc = bool(value) + else: + out[int(lhs[1:])] = int(value) + return out, scc + + +def runtime_semantics(): + """Evaluate the run-time block for operands unknown at translation time against the reference.""" + funcs = make_helpers(S.translate('v_lshlrev_b64', 'shl64')[1]) + rows = {'s_lshl_b64': ((1, 32), (1, 1), (0x8000000000000000, 1), (0x00000000f0f0f0f0, 4)), + 's_lshr_b64': ((0x100000000, 32), (0x8000000000000000, 63), (1, 1)), + 's_ashr_i64': ((0x8000000000000000, 1), (0x7fffffffffffffff, 62)), + 's_bfe_i32': ((0x000000f0, 4 | 4 << 16), (0x80000000, 31 | 1 << 16), (0x12345678, 0), (0x1, 2 << 16)), + 's_bfe_u64': ((0x123456789abcdef0, 32 | 16 << 16), (M64, 63 | 8 << 16)), + 's_bfe_i64': ((0x00000000000000f0, 4 | 4 << 16), (0x8000000000000000, 63 | 1 << 16))} + for op, cases in rows.items(): + wide = op in WIDE_RESULT + stage = stage_for(op) # s6, s7 and s9 are unknown at translation time + text = [line for line in stage.lines if HELPERS[op][0] + '(' in line][0] + for x, amount in cases: + regs = {SRC: x & M32, SRC + 1: x >> 32, AMT: amount, DST: 0xdeadbeef, DST + 1: 0xdeadbeef} + if op == 's_bfe_i32': + x &= M32 + out, scc = run_block(text, funcs, regs) + want = reference(op, x, amount) + got = out[DST] | (out[DST + 1] << 32 if wide else 0) + assert got == want, '%s %#x,%#x: block gave %#x, reference %#x' % (op, x, amount, got, want) + assert scc == (want != 0), '%s %#x,%#x: SCC %s for result %#x' % (op, x, amount, scc, want) + if not wide: + assert out[DST + 1] == 0xdeadbeef, (op, 'wrote the next register') + + +def partly_known(): + """One constant word, one unknown word, or a constant source with an unknown amount: no folding.""" + cases = ((('s_lshl_b64', 's[20:21], s[6:7], s9'), {6: ('const', 1)}), + (('s_lshl_b64', 's[20:21], s[6:7], s9'), {7: ('const', 0)}), + (('s_lshl_b64', 's[20:21], s[6:7], s9'), {6: ('const', 1), 7: ('const', 0)}), + (('s_lshl_b64', 's[20:21], s[6:7], s9'), {9: ('const', 3)}), + (('s_lshl_b64', 's[20:21], s[6:7], s9'), {6: ('const', 1), 9: ('const', 3)}), + (('s_lshl_b64', 's[20:21], s[6:7], s9'), {7: ('const', 0), 9: ('const', 3)}), + (('s_bfe_i32', 's20, s6, s9'), {6: ('const', 5)}), + (('s_bfe_i32', 's20, s6, s9'), {9: ('const', 5)})) + funcs = make_helpers(S.translate('v_lshlrev_b64', 'shl64')[1]) + fills = {'s_lshl_b64': ((1, 2, 1), (0x80000000, 1, 3), (0xf0f0f0f0, 0x0f0f0f0f, 33)), + 's_bfe_i32': ((0xf0, 0, 4 | 4 << 16), (0x8000, 0, 15 | 1 << 16), (0x1, 0, 2 << 16))} + for (op, operands), sym in cases: + stage = M.ProbeStage() + stage.sym.update(sym) + stage.one(op, '%s %s' % (op, operands)) + assert any(HELPERS[op][0] + '(' in line for line in stage.lines), (op, sym, stage.lines) + assert not any(line.startswith('s20 = 0x') for line in stage.lines), (op, sym, stage.lines) + # Run the emitted block: constants stay in their registers, the unknown ones take concrete values. + text = [line for line in stage.lines if HELPERS[op][0] + '(' in line][0] + wide = op in WIDE_RESULT + for lo, hi, amount in fills[op]: + regs = {SRC: lo, SRC + 1: hi, AMT: amount, DST: 0xdeadbeef, DST + 1: 0xdeadbeef} + regs.update({r: v[1] for r, v in sym.items()}) + x = regs[SRC] | (regs[SRC + 1] << 32 if wide else 0) + out, scc = run_block(text, funcs, regs) + want = reference(op, x, regs[AMT]) + got = out[DST] | (out[DST + 1] << 32 if wide else 0) + assert got == want, '%s %s %#x,%#x: block gave %#x, reference %#x' % (op, sym, x, regs[AMT], got, want) + assert scc == (want != 0), (op, sym, x, regs[AMT], scc, want) + # A destination that held a constant must not keep it once the run-time block has overwritten it. + stale = M.ProbeStage() + stale.sym.update(sym) + stale.sym.update({DST: ('const', 7), DST + 1: ('const', 9)}) + stale.one(op, '%s %s' % (op, operands)) + assert not set(range(DST, DST + 1 + wide)) & set(stale.sym), (op, sym, stale.sym) + + def uniformity(): for op in OPCODES: stage = M.ProbeStage() @@ -264,6 +349,24 @@ def uniformity(): raise AssertionError('%s on a lane mask should be refused' % op) +def varying_operand(): + """A varying low word, high word or shift amount makes the result and SCC varying.""" + for op in OPCODES: + wide = op in WIDE_RESULT + for varying in ([SRC, AMT] if not wide else [SRC, SRC + 1, AMT]): + stage = M.ProbeStage() + stage.varying_s, stage.scc_uniform = set(), True + code = M.encode_sop2(OPCODES[op], DST, SRC, AMT) + _, name, asm, _ = M.D.decode_instruction(code, 0) + for reg in (SRC, SRC + 1, AMT): + stage.sym[reg] = ('ud', 1) + stage.sym.pop(varying) + stage.varying_s.add(varying) + stage.one(name, asm) + assert DST in stage.varying_s and not stage.scc_uniform, (op, varying, stage.varying_s) + assert (not wide) or DST + 1 in stage.varying_s, (op, varying, stage.varying_s) + + def overwritten_mask(): for op in OPCODES: stage = M.ProbeStage() @@ -313,7 +416,10 @@ def main(): checked = helper_grid() const_folding() runtime_blocks() + runtime_semantics() + partly_known() uniformity() + varying_operand() refusals() overwritten_mask() print('startup scalar 64-bit shift and bitfield extract controls passed (%d helper cases)' % checked) From a96874a6afe8736df6893ee66184d303dda50f13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=A9=E5=87=BA=E9=81=93?= Date: Thu, 26 Nov 2026 01:15:40 +0800 Subject: [PATCH 065/232] docs: add RTX 3070 Ti driver 610.88 GPU check report (#2402) Co-authored-by: wanchudao <280326495+wanchudao@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a7abb29df..39b610bf2 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ Results are grouped by adapter. Open a report for the driver, build and any capa |---|---:|---|---|---| | NVIDIA GeForce RTX 2060 | 32 | Skipped | 408 queries passed | [Maintainer baseline](docs/experiments.md#independent-bvh-checks-on-pc) · [32.0.16.2124 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7077064410) | | NVIDIA GeForce RTX 3070 (driver 32.0.16.1088) | 32 | Skipped, lane range 32–32 | 408 queries passed | [RTX 3070 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063566753) · [32.0.16.2101 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064780514) · [Independent 32.0.16.2101 run, source build at b860dd5](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7070552394) · [Independent 32.0.16.1088 run, Windows 10](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7084482487) | -| NVIDIA GeForce RTX 3070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1692 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7099622883) · [32.0.16.1742 report, Windows build 26200](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7121943659) · [32.0.16.2114 report by @Maxim-Root, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7129028243) | +| NVIDIA GeForce RTX 3070 Ti | 32 | Skipped, lane range 32–32 | 408 queries passed | [32.0.16.1692 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7099622883) · [32.0.16.1742 report, Windows build 26200](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7121943659) · [32.0.16.2114 report by @Maxim-Root, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7129028243) · [32.0.16.1088 (610.88) report by @wanchudao](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7166634226) | | NVIDIA GeForce RTX 4060 Laptop GPU | 32 | Skipped | 408 queries passed | [Second maintainer workstation](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7058907095) · [Independent Windows run, driver 32.0.16.2124](https://github.com/R0Y00/Xbox2Windows/issues/60) · [32.0.16.1742 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064580375) · [32.0.16.1091 report, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7082946105) | | NVIDIA GeForce RTX 5070 | 32 on every run | Skipped on every run, lane range 32–32 | 408 queries passed per run | [32.0.16.1692, debug layer unavailable](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063361337) · [32.0.16.2135 retest, debug layer enabled](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063626309) · [32.0.16.2124 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066814242) · [32.0.16.1686 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7067154644) · [Independent 32.0.16.2135 run](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7068151257) · [38.0.1.104 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7066183143) | | AMD Radeon RX 6600 (driver 32.0.21045.16010) | 32 | Passed, 64 lanes; skipped, Shader Model 6.5 on build 19044 | 408 queries passed | [RX 6600 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063312495) · [32.0.11037.4004 retest](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7063794169) · [32.0.21045.29003 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7064667296) · [32.0.21030.2001 report, Windows 10 build 19044](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080061922) · [31.0.22017.3004 report](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7080963908) · [Independent 32.0.21045.29003 run, Windows build 26300](https://github.com/R0Y00/Xbox2Windows/issues/1#issuecomment-7122426568) | From 8e5dcb6979b7ba6f23990c458996f992253731d6 Mon Sep 17 00:00:00 2001 From: KomaGuy Date: Wed, 25 Nov 2026 20:19:47 +0300 Subject: [PATCH 066/232] tests: add supplemental SDWA 32-bit integer compare draws and refusal controls (#1923) Rebase #1923 onto current main (after #1790 landed all 46 non-cmpx SDWA comparisons in tools/pixel_aot.py and tools/scan_unsupported_shaders.py) and keep the supplemental per-predicate 32-bit integer test coverage: - Four 4-channel draw programs (i32_lo, i32_hi, u32_lo, u32_hi) covering all 16 v_cmp_*_{i32,u32}_sdwa forms with 41 targeted single-channel negative controls (signed vs unsigned, sext vs zero-extend, byte/word selectors, predicate swaps) registered as pixel_aot_sdwa_int_compare_{warp,hardware} and included in check_binary. - Additional static lowering and refusal checks: whole-dword equivalence with e32, single-register destination enforcement (refusing SGPR pairs and out-of-range s106), low16 VGPR source refusal, pending sample and pending scalar source/destination refusal, non-entry mask refusal, float modifiers, clamp, dst_sel, and remaining unlowered SDWA compare neighbours (i64, v_cmpx). Co-authored-by: KomaGuy <265821007+KomaGuy@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 2 +- tests/pixel_aot_check.py | 289 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 294 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d7c2b8485..7161063c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8950,6 +8950,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_sdwa_cmp_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_cmp_${adapter}.txt") + add_test(NAME pixel_aot_sdwa_int_compare_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-sdwa-int-compare "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sdwa_int_compare_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_int_compare_${adapter}.txt") add_test(NAME pixel_aot_get_lod_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_get_lod_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index a759c472e..45e57a479 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7780,7 +7780,7 @@ Scalar ALU support also covers the 64-bit SOP1/SOP2 family (`s_cmov_b64`, `s_not The SDWA forms of the 16 `v_cmp_*_f32` predicates are lowered when both `src0_sel` and `src1_sel` are `DWORD`. With whole-dword selections they compare the operands exactly as the e32/e64 forms do; the translator emits identical HLSL for both, and a control asserts it. A byte or word selection would compare a zero-extended field as binary32 and is refused. The predicate draws are repeated with the SDWA compares for all four groups and the same five input pairs, including NaN on either side. A reference that inverts each group's unordered result must report a mismatch. -The 46 non-`v_cmpx` VOPC SDWA comparisons left by lot 1a are lowered: the 16 binary16 predicates and `v_cmp_class_f16_sdwa`, `v_cmp_class_f32_sdwa`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA encodes only `src0_sel` and `src1_sel`; `llvm-mc` rejects `dst_sel`/`dst_unused` on these instructions, so the destination stays `vcc`/`vcc_lo` or one SGPR and the translator refuses an SGPR pair and the destination fields. Sources accept `BYTE_0..3`, `WORD_0..1` and `DWORD`, with `sext()` where LLVM prints it. The selection is zero-extended, or sign-extended under `sext()`, before the existing table applies: binary16 uses the low 16 bits through `widen16`/`num16`, the 16-bit integer forms take the low 16 bits, the 32-bit integer forms compare the selected word as signed or unsigned, and the class forms feed the selected bits to `class16` or `class32`. The comparison result is tracked in the same VCC/SGPR lane-mask state as the e32 and e64 forms, so `v_cndmask_b32` consumes it unchanged. The source-built fixture `tests/pixel_aot_check.py draw-sdwa-cmp` puts all 46 forms in one program, folds each predicate into two exported `R32G32B32A32_UINT` words, and repeats the rows with selections on every field. Its wrong references must each report `pixel_mismatch`: selections ignored (whole dwords), every field reversed (`BYTE_0`/`BYTE_3`, `BYTE_1`/`BYTE_2`, `WORD_0`/`WORD_1`), signedness inverted on the rows containing `0x8000`/`0xffff`, and zero extension in place of `sext()`. A second program writes two comparisons to `s52` and `vcc_lo` before consuming both; a reference that uses the second mask for both channels must mismatch. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts the 46 forms count in both `gfx1013.tsv` and `rdna2.tsv`, while the non-SDWA `v_cmp_*` neighbours and the `v_cmpx_*_sdwa` forms stay out. The same program is part of `check_binary`, so the LLVM 15 `Assemble and translate gfx1013 fixtures` job assembles, disassembles and re-translates it. On base `0aa6522c` the measurement moved from 1255/1968 to 1301/1968 on gfx1013 and from 1246/1863 to 1292/1863 on gfx1030, exactly 46 forms in each reference. The new tests passed on WARP and on `pixel_aot_sdwa_cmp_hardware` on an AMD Radeon RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075, in 1.10 s; the debug layer was unavailable. The separate `pixel_aot_comparisons_hardware` entry still fails on this adapter in its pre-existing strict binary32 subnormal comparison ([issue #958](https://github.com/R0Y00/Xbox2Windows/issues/958)); that failure is outside this lot and does not affect the SDWA draw. This measures translated fixtures, not console behavior or full title execution. Reproduce with `ctest --preset dev --no-tests=error -R '^pixel_aot_sdwa_cmp_' -V`; the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-sdwa-after.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-sdwa-after.xml --records out/build/dev/form_coverage --json out/wave1-sdwa-after.json`. +The 46 non-`v_cmpx` VOPC SDWA comparisons left by lot 1a are lowered: the 16 binary16 predicates and `v_cmp_class_f16_sdwa`, `v_cmp_class_f32_sdwa`, the 8 signed and 8 unsigned 32-bit predicates and the 6 signed and 6 unsigned 16-bit predicates. VOPC SDWA encodes only `src0_sel` and `src1_sel`; `llvm-mc` rejects `dst_sel`/`dst_unused` on these instructions, so the destination stays `vcc`/`vcc_lo` or one SGPR and the translator refuses an SGPR pair and the destination fields. Sources accept `BYTE_0..3`, `WORD_0..1` and `DWORD`, with `sext()` where LLVM prints it. The selection is zero-extended, or sign-extended under `sext()`, before the existing table applies: binary16 uses the low 16 bits through `widen16`/`num16`, the 16-bit integer forms take the low 16 bits, the 32-bit integer forms compare the selected word as signed or unsigned, and the class forms feed the selected bits to `class16` or `class32`. The comparison result is tracked in the same VCC/SGPR lane-mask state as the e32 and e64 forms, so `v_cndmask_b32` consumes it unchanged. The source-built fixture `tests/pixel_aot_check.py draw-sdwa-cmp` puts all 46 forms in one program, folds each predicate into two exported `R32G32B32A32_UINT` words, and repeats the rows with selections on every field. Its wrong references must each report `pixel_mismatch`: selections ignored (whole dwords), every field reversed (`BYTE_0`/`BYTE_3`, `BYTE_1`/`BYTE_2`, `WORD_0`/`WORD_1`), signedness inverted on the rows containing `0x8000`/`0xffff`, and zero extension in place of `sext()`. A second program writes two comparisons to `s52` and `vcc_lo` before consuming both; a reference that uses the second mask for both channels must mismatch. `tests/form_coverage_check.py` isolates this fixture's accepted words and asserts the 46 forms count in both `gfx1013.tsv` and `rdna2.tsv`, while the non-SDWA `v_cmp_*` neighbours and the `v_cmpx_*_sdwa` forms stay out. The same program is part of `check_binary`, so the LLVM 15 `Assemble and translate gfx1013 fixtures` job assembles, disassembles and re-translates it. On base `0aa6522c` the measurement moved from 1255/1968 to 1301/1968 on gfx1013 and from 1246/1863 to 1292/1863 on gfx1030, exactly 46 forms in each reference. The new tests passed on WARP and on `pixel_aot_sdwa_cmp_hardware` on an AMD Radeon RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075, in 1.10 s; the debug layer was unavailable. The separate `pixel_aot_comparisons_hardware` entry still fails on this adapter in its pre-existing strict binary32 subnormal comparison ([issue #958](https://github.com/R0Y00/Xbox2Windows/issues/958)); that failure is outside this lot and does not affect the SDWA draw. This measures translated fixtures, not console behavior or full title execution. Reproduce with `ctest --preset dev --no-tests=error -R '^pixel_aot_sdwa_cmp_' -V`; the full measurement is `ctest --preset dev --no-tests=error -R '^(pixel_aot_|compute_store_aot_)' -E '_hardware$' -j 1 --output-junit out/build/dev/out/wave1-sdwa-after.xml` followed by `python -B tools/form_coverage.py out/build/dev/out/wave1-sdwa-after.xml --records out/build/dev/form_coverage --json out/wave1-sdwa-after.json`. A supplemental per-predicate fixture (`tests/pixel_aot_check.py draw-sdwa-int-compare`, tests `pixel_aot_sdwa_int_compare_{warp,hardware}`) exercises all 16 32-bit integer SDWA comparisons across four 4-channel groups (`i32_lo`, `i32_hi`, `u32_lo`, `u32_hi`) with 41 targeted single-channel negative controls plus static refusal checks for `low16` sources, pending loads, masked regions, float modifiers, `clamp` and SGPR pair destinations. Binary32 floating-point vector comparisons (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f32` in e32, e64, and whole-dword SDWA forms) evaluate the 16 IEEE-754 relations against scalar and vector operands, including subnormals, signed zeroes, infinities, and quiet/signaling NaNs. The e32 (VOPC) encoding requires destination `vcc` or `vcc_lo`; SGPR destinations (`s52`, `s[52:53]`) are accepted on suffix-less and explicit `_e64` (VOP3) encodings. Source modifiers (`neg`, `abs`) are accepted on e64 operands (`-s44`, `|v18|`, `-|s44|`), while `clamp` and `op_sel` remain rejected on comparisons. Rejection controls verify that untracked source registers, SGPR destinations on explicit e32, and sub-dword SDWA selections (`src0_sel:WORD_0`, `src1_sel:BYTE_2`) raise `ValueError`. The synthetic fixture `f32_compares()` verifies all 16 predicates across e32, e64, and whole-dword SDWA, validating them against an exact reference oracle (`f32_compares_reference()`). Mutating predicates or modifiers produces a mismatch. diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 41f7000cd..e7e9ff37a 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -11346,6 +11346,167 @@ def sdwa_integer_cases(group): return cases +# Supplemental per-predicate SDWA 32-bit integer comparison draws (all 16 forms across four 4-channel groups), +# with A, B, C and D in s44 to s47, B in v18, C in v19 and 1.0 (0x3f800000) in v20. Each channel writes 0 or +# 0x3f800000 via v_cndmask_b32 from vcc_lo or s52. Together the four groups cover all 16 opcodes, all 7 +# selectors on both src0_sel and src1_sel, zero- and sign-extension on either or both sources, and all +# SGPR/VGPR source pairs. +SDWA_INT_CMP_ONE = 0x3f800000 +SDWA_INT_CMP_BODIES = { + "i32_lo": [ + "v_cmp_f_i32_sdwa vcc_lo, s44, v18 src0_sel:DWORD src1_sel:DWORD", + "v_cndmask_b32_e32 v12, 0, v20, vcc_lo", + "v_cmp_lt_i32_sdwa s52, sext(s44), v18 src0_sel:BYTE_0 src1_sel:BYTE_1", + "v_cndmask_b32_e64 v13, 0, v20, s52", + "v_cmp_eq_i32_sdwa vcc_lo, sext(v18), sext(s44) src0_sel:WORD_0 src1_sel:WORD_1", + "v_cndmask_b32_e32 v14, 0, v20, vcc_lo", + "v_cmp_le_i32_sdwa s52, s44, sext(v19) src0_sel:WORD_0 src1_sel:BYTE_2", + "v_cndmask_b32_e64 v15, 0, v20, s52", + ], + "i32_hi": [ + "v_cmp_gt_i32_sdwa vcc_lo, s44, sext(s45) src0_sel:BYTE_3 src1_sel:BYTE_2", + "v_cndmask_b32_e32 v12, 0, v20, vcc_lo", + "v_cmp_ne_i32_sdwa s52, v18, v19 src0_sel:BYTE_1 src1_sel:BYTE_0", + "v_cndmask_b32_e64 v13, 0, v20, s52", + "v_cmp_ge_i32_sdwa vcc_lo, sext(v18), sext(s44) src0_sel:BYTE_3 src1_sel:WORD_1", + "v_cndmask_b32_e32 v14, 0, v20, vcc_lo", + "v_cmp_t_i32_sdwa s52, s44, v18 src0_sel:DWORD src1_sel:DWORD", + "v_cndmask_b32_e64 v15, 0, v20, s52", + ], + "u32_lo": [ + "v_cmp_f_u32_sdwa vcc_lo, v18, s44 src0_sel:DWORD src1_sel:DWORD", + "v_cndmask_b32_e32 v12, 0, v20, vcc_lo", + "v_cmp_lt_u32_sdwa s52, s44, sext(v18) src0_sel:WORD_0 src1_sel:BYTE_0", + "v_cndmask_b32_e64 v13, 0, v20, s52", + "v_cmp_eq_u32_sdwa vcc_lo, s44, s45 src0_sel:BYTE_2 src1_sel:BYTE_3", + "v_cndmask_b32_e32 v14, 0, v20, vcc_lo", + "v_cmp_le_u32_sdwa s52, v18, v19 src0_sel:DWORD src1_sel:DWORD", + "v_cndmask_b32_e64 v15, 0, v20, s52", + ], + "u32_hi": [ + "v_cmp_gt_u32_sdwa vcc_lo, sext(s44), v18 src0_sel:WORD_1 src1_sel:DWORD", + "v_cndmask_b32_e32 v12, 0, v20, vcc_lo", + "v_cmp_ne_u32_sdwa s52, sext(v18), sext(s44) src0_sel:BYTE_1 src1_sel:BYTE_1", + "v_cndmask_b32_e64 v13, 0, v20, s52", + "v_cmp_ge_u32_sdwa vcc_lo, s44, v19 src0_sel:WORD_0 src1_sel:WORD_0", + "v_cndmask_b32_e32 v14, 0, v20, vcc_lo", + "v_cmp_t_u32_sdwa s52, v18, s44 src0_sel:DWORD src1_sel:DWORD", + "v_cndmask_b32_e64 v15, 0, v20, s52", + ], +} +SDWA_INT_CMP_OPS = tuple(sorted({line.split()[0] for body in SDWA_INT_CMP_BODIES.values() for line in body + if line.split()[0].endswith("_sdwa")})) + + +def _u32_sext(value, width): + return _sext(value, width) & 0xffffffff + + +SDWA_INT_CMP_RESULTS = { + "i32_lo": lambda a, b, c, d: ( + False, + _sext(_byte(a, 0), 8) < _byte(b, 1), + _sext(_word(b, 0), 16) == _sext(_word(a, 1), 16), + _word(a, 0) <= _sext(_byte(c, 2), 8), + ), + "i32_hi": lambda a, b, c, d: ( + _byte(a, 3) > _sext(_byte(b, 2), 8), + _byte(b, 1) != _byte(c, 0), + _sext(_byte(b, 3), 8) >= _sext(_word(a, 1), 16), + True, + ), + "u32_lo": lambda a, b, c, d: ( + False, + _word(a, 0) < _u32_sext(_byte(b, 0), 8), + _byte(a, 2) == _byte(b, 3), + b <= c, + ), + "u32_hi": lambda a, b, c, d: ( + _u32_sext(_word(a, 1), 16) > b, + _u32_sext(_byte(b, 1), 8) != _u32_sext(_byte(a, 1), 8), + _word(a, 0) >= _word(c, 0), + True, + ), +} +SDWA_INT_CMP_WRONG = { + "i32_lo": ( + (0, 0, lambda a, b, c, d: True, "t for f"), + (0, 1, lambda a, b, c, d: _byte(a, 0) < _byte(b, 1), "sign extension dropped on src0"), + (0, 1, lambda a, b, c, d: _u32_sext(_byte(a, 0), 8) < _byte(b, 1), "unsigned for signed"), + (1, 1, lambda a, b, c, d: _sext(_byte(a, 1), 8) < _byte(b, 1), "BYTE_1 for BYTE_0"), + (0, 2, lambda a, b, c, d: _word(b, 0) == _sext(_word(a, 1), 16), "sign extension dropped on src0"), + (0, 2, lambda a, b, c, d: _s32(b) == _s32(a), "whole DWORD for WORD_0/WORD_1"), + (0, 2, lambda a, b, c, d: _sext(_word(b, 0), 16) != _sext(_word(a, 1), 16), "ne for eq"), + (0, 3, lambda a, b, c, d: _word(a, 0) <= _byte(c, 2), "sign extension dropped on src1"), + (0, 3, lambda a, b, c, d: _word(a, 0) <= _u32_sext(_byte(c, 2), 8), "unsigned for signed"), + (1, 3, lambda a, b, c, d: _word(a, 0) < _sext(_byte(c, 2), 8), "lt for le"), + (1, 3, lambda a, b, c, d: _word(a, 1) <= _sext(_byte(c, 2), 8), "WORD_1 for WORD_0"), + ), + "i32_hi": ( + (0, 0, lambda a, b, c, d: _byte(a, 3) > _byte(b, 2), "sign extension dropped on src1"), + (0, 0, lambda a, b, c, d: _byte(a, 3) > _u32_sext(_byte(b, 2), 8), "unsigned for signed"), + (1, 0, lambda a, b, c, d: _byte(a, 3) >= _sext(_byte(b, 2), 8), "ge for gt"), + (0, 1, lambda a, b, c, d: b != c, "whole DWORD for BYTE_1/BYTE_0"), + (0, 1, lambda a, b, c, d: _byte(b, 0) != _byte(c, 0), "BYTE_0 for BYTE_1"), + (0, 1, lambda a, b, c, d: _byte(b, 1) == _byte(c, 0), "eq for ne"), + (0, 2, lambda a, b, c, d: _sext(_byte(b, 3), 8) >= _word(a, 1), "sign extension dropped on src1"), + (0, 2, lambda a, b, c, d: _u32_sext(_byte(b, 3), 8) >= _u32_sext(_word(a, 1), 16), "unsigned for signed"), + (1, 2, lambda a, b, c, d: _byte(b, 3) >= _sext(_word(a, 1), 16), "sign extension dropped on src0"), + (0, 3, lambda a, b, c, d: False, "f for t"), + ), + "u32_lo": ( + (0, 0, lambda a, b, c, d: True, "t for f"), + (0, 1, lambda a, b, c, d: _word(a, 0) < _byte(b, 0), "sign extension dropped on src1"), + (0, 1, lambda a, b, c, d: _word(a, 0) < _sext(_byte(b, 0), 8), "signed for unsigned"), + (0, 1, lambda a, b, c, d: _word(a, 0) > _u32_sext(_byte(b, 0), 8), "gt for lt"), + (0, 2, lambda a, b, c, d: _byte(a, 3) == _byte(b, 3), "BYTE_3 for BYTE_2"), + (0, 2, lambda a, b, c, d: _byte(a, 2) == _byte(b, 2), "BYTE_2 for BYTE_3"), + (0, 2, lambda a, b, c, d: a == b, "whole DWORD for BYTE_2/BYTE_3"), + (0, 2, lambda a, b, c, d: _byte(a, 2) != _byte(b, 3), "ne for eq"), + (0, 3, lambda a, b, c, d: _s32(b) <= _s32(c), "signed for unsigned"), + (1, 3, lambda a, b, c, d: b < c, "lt for le"), + ), + "u32_hi": ( + (0, 0, lambda a, b, c, d: _word(a, 1) > b, "sign extension dropped on src0"), + (0, 0, lambda a, b, c, d: _sext(_word(a, 1), 16) > _s32(b), "signed for unsigned"), + (0, 0, lambda a, b, c, d: _u32_sext(_word(a, 0), 16) > b, "WORD_0 for WORD_1"), + (0, 1, lambda a, b, c, d: b != a, "whole DWORD for BYTE_1"), + (0, 1, lambda a, b, c, d: _u32_sext(_byte(b, 0), 8) != _u32_sext(_byte(a, 1), 8), "BYTE_0 for BYTE_1"), + (0, 1, lambda a, b, c, d: _u32_sext(_byte(b, 1), 8) == _u32_sext(_byte(a, 1), 8), "eq for ne"), + (0, 2, lambda a, b, c, d: _word(a, 0) >= _word(c, 1), "WORD_1 for WORD_0 on src1"), + (0, 2, lambda a, b, c, d: _word(c, 0) >= _word(a, 0), "swapped operands"), + (1, 2, lambda a, b, c, d: _word(a, 0) > _word(c, 0), "gt for ge"), + (0, 3, lambda a, b, c, d: False, "f for t"), + ), +} +SDWA_INT_CMP_ROWS = { + "i32_lo": ((0x81250090, 0x40d18125, 0x3ef01234, 0), (0x40250040, 0x3f802001, 0x3e401234, 0)), + "i32_hi": ((0xc0251234, 0x40f05511, 0x3f002255, 0), (0x00801234, 0xc0005511, 0x3f002266, 0)), + "u32_lo": ((0x3f400100, 0x40123480, 0xbf800000, 0), (0x3f410100, 0x4012347f, 0x4012347f, 0)), + "u32_hi": ((0xc0257000, 0x3f807011, 0xbf803f80, 0), (0x3f803f80, 0x3f809111, 0xbf803f80, 0)), +} + + +def sdwa_int_compare_group(group): + return ["v_mov_b32_e32 v18, s45", "v_mov_b32_e32 v19, s46", "v_mov_b32_e32 v20, 1.0", + *SDWA_INT_CMP_BODIES[group]] + + +def sdwa_int_compare_cases(group): + """(row, expected words, status, reason) for every draw of a group: the right rows, then the controls.""" + rows = SDWA_INT_CMP_ROWS[group] + right = [tuple(SDWA_INT_CMP_ONE if flag else 0 for flag in SDWA_INT_CMP_RESULTS[group](*row)) for row in rows] + cases = [(row, words, "pass", "") for row, words in zip(rows, right)] + for index, channel, wrong, reason in SDWA_INT_CMP_WRONG[group]: + words = list(right[index]) + words[channel] = SDWA_INT_CMP_ONE if wrong(*rows[index]) else 0 + assert words[channel] != right[index][channel], (group, reason) + cases.append((rows[index], tuple(words), "mismatch", reason)) + for row, words in zip(rows, right): + assert all(binary32_normal_or_zero(word) for word in (*row, *words)), (group, [hex(w) for w in (*row, *words)]) + return cases + + # Saturating 16-bit packs (v_cvt_pk_u16_u32, v_cvt_pk_i16_i32). Bodies for uncompressed_export(): s44 = A and # s45 = B from the constants, v18 = B, v19 = B >> 16 (the high half, always inside both 16-bit ranges when # read as unsigned or sign-extended below), v20 = B >> 12 and v21 = B >> 16 arithmetic. A normal binary32 @@ -12614,6 +12775,99 @@ def statement(*body): must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad])) +def check_sdwa_int_compare_lowering(): + """Supplemental static lowering and refusal checks for the 16 32-bit integer SDWA comparisons.""" + assert (SDWA_INT_CMP_BODIES.keys() == SDWA_INT_CMP_RESULTS.keys() + == SDWA_INT_CMP_WRONG.keys() == SDWA_INT_CMP_ROWS.keys()) + src0_sels, src1_sels = set(), set() + for group, body in SDWA_INT_CMP_BODIES.items(): + translate_int(uncompressed_export(sdwa_int_compare_group(group))) + sdwa_int_compare_cases(group) + for line in body: + if m := re.search(r"src0_sel:(\S+) src1_sel:(\S+)", line): + src0_sels.add(m.group(1)) + src1_sels.add(m.group(2)) + assert src0_sels == set(pixel_aot.SDWA_SEL), src0_sels + assert src1_sels == set(pixel_aot.SDWA_SEL), src1_sels + expected_ops = {f"v_cmp_{op}_{kind}_sdwa" for op in INT_PREDICATES for kind in ("i32", "u32")} + assert len(SDWA_INT_CMP_OPS) == 16 and set(SDWA_INT_CMP_OPS) == expected_ops + assert expected_ops <= ACCEPTED, expected_ops - ACCEPTED + + def cmp_statement(compare_line, mask_reg="vcc_lo"): + cnd = f"v_cndmask_b32_{'e32' if mask_reg in ('vcc', 'vcc_lo') else 'e64'} v12, 0, v19, {mask_reg}" + program = uncompressed_export(["v_mov_b32_e32 v18, s45", "v_mov_b32_e32 v19, 1.0", compare_line, cnd]) + index = program.index(compare_line) + lines = [line for line in translate_int(program).splitlines() if line.startswith(f" bool cmp{index} = ")] + assert len(lines) == 1, (compare_line, lines) + return lines[0].replace(f"cmp{index} ", "c ", 1) + + a, v = "params[0].w", "asuint(alu20)" + # With whole-dword selections every form matches its e32 comparison, and vcc/vcc_lo/s52 emit identical HLSL. + for kind in ("i32", "u32"): + for op in INT_PREDICATES: + whole_vcc = cmp_statement(f"v_cmp_{op}_{kind}_sdwa vcc_lo, s44, v18 src0_sel:DWORD src1_sel:DWORD") + whole_vcc64 = cmp_statement(f"v_cmp_{op}_{kind}_sdwa vcc, s44, v18 src0_sel:DWORD src1_sel:DWORD", "vcc") + whole_s52 = cmp_statement(f"v_cmp_{op}_{kind}_sdwa s52, s44, v18 src0_sel:DWORD src1_sel:DWORD", "s52") + assert whole_vcc == whole_vcc64 == whole_s52, (kind, op, whole_vcc, whole_vcc64, whole_s52) + plain = cmp_statement(f"v_cmp_{op}_{kind}_e32 vcc_lo, s44, v18") + if kind == "u32": + assert whole_vcc == plain, (kind, op, whole_vcc, plain) + else: + assert whole_vcc == plain.replace("asint(alu20)", f"asint({v})"), (kind, op, whole_vcc, plain) + assert cmp_statement("v_cmp_lt_i32_sdwa s52, sext(s44), v18 src0_sel:BYTE_0 src1_sel:BYTE_1", "s52") == ( + f" bool c = asint(asuint(asint({a} << 24u) >> 24u)) < asint((({v} >> 8u) & 0xffu));") + assert cmp_statement("v_cmp_lt_u32_sdwa s52, s44, sext(v18) src0_sel:WORD_0 src1_sel:BYTE_0", "s52") == ( + f" bool c = (({a} >> 0u) & 0xffffu) < asuint(asint({v} << 24u) >> 24u);") + + good = "v_cmp_lt_i32_sdwa vcc_lo, s44, v18 src0_sel:DWORD src1_sel:DWORD" + for bad, message in ( + (good.replace("s44,", "sext(s44,"), "Unsupported SDWA comparison operands"), + (good.replace("s44,", "s44),"), "Unsupported SDWA comparison operands"), + (good.replace("v18 ", "sext(v18 "), "Unsupported SDWA comparison operands"), + (good + " clamp", "Unsupported SDWA comparison operands"), + ("v_cmp_lt_i32_sdwa vcc_lo, s44, v18 src0_sel:DWORD", "Unsupported SDWA comparison operands"), + (good.replace("src0_sel:DWORD", "src0_sel:WORD_2"), "Unsupported SDWA comparison operands"), + (good.replace("vcc_lo", "s106"), "Scalar register out of range"), + (good.replace("vcc_lo", "s[52:53]"), "VOPC SDWA destination cannot be an SGPR pair"), + (good.replace("vcc_lo", "s[51:52]"), "VOPC SDWA destination cannot be an SGPR pair"), + (good.replace("vcc_lo", "s[105:106]"), "VOPC SDWA destination cannot be an SGPR pair"), + (good.replace("v18", "v0"), "Expected a numeric register"), + ): + expect_value_error(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad]), message) + for bad in ( + "v_cmp_lt_i32_sdwa vcc_lo, s44, v18 dst_sel:DWORD src0_sel:DWORD src1_sel:DWORD", + good.replace("s44,", "-s44,"), + good.replace("v18 ", "|v18| "), + good.replace("v18 ", "abs(v18) "), + good.replace("s44,", "sext(-s44),"), + good.replace("v18", "v106"), + ): + must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad])) + # A low16 VGPR source (undefined high half) is rejected as non-numeric, matching SDWA_INT. + expect_value_error( + translate_int, + uncompressed_export(["v_mov_b32_e32 v18, s45", "v_add_nc_u16 v24, s44, v18", + "v_cmp_lt_i32_sdwa vcc_lo, v24, v18 src0_sel:WORD_0 src1_sel:WORD_0"]), + "Expected a numeric register", + ) + # Pending sample source, pending scalar source/destination and non-entry mask are rejected. + base_prog = uncompressed_export(sdwa_int_compare_group("i32_lo")) + pos = base_prog.index("s_waitcnt vmcnt(0)") + must_reject(translate_int, base_prog[:pos] + ["v_cmp_eq_u32_sdwa vcc_lo, v12, v13 src0_sel:DWORD src1_sel:DWORD"] + base_prog[pos:]) + load = next(i for i, line in enumerate(base_prog) if line.startswith("s_buffer_load_dwordx4")) + pos = base_prog.index("s_waitcnt lgkmcnt(0)", load) + must_reject(translate_int, base_prog[:pos] + ["v_cmp_eq_i32_sdwa vcc_lo, s44, s45 src0_sel:DWORD src1_sel:DWORD"] + base_prog[pos:]) + must_reject(translate_int, base_prog[:pos] + ["v_cmp_eq_i32_sdwa s44, s46, s47 src0_sel:DWORD src1_sel:DWORD"] + base_prog[pos:]) + pos = base_prog.index("s_wqm_b64 exec, exec") + 1 + must_reject(translate_int, base_prog[:pos] + [good] + base_prog[pos:]) + # Remaining unlowered SDWA compare neighbours stay refused. + for bad in ( + "v_cmp_lt_i64_sdwa vcc_lo, s[44:45], v[18:19] src0_sel:DWORD src1_sel:DWORD", + "v_cmpx_lt_i32_sdwa s44, v18 src0_sel:DWORD src1_sel:DWORD", + ): + must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad])) + + def check_pack_int16_lowering(): """Static checks for v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 in the programs of pack_group().""" a = "params[0].w" @@ -18508,6 +18762,7 @@ def _check_controls_inline(directory): "check_cvt_int_f64_lowering", "check_cvt_f32_f64_lowering", "check_sdwa_integer_lowering", + "check_sdwa_int_compare_lowering", "check_sdwa_cmp_controls", "check_pack_int16_lowering", "check_sat_pack_u8_lowering", @@ -19159,6 +19414,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.extend((cvt_int_f64_static_binary_program(kind), translate_int) for kind in CVT_INT_F64_STATIC_ROWS) fixtures.append((cvt_f32_f64_binary_program(), translate_int)) fixtures.extend((uncompressed_export(sdwa_integer_group(group)), translate_int) for group in SDWA_INT_BODIES) + fixtures.extend((uncompressed_export(sdwa_int_compare_group(group)), translate_int) for group in SDWA_INT_CMP_BODIES) fixtures.extend((uncompressed_export(pack_group(group)), translate_int) for group in PACK_BODIES) fixtures.append((sat_pack_u8_program(), translate_int)) fixtures.append((uncompressed_export(pack_b32_group()), translate_int)) @@ -19840,6 +20096,36 @@ def check_sdwa_integer_draws(directory, compiler, renderer, backend): return 0 +def check_sdwa_int_compare_draws(directory, compiler, renderer, backend): + """Draw the supplemental per-predicate SDWA 32-bit integer comparison groups through integer readback. + + Each group of SDWA_INT_CMP_BODIES is compiled once and drawn in one renderer batch: every row of + SDWA_INT_CMP_ROWS with the right words, then one draw per SDWA_INT_CMP_WRONG entry with one channel + replaced by the word a wrong signedness, extension, selection or predicate would give, which must + report a mismatch. On a desktop GPU the draws establish that the translated shader computes the stated + words, not what the console does. + """ + source = directory / "sdwa_int_compare.hlsl" + shader = directory / "sdwa_int_compare.cso" + for group in SDWA_INT_CMP_BODIES: + source.write_text(translate_int(uncompressed_export(sdwa_int_compare_group(group))), encoding="ascii") + compile_shader(compiler, source, shader) + cases = [] + for row, words, status, _ in sdwa_int_compare_cases(group): + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *row) + case = directory / f"sdwa_int_compare-{len(cases)}.case" + case.write_bytes(bytes(constants) + struct.pack("<4I", *words) * 64 + b"\x01") + cases.append((case, status)) + try: + run_pixel_batch(renderer, backend, shader, cases) + except subprocess.CalledProcessError as error: + if error.returncode == 77: + return 77 + raise + return 0 + + def check_pack_int16_draws(directory, compiler, renderer, backend): """Draw v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 through the integer readback target and compare the words. @@ -25527,7 +25813,7 @@ def main(): directory = Path(tmp) if mode in ("draw-blend-scalar", "draw-predicate-rounding", "draw-integer-nc", "draw-e64-integer", "draw-bfm", "draw-brev", "draw-align", - "draw-sdwa-integer", "draw-plain-bitscan", "draw-vop3-ternary-int", "draw-swap", + "draw-sdwa-integer", "draw-sdwa-int-compare", "draw-plain-bitscan", "draw-vop3-ternary-int", "draw-swap", "draw-mac-legacy", "draw-carry-out", "draw-carry-in", "draw-mad64", "draw-cvt-f64-int", "draw-cvt-f64-f32", "draw-cvt-int-f64", "draw-cvt-f32-f64", "draw-pack-int16", "draw-pack-b32", "draw-sad", "draw-int16-vop3", "draw-int16-ternary", "draw-compressed-export", "draw-uncompressed-export", @@ -25557,6 +25843,7 @@ def main(): "draw-cvt-int-f64": check_cvt_int_f64_draws, "draw-cvt-f32-f64": check_cvt_f32_f64_draws, "draw-sdwa-integer": check_sdwa_integer_draws, + "draw-sdwa-int-compare": check_sdwa_int_compare_draws, "draw-bfm": check_bfm_draw, "draw-brev": check_brev_draw, "draw-align": check_align_draws, From 07c0828500c26a5bc33dc9ca0aeddd376f4d08f1 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 01:22:08 +0800 Subject: [PATCH 067/232] tests: report both dispatch widths and first differing compaction word (#2414) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 6 ++++++ tests/spirv_window/compaction.py | 34 +++++++++++++++++++++++--------- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 45e57a479..33231b875 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1308,6 +1308,12 @@ Run `ctest --preset dev --no-tests=error -R '^spirv_address_window_qword_' -V` f An optional experiment starts from the optional bridge fixture and compares a source-built subgroup compaction dispatch on a physical adapter and on WARP. The [SPIR-V module](../tests/spirv_window/compaction.spvasm) is one 64-thread group. It computes a sparse predicate from a 64-bit mask, ballots it with `OpGroupNonUniformBallot`, derives the first and last active lane and each lane's compaction rank, and writes the lane index, the observed lane width, the four ballot words, the active count, the selected lane's rank and the compacted payloads into separate output words. Compacted writes go to per-wave disjoint ranges keyed by rank, so the readback does not depend on workgroup or wave scheduling order; a repeated dispatch must be word-identical. The [direct desktop-HLSL control](../tests/spirv_window/compaction.hlsl) implements the same contract independently, so the bridge path and the direct path can be compared word for word. The CPU reference in `compaction.py` is recomputed with the lane width the shader observed, from an independent Python model of the ballot, first/last lanes, ranks and compaction. +If two dispatch readbacks differ, the fixture reports the first differing word and field, both hexadecimal +values, both observed lane widths and the number of differing words. This applies to a repeated dispatch +and to the bridge/direct comparison. For a negative control it computes the mutated reference at the width +reported by that control. A different width from the baseline still fails the test, with +`mutated_reference=exact` if all 328 control words match at that width. + Two deterministic masks are injected into the fixture constants. Every 4-bit nibble of both masks has one bit set, so every wave of every supported width (4, 8, 16, 32 and 64) has an active lane. The negative controls flip the predicate bit selection and shift the compaction write index by one; the first divergent word must be the wave-0 ballot word (65) and the first compacted payload (257) respectively, otherwise the test fails. The original SM 6.6 fixture was measured with SPIRV-Tools 2025.5 (`262bdab`), SPIRV-Cross `57e4efc`, DXC 1.9.2609.5 and MSVC 19.50 on Windows 11 build 26300, debug layer unavailable: the RTX 4060 (driver 32.0.16.2124) reports a 32-lane wave and WARP 10.0.26100.10068 reports a 4-lane wave (`D3D12_OPTIONS1.WaveLaneCountMin/Max` are 4/4). Each adapter matched its own width-aware CPU reference in all 328 words for both masks, on both the bridge and the direct-HLSL path, and both negative controls were caught at the predicted first word. The first difference between the adapters is output word 4 (the lane index each group thread observed): the RTX 4060 wrote 4 where WARP wrote 0, and 259 words differ in total. A CPU reference computed at width 32 reports the same word 4 as the first mismatch against the WARP readback, so the difference is the subgroup width the shader runs at, not WARP ballot or compaction arithmetic. Neither adapter exposes a 64-lane wave here, so an intra-wave 31/32 ballot-word boundary is a capability skip; the 31/32 mask-bit boundary is still exercised across the two 32-lane waves. diff --git a/tests/spirv_window/compaction.py b/tests/spirv_window/compaction.py index 1c2d4b31a..b98426114 100644 --- a/tests/spirv_window/compaction.py +++ b/tests/spirv_window/compaction.py @@ -204,6 +204,16 @@ def mismatches(observed, expected): return [index for index in range(WORD_COUNT) if observed[index] != expected[index]] +def require_matching_dispatches(context, first_name, first, second_name, second): + differences = mismatches(first, second) + if differences: + i = differences[0] + raise RuntimeError(f"{context}: first_mismatch=word={i} field={field(i)} " + f"{first_name}={first[i]:08x} {second_name}={second[i]:08x} " + f"{first_name}_width={first[WIDTH]} {second_name}_width={second[WIDTH]} " + f"mismatches={len(differences)}") + + def report_mismatches(observed, expected, problems): first = problems[0] print(f"first_mismatch=word={first} field={field(first)} " @@ -225,12 +235,18 @@ def check_source(label, adapter, mask_name, observed, width, mask): raise RuntimeError(f"{label} readback differs from the CPU reference at word {problems[0]}") -def run_control(adapter, observed, mask, width, name, mutation, predicted): +def run_control(adapter, observed, mask, baseline_width, name, mutation, predicted): + width = observed[WIDTH] + widths = f"baseline_width={baseline_width} control_width={width}" + if width not in SUPPORTED_WIDTHS: + raise RuntimeError(f"negative control {name} reported an unsupported subgroup width: {widths}") mutated = reference(mask, width, **mutation) unexpected = mismatches(observed, mutated) if unexpected: first = report_mismatches(observed, mutated, unexpected) - raise RuntimeError(f"negative control {name} differs from its mutated reference at word {first}") + raise RuntimeError(f"negative control {name} differs from its mutated reference at word {first}: {widths}") + if width != baseline_width: + raise RuntimeError(f"negative control {name} changed subgroup width: {widths} mutated_reference=exact") expected = reference(mask, width) problems = mismatches(observed, expected) @@ -267,14 +283,14 @@ def main(argv): raise RuntimeError(f"{label} reported an invalid subgroup width: {width}") check_source(label, adapter, mask_name, observed, width, mask) code, repeat = run(offscreen_check, adapter, dxil) - if repeat != observed: - raise RuntimeError(f"{label} readback changed between identical dispatches") + if code == SKIP: + raise RuntimeError(f"{label} {mask_name} repeat skipped after first dispatch at width {width}") + require_matching_dispatches(f"{label} readback changed between identical dispatches ({mask_name})", + "first", observed, "repeat", repeat) print(f"source={label} adapter={adapter} mask={mask_name} repeat=identical") results[label] = observed - if results["bridge"] != results["direct"]: - first = next(index for index in range(WORD_COUNT) - if results["bridge"][index] != results["direct"][index]) - raise RuntimeError(f"bridge and direct HLSL differ at word {first} ({field(first)})") + require_matching_dispatches(f"bridge and direct HLSL differ ({mask_name})", + "bridge", results["bridge"], "direct", results["direct"]) print(f"adapter={adapter} mask={mask_name} bridge_equals_direct=true") for control_name, (mutation, predicted) in CONTROLS.items(): control = emit_bridge(directory, tools, mask, **mutation) @@ -282,7 +298,7 @@ def main(argv): if code == SKIP: print(f"skip: {adapter} has no capable D3D12 adapter") return SKIP - run_control(adapter, observed, mask, width, control_name, mutation, predicted) + run_control(adapter, observed, mask, results["bridge"][WIDTH], control_name, mutation, predicted) print(f"subgroup compaction fixture passed on {adapter}") return 0 From 0b552e0cecd2d90582e7e97eb4659514ab833d27 Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 01:23:42 +0800 Subject: [PATCH 068/232] gpu: accept cached mesh depth-only pixel pipelines --- README.md | 1 + docs/experiments.md | 19 ++++++-- src/startup_stubs/d3d12_xs_device.cpp | 2 +- tests/startup_indirect_draw_indexed.cpp | 54 ++++++++++++++++------ tests/startup_indirect_mesh_cache.hlsl | 6 +++ tests/startup_indirect_mesh_cache_check.py | 30 +++++++----- 6 files changed, 80 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 39b610bf2..9f2fc036a 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | [Publish RGBA8 textures from completed archive records](docs/experiments.md#publishing-a-texture-from-each-complete-archive-record) | `ctest --preset release --no-tests=error -R '^cpu_archive_texture_publication$' -V` | | [Draw each archive record through D3D12](docs/experiments.md#drawing-each-archive-record-through-d3d12) | `ctest --preset dev --no-tests=error -R '^cpu_archive_texture_gpu_warp$' -V` | | Indexed mesh draw on WARP | `ctest --preset dev --no-tests=error -R '^mesh_indexed_draw_warp$' -V` | +| [Cached indirect mesh with a depth-only pixel stage](docs/experiments.md#gpu-written-indirect-mesh-dispatch-arguments) | `ctest --preset release --no-tests=error -R '^startup_indirect_mesh_cache_' -V` | | [Cached mesh draw with two queue writers](docs/experiments.md#cached-mesh-draw-with-two-queue-writers) | `ctest --preset release --no-tests=error -R '^startup_indirect_mesh_lease_(warp\|hardware)_dual' -V` | | [Amplification plus mesh pipeline on WARP](docs/experiments.md#amplification-and-mesh-pipeline-forms) | `ctest --preset dev --no-tests=error -R '^mesh_amplified_draw_warp$' -V` | | Textured mesh fallback at Shader Model 6.0 | `ctest --preset dev --no-tests=error -R '^mesh_textured_fallback_' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index a759c472e..947d9d116 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8852,14 +8852,23 @@ ctest --preset release --no-tests=error -R '^startup_indirect_mesh_cache_' -V The executable subset uses the original root and PSO state. It accepts root constants captured on the list, single-sample color attachments in exact format -order and a matching depth view when the stream declares one. A mesh stream -without a pixel stage requires zero color attachments, a writable matching -depth view and a physical adapter. The depth-only fixture removed the device -on WARP when dispatched, so the shim refuses it there. Untracked descriptor -tables, heap indexing, root descriptors, +order and a matching depth view when the stream declares one. A cached mesh +stream with zero color attachments requires a writable matching depth view. +It can include a depth-only pixel stage. The mesh-only depth path still +requires a physical adapter because its fixture removed the device on WARP. +Untracked descriptor tables, heap indexing, root descriptors, stencil state and depth bounds are refused. A shader accepted individually can still fail PSO creation or lack a consumable root binding. +The depth-only pixel fixture publishes a source-built mesh and pixel pair, binds +zero color targets and a writable D16 depth view, and uses the guest +`ExecuteIndirect` entry point. The pixel shader writes `SV_Depth = 0.25` on +the left half and discards the right half. Readback checks four `0x4000` depth +words and four unchanged `0xffff` clear words. A missing DSV format and a +zero depth-write mask each leave the cached PSO unavailable. Missing draw +attachments and incomplete root constants also leave depth clear. The MS-only +depth and three-color-target controls still run in the same test. + The fixture writes its group counts at byte offset four on the GPU and checks all eight pixels and the surrounding argument words. One group paints the left half. Two groups paint both halves. An omitted writer, a short argument diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 00f1b36fc..0b43dc27c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2080,7 +2080,7 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES offset += desktop_stream_size(type); } if (ok && cached_mesh && (untracked_depth_state || targets.NumRenderTargets > 8 || - (pixel ? !targets.NumRenderTargets : targets.NumRenderTargets || !depth_enabled || !depth_writes) || + (targets.NumRenderTargets ? !pixel : !depth_writes) || (depth_enabled && depth == DXGI_FORMAT_UNKNOWN) || std::any_of(targets.RTFormats, targets.RTFormats + std::min(targets.NumRenderTargets, 8), [](DXGI_FORMAT value) { return value == DXGI_FORMAT_UNKNOWN; }))) { diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 402cb2f0a..317ef8939 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -252,7 +252,7 @@ Method slot(IUnknown* object, unsigned index) } template -ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object, bool allow_missing = false) { // The guest forwards SetPrivateDataInterface with the underlying desktop argument. constexpr GUID key{0x18097577, 0x0a4a, 0x427c, {0xac, 0xd5, 0xac, 0x1d, 0x98, 0x90, 0x65, 0x85}}; @@ -261,6 +261,7 @@ ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* obj UINT bytes = sizeof(IUnknown*); const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); + if (allow_missing && (read == DXGI_ERROR_NOT_FOUND || (SUCCEEDED(read) && !stored))) return {}; check(read, "retrieve underlying object"); ComPtr result; check(stored.As(&result), "query underlying object"); @@ -356,10 +357,12 @@ struct alignas(void*) Subobject { T value{}; }; +enum class StreamDepth { none, writable, read_only }; + template ComPtr guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, D3D12_SHADER_BYTECODE source, D3D12_SHADER_BYTECODE pixel, - D3D12_SHADER_BYTECODE amplification = {}, UINT targets = 1, bool depth_only = false) + D3D12_SHADER_BYTECODE amplification = {}, UINT targets = 1, StreamDepth depth = StreamDepth::none) { struct { Subobject root; @@ -382,9 +385,10 @@ ComPtr guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, stream.raster.value.DepthClipEnable = TRUE; stream.depth.value.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; stream.depth.value.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; - if (depth_only) { + if (depth != StreamDepth::none) { stream.depth.value.DepthEnable = TRUE; - stream.depth.value.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + if (depth == StreamDepth::writable) + stream.depth.value.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; stream.depth.value.DepthFunc = D3D12_COMPARISON_FUNC_LESS; stream.dsv.value = DXGI_FORMAT_D16_UNORM; } @@ -680,7 +684,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ const TranslatedDrawFixture* translated = nullptr, bool upload_table = false, const ReplayCopy* replay = nullptr, bool upload_index = false, bool alias_index = false, UINT cached_mesh_targets = 0, bool cached_depth_only = false, bool restore_compute = false, - const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr) + const MeshLeaseDraw* leased = nullptr, Gate* gate = nullptr, bool cached_depth_pixel = false) { std::unique_lock recording; if (gate) recording = std::unique_lock(gate->state); @@ -1128,10 +1132,12 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ std::memcpy(&actual, static_cast(memory) + y * footprint.Footprint.RowPitch + x * pixel_bytes, pixel_bytes); const bool right_half = x >= width / 2; - const bool covered = cached_depth_only || (indexed ? right_half == draw_right : translated || !right_half || draw_right); + const bool covered = (cached_depth_only && !cached_depth_pixel) || + (indexed ? right_half == draw_right : translated || !right_half || draw_right); const bool drawn = writer && refusal == Refusal::none && covered; // overflowing_count draws nothing const std::uint32_t background = cached_depth_only ? 0xffff : black; - auto wanted = drawn ? (cached_depth_only ? 0u : + const auto depth_word = cached_depth_pixel ? 0x4000u : 0u; // D16_UNORM encodes SV_Depth 0.25. + auto wanted = drawn ? (cached_depth_only ? depth_word : translated ? (draw_right ? green : red) : (right_half ? green : red)) : background; if (leased) wanted = right_half ? leased->expected_right.value_or(leased->expected) : leased->expected; if (rect) { @@ -1469,6 +1475,11 @@ int main(int argc, char** argv) try wchar_t mesh86_dir[MAX_PATH]{}; if (mesh && GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_DIR", mesh86_dir, MAX_PATH)) { const bool depth_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH", nullptr, 0) != 0; + char depth_mode[16]{}; + const bool depth_pixel = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DEPTH_PIXEL", depth_mode, sizeof(depth_mode)) != 0; + auto depth = depth_only ? StreamDepth::writable : StreamDepth::none; + if (std::strcmp(depth_mode, "no-dsv") == 0) depth = StreamDepth::none; + if (std::strcmp(depth_mode, "read-only") == 0) depth = StreamDepth::read_only; const auto input = std::filesystem::path(mesh86_dir); const auto read_stage = [&](const char* name) { std::ifstream file(input / name, std::ios::binary); @@ -1476,7 +1487,7 @@ int main(int argc, char** argv) try return std::vector(std::istreambuf_iterator(file), {}); }; const auto ms = read_stage("source.ms.dxbc"); - const auto ps = depth_only ? std::vector{} : read_stage("source.ps.dxbc"); + const auto ps = depth_only && !depth_pixel ? std::vector{} : read_stage("source.ps.dxbc"); D3D12_ROOT_PARAMETER parameter{}; parameter.ParameterType = lease_fixture ? D3D12_ROOT_PARAMETER_TYPE_SRV : D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; parameter.ShaderVisibility = lease_fixture ? D3D12_SHADER_VISIBILITY_MESH : D3D12_SHADER_VISIBILITY_ALL; @@ -1490,7 +1501,7 @@ int main(int argc, char** argv) try check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create cached mesh signature"); const auto pso = guest_pipeline( guest.Get(), root.Get(), {ms.data(), ms.size()}, {ps.empty() ? nullptr : ps.data(), ps.size()}, - {}, depth_only ? 0 : lease_fixture ? 1 : 3, depth_only); + {}, depth_only ? 0 : lease_fixture ? 1 : 3, depth); if (dual_lease) { const bool init_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_INIT_ONLY", nullptr, 0) != 0; const auto initialize = writer_pipeline(device.Get(), writer.Get(), "initialize_mesh_record"); @@ -1551,13 +1562,26 @@ int main(int argc, char** argv) try } const auto verify = [&](Refusal control, const char* label) { return run(device.Get(), guest.Get(), writer.Get(), work.Get(), root.Get(), pso.Get(), signature.Get(), - DrawKind::mesh, false, control, label, nullptr, false, nullptr, false, false, depth_only ? 0 : 3, depth_only); + DrawKind::mesh, false, control, label, nullptr, false, nullptr, false, false, + depth_only ? 0 : 3, depth_only, false, nullptr, nullptr, depth_pixel); }; - if (!GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0)) - return verify(Refusal::mesh_pending, "unavailable cached mesh") ? 0 : 1; - return verify(Refusal::none, depth_only ? "cached mesh depth-only" : "cached translated mesh with three attachments") && - verify(Refusal::incomplete_mesh_constants, "cached mesh incomplete root constants") && - verify(Refusal::mesh_attachment_count, "cached mesh missing attachment") ? 0 : 1; + const bool ready = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0) != 0; + const bool invalid_depth_pixel = depth_pixel && depth != StreamDepth::writable; + if (depth_pixel) { + const bool native = bool(native_object(device.Get(), guest.Get(), pso.Get(), true)); + if (native != (ready && !invalid_depth_pixel)) { + std::fprintf(stderr, "depth-only pixel mode %s: unexpected native PSO presence %d\n", depth_mode, native); + return 1; + } + } + const bool ok = !ready || invalid_depth_pixel + ? verify(Refusal::mesh_pending, invalid_depth_pixel ? depth_mode : "unavailable cached mesh") + : verify(Refusal::none, depth_pixel ? "cached mesh depth-only pixel stage" : + depth_only ? "cached mesh depth-only" : "cached translated mesh with three attachments") && + verify(Refusal::incomplete_mesh_constants, "cached mesh incomplete root constants") && + verify(Refusal::mesh_attachment_count, "cached mesh missing attachment"); + if (depth_pixel) check_lease_debug(info.Get()); + return ok ? 0 : 1; } if (mesh && GetEnvironmentVariableA("X2W_MESH_REQUEST_FIXTURE", nullptr, 0)) { const auto cache = std::filesystem::current_path() / ("slot57-mesh-" + std::to_string(GetCurrentProcessId())); diff --git a/tests/startup_indirect_mesh_cache.hlsl b/tests/startup_indirect_mesh_cache.hlsl index 96a984e3c..283760b4f 100644 --- a/tests/startup_indirect_mesh_cache.hlsl +++ b/tests/startup_indirect_mesh_cache.hlsl @@ -20,3 +20,9 @@ PixelOutput main(PixelInput input) { output.first = output.second = output.third = float4(1, 0, 0, 1); return output; } + +float depth_only(PixelInput input) : SV_Depth { + if (any(gates != uint2(17, 29)) || input.side != 0 || input.position.x >= 2) + discard; + return 0.25; +} diff --git a/tests/startup_indirect_mesh_cache_check.py b/tests/startup_indirect_mesh_cache_check.py index 814b9e57a..73671bc78 100644 --- a/tests/startup_indirect_mesh_cache_check.py +++ b/tests/startup_indirect_mesh_cache_check.py @@ -25,14 +25,18 @@ def source_envelope(stage): return b'DXBC' + bytes(16) + struct.pack(' 1 else None) + lease[1] if len(lease) > 1 else None, depth_pixel) if result: sys.exit(result) From e4ad1fcf640ce6ad0c1a7447c0039dbd306b3872 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 01:24:25 +0800 Subject: [PATCH 069/232] tests: sample fractional MinLod one step below both observed mip transitions (#2412) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 9 ++++++++- tests/spirv_window/minlod_levels.py | 4 +++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 33231b875..9191a9178 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12043,7 +12043,7 @@ adapter, with zero D3D12 debug errors and warnings. The fractional case on the s must fail at pixel (0, 0). `spirv_minlod_fractional_*` retains the `ps_6_6` capability gate. It requires -mip 1 at 1.4375 and mip 3 at 3.75. At 1.5 and 1.5625 it checks for exact +mip 1 at 1.4375, mip 2 at 2 and mip 3 at 3.75. At 1.49609375, 1.5, 1.5625 and 1.99609375 it checks for exact readback of mip 1 or 2, then requires the translated and direct HLSL shaders to agree and reports the selected mip. The wrong-mip control at 1.5625 must reject mip 0 at pixel (0, 0) under either rounding rule. To test @@ -12052,6 +12052,13 @@ the normal arguments to `tests/spirv_window/minlod_fractional.py`. [Issue #809](https://github.com/R0Y00/Xbox2Windows/issues/809) records why the fractional point cases run separately. +On a 1/256 grid the UHD Graphics 770 (32.0.101.5973) last read mip 1 at 1.99609375 and first read +mip 2 at 2. On the RTX 4060 (32.0.15.9579) and in-box WARP (10.0.26100.9711) these adjacent +clamps were 1.49609375 and 1.5. The translated SPIR-V and direct HLSL matched all 64 pixels +at each sampled clamp (Windows 11 build 26100.9711, DXC 1.9.2609.5, debug layer unavailable). +Rounding the translated clamp to the nearest 1/128 changes the selected mip at 1.99609375 on the UHD +and at 1.49609375 on RTX and WARP. The four original fractional fixture inputs are all exact multiples of 1/128. + In separate `ps_6_0` and `ps_6_2` probes, in-box WARP 10.0.19041.5794 selected green mip 1 for a per-sample clamp of 1.5625 under point mip filtering. An explicit `SampleLevel` at the same LOD selected diff --git a/tests/spirv_window/minlod_levels.py b/tests/spirv_window/minlod_levels.py index 321cda2dd..aca3be983 100644 --- a/tests/spirv_window/minlod_levels.py +++ b/tests/spirv_window/minlod_levels.py @@ -18,7 +18,9 @@ # (clamp, accepted exact mips), listing nearest first. EXACT = (("0", (0,)), ("1", (1,)), ("2", (2,)), ("3", (3,))) -FRACTIONAL = (("1.4375", (1,)), ("1.5", (2, 1)), ("1.5625", (2, 1)), ("3.75", (3,))) +# Probe one 1/256 step below both observed point-filter transitions (1.5 and 2). +FRACTIONAL = (("1.4375", (1,)), ("1.49609375", (1, 2)), ("1.5", (2, 1)), ("1.5625", (2, 1)), + ("1.99609375", (2, 1)), ("2", (2,)), ("3.75", (3,))) WRONG = ("1", 2) # negative control: a clamp of 1 must not read mip 2 WRONG_FRACTIONAL = ("1.5625", 0) # neither observed rounding rule selects mip zero # Clamps for the mip-linear sampler: exact steps, a weight between 1/256 steps (1.3) From d3e3ea776e4fb32401f1eed3dc109fb477d9cbd8 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 01:25:50 +0800 Subject: [PATCH 070/232] tests: report each split sampler mismatch and detect omitted stores (#2406) * tests: report all differing split sampler readback words * tests: distinguish missing sampler writes from previous swap results * docs: record the split sampler comparison on Intel UHD 770 * tests: label the sampler validation summary separately from GPU readback --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 14 +++++++++++++ tests/sampler_index_control.hlsl | 10 +++++++-- tests/spirv_window/sampler.py | 27 +++++++++++++++++++++++-- tests/spirv_window/sampler_readback.cpp | 27 ++++++++++++++++++++----- 4 files changed, 69 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 9191a9178..06311de26 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -11409,6 +11409,12 @@ the first thread's descriptors. The same commit's RTX 5080 Laptop three orders. [Issue #1115](https://github.com/R0Y00/Xbox2Windows/issues/1115) has the reports. +The strict readback initializes the four output words to -1.0, -2.0, -3.0 and -4.0 before each dispatch. +It prints the zero-based index and expected and actual bits of every differing word, finishes all three +sampler orders and returns failure on any difference. In the missing-store control the shader omits both +comparison stores only when the ordinary pair is reversed (swap 1). Those results would otherwise carry +over from swap 0 and pass. Words 2 and 3 must instead retain the sentinels `c0400000` and `c0800000`. + Two controls written as direct HLSL on that adapter, compiled with the same DXC at `cs_6_0` and run through the same readback path, separate the shader from the descriptor layer. With the two bindings written out explicitly — `SamplerState @@ -11455,6 +11461,14 @@ Laptop (32.0.15.8142), the Intel Arc 140T (32.0.101.8132) and in-box WARP `0.25 0.25`/`0 0`, `0.75 0.75`/`0 0` and `0.25 0.25`/`1 1` on the Arc. An Arc rerun with fixed output indexing can isolate the sampler index. +On Intel UHD Graphics 770 (8086:a780, driver 32.0.101.5973), both the plain and renamed translated tables +differed at words 1 and 3 in each swap. Swaps 0, 1 and 2 produced `0.25 0.25 0 0`, `0.75 0.75 0 0` and +`0.25 0.25 1 1` with DXC 1.9.2609.5 and the pinned SPIR-V tools. The same shader binaries matched all four +words in every swap on RTX 4060 (32.0.15.9579) and in-box WARP (10.0.26100.9711). +The direct control with fixed dispatch-thread output indexing also distinguished the two index sources on +the UHD 770. Its dispatch-thread sampler index passed and its group sampler index reproduced all three rows. +The local D3D12 debug layer was unavailable. + ### Standalone comparison-sampler split in the SPIR-V bridge When one standalone SPIR-V sampler variable feeds both depth-comparison and ordinary diff --git a/tests/sampler_index_control.hlsl b/tests/sampler_index_control.hlsl index 5f175debc..27f06f5f4 100644 --- a/tests/sampler_index_control.hlsl +++ b/tests/sampler_index_control.hlsl @@ -1,4 +1,5 @@ -// One control shader, built twice, that differs only in the source of the sampler descriptor index. +// The two index controls differ only in the source of the sampler descriptor index. +// The split-sampler readback also uses this shader to check for missing output stores. // // The descriptor tables, the shader model, the output indexing and the three sampler swaps stay // identical between the two builds, so a difference in the readback can only come from the index: @@ -24,7 +25,12 @@ void main(uint3 dispatch_thread : SV_DispatchThreadID, uint3 group : SV_GroupID) #endif const uint output_index = dispatch_thread.x; const float2 uv = float2(1.25, 0.5); - results.Store(output_index * 4, asuint(depth_texture.SampleLevel(ordinary[sampler_index], uv, 0).x)); + const float sample_value = depth_texture.SampleLevel(ordinary[sampler_index], uv, 0).x; + results.Store(output_index * 4, asuint(sample_value)); +#if defined(OMIT_STORES_ON_ORDINARY_SWAP) + // Skip both comparison stores only when the ordinary sampler pair is reversed. + if (sample_value != (output_index == 0 ? 0.25 : 0.75)) return; +#endif results.Store((output_index + 2) * 4, asuint(depth_texture.SampleCmpLevelZero(comparison[sampler_index], uv, 0.5))); } diff --git a/tests/spirv_window/sampler.py b/tests/spirv_window/sampler.py index e091e90c8..fb07b4e14 100644 --- a/tests/spirv_window/sampler.py +++ b/tests/spirv_window/sampler.py @@ -281,6 +281,24 @@ def emit(folder, assembler, validator, cross, pixel=False, variant=None): return hlsl +def check_missing_stores(folder, compiler, renderer, adapter): + shader = Path(__file__).resolve().parents[1] / "sampler_index_control.hlsl" + dxil = folder / "missing-stores.dxil" + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-D", "OMIT_STORES_ON_ORDINARY_SWAP", + "-Fo", dxil, shader], check=True) + run = subprocess.run([renderer, adapter, "--spirv-sampler-views", dxil], capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr, end="") + return 77 + differences = [line for line in run.stdout.splitlines() if re.match(r"sampler swap \d+ word ", line)] + expected = ["sampler swap 1 word 2: expected=00000000 actual=c0400000", + "sampler swap 1 word 3: expected=3f800000 actual=c0800000"] + if run.returncode != 1 or differences != expected or "Split sampler readback mismatch" not in run.stderr: + raise AssertionError(f"missing comparison stores: exit {run.returncode}\n{run.stdout}{run.stderr}") + print("missing comparison stores detected:", *differences, sep="\n") + return 0 + + if __name__ == "__main__": status = 0 with tempfile.TemporaryDirectory() as tmp: @@ -300,6 +318,11 @@ def emit(folder, assembler, validator, cross, pixel=False, variant=None): dxil = hlsl.with_suffix(".dxil") subprocess.run([sys.argv[4], "-T", "cs_6_0", "-E", "main", "-Fo", dxil, hlsl], check=True) # The renamed table is read back exactly as the original is: same slots, same expected words. - status |= subprocess.run([sys.argv[5], sys.argv[6], "--spirv-sampler-views", dxil]).returncode - print("sampler views: plain and renamed tables and a level-of-detail query validated; controls passed") + print(f"sampler table: {variant or 'plain'}", flush=True) + result = subprocess.run([sys.argv[5], sys.argv[6], "--spirv-sampler-views", dxil]).returncode + if result and (result != 77 or status == 0): + status = result + if len(sys.argv) > 4 and status == 0: + status = check_missing_stores(Path(tmp), *sys.argv[4:7]) + print("sampler views: validated plain and renamed SPIR-V tables and the level-of-detail query") sys.exit(status) diff --git a/tests/spirv_window/sampler_readback.cpp b/tests/spirv_window/sampler_readback.cpp index ed0322632..4f5593df5 100644 --- a/tests/spirv_window/sampler_readback.cpp +++ b/tests/spirv_window/sampler_readback.cpp @@ -55,6 +55,11 @@ void check_sampler_views(ID3D12Device* device, const char* path) auto output = make_buffer(device, 16, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); auto readback = make_buffer(device, 16, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const std::array sentinels{-1.0f, -2.0f, -3.0f, -4.0f}; + auto reset = make_buffer(device, sizeof(sentinels), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + check(reset->Map(0, &empty, &mapped), "Map sampler fixture sentinels"); + std::memcpy(mapped, sentinels.data(), sizeof(sentinels)); + reset->Unmap(0, nullptr); D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; ComPtr views, samplers; check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)), "Create sampler fixture views"); @@ -74,6 +79,7 @@ void check_sampler_views(ID3D12Device* device, const char* path) UINT sampler_stride = device->GetDescriptorHandleIncrementSize(hd.Type); // Reverse each typed pair independently. The other operation must retain its results. + bool mismatched = false; for (UINT mask : {0u, 1u, 2u}) { auto handle = samplers->GetCPUDescriptorHandleForHeapStart(); for (UINT i = 0; i < 4; ++i) { @@ -91,15 +97,17 @@ void check_sampler_views(ID3D12Device* device, const char* path) ComputeCommands commands(device, pipeline.Get()); auto list = commands.list.Get(); if (mask == 0) { - transition(list, output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); D3D12_TEXTURE_COPY_LOCATION dst{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; D3D12_TEXTURE_COPY_LOCATION src{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; src.PlacedFootprint = footprint; list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); transition(list, texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - } else { - transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); } + // Each sampler swap must write its own four results, including values unchanged from the previous swap. + transition(list, output.Get(), mask == 0 ? D3D12_RESOURCE_STATE_COMMON : D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(output.Get(), 0, reset.Get(), 0, sizeof(sentinels)); + transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list->SetComputeRootSignature(root.Get()); ID3D12DescriptorHeap* heaps[] = {views.Get(), samplers.Get()}; list->SetDescriptorHeaps(2, heaps); @@ -125,7 +133,16 @@ void check_sampler_views(ID3D12Device* device, const char* path) readback->Unmap(0, &empty); std::printf("sampler swap %u: sample %g %g, comparison %g %g\n", mask, actual[0], actual[1], actual[2], actual[3]); - if (std::memcmp(actual.data(), expected.data(), sizeof(actual)) != 0) - throw std::runtime_error("Split sampler readback mismatch"); + for (size_t i = 0; i < expected.size(); ++i) { + UINT expected_word, actual_word; + std::memcpy(&expected_word, &expected[i], sizeof(expected_word)); + std::memcpy(&actual_word, &actual[i], sizeof(actual_word)); + if (actual_word != expected_word) { + std::printf("sampler swap %u word %zu: expected=%08x actual=%08x\n", + mask, i, expected_word, actual_word); + mismatched = true; + } + } } + if (mismatched) throw std::runtime_error("Split sampler readback mismatch"); } From 673d8e4ae941d9d991867d9d021caca1ca381d9f Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 01:29:22 +0800 Subject: [PATCH 071/232] tests: write raw UINT expectations for pixel copy and scratch readbacks (#2458) AI-assisted with Codex + GPT-6.2 Astra (xhigh). Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 6 ++++++ tests/pixel_aot_check.py | 35 ++++++++++++++++++++++------------- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index a2b867d35..bda0e0243 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7616,6 +7616,12 @@ A sampled program can also read attr0.z/w, as plain values from a P1/P2 pair in The integer readback profile declares the primary constant buffer as `uint4`. Integer consumers read its words directly, and floating-point consumers reinterpret the same bits. The byte layout is unchanged. The constant-index bitset draw checks copying `0xffffffff` through a VGPR and overwriting the destination with a floating-point result. On RTX 4060 Laptop (driver 32.0.16.1656), the previous float-typed load returned `0x7fffffff` for the immediate-index-31 copy; the integer load preserves `0xffffffff`. [Original report and independent reproduction](https://github.com/R0Y00/Xbox2Windows/pull/680#issuecomment-7099515543) +The integer-copy and flat-scratch fixtures write expected UINT texels directly as +four little-endian words. On Windows with CPython 3.11.9, converting the word +`0xff812345` to a Python float and back writes `0xffc12345`. The copy fixture +checks both signs and rejects changing just the quiet bit. The scratch fixtures +carry the same payloads through their loads and stores. + For normalized compressed whole-pair exports, the Python API can return `(source, mask)` via `return_write_mask=True`. The caller applies the returned RT0 mask (RG = `0x3`, BA = `0xC`, RGBA = `0xF`) in the PSO. Disabled components in the emitted `float4` are placeholders. The regular API still returns `float2` for its existing RG form and rejects a BA-only export. Because disassembly text can hide raw enable-bit differences, this API requires known whole-pair input. The draw fixture uses distinct clear sentinels and checks that a full PSO mask or incorrect enabled-channel values fail. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_compressed_export_(warp|hardware)$' -V`. The LLVM 15 binary fixture for #361 changes only the four EN bits of an assembled gfx1013 export and checks all 16 raw values. Reassembling the printed text keeps a packed pair when its first printed operand is enabled: raw 0x2 and 0xA reassemble as 0x0, and 0x5 reassembles as 0xF. Fully disabled source fields reassemble as zero. The normal lowering accepts 0x3, 0xC and 0xF through its explicit RT0-mask API. Other masks are rejected. These checks characterize the encoding and LLVM 15 behavior; they establish no gfx1013 channel-write semantics for non-pair masks. diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index e7e9ff37a..545dae486 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -441,6 +441,12 @@ def write_case(path, constants, pixels, *, nan_mask=None, integer_rt=False, extr return Path(path) +def write_uint_case(path, constants, words): + """Broadcast a raw uint4 to all 64 expected texels of a UINT readback case.""" + path.write_bytes(constants + struct.pack("<4I", *words) * 64 + b"\x01") + return path + + def check_container_selector(directory: Path, code: bytes, library: str | None = None) -> None: archive = directory / "same-name.rpf" records = [envelope(code, private_data=metadata) for metadata in (b"first", b"second")] @@ -19861,11 +19867,7 @@ def check_integer_readback_draw(directory, compiler, renderer, backend): """Round-trip v_mov_b32 bit copies bit-for-bit through the integer readback target.""" source = directory / "integer_readback.hlsl" shader = directory / "integer_readback.cso" - pass_case = directory / "integer_readback-pass.case" - corrupted_case = directory / "integer_readback-corrupted.case" words = (0x7fc00001, 0xffc00003, 0x00000001, 0x80000000) - constants = bytearray(256) - struct.pack_into(" Date: Wed, 25 Nov 2026 18:32:43 +0100 Subject: [PATCH 072/232] fix: keep exe_exit fixtures from ending a pe_map host process (#2465) --- tests/cpu/exe_exit.h | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/cpu/exe_exit.h b/tests/cpu/exe_exit.h index b304cd5c8..790d11d43 100644 --- a/tests/cpu/exe_exit.h +++ b/tests/cpu/exe_exit.h @@ -27,8 +27,16 @@ inline T at(const unsigned char* base, std::uint32_t offset) { return *reinterpret_cast(base + offset); } -// PEB::ImageBaseAddress. In a pe_map host it names the host EXE, not this image. -inline bool started_as_process() { return at(peb(), 0x10) == &__ImageBase; } +// True only when Windows started this image as the process EXE. PEB::ImageBaseAddress alone is not enough: +// pe_map_run_main reports the mapped EXE there (#1151), so under pe_run_package it also equals &__ImageBase. +// pe_map leaves the PEB loader list alone, so there the first InLoadOrderModuleList entry is the host EXE. +// Natively the process EXE is the first entry. Both must name this image. +inline bool started_as_process() { + if (at(peb(), 0x10) != &__ImageBase) return false; + const unsigned char* head = at(peb(), 0x18) + 0x10; + const unsigned char* first = at(head, 0); + return first != head && at(first, 0x30) == &__ImageBase; // DllBase +} inline bool same_ascii(const wchar_t* name, std::uint16_t bytes, const char* expected) { std::uint16_t i = 0; From df1c3e13a45a3c9a63d9e8dfa76e71a41484262d Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 01:45:00 +0800 Subject: [PATCH 073/232] gpu: bind proven mesh root reads from ordinary XMem pages --- CMakeLists.txt | 2 +- docs/experiments.md | 31 +++++ src/startup_stubs/d3d12_xs_device.cpp | 2 +- src/startup_stubs/mesh86_cache.inl | 2 +- src/startup_stubs/mesh_xmem_handoff.inl | 136 +++++++++------------ src/startup_stubs/xmem_section_buffer.h | 96 +++++++++++++++ tests/startup_indirect_draw_indexed.cpp | 74 ++++++++++- tests/startup_indirect_mesh_cache_check.py | 7 +- tests/startup_indirect_mesh_lease.inl | 35 +++++- 9 files changed, 298 insertions(+), 87 deletions(-) create mode 100644 src/startup_stubs/xmem_section_buffer.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 7161063c3..92f18123e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1508,7 +1508,7 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend}) set_tests_properties(startup_indirect_mesh_cache_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) - foreach(mode IN ITEMS ordered_control skip-wait dual dual-skip-srv dual-skip-argument dual-init-only) + foreach(mode IN ITEMS ordered_control skip-wait dual dual-skip-srv dual-skip-argument dual-init-only loose-root) set(test_name startup_indirect_mesh_lease_${backend}_${mode}) add_test(NAME ${test_name} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index bda0e0243..0e7281e39 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9634,6 +9634,37 @@ On Windows 10 22H2 build 19045.6456 with MSVC 19.44 x64, both Debug and Release Build the same `xg_swizzle_select_check` target and run both factory tests with `ctest --preset dev --no-tests=error -R '^xg_swizzle_factory' -V`. Repeat with the `release` preset. Both tests return 77 when the optional AddrLib dependency is absent. +## Cached mesh root SRV in ordinary XMem + +Set X2W_MESH86_LOOSE_XMEM_SRV=1 to allow a cached mesh pipeline's proved +raw t0/space0 Load(0) from an ordinary XMem address without a placed +buffer. The existing cache publication proof supplies the one-DWORD +shader read. The shim requires a 16-byte aligned address and a version 2 +section lease for the four bytes. It opens the pinned section view as a +desktop buffer while continuing to restrict the root read to the proved +DWORD. A placed resource stays on the existing submitted-writer path. + +The input is an ordinary CPU-backed XMem word. Synchronize CPU writes with +the command queue as for other CPU-visible GPU inputs. The shim revalidates +the original page identity at submission, serializes shared lease use +across queues, and keeps the physical page pinned through the completion +fence. Independently mapped physical aliases with competing GPU writers in +a different backing are outside this path. This opt-in does not establish +a view of a larger allocation or support arbitrary GPU root pointers. + +Build startup_indirect_draw_indexed using the existing mesh-agility +configuration above, then run: + + ctest --test-dir out/build/mesh-agility --no-tests=error -j1 -R '^startup_indirect_mesh_lease_(warp|hardware)_loose-root$' -V + +The fixture submits the cached mesh pipeline through slot 61 and reads +back its pixels. It checks a source-owned ordinary XMem page, a write +after Close, and a new recording after a remap at the same address. The +stale recording, unmapped page, untracked readable memory, misaligned SRV and registered resource +without a published writer must leave the target at its clear color. +Windows build 26200.9974 with D3D12 debug enabled passed on WARP +10.0.26100.9818 and RTX 4060 Laptop 32.0.16.1656. + ## Offscreen rendering and readback `offscreen_hardware` selects a high-performance adapter. `offscreen_warp` selects Microsoft's software rasterizer. Both draw the same DXC-compiled triangle to a 64×64 RGBA8 texture. After GPU completion the test reads the texture using its row pitch and compares colors and coverage pixel by pixel. Outputs are `triangle_hardware.bmp` and `triangle_warp.bmp` in the build directory. `ctest --preset dev -V` reports the adapter, driver, debug layer and pixel differences. Error or corruption messages from an available debug layer fail the test. diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0b43dc27c..d1691d9c0 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -64,7 +64,7 @@ #include "present_view_format.h" #include "state_block_blend.h" #include "title_heap_memory.h" -#include "xmem_section_lease.h" +#include "startup_stubs/xmem_section_buffer.h" #include #include #include diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index f481353a1..6eb329ddc 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -178,7 +178,7 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d const auto& parameter = (*params)[i]; if (parameter.type == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS && parameter.constants_count && parameter.constants_count <= 8) continue; - if (mesh_xmem_handoff() && srv_root == UINT_MAX && parameter.type == D3D12_ROOT_PARAMETER_TYPE_SRV && + if ((mesh_xmem_handoff() || mesh_xmem_loose_srv()) && srv_root == UINT_MAX && parameter.type == D3D12_ROOT_PARAMETER_TYPE_SRV && parameter.shader_register == 0 && parameter.space == 0 && !request.ps.empty()) { srv_root = i; continue; diff --git a/src/startup_stubs/mesh_xmem_handoff.inl b/src/startup_stubs/mesh_xmem_handoff.inl index ce80f92c9..2bad127b7 100644 --- a/src/startup_stubs/mesh_xmem_handoff.inl +++ b/src/startup_stubs/mesh_xmem_handoff.inl @@ -13,40 +13,24 @@ bool mesh_xmem_indirect() return enabled; } +bool mesh_xmem_loose_srv() +{ + static const bool enabled = x2w_local::env_on("X2W_MESH86_LOOSE_XMEM_SRV"); + return enabled; +} + bool mesh_xmem_tracking() { - return mesh_xmem_handoff() || mesh_xmem_indirect(); + return mesh_xmem_handoff() || mesh_xmem_indirect() || mesh_xmem_loose_srv(); } -struct MeshXMemLease { - using Release = BOOL (WINAPI*)(UINT, ULONG64); - X2WXMemSectionLease lease{}; - Release release{}; - X2WXMemMatchSection match{}; +struct MeshXMemLease : x2w_startup::XMemSectionBuffer { Wrapper* owner{}; Wrapper* device{}; u64 offset{}, address{}, bytes{}; - void* view{}; - x2w_startup::ComPtr heap; - x2w_startup::ComPtr buffer; x2w_startup::ComPtr last_access; ID3D12CommandQueue* last_queue{}; bool untracked{}; - - ~MeshXMemLease() - { - buffer.Reset(); - heap.Reset(); - if (lease.section) CloseHandle(lease.section); - // A view that could not be removed still has access to the slots. - if ((!view || UnmapViewOfFile(view)) && lease.id) - release(x2w_xmem_section_lease_version, lease.id); - } - - bool matches(u64 candidate) const - { - return match(x2w_xmem_section_lease_version, lease.id, lease.first_byte, candidate, bytes); - } }; struct MeshXMemRecording { @@ -73,6 +57,7 @@ std::mutex mesh_xmem_mutex; // The root word and the dispatch record each have one active lease. constexpr size_t mesh_xmem_srv_index = 0, mesh_xmem_argument_index = 1; std::array mesh_xmem_publications; +std::vector> mesh_xmem_loose_views; std::unordered_map mesh_xmem_recordings; std::vector mesh_xmem_flights; bool mesh_xmem_tracking_failed; @@ -145,54 +130,43 @@ bool mesh_xmem_windows_disjoint(const X2WXMemSectionLease& one, const X2WXMemSec } std::shared_ptr open_mesh_xmem_lease(Wrapper* device, Wrapper* owner, - u64 offset, u64 address, u64 bytes, const MeshXMemLease* other) + u64 offset, u64 address, u64 bytes) { - using Pin = BOOL (WINAPI*)(UINT, ULONG_PTR, SIZE_T, X2WXMemSectionLease*, SIZE_T); - HMODULE xmem = nullptr; - if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, L"xmem.dll", &xmem)) return {}; - const auto pin = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_lease_section")); - const auto release = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_release_section")); - const auto match = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_match_section")); - if (!pin || !release || !match) return {}; - D3D12_FEATURE_DATA_EXISTING_HEAPS feature{}; - x2w_startup::ComPtr desktop; - if (FAILED(device_of(device)->QueryInterface(IID_PPV_ARGS(&desktop)))) return {}; - const auto check_heaps = [&] { -#if defined(X2W_MESH_XMEM_AGILITY_620) && defined(__ID3D12Device16_INTERFACE_DEFINED__) - x2w_startup::ComPtr versioned; - if (SUCCEEDED(desktop.As(&versioned))) - return versioned->CheckFeatureSupport1(D3D12_FEATURE_EXISTING_HEAPS, &feature, sizeof(feature), 620); -#endif - return desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &feature, sizeof(feature)); - }; - if (FAILED(check_heaps()) || !feature.Supported) return {}; auto result = std::make_shared(); result->owner = owner; result->device = device; result->address = address; result->offset = offset; result->bytes = bytes; - result->release = release; - result->match = match; - auto& lease = result->lease; - if (!pin(x2w_xmem_section_lease_version, address, bytes, &lease, sizeof(lease))) return {}; - // The desktop buffers transition independently, so their state changes - // must never cover the same physical section bytes. Compare the pinned - // sections directly, since the guest addresses can be remapped here. - if (other && !mesh_xmem_windows_disjoint(lease, other->lease)) return {}; - result->view = MapViewOfFile(lease.section, FILE_MAP_WRITE, static_cast(lease.section_offset >> 32), - static_cast(lease.section_offset), static_cast(lease.window_bytes)); - if (!result->view || FAILED(desktop->OpenExistingHeapFromAddress(result->view, IID_PPV_ARGS(&result->heap)))) - return {}; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = lease.window_bytes; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; - if (FAILED(desktop->CreatePlacedResource(result->heap.Get(), 0, &desc, D3D12_RESOURCE_STATE_COMMON, - nullptr, IID_PPV_ARGS(&result->buffer)))) return {}; - return result->matches(address) ? result : nullptr; + const UINT version = owner ? x2w_xmem_section_lease_version : x2w_xmem_single_page_lease_version; + const auto unused_window = [&](const X2WXMemSectionLease& lease) { + // Do not transition two different desktop resources over the same + // section bytes. The virtual addresses can be different XMem aliases. + for (const auto& publication : mesh_xmem_publications) + if (const auto other = publication.active.lock(); other && !mesh_xmem_windows_disjoint(lease, other->lease)) + return false; + for (const auto& loose : mesh_xmem_loose_views) + if (const auto other = loose.lock(); other && !mesh_xmem_windows_disjoint(lease, other->lease)) + return false; + return true; + }; + return result->open(device_of(device), version, address, bytes, unused_window) ? result : nullptr; +} + +// Called with mesh_xmem_mutex held after the caller established there is no +// registered placement covering or overlapping the requested word. +std::shared_ptr loose_mesh_xmem_srv(Wrapper* device, u64 address, u64 bytes) +{ + mesh_xmem_loose_views.erase(std::remove_if(mesh_xmem_loose_views.begin(), mesh_xmem_loose_views.end(), + [](const auto& view) { return view.expired(); }), mesh_xmem_loose_views.end()); + for (const auto& known : mesh_xmem_loose_views) { + if (const auto view = known.lock(); view && view->device == device && view->address == address && + view->bytes == bytes && !view->untracked && view->matches(address)) + return view; + } + auto view = open_mesh_xmem_lease(device, nullptr, 0, address, bytes); + if (view) mesh_xmem_loose_views.push_back(view); + return view; } size_t mesh_xmem_index(u64 bytes) @@ -211,7 +185,7 @@ bool mesh_xmem_write_overlaps(const MeshXMemRecording::Write& write, const MeshX void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, ID3D12Resource* source = nullptr, u64 source_offset = 0) { - if (!mesh_xmem_tracking() || !owner || !owner->own().title_memory) return; + if ((!mesh_xmem_handoff() && !mesh_xmem_indirect()) || !owner || !owner->own().title_memory) return; const auto* info = resource_info(owner); if (!info || info->placement != Placement::copied_buffer || info->placement_device != list->own().list_device || info->console.Flags != D3D12_RESOURCE_FLAG_NONE) @@ -236,9 +210,7 @@ void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, auto& publication = mesh_xmem_publications[index]; auto lease = publication.active.lock(); if (!lease) { - const auto other_index = index == mesh_xmem_srv_index ? mesh_xmem_argument_index : mesh_xmem_srv_index; - const auto other = mesh_xmem_publications[other_index].active.lock(); - lease = open_mesh_xmem_lease(list->own().list_device, owner, offset, address, bytes, other.get()); + lease = open_mesh_xmem_lease(list->own().list_device, owner, offset, address, bytes); if (!lease) return; publication.active = lease; } @@ -281,14 +253,28 @@ const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t co if (read.bytes != sizeof(UINT) && read.bytes != sizeof(D3D12_DISPATCH_MESH_ARGUMENTS)) return "mesh XMem read has an unsupported size"; const auto index = mesh_xmem_index(read.bytes); - const auto& lease = mesh_xmem_publications[index].ready; - if (mesh_xmem_tracking_failed || !lease || lease->device != list->own().list_device || lease->bytes != read.bytes) - return "mesh XMem read has no submitted writer for the required size"; + if (mesh_xmem_tracking_failed) + return "mesh XMem read tracking is unavailable"; const u64 alignment = index == mesh_xmem_srv_index ? D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT : sizeof(UINT); if (!read.address || read.address % alignment) return "mesh XMem read address is missing or misaligned"; const auto placed = placed_buffer_range(list->own().list_device, read.address, read.bytes); - if (!lease->matches(read.address) || placed.reject || placed.owner != lease->owner) + if (placed.reject) + return "mesh XMem read does not match the writer's leased page and byte range"; + auto lease = mesh_xmem_publications[index].ready; + if (!placed.owner && index == mesh_xmem_srv_index && mesh_xmem_loose_srv()) { + // The cached mesh PSO has already proved this raw root SRV reads + // one DWORD at byte zero. The section may hold unrelated data. + try { + lease = loose_mesh_xmem_srv(list->own().list_device, read.address, read.bytes); + } catch (const std::bad_alloc&) { + return "mesh XMem loose root SRV allocation failed"; + } + if (!lease) return "mesh XMem loose root SRV has no usable single-page lease"; + } + if (!lease || lease->device != list->own().list_device || lease->bytes != read.bytes) + return "mesh XMem read has no submitted writer for the required size"; + if (placed.owner != lease->owner || !lease->matches(read.address)) return "mesh XMem read does not match the writer's leased page and byte range"; if (verified[index].lease) return "mesh XMem draw repeats the same input kind"; @@ -318,7 +304,7 @@ const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t co static LONG reports; if (first_calls(reports, 16)) log("x2w-render mesh XMem %s: lease %llu section page +0x%llx byte +0x%llx, %llu bytes", - index == mesh_xmem_srv_index ? "root bind" : "indirect bind", + !lease->owner ? "loose root bind" : index == mesh_xmem_srv_index ? "root bind" : "indirect bind", lease->lease.id, lease->lease.section_offset, lease->lease.first_byte, read.bytes); } } catch (const std::bad_alloc&) { @@ -373,7 +359,7 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l const u64 address = read.lease ? read.address : lease->address; const auto placed = placed_buffer_range(lease->device, address, lease->bytes); if (mesh_xmem_tracking_failed || lease->untracked || placed.reject || placed.owner != lease->owner || - !lease->matches(address) || (read.lease && mesh_xmem_publications[i].ready != lease)) { + !lease->matches(address) || (read.lease && lease->owner && mesh_xmem_publications[i].ready != lease)) { log("x2w-render mesh XMem submit refused: writer or live page identity changed"); return; } diff --git a/src/startup_stubs/xmem_section_buffer.h b/src/startup_stubs/xmem_section_buffer.h new file mode 100644 index 000000000..43e40db92 --- /dev/null +++ b/src/startup_stubs/xmem_section_buffer.h @@ -0,0 +1,96 @@ +#pragma once + +#include "xmem_section_lease.h" + +#include +#include + +namespace x2w_startup { + +// The caller supplies the exact shader-accessible range and holds this object +// through the last GPU consumer. A section window is backing, never a proof +// that its other bytes may be accessed by that shader. +class XMemSectionBuffer { +public: + XMemSectionBuffer() = default; + XMemSectionBuffer(const XMemSectionBuffer&) = delete; + XMemSectionBuffer& operator=(const XMemSectionBuffer&) = delete; + ~XMemSectionBuffer() + { + buffer.Reset(); + heap_.Reset(); + if (lease.section) CloseHandle(lease.section); + // A view that could not be removed still has access to the slots. + if ((!view_ || UnmapViewOfFile(view_)) && lease.id) release_(version_, lease.id); + } + + bool matches(std::uint64_t candidate) const + { + return match_ && match_(version_, lease.id, lease.first_byte, candidate, bytes_); + } + + D3D12_GPU_VIRTUAL_ADDRESS gpu_address() const + { + const auto base = buffer ? buffer->GetGPUVirtualAddress() : 0; + return base && lease.first_byte <= UINT64_MAX - base ? base + lease.first_byte : 0; + } + + // Failure is final for the instance. The destructor releases any backing + // acquired on the way. The overlap predicate sees the physical lease + // before D3D12 maps it as a resource. + template + bool open(ID3D12Device* device, UINT version, std::uint64_t address, std::uint64_t bytes, Accept accept) + { + if (lease.id || !device || !address || !bytes || bytes > SIZE_MAX || bytes > UINT64_MAX - address) + return false; + HMODULE xmem{}; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, L"xmem.dll", &xmem)) return false; + using Pin = BOOL (WINAPI*)(UINT, ULONG_PTR, SIZE_T, X2WXMemSectionLease*, SIZE_T); + const auto pin = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_lease_section")); + release_ = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_release_section")); + match_ = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_match_section")); + if (!pin || !release_ || !match_) return false; + + Microsoft::WRL::ComPtr desktop; + if (FAILED(device->QueryInterface(IID_PPV_ARGS(&desktop)))) return false; + D3D12_FEATURE_DATA_EXISTING_HEAPS feature{}; + const auto check_heaps = [&] { +#if defined(X2W_MESH_XMEM_AGILITY_620) && defined(__ID3D12Device16_INTERFACE_DEFINED__) + Microsoft::WRL::ComPtr versioned; + if (SUCCEEDED(desktop.As(&versioned))) + return versioned->CheckFeatureSupport1(D3D12_FEATURE_EXISTING_HEAPS, &feature, sizeof(feature), 620); +#endif + return desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &feature, sizeof(feature)); + }; + if (FAILED(check_heaps()) || !feature.Supported) return false; + version_ = version; + bytes_ = bytes; + if (!pin(version_, address, static_cast(bytes), &lease, sizeof(lease)) || + !lease.section || !lease.id || !lease.window_bytes || lease.window_bytes > SIZE_MAX || + lease.first_byte > lease.window_bytes || bytes > lease.window_bytes - lease.first_byte || + lease.window_bytes > UINT64_MAX - lease.section_offset || !accept(lease)) return false; + view_ = MapViewOfFile(lease.section, FILE_MAP_WRITE, static_cast(lease.section_offset >> 32), + static_cast(lease.section_offset), static_cast(lease.window_bytes)); + if (!view_ || FAILED(desktop->OpenExistingHeapFromAddress(view_, IID_PPV_ARGS(&heap_)))) return false; + const D3D12_RESOURCE_DESC desc{ + D3D12_RESOURCE_DIMENSION_BUFFER, 0, lease.window_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, + {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER + }; + return SUCCEEDED(desktop->CreatePlacedResource(heap_.Get(), 0, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&buffer))) && gpu_address() && matches(address); + } + + X2WXMemSectionLease lease{}; + Microsoft::WRL::ComPtr buffer; + +private: + using Release = BOOL (WINAPI*)(UINT, ULONG64); + Release release_{}; + X2WXMemMatchSection match_{}; + UINT version_{}; + std::uint64_t bytes_{}; + void* view_{}; + Microsoft::WRL::ComPtr heap_; +}; + +} // namespace x2w_startup diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 317ef8939..6da1a6620 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1370,7 +1370,11 @@ int main(int argc, char** argv) try const bool lease_fixture = GetEnvironmentVariableW(L"X2W_MESH86_FIXTURE_XMEM", lease_xmem, MAX_PATH) != 0; const bool dual_lease = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_DUAL", nullptr, 0) != 0; if (dual_lease) check(lease_fixture && !lease_arguments ? S_OK : E_FAIL, "configure combined mesh XMem fixture"); - if (lease_fixture && !lease_arguments) + const bool loose_root = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_LOOSE_ROOT", nullptr, 0) != 0; + if (loose_root) + check(lease_fixture && SetEnvironmentVariableA("X2W_MESH86_LOOSE_XMEM_SRV", "1") && + SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", nullptr) ? S_OK : E_FAIL, "enable loose XMem root SRV"); + else if (lease_fixture && !lease_arguments) check(SetEnvironmentVariableA("X2W_MESH86_XMEM_SRV", "1") ? S_OK : E_FAIL, "enable mesh XMem handoff"); const bool console_mesh = argc == 3 && std::strcmp(argv[2], "mesh-console") == 0; const bool desktop_as = argc == 3 && std::strcmp(argv[2], "mesh-amplified") == 0; @@ -1426,7 +1430,7 @@ int main(int argc, char** argv) try wchar_t directory[MAX_PATH]; if (!GetTempPathW(MAX_PATH, directory)) return 4; const std::wstring log_path = std::wstring(directory) + L"x2w_indirect_counts_" + std::to_wstring(GetCurrentProcessId()) + L".log"; - if (indexed || lease_arguments || dual_lease || refusal_census) { + if (indexed || lease_arguments || dual_lease || loose_root || refusal_census) { DeleteFileW(log_path.c_str()); SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); SetEnvironmentVariableA("X2W_PRESENT_SIGNATURE_EVERY", "0"); @@ -1511,6 +1515,72 @@ int main(int argc, char** argv) try writer.Get(), initialize.Get(), append.Get(), root.Get(), pso.Get(), signature.Get()) ? 0 : 1; } const auto work = writer_pipeline(device.Get(), writer.Get(), "write_one_mesh_group"); + if (loose_root) { + const bool ready = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_READY", nullptr, 0) != 0; + MeshLeaseWriter source(device.Get(), guest.Get(), lease_xmem, nullptr, nullptr, nullptr, nullptr, true); + const auto queue = source.create_queue(D3D12_COMMAND_LIST_TYPE_DIRECT); + const auto verify = [&](const MeshLeaseDraw& draw, const char* label) { + return run(device.Get(), guest.Get(), writer.Get(), work.Get(), root.Get(), pso.Get(), signature.Get(), + DrawKind::mesh, false, Refusal::none, label, nullptr, false, nullptr, false, false, 1, false, false, + &draw); + }; + if (!ready) { + const bool ok = verify({source.address(), queue.Get(), black}, "loose mesh requires shader proof"); + source.free_original(); + return ok ? 0 : 1; + } + if (!verify({source.address(), queue.Get(), green}, "loose mesh reads ordinary XMem root SRV") || + !verify({source.address() + 4, queue.Get(), black}, "loose mesh refuses misaligned root") || + !verify({source.address() + 2 * MeshLeaseWriter::page, queue.Get(), black}, "loose mesh refuses unmapped page")) + return 1; + const std::unique_ptr unrelated( + VirtualAlloc(nullptr, MeshLeaseWriter::page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!unrelated || !verify({reinterpret_cast(unrelated.get()), queue.Get(), black}, + "loose mesh refuses readable untracked memory")) return 1; + const auto registered_desc = D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_BUFFER, 0, MeshLeaseWriter::page, + 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + using Place = HRESULT (WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + ComPtr placed; + check(slot(guest.Get(), 133)(guest.Get(), source.cpu, ®istered_desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, __uuidof(ID3D12Resource), reinterpret_cast(placed.GetAddressOf())), "register overlapping buffer"); + if (!verify({source.address(), queue.Get(), black}, "loose mesh refuses registered resource without a publisher")) return 1; + placed.Reset(); + + MeshLeaseDraw late{source.address(), queue.Get(), red}; + late.before_submit = [&] { std::memcpy(source.cpu + source.record_offset, &red, sizeof(red)); }; + if (!verify(late, "loose mesh sees a CPU write after Close")) return 1; + // The queue rejects the entire stale recording, so use already + // initialized external DispatchMesh arguments for this control. + PlacedBuffer args(device.Get(), guest.Get(), sizeof(MeshLeaseWriter::old_groups), D3D12_RESOURCE_FLAG_NONE); + const auto upload = make_buffer(device.Get(), sizeof(MeshLeaseWriter::old_groups), D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ); + const D3D12_RANGE empty{}; + void* memory{}; + check(upload->Map(0, &empty, &memory), "map loose-root dispatch arguments"); + std::memcpy(memory, MeshLeaseWriter::old_groups.data(), sizeof(MeshLeaseWriter::old_groups)); + upload->Unmap(0, nullptr); + ComputeCommands seed(device.Get(), nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + seed.list->CopyBufferRegion(args.native.Get(), 0, upload.Get(), 0, sizeof(MeshLeaseWriter::old_groups)); + seed.submit_and_wait(device.Get()); + MeshLeaseDraw remap{source.address(), queue.Get(), black}; + remap.argument = args.wrapped.Get(); + remap.before_submit = [&] { source.replace_loose_page(); }; + if (!verify(remap, "loose mesh refuses a remapped page on submit") || + !verify({source.address(), queue.Get(), green}, "new loose mesh recording reads replacement page")) return 1; + source.free_original(); + check_lease_debug(info.Get()); + + std::ifstream log{std::filesystem::path(log_path)}; + const std::string lines{std::istreambuf_iterator(log), {}}; + log.close(); + DeleteFileW(log_path.c_str()); + check(lines.find("mesh XMem loose root bind") != std::string::npos && + lines.find("mesh XMem submit refused: writer or live page identity changed") != std::string::npos && + lines.find("mesh XMem loose root SRV has no usable single-page lease") != std::string::npos && + lines.find("mesh XMem read address is missing or misaligned") != std::string::npos ? S_OK : E_FAIL, + "observe loose binding, stale submission and invalid range refusals"); + return 0; + } if (lease_fixture) { MeshLeaseWriter source(device.Get(), guest.Get(), lease_xmem); const auto queue = source.create_queue(D3D12_COMMAND_LIST_TYPE_DIRECT); diff --git a/tests/startup_indirect_mesh_cache_check.py b/tests/startup_indirect_mesh_cache_check.py index 73671bc78..884155332 100644 --- a/tests/startup_indirect_mesh_cache_check.py +++ b/tests/startup_indirect_mesh_cache_check.py @@ -41,9 +41,12 @@ def run(dxc, fixture, backend, work, depth_only, lease_xmem=None, mode=None, dep environment['X2W_MESH86_FIXTURE_XMEM'] = str(lease_xmem) for flag in ('X2W_TEST_MESH_XMEM_SKIP_WAIT', 'X2W_TEST_MESH_XMEM_SKIP_SRV_WAIT', 'X2W_TEST_MESH_XMEM_SKIP_ARGUMENT_WAIT', 'X2W_MESH86_FIXTURE_DUAL', - 'X2W_MESH86_FIXTURE_INIT_ONLY', 'X2W_MESH_INDIRECT_XMEM'): + 'X2W_MESH86_FIXTURE_INIT_ONLY', 'X2W_MESH_INDIRECT_XMEM', + 'X2W_MESH86_FIXTURE_LOOSE_ROOT'): environment.pop(flag, None) - if mode == 'skip-wait': + if mode == 'loose-root': + environment['X2W_MESH86_FIXTURE_LOOSE_ROOT'] = '1' + elif mode == 'skip-wait': environment['X2W_TEST_MESH_XMEM_SKIP_WAIT'] = '1' elif mode in ('dual', 'dual-skip-srv', 'dual-skip-argument', 'dual-init-only'): environment.update(X2W_MESH86_FIXTURE_DUAL='1', X2W_MESH_INDIRECT_XMEM='1') diff --git a/tests/startup_indirect_mesh_lease.inl b/tests/startup_indirect_mesh_lease.inl index 7f5fb532a..c31af6dc8 100644 --- a/tests/startup_indirect_mesh_lease.inl +++ b/tests/startup_indirect_mesh_lease.inl @@ -16,6 +16,7 @@ struct MeshLeaseWriter { const UINT64 record_bytes; const UINT64 record_offset; const UINT expected_group_x; + const bool loose; Allocate alloc; Map map; Free free_pages; @@ -40,14 +41,24 @@ struct MeshLeaseWriter { MeshLeaseWriter(ID3D12Device* d, ID3D12Device* g, const wchar_t* dll, ID3D12RootSignature* writer_root = nullptr, ID3D12PipelineState* writer = nullptr, - MeshLeaseWriter* mirror_owner = nullptr, ID3D12PipelineState* append = nullptr) + MeshLeaseWriter* mirror_owner = nullptr, ID3D12PipelineState* append = nullptr, bool loose_root = false) : device(d), guest(g), xmem(LoadLibraryW(dll)), record_bytes(writer ? sizeof(old_groups) : sizeof(red)), record_offset(mirror_owner ? 0x80 : word_offset), expected_group_x(mirror_owner && !append ? 0 : new_groups[0]), - alloc(function("XMemAllocatePhysicalPages")), + loose(loose_root), alloc(function("XMemAllocatePhysicalPages")), map(function("XMemMapPhysicalPagesScatter")), free_pages(function("XMemFreePhysicalPages")), pin(function("x2w_xmem_lease_section")), unpin(function("x2w_xmem_release_section")) { - if (mirror_owner) { + if (loose) { + check(SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1") && SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1") ? S_OK : E_FAIL, "enable shared XMem pages"); + const auto reserve = function("XMemVirtualAlloc"); + cpu = static_cast(reserve(nullptr, 4 * page, 0x20402000, 0x21, PAGE_READWRITE)); + mirror = reinterpret_cast(cpu); + ULONG_PTR first_count = 1, second_count = 1; + void* const addresses[]{cpu, cpu ? cpu + page : nullptr}; + check(cpu && alloc(0x280, &first_count, original) && first_count == 1 && + alloc(0x280, &second_count, original + 1) && second_count == 1 && map(addresses, 2, original) ? S_OK : E_FAIL, + "map ordinary CPU XMem pages"); + } else if (mirror_owner) { cpu = mirror_owner->cpu + page; mirror = mirror_owner->mirror + page; } else { @@ -76,6 +87,7 @@ struct MeshLeaseWriter { std::memcpy(cpu + page + record_offset, &green, sizeof(green)); } published_page = inspect(address()); + if (loose) return; const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, writer && !mirror_owner ? 2 * page : page, 1, 1, 1, DXGI_FORMAT_UNKNOWN, @@ -152,10 +164,11 @@ struct MeshLeaseWriter { std::pair inspect(UINT64 guest_address) { X2WXMemSectionLease lease{}; - check(pin(x2w_xmem_section_lease_version, guest_address, record_bytes, &lease, sizeof(lease)) ? S_OK : E_FAIL, + const UINT version = loose ? x2w_xmem_single_page_lease_version : x2w_xmem_section_lease_version; + check(pin(version, guest_address, record_bytes, &lease, sizeof(lease)) ? S_OK : E_FAIL, "inspect XMem page"); CloseHandle(lease.section); - check(unpin(x2w_xmem_section_lease_version, lease.id) ? S_OK : E_FAIL, "release inspection lease"); + check(unpin(version, lease.id) ? S_OK : E_FAIL, "release inspection lease"); return {lease.section_offset, lease.first_byte}; } @@ -217,6 +230,18 @@ struct MeshLeaseWriter { check(map(addresses, 2, empty) && free_pages(2, original) ? S_OK : E_FAIL, "release the original XMem grant"); } + void replace_loose_page() + { + void* const address = cpu; + const ULONG_PTR empty{}; + ULONG_PTR replacement{}, count = 1; + check(map(&address, 1, &empty) && alloc(0x280, &count, &replacement) && count == 1 && + map(&address, 1, &replacement) && free_pages(1, original) ? S_OK : E_FAIL, + "replace the mapped generation at the same address"); + original[0] = replacement; + std::memcpy(cpu + record_offset, &green, sizeof(green)); + } + std::pair allocate_probe(UINT64 index) { ULONG_PTR token{}, count = 1; From 9dbf132e69df17a3e27ce2732429b54b19f362fa Mon Sep 17 00:00:00 2001 From: Royoo <3230853833@qq.com> Date: Thu, 26 Nov 2026 01:59:58 +0800 Subject: [PATCH 074/232] gpu: ignore padding in mesh slot86 cache keys --- docs/experiments.md | 9 +++- src/startup_stubs/mesh86_cache.inl | 32 ++++++++++-- tests/startup_indirect_draw_indexed.cpp | 57 ++++++++++++++++++---- tests/startup_indirect_mesh_cache_check.py | 31 ++++++++++-- 4 files changed, 110 insertions(+), 19 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index bda0e0243..050f316b5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8851,11 +8851,16 @@ of console shader programs and support for other console mesh paths are tracked Slot 86 publishes complete Xbox mesh containers under a separate cache key. The key frames the original MS, the optional PS, the creation root signature and the -pipeline-state stream with its pointers cleared. The shim writes `.m86` last, +pipeline-state stream with its pointers and known padding cleared. A request that +previously contained nonzero blend or depth-stencil padding gets a new key and +must be published once under that key. The shim writes `.m86` last, after `.ps86`, `.root` and `.stream86`. An empty `.ps86` records a stream without a pixel shader. Use the cache tool with a desktop pair independently validated for that exact source and root. The ready marker records both output -shader hashes so an incomplete or mixed update cannot reach PSO creation. +shader hashes so an incomplete or mixed update cannot reach PSO creation. The +cache fixture changes only blend and depth-stencil padding and reuses the cached +PSO, then changes one sample-mask bit and checks for a new request and clear +attachments. ```powershell python -B tools/startup/mesh86_cache.py --mesh --pixel diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index f481353a1..ff8adb5e6 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -62,6 +62,34 @@ bool mesh86_hardware_depth() !(desc.VendorId == 0x1414 && desc.DeviceId == 0x008c); } +void mesh86_clear_state_padding(unsigned char* record, UINT type, std::size_t size) +{ + constexpr std::size_t tag_size = sizeof(UINT); + if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND) { + constexpr auto targets = tag_size + offsetof(D3D12_BLEND_DESC, RenderTarget); + constexpr auto stride = sizeof(D3D12_RENDER_TARGET_BLEND_DESC); + constexpr auto fields = offsetof(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + 1; + static_assert(stride == 40 && fields == 37); + for (UINT i = 0; i < 8; ++i) + std::memset(record + targets + i * stride + fields, 0, stride - fields); + constexpr auto used = tag_size + sizeof(D3D12_BLEND_DESC); + std::memset(record + used, 0, size - used); + } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL || + type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1) { + constexpr auto masks = offsetof(D3D12_DEPTH_STENCIL_DESC, StencilWriteMask) + 1; + constexpr auto faces = offsetof(D3D12_DEPTH_STENCIL_DESC, FrontFace); + static_assert(masks == offsetof(D3D12_DEPTH_STENCIL_DESC1, StencilWriteMask) + 1 && + faces == offsetof(D3D12_DEPTH_STENCIL_DESC1, FrontFace)); + std::memset(record + tag_size + masks, 0, faces - masks); + const auto used = tag_size + (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL + ? sizeof(D3D12_DEPTH_STENCIL_DESC) : sizeof(D3D12_DEPTH_STENCIL_DESC1)); + std::memset(record + used, 0, size - used); + } else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC) { + constexpr auto used = tag_size + sizeof(DXGI_SAMPLE_DESC); + std::memset(record + used, 0, size - used); + } +} + // Parse the entire stream and keep a pointer-free copy. The shared tag is only // recognized as Xbox MS when its shader container declares mesh and native code. bool mesh86_request(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Mesh86Request& result, bool& recognized) @@ -122,9 +150,7 @@ bool mesh86_request(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, Mesh86Request& if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE || mesh || (type >= D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS && type <= D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS)) std::memset(record + 4, 0, 4); - if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND || type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC || - type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1) - std::memset(record + size - 4, 0, 4); + mesh86_clear_state_padding(record, type, size); offset += size; } return recognized && result.root && result.root->own().kind == root_signature_kind; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 317ef8939..185bb9423 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); @@ -359,24 +360,29 @@ struct alignas(void*) Subobject { enum class StreamDepth { none, writable, read_only }; -template +template ComPtr guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, D3D12_SHADER_BYTECODE source, D3D12_SHADER_BYTECODE pixel, D3D12_SHADER_BYTECODE amplification = {}, UINT targets = 1, StreamDepth depth = StreamDepth::none) { + using Depth = std::conditional_t; + constexpr auto depth_type = CacheControl ? D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 + : D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; struct { Subobject root; Subobject source; Subobject ps; Subobject raster; - Subobject depth; + Subobject depth; Subobject topology; Subobject targets; Subobject samples; Subobject dsv; Subobject as; + Subobject blend; + Subobject sample_mask; } stream; - static_assert(sizeof(stream) == 16 + 24 + 24 + 48 + 56 + 8 + 40 + 16 + 8 + 24); + static_assert(offsetof(decltype(stream), as) == 16 + 24 + 24 + 48 + (CacheControl ? 64 : 56) + 8 + 40 + 16 + 8); stream.root.value = root; stream.source.value = source; stream.ps.value = pixel; @@ -397,12 +403,40 @@ ComPtr guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root, stream.targets.value.NumRenderTargets = targets; stream.samples.value.Count = 1; stream.as.value = amplification; - const D3D12_PIPELINE_STATE_STREAM_DESC desc{ - amplification.pShaderBytecode ? sizeof(stream) : sizeof(stream) - sizeof(stream.as), &stream}; using Create = HRESULT (WINAPI*)(IUnknown*, const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**); ComPtr result; - check(slot(guest, 86)(guest, &desc, __uuidof(ID3D12PipelineState), - reinterpret_cast(result.GetAddressOf())), "create guest graphics pipeline"); + const auto create = [&](void* bytes, std::size_t size) { + const D3D12_PIPELINE_STATE_STREAM_DESC desc{size, bytes}; + check(slot(guest, 86)(guest, &desc, __uuidof(ID3D12PipelineState), + reinterpret_cast(result.GetAddressOf())), "create guest graphics pipeline"); + }; + if constexpr (CacheControl) { + constexpr auto masks = offsetof(Depth, StencilWriteMask) + 1; + constexpr auto faces = offsetof(Depth, FrontFace); + constexpr auto write_mask = offsetof(D3D12_RENDER_TARGET_BLEND_DESC, RenderTargetWriteMask) + 1; + const int padding = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_PADDING", nullptr, 0) ? 0xa5 : 0; + std::memset(reinterpret_cast(&stream.depth.value) + masks, padding, faces - masks); + for (auto& blend : stream.blend.value.RenderTarget) { + blend.SrcBlend = blend.SrcBlendAlpha = D3D12_BLEND_ONE; + blend.DestBlend = blend.DestBlendAlpha = D3D12_BLEND_ZERO; + blend.BlendOp = blend.BlendOpAlpha = D3D12_BLEND_OP_ADD; + blend.LogicOp = D3D12_LOGIC_OP_NOOP; + blend.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + std::memset(reinterpret_cast(&blend) + write_mask, padding, sizeof(blend) - write_mask); + } + stream.sample_mask.value = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_SAMPLE_MASK", nullptr, 0) + ? UINT_MAX ^ 1u : UINT_MAX; + + // Omit the amplification record from this cache profile. + constexpr auto prefix = offsetof(decltype(stream), as); + constexpr auto suffix = offsetof(decltype(stream), blend); + alignas(void*) std::array bytes; + std::memcpy(bytes.data(), &stream, prefix); + std::memcpy(bytes.data() + prefix, &stream.blend, sizeof(stream) - suffix); + create(bytes.data(), bytes.size()); + } else { + create(&stream, amplification.pShaderBytecode ? offsetof(decltype(stream), blend) : offsetof(decltype(stream), as)); + } return result; } @@ -1499,9 +1533,12 @@ int main(int argc, char** argv) try const D3D12_COMMAND_SIGNATURE_DESC signature_desc{sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), 1, &argument, 0}; ComPtr signature; check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create cached mesh signature"); - const auto pso = guest_pipeline( - guest.Get(), root.Get(), {ms.data(), ms.size()}, {ps.empty() ? nullptr : ps.data(), ps.size()}, - {}, depth_only ? 0 : lease_fixture ? 1 : 3, depth); + const D3D12_SHADER_BYTECODE ms_code{ms.data(), ms.size()}; + const D3D12_SHADER_BYTECODE ps_code{ps.empty() ? nullptr : ps.data(), ps.size()}; + const auto pso = lease_fixture + ? guest_pipeline(guest.Get(), root.Get(), ms_code, ps_code, {}, 1, depth) + : guest_pipeline(guest.Get(), root.Get(), ms_code, ps_code, {}, + depth_only ? 0 : 3, depth); if (dual_lease) { const bool init_only = GetEnvironmentVariableA("X2W_MESH86_FIXTURE_INIT_ONLY", nullptr, 0) != 0; const auto initialize = writer_pipeline(device.Get(), writer.Get(), "initialize_mesh_record"); diff --git a/tests/startup_indirect_mesh_cache_check.py b/tests/startup_indirect_mesh_cache_check.py index 73671bc78..d8b4ecbee 100644 --- a/tests/startup_indirect_mesh_cache_check.py +++ b/tests/startup_indirect_mesh_cache_check.py @@ -29,9 +29,8 @@ def run(dxc, fixture, backend, work, depth_only, lease_xmem=None, mode=None, dep for suffix, stage in (('ms', 13), ('ps', 0)): (work / f'source.{suffix}.dxbc').write_bytes(source_envelope(stage)) environment = dict(os.environ, X2W_MESH86_FIXTURE_DIR=str(work), X2W_SHADER_CACHE=str(work)) - environment.pop('X2W_MESH86_FIXTURE_READY', None) - environment.pop('X2W_MESH86_FIXTURE_DEPTH', None) - environment.pop('X2W_MESH86_FIXTURE_DEPTH_PIXEL', None) + for flag in ('READY', 'DEPTH', 'DEPTH_PIXEL', 'PADDING', 'SAMPLE_MASK'): + environment.pop(f'X2W_MESH86_FIXTURE_{flag}', None) if depth_only: environment['X2W_MESH86_FIXTURE_DEPTH'] = '1' if depth_pixel: @@ -85,7 +84,31 @@ def run(dxc, fixture, backend, work, depth_only, lease_xmem=None, mode=None, dep # WARP keeps the existing MS-only depth refusal. if has_pixel or backend == 'hardware': environment['X2W_MESH86_FIXTURE_READY'] = '1' - return subprocess.run(cmd, env=environment).returncode + if lease_xmem or depth_only: + return subprocess.run(cmd, env=environment).returncode + + # Change only the blend and depth-stencil object padding between capture + # and replay. A cache miss leaves the fixture's color attachments clear. + padded = dict(environment, X2W_MESH86_FIXTURE_PADDING='1') + replay = subprocess.run(cmd, env=padded) + if replay.returncode: + return replay.returncode + assert list(work.glob('req_*.m86')) == [marker] + + # A real sample-mask change must instead publish a different request and + # refuse the previously cached PSO, leaving all attachments clear. + padded.pop('X2W_MESH86_FIXTURE_READY') + changed = subprocess.run(cmd, env=dict(padded, X2W_MESH86_FIXTURE_SAMPLE_MASK='1')) + if changed.returncode: + return changed.returncode + changed_marker, = set(work.glob('req_*.m86')) - {marker} + changed_key = int(changed_marker.stem.removeprefix('req_'), 16) + changed_ms, changed_ps, changed_root, changed_stream = mesh86_cache.load_request(work, changed_key) + assert (changed_ms, changed_ps, changed_root) == (source_ms, source_ps, root) + assert stream[-8:] == struct.pack(' Date: Thu, 26 Nov 2026 02:24:01 +0800 Subject: [PATCH 075/232] startup: lower v_{add,sub,subrev}_co_ci_u32 in gfx2hlsl (#2428) --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + tests/startup_gfx2hlsl_add_sub_co_ci_check.py | 169 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 59 ++++++ 5 files changed, 233 insertions(+) create mode 100644 tests/startup_gfx2hlsl_add_sub_co_ci_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 28d8db317..979120845 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -225,6 +225,7 @@ jobs: tests/startup_gfx2hlsl_mask_overwrite_check.py \ tests/startup_gfx2hlsl_image_get_lod_check.py \ tests/startup_gfx2hlsl_add_sub_co_check.py \ + tests/startup_gfx2hlsl_add_sub_co_ci_check.py \ tests/startup_gfx2hlsl_saveexec_same_reg_check.py \ tests/startup_gfx2hlsl_compare_dst_check.py \ tests/startup_gfx2hlsl_capture_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2af03946a..04ec6110c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -192,6 +192,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mask_overwrite_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_get_lod_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_add_sub_co_ci_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_saveexec_same_reg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compare_dst_check.py ./out/pe-env/bin/python -B tests/startup_flat_param_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7161063c3..a963dbbbf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3085,6 +3085,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: v_add/sub/subrev_co_u32 against ISA references. add_test(NAME startup_gfx2hlsl_add_sub_co_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_add_sub_co_check.py") + # Startup shader translator: v_{add,sub,subrev}_co_ci_u32 carry/borrow-in and out. + add_test(NAME startup_gfx2hlsl_add_sub_co_ci_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_add_sub_co_ci_check.py") # Startup shader translator: s_*_saveexec with D == S0 reads S0 before writing D. add_test(NAME startup_gfx2hlsl_saveexec_same_reg_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_saveexec_same_reg_check.py") diff --git a/tests/startup_gfx2hlsl_add_sub_co_ci_check.py b/tests/startup_gfx2hlsl_add_sub_co_ci_check.py new file mode 100644 index 000000000..4ec222874 --- /dev/null +++ b/tests/startup_gfx2hlsl_add_sub_co_ci_check.py @@ -0,0 +1,169 @@ +"""v_add_co_ci_u32, v_sub_co_ci_u32 and v_subrev_co_ci_u32 in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_add_sub_co_ci_check.py + +Synthetic VOP2 (_e32) and VOP3b (_e64) words only; the spellings are asserted from the translator's decoder. +AMD RDNA 2 ISA: V_ADD_CO_CI_U32 D = S0 + S1 + S2[lane] with carry out to SDST[lane]; V_SUB_CO_CI_U32 +D = S0 - S1 - S2[lane] with borrow out to SDST[lane]; V_SUBREV_CO_CI_U32 swaps S0 and S1. +""" +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr # noqa: E402 + +MASK = 0xffffffff +GRID = [0, 1, 2, 0x7fffffff, 0x80000000, 0xfffffffe, MASK, 0x12345678] +failures = 0 + + +def check(what, ok, detail=''): + global failures + print('%s %s%s' % ('ok ' if ok else 'FAIL', what, '' if ok or not detail else ': %s' % (detail,))) + if not ok: + failures += 1 + + +class Pipe: + root = {'params': [], 'flags': 0} + + def ud(self, source): + return 0 + + +def vop2(op, vdst, src0, vsrc1): + return [op << 25 | vdst << 17 | vsrc1 << 9 | src0] + + +def vop3b(op, vdst, sdst, src0, src1, src2, clamp=False): + return [0xd4000000 | op << 16 | (1 << 15 if clamp else 0) | sdst << 8 | vdst, src0 | src1 << 9 | src2 << 18] + + +V2, V3, V4, VCC_LO, EXEC_LO = 256 + 2, 256 + 3, 256 + 4, 106, 126 + + +def stage(exec_known=True, masks=()): + s = G.Stage(Pipe(), 'ps', struct.pack('> 32 + diff = a - b - ci + return diff & MASK, int(diff < 0) + + +FORMS = ( + ('add', 0x28, 0x128), + ('sub', 0x29, 0x129), + ('subrev', 0x2a, 0x12a), +) + + +def main(): + count = 0 + for kind, op2, op3 in FORMS: + # VOP2 (_e32): implicit vcc_lo carry-out and carry-in. + s, text, lines = translate(vop2(op2, 2, V4, 3)) + expected = 'v_%s_co_ci_u32_e32 v2, vcc_lo, v4, v3, vcc_lo' % kind + check('decodes as %s' % expected, text == expected, text) + bad = None + for a in GRID: + for b in GRID: + for ci in (0, 1): + env = evaluate(lines, {'v4': a, 'v3': b, 'vcc': ci | 0xdeadbee0, 'v2': 0xdeadbeef}) + got = env['v2'], env['vcc'] + if got != ref(kind, a, b, ci) and bad is None: + bad = (a, b, ci, got, ref(kind, a, b, ci), lines) + count += 1 + check('%s matches the ISA reference on the grid' % text, bad is None, bad) + + # VOP3b (_e64): overlapping destination/carry-out with sources (v4, s18 <- v4, v3, s18). + s, text, lines = translate(vop3b(op3, 4, 18, V4, V3, 18), masks=(18,)) + expected = 'v_%s_co_ci_u32_e64 v4, s18, v4, v3, s18' % kind + check('decodes as %s' % expected, text == expected, text) + check('%s: carry-out SGPR stays a lane mask' % text, 18 in s.masks, s.masks) + bad = None + for a in GRID: + for b in GRID: + for ci in (0, 1): + env = evaluate(lines, {'v4': a, 'v3': b, 's18': ci | 0x12345670}) + got = env['v4'], env['s18'] + if got != ref(kind, a, b, ci) and bad is None: + bad = (a, b, ci, got, ref(kind, a, b, ci), lines) + count += 1 + check('%s overlapping dst/src matches the ISA reference on the grid' % text, bad is None, bad) + + # Constant carry-in (0 and -1) and inactive lane behavior when exec is not known. + s, text, lines = translate(vop3b(0x128, 2, 18, V4, V3, 128)) # src2 = inline 0 + env = evaluate(lines, {'v4': MASK, 'v3': 1, 'v2': 0xdeadbeef, 's18': 0xdeadbeef}) + check('constant 0 carry-in works', (env['v2'], env['s18']) == (0, 1), (env['v2'], env['s18'])) + + s, text, lines = translate(vop3b(0x128, 2, 18, V4, V3, 193)) # src2 = inline -1 + env = evaluate(lines, {'v4': MASK, 'v3': 0, 'v2': 0xdeadbeef, 's18': 0xdeadbeef}) + check('constant -1 carry-in works', (env['v2'], env['s18']) == (0, 1), (env['v2'], env['s18'])) + + s, text, lines = translate(vop2(0x28, 2, V4, 3), exec_known=False) + env = evaluate(lines, {'v4': MASK, 'v3': 1, 'vcc': 1, 'v2': 0x55555555, 'exec': 0}) + check('inactive lane keeps D and gets 0 carry', (env['v2'], env['vcc']) == (0x55555555, 0), (env['v2'], env['vcc'])) + + # Refusals: clamp, non-mask SGPR carry-in, vcc_hi carry-in, EXEC carry-out, wrong operand count. + for label, fn in ( + ('clamp refused', lambda: translate(vop3b(0x128, 2, 18, V4, V3, VCC_LO, clamp=True))), + ('non-mask SGPR carry-in refused', lambda: translate(vop3b(0x128, 2, 18, V4, V3, 20))), + ('vcc_hi carry-in refused', lambda: translate(vop3b(0x128, 2, 18, V4, V3, 107))), + ('EXEC carry-out refused', lambda: translate(vop3b(0x128, 2, EXEC_LO, V4, V3, VCC_LO))), + ('wrong operand count refused', lambda: stage().one('v_add_co_ci_u32', 'v_add_co_ci_u32 v2, s18, v4, v3')), + ): + try: + fn() + except G.Unsupported: + check(label, True) + else: + check(label, False, 'accepted') + + # Negative control: omitting carry-in from the reference must disagree on the grid. + _, _, lines = translate(vop2(0x28, 2, V4, 3)) + env = evaluate(lines, {'v4': MASK, 'v3': 0, 'vcc': 1, 'v2': 0}) + check('negative control: carry-in 1 changes result and carry-out', + (env['v2'], env['vcc']) == (0, 1) and (env['v2'], env['vcc']) != ref('add', MASK, 0, 0)) + + print('checked %d grid points, %d failures' % (count, failures)) + sys.exit(1 if failures else 0) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ce765c119..964f98cd6 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4359,6 +4359,65 @@ def op_v_sub_co_u32(self, ops, mods): def op_v_subrev_co_u32(self, ops, mods): self.carry_out_op(ops, mods, 'subrev') + def carry_in_out_op(self, ops, mods, kind): + """v_{add,sub,subrev}_co_ci_u32 D, SDST, S0, S1, S2: 32-bit add/sub with carry or borrow in and out. + + AMD RDNA 2 ISA: V_ADD_CO_CI_U32 D = S0 + S1 + S2[lane] with carry out to SDST[lane]; + V_SUB_CO_CI_U32 D = S0 - S1 - S2[lane] with borrow out to SDST[lane]; V_SUBREV_CO_CI_U32 swaps S0 and S1. + Both VOP2 (_e32, implicit vcc_lo) and VOP3b (_e64) forms arrive with five operands. Results go through + scratch a and w first so D or SDST may overlap any source. + """ + name = 'v_%s_co_ci_u32' % kind + if mods: + raise Unsupported('%s with %s' % (name, ' '.join(mods))) + if len(ops) != 5: + raise Unsupported('%s with %d operands' % (name, len(ops))) + d = reg_range(ops[0]) + if not d or d[0] != 'v' or d[1] != d[2] or d[1] > 255: + raise Unsupported('%s destination %s' % (name, ops[0])) + sdst = reg_range(ops[1]) + if ops[1] not in ('vcc', 'vcc_lo') and not (sdst and sdst[0] == 's' and sdst[1] == sdst[2] and sdst[1] <= 105): + raise Unsupported('%s carry-out destination %s' % (name, ops[1])) + cin_tok = ops[4] + if cin_tok in ('vcc_hi', 'exec_hi'): + raise Unsupported('%s carry-in %s' % (name, cin_tok)) + cin_const = self.const_u32(cin_tok) + if cin_const in (0, 0xffffffff): + ci = '1u' if cin_const else '0u' + elif self.is_lane_mask(cin_tok): + ci = '(%s & 1u)' % self.u(cin_tok) + else: + raise Unsupported('%s carry-in %s' % (name, cin_tok)) + a, b = self.u(ops[2]), self.u(ops[3]) + if kind == 'subrev': + a, b = b, a + if kind == 'add': + self.emit('a = %s + %s;' % (a, b)) + self.emit('w = a < %s ? 1u : 0u;' % a) + self.emit('a = a + %s;' % ci) + self.emit('w = w | (a < %s ? 1u : 0u);' % ci) + else: + self.emit('a = %s - %s;' % (a, b)) + self.emit('w = %s > %s ? 1u : 0u;' % (b, a)) + self.emit('w = w | (%s > a ? 1u : 0u);' % ci) + self.emit('a = a - %s;' % ci) + self.set_v(d[1], 'a') + predicate = 'w' if self.exec_known else '(exec & w)' + if ops[1] in ('vcc', 'vcc_lo'): + self.emit('vcc = %s;' % predicate) + else: + self.set_s(sdst[1], predicate, uniform=False) + self.masks.add(sdst[1]) + + def op_v_add_co_ci_u32(self, ops, mods): + self.carry_in_out_op(ops, mods, 'add') + + def op_v_sub_co_ci_u32(self, ops, mods): + self.carry_in_out_op(ops, mods, 'sub') + + def op_v_subrev_co_ci_u32(self, ops, mods): + self.carry_in_out_op(ops, mods, 'subrev') + def op_v_lshlrev_b64(self, ops, mods): self.shift64(ops, mods, 'shl64') From c887a65aa77491b266a4290269def366a93c5085 Mon Sep 17 00:00:00 2001 From: JB2WIN Date: Wed, 25 Nov 2026 19:26:19 +0100 Subject: [PATCH 076/232] startup: opt-in release of retired committed 2D textures after list and fence lifetimes (slice 1) (#2443) * startup: opt-in release of retired committed 2D textures (X2W_D3D12_RELEASE_RETIRED) With X2W_D3D12_RELEASE_RETIRED=1, a committed 2D texture of one narrow class (slot 27 or 127, one sample, no render-target/depth/UAV flag, default heap, no title memory) gives up its desktop object after its final guest Release, but only when the release-time fence of every queue has passed and no recorded list or submission still names it. Lists hold the resource across copy, texture copy and resolve until Reset or destruction (an unsubmitted list is discarded without any submission); each submission holds it until a fence signalled behind it passes. Views, MakeResident/Evict and Present take a resource out of the class. Unset, nothing changes. The fixture startup_resource_retire uses the budget retained column as oracle and reads results back through its own desktop queue. AI-assisted (Claude Code) Co-Authored-By: Claude Opus 5.5 Refs #2379 * startup: tighten the retire-class fixture, docs and comments (review follow-up) - Check the CopyResource destination hold by behaviour first: the fixture no longer asserts the hold count before the destination-released stage. - The retire probe export returns FALSE without the switch. - Document that the switch needs X2W_D3D12_RENDER=1, that a title exporting __XMemAllocationHooks__ leaves slot 127 outside the class, and the debug layer skip. Lists drop their holds on Reset, destruction or a Close that fails. - Take the submission reference only after its fence was signalled; shorten comments. AI-assisted (Claude Code) Co-Authored-By: Claude Opus 5.5 Refs #2379 --- CMakeLists.txt | 19 + docs/experiments.md | 8 + docs/startup-runtime.md | 44 ++ src/startup_stubs/d3d12_xs_device.cpp | 344 +++++++++- src/startup_stubs/list_copy.inl | 3 + src/startup_stubs/list_copy_texture.inl | 9 +- tests/startup_resource_retire.cpp | 829 ++++++++++++++++++++++++ 7 files changed, 1251 insertions(+), 5 deletions(-) create mode 100644 tests/startup_resource_retire.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index a963dbbbf..3962c2466 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1325,6 +1325,25 @@ foreach(backend IN ITEMS warp hardware) endforeach() endforeach() +# X2W_D3D12_RELEASE_RETIRED=1 frees the desktop object of a committed 2D texture only when no recorded list, no submission +# and no release-time fence still refers to it (docs/startup-runtime.md#d3d12-resource-budget). The `off` case runs +# without the switch and expects the lifetime of the budget fixture: every released resource stays retained. +add_executable(startup_resource_retire tests/startup_resource_retire.cpp) +target_include_directories(startup_resource_retire PRIVATE src) +target_compile_features(startup_resource_retire PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(retire_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=${debug}") + add_test(NAME startup_resource_retire_${backend}_debug${debug} COMMAND startup_resource_retire ${backend}) + set_tests_properties(startup_resource_retire_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_env};X2W_D3D12_RELEASE_RETIRED=1") + endforeach() + add_test(NAME startup_resource_retire_off_${backend} COMMAND startup_resource_retire ${backend} off) + set_tests_properties(startup_resource_retire_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") +endforeach() + # GPU writes the dispatch record that the desktop command processor consumes (Refs #1412). add_executable(startup_compute_binding_trace tests/startup_compute_binding_trace.cpp) target_compile_features(startup_compute_binding_trace PRIVATE cxx_std_20) diff --git a/docs/experiments.md b/docs/experiments.md index 050f316b5..9a618c3f7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -36,6 +36,14 @@ cmake --build --preset release --target startup_resource_budget -j 2 ctest --preset release --no-tests=error -j 1 -R '^startup_resource_budget_' -V ``` +`startup_resource_retire` covers `X2W_D3D12_RELEASE_RETIRED=1` +([class and fences](startup-runtime.md#d3d12-resource-budget)): + +```powershell +cmake --build --preset release --target startup_resource_retire -j 2 +ctest --preset release --no-tests=error -j 1 -R '^startup_resource_retire_' -V +``` + The test runs on WARP and hardware with the debug layer on and off. The [budget heartbeat](startup-runtime.md#d3d12-resource-budget) correlates these counts with DXGI usage. The fixture measures the accounting and retirement diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 173a2d214..5ba9513ec 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1265,6 +1265,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | +| `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | @@ -1327,11 +1328,54 @@ those lifetimes intact. `unmeasured` counts tracking failures. DXGI usage can also include allocations outside these categories, such as swap chain and descriptor heap backing. +`X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for one class: a +texture created by device slot 27 or 127 that is two-dimensional, has one +sample, no render-target, depth-stencil or unordered-access flag, lives in a +default heap without heap flags and has no title memory. If the title exports +`__XMemAllocationHooks__`, every slot 127 resource gets title memory and none is in the class; the fixture runs +without that export. Every other resource +keeps the lifetime described above. A resource leaves the class for good when a +view is created for it (slots 18 to 21, also a refused one), when it is passed +to MakeResident or Evict (slots 34 and 35), or when it is presented. Only +wrappers can be in the class; a raw desktop pointer never is. Sampler feedback +is not checked: no device slot of the stand-in reaches it. + +The final guest release signals a private desktop fence on every queue the +stand-in created. The desktop object is released when all of those fences have +passed and nothing else names it. A copy (list slot 17), texture copy (16) or +resolve destination (19) that the stand-in forwards makes the list hold a +desktop reference to each resource of the class it names, source and +destination, until the list is Reset, fails to Close or is destroyed. A list +that is closed and never submitted is thus discarded without any submission. +Each submission holds the same references until its queue passes a fence +signalled behind it. A release with no registered queue, and a hold, marker or +submission fence that cannot be recorded, keep the resource retained. Nothing +waits: `ExecuteCommandLists` and `Present` check and release without blocking. +The wrapper stays allocated, and a guest that uses a resource after its final +release is not supported with the switch. Buffers, placed and reserved +resources, slot 133 and all resources with title memory are not in the class. +Slot 18 (`CopyTiles`) is not forwarded at all and is outside this change. + The source-built fixture reads the process-wide counters through `x2w_d3d12_budget_snapshot` and checks allocation sizes, final guest release, and slot 148 page retirement after queue completion. See [D3D12 budget accounting](experiments.md#d3d12-budget-accounting) for the test command. +`startup_resource_retire_{warp,hardware}_debug{0,1}` use the retained column as +the oracle that a desktop object is destroyed, and read results back through +their own desktop queue. They cover two closed lists on one texture that are +submitted separately after the release, a Reset or destroyed list with no +submission (the destination stays unchanged), a second submission held behind +its own fence, a destination released after recording (slots 17, 16 and 19), a +list destroyed while its submission is held, a copy queue, an open list that +D3D12 refuses to Reset and one that is destroyed, a release that no list +refers to behind a held queue, and, in one run with the class, a buffer, +render target, title-memory texture, viewed texture, resident texture and +presented texture that must stay retained. The fixture-only export +`x2w_d3d12_retire_probe` returns FALSE without the switch, like +`x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` +runs the same steps without the switch. The hardware cases report 77 without a +physical adapter, and the debug-layer cases report 77 where the debug layer is not installed. ## Input script diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0b43dc27c..f20d25d02 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -153,6 +153,8 @@ struct alignas(16) WrapperOwn { ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. + bool retire_when_idle; // Resource: in the retire class (X2W_D3D12_RELEASE_RETIRED); cleared by any other use. Plain + // accesses: a race needs the guest to use a resource across its own final Release. bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline u64 compute_trace_key; // Opt-in trace: selected slot 62 container hash @@ -764,6 +766,25 @@ D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) return copy; } +bool release_retired_enabled() +{ + static const bool on = x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); + return on; +} + +// The retire class of X2W_D3D12_RELEASE_RETIRED, decided once at creation from the desktop description: a committed +// 2D texture with one sample, no render-target, depth-stencil or unordered-access use, in a default heap with no heap +// flags, that has no title memory (with the title's __XMemAllocationHooks__ export every slot 127 resource gets title +// memory, so none is in the class then). Every use reaches the shim through handlers that retire_hold covers or that +// clear the flag; see docs/startup-runtime.md#d3d12-resource-budget. +bool retire_class(const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, + const void* title_memory) +{ + return release_retired_enabled() && props.Type == D3D12_HEAP_TYPE_DEFAULT && heap_flags == D3D12_HEAP_FLAG_NONE && + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && + (desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == D3D12_RESOURCE_FLAG_NONE && !title_memory; +} + template __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, u64 e, u64 f, u64 g, u64 h) { @@ -788,6 +809,11 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, if (Desc >= 0 && kind == resource_kind && requested_format != DXGI_FORMAT_UNKNOWN) x2w_startup::mark_packed_stand_in(static_cast(*out), requested_format); Wrapper* child = wrap(static_cast(*out), kind); + if constexpr (K == device_kind && N == 27) { + if (kind == resource_kind && args[0]) + child->own().retire_when_idle = retire_class(*reinterpret_cast(args[0]), + static_cast(args[1]), desc_copy, nullptr); + } if constexpr (K == device_kind && (N == 27 || N == 28 || N == 29)) { if (x2w_budget::enabled()) { using Microsoft::WRL::ComPtr; @@ -872,8 +898,18 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) return hr; } ULONG __stdcall add_ref(Wrapper* self) { return static_cast(InterlockedIncrement(&self->own().refs)); } -// The wrappers and their desktop objects stay alive for the process (experiment scope). +// The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is +// X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. +// The wrapper stays. void retire_placement(Wrapper* w); +void register_retire_queue(Wrapper* queue); +void retire_resource(Wrapper* w); +void retire_leave_class(const void* object); +void retire_hold(Wrapper* list, Wrapper* resource); +void retire_drop_recording(Wrapper* list); +void retire_discard_holds(Wrapper* list); +void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists); +void drain_retired_resources(); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); ULONG __stdcall release(Wrapper* self) @@ -886,8 +922,11 @@ ULONG __stdcall release(Wrapper* self) drop_mesh_lease_owner(self); retire_placement(self); } - if (self->own().kind == list_kind && self->own().real) + if (self->own().kind == list_kind && self->own().real) { discard_mesh_lease_recording(static_cast(self->own().real)); + retire_drop_recording(self); + } + if (self->own().retire_when_idle) retire_resource(self); } return static_cast(refs); } @@ -916,6 +955,7 @@ HRESULT __stdcall device_create_command_queue(Wrapper* self, const D3D12_COMMAND desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + register_retire_queue(static_cast(*out)); return S_OK; } @@ -939,6 +979,7 @@ HRESULT __stdcall device_create_command_queue_x(Wrapper* self, const D3D12_COMMA desc->Type, desc->Priority, desc->Flags, desc->NodeMask, text, static_cast(hr)); if (FAILED(hr)) return hr; *out = wrap(queue, queue_kind); + register_retire_queue(static_cast(*out)); return S_OK; } @@ -1165,7 +1206,10 @@ template HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objects) { std::vector real(count); - for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(objects[i]))); + for (UINT i = 0; i < count; ++i) { + retire_leave_class(objects[i]); // no hold tracks the residency of a desktop object + real[i] = reinterpret_cast(unwrap(reinterpret_cast(objects[i]))); + } return N == 34 ? device_of(self)->MakeResident(count, real.data()) : device_of(self)->Evict(count, real.data()); } @@ -1560,6 +1604,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) discard_draw_sampler_heaps(previous); discard_address_uploads(previous); discard_mesh_lease_recording(previous); + retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(previous); discard_red_producer(previous); } @@ -1597,6 +1642,7 @@ HRESULT __stdcall list_close(Wrapper* self) discard_draw_sampler_heaps(list); discard_address_uploads(list); discard_mesh_lease_recording(list); + retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(list); discard_red_producer(list); static LONG failures; @@ -2351,6 +2397,16 @@ void release_targets(Wrapper* self) pass = Pass{}; } +// A dropped recording (Reset, or its list destroyed) names no resource any more. The raw pointers the pass keeps for +// Close go first, then the holds that kept those resources alive (X2W_D3D12_RELEASE_RETIRED). Without the switch +// nothing changes. +void retire_drop_recording(Wrapper* list) +{ + if (!release_retired_enabled()) return; + if (list->own().pass) pass_of(list).states.clear(); + retire_discard_holds(list); +} + // A reset list has no viewport or scissor and uses the default stencil reference. void reset_list_dynamic_state(Wrapper* self) { @@ -3318,6 +3374,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) { X2W_ZONE("ExecuteCommandLists"); static LONG calls; + drain_retired_resources(); if (render_mode()) { // A closed list stays submittable until its next Reset, as on the desktop. std::vector ready; @@ -3346,6 +3403,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) retire_address_uploads(queue, native_lists); retire_draw_sampler_heaps(queue, native_lists); note_submits(queue, wrappers); + retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w); InterlockedIncrement(&render_executes); }; @@ -3377,6 +3435,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u -> not submitted (noop lists)", count); return; } + // No hold or flight is recorded here: the copy handlers that create holds exist only in render mode. std::vector real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast(unwrap(reinterpret_cast(lists[i]))); static_cast(self->own().real)->ExecuteCommandLists(count, real.data()); @@ -3709,6 +3768,9 @@ template __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) { Timed timed(time_view); + // A view keeps the resource's old lifetime, whether or not the view is created (X2W_D3D12_RELEASE_RETIRED). + if constexpr (N >= 18 && N <= 21) retire_leave_class(reinterpret_cast(a)); + if constexpr (N == 19) retire_leave_class(reinterpret_cast(b)); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); @@ -4136,6 +4198,274 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 #include "d3d12_memory_srv.inl" #include "startup_stubs/list_copy.inl" +// X2W_D3D12_RELEASE_RETIRED=1 (docs/startup-runtime.md#d3d12-resource-budget): the desktop object of a retire class +// member is released after its final guest Release once (1) the release-time fence of every queue has passed (each queue +// owns a private fence that the Release signals) and (2) no list or submission names it: a list holds a desktop +// reference from a forwarded copy until it is Reset, fails to Close or is destroyed, and each submission holds one until +// its queue passes a fence signalled behind it. Nothing waits; the drain only try-locks and drops references outside +// the lock. What cannot be recorded stays retained for the process, the lifetime without the switch. +constexpr LONG retired_refs = -0x40000000; +SRWLOCK retire_lock = SRWLOCK_INIT; // a leaf: taken after draw_lock and allocator_lock, nothing is taken under it +struct RetireQueue { + ID3D12CommandQueue* queue; // no reference: release() never frees a queue object + ID3D12Fence* fence; // null: no marker for this queue, so nothing retires + UINT64 signaled; +}; +struct RetiredResource { + Wrapper* wrapper; + std::vector targets; // per RetireQueue that existed at the Release +}; +struct RetireFlight { + std::size_t queue; + UINT64 value; + std::vector resources; // one desktop reference each +}; +std::vector retire_queues; +std::vector retired_resources; +std::vector retire_flights; +std::unordered_map> retire_list_holds; // one desktop reference per entry +volatile LONG retire_pending; // retired_resources and retire_flights, read without the lock +volatile LONG retire_holds; // entries of retire_list_holds, read without the lock +volatile LONG64 retire_freed, retire_kept; + +void register_retire_queue(Wrapper* queue) +{ + if (!release_retired_enabled() || !queue || !queue->own().real) return; + auto* real = static_cast(queue->own().real); + ID3D12Fence* fence = nullptr; + ID3D12Device* device = nullptr; + if (SUCCEEDED(real->GetDevice(IID_PPV_ARGS(&device)))) { + if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) fence = nullptr; + device->Release(); + } + AcquireSRWLockExclusive(&retire_lock); + try { + retire_queues.push_back({real, fence, 0}); + } catch (const std::bad_alloc&) { + if (fence) fence->Release(); + } + ReleaseSRWLockExclusive(&retire_lock); +} + +// A use the holds do not cover (a view, residency, presentation) takes the resource out of the class for good. +void retire_leave_class(const void* object) +{ + if (!release_retired_enabled()) return; + if (Wrapper* w = as_wrapper(object)) w->own().retire_when_idle = false; +} + +// After a copy, texture copy or resolve was forwarded to the desktop list: the list keeps a desktop reference to the +// resource until its recording is dropped. Only wrappers are members of the class, so a raw desktop pointer is never +// held. Assumption, not proven: the guest has no raw pointer to the desktop object of a class member. +void retire_hold(Wrapper* list, Wrapper* resource) +{ + if (!resource || !resource->own().retire_when_idle) return; + auto* real = static_cast(resource->own().real); + bool held = false; + if (real) { + AcquireSRWLockExclusive(&retire_lock); + try { + auto& held_by_list = retire_list_holds[list]; + if (std::find(held_by_list.begin(), held_by_list.end(), real) != held_by_list.end()) { + held = true; + } else { + held_by_list.reserve(held_by_list.size() + 1); + real->AddRef(); + held_by_list.push_back(real); + InterlockedIncrement(&retire_holds); + held = true; + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockExclusive(&retire_lock); + } + // The guest still references the resource in this call, so it cannot be retired yet: leave the class instead. + if (!held) resource->own().retire_when_idle = false; +} + +void retire_discard_holds(Wrapper* list) +{ + if (!InterlockedCompareExchange(&retire_holds, 0, 0)) return; + std::vector dropped; + AcquireSRWLockExclusive(&retire_lock); + if (const auto found = retire_list_holds.find(list); found != retire_list_holds.end()) { + dropped = std::move(found->second); + retire_list_holds.erase(found); + InterlockedAdd(&retire_holds, -static_cast(dropped.size())); + } + ReleaseSRWLockExclusive(&retire_lock); + for (ID3D12Resource* resource : dropped) resource->Release(); +} + +// Right after ExecuteCommandLists: the lists' held resources stay referenced until the queue passes a fence signalled +// behind the submission. If that fence cannot be recorded or signalled the references are kept for the process. +void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists) +{ + if (!InterlockedCompareExchange(&retire_holds, 0, 0)) return; + std::vector named; + AcquireSRWLockExclusive(&retire_lock); + bool room = true; + try { + for (Wrapper* list : lists) { + const auto found = retire_list_holds.find(list); + if (found == retire_list_holds.end()) continue; + for (ID3D12Resource* resource : found->second) + if (std::find(named.begin(), named.end(), resource) == named.end()) named.push_back(resource); + } + retire_flights.reserve(retire_flights.size() + 1); + } catch (const std::bad_alloc&) { + room = false; + } + bool recorded = false; + if (room && !named.empty()) { + std::size_t index = 0; + while (index < retire_queues.size() && retire_queues[index].queue != queue) ++index; + if (index < retire_queues.size() && retire_queues[index].fence) { + RetireQueue& q = retire_queues[index]; + if (SUCCEEDED(queue->Signal(q.fence, q.signaled + 1))) { + for (ID3D12Resource* resource : named) resource->AddRef(); + ++q.signaled; + retire_flights.push_back({index, q.signaled, std::move(named)}); + InterlockedIncrement(&retire_pending); + recorded = true; + } + } + } + if (!recorded && (!room || !named.empty())) { + // Keep everything the lists name for the process; no allocation is needed to do so. + for (Wrapper* list : lists) + if (const auto found = retire_list_holds.find(list); found != retire_list_holds.end()) + for (ID3D12Resource* resource : found->second) resource->AddRef(); + InterlockedIncrement64(&retire_kept); + } + ReleaseSRWLockExclusive(&retire_lock); + if (!recorded && (!room || !named.empty())) { + static LONG reported; + if (first_calls(reported, 4)) log("x2w-d3d12 retire: a submission could not be fenced; its resources stay retained"); + } +} + +// Called by the final Release of a resource of the class. +void retire_resource(Wrapper* w) +{ + if (w->own().kind != resource_kind || !w->own().real) return; + RetiredResource item{w, {}}; + bool queued = false; + AcquireSRWLockExclusive(&retire_lock); + try { + // Without a registered queue nothing orders a marker: keep the resource. Every queue needs its fence. + queued = !retire_queues.empty(); + for (const RetireQueue& q : retire_queues) queued = queued && q.fence; + if (queued) { + item.targets.reserve(retire_queues.size()); + retired_resources.reserve(retired_resources.size() + 1); + for (RetireQueue& q : retire_queues) { + if (FAILED(q.queue->Signal(q.fence, q.signaled + 1))) { + queued = false; + break; + } + item.targets.push_back(++q.signaled); + } + } + if (queued) { + retired_resources.push_back(std::move(item)); + InterlockedIncrement(&retire_pending); + } + } catch (const std::bad_alloc&) { + queued = false; + } + ReleaseSRWLockExclusive(&retire_lock); + if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch +} + +// Never blocks: a contended lock or an unfinished queue leaves the work for the next call. +void drain_retired_resources() +{ + if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; + constexpr std::size_t batch = 256; + std::vector dropped; + try { + dropped.reserve(batch); + } catch (const std::bad_alloc&) { + return; + } + if (!TryAcquireSRWLockExclusive(&retire_lock)) return; + for (std::size_t i = 0; i < retired_resources.size() && dropped.size() < batch;) { + RetiredResource& item = retired_resources[i]; + bool reached = item.targets.size() <= retire_queues.size(); + for (std::size_t q = 0; q < item.targets.size() && reached; ++q) + reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; + if (!reached) { + ++i; + continue; + } + Wrapper* w = item.wrapper; + // Claim the reference count so that a late AddRef cannot bring the wrapper back while its object goes. + if (InterlockedCompareExchange(&w->own().refs, retired_refs, 0) == 0) { + dropped.push_back(static_cast(w->own().real)); + w->own().real = nullptr; + } else { + InterlockedIncrement64(&retire_kept); // referenced again after its final Release + } + if (i + 1 != retired_resources.size()) item = std::move(retired_resources.back()); + retired_resources.pop_back(); + InterlockedDecrement(&retire_pending); + } + for (std::size_t i = 0; i < retire_flights.size() && dropped.size() < batch;) { + RetireFlight& flight = retire_flights[i]; + if (retire_queues[flight.queue].fence->GetCompletedValue() < flight.value) { + ++i; + continue; + } + // A flight holds at most a list's resources; it may overshoot the batch by that much. + dropped.insert(dropped.end(), flight.resources.begin(), flight.resources.end()); + if (i + 1 != retire_flights.size()) flight = std::move(retire_flights.back()); + retire_flights.pop_back(); + InterlockedDecrement(&retire_pending); + } + ReleaseSRWLockExclusive(&retire_lock); + for (ID3D12Resource* resource : dropped) { + resource->Release(); + const LONG64 total = InterlockedIncrement64(&retire_freed); + if (total <= 8 || total % 1000 == 0) log("x2w-d3d12 retire: %lld desktop references dropped", total); + } +} + +// Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many +// resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. +struct RetireProbe { + unsigned cache_entries; + unsigned list_states; + unsigned list_holds; +}; +extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, void* list, RetireProbe* out) +{ + if (!out) return FALSE; + *out = {}; + if (!release_retired_enabled()) return FALSE; // like x2w_d3d12_budget_snapshot: nothing to report without the switch + if (Wrapper* r = as_wrapper(resource); r && r->own().kind == resource_kind && r->own().real) { + auto* real = static_cast(r->own().real); + AcquireSRWLockExclusive(&draw_lock); + out->cache_entries += static_cast(texture_uploads().count(real)); + ReleaseSRWLockExclusive(&draw_lock); + AcquireSRWLockShared(&target_lock); + for (const auto& view : view_targets()) out->cache_entries += view.second.resource == real; + ReleaseSRWLockShared(&target_lock); + AcquireSRWLockShared(&pending_writes_lock); + for (const auto& writes : pending_gpu_writes()) + out->cache_entries += static_cast(std::count(writes.second.begin(), writes.second.end(), real)); + ReleaseSRWLockShared(&pending_writes_lock); + } + if (Wrapper* l = as_wrapper(list); l && l->own().kind == list_kind) { + if (l->own().pass) out->list_states = static_cast(pass_of(l).states.size()); + AcquireSRWLockShared(&retire_lock); + if (const auto found = retire_list_holds.find(l); found != retire_list_holds.end()) + out->list_holds = static_cast(found->second.size()); + ReleaseSRWLockShared(&retire_lock); + } + return TRUE; +} + // The title exports __XMemAllocationHooks__ = {alloc(size, attributes), free(ptr, attributes), ...}. // Its alloc routine selects a hook chain by allocatorId (attribute bits 16-23). Around the creation // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that @@ -4467,6 +4797,7 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP Wrapper* w = wrap(resource, resource_kind); w->own().budget = x2w_budget::committed(device_of(self), resource, props->Type); w->own().title_memory = title_memory; + w->own().retire_when_idle = retire_class(*props, flags, copy, title_memory); note_resource(w, desc, info.SizeInBytes != ~0ull ? info.SizeInBytes : 0); *out = w; return S_OK; @@ -4666,6 +4997,13 @@ void report_budget(ID3D12CommandQueue* queue) // console present. Nothing is shown yet; frames are counted and a heartbeat is logged. HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_parameters, const void* present_parameters) { + // First, before anything reads or copies the surface: a presented resource keeps its old lifetime. + if (release_retired_enabled() && planes && plane_parameters) { + const auto* words = static_cast(plane_parameters); + if (x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast(words[2]), 8)) + retire_leave_class(*reinterpret_cast(words[2])); + } + drain_retired_resources(); Timed timed(time_present); X2W_ZONE("Present"); X2W_FRAME_MARK; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index fd78ce8dc..7f5fa07aa 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -234,6 +234,8 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) require_copy_state(self, from.resource, D3D12_RESOURCE_STATE_COPY_SOURCE); require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_COPY_DEST); static_cast(self->own().real)->CopyResource(to.resource, from.resource); + retire_hold(self, to.wrapper); + retire_hold(self, from.wrapper); if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width); note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); @@ -263,6 +265,7 @@ void __stdcall list_resolve_subresource(Wrapper* self, u64 destination, UINT des require_copy_state(self, to.resource, D3D12_RESOURCE_STATE_RESOLVE_DEST); static_cast(self->own().real) ->ResolveSubresource(to.resource, destination_subresource, from.resource, source_subresource, plan.format); + retire_hold(self, to.wrapper); // the source is multisampled, so never a member of the retire class mark_gpu_written(self, to); InterlockedIncrement(&list_resolves); } diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 3d9a4c31c..57ffaaf7c 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -147,14 +147,19 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO } // Bring a texture's desktop copy up to date with its guest backing before the copy reads or partly overwrites it, // and record that upload so a later sample does not replace the copied texels. - if (side_src.kind == x2w_list_copy_texture::Kind::subresource) upload_texture(self, src_wrapper, real_src); - if (side_dst.kind == x2w_list_copy_texture::Kind::subresource) upload_texture(self, dst_wrapper, real_dst); + // A resource of the retire class has no title memory, so there is nothing to upload and no cache entry to leave behind. + if (side_src.kind == x2w_list_copy_texture::Kind::subresource && !src_wrapper->own().retire_when_idle) + upload_texture(self, src_wrapper, real_src); + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && !dst_wrapper->own().retire_when_idle) + upload_texture(self, dst_wrapper, real_dst); if (!src_fixed) require_state(self, real_src, D3D12_RESOURCE_STATE_COPY_SOURCE); if (!dst_fixed) require_state(self, real_dst, D3D12_RESOURCE_STATE_COPY_DEST); D3D12_TEXTURE_COPY_LOCATION to = *dst, from = *src; to.pResource = real_dst; from.pResource = real_src; static_cast(self->own().real)->CopyTextureRegion(&to, x, y, z, &from, box ? box : nullptr); + retire_hold(self, dst_wrapper); + retire_hold(self, src_wrapper); InterlockedIncrement(&list_copy_texture_forwarded); } diff --git a/tests/startup_resource_retire.cpp b/tests/startup_resource_retire.cpp new file mode 100644 index 000000000..3eeb50f6f --- /dev/null +++ b/tests/startup_resource_retire.cpp @@ -0,0 +1,829 @@ +// X2W_D3D12_RELEASE_RETIRED=1: a committed 2D texture of the retire class (docs/startup-runtime.md#d3d12-resource-budget) +// gives up its desktop object only when no recorded list and no submission still refers to it and the release-time +// fence of every queue has passed. The retained column of the budget snapshot is the oracle for "the desktop object +// is destroyed": a ticket leaves it when its object dies. Readbacks go through the fixture's own desktop queue. +// +// startup_resource_retire [off] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1, and +// X2W_D3D12_RELEASE_RETIRED=1 unless the argument is "off") +// +// Cases with the switch on (each failure prints one "FAIL: ..." line and exits 5): +// 1 two lists record a copy of R, both closed and not submitted; R is released, every queue's release-time fence +// passes: R stays; the lists are submitted one by one and both readbacks are right. +// 2 a list that is Reset, or destroyed, without a submission drops its hold and invents nothing. +// 3 a second submission waits on its own fence; its list is Reset; R stays until the fence has passed. +// 4 a destination released after recording (slots 17, 16, 19), a list destroyed while its submission is held, a copy queue. +// 5 an open recording: D3D12 refuses its Reset (the holds stay); a list destroyed while open drops its state first. +// 6 a release that no list names waits for the release-time fence of a held queue. +// 7 buffer, render target, title memory, a view, MakeResident and Present keep the old lifetime next to ones that retire. +// "off" runs the same steps without the switch: nothing is ever freed, and the probe export reports nothing. +// Present opens the output window of the stand-in, as the other present fixtures do; without a desktop session the +// window presenter fails quietly and the case still holds, since the resource leaves the class before any window work. +#include "startup_stubs/resource_budget.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +struct RetireProbe { + unsigned cache_entries; // texture_uploads, pending_gpu_writes and view_targets entries naming the resource + unsigned list_states; // resources the open recording of the list moved out of COMMON + unsigned list_holds; // resources the list's recordings hold +}; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_retire_probe(void*, void*, RetireProbe*); + +namespace { +using namespace x2w_budget; + +constexpr UINT side = 64, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; // bounded drains, no sleeping +constexpr int seed_source = 3, seed_sentinel = 9; + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + // Same temporary private-data bridge as startup_resource_budget. The bridge reference is dropped on return. + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +std::uint8_t pattern_byte(int seed, UINT i) { return static_cast(i * 7 + seed * 13 + 1); } + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +// A guest resource and what the budget must say about it. +struct Res { + ComPtr guest; + const char* name = ""; + Category category = texture; + UINT64 bytes = 0; + bool released = false; // the guest dropped its last reference: the ticket sits in the retained column + bool freed = false; // the desktop object is destroyed: the ticket is gone +}; + +struct GuestList { + ComPtr allocator, list; +}; + +// A guest queue with a completion fence the host can wait on. +struct GuestQueue { + ComPtr queue, done; + ComPtr done_real; + UINT64 value = 0; +}; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ID3D12InfoQueue* debug; + ComPtr own_queue; + ComPtr own_allocator; + ComPtr own_list; + ComPtr own_fence; + UINT64 own_value = 0; + HANDLE event = nullptr; + ComPtr upload, readback; + Snapshot base{}; + std::deque pool; + GuestQueue direct, other, gated, copy; // submissions, drains, held submissions, a copy queue + GuestList drain_list; + D3D12_RESOURCE_DESC desc{}; + UINT64 texture_bytes = 0; + std::array iid_resource{__uuidof(ID3D12Resource)}; + + bool wait(ID3D12Fence* fence, UINT64 value) + { + if (fence->GetCompletedValue() >= value) return true; + if (FAILED(fence->SetEventOnCompletion(value, event))) return false; + return WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0; + } + bool own_run() + { + if (!require(own_list->Close(), "own list close")) return false; + ID3D12CommandList* lists[] = {own_list.Get()}; + own_queue->ExecuteCommandLists(1, lists); + if (!require(own_queue->Signal(own_fence.Get(), ++own_value), "own signal")) return false; + if (wait(own_fence.Get(), own_value)) return true; + std::puts("FAIL: the fixture's own queue did not finish"); + return false; + } + void own_barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) + { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + own_list->ResourceBarrier(1, &barrier); + } + D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* buffer) const + { + D3D12_TEXTURE_COPY_LOCATION location{buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + location.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}}; + return location; + } + // Writes the pattern of `seed` into a guest texture, through the desktop object that stands behind it. + bool fill(IUnknown* texture_object, int seed) + { + const auto real = desktop_object(guest, device, texture_object); + if (!real) return false; + void* mapped = nullptr; + if (!require(upload->Map(0, nullptr, &mapped), "upload map")) return false; + for (UINT i = 0; i < image_bytes; ++i) static_cast(mapped)[i] = pattern_byte(seed, i); + upload->Unmap(0, nullptr); + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_TEXTURE_COPY_LOCATION to{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const auto from = footprint(upload.Get()); + own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + return own_run(); + } + // True when the guest texture holds the pattern of `seed`. + bool holds(IUnknown* texture_object, int seed, const char* what) + { + const auto real = desktop_object(guest, device, texture_object); + if (!real) return false; + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) return false; + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const D3D12_TEXTURE_COPY_LOCATION from{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const auto to = footprint(readback.Get()); + own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + own_barrier(real.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, image_bytes}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + UINT wrong = image_bytes; + for (UINT i = 0; i < image_bytes; ++i) + if (static_cast(mapped)[i] != pattern_byte(seed, i)) { wrong = i; break; } + const std::uint8_t got = wrong < image_bytes ? static_cast(mapped)[wrong] : 0; + readback->Unmap(0, nullptr); + if (wrong < image_bytes) std::printf("FAIL: readback of %s differs at byte %u: got %02x want %02x\n", what, wrong, got, pattern_byte(seed, wrong)); + return wrong == image_bytes; + } + + // ---- guest objects ---- + Res& make_texture(const char* name, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, bool through_slot_27 = false) + { + D3D12_RESOURCE_DESC d = desc; + d.Flags = flags; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& r = pool.emplace_back(); + r.name = name; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + const HRESULT hr = through_slot_27 + ? invoke(guest, 27, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, &iid_resource[0], + r.guest.GetAddressOf()) + : invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, nullptr, + &iid_resource[0], r.guest.GetAddressOf()); + if (!require(hr, name)) pool.pop_back(), throw 4; + return r; + } + Res& make_buffer(const char* name) + { + D3D12_RESOURCE_DESC d{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& r = pool.emplace_back(); + r.name = name; + r.category = buffer; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + if (!require(invoke(guest, 27, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, &iid_resource[0], + r.guest.GetAddressOf()), name)) pool.pop_back(), throw 4; + return r; + } + void release(Res& r) + { + r.guest.Reset(); + r.released = true; + } + bool make_queue(GuestQueue& q, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + const D3D12_COMMAND_QUEUE_DESC d{type}; + ComPtr fence; + if (!require(invoke(guest, 8, &d, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "done fence")) + return false; + q.done_real = desktop_object(guest, device, q.done.Get()); + return q.done_real != nullptr; + } + // Everything the queue was given so far, including the release-time markers, has passed once this returns. + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (wait(q.done_real.Get(), q.value)) return true; + std::puts("FAIL: a queue did not reach its completion fence"); + return false; + } + bool make_list(GuestList& l, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + const unsigned list_desc[] = {static_cast(type), 2, 1, 0}; + return require(invoke(guest, 9, type, &__uuidof(ID3D12CommandAllocator), l.allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, l.allocator.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), + l.list.GetAddressOf()), "list") && + require(invoke(l.list.Get(), 139, l.allocator.Get(), nullptr), "list reset"); + } + // Reset onto a new allocator, as a frame loop does. Returns the HRESULT of the Reset. + HRESULT reset_list(GuestList& l, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + ComPtr next; + if (!require(invoke(guest, 9, type, &__uuidof(ID3D12CommandAllocator), next.GetAddressOf()), "allocator")) return E_FAIL; + const HRESULT hr = invoke(l.list.Get(), 139, next.Get(), nullptr); + if (SUCCEEDED(hr)) l.allocator = next; + return hr; + } + bool close(GuestList& l) { return require(invoke(l.list.Get(), 9), "list close"); } + void execute(GuestQueue& q, GuestList& l) + { + IUnknown* lists[] = {l.list.Get()}; + invoke(q.queue.Get(), 10, 1u, lists); + } + // ExecuteCommandLists on the second queue runs the retire drain; its empty list does nothing else. + void drain() { execute(other, drain_list); } + + // ---- the oracle ---- + Snapshot expected() const + { + Snapshot e = base; + for (const Res& r : pool) { + if (r.freed) continue; + Counts& c = r.released ? e.retained[r.category] : e.live[r.category]; + c.bytes += r.bytes; + ++c.objects; + } + return e; + } + static bool same(Counts a, Counts b) { return a.bytes == b.bytes && a.objects == b.objects; } + bool counts_match(Snapshot* actual_out = nullptr) const + { + Snapshot actual{}; + if (!x2w_d3d12_budget_snapshot(&actual, sizeof(actual))) return false; + if (actual_out) *actual_out = actual; + const Snapshot e = expected(); + bool pass = e.unmeasured == actual.unmeasured; + for (unsigned i = 0; i < category_count; ++i) pass = pass && same(e.live[i], actual.live[i]) && same(e.retained[i], actual.retained[i]); + return pass; + } + // The stage's expectation holds right now. `fail` is the one line a missing protection prints. + bool expect(const char* stage, const char* fail) + { + Snapshot actual{}; + if (counts_match(&actual)) return true; + const Snapshot e = expected(); + std::printf("FAIL: %s\n", fail); + for (unsigned i = 0; i < category_count; ++i) + if (!same(e.live[i], actual.live[i]) || !same(e.retained[i], actual.retained[i])) + std::printf(" stage '%s' %s live=%llu/%llu expected=%llu/%llu retained=%llu/%llu expected=%llu/%llu\n", stage, names[i], + actual.live[i].bytes, actual.live[i].objects, e.live[i].bytes, e.live[i].objects, + actual.retained[i].bytes, actual.retained[i].objects, e.retained[i].bytes, e.retained[i].objects); + if (e.unmeasured != actual.unmeasured) std::printf(" unmeasured=%llu expected=%llu\n", actual.unmeasured, e.unmeasured); + return false; + } + // Drains until the counters equal the expectation, at most settle_limit times, without sleeping. + bool settle(const char* stage, const char* fail) + { + for (int i = 0; i < settle_limit; ++i) { + drain(); + if (counts_match()) return true; + } + return expect(stage, fail); + } + // A few drains in a row never change the counters: nothing may go early. + bool stays(const char* stage, const char* fail) + { + for (int i = 0; i < 4; ++i) drain(); + return expect(stage, fail); + } + // Without the switch the export reports nothing (FALSE, zeros). + mutable bool probe_available = false; + RetireProbe probe(const Res* r, const GuestList* l) const + { + RetireProbe p{}; + probe_available = x2w_d3d12_retire_probe(r ? r->guest.Get() : nullptr, l ? l->list.Get() : nullptr, &p) != FALSE; + return p; + } +}; + +// ---- stages ---- + +// 1: two closed lists on R, R released while both are unsubmitted, then submitted one by one. +bool closed_lists(Context& c, bool on, Res& R, Res& D1, Res& D2, GuestList& L1, GuestList& L2) +{ + if (!c.make_list(L1) || !c.make_list(L2)) return false; + invoke(L1.list.Get(), 17, D1.guest.Get(), R.guest.Get()); + invoke(L2.list.Get(), 17, D2.guest.Get(), R.guest.Get()); + if (!c.close(L1) || !c.close(L2)) return false; + c.release(R); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (on) { + // The release-time fence of every queue has passed. The lists still name R. + if (!c.stays("closed lists", "early release (closed lists)")) return false; + const RetireProbe p = c.probe(&D1, &L1); + if (p.cache_entries) { + std::printf("FAIL: %u cache entries on a copy destination\n", p.cache_entries); + return false; + } + } else if (!c.stays("closed lists, switch off", "switch off changed the lifetime")) return false; + c.execute(c.direct, L1); + if (!c.sync(c.direct) || !c.holds(D1.guest.Get(), seed_source, "D1 after the first submission")) return false; + if (!c.holds(D2.guest.Get(), seed_sentinel, "D2 before its submission")) return false; + if (!c.stays("first list submitted", "early release (first submission)")) return false; + // A Reset on a fresh allocator drops L1's hold; L2 still names R. + if (!SUCCEEDED(c.reset_list(L1))) return false; + return c.stays("first list reset", "early release (second list)"); +} + +// 2: discard by Reset, discard by destroying the list; neither invents a submission. +bool discards(Context& c, bool on, Res& Rb, Res& D3, Res& Rc, Res& D4, GuestList& L3, GuestList& L4) +{ + if (!c.make_list(L3) || !c.make_list(L4)) return false; + invoke(L3.list.Get(), 17, D3.guest.Get(), Rb.guest.Get()); + invoke(L4.list.Get(), 17, D4.guest.Get(), Rc.guest.Get()); + if (!c.close(L3) || !c.close(L4)) return false; + c.release(Rb); + c.release(Rc); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("discard lists recorded", "early release (discard lists)")) return false; + if (!SUCCEEDED(c.reset_list(L3))) return false; // Reset of a closed, never submitted list + if (on) Rb.freed = true; + if (!c.settle("Reset discard", "a Reset list kept its resource")) return false; + L4.list.Reset(); // the guest destroys a closed, never submitted list + if (on) Rc.freed = true; + if (!c.settle("destroy discard", "a destroyed list kept its resource")) return false; + // Nothing was submitted for either list: the destinations still hold the sentinel. + return c.holds(D3.guest.Get(), seed_sentinel, "D3 after a discarded Reset") && + c.holds(D4.guest.Get(), seed_sentinel, "D4 after a discarded destroy"); +} + +// 3: a second submission behind its own fence. +bool second_submission(Context& c, bool on, Res& R, Res& D2, GuestList& L2) +{ + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence")) return false; + if (!require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) return false; + c.execute(c.gated, L2); + if (!SUCCEEDED(c.reset_list(L2))) return false; // the list's hold falls; only the submission names R + if (!c.stays("held submission", "early release (submission fence)")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync(c.gated)) return false; + if (on) R.freed = true; + if (!c.settle("submission passed", "R kept after its submission passed")) return false; + return c.holds(D2.guest.Get(), seed_source, "D2 after the second submission"); +} + +// 4a: destination released after recording (CopyResource), the destination only; the second copy checks the run. +bool destination_released(Context& c, bool on, Res& Rs, Res& D5, Res& Dout5, GuestList& L5) +{ + if (!c.make_list(L5)) return false; + invoke(L5.list.Get(), 17, D5.guest.Get(), Rs.guest.Get()); + invoke(L5.list.Get(), 17, Dout5.guest.Get(), Rs.guest.Get()); + if (!c.close(L5)) return false; + c.release(D5); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("destination released", "early release (copy destination)")) return false; + c.execute(c.direct, L5); + if (!c.sync(c.direct) || !c.holds(Dout5.guest.Get(), seed_source, "Dout5")) return false; + if (!c.stays("destination submitted", "early release (copy destination, submitted)")) return false; + if (!SUCCEEDED(c.reset_list(L5))) return false; + if (on) D5.freed = true; + return c.settle("destination list reset", "a Reset list kept its destination"); +} + +// 4b: CopyTextureRegion (slot 16): both ends released after recording. +bool texture_region(Context& c, bool on, Res& R10, Res& D10, Res& Dout10, GuestList& L) +{ + if (!c.make_list(L)) return false; + D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(D10.guest.Get())), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + D3D12_TEXTURE_COPY_LOCATION out{static_cast(static_cast(Dout10.guest.Get())), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(R10.guest.Get())), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + invoke(L.list.Get(), 16, &out, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + // The recording must not leave cache entries behind that name these resources by their raw pointer. + unsigned entries = 0; + for (const Res* r : {&R10, &D10, &Dout10}) entries += c.probe(r, &L).cache_entries; + if (entries != 0 || c.probe_available != on) { + std::printf("FAIL: %u cache entries name the resources of a texture copy (switch %s, probe %s)\n", entries, + on ? "on" : "off", c.probe_available ? "available" : "off"); + return false; + } + c.release(R10); + c.release(D10); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("texture region released", "early release (texture copy)")) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct) || !c.holds(Dout10.guest.Get(), seed_source, "Dout10")) return false; + if (!SUCCEEDED(c.reset_list(L))) return false; + if (on) R10.freed = D10.freed = true; + return c.settle("texture region list reset", "a Reset list kept its texture copy resources"); +} + +// 4c: ResolveSubresource (slot 19), destination released after recording. +bool resolve_destination(Context& c, bool on, GuestList& L) +{ + D3D12_RESOURCE_DESC msaa = c.desc; + msaa.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + msaa.SampleDesc = {4, 0}; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& source = c.pool.emplace_back(); + source.name = "resolve source"; + source.bytes = c.device->GetResourceAllocationInfo(0, 1, &msaa).SizeInBytes; + if (!require(invoke(c.guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &msaa, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &c.iid_resource[0], source.guest.GetAddressOf()), "msaa source")) return false; + Res& Dr = c.make_texture("resolve destination"); + Res& Dkeep = c.make_texture("resolve destination, kept"); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } rtv_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + ComPtr heap_object; + if (!require(invoke(c.guest, 14, &rtv_heap, &__uuidof(ID3D12DescriptorHeap), heap_object.GetAddressOf()), "rtv heap")) return false; + const UINT64 handle = invoke(heap_object.Get(), 9); + const D3D12_RENDER_TARGET_VIEW_DESC view{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2DMS, {}}; + invoke(c.guest, 20, source.guest.Get(), &view, handle); + constexpr float magenta[]{1.0f, 0.0f, 1.0f, 1.0f}; + if (!c.make_list(L)) return false; + invoke(L.list.Get(), 52, handle, magenta, 0u, static_cast(nullptr)); + invoke(L.list.Get(), 19, Dr.guest.Get(), 0u, source.guest.Get(), 0u, static_cast(DXGI_FORMAT_R8G8B8A8_UNORM)); + invoke(L.list.Get(), 19, Dkeep.guest.Get(), 0u, source.guest.Get(), 0u, static_cast(DXGI_FORMAT_R8G8B8A8_UNORM)); + if (!c.close(L)) return false; + { + const RetireProbe p = c.probe(&Dr, &L); + if (p.cache_entries) { + std::printf("FAIL: the resolve destination has %u cache entries\n", p.cache_entries); + return false; + } + } + c.release(Dr); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("resolve destination released", "early release (resolve destination)")) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + // Every pixel of the kept destination is the clear colour: the resolve ran. + const auto real = desktop_object(c.guest, c.device, Dkeep.guest.Get()); + if (!real) return false; + if (!require(c.own_allocator->Reset(), "own allocator") || !require(c.own_list->Reset(c.own_allocator.Get(), nullptr), "own list")) return false; + c.own_barrier(real.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const D3D12_TEXTURE_COPY_LOCATION from{real.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const auto to = c.footprint(c.readback.Get()); + c.own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + c.own_barrier(real.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (!c.own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, image_bytes}; + if (!require(c.readback->Map(0, &all, &mapped), "readback map")) return false; + bool uniform = true; + for (UINT i = 0; i < image_bytes; i += 4) { + const auto* p = static_cast(mapped) + i; + uniform = uniform && p[0] == 255 && p[1] == 0 && p[2] == 255 && p[3] == 255; + } + c.readback->Unmap(0, nullptr); + if (!uniform) { + std::puts("FAIL: the resolved destination is not the clear colour"); + return false; + } + if (!SUCCEEDED(c.reset_list(L))) return false; + if (on) Dr.freed = true; + return c.settle("resolve list reset", "a Reset list kept its resolve destination"); +} + +// 5: a list destroyed while its submission is still held, and a copy queue. +bool in_flight(Context& c, bool on, Res& R, Res& D, Res& Dout, GuestList& L, GuestQueue& queue, D3D12_COMMAND_LIST_TYPE type, + bool destroy_list, const char* fail) +{ + if (!c.make_list(L, type)) return false; + invoke(L.list.Get(), 17, D.guest.Get(), R.guest.Get()); + invoke(L.list.Get(), 17, Dout.guest.Get(), R.guest.Get()); + if (!c.close(L)) return false; + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence") || + !require(invoke(queue.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) + return false; + c.execute(queue, L); + c.release(R); + c.release(D); + if (destroy_list) L.list.Reset(); + else if (!SUCCEEDED(c.reset_list(L, type))) return false; + if (!c.stays("in flight", fail)) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync(queue)) return false; + if (on) R.freed = D.freed = true; + if (!c.settle("in flight passed", "resources kept after their submission passed")) return false; + return c.holds(Dout.guest.Get(), seed_source, "output of the held submission"); +} + +// 6: a recording that is still open. D3D12 refuses a Reset of an open list, so that Reset must leave its holds; a list +// destroyed while open drops the recording state that names the resources before their holds fall. +bool open_list(Context& c, bool on, Res& R7, Res& D7, Res& R11, Res& D11, GuestList& L, GuestList& L11) +{ + if (!c.make_list(L)) return false; + invoke(L.list.Get(), 17, D7.guest.Get(), R7.guest.Get()); + { + const RetireProbe p = c.probe(nullptr, &L); + if (on && p.list_states != 2) { + std::printf("FAIL: the open recording moved %u resources out of COMMON, expected 2\n", p.list_states); + return false; + } + } + c.release(R7); + c.release(D7); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("open list", "early release (open list)")) return false; + const HRESULT hr = c.reset_list(L); + std::printf("Reset of an open list: 0x%08lx\n", static_cast(hr)); + if (SUCCEEDED(hr)) { + const RetireProbe p = c.probe(nullptr, &L); + if (on && (p.list_states != 0 || p.list_holds != 0)) { + std::printf("FAIL: reset kept render state of a dropped recording (%u states, %u holds)\n", p.list_states, p.list_holds); + return false; + } + if (on) R7.freed = D7.freed = true; + if (!c.settle("open list reset", "a Reset open list kept its resources")) return false; + } else if (!c.stays("open list, reset refused", "early release (refused Reset)")) return false; + // The recording closes and runs without touching anything freed. + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + + if (!c.make_list(L11)) return false; + void* const destroyed = L11.list.Get(); // the wrapper outlives its Release + invoke(L11.list.Get(), 17, D11.guest.Get(), R11.guest.Get()); + { + const RetireProbe p = c.probe(nullptr, &L11); + if (on && (p.list_states != 2 || p.list_holds != 2)) { + std::printf("FAIL: the open recording has %u states and %u holds, expected 2 and 2\n", p.list_states, p.list_holds); + return false; + } + } + c.release(R11); + c.release(D11); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays("open list destroyed", "early release (open list, before destroy)")) return false; + L11.list.Reset(); + RetireProbe after{}; + x2w_d3d12_retire_probe(nullptr, destroyed, &after); + if (on && (after.list_states != 0 || after.list_holds != 0)) { + std::printf("FAIL: reset kept render state of a dropped recording (%u states, %u holds)\n", after.list_states, after.list_holds); + return false; + } + if (on) R11.freed = D11.freed = true; + return c.settle("open list destroyed", "a destroyed open list kept its resources"); +} + +// 7: a release with no list at all waits for the release-time fence of a held queue. +bool release_time_fence(Context& c, bool on) +{ + Res& Zg = c.make_texture("Zg"); + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) + return false; + c.release(Zg); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.copy)) return false; + if (!c.stays("release-time fence held", "early release (release-time fence)")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync(c.gated)) return false; + if (on) Zg.freed = true; + return c.settle("release-time fence passed", "a resource kept after the release-time fence passed"); +} + +// 8: what keeps the old lifetime, next to what retires. +bool classes(Context& c, bool on) +{ + constexpr SIZE_T page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + auto* title_memory = static_cast(VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!title_memory) return false; + Res& Z127 = c.make_texture("Z127"); + Res& Z27 = c.make_texture("Z27", D3D12_RESOURCE_FLAG_NONE, true); + Res& B = c.make_buffer("B (buffer)"); + Res& G = c.make_texture("G (render target)", D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Res& V = c.make_texture("V (view)"); + Res& M = c.make_texture("M (MakeResident)"); + Res& P = c.make_texture("P (presented)"); + Res& T = c.pool.emplace_back(); + T.name = "T (title memory)"; + T.bytes = c.texture_bytes = c.device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + if (!require(invoke(c.guest, 133, title_memory, &c.desc, D3D12_RESOURCE_STATE_COMMON, nullptr, &c.iid_resource[0], + T.guest.GetAddressOf()), "slot 133 texture")) return false; + if (!c.expect("classes created", "the control resources are not all live")) return false; + + // A view, MakeResident and Present each take their resource out of the class. + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr heap_object; + if (!require(invoke(c.guest, 14, &view_heap, &__uuidof(ID3D12DescriptorHeap), heap_object.GetAddressOf()), "view heap")) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + invoke(c.guest, 18, V.guest.Get(), &srv, invoke(heap_object.Get(), 9)); + IUnknown* residents[] = {M.guest.Get()}; + if (!require(invoke(c.guest, 34, 1u, residents), "MakeResident")) return false; + void* surface = P.guest.Get(); + const UINT64 plane[10]{0, 1, reinterpret_cast(&surface)}; + const UINT64 present_parameters[8]{}; + if (!require(invoke(c.direct.queue.Get(), 32, 1u, plane, present_parameters), "Present")) return false; + + struct Control { Res* resource; const char* fail; }; + const Control controls[] = { + {&B, "a buffer was freed"}, {&G, "a render target was freed"}, {&T, "a texture with title memory was freed"}, + {&V, "a resource with a view was freed"}, {&M, "a resource passed to MakeResident was freed"}, + {&P, "the presented surface was freed"}}; + for (const Control& control : controls) { + c.release(*control.resource); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (!c.stays(control.resource->name, control.fail)) return false; + } + c.release(Z127); + c.release(Z27); + if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; + if (on) Z127.freed = Z27.freed = true; + if (!c.settle("class released", "a resource of the class kept its desktop object")) return false; + VirtualFree(title_memory, 0, MEM_RELEASE); + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) + || (argc == 3 && std::strcmp(argv[2], "off"))) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + char debug_env[2]{}; + const bool debug_on = GetEnvironmentVariableA("X2W_D3D12_DEBUG", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_on) { + ComPtr debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) return 77; + debug->EnableDebugLayer(); + } + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") + || !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) return 3; + ComPtr debug; + if (debug_on && FAILED(device.As(&debug))) return 3; + if (debug) { + D3D12_MESSAGE_SEVERITY severities[] = { + D3D12_MESSAGE_SEVERITY_CORRUPTION, D3D12_MESSAGE_SEVERITY_ERROR, D3D12_MESSAGE_SEVERITY_WARNING}; + D3D12_INFO_QUEUE_FILTER filter{}; + filter.AllowList.NumSeverities = static_cast(std::size(severities)); + filter.AllowList.pSeverityList = severities; + if (FAILED(debug->AddStorageFilterEntries(&filter))) return 3; + debug->ClearStoredMessages(); + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + char switch_value[2]{}; + const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", switch_value, sizeof(switch_value)) == 1 && + switch_value[0] == '1'; + const bool off_mode = argc == 3; + if (switch_on == off_mode) { + std::puts("FAIL: the X2W_D3D12_RELEASE_RETIRED environment does not match the requested mode"); + return 2; + } + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", off_mode ? "off" : "on"); + const bool on = !off_mode; + + Context c{guest.Get(), device.Get(), debug.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.own_queue)), "own queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.own_allocator)), "own allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.own_allocator.Get(), nullptr, IID_PPV_ARGS(&c.own_list)), "own list") || + !require(c.own_list->Close(), "own list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.own_fence)), "own fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback")) return 4; + if (!c.make_queue(c.direct) || !c.make_queue(c.other) || !c.make_queue(c.gated) || + !c.make_queue(c.copy, D3D12_COMMAND_LIST_TYPE_COPY)) return 4; + if (!c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) { + std::puts("FAIL: budget snapshot unavailable"); + return 4; + } + + // Resources. Sources carry the source pattern, destinations the sentinel. + Res& R = c.make_texture("R"); + Res& Rb = c.make_texture("Rb"); + Res& Rc = c.make_texture("Rc"); + Res& Rs = c.make_texture("Rs"); + Res& R7 = c.make_texture("R7"); + Res& R8 = c.make_texture("R8"); + Res& R9 = c.make_texture("R9"); + Res& R10 = c.make_texture("R10"); + Res& R11 = c.make_texture("R11"); + Res* sources[] = {&R, &Rb, &Rc, &Rs, &R7, &R8, &R9, &R10, &R11}; + Res& D1 = c.make_texture("D1"); + Res& D2 = c.make_texture("D2"); + Res& D3 = c.make_texture("D3"); + Res& D4 = c.make_texture("D4"); + Res& D5 = c.make_texture("D5"); + Res& Dout5 = c.make_texture("Dout5"); + Res& D7 = c.make_texture("D7"); + Res& D8 = c.make_texture("D8"); + Res& Dout8 = c.make_texture("Dout8"); + Res& D9 = c.make_texture("D9"); + Res& Dout9 = c.make_texture("Dout9"); + Res& D10 = c.make_texture("D10"); + Res& Dout10 = c.make_texture("Dout10"); + Res& D11 = c.make_texture("D11"); + Res* destinations[] = {&D1, &D2, &D3, &D4, &D5, &Dout5, &D7, &D8, &Dout8, &D9, &Dout9, &D10, &Dout10, &D11}; + for (Res* r : sources) if (!c.fill(r->guest.Get(), seed_source)) return 4; + for (Res* r : destinations) if (!c.fill(r->guest.Get(), seed_sentinel)) return 4; + if (!c.expect("allocated", "the resources are not all live")) return 5; + + GuestList L1, L2, L3, L4, L5, L6, L8, L9, L10, L11, L12; + if (!closed_lists(c, on, R, D1, D2, L1, L2)) return 5; + std::puts("1 closed lists: R stays while both lists are unsubmitted, then both readbacks"); + if (!discards(c, on, Rb, D3, Rc, D4, L3, L4)) return 5; + std::puts("2 discard: a Reset list and a destroyed list free their resource without a submission"); + if (!second_submission(c, on, R, D2, L2)) return 5; + std::puts("3 second submission: held behind its own fence, then freed"); + if (!destination_released(c, on, Rs, D5, Dout5, L5)) return 5; + std::puts("4a copy destination released after recording stays until its list drops it"); + if (!texture_region(c, on, R10, D10, Dout10, L10)) return 5; + std::puts("4b CopyTextureRegion: both ends held"); + if (!resolve_destination(c, on, L12)) return 5; + std::puts("4c ResolveSubresource: destination held"); + if (!in_flight(c, on, R8, D8, Dout8, L8, c.gated, D3D12_COMMAND_LIST_TYPE_DIRECT, true, "early release (list destroyed in flight)")) return 5; + std::puts("5a list destroyed while its submission is held"); + if (!in_flight(c, on, R9, D9, Dout9, L9, c.copy, D3D12_COMMAND_LIST_TYPE_COPY, false, "early release (copy queue)")) return 5; + std::puts("5b copy queue"); + if (!open_list(c, on, R7, D7, R11, D11, L6, L11)) return 5; + std::puts("6 open recording: a refused Reset keeps its holds, a destroyed open list drops them"); + if (!release_time_fence(c, on)) return 5; + std::puts("7 release-time fence: a release with no list waits for the held queue"); + if (!classes(c, on)) return 5; + std::puts("8 classes: buffer, render target, title memory, view, MakeResident and Present keep the old lifetime"); + } catch (int code) { + return code; + } + const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("debug_errors_or_warnings=%llu\n", errors); + if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(on ? "release-retired checks passed" : "switch-off checks passed"); + return 0; +} From dbab5435326c84ee3929d4b5cd82c7e0c98a98ae Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:30:27 +0100 Subject: [PATCH 077/232] startup: accept a null-export-only pixel stage in the slot 57 role check (#2421) A pixel stage whose only export is the null target carries no colour output (LLVM SILateBranchLowering emits "exp null ... done vm" for such shaders; Mesa ACO create_fs_null_export does the same when there are no other exports), so the slot 57 role check treats it as depth-only. Any other non-colour target stays refused. The shared classify_decoded is unchanged. The request still ends in "slot 57 mesh code emission is unavailable". Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/startup_gfx2hlsl_watch_check.py | 6 ++++++ tools/startup/gfx2hlsl.py | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index c96006fdc..45cd16405 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -106,6 +106,12 @@ def mesh57_fixture(ms, ps, expected, tamper=False): mesh57_fixture(mesh, pixel, 'slot 57 mesh code emission is unavailable') mesh57_fixture(mesh, b'', 'slot 57 mesh code emission is unavailable') mesh57_fixture(vertex, pixel, 'slot 57 mesh stage has no verified allocation and primitive export') +# A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check. +null_export = struct.pack('<3I', 0xf8001890, 0, endpgm) +mesh57_fixture(mesh, null_export, 'slot 57 mesh code emission is unavailable') +# Controls: a position export, or a null export mixed with one, stays refused. +mesh57_fixture(mesh, struct.pack('<3I', *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') +mesh57_fixture(mesh, struct.pack('<5I', 0xf8001890, 0, *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') mesh57_fixture(mesh, vertex, 'slot 57 pixel stage has an incompatible export or termination') mesh57_fixture(mesh, pixel, 'slot 57 mesh request key mismatch', tamper=True) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 964f98cd6..ebff0b94f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5796,7 +5796,9 @@ def inspect_mesh57_request(out_dir, key): raise Unsupported('slot 57 mesh stage has no verified allocation and primitive export') if ps: pixel = decode(strip_header(ps)) - if not pixel or pixel[-1][2] != 's_endpgm' or classify_decoded(pixel) != 'ps': + # A pixel shader with no colour output ends in a null-target export (LLVM SILateBranchLowering, Mesa ACO create_fs_null_export): depth-only. + null_only = {a.split()[1] for _, _, op, a in pixel if op == 'exp'} == {'null'} + if not pixel or pixel[-1][2] != 's_endpgm' or classify_decoded(pixel) != 'ps' and not null_only: raise Unsupported('slot 57 pixel stage has an incompatible export or termination') for offset, _, op, _ in mesh: if op.startswith('ds_'): From 18d623e6064bfe944c6033737a74e05a27707248 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 19:35:04 +0100 Subject: [PATCH 078/232] startup: lower s_waitcnt_depctr as a wait without effect in gfx2hlsl (#2445) LLVM defines S_WAITCNT_DEPCTR with one immediate and no register definition, use or side effect, and emits it only as a hazard delay. The translator now treats it like s_nop. A pure-Python check compares the translation with and without the wait for five immediates, keeps three neighbouring SOPP forms refused, and checks the encodings against llvm-mc. Refs #2413 Co-authored-by: Claude Fable 5.2 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 3 + .../startup_gfx2hlsl_waitcnt_depctr_check.py | 94 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 6 +- 5 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_waitcnt_depctr_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 979120845..10065406a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -81,6 +81,7 @@ jobs: (["tests/mesh_shadow_check.py", *COMMON_LLVM], {}), (["tests/startup_sampler_heap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cmp16_check.py", "binary", "llvm-mc-15", "llvm-objcopy-15"], {}), @@ -237,6 +238,7 @@ jobs: tests/startup_compute_request_offline_check.py \ tests/compute_container_index_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ + tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 04ec6110c..2c9e2bdda 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,6 +180,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py ./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3962c2466..84714722f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3055,6 +3055,9 @@ if(EXISTS "${INTAKE_PYTHON}") # 32-bit scalar complement logic: s_nand_b32, s_nor_b32 and s_xnor_b32 against an integer reference (#1919). add_test(NAME startup_gfx2hlsl_sop2_complement COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sop2_complement_check.py") + # s_waitcnt_depctr is a hazard delay without architectural effect: the translation is unchanged by it (#2413). + add_test(NAME startup_gfx2hlsl_waitcnt_depctr COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_waitcnt_depctr_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") diff --git a/tests/startup_gfx2hlsl_waitcnt_depctr_check.py b/tests/startup_gfx2hlsl_waitcnt_depctr_check.py new file mode 100644 index 000000000..42032c6be --- /dev/null +++ b/tests/startup_gfx2hlsl_waitcnt_depctr_check.py @@ -0,0 +1,94 @@ +"""s_waitcnt_depctr is a wait without architectural effect in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_waitcnt_depctr_check.py + startup_gfx2hlsl_waitcnt_depctr_check.py binary + +LLVM defines S_WAITCNT_DEPCTR (SOPP 0x23, gfx10 and later) with one immediate operand and no register +definition, use or side effect (llvm/lib/Target/AMDGPU/SOPInstructions.td) and emits it only as a hazard delay +(GCNHazardRecognizer.cpp, fixVMEMtoScalarWriteHazards, immediate 0xffe3). The translator therefore lowers it +like s_nop: a program with the wait must translate to the same text and state as the program without it. + +Controls: s_wait_idle, s_sleep and s_round_mode stay refused, and replacing the wait by a scalar move changes +the compared text, so the comparison can fail. +""" +from pathlib import Path +import re +import struct +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_scalar_m0_check import ProbeStage, encode_sop1, encode_sop2 # noqa: E402 + + +def sopp(op, imm=0): + return struct.pack(' Date: Wed, 25 Nov 2026 19:36:51 +0100 Subject: [PATCH 079/232] tools: cache parse and reg_range results in gfx2hlsl (#2453) The analysis passes parse the text of each decoded instruction many times. Cache the parsed tuple per instruction text and the register range per token; parse() still returns fresh lists, so callers that edit the operand list are unaffected. Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tools/startup/gfx2hlsl.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a8e4934c5..0d58e1df5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6,6 +6,7 @@ The output is HLSL for both stages plus a manifest that tells the runtime what to bind where. """ from contextlib import suppress +import functools import os import re import struct @@ -434,15 +435,21 @@ def split_top(text, sep=','): return parts -def parse(asm): - """-> (mnemonic, [operands], [modifier tokens])""" +@functools.lru_cache(maxsize=None) +def parse_cached(asm): name, _, rest = asm.partition(' ') ops = split_top(rest) mods = [] if ops: tail = split_top(ops[-1], ' ') ops[-1], mods = tail[0], tail[1:] - return name, ops, mods + return name, tuple(ops), tuple(mods) + + +def parse(asm): + """-> (mnemonic, [operands], [modifier tokens]); the analysis passes parse each instruction many times.""" + name, ops, mods = parse_cached(asm) + return name, list(ops), list(mods) FLOATS = {'0.5': 0.5, '-0.5': -0.5, '1.0': 1.0, '-1.0': -1.0, '2.0': 2.0, '-2.0': -2.0, '4.0': 4.0, '-4.0': -4.0, @@ -453,6 +460,7 @@ def fbits(x): return struct.unpack(' ('s', 8, 11); 's8' -> ('s', 8, 8); 'v[1:3]' -> ('v', 1, 3); 'exec'/'vcc' pairs too.""" m = re.fullmatch(r'([sv])\[(\d+):(\d+)\]', tok) From 530e67968bbd7423e9d60333a8b9c6bb3da009cf Mon Sep 17 00:00:00 2001 From: sydney-0o <215686885+sydney-0o@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:37:24 +0500 Subject: [PATCH 080/232] gpu: wait for both leased XMem ranges in cached mesh dispatches (#2375) Compose the independently published ranges from R0Y00/Xbox2Windows#2303 and R0Y00/Xbox2Windows#2332. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakePresets.json | 2 +- docs/experiments.md | 6 ++ tests/startup_indirect_mesh_lease.inl | 110 ++++++++++++++++++++------ 3 files changed, 95 insertions(+), 23 deletions(-) diff --git a/CMakePresets.json b/CMakePresets.json index f3a14a666..d3cdebc55 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 9a618c3f7..c839cadda 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8958,6 +8958,12 @@ pixels and four clear pixels. Replacing the argument page between recording and submission left the entire target clear. Restoring the page restored the draw. Both adapters ran with the D3D12 debug layer enabled. +The ordered fixture also keeps the target clear when only the SRV writer has +been submitted and when the SRV page is remapped before submission. A gated +DIRECT consumer still paints eight red pixels after the guest unmaps both +pages. Neither physical page can be reused until the consumer fence finishes. +Both pages are reusable afterward. + ```powershell ctest --preset release --no-tests=error -j1 -R '^startup_indirect_mesh_lease_(warp|hardware)_dual' -V ``` diff --git a/tests/startup_indirect_mesh_lease.inl b/tests/startup_indirect_mesh_lease.inl index 7f5fb532a..9168f79d0 100644 --- a/tests/startup_indirect_mesh_lease.inl +++ b/tests/startup_indirect_mesh_lease.inl @@ -379,12 +379,18 @@ bool check_mesh_dual_xmem(ID3D12Device* device, ID3D12Device* guest, const wchar check(static_cast(skip_srv) + static_cast(skip_arguments) + static_cast(init_only) <= 1 ? S_OK : E_FAIL, "select one combined mesh control"); const bool control = skip_srv || skip_arguments; + const bool ordered_case = !control && !init_only; auto consume = init_only ? refused : draw(skip_srv ? green : red, skip_srv ? green : skip_arguments ? black : red); const char* label = init_only ? "combined mesh initialized arguments: zero groups" : skip_srv ? "combined mesh stale SRV: two green halves" : skip_arguments ? "combined mesh stale arguments: left red, right clear" : "combined mesh fresh inputs: two red halves"; colour.start(); + if (ordered_case) { + if (!verify(refused, "combined mesh refuses recorded but unsubmitted argument writer")) return false; + check(colour.completion->GetCompletedValue() == 0 ? S_OK : E_FAIL, + "refusal completes with the published SRV writer still gated"); + } arguments.start(); bool ordered = false; consume.queued = [&](ID3D12Fence* done) { @@ -405,36 +411,96 @@ bool check_mesh_dual_xmem(ID3D12Device* device, ID3D12Device* guest, const wchar colour.finish(); arguments.finish(); - if (!control && !init_only) { - auto remapped = refused; - ULONG_PTR replacement{}, count = 1; - check(colour.alloc(0x280, &count, &replacement) && count == 1 ? S_OK : E_FAIL, - "allocate replacement argument page"); - void* const replaced_address = arguments.cpu; - remapped.before_submit = [&] { - check(colour.map(&replaced_address, 1, &replacement) ? S_OK : E_FAIL, - "remap only the argument page before submission"); - std::memcpy(arguments.cpu + arguments.record_offset, MeshLeaseWriter::old_groups.data(), - sizeof(MeshLeaseWriter::old_groups)); - check(arguments.inspect(arguments.address()) != arguments.published_page && - colour.inspect(colour.address()) == colour.published_page ? S_OK : E_FAIL, - "argument page identity changed while SRV page stayed mapped"); + if (ordered_case) { + for (std::size_t page = 0; page < std::size(colour.original); ++page) { + const bool root_page = page == 0; + auto& writer = root_page ? colour : arguments; + auto& other = root_page ? arguments : colour; + auto remapped = refused; + ULONG_PTR replacement{}, count = 1; + check(colour.alloc(0x280, &count, &replacement) && count == 1 ? S_OK : E_FAIL, + "allocate replacement mesh page"); + void* const replaced_address = writer.cpu; + remapped.before_submit = [&] { + check(colour.map(&replaced_address, 1, &replacement) ? S_OK : E_FAIL, + "remap one mesh input before submission"); + if (root_page) + std::memcpy(writer.cpu + writer.record_offset, &green, sizeof(green)); + else + std::memcpy(writer.cpu + writer.record_offset, MeshLeaseWriter::old_groups.data(), + sizeof(MeshLeaseWriter::old_groups)); + check(writer.inspect(writer.address()) != writer.published_page && + other.inspect(other.address()) == other.published_page ? S_OK : E_FAIL, + "only the selected mesh page identity changed"); + }; + const bool unchanged = verify(remapped, root_page + ? "combined mesh with remapped root SRV leaves target clear" + : "combined mesh with remapped arguments leaves target clear"); + check(colour.map(&replaced_address, 1, &colour.original[page]) && + colour.free_pages(1, &replacement) ? S_OK : E_FAIL, "restore the original mesh page"); + if (!unchanged || !verify(draw(red, red), "combined mesh reads both ranges after restoring mapping")) return false; + } + + const auto gate = colour.create_fence(); + struct ReleaseGate { + ID3D12Fence* gate; + ~ReleaseGate() { gate->Signal(1); } + } release{gate.Get()}; + const auto native = native_object(device, guest, queue.Get()); + check(native->Wait(gate.Get(), 1), "hold the combined consumer"); + const auto probe_reusable_pages = [&] { + // Hold both probe allocations at once to test for both original + // pages. Compare section offsets because the word offsets differ. + ULONG_PTR tokens[2]{}, count = std::size(tokens); + void* const probes[]{colour.cpu + 2 * MeshLeaseWriter::page, colour.cpu + 3 * MeshLeaseWriter::page}; + check(colour.alloc(0x280, &count, tokens) && count == std::size(tokens) && + colour.map(probes, count, tokens) ? S_OK : E_FAIL, "map two physical probe pages"); + std::array reusable{}; + for (std::size_t i = 0; i < std::size(probes); ++i) { + const auto page = colour.inspect(colour.address() + (2 + i) * MeshLeaseWriter::page).first; + reusable[0] |= page == colour.published_page.first; + reusable[1] |= page == arguments.published_page.first; + } + const ULONG_PTR empty[]{0, 0}; + check(colour.map(probes, count, empty) && colour.free_pages(count, tokens) ? S_OK : E_FAIL, + "release both physical probe pages"); + return reusable; + }; + auto pinned = draw(red, red); + pinned.drop_recording = true; + pinned.queued = [&](ID3D12Fence* done) { + release_pages(); + const bool pending = done->GetCompletedValue() == 0; + const auto reusable = probe_reusable_pages(); + check(gate->Signal(1), "release the combined consumer"); + check(pending && reusable == std::array{false, false} ? S_OK : E_FAIL, + "neither original page is reusable before the DIRECT fence"); }; - const bool unchanged = verify(remapped, "combined mesh submit with remapped argument page leaves target clear"); - check(colour.map(&replaced_address, 1, &colour.original[1]) && colour.free_pages(1, &replacement) ? S_OK : E_FAIL, - "restore the original argument page"); - if (!unchanged || !verify(draw(red, red), "combined mesh reads both original ranges after restoring mapping")) return false; + if (!verify(pinned, "combined mesh still reads both XMem pages after guest unmap")) return false; + const auto deadline = GetTickCount64() + 3000; + while (probe_reusable_pages() != std::array{true, true}) { + check(GetTickCount64() < deadline ? S_OK : E_FAIL, "both original pages return after the DIRECT fence"); + Sleep(1); + } + std::puts("both original XMem pages returned after the DIRECT fence"); + } else { + release_pages(); } - release_pages(); std::ifstream log{std::filesystem::path(log_path)}; check(log ? S_OK : E_FAIL, "open combined mesh handoff log"); const std::string lines{std::istreambuf_iterator(log), {}}; log.close(); DeleteFileW(log_path.c_str()); - check(lines.find("mesh XMem read has no submitted writer for the required size") != std::string::npos && - (control || init_only || lines.find("mesh XMem submit refused: writer or live page identity changed") != std::string::npos) - ? S_OK : E_FAIL, "check combined mesh missing-writer and remapped-argument refusals"); + constexpr char missing_writer[] = "mesh XMem read has no submitted writer for the required size"; + constexpr char remapped_page[] = "mesh XMem submit refused: writer or live page identity changed"; + const auto first_missing = lines.find(missing_writer); + const auto first_remap = lines.find(remapped_page); + check(first_missing != std::string::npos && + (!ordered_case || (lines.find(missing_writer, first_missing + sizeof(missing_writer) - 1) != std::string::npos && + first_remap != std::string::npos && + lines.find(remapped_page, first_remap + sizeof(remapped_page) - 1) != std::string::npos)) + ? S_OK : E_FAIL, "check both missing-writer and both remapped-page refusals"); check_lease_debug(info); return true; } From 899cadbafbf7ba44cadef50bb1c0b9a0d208f72d Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 02:37:58 +0800 Subject: [PATCH 081/232] shader: lower measured narrow integer render target exports (#2392) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/startup-runtime.md | 10 ++-- tests/startup_gfx2hlsl_export_mask_check.py | 24 +++++--- tests/startup_mrt_check.py | 63 ++++++++++++++++----- tests/startup_stream_setup.h | 12 ++++ tools/startup/gfx2hlsl.py | 8 +-- 5 files changed, 85 insertions(+), 32 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 5ba9513ec..fb42f2a1f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2147,12 +2147,14 @@ These are measured on one executable; treat them as hypotheses for others. negative denormal. Uncompressed exports to `R8G8B8A8_UINT` and `R8G8B8A8_SINT` use unsigned and signed integer shader outputs. The output merger clamps each channel to 0–255 or −128–127 respectively. With export words `ffffffff ffffff7f 00000080 00000100`, the stored bytes are - `ff ff 80 ff` for UINT and `ff 80 7f 7f` for SINT. The other 8- and 16-bit integer views - still return `unverified UINT/SINT RTV format `. + `ff ff 80 ff` for UINT and `ff 80 7f 7f` for SINT. The same conversion applies to one or two + 8-bit channels and one, two or four 16-bit channels. An uncompressed UINT export to + `R10G10B10A2_UINT` clamps RGB to 0–1023 and alpha to 0–3 before storage. Three-channel + `R32G32B32_UINT` and `R32G32B32_SINT` views still require readback verification. Uncompressed binary32 FLOAT outputs bitcast the export words after XOR with a private zero-valued entry constant so optimized FXC keeps denormal bit patterns. UNORM outputs still - undergo float-to-UNORM conversion. Packed integer exports and other integer formats remain - unsupported by this path. + undergo float-to-UNORM conversion. Compressed gfx1013 integer exports remain unsupported, + including when the destination is `R10G10B10A2_UINT`. - A colour export that leaves channels `off` does not write them, so the target keeps what it held there (#1674). `gfx2hlsl.py` records the written channels per target and writes `wmask 0x` to the manifest when an export leaves any channel unwritten. The draw diff --git a/tests/startup_gfx2hlsl_export_mask_check.py b/tests/startup_gfx2hlsl_export_mask_check.py index d090f2a85..27a22105a 100644 --- a/tests/startup_gfx2hlsl_export_mask_check.py +++ b/tests/startup_gfx2hlsl_export_mask_check.py @@ -159,21 +159,27 @@ def revision_key(revision): check('refused: partial compr export to param0', got == 'partial compressed export to param0', got) # 7. Typed colour targets (#1999 F): each verified format gets a matching shader output. -typed = (('R32G32B32A32_UINT', 3, 'uint4 mrt0', 'uint4(v0'), ('R32G32B32A32_SINT', 4, 'int4 mrt0', 'asint(uint4'), - ('R32G32_UINT', 17, 'uint4 mrt0', 'uint4(v0'), ('R32G32_SINT', 18, 'int4 mrt0', 'asint(uint4'), - ('R8G8B8A8_UINT', 30, 'uint4 mrt0', 'uint4(v0'), ('R8G8B8A8_SINT', 32, 'int4 mrt0', 'asint(uint4'), - ('R32_UINT', 42, 'uint4 mrt0', 'uint4(v0'), ('R32_SINT', 43, 'int4 mrt0', 'asint(uint4'), - ('R32G32_FLOAT', 16, 'float4 mrt0', 'float4(F(('), ('R32_FLOAT', 41, 'float4 mrt0', 'float4(F((')) -for name, fmt, signature, store in typed: +typed = ( + ('R32G32B32A32_UINT', 3), ('R32G32B32A32_SINT', 4), ('R16G16B16A16_UINT', 12), ('R16G16B16A16_SINT', 14), + ('R32G32_FLOAT', 16), ('R32G32_UINT', 17), ('R32G32_SINT', 18), ('R10G10B10A2_UINT', 25), + ('R8G8B8A8_UINT', 30), ('R8G8B8A8_SINT', 32), ('R16G16_UINT', 36), ('R16G16_SINT', 38), + ('R32_FLOAT', 41), ('R32_UINT', 42), ('R32_SINT', 43), ('R8G8_UINT', 50), ('R8G8_SINT', 52), + ('R16_UINT', 57), ('R16_SINT', 59), ('R8_UINT', 62), ('R8_SINT', 64), +) +expected_output = {'UINT': ('uint4 mrt0', 'uint4(v0'), 'SINT': ('int4 mrt0', 'asint(uint4'), + 'FLOAT': ('float4 mrt0', 'float4(F((')} +for name, fmt in typed: + signature, store = expected_output[name.rsplit('_', 1)[1]] got = translate(exp(0, 0xf, (0, 1, 2, 3)), (fmt,)) ok = isinstance(got, tuple) and signature in got[0] and store in assignment(got[0], 0).replace('uint4(U(v', 'uint4(v') check('typed target ' + name, ok, repr(got)[:300]) -for name, fmt in (('R16G16B16A16_UINT', 12), ('R16G16B16A16_SINT', 14), ('R8_UINT', 62), - ('R16_SINT', 59), ('R8_SINT', 64)): +for name, fmt in (('R32G32B32_UINT', 7), ('R32G32B32_SINT', 8)): got = translate(exp(0, 0xf, (0, 1, 2, 3)), (fmt,)) want = 'unverified %s RTV format %d' % ('UINT' if fmt in G.UINT_RTVS else 'SINT', fmt) check('typed target %s refused' % name, got == want, repr(got)[:200]) -for fmt in (30, 32): +for name, fmt in typed: + if name.endswith('_FLOAT'): + continue got = translate(exp(0, 0xf, (0, 1, 2, 3), compr=True), (fmt,)) check('packed integer export refused for format %d' % fmt, got == 'packed integer export mrt0', repr(got)[:200]) diff --git a/tests/startup_mrt_check.py b/tests/startup_mrt_check.py index 62d9a3a0e..e4a48f226 100644 --- a/tests/startup_mrt_check.py +++ b/tests/startup_mrt_check.py @@ -15,7 +15,16 @@ INTEGER_WORD = 0x80000001 # Typed formats whose channels are all 32 bits: DXGI value -> (shader output type, channels). INTEGER_FORMATS = ((42, 'uint', 1), (43, 'int', 1), (17, 'uint', 2), (18, 'int', 2), (3, 'uint', 4), (4, 'int', 4)) -REFUSED_INTEGER_FORMATS = (12, 14, 57, 59, 62, 64) +REFUSED_INTEGER_FORMATS = (7, 8) # Three 32-bit channels have no verified RTV readback. +# MRT0 bytes for export words (ffff7ffe, 21, 235, 104), ordered R to A in little-endian storage. +NARROW_INTEGER_FORMATS = ( + (12, 'uint', 'ffff210035020401'), (14, 'int', '0080210035020401'), # RGBA16 + (25, 'uint', 'ff8750e3'), # RGB10A2: R=1023, G=33, B=565, A=3 + (36, 'uint', 'ffff2100'), (38, 'int', '00802100'), # RG16 + (50, 'uint', 'ff21'), (52, 'int', '8021'), # RG8 + (57, 'uint', 'ffff'), (59, 'int', '0080'), # R16 + (62, 'uint', 'ff'), (64, 'int', '80'), # R8 +) def pixel(values, unorm=False): @@ -71,13 +80,17 @@ def draw(fmt, word=0, wanted_draw=True): assert result.returncode == 0 and actual_draw == wanted_draw, result.stderr return output.read_bytes(), result.stderr - def request(fmt, formats): + def queue_request(fmt, formats): pixels, log = draw(fmt, wanted_draw=False) assert 'no RTV translation' in log, log base = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) line = 'rtv1 ' + ' '.join(map(str, (base, *formats))) key = f'{gfx2hlsl.fnv(line.encode("ascii")):016x}' assert (cache / f'req_{key}.rtv').read_text() == line + return key, line, pixels + + def request(fmt, formats): + key, line, pixels = queue_request(fmt, formats) subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) assert (cache / f'{key}.txt').read_text().splitlines()[-1] == line return key, pixels @@ -108,17 +121,17 @@ def compile_pair(key): assert pixels == struct.pack(f'<{channels}I4B', *words, 255, 0, 0, 255), pixels.hex() print(f'{kind} {backend} {expected_type} format {fmt} MRT0={pixels[:4 * channels].hex()}; UNORM MRT1=ff0000ff') if fmt == 42: - for narrow in REFUSED_INTEGER_FORMATS: - line = f'rtv1 {gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes())} {narrow} 28' + for unverified in REFUSED_INTEGER_FORMATS: + line = f'rtv1 {gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes())} {unverified} 28' refused = f'{gfx2hlsl.fnv(line.encode("ascii")):016x}' marker = cache / f'req_{refused}.rtv' marker.write_text(line) result = gfx2hlsl.translate_request(cache, int(refused, 16)) - assert re.fullmatch(rf'unsupported: unverified (UINT|SINT) RTV format {narrow}', result), result + assert re.fullmatch(rf'unsupported: unverified (UINT|SINT) RTV format {unverified}', result), result assert not (cache / f'{refused}.txt').exists() # Later --pending runs would retry this synthetic request on every valid format. marker.unlink() - print(f'{kind} {backend} narrow integer formats {REFUSED_INTEGER_FORMATS} refused at translation') + print(f'{kind} {backend} three-channel integer formats {REFUSED_INTEGER_FORMATS} refused at translation') # A pre-existing base translation may lack its original request files. base = f'{gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()):016x}' compile_pair(base) @@ -133,6 +146,17 @@ def compile_pair(key): assert pixels.hex() == '000000000000ffff', pixels.hex() print(f'{kind} {backend} stale signedness control: refused before PSO creation') + def low_bits_control(key, fmt, trunc, expected): + source = (cache / f'{key}.ps.hlsl').read_text() + end = ' return o;' + assert source.count(end) == 1 + wrong = cache / f'{key}.low-bits.hlsl' + wrong.write_text(source.replace(end, f' o.mrt0 = {trunc};\n{end}')) + compile_shader(compiler, kind, 'ps', wrong, cache / f'{key}.ps.cso', cache / f'{key}.low-bits.asm') + control, _ = draw(fmt) + assert control == bytes.fromhex(expected + 'ff0000ff'), control.hex() + return control[:-4].hex() + # Distinguish signed and unsigned saturation from writing the low eight bits. ps.write_bytes(pixel((0xffffffff, 0xffffff7f, 0x80, 0x100), unorm=True)) for fmt, expected_type, rgba in ((30, 'uint', 'ffff80ff'), (32, 'int', 'ff807f7f')): @@ -142,16 +166,25 @@ def compile_pair(key): assert outputs == {'0': expected_type, '1': 'float'}, outputs pixels, _ = draw(fmt) assert pixels == bytes.fromhex(rgba + 'ff0000ff'), pixels.hex() - source = (cache / f'{key}.ps.hlsl').read_text() - end = ' return o;' - assert source.count(end) == 1 trunc = 'o.mrt0 & 255u' if fmt == 30 else 'asint(asuint(o.mrt0) << 24u) >> 24u' - wrong = cache / f'{key}.low-byte.hlsl' - wrong.write_text(source.replace(end, f' o.mrt0 = {trunc};\n{end}')) - compile_shader(compiler, kind, 'ps', wrong, cache / f'{key}.ps.cso', cache / f'{key}.low-byte.asm') - control, _ = draw(fmt) - assert control == bytes.fromhex('ff7f8000ff0000ff'), control.hex() - print(f'{kind} {backend} RGBA8 {expected_type} MRT0={rgba}; low-byte control={control[:4].hex()}') + control = low_bits_control(key, fmt, trunc, 'ff7f8000') + print(f'{kind} {backend} RGBA8 {expected_type} MRT0={rgba}; low-byte control={control}') + + # All views share this shader, so one pending scan can publish their variants. + ps.write_bytes(pixel((0xffff7ffe, 0x21, 0x235, 0x104), unorm=True)) + queued = {fmt: queue_request(fmt, (fmt, 28)) for fmt, _, _ in NARROW_INTEGER_FORMATS} + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) + for fmt, expected_type, rgba in NARROW_INTEGER_FORMATS: + key, record, _ = queued[fmt] + assert (cache / f'{key}.txt').read_text().splitlines()[-1] == record + assert compile_pair(key) == {'0': expected_type, '1': 'float'} + pixels, _ = draw(fmt) + assert pixels == bytes.fromhex(rgba + 'ff0000ff'), (fmt, pixels.hex()) + if fmt == 14: + low_bits_control(key, fmt, 'asint(asuint(o.mrt0) << 16u) >> 16u', 'fe7f210035020401') + if fmt == 25: + low_bits_control(key, fmt, 'o.mrt0 & uint4(1023u, 1023u, 1023u, 3u)', 'fe875023') + print(f'{kind} {backend} narrow format {fmt} MRT0={rgba}; UNORM MRT1=ff0000ff') ps.write_bytes(pixel(FLOAT_WORDS)) key, _ = request(2, (2,)) diff --git a/tests/startup_stream_setup.h b/tests/startup_stream_setup.h index 32216c871..09349f842 100644 --- a/tests/startup_stream_setup.h +++ b/tests/startup_stream_setup.h @@ -46,6 +46,18 @@ struct StreamMrtFormat { inline bool stream_mrt_format(DXGI_FORMAT format, StreamMrtFormat& out) { switch (format) { + case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_SINT: + out = {true, true, 1, DXGI_FORMAT_R8_TYPELESS}; return true; + case DXGI_FORMAT_R8G8_UINT: case DXGI_FORMAT_R8G8_SINT: + out = {true, true, 2, DXGI_FORMAT_R8G8_TYPELESS}; return true; + case DXGI_FORMAT_R16_UINT: case DXGI_FORMAT_R16_SINT: + out = {true, true, 2, DXGI_FORMAT_R16_TYPELESS}; return true; + case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SINT: + out = {true, true, 4, DXGI_FORMAT_R16G16_TYPELESS}; return true; + case DXGI_FORMAT_R16G16B16A16_UINT: case DXGI_FORMAT_R16G16B16A16_SINT: + out = {true, true, 8, DXGI_FORMAT_R16G16B16A16_TYPELESS}; return true; + case DXGI_FORMAT_R10G10B10A2_UINT: + out = {true, true, 4, DXGI_FORMAT_R10G10B10A2_TYPELESS}; return true; case DXGI_FORMAT_R8G8B8A8_UINT: case DXGI_FORMAT_R8G8B8A8_SINT: out = {true, true, 4, DXGI_FORMAT_R8G8B8A8_TYPELESS}; return true; case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_SINT: out = {true, true, 4, DXGI_FORMAT_R32_TYPELESS}; return true; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 0d58e1df5..6f1bf62bc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5014,10 +5014,10 @@ def read(fmt, data, offset): D16_FLOAT_EXACT_SRV_FORMATS = frozenset((2, 6, 16, 21, 28, 41, 49, 61, 65, 87, 88)) D16_UNORM16_SRV_FORMATS = frozenset((11, 35, 56)) D16_EXACT_SRV_FORMATS = D16_FLOAT_EXACT_SRV_FORMATS | D16_UNORM16_SRV_FORMATS -# Uncompressed exports keep their 32-bit shader values. RGBA8 integer RTVs clamp each -# channel to the destination range in the output merger. -VERIFIED_UINT_RTVS = frozenset((3, 17, 30, 42)) -VERIFIED_SINT_RTVS = frozenset((4, 18, 32, 43)) +# Uncompressed exports keep their 32-bit shader values. Narrow integer RTVs clamp +# each channel to the destination range in the output merger. +VERIFIED_UINT_RTVS = frozenset((3, 12, 17, 25, 30, 36, 42, 50, 57, 62)) +VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) class Pipeline: From a75bf57f2e4fe25f65778f72aa9411b29456f92b Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Thu, 26 Nov 2026 02:38:29 +0800 Subject: [PATCH 082/232] startup: wire PerReasonRefusalCensus into ExecuteIndirect other refusals (#2411) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 10 +- docs/startup-runtime.md | 22 +++- src/startup_stubs/d3d12_draw.inl | 21 ++++ src/startup_stubs/d3d12_xs_device.cpp | 148 ++++++++++++++++++------ tests/startup_indirect_draw_indexed.cpp | 113 +++++++++++++++++- 5 files changed, 272 insertions(+), 42 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 84714722f..a29d20fc5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1382,6 +1382,7 @@ foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} draw) add_test(NAME startup_indirect_translated_draw_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated) add_test(NAME startup_indirect_translated_refusal_census_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated-refusal-census) + add_test(NAME startup_indirect_other_refusal_census_${backend} COMMAND startup_indirect_draw_indexed ${backend} indirect-other-refusal-census) add_test(NAME startup_indirect_copy_provenance_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance) add_test(NAME startup_indirect_copy_provenance_off_${backend} COMMAND startup_indirect_draw_indexed ${backend} copy-provenance-off) add_test(NAME startup_indirect_translated_indexed_${backend} COMMAND startup_indirect_draw_indexed ${backend} translated-indexed) @@ -1404,7 +1405,8 @@ foreach(backend IN ITEMS warp hardware) set_tests_properties(startup_indirect_mesh_${backend} startup_indirect_mesh_console_${backend} startup_indirect_mesh_amplified_${backend} PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_translated_draw_${backend} - startup_indirect_translated_refusal_census_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + startup_indirect_translated_refusal_census_${backend} + startup_indirect_other_refusal_census_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_copy_provenance_${backend} startup_indirect_copy_provenance_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) set_tests_properties(startup_indirect_translated_indexed_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) @@ -1434,6 +1436,12 @@ add_test(NAME startup_indirect_translated_refusal_census_control_warp COMMAND startup_indirect_draw_indexed warp translated-refusal-census-control) set_tests_properties(startup_indirect_translated_refusal_census_control_warp PROPERTIES TIMEOUT 60 PASS_REGULAR_EXPRESSION "got +'x2w-d3d12 indirect-draw refusals: total 5. distinct keys 3, distinct pairs 3 \\(overflow calls 0\\)'") +# Negative control for the per-(key, reason) ExecuteIndirect other-refusal census: replacing the second refusal on +# key 1 with a valid draw must report the real total (3) and pair count (2) as a mismatch. +add_test(NAME startup_indirect_other_refusal_census_control_warp + COMMAND startup_indirect_draw_indexed warp indirect-other-refusal-census-control) +set_tests_properties(startup_indirect_other_refusal_census_control_warp PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "got +'x2w-d3d12 indirect-other refusals: total 3. distinct keys 2, distinct pairs 2 \\(overflow calls 0\\)'") # OMSetRenderTargets with a single descriptor range, handles that hold no view, and a cleared copied descriptor. add_executable(startup_rtv_bind tests/startup_rtv_bind.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index fb42f2a1f..18ccd39a0 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -455,6 +455,16 @@ with the last refusal: existing four memory-SRV lines). Refusals without a resolved translated pipeline (`shader_key == 0`) are not counted in this census (matching the per-call log gate), so `total` counts only refusals attributed to a resolved translated shader key rather than all `ExecuteIndirect` refusals. +- [`d3d12_xs_device.cpp`](../src/startup_stubs/d3d12_xs_device.cpp) also wires an `indirect-other` + census instance into `list_execute_indirect`: every `ExecuteIndirect` pre-check refusal counted under + `other` records `(key, reason_code)` (using the bound pipeline's known shader key when available, or + `0000000000000000` when no console pipeline key is resolved), distinguishes render-target and state + checks (`no_render_target`, `multiple_render_targets`, `depth_target_bound`, + `missing_viewport_or_scissor`, `target_format_mismatch`, `graphics_multi_command`, + `argument_outside_placed_buffer`, etc.), keeps logging the first occurrence of each of the first 8 + distinct `(key, reason)` pairs even after the 16-call global refusal log limit is spent, emits deltas + in the five-second report, and appends the full `x2w-d3d12 indirect-other refusals:` lines to + `x2w_d3d12_census_report` whenever at least one `other` refusal occurred. Check without a device via `ctest --preset dev --no-tests=error -R '^startup_per_reason_refusal_census(_keep-(last|first)_control)?$' -V`: @@ -464,12 +474,18 @@ reports; the `keep-last` and `keep-first` controls compile `PerReasonRefusalCens mismatch output, and are marked `WILL_FAIL`. Check the runtime wiring on WARP and hardware via -`ctest --preset dev --no-tests=error -R '^startup_indirect_translated_refusal_census_(warp|hardware|control_warp)$' -V`: -the pass runs interleave `missing_guest_root` and `sampled_texture_mismatch` on one translated pipeline +`ctest --preset dev --no-tests=error -R '^startup_indirect_(translated|other)_refusal_census_(warp|hardware|control_warp)$' -V`: +the `translated` pass runs interleave `missing_guest_root` and `sampled_texture_mismatch` on one translated pipeline key alongside `unsupported_resource_or_entry` and `incomplete_table_buffer` on two other keys plus a succeeding draw, then verify both `x2w_d3d12_census_report` (6 refusals, 3 keys, 4 pairs, 0 overflow) -and both per-call log lines for the shared key; the control replaces the second refusal on key 1 with a +and both per-call log lines for the shared key; its control replaces the second refusal on key 1 with a valid draw and must report the real counts (`total 5; distinct keys 3, distinct pairs 3`) as a mismatch. +The `other` pass runs warm up one translated pipeline key, interleave `missing_viewport_or_scissor` and +`argument_outside_placed_buffer` on that key alongside `graphics_multi_command` on key `0` (plus +non-`other` placeholder, graphics-pipeline and compute-pipeline refusals that must not be counted), and +verify `x2w_d3d12_census_report` (4 refusals, 2 keys, 3 pairs, 0 overflow, no `indirect-draw` lines) +and the three per-call log lines; its control replaces the second refusal on key 1 with a valid draw and +must report `total 3; distinct keys 2, distinct pairs 2` as a mismatch. ## Root constant buffer views diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 335498a90..70019fe00 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -713,6 +713,27 @@ void request_translation(Wrapper* pipeline) known ? "already known" : "new"); } +// Side-effect-free pipeline key lookup for ExecuteIndirect refusal attribution: never writes +// translation request files and returns 0 when the pipeline has no known console shader key. +u64 known_pipeline_key(Wrapper* pipeline) +{ + if (!pipeline) return 0; + if (pipeline->own().mesh86_key) return pipeline->own().mesh86_key; + if (pipeline->own().compute_trace_key) return pipeline->own().compute_trace_key; + if (pipeline->own().real) return 0; + AcquireSRWLockShared(&draw_lock); + const auto& by_pipeline = translation_by_pipeline(); + const auto known = by_pipeline.find(pipeline); + u64 key = known != by_pipeline.end() && known->second && known->second->translation + ? known->second->translation->key : 0; + ReleaseSRWLockShared(&draw_lock); + if (!key) { + const PipelineInfo* info = pipeline_info(pipeline); + if (info && info->path == 86 && info->stream_translation) key = info->stream_translation->key; + } + return key; +} + bool needs_rtv_variant(DXGI_FORMAT format) { switch (format) { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index f20d25d02..5df3194f4 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -97,12 +97,13 @@ namespace { using u64 = std::uint64_t; constexpr int slot_count = 512; -// Refused slot 70 calls, "token" texture nulls (memory_srv_census.h), and translated indirect draw -// refusals per (pipeline key, reason) (per_reason_refusal_census.h), printed with the five-second report. +// Refused slot 70 calls, "token" texture nulls (memory_srv_census.h), and indirect refusal censuses +// per (pipeline key, reason) (per_reason_refusal_census.h), printed with the five-second report. x2w_startup::MemorySrvCensus memory_srv_census; x2w_startup::TokenNullCensus token_null_census; x2w_startup::MemorySrvWrites memory_srv_writes; x2w_startup::PerReasonRefusalCensus indirect_draw_refusal_census{"indirect-draw"}; +x2w_startup::PerReasonRefusalCensus indirect_other_refusal_census{"indirect-other"}; enum Kind : int { device_kind, queue_kind, fence_kind, allocator_kind, list_kind, descriptor_heap_kind, root_signature_kind, @@ -2637,6 +2638,47 @@ struct IndirectIndexView { }; const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset, const IndirectIndexView& indices); +u64 known_pipeline_key(Wrapper* pipeline); + +namespace indirect_other_refusal_code { +constexpr const char* list_closed = "list_closed"; +constexpr const char* invalid_list_type = "invalid_list_type"; +constexpr const char* invalid_command_count = "invalid_command_count"; +constexpr const char* count_offset_without_buffer = "count_offset_without_buffer"; +constexpr const char* signature_device_mismatch = "signature_device_mismatch"; +constexpr const char* graphics_multi_command = "graphics_multi_command"; +constexpr const char* cached_mesh_attachments = "cached_mesh_attachments"; +constexpr const char* no_render_target = "no_render_target"; +constexpr const char* multiple_render_targets = "multiple_render_targets"; +constexpr const char* depth_target_bound = "depth_target_bound"; +constexpr const char* missing_viewport_or_scissor = "missing_viewport_or_scissor"; +constexpr const char* target_format_mismatch = "target_format_mismatch"; +constexpr const char* rect_list_indexed = "rect_list_indexed"; +constexpr const char* unsupported_topology = "unsupported_topology"; +constexpr const char* multisample_target = "multisample_target"; +constexpr const char* compute_root_mismatch = "compute_root_mismatch"; +constexpr const char* dispatch_root_multi_command = "dispatch_root_multi_command"; +constexpr const char* missing_argument_resource = "missing_argument_resource"; +constexpr const char* invalid_argument_offset = "invalid_argument_offset"; +constexpr const char* argument_address_overflow = "argument_address_overflow"; +constexpr const char* argument_outside_placed_buffer = "argument_outside_placed_buffer"; +constexpr const char* argument_not_common_state = "argument_not_common_state"; +constexpr const char* invalid_index_view = "invalid_index_view"; +constexpr const char* index_view_overlap = "index_view_overlap"; +constexpr const char* index_not_common_state = "index_not_common_state"; +constexpr const char* index_unaligned_address = "index_unaligned_address"; +constexpr const char* upload_index_unaligned = "upload_index_unaligned"; +constexpr const char* index_no_desktop_range = "index_no_desktop_range"; +constexpr const char* aliased_index_unaligned = "aliased_index_unaligned"; +constexpr const char* mesh_xmem_read = "mesh_xmem_read"; +constexpr const char* rect_live_compute_root = "rect_live_compute_root"; +constexpr const char* rect_conversion_unavailable = "rect_conversion_unavailable"; +constexpr const char* count_missing_resource = "count_missing_resource"; +constexpr const char* count_invalid_offset = "count_invalid_offset"; +constexpr const char* count_outside_placed_buffer = "count_outside_placed_buffer"; +constexpr const char* count_not_common_state = "count_not_common_state"; +constexpr const char* unknown = "unknown"; +} // namespace indirect_other_refusal_code // The guest method has independent resource and byte-offset arguments. void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, void* argument, u64 offset, @@ -2645,34 +2687,48 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, // Every refusal is counted under the signature's kind, including those before the signature is checked. Wrapper* sig = as_wrapper(signature); IndirectCommand kind = sig && sig->own().kind == command_signature_kind ? sig->own().indirect_command : IndirectCommand::none; - const auto refuse = [&kind](const char* reason, int outcome = indirect_other) { + Wrapper* refusal_pipeline = nullptr; + const auto refuse = [&kind, &refusal_pipeline](const char* reason, int outcome = indirect_other, + const char* code = nullptr) { InterlockedIncrement64(&indirect_calls[outcome][static_cast(kind)]); static LONG refusals; + if (outcome == indirect_other) { + const u64 key = known_pipeline_key(refusal_pipeline); + const char* reason_code = code ? code : indirect_other_refusal_code::unknown; + const bool first_pair = indirect_other_refusal_census.note(key, reason_code); + if (first_pair || first_calls(refusals, 16)) + log("x2w-render ExecuteIndirect refused, key %016llx [%s]: %s", key, reason_code, reason); + return; + } if (first_calls(refusals, 16)) log("x2w-render ExecuteIndirect refused: %s", reason); }; auto* list = recording(self); - if (!list) return refuse("list is closed"); + if (!list) return refuse("list is closed", indirect_other, indirect_other_refusal_code::list_closed); const auto type = list->GetType(); if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) - return refuse("requires a direct or compute command list"); + return refuse("requires a direct or compute command list", indirect_other, indirect_other_refusal_code::invalid_list_type); // Only a desktop Dispatch signature runs more than one command or reads a count buffer here. constexpr UINT max_dispatch_commands = 1u << 16; - if (!count || count > max_dispatch_commands) return refuse("command count is zero or above the supported maximum"); - if (!count_buffer && count_offset) return refuse("count offset without a count buffer"); + if (!count || count > max_dispatch_commands) + return refuse("command count is zero or above the supported maximum", indirect_other, indirect_other_refusal_code::invalid_command_count); + if (!count_buffer && count_offset) + return refuse("count offset without a count buffer", indirect_other, indirect_other_refusal_code::count_offset_without_buffer); if (!sig || sig->own().kind != command_signature_kind || !sig->own().real) return refuse("missing or placeholder signature", indirect_placeholder); const Wrapper* device = self->own().list_device; if (!device || sig->own().signature_device != device) - return refuse("requires a supported signature from this device"); + return refuse("requires a supported signature from this device", indirect_other, indirect_other_refusal_code::signature_device_mismatch); const auto command = sig->own().indirect_command; const bool indexed = command == IndirectCommand::draw_indexed; const bool mesh = command == IndirectCommand::dispatch_mesh; const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); + refusal_pipeline = pass.pipeline; const bool translated = (command == IndirectCommand::draw || indexed) && pass.pipeline && !pass.pipeline->own().real && (pass.graphics_root || pass.deferred_root) && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); u64 bytes = sig->own().indirect_bytes; - if (graphics && (count != 1 || count_buffer)) return refuse("indirect graphics requires one command and no count buffer"); + if (graphics && (count != 1 || count_buffer)) + return refuse("indirect graphics requires one command and no count buffer", indirect_other, indirect_other_refusal_code::graphics_multi_command); if (graphics) { if (indexed) bytes = sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); else if (mesh) bytes = sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); @@ -2705,7 +2761,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, pass.target_count != pso.cached_target_count || pass.dsv_format != pso.cached_depth || (pso.cached_depth_writes && !pass.depth_view_writable) || !std::equal(pso.cached_targets, pso.cached_targets + pso.cached_target_count, pass.target_formats)) - return refuse("cached mesh requires matching color and depth attachments, viewport and scissor"); + return refuse("cached mesh requires matching color and depth attachments, viewport and scissor", + indirect_other, indirect_other_refusal_code::cached_mesh_attachments); if (!pass.root || pass.root != pso.guest_root_params || pass.root_heap_flags) return refuse("cached mesh requires a recorded root without heap indexing", indirect_graphics_pipeline); for (std::size_t i = 0; i < pass.root->size(); ++i) { @@ -2716,40 +2773,50 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, } } else if (!pass.targets_bound || pass.target_count != 1 || !pass.target0 || (!translated && pass.target_formats[0] != pass.indirect_graphics.target_format) || - pass.dsv_format != DXGI_FORMAT_UNKNOWN || !pass.viewport_set || !pass.scissor_set) - return refuse("indirect graphics requires one matching target, viewport and scissor"); + pass.dsv_format != DXGI_FORMAT_UNKNOWN || !pass.viewport_set || !pass.scissor_set) { + const char* code = + pass.target_count > 1 ? indirect_other_refusal_code::multiple_render_targets + : (!pass.targets_bound || !pass.target_count || !pass.target0) ? indirect_other_refusal_code::no_render_target + : pass.dsv_format != DXGI_FORMAT_UNKNOWN ? indirect_other_refusal_code::depth_target_bound + : (!pass.viewport_set || !pass.scissor_set) ? indirect_other_refusal_code::missing_viewport_or_scissor + : indirect_other_refusal_code::target_format_mismatch; + return refuse("indirect graphics requires one matching target, viewport and scissor", indirect_other, code); + } const bool rect_list = !mesh && pass.topology == 0x11; if (rect_list && indexed && !translated) - return refuse("indirect rectangle list requires a non-indexed draw"); + return refuse("indirect rectangle list requires a non-indexed draw", indirect_other, indirect_other_refusal_code::rect_list_indexed); if (!mesh && !rect_list && pass.topology != D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST) - return refuse("indirect draw requires triangle-list or rectangle-list topology"); + return refuse("indirect draw requires triangle-list or rectangle-list topology", indirect_other, indirect_other_refusal_code::unsupported_topology); if (!pass.indirect_graphics.cached_mesh) { const auto samples = pass.target0->GetDesc().SampleDesc; if (samples.Count != 1 || samples.Quality) - return refuse("draw requires a single-sample render target"); + return refuse("draw requires a single-sample render target", indirect_other, indirect_other_refusal_code::multisample_target); } } else if (!pass.compute_pipeline || !pass.compute_root) { return refuse("requires a desktop compute pipeline and root", indirect_compute_pipeline); } else if (sig->own().signature_root && sig->own().signature_root != pass.compute_root) { - return refuse("signature root constants require the bound compute root"); + return refuse("signature root constants require the bound compute root", indirect_other, indirect_other_refusal_code::compute_root_mismatch); } else if (sig->own().signature_root && (count != 1 || count_buffer)) { // Batched and count-buffer Dispatch is supported for rootless signatures only in this slice. - return refuse("a Dispatch signature with root constants requires one command and no count buffer"); + return refuse("a Dispatch signature with root constants requires one command and no count buffer", + indirect_other, indirect_other_refusal_code::dispatch_root_multi_command); } Wrapper* buffer = as_wrapper(argument); if (!buffer || buffer->own().kind != resource_kind || !buffer->own().real) - return refuse("argument has no desktop resource"); + return refuse("argument has no desktop resource", indirect_other, indirect_other_refusal_code::missing_argument_resource); const auto base = reinterpret_cast(buffer->own().title_memory); if (!base || (offset & 3) || offset > ~u64{} - base) - return refuse("invalid argument offset or unmapped buffer"); + return refuse("invalid argument offset or unmapped buffer", indirect_other, indirect_other_refusal_code::invalid_argument_offset); // Every record up to the maximum must lie in the buffer: the count word can only lower the number executed. const u64 span = u64{count - 1} * sig->own().indirect_bytes + bytes; - if (span < bytes || base + offset > ~u64{} - span) return refuse("argument records overflow the address space"); + if (span < bytes || base + offset > ~u64{} - span) + return refuse("argument records overflow the address space", indirect_other, indirect_other_refusal_code::argument_address_overflow); const auto found = placed_buffer_range(device, base + offset, span); - if (found.reject || found.owner != buffer) return refuse("argument record is outside a unique placed buffer"); + if (found.reject || found.owner != buffer) + return refuse("argument record is outside a unique placed buffer", indirect_other, indirect_other_refusal_code::argument_outside_placed_buffer); const auto* info = resource_info(buffer); if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) - return refuse("argument buffer does not use COMMON state tracking"); + return refuse("argument buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::argument_not_common_state); auto* resource = static_cast(buffer->own().real); IndirectIndexView index_view; if (indexed) { @@ -2757,19 +2824,20 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const UINT alignment = view.Format == DXGI_FORMAT_R16_UINT ? 2 : view.Format == DXGI_FORMAT_R32_UINT ? 4 : 0; if (!alignment || !view.BufferLocation || !view.SizeInBytes || view.BufferLocation % alignment || view.SizeInBytes % alignment) - return refuse("invalid index view"); + return refuse("invalid index view", indirect_other, indirect_other_refusal_code::invalid_index_view); const auto indices = placed_buffer_range(device, view.BufferLocation, view.SizeInBytes); - if (indices.reject) return refuse("index view crosses or overlaps placed buffers"); + if (indices.reject) + return refuse("index view crosses or overlaps placed buffers", indirect_other, indirect_other_refusal_code::index_view_overlap); if (indices.owner && indices.owner->own().real) { const auto* index_info = resource_info(indices.owner); if (!index_info || index_info->initial_state != D3D12_RESOURCE_STATE_COMMON) - return refuse("index buffer does not use COMMON state tracking"); + return refuse("index buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::index_not_common_state); auto* index = static_cast(indices.owner->own().real); const auto index_base = reinterpret_cast(indices.owner->own().title_memory); const auto index_offset = view.BufferLocation - index_base; const auto native_base = index->GetGPUVirtualAddress(); if (!native_base || index_offset > ~u64{} - native_base || (native_base + index_offset) % alignment) - return refuse("index view has no aligned desktop address"); + return refuse("index view has no aligned desktop address", indirect_other, indirect_other_refusal_code::index_unaligned_address); view.BufferLocation = native_base + index_offset; index_view = {view, index, index_offset}; } else { @@ -2779,16 +2847,19 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, // load an adjacent recording upload allocation when extracting a half-word. if (upload.resource) { if ((upload.offset | view.SizeInBytes) & 3) - return refuse("upload index view is not dword-aligned and dword-sized"); + return refuse("upload index view is not dword-aligned and dword-sized", + indirect_other, indirect_other_refusal_code::upload_index_unaligned); view.BufferLocation = upload.gpu; index_view = {view, upload.resource, upload.offset, true}; } else { const auto alias = translated && !indices.owner && !list_upload_range(self, view.BufferLocation, 1).resource ? indirect_address_alias(self->own().list_device, view.BufferLocation, view.SizeInBytes) : IndirectAddressAlias{}; - if (!alias.resource) return refuse("index view has no proven desktop buffer range"); + if (!alias.resource) + return refuse("index view has no proven desktop buffer range", indirect_other, indirect_other_refusal_code::index_no_desktop_range); const auto gpu = alias.resource->GetGPUVirtualAddress(); if (!gpu || ((alias.offset | view.SizeInBytes) & 3)) - return refuse("aliased index view is not dword-aligned and dword-sized"); + return refuse("aliased index view is not dword-aligned and dword-sized", + indirect_other, indirect_other_refusal_code::aliased_index_unaligned); view.BufferLocation = gpu + alias.offset; index_view = {view, alias.resource, alias.offset}; } @@ -2822,7 +2893,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, inputs[input_count++] = {base + offset, bytes, argument_state}; if (input_count) { if (const char* failure = record_mesh_xmem_reads(self, inputs, input_count)) - return refuse(failure, mesh_srv != UINT_MAX ? indirect_graphics_pipeline : indirect_other); + return refuse(failure, mesh_srv != UINT_MAX ? indirect_graphics_pipeline : indirect_other, + indirect_other_refusal_code::mesh_xmem_read); if (leased_arguments) { draw_arguments = inputs[input_count - 1].resource; draw_offset = inputs[input_count - 1].offset; @@ -2831,7 +2903,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (rect_list) { if (std::any_of(pass.desktop_compute_upload_srvs.begin(), pass.desktop_compute_upload_srvs.end(), [](u64 address) { return address != 0; })) - return refuse("rectangle-list conversion would drop live compute root arguments"); + return refuse("rectangle-list conversion would drop live compute root arguments", + indirect_other, indirect_other_refusal_code::rect_live_compute_root); // The producer's count names three vertices per rectangle; the desktop draw needs six. Convert on the GPU // into a scratch record and draw from that. The compute root signature and bindings of the list are replaced. // The four words are copied into the scratch first (the pass never reads the title's buffer), so the source only @@ -2839,7 +2912,8 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, require_state(self, resource, argument_state | D3D12_RESOURCE_STATE_COPY_SOURCE); scratch = recording_rect_scratch(self); if (!scratch || !x2w_startup::rect_indirect_arguments().convert(list, resource, offset, scratch)) - return refuse("rectangle-list argument conversion is unavailable"); + return refuse("rectangle-list argument conversion is unavailable", + indirect_other, indirect_other_refusal_code::rect_conversion_unavailable); if (pass.desktop_compute_root) list->SetComputeRootSignature(pass.desktop_compute_root.Get()); list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); draw_arguments = scratch; @@ -2863,16 +2937,16 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, // The count word is four bytes in a unique placed buffer that also tracks state from COMMON. Wrapper* count_wrapper = as_wrapper(count_buffer); if (!count_wrapper || count_wrapper->own().kind != resource_kind || !count_wrapper->own().real) - return refuse("count buffer has no desktop resource"); + return refuse("count buffer has no desktop resource", indirect_other, indirect_other_refusal_code::count_missing_resource); const auto count_base = reinterpret_cast(count_wrapper->own().title_memory); if (!count_base || (count_offset & 3) || count_offset > ~u64{} - count_base - sizeof(UINT)) - return refuse("invalid count offset or unmapped count buffer"); + return refuse("invalid count offset or unmapped count buffer", indirect_other, indirect_other_refusal_code::count_invalid_offset); const auto count_found = placed_buffer_range(device, count_base + count_offset, sizeof(UINT)); if (count_found.reject || count_found.owner != count_wrapper) - return refuse("count word is outside a unique placed buffer"); + return refuse("count word is outside a unique placed buffer", indirect_other, indirect_other_refusal_code::count_outside_placed_buffer); const auto* count_info = resource_info(count_wrapper); if (!count_info || count_info->initial_state != D3D12_RESOURCE_STATE_COMMON) - return refuse("count buffer does not use COMMON state tracking"); + return refuse("count buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::count_not_common_state); counts = static_cast(count_wrapper->own().real); if (counts != resource) require_state(self, counts, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); } @@ -5154,6 +5228,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa token_null_census.report([](const char* line) { log("%s", line); }, true); memory_srv_writes.report([](const char* line) { log("%s", line); }, true); indirect_draw_refusal_census.report([](const char* line) { log("%s", line); }, true); + indirect_other_refusal_census.report([](const char* line) { log("%s", line); }, true); log("x2w-d3d12 heartbeat: %ld frames presented in %.1f s (%.1f fps overall); frame waits by type %ld/%ld/%ld/%ld, " "%lld ms slept", frame, (now - started) / 1000.0, frame * 1000.0 / (now - started ? now - started : 1), frame_waits[0], frame_waits[1], frame_waits[2], frame_waits[3], static_cast(frame_wait_ms)); @@ -5176,6 +5251,7 @@ extern "C" __declspec(dllexport) std::size_t x2w_d3d12_census_report(char* out, token_null_census.report(emit, false); memory_srv_writes.report(emit, false); if (indirect_draw_refusal_census.total()) indirect_draw_refusal_census.report(emit, false); + if (indirect_other_refusal_census.total()) indirect_other_refusal_census.report(emit, false); if (out && capacity) out[length < capacity ? length : capacity - 1] = 0; return length; } diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 185bb9423..1f0834431 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1318,6 +1318,98 @@ bool check_translated_refusal_census(const std::wstring& log_path) for (const auto& line : entries) std::printf("%s\n", line.c_str()); return true; } + +bool check_indirect_other_refusal_census(const std::wstring& log_path) +{ + const std::size_t needed = x2w_d3d12_census_report(nullptr, 0); + std::string report(needed + 1, '\0'); + x2w_d3d12_census_report(report.data(), report.size()); + report.resize(std::strlen(report.c_str())); + std::string summary; + std::vector entries; + bool saw_indirect_draw = false; + std::size_t pos = 0; + while (pos < report.size()) { + std::size_t end = report.find('\n', pos); + if (end == std::string::npos) end = report.size(); + std::string line = report.substr(pos, end - pos); + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.rfind("x2w-d3d12 indirect-other refusals:", 0) == 0) summary = line; + else if (line.rfind("x2w-d3d12 indirect-other refusal ", 0) == 0) entries.push_back(line); + else if (line.rfind("x2w-d3d12 indirect-draw refusal", 0) == 0) saw_indirect_draw = true; + pos = end + 1; + } + if (saw_indirect_draw) { + std::fprintf(stderr, "indirect-other refusal census saw unexpected indirect-draw refusal lines\n"); + return false; + } + const std::string expected = + "x2w-d3d12 indirect-other refusals: total 4; distinct keys 2, distinct pairs 3 (overflow calls 0)"; + if (summary != expected) { + std::fprintf(stderr, "indirect-other refusal census mismatch:\n got '%s'\n expected '%s'\n", + summary.c_str(), expected.c_str()); + return false; + } + if (entries.size() != 3) { + std::fprintf(stderr, "indirect-other refusal census expected 3 detail lines, got %zu\n", entries.size()); + return false; + } + struct ParsedEntry { + unsigned index = 0; + std::string key; + std::string reason; + unsigned long long calls = 0; + }; + std::vector parsed; + for (const auto& line : entries) { + unsigned index = 0; + char key[32]{}; + char reason[64]{}; + unsigned long long calls = 0; + if (std::sscanf(line.c_str(), "x2w-d3d12 indirect-other refusal %u: key=%16[0-9a-f] reason=%63s calls=%llu", + &index, key, reason, &calls) != 4 || std::strlen(key) != 16) { + std::fprintf(stderr, "malformed indirect-other refusal detail line: '%s'\n", line.c_str()); + return false; + } + parsed.push_back({index, key, reason, calls}); + } + const std::string zero_key = "0000000000000000"; + const bool entries_ok = + parsed[0].index == 1 && parsed[0].key != zero_key && + parsed[0].reason == "missing_viewport_or_scissor" && parsed[0].calls == 2 && + parsed[1].index == 2 && parsed[1].key == parsed[0].key && + parsed[1].reason == "argument_outside_placed_buffer" && parsed[1].calls == 1 && + parsed[2].index == 3 && parsed[2].key == zero_key && + parsed[2].reason == "graphics_multi_command" && parsed[2].calls == 1; + if (!entries_ok) { + std::fprintf(stderr, "indirect-other refusal census entries did not match expected per-(key, reason) rows:\n"); + for (const auto& line : entries) std::fprintf(stderr, " %s\n", line.c_str()); + return false; + } + std::ifstream file(log_path, std::ios::binary); + std::string log_line; + bool saw_vp_log = false, saw_arg_log = false, saw_multi_log = false; + const std::string want_vp = "x2w-render ExecuteIndirect refused, key " + parsed[0].key + + " [missing_viewport_or_scissor]: indirect graphics requires one matching target, viewport and scissor"; + const std::string want_arg = "x2w-render ExecuteIndirect refused, key " + parsed[0].key + + " [argument_outside_placed_buffer]: argument record is outside a unique placed buffer"; + const std::string want_multi = "x2w-render ExecuteIndirect refused, key " + zero_key + + " [graphics_multi_command]: indirect graphics requires one command and no count buffer"; + while (std::getline(file, log_line)) { + if (!log_line.empty() && log_line.back() == '\r') log_line.pop_back(); + if (log_line == want_vp) saw_vp_log = true; + if (log_line == want_arg) saw_arg_log = true; + if (log_line == want_multi) saw_multi_log = true; + } + if (!saw_vp_log || !saw_arg_log || !saw_multi_log) { + std::fprintf(stderr, "indirect-other refusal log lines missing (vp=%d, arg=%d, multi=%d)\n", + saw_vp_log ? 1 : 0, saw_arg_log ? 1 : 0, saw_multi_log ? 1 : 0); + return false; + } + std::printf("%s\n", summary.c_str()); + for (const auto& line : entries) std::printf("%s\n", line.c_str()); + return true; +} bool fixed_mesh_create_contract(ID3D12Device* guest) { const D3D12_ROOT_SIGNATURE_DESC root_desc{}; @@ -1412,12 +1504,14 @@ int main(int argc, char** argv) try const bool copy_off = argc == 3 && std::strcmp(argv[2], "copy-provenance-off") == 0; const bool refusal_census_control = argc == 3 && std::strcmp(argv[2], "translated-refusal-census-control") == 0; const bool refusal_census = refusal_census_control || (argc == 3 && std::strcmp(argv[2], "translated-refusal-census") == 0); + const bool other_refusal_census_control = argc == 3 && std::strcmp(argv[2], "indirect-other-refusal-census-control") == 0; + const bool other_refusal_census = other_refusal_census_control || (argc == 3 && std::strcmp(argv[2], "indirect-other-refusal-census") == 0); const bool upload_index = argc == 3 && std::strcmp(argv[2], "translated-indexed-upload") == 0; const bool rect = argc == 3 && std::strcmp(argv[2], "translated-indexed-rect") == 0; const bool alias_disabled = argc == 3 && std::strcmp(argv[2], "translated-indexed-alias-off") == 0; const bool alias_index = alias_disabled || (argc == 3 && std::strcmp(argv[2], "translated-indexed-alias") == 0); const bool translated_indexed = alias_index || upload_index || rect || (argc == 3 && std::strcmp(argv[2], "translated-indexed") == 0); - const bool translated = copy_on || copy_off || refusal_census || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); + const bool translated = copy_on || copy_off || refusal_census || other_refusal_census || translated_indexed || (argc == 3 && std::strcmp(argv[2], "translated") == 0); // "count-control" is the negative control: it expects one forwarded call too many. const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; @@ -1460,7 +1554,7 @@ int main(int argc, char** argv) try wchar_t directory[MAX_PATH]; if (!GetTempPathW(MAX_PATH, directory)) return 4; const std::wstring log_path = std::wstring(directory) + L"x2w_indirect_counts_" + std::to_wstring(GetCurrentProcessId()) + L".log"; - if (indexed || lease_arguments || dual_lease || refusal_census) { + if (indexed || lease_arguments || dual_lease || refusal_census || other_refusal_census) { DeleteFileW(log_path.c_str()); SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); SetEnvironmentVariableA("X2W_PRESENT_SIGNATURE_EVERY", "0"); @@ -1803,6 +1897,21 @@ int main(int argc, char** argv) try DeleteFileW(log_path.c_str()); return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; } + if (other_refusal_census) { + bool ok = verify(producer.Get(), false, Refusal::none, "other census warm up translated pipeline key") && + verify(producer.Get(), false, Refusal::missing_viewport, "other census key1 missing_viewport_or_scissor #1") && + verify(producer.Get(), false, other_refusal_census_control ? Refusal::none : Refusal::short_argument, + other_refusal_census_control ? "other census control valid draw replaces second reason" + : "other census key1 argument_outside_placed_buffer") && + verify(producer.Get(), false, Refusal::missing_viewport, "other census key1 missing_viewport_or_scissor #2"); + if (ok) { + refuse_each_reason(guest.Get(), signature.Get()); + ok = check_indirect_other_refusal_census(log_path); + } + std::filesystem::remove_all(cache); + DeleteFileW(log_path.c_str()); + return ok && (!info || !info->GetNumStoredMessages()) ? 0 : 1; + } bool ok = verify(producer.Get(), false, Refusal::none, "translated red texture") && verify(producer.Get(), true, Refusal::none, "translated green texture") && verify(nullptr, false, Refusal::none, "translated omitted GPU writer") && From 6ac16247742a5b43ed819b09ea8fd1c021e12388 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 20:38:59 +0200 Subject: [PATCH 083/232] cpu: lower FSIN, FCOS, FSINCOS, FPTAN, and FPATAN instructions in x87_lower (#1663) * cpu: lower FSIN, FCOS, FSINCOS, FPTAN, and FPATAN instructions in x87_lower * cpu: clarify x87 fsincos/fptan out-of-range profile and add C2 reset/lifted checks * cpu: trap on out-of-range FSINCOS/FPTAN in x87_lower --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 19 + docs/experiments.md | 4 +- tests/cpu/x87_add.py | 2 +- tests/cpu/x87_compare.py | 2 +- tests/cpu/x87_iarith.py | 2 +- tests/cpu/x87_moves.py | 2 +- tests/cpu/x87_sqrt.py | 4 +- tests/cpu/x87_status.py | 4 +- tests/cpu/x87_sub.py | 2 +- tests/cpu/x87_trig.asm | 251 +++++++++++++ tests/cpu/x87_trig.def | 19 + tests/cpu/x87_trig.py | 764 +++++++++++++++++++++++++++++++++++++++ tools/x87_lower.py | 35 +- tools/x87_soft.h | 432 ++++++++++++++++++++++ 14 files changed, 1528 insertions(+), 14 deletions(-) create mode 100644 tests/cpu/x87_trig.asm create mode 100644 tests/cpu/x87_trig.def create mode 100644 tests/cpu/x87_trig.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a29d20fc5..72de7287e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6998,6 +6998,25 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_x87_bcd COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_bcd.py" check "$" "$" "$" ${x87_bcd_control_files}) + cpu_asm_fixture(cpu_x87_trig x87_trig) + # The lifted DLL and eight mutated controls that the check requires to mismatch. + set(x87_trig_control_files "") + foreach(variant IN ITEMS lifted noc2 c262 sincosswap ptanno1 patanswap sinnegzero snan pc53) + set(x87_trig_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_x87_trig_${variant}.cpp") + add_custom_command(OUTPUT "${x87_trig_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_trig.py" + emit "$" "${x87_trig_fixture}" ${variant} + DEPENDS cpu_x87_trig tests/cpu/x87_trig.py tests/cpu/x87_moves.py tests/cpu/x87_div.py + tests/cpu/x87_mul.py tests/cpu/x87_add.py tools/ffx_version_query.py tools/x87_lower.py + tools/x87_soft.h tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_x87_trig_${variant} SHARED "${x87_trig_fixture}") + if(NOT variant STREQUAL "lifted") + list(APPEND x87_trig_control_files "$") + endif() + endforeach() + add_test(NAME cpu_aot_x87_trig COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_trig.py" + check "$" "$" + "$" ${x87_trig_control_files}) cpu_asm_fixture(cpu_create create_context) set(create_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_create_lifted.cpp") add_custom_command(OUTPUT "${create_fixture}" diff --git a/docs/experiments.md b/docs/experiments.md index c839cadda..b31ebc06b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -1984,7 +1984,7 @@ CPU vendors, `XSAVE`-family state management, control flow, and title CPU code e ## x87 in the shared lowering -`lower(..., x87=True)` in `tools/ffx_version_query.py` accepts an opt-in x87 leaf-function profile. The default (`x87=False`) still rejects every x87 instruction, so existing callers are unchanged. The profile accepts `fld` and `fstp` with an m32, m64 or m80 memory operand, `fst` with an m32 or m64 operand, `fld st(i)`, `fst st(i)`, `fstp st(i)`, `fxch st(i)`, `fchs`, `fabs`, `fsqrt`, `frndint`, `fxtract` and `fscale`, the constant loads `fld1`, `fldz`, `fldpi`, `fldl2t`, `fldl2e`, `fldlg2` and `fldln2`, `fild`, `fistp` and `fisttp` with an m16, m32 or m64 integer operand, `fist` with m16 or m32, `fbstp` with an m80 packed BCD operand, `fcomi`, `fcomip`, `fucomi` and `fucomip` with `st, st(i)`, `fcmovb`, `fcmove`, `fcmovbe`, `fcmovnb`, `fcmovne`, `fcmovnbe`, `fcmovu` and `fcmovnu` with `st, st(i)`, `fcom` and `fcomp` with `st(i)` or an m32 or m64 operand, `fcompp`, `fucom` and `fucomp` with `st(i)`, `fucompp`, `fnstsw ax`, and five forms of each of `fadd`, `fsub`, `fsubr`, `fmul`, `fdiv` and `fdivr`: an m32 or m64 operand, `st, st(i)`, `st(i), st`, and the popping form (`faddp`, `fsubp`, `fsubrp`, `fmulp`, `fdivp`, `fdivrp`) with `st(i), st` for `i` from 1 to 7. It also accepts `fiadd`, `fisub`, `fisubr`, `fimul`, `fidiv` and `fidivr` with an m16 or m32 integer operand, `fnstcw` and `fstcw` with an m16 operand, which store the fixed control word `0x027F`, and `wait`, which does nothing because every exception is masked. A popping form with `st(0)` as the destination is rejected. A function enters with control word 0x027F (53-bit precision, round to nearest-even, all exceptions masked), TOP 0, all eight registers empty and a clear status word, and it must return with the stack empty. The stack depth before each instruction is fixed at translation time (`tools/x87_lower.py`), so each register becomes a C++ slot and no TOP exists at run time. Translation rejects any other x87 instruction, including `fldcw`, `fninit` and `fbld` (which only the checked entry below accepts), `ffree`, `fnstsw` with a memory operand, and environment access; a ninth push; a pop, an `st(i)` operand or `faddp` without enough values; depths that differ where control flow joins; an x87 instruction that is not reachable from the entry through direct edges; and a nonempty stack at a return, a call, an indirect branch or an external edge. +`lower(..., x87=True)` in `tools/ffx_version_query.py` accepts an opt-in x87 leaf-function profile. The default (`x87=False`) still rejects every x87 instruction, so existing callers are unchanged. The profile accepts `fld` and `fstp` with an m32, m64 or m80 memory operand, `fst` with an m32 or m64 operand, `fld st(i)`, `fst st(i)`, `fstp st(i)`, `fxch st(i)`, `fchs`, `fabs`, `fsqrt`, `frndint`, `fsin`, `fcos`, `fsincos`, `fptan`, `fpatan`, `fxtract` and `fscale`, the constant loads `fld1`, `fldz`, `fldpi`, `fldl2t`, `fldl2e`, `fldlg2` and `fldln2`, `fild`, `fistp` and `fisttp` with an m16, m32 or m64 integer operand, `fist` with m16 or m32, `fbstp` with an m80 packed BCD operand, `fcomi`, `fcomip`, `fucomi` and `fucomip` with `st, st(i)`, `fcmovb`, `fcmove`, `fcmovbe`, `fcmovnb`, `fcmovne`, `fcmovnbe`, `fcmovu` and `fcmovnu` with `st, st(i)`, `fcom` and `fcomp` with `st(i)` or an m32 or m64 operand, `fcompp`, `fucom` and `fucomp` with `st(i)`, `fucompp`, `fnstsw ax`, and five forms of each of `fadd`, `fsub`, `fsubr`, `fmul`, `fdiv` and `fdivr`: an m32 or m64 operand, `st, st(i)`, `st(i), st`, and the popping form (`faddp`, `fsubp`, `fsubrp`, `fmulp`, `fdivp`, `fdivrp`) with `st(i), st` for `i` from 1 to 7. It also accepts `fiadd`, `fisub`, `fisubr`, `fimul`, `fidiv` and `fidivr` with an m16 or m32 integer operand, `fnstcw` and `fstcw` with an m16 operand, which store the fixed control word `0x027F`, and `wait`, which does nothing because every exception is masked. A popping form with `st(0)` as the destination is rejected. A function enters with control word 0x027F (53-bit precision, round to nearest-even, all exceptions masked), TOP 0, all eight registers empty and a clear status word, and it must return with the stack empty. The stack depth before each instruction is fixed at translation time (`tools/x87_lower.py`), so each register becomes a C++ slot and no TOP exists at run time. Translation rejects any other x87 instruction, including `fldcw`, `fninit` and `fbld` (which only the checked entry below accepts), `ffree`, `fnstsw` with a memory operand, and environment access; a ninth push; a pop, an `st(i)` operand or `faddp` without enough values; depths that differ where control flow joins; an x87 instruction that is not reachable from the entry through direct edges; and a nonempty stack at a return, a call, an indirect branch or an external edge. The helpers in `tools/x87_soft.h` compute in integers and do not use host floating point. A register holds the full 80-bit encoding. m80 loads and stores copy all 80 bits, including NaN payloads, denormals, pseudo-denormals and unnormals. m32 and m64 loads convert exactly and quiet a signaling NaN. Under the fixed control word a sum rounds to 53 significand bits within the extended exponent range; a result below that range is denormalized first and then rounded at the same bit positions. The sum rounds again when it is stored to m32 or m64. NaN operands follow the x87 column of Intel SDM Vol. 1, Table 4-7: a QNaN beats an SNaN, and otherwise the larger significand wins. When two NaNs have equal significands, the positive one wins in either operand order. This tie rule was measured, not taken from the table. Infinities of opposite sign, unnormals, pseudo-infinities and pseudo-NaNs give the indefinite. An exact zero sum of nonzero addends is +0 (-0 when rounding toward negative infinity), and -0 + -0 is -0. Every rounding helper takes the control word and follows its precision and rounding control. The fixed profile passes `0x027F`, so only the checked entry below reaches the other words. Exceptions are not modelled, and of the status word only C0, C2, C3 and TOP are (see `cpu_aot_x87_status`). This is safe only because translation rejects every reader of the other status-word bits, and the checked entry stops at a word that unmasks an exception. @@ -2153,6 +2153,8 @@ On the AMD Ryzen 7 7700 every translated case matched the model. Every native ca Two observations on this processor are not modelled. A partial step clears C0, C1 and C3 and leaves an exponent difference of 32 + (D mod 32), where D is the difference before the step. After a NaN result, C0 and C3 keep their previous values and C1 and C2 are cleared. Translation rejects `fprem` and `fprem1` in the fixed profile, `fprem` with one value, `fprem1` on an empty stack, `test ah, 80h` (the busy bit) after `fprem`, `fadd` between `fprem` and `fnstsw`, a push inside the fmod loop, and a return with the status word in AX. It translates `test ah, 02h` after `fprem1`, `sahf; je` after `fprem`, the fmod loop, and `fprem` without `fnstsw`. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_fprem$' -V`. +`cpu_aot_x87_trig` checks `fsin`, `fcos`, `fsincos`, `fptan` and `fpatan` in the same way, with 18 exports and 99184 cases. Each computes in 64-bit extended precision without host floating point (`tools/x87_soft.h`), ignoring the precision control and following the rounding control (for `|x| < 2^-64`, `x87_soft.h` returns `x` unrounded, which can differ by 1 ULP under directed rounding in the checked entry). `fsin`, `fcos`, `fsincos` and `fptan` use 256-bit Payne-Hanek range reduction modulo `pi/2` and 128-bit Taylor series when `|ST(0)| < 2^63`, setting `C2` to 0 and leaving `C0`, `C1` and `C3` undefined. For finite `|ST(0)| >= 2^63`, `fsin` and `fcos` set `C2` to 1 and leave `ST(0)` unchanged; for `fsincos` and `fptan`, finite `|ST(0)| >= 2^63` is outside the fixed static-depth profile because hardware sets `C2` to 1 without pushing; rather than continuing with a divergent stack, the lowered `fsincos` and `fptan` paths trap via `x87_trap()` (`__ud2()` on MSVC, raising `STATUS_ILLEGAL_INSTRUCTION`), verified on the translated DLL for `sincos_m80`, `ptan_m80`, and `ptan_c2_reset` while the native differential filters `fsincos` and `fptan` inputs to `|x| < 2^63`; `ptan_c2_reset` also checks that `fptan` clears a prior `C2 = 1` from `ftst` on in-range inputs). `fsincos` replaces `ST(0)` by `sin` and pushes `cos`; `fptan` replaces `ST(0)` by `tan` and pushes `1.0` (or the quieted NaN / indefinite on NaN, infinity or unsupported encodings). `fpatan` computes `atan2(ST(1), ST(0))` into `ST(1)` and pops `ST(0)`, leaving `C0` to `C3` undefined. The independent model uses 150-digit `Decimal` arithmetic. Special encodings, zeros, infinities, NaNs, unsupported values, out-of-range `C2` flags (for `fsin`/`fcos`) and `fptan`'s pushed `1.0` match bit-for-bit in native and translated runs. For the listed fixture cases, finite `m80` results with `|x| <= 8` (and magnitudes `>= 2^-50`, and `<= 2^50` for `fptan`) match within 4 ULPs natively on the tested hosts (within 2 ULPs for `fpatan`, and within 1 ULP in the translated DLL); `native_matches` checks `|x| > 8` and tiny/near-pole outputs only for finiteness because hardware's 66-bit `pi` diverges near multiples of `pi/2`, and borderline cases are hardware-dependent. Eight mutated translations must each mismatch: `C2` never set (318), out-of-range threshold at `2^62` (24), `fsincos` outputs swapped (627), `fptan` pushing `0.0` (1150), `fpatan` operands swapped (84768), `sin(-0)` returning `+0` (8), unquieted signaling NaNs (132), and 53-bit rounding (27168). Translation rejects underflows, `fsincos`/`fptan` at depth 8, unpopped stack values, readers of unknown `C0`/`C1`/`C3` after trig ops or `C2` after `fpatan`, `fnstsw m16` after `fsin`, and `f2xm1`. Rejection cases in earlier `x87` tests that used `fsin`, `fcos`, `fsincos`, `fptan` or `fpatan` as unsupported examples now use `f2xm1` or `fyl2x`. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_x87_trig$' -V`. + ### Ryzen 7 7800X3D measurements The four x87 fixtures reported in [#592](https://github.com/R0Y00/Xbox2Windows/pull/592) also passed on an AMD Ryzen 7 7800X3D with Windows 11 Pro x64 build `26200.9974` and MSVC `19.44.35228.0`. The `dev` build used commit `af942385c9561a9ee4d5d202d79bae9a084fb87f`. diff --git a/tests/cpu/x87_add.py b/tests/cpu/x87_add.py index a4d2fa5c3..134dfcbf0 100644 --- a/tests/cpu/x87_add.py +++ b/tests/cpu/x87_add.py @@ -497,7 +497,7 @@ def attempt(hex_bytes, *, x87=True, calls=None, exits=None): rejected = { "the profile off (default)": (attempt(f"{fld} {fstp} c3", x87=False), "unsupported query operation"), "fbld m80": (attempt(f"{fld} df 21 de c1 {fstp} c3"), "unsupported x87 operation"), - "fsin": (attempt(f"{fld} d9 fe {fstp} c3"), "unsupported x87 operation"), + "f2xm1": (attempt(f"{fld} d9 f0 {fstp} c3"), "unsupported x87 operation"), "fnstsw m16": (attempt(f"{fld} dd 3a {fstp} c3"), "stores status-word bits"), "fldcw": (attempt(f"d9 29 {fld} {fstp} c3"), "fldcw"), "fninit": (attempt(f"{fld} db e3 {fstp} c3"), "unsupported x87 operation"), diff --git a/tests/cpu/x87_compare.py b/tests/cpu/x87_compare.py index 5b243e1b8..05db6588b 100644 --- a/tests/cpu/x87_compare.py +++ b/tests/cpu/x87_compare.py @@ -351,7 +351,7 @@ def after_fucomi(consumer): "fcom st(1) as DC D1": (attempt(f"{fld} {fld} dc d1 {pop2}"), "unsupported x87 encoding"), "fucompp with one value": (attempt(f"{fld} da e9 c3"), "x87 stack underflow"), "f2xm1": (attempt(f"{fld} d9 f0 dd d8 c3"), "unsupported x87 operation"), - "fptan": (attempt(f"{fld} d9 f2 dd d8 c3"), "unsupported x87 operation"), + "fyl2x": (attempt(f"{fld} d9 f1 dd d8 c3"), "unsupported x87 operation"), "frstor m108": (attempt(f"{fld} dd 21 dd d8 c3"), "unsupported x87 operation"), "fnstsw m16": (attempt(f"{fld} dd 3a dd d8 c3"), "stores status-word bits"), } diff --git a/tests/cpu/x87_iarith.py b/tests/cpu/x87_iarith.py index 84178121b..065f8a471 100644 --- a/tests/cpu/x87_iarith.py +++ b/tests/cpu/x87_iarith.py @@ -271,7 +271,7 @@ def attempt(hex_bytes): fld, fstp = "db 29", "db 3a" # fld tbyte ptr [rcx]; fstp tbyte ptr [rdx] rejected = { "fbld m80": (attempt(f"{fld} df 21 {fstp} c3"), "unsupported x87 operation"), - "fsincos": (attempt(f"{fld} d9 fb {fstp} c3"), "unsupported x87 operation"), + "fyl2x": (attempt(f"{fld} d9 f1 {fstp} c3"), "unsupported x87 operation"), "fiadd m32 on an empty stack": (attempt(f"da 01 {fld} {fstp} c3"), "x87 stack underflow"), "fidivr m16 on an empty stack": (attempt(f"de 39 {fld} {fstp} c3"), "x87 stack underflow"), "fisub m32 with two values and one store": (attempt(f"{fld} {fld} da 21 {fstp} c3"), diff --git a/tests/cpu/x87_moves.py b/tests/cpu/x87_moves.py index f57bbbfb6..a83ae1074 100644 --- a/tests/cpu/x87_moves.py +++ b/tests/cpu/x87_moves.py @@ -309,7 +309,7 @@ def attempt(hex_bytes): "fxch st(1) as DD C9": (attempt(f"{fld} {fld} dd c9 {fstp} {fstp} c3"), "unsupported x87 encoding"), "fxch st(1) as DF C9": (attempt(f"{fld} {fld} df c9 {fstp} {fstp} c3"), "unsupported x87 encoding"), "fnstenv m28": (attempt(f"{fld} d9 32 {fstp} c3"), "stores the tag word of a non-empty x87 stack"), - "fsin": (attempt(f"{fld} d9 fe {fstp} c3"), "unsupported x87 operation"), + "f2xm1": (attempt(f"{fld} d9 f0 {fstp} c3"), "unsupported x87 operation"), "ffree st(0)": (attempt(f"{fld} dd c0 {fstp} c3"), "frees an occupied register"), "fdecstp": (attempt(f"{fld} d9 f6 {fstp} c3"), "unsupported x87 operation"), } diff --git a/tests/cpu/x87_sqrt.py b/tests/cpu/x87_sqrt.py index c017f0df2..9a62900df 100644 --- a/tests/cpu/x87_sqrt.py +++ b/tests/cpu/x87_sqrt.py @@ -273,8 +273,8 @@ def attempt(hex_bytes): rejected = { "fsqrt on an empty stack": (attempt("d9 fa c3"), "x87 stack underflow"), "fsqrt without a store": (attempt(f"{fld} d9 fa c3"), "x87 stack not empty at return"), - "fsin": (attempt(f"{fld} d9 fe {fstp} c3"), "unsupported x87 operation"), - "fsincos": (attempt(f"{fld} d9 fb {fstp} {fstp} c3"), "unsupported x87 operation"), + "f2xm1": (attempt(f"{fld} d9 f0 {fstp} c3"), "unsupported x87 operation"), + "fyl2x": (attempt(f"{fld} d9 f1 {fstp} {fstp} c3"), "unsupported x87 operation"), "fnsave": (attempt(f"{fld} dd 31 {fstp} c3"), "unsupported x87 operation"), "frstor": (attempt(f"dd 21 {fld} {fstp} c3"), "unsupported x87 operation"), } diff --git a/tests/cpu/x87_status.py b/tests/cpu/x87_status.py index 86cbfa50f..a1526973f 100644 --- a/tests/cpu/x87_status.py +++ b/tests/cpu/x87_status.py @@ -536,8 +536,8 @@ def split(last): # test ah, 40h; jne C3; test ah, 01h; jmp out; C3: ; jne "FCOM alias DC D1": (attempt(f"{two} dc d1 {pop2} {clear}"), "unsupported x87 encoding"), "FCOMP alias DC D9": (attempt(f"{two} dc d9 dd d8 {clear}"), "unsupported x87 encoding"), "FCOMP alias DE D1": (attempt(f"{two} de d1 dd d8 {clear}"), "unsupported x87 encoding"), - "FSINCOS": (attempt(f"{fld} d9 fb dd d8 {clear}"), "unsupported x87 operation"), - "FPATAN": (attempt(f"{fld} d9 f3 dd d8 {clear}"), "unsupported x87 operation"), + "F2XM1": (attempt(f"{fld} d9 f0 dd d8 {clear}"), "unsupported x87 operation"), + "FYL2X": (attempt(f"{fld} d9 f1 dd d8 {clear}"), "unsupported x87 operation"), "FLDENV m28": (attempt(f"{fld} d9 21 dd d8 {clear}"), "unsupported x87 operation"), "FCOMPP with one value": (attempt(f"{fld} de d9 {clear}"), "x87 stack underflow"), "FUCOM ST(2) with two values": (attempt(f"{two} dd e2 {pop2} {clear}"), "x87 stack underflow"), diff --git a/tests/cpu/x87_sub.py b/tests/cpu/x87_sub.py index c20553923..4276e4593 100644 --- a/tests/cpu/x87_sub.py +++ b/tests/cpu/x87_sub.py @@ -288,7 +288,7 @@ def attempt(hex_bytes): "fdecstp": (attempt(f"{fld} d9 f6 {fstp} c3"), "unsupported x87 operation"), "fxsave": (attempt(f"{fld} 0f ae 01 {fstp} c3"), "unsupported x87 operation"), "fnstenv": (attempt(f"{fld} {fld} d9 31 {fstp} {fstp} c3"), "stores the tag word of a non-empty x87 stack"), - "fcos": (attempt(f"{fld} d9 ff {fstp} c3"), "unsupported x87 operation"), + "f2xm1": (attempt(f"{fld} d9 f0 {fstp} c3"), "unsupported x87 operation"), } for case, (message, needle) in rejected.items(): if message is None or needle not in message: diff --git a/tests/cpu/x87_trig.asm b/tests/cpu/x87_trig.asm new file mode 100644 index 000000000..e046cbc6f --- /dev/null +++ b/tests/cpu/x87_trig.asm @@ -0,0 +1,251 @@ +; coverage: source cpu_aot_x87_trig +; Generated by tests/cpu/x87_trig.py asm; edit SEQUENCES there and regenerate. +; Source-owned differential fixture for FSIN, FCOS, FSINCOS, FPTAN and FPATAN in the x87 +; leaf-function profile. Each export reads an input block at RCX, writes an output block at +; RDX and returns with the x87 stack empty. +.code + +sin_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsin + fnstsw ax + and ah, 04h + mov byte ptr [rdx+32], ah + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +sin_m80 ENDP + +sin_to_m64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsin + fstp qword ptr [rdx+0] + mov eax, 0 + ret +sin_to_m64 ENDP + +sin_to_m32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsin + fstp dword ptr [rdx+0] + mov eax, 0 + ret +sin_to_m32 ENDP + +cos_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fcos + fnstsw ax + and ah, 04h + mov byte ptr [rdx+32], ah + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +cos_m80 ENDP + +cos_to_m64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fcos + fstp qword ptr [rdx+0] + mov eax, 0 + ret +cos_to_m64 ENDP + +cos_to_m32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fcos + fstp dword ptr [rdx+0] + mov eax, 0 + ret +cos_to_m32 ENDP + +sin_c2_readers PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsin + fnstsw ax + sahf + mov byte ptr [rdx+32], 1 + jp sin_c2_readers_jp + mov byte ptr [rdx+32], 0 +sin_c2_readers_jp: + test ah, 04h + mov byte ptr [rdx+33], 1 + jne sin_c2_readers_jne + mov byte ptr [rdx+33], 0 +sin_c2_readers_jne: + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +sin_c2_readers ENDP + +sincos_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsincos + fnstsw ax + and ah, 04h + mov byte ptr [rdx+32], ah + fstp tbyte ptr [rdx+16] + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +sincos_m80 ENDP + +sincos_sum PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fsincos + fmul st(0), st(0) + fxch st(1) + fmul st(0), st(0) + faddp st(1), st + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +sincos_sum ENDP + +sincos_depth7 PROC FRAME + .endprolog + fld qword ptr [rcx+0] + fld qword ptr [rcx+8] + fld qword ptr [rcx+16] + fld qword ptr [rcx+24] + fld qword ptr [rcx+32] + fld qword ptr [rcx+40] + fld qword ptr [rcx+48] + fsincos + fstp qword ptr [rdx+0] + fstp qword ptr [rdx+8] + fstp qword ptr [rdx+16] + fstp qword ptr [rdx+24] + fstp qword ptr [rdx+32] + fstp qword ptr [rdx+40] + fstp qword ptr [rdx+48] + fstp qword ptr [rdx+56] + mov eax, 0 + ret +sincos_depth7 ENDP + +ptan_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fptan + fnstsw ax + and ah, 04h + mov byte ptr [rdx+32], ah + fstp tbyte ptr [rdx+16] + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +ptan_m80 ENDP + +ptan_c2_reset PROC FRAME + .endprolog + fldz + fldz + fdivp st(1), st + ftst + fstp st(0) + fld tbyte ptr [rcx+0] + fptan + fnstsw ax + and ah, 04h + mov byte ptr [rdx+32], ah + fstp tbyte ptr [rdx+16] + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +ptan_c2_reset ENDP + +ptan_to_m64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+0] + fptan + fstp st(0) + fstp qword ptr [rdx+0] + mov eax, 0 + ret +ptan_to_m64 ENDP + +ptan_depth7 PROC FRAME + .endprolog + fld qword ptr [rcx+0] + fld qword ptr [rcx+8] + fld qword ptr [rcx+16] + fld qword ptr [rcx+24] + fld qword ptr [rcx+32] + fld qword ptr [rcx+40] + fld qword ptr [rcx+48] + fptan + fstp qword ptr [rdx+0] + fstp qword ptr [rdx+8] + fstp qword ptr [rdx+16] + fstp qword ptr [rdx+24] + fstp qword ptr [rdx+32] + fstp qword ptr [rdx+40] + fstp qword ptr [rdx+48] + fstp qword ptr [rdx+56] + mov eax, 0 + ret +ptan_depth7 ENDP + +patan_m80 PROC FRAME + .endprolog + fld tbyte ptr [rcx+16] + fld tbyte ptr [rcx+0] + fpatan + fstp tbyte ptr [rdx+0] + mov eax, 0 + ret +patan_m80 ENDP + +patan_to_m64 PROC FRAME + .endprolog + fld tbyte ptr [rcx+16] + fld tbyte ptr [rcx+0] + fpatan + fstp qword ptr [rdx+0] + mov eax, 0 + ret +patan_to_m64 ENDP + +patan_to_m32 PROC FRAME + .endprolog + fld tbyte ptr [rcx+16] + fld tbyte ptr [rcx+0] + fpatan + fstp dword ptr [rdx+0] + mov eax, 0 + ret +patan_to_m32 ENDP + +patan_depth8 PROC FRAME + .endprolog + fld qword ptr [rcx+0] + fld qword ptr [rcx+8] + fld qword ptr [rcx+16] + fld qword ptr [rcx+24] + fld qword ptr [rcx+32] + fld qword ptr [rcx+40] + fld qword ptr [rcx+48] + fld qword ptr [rcx+56] + fpatan + fstp qword ptr [rdx+0] + fstp qword ptr [rdx+8] + fstp qword ptr [rdx+16] + fstp qword ptr [rdx+24] + fstp qword ptr [rdx+32] + fstp qword ptr [rdx+40] + fstp qword ptr [rdx+48] + mov eax, 0 + ret +patan_depth8 ENDP + +END diff --git a/tests/cpu/x87_trig.def b/tests/cpu/x87_trig.def new file mode 100644 index 000000000..fc84eaf2c --- /dev/null +++ b/tests/cpu/x87_trig.def @@ -0,0 +1,19 @@ +EXPORTS + sin_m80 + sin_to_m64 + sin_to_m32 + cos_m80 + cos_to_m64 + cos_to_m32 + sin_c2_readers + sincos_m80 + sincos_sum + sincos_depth7 + ptan_m80 + ptan_c2_reset + ptan_to_m64 + ptan_depth7 + patan_m80 + patan_to_m64 + patan_to_m32 + patan_depth8 diff --git a/tests/cpu/x87_trig.py b/tests/cpu/x87_trig.py new file mode 100644 index 000000000..c4f4d6020 --- /dev/null +++ b/tests/cpu/x87_trig.py @@ -0,0 +1,764 @@ +"""Compare native and translated FSIN, FCOS, FSINCOS, FPTAN and FPATAN of the x87 leaf-function profile. + +Usage: + python tests/cpu/x87_trig.py asm regenerate the MASM source and exports + python tests/cpu/x87_trig.py emit [control] translate (and optionally mutate) the fixture + python tests/cpu/x87_trig.py check [controls...] + +The exports, harness and guards follow tests/cpu/x87_add.py, and the other steps use the format of +tests/cpu/x87_moves.py. emit checks that every decoded x87 instruction is the form its sequence names. +The independent model uses 150-digit Decimal arithmetic and shares no code with tools/x87_soft.h. +""" +from decimal import Decimal, ROUND_HALF_EVEN, getcontext +import ctypes +from pathlib import Path +import platform +import random +import re +import sys + +getcontext().prec = 150 + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +import x87_add as base # noqa: E402 (tests/cpu is the script directory) +import x87_moves as moves # noqa: E402 +from x87_add import INDEFINITE, J, Q, classify, from_binary, m80_bytes, to_binary # noqa: E402 +from x87_div import SIZE # noqa: E402 + +INPUT, OUTPUT = base.INPUT, base.OUTPUT +PI = Decimal("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128") +TWO_PI = 2 * PI +SQRT3 = Decimal(3).sqrt() +ATAN_THRESH = Decimal(2) - SQRT3 + +# name: (input kind, steps). +SEQUENCES = { + "sin_m80": ("m80", [("fld", "m80", 0), ("fsin",), ("sw_c2", 32), ("fstp", "m80", 0)]), + "sin_to_m64": ("m80", [("fld", "m80", 0), ("fsin",), ("fstp", "m64", 0)]), + "sin_to_m32": ("m80", [("fld", "m80", 0), ("fsin",), ("fstp", "m32", 0)]), + "cos_m80": ("m80", [("fld", "m80", 0), ("fcos",), ("sw_c2", 32), ("fstp", "m80", 0)]), + "cos_to_m64": ("m80", [("fld", "m80", 0), ("fcos",), ("fstp", "m64", 0)]), + "cos_to_m32": ("m80", [("fld", "m80", 0), ("fcos",), ("fstp", "m32", 0)]), + "sin_c2_readers": ("m80", [("fld", "m80", 0), ("fsin",), ("c2_readers", 32), ("fstp", "m80", 0)]), + # FSINCOS replaces ST(0) with sin and pushes cos: ST(0)=cos -> [rdx+16], ST(1)=sin -> [rdx+0]. + "sincos_m80": ("m80_in", [("fld", "m80", 0), ("fsincos",), ("sw_c2", 32), + ("fstp", "m80", 16), ("fstp", "m80", 0)]), + "sincos_sum": ("m80_in", [("fld", "m80", 0), ("fsincos",), ("fmul_st0",), ("fxch", 1), + ("fmul_st0",), ("faddp", "pop", 1), ("fstp", "m80", 0)]), + "sincos_depth7": ("m64x7_in", [("fld", "m64", 8 * k) for k in range(7)] + [("fsincos",)] + + [("fstp", "m64", 8 * k) for k in range(8)]), + # FPTAN replaces ST(0) with tan and pushes 1.0: ST(0)=1.0 -> [rdx+16], ST(1)=tan -> [rdx+0]. + "ptan_m80": ("m80_in", [("fld", "m80", 0), ("fptan",), ("sw_c2", 32), + ("fstp", "m80", 16), ("fstp", "m80", 0)]), + "ptan_c2_reset": ("m80_in", [("fldz",), ("fldz",), ("fdivp", "pop", 1), ("ftst",), ("pop",), + ("fld", "m80", 0), ("fptan",), ("sw_c2", 32), + ("fstp", "m80", 16), ("fstp", "m80", 0)]), + "ptan_to_m64": ("m80_in", [("fld", "m80", 0), ("fptan",), ("pop",), ("fstp", "m64", 0)]), + "ptan_depth7": ("m64x7_in", [("fld", "m64", 8 * k) for k in range(7)] + [("fptan",)] + + [("fstp", "m64", 8 * k) for k in range(8)]), + # FPATAN computes atan2(ST(1), ST(0)) into ST(1) and pops: load y at [rcx+16], x at [rcx+0]. + "patan_m80": ("pair80", [("fld", "m80", 16), ("fld", "m80", 0), ("fpatan",), ("fstp", "m80", 0)]), + "patan_to_m64": ("pair80", [("fld", "m80", 16), ("fld", "m80", 0), ("fpatan",), ("fstp", "m64", 0)]), + "patan_to_m32": ("pair80", [("fld", "m80", 16), ("fld", "m80", 0), ("fpatan",), ("fstp", "m32", 0)]), + "patan_depth8": ("m64x8", [("fld", "m64", 8 * k) for k in range(8)] + [("fpatan",)] + + [("fstp", "m64", 8 * k) for k in range(7)]), +} + +CONTROLS = { + # C2 is never set for |x| >= 2^63. + "noc2": (re.compile(r"x87_sw = static_cast\(c2 \? 0x0400 : 0\);"), "x87_sw = 0;"), + # The out-of-range threshold uses 2^62 instead of 2^63. + "c262": (re.compile(r"if \(u\.e >= 63\) \{([^\n]*// trig range)"), r"if (u.e >= 62) {\1"), + # FSINCOS writes cos into ST(1) and sin into ST(0). + "sincosswap": (re.compile(r"x87_slot\[(\d+)\] = x87_sincos\(([^;]+)\); if \(c2\) x87_trap\(\); x87_slot\[(\d+)\] = c;"), + r"x87_slot[\3] = x87_sincos(\2); if (c2) x87_trap(); x87_slot[\1] = c;"), + # FPTAN pushes 0.0 instead of 1.0. + "ptanno1": (re.compile(r"one_out = \{x87_integer_bit, 0x3fff\}; // ptan one"), + "one_out = {0, 0}; // ptan one"), + # FPATAN computes atan2(x, y) instead of atan2(y, x). + "patanswap": (re.compile(r"x87_patan\(x87_slot\[(\d+)\], x87_slot\[(\d+)\], x87_cw\)"), + r"x87_patan(x87_slot[\2], x87_slot[\1], x87_cw)"), + # sin(-0) returns +0. + "sinnegzero": (re.compile(r"if \(sin_out\) \*sin_out = a; // trig zero"), + "if (sin_out) *sin_out = {0, 0}; // trig zero"), + # Signaling NaN is returned unquieted. + "snan": (re.compile(r"x87_quiet\(a\)"), "a"), + # Transcendental results round to 53 bits instead of 64. + "pc53": (re.compile(r"x87_arith64, x87_rounding"), "x87_arith, x87_rounding"), +} + + +# ---- MASM generation and decoding ------------------------------------------------------------------ + +def asm_lines(step, name): + op, *args = step + if op in ("fsin", "fcos", "fsincos", "fptan", "fpatan", "fldz", "ftst"): + return [f" {op}"] + if op == "fmul_st0": + return [" fmul st(0), st(0)"] + if op == "pop": + return [" fstp st(0)"] + if op == "sw_c2": + return [" fnstsw ax", " and ah, 04h", f" mov byte ptr [rdx+{args[0]}], ah"] + if op == "c2_readers": + o = args[0] + return [" fnstsw ax", " sahf", + f" mov byte ptr [rdx+{o}], 1", f" jp {name}_jp", f" mov byte ptr [rdx+{o}], 0", + f"{name}_jp:", + " test ah, 04h", + f" mov byte ptr [rdx+{o + 1}], 1", f" jne {name}_jne", f" mov byte ptr [rdx+{o + 1}], 0", + f"{name}_jne:"] + return [moves.asm_line(step)] + + +def expected_forms(step): + op, *args = step + if op in ("fsin", "fcos", "fsincos", "fptan", "fpatan", "fldz", "ftst"): + return [(op, "")] + if op == "fmul_st0": + return [("fmul", "st0,st0")] + if op == "pop": + return [("fstp", "st0")] + if op in ("sw_c2", "c2_readers"): + return [("fnstsw", "ax")] + return [moves.expected_form(step)] + + +def decoded_form(i): + from iced_x86 import Mnemonic as M, Register as R + + if i.mnemonic == M.FNSTSW and i.op0_register == R.AX: + return "fnstsw", "ax" + return moves.decoded_form(i) + + +def write_asm(asm_path, def_path): + lines = ["; coverage: source cpu_aot_x87_trig", + "; Generated by tests/cpu/x87_trig.py asm; edit SEQUENCES there and regenerate.", + "; Source-owned differential fixture for FSIN, FCOS, FSINCOS, FPTAN and FPATAN in the x87", + "; leaf-function profile. Each export reads an input block at RCX, writes an output block at", + "; RDX and returns with the x87 stack empty.", ".code", ""] + for name, (_, steps) in SEQUENCES.items(): + body = [line for s in steps for line in asm_lines(s, name)] + lines += [f"{name} PROC FRAME", " .endprolog", *body, " mov eax, 0", " ret", f"{name} ENDP", ""] + lines.append("END") + Path(asm_path).write_text("\n".join(lines) + "\n", encoding="ascii") + Path(def_path).write_text("EXPORTS\n" + "".join(f" {name}\n" for name in SEQUENCES), encoding="ascii") + + +def emit(image, output, control="lifted"): + import pefile + from cpu_leaf_aot import export_rva + from cpu_ranges import function_ranges + from ffx_version_query import INTEGER_HEADER, lower, region + from x87_lower import X87_HEADER, is_x87 + + parts = [INTEGER_HEADER, X87_HEADER] + with pefile.PE(str(image), fast_load=True) as pe: + for name, (_, steps) in SEQUENCES.items(): + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + decoded = [decoded_form(i) for i in body if is_x87(i)] + wanted = [form for s in steps for form in expected_forms(s)] + if decoded != wanted: + raise AssertionError(f"{name} assembled as {decoded}, expected {wanted}") + code = lower(body, ["rcx = a; rdx = b;"], {}, {}, {}, x87=True) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b) {{\n{code}\n}}\n') + text = "".join(parts) + if control != "lifted": + expression, replacement = CONTROLS[control] + text, count = expression.subn(replacement, text) + if not count: + raise AssertionError(f"control {control} changed nothing") + print(f"control {control}: {count} replacements") + output.write_text(text, encoding="ascii") + + +# ---- Independent model ----------------------------------------------------------------------------- + +def m80_to_dec(v): + c = classify(v) + assert c[0] in ("zero", "finite"), c + if c[0] == "zero": + return Decimal(0) + sign = -1 if c[1] else 1 + q = c[2] + return sign * Decimal(q.numerator) / Decimal(q.denominator) + + +def dec_to_m80(sign, val): + """Round exact nonnegative Decimal val to 64-bit extended m80 (nearest-even).""" + if val == 0: + return 0, sign << 15 + # Estimate binary exponent via Decimal.adjusted() * log2(10). + e = int(val.adjusted() * 3.321928094887362) + p2 = Decimal(2) + while p2 ** (e + 1) <= val: + e += 1 + while p2 ** e > val: + e -= 1 + if e > 16383: + return J, (sign << 15) | 0x7FFF + if e < -16382: + shift = -16382 - 63 - e + if shift > 64: + return 0, sign << 15 + scaled = val / (p2 ** (-16382 - 63)) + sig = int(scaled.to_integral_value(rounding=ROUND_HALF_EVEN)) + if sig >= J: + return J, (sign << 15) | 1 + return sig, sign << 15 + scaled = val * (p2 ** (63 - e)) + sig = int(scaled.to_integral_value(rounding=ROUND_HALF_EVEN)) + if sig >= (1 << 64): + sig >>= 1 + e += 1 + if e > 16383: + return J, (sign << 15) | 0x7FFF + return sig, (sign << 15) | (e + 16383) + + +def dec_sincos(x): + """High-precision (sin(x), cos(x)) for Decimal x.""" + k = (x / TWO_PI).to_integral_value() + r = x - k * TWO_PI + r2 = r * r + term = r + s = r + n = 1 + while abs(term) > Decimal("1e-115"): + term = -term * r2 / ((2 * n) * (2 * n + 1)) + s += term + n += 1 + term = Decimal(1) + c = Decimal(1) + n = 1 + while abs(term) > Decimal("1e-115"): + term = -term * r2 / ((2 * n - 1) * (2 * n)) + c += term + n += 1 + return s, c + + +def dec_atan_unit(z): + if z > ATAN_THRESH: + return PI / 6 + dec_atan_unit((SQRT3 * z - 1) / (SQRT3 + z)) + term = z + a = z + z2 = z * z + n = 1 + while abs(term) > Decimal("1e-115"): + term = -term * z2 + a += term / (2 * n + 1) + n += 1 + return a + + +def dec_atan2(y, x): + ay, ax = abs(y), abs(x) + a = dec_atan_unit(ay / ax) if ay <= ax else (PI / 2 - dec_atan_unit(ax / ay)) + if x < 0: + a = PI - a + return -a if y < 0 else a + + +def trig_op(op, v): + """Model FSIN/FCOS/FSINCOS/FPTAN: returns (c2, result_list) where result_list has 1 or 2 m80 pairs.""" + c = classify(v) + if c[0] in ("unsupported", "inf"): + return 0, [INDEFINITE] if op in ("fsin", "fcos") else [INDEFINITE, INDEFINITE] + if c[0] == "nan": + q = (v[0] | Q, v[1]) + return 0, [q] if op in ("fsin", "fcos") else [q, q] + if c[0] == "zero": + one = (J, 0x3FFF) + if op == "fsin": + return 0, [v] + if op == "fcos": + return 0, [one] + if op == "fsincos": + return 0, [v, one] + return 0, [v, one] + # Finite nonzero + x = m80_to_dec(v) + if abs(x) >= Decimal(2) ** 63: + if op in ("fsin", "fcos"): + return 1, [v] + return 1, [v, INDEFINITE] + if abs(x) < Decimal(2) ** -64: + # Re-encode pseudo-denormal at biased exp 1, keep denormal/normal unchanged. + re_v = (v[0], (v[1] & 0x8000) | 1) if (v[1] & 0x7FFF) == 0 and (v[0] & J) else v + one = (J, 0x3FFF) + if op == "fsin": + return 0, [re_v] + if op == "fcos": + return 0, [one] + return 0, [re_v, one] + s, co = dec_sincos(x) + if op == "fsin": + return 0, [dec_to_m80(int(s < 0), abs(s))] + if op == "fcos": + return 0, [dec_to_m80(int(co < 0), abs(co))] + if op == "fsincos": + return 0, [dec_to_m80(int(s < 0), abs(s)), dec_to_m80(int(co < 0), abs(co))] + t = s / co + return 0, [dec_to_m80(int(t < 0), abs(t)), (J, 0x3FFF)] + + +def patan(y, x): + """Model FPATAN = atan2(y, x).""" + cy, cx = classify(y), classify(x) + if "unsupported" in (cy[0], cx[0]) or "nan" in (cy[0], cx[0]): + return base.add(y, x) + sy, sx = y[1] >> 15, x[1] >> 15 + if cy[0] == "zero": + return dec_to_m80(sy, PI) if sx else (0, sy << 15) + if cy[0] == "inf": + if cx[0] == "inf": + return dec_to_m80(sy, 3 * PI / 4 if sx else PI / 4) + return dec_to_m80(sy, PI / 2) + if cx[0] == "inf": + return dec_to_m80(sy, PI) if sx else (0, sy << 15) + if cx[0] == "zero": + return dec_to_m80(sy, PI / 2) + val = dec_atan2(m80_to_dec(y), m80_to_dec(x)) + return dec_to_m80(sy, abs(val)) + + +def reference(name, data): + """Returns (output_bytes, c2, exact_slots_mask) for output comparison.""" + slots, out = [], bytearray(b"\xcc" * OUTPUT) + c2 = 0 + inexact = [] # track whether each output offset may differ by ULP on native hardware + + def read(kind, offset): + return int.from_bytes(data[offset:offset + SIZE[kind]], "little") + + for op, *args in SEQUENCES[name][1]: + if op in ("fsin", "fcos", "fsincos", "fptan"): + v = slots.pop() + c2, res = trig_op(op, v) + c = classify(v) + is_finite_inrange = c[0] == "finite" and abs(m80_to_dec(v)) < Decimal(2) ** 63 + slots.extend(res) + # Mark transcendental slot(s) as inexact if finite in-range (except pushed 1.0 of fptan). + if op in ("fsin", "fcos"): + inexact.append(is_finite_inrange) + elif op == "fsincos": + inexact.extend([is_finite_inrange, is_finite_inrange]) + else: + inexact.extend([is_finite_inrange, False]) + elif op == "fpatan": + x = slots.pop() + y = slots.pop() + cy, cx = classify(y), classify(x) + is_fin = cy[0] == "finite" and cx[0] == "finite" + slots.append(patan(y, x)) + inexact = inexact[:-2] + [is_fin] + elif op == "fldz": + slots.append((0, 0)) + inexact.append(False) + elif op == "fdivp": + b = slots.pop() + a = slots.pop() + slots.append(_div(a, b)) + inexact = inexact[:-2] + [False] + elif op == "ftst": + c2 = 1 if classify(slots[-1])[0] in ("nan", "unsupported") else 0 + elif op == "fld": + raw = read(*args) + slots.append((raw & (2 ** 64 - 1), raw >> 64) if args[0] == "m80" else from_binary(args[0], raw)) + inexact.append(False) + elif op == "fstp": + kind, offset = args + v = slots.pop() + inexact.pop() + encoded = v[0] | v[1] << 64 if kind == "m80" else to_binary(kind, v) + out[offset:offset + SIZE[kind]] = encoded.to_bytes(SIZE[kind], "little") + elif op == "pop": + slots.pop() + inexact.pop() + elif op == "fxch": + k = -1 - args[0] + slots[-1], slots[k] = slots[k], slots[-1] + inexact[-1], inexact[k] = inexact[k], inexact[-1] + elif op == "fmul_st0": + slots[-1] = base.mul(slots[-1], slots[-1]) if hasattr(base, "mul") else _mul(slots[-1], slots[-1]) + elif op == "faddp": + slots[-2] = base.add(slots[-2], slots[-1]) + slots.pop() + inexact[-2] = inexact[-2] or inexact[-1] + inexact.pop() + elif op == "sw_c2": + out[args[0]] = 4 if c2 else 0 + elif op == "c2_readers": + out[args[0]] = 1 if c2 else 0 + out[args[0] + 1] = 1 if c2 else 0 + assert not slots + return bytes(out) + + +def _mul(a, b): + import x87_mul + return x87_mul.mul(a, b) + + +def _div(a, b): + import x87_div + return x87_div.div(a, b) + + +# ---- Inputs ---------------------------------------------------------------------------------------- + +def quadrant_values(): + """Values around quadrant boundaries k * pi / 2 and fractions.""" + vals = [] + for num, den in [(1, 6), (1, 4), (1, 3), (1, 2), (2, 3), (3, 4), (1, 1), (5, 4), (3, 2), (7, 4), (2, 1), (5, 2), (3, 1)]: + for sign in (0, 1): + base_v = dec_to_m80(sign, Decimal(num) * PI / Decimal(den)) + vals.append(base_v) + # Neighbors +-1 ULP around the boundary + vals.append((base_v[0] - 1, base_v[1])) + vals.append((base_v[0] + 1 if base_v[0] < (1 << 64) - 1 else base_v[0], base_v[1])) + for frac in ["0.1", "0.25", "0.5", "0.75", "1.0", "1.5", "2.0", "3.0", "7.5"]: + d = Decimal(frac) + vals.append(dec_to_m80(0, d)) + vals.append(dec_to_m80(1, d)) + return vals + + +def cases(): + rng = random.Random(37) + singles = list(base.m80_singles()) + quadrant_values() + # Add out-of-range boundaries: 2^63 - 1, 2^63, -2^63, 2^64, -2^64, 2^100, and tiny values. + singles += [ + (0xFFFFFFFFFFFFFFFF, 16383 + 62), + (0xFFFFFFFFFFFFFFFF, (16383 + 62) | 0x8000), + (J, 16383 + 63), + (J, (16383 + 63) | 0x8000), + (J, 16383 + 64), + (J, (16383 + 64) | 0x8000), + (J, 16383 + 100), + (J, 16383 - 34), + (J, 16383 - 65), + (J, (16383 - 65) | 0x8000), + (1, 0), + (1, 0x8000), + (J, 0), + ] + # Small/moderate random values (|x| <= 8) for tight native comparison, plus large |x| < 2^63. + for _ in range(150): + singles.append((J | rng.getrandbits(63), rng.randint(16383 - 30, 16383 + 2) | rng.choice((0, 0x8000)))) + for _ in range(80): + singles.append((J | rng.getrandbits(63), rng.randint(16383 + 3, 16383 + 62) | rng.choice((0, 0x8000)))) + for _ in range(20): + singles.append((J | 1 + rng.getrandbits(61), 0x7FFF | rng.choice((0, 0x8000)))) + + def in_range(v): + c = classify(v) + return c[0] != "finite" or abs(m80_to_dec(v)) < Decimal(2) ** 63 + + singles_in = [v for v in singles if in_range(v)] + f64_in = [b for b in base.f64_bits() if in_range(from_binary("m64", b))] + pairs = [(a, b) for a in base.m80_singles() for b in base.m80_singles()[::3]] + pairs += [(a, b) for a, b in zip(singles, reversed(singles))] + # Huge/tiny ratio pairs for FPATAN + pairs += [((1, 0), (J, 0x7FFE)), ((J, 0x7FFE), (1, 0)), ((J, 0x3FFF), (J, 0x3FFF))] + + blocks = { + "m80": [m80_bytes(v) for v in singles], + "m80_in": [m80_bytes(v) for v in singles_in], + "pair80": [m80_bytes(x) + m80_bytes(y) for x, y in pairs], + "m64x7_in": [b"".join(rng.choice(f64_in).to_bytes(8, "little") for _ in range(7)) for _ in range(150)], + "m64x8": [b"".join(rng.choice(base.f64_bits()).to_bytes(8, "little") for _ in range(8)) for _ in range(150)], + } + for name, (kind, _) in SEQUENCES.items(): + for block in blocks[kind]: + yield name, block.ljust(INPUT, b"\0") + + +# ---- Comparison helpers ---------------------------------------------------------------------------- + +def unpack_m80(buf): + return int.from_bytes(buf[:8], "little"), int.from_bytes(buf[8:10], "little") + + +def m80_ulp_diff(got_v, want_v): + cg, cw = classify(got_v), classify(want_v) + if cg[0] != cw[0]: + return float("inf") + if cg[0] in ("unsupported", "nan", "inf", "zero"): + return 0.0 if got_v == want_v else float("inf") + dg, dw = m80_to_dec(got_v), m80_to_dec(want_v) + e = (want_v[1] & 0x7FFF) - 16383 + if (want_v[1] & 0x7FFF) == 0: + e = -16382 + return float(abs(dg - dw) / (Decimal(2) ** (e - 63))) + + +def binary_ulp_diff(kind, got_bytes, want_bytes): + g_raw = int.from_bytes(got_bytes, "little") + w_raw = int.from_bytes(want_bytes, "little") + if g_raw == w_raw: + return 0 + g = from_binary(kind, g_raw) + w = from_binary(kind, w_raw) + if classify(g)[0] != "finite" or classify(w)[0] != "finite": + return float("inf") + bits = 32 if kind == "m32" else 64 + # Signed magnitude to ordered int for ULP distance + def ordered(raw): + sign = 1 << (bits - 1) + return -(raw & (sign - 1)) if (raw & sign) else raw + return abs(ordered(g_raw) - ordered(w_raw)) + + +def native_matches(name, data, got, want): + """Compare native hardware output with the model, allowing documented x87 transcendental tolerance.""" + if got == want: + return True + kind, steps = SEQUENCES[name] + if kind == "pair80" or name == "patan_depth8": + # FPATAN matches <= 2 ULPs in m80 and <= 1 ULP in m64/m32 across the entire range. + if name == "patan_m80": + return got[10:] == want[10:] and m80_ulp_diff(unpack_m80(got[:10]), unpack_m80(want[:10])) <= 2.0 + if name == "patan_to_m64": + return got[8:] == want[8:] and binary_ulp_diff("m64", got[:8], want[:8]) <= 1 + if name == "patan_to_m32": + return got[4:] == want[4:] and binary_ulp_diff("m32", got[:4], want[:4]) <= 1 + if name == "patan_depth8": + return got[8:] == want[8:] and binary_ulp_diff("m64", got[:8], want[:8]) <= 1 + # Single-input trig functions: check input magnitude and special status first. + v = unpack_m80(data[:10]) if kind in ("m80", "m80_in") else from_binary("m64", int.from_bytes(data[48:56], "little")) + c = classify(v) + if c[0] in ("unsupported", "nan", "inf", "zero"): + return False # Special values must match bit-for-bit. + xv = m80_to_dec(v) + if abs(xv) >= Decimal(2) ** 63: + return False # Out-of-range must match bit-for-bit (C2=1 and ST(0) unchanged). + # For |x| > 8 (large pi reduction) or near exact zero of sin/cos where 66-bit pi diverges: + # check C2/guard/auxiliary bytes match and result is finite; for |x| <= 8 check tight ULP bound. + large = abs(xv) > 8 + if name in ("sin_m80", "cos_m80"): + if got[10:32] != want[10:32] or got[32] != want[32] or got[33:] != want[33:]: + return False + gv, wv = unpack_m80(got[:10]), unpack_m80(want[:10]) + if large or abs(m80_to_dec(wv)) < Decimal(2) ** -50: + return classify(gv)[0] in ("zero", "finite") + return m80_ulp_diff(gv, wv) <= 4.0 + if name == "sin_c2_readers": + if got[10:34] != want[10:34] or got[34:] != want[34:]: + return False + gv, wv = unpack_m80(got[:10]), unpack_m80(want[:10]) + if large or abs(m80_to_dec(wv)) < Decimal(2) ** -50: + return classify(gv)[0] in ("zero", "finite") + return m80_ulp_diff(gv, wv) <= 4.0 + if name in ("sin_to_m64", "cos_to_m64", "ptan_to_m64"): + if got[8:] != want[8:]: + return False + if large: + return classify(from_binary("m64", int.from_bytes(got[:8], "little")))[0] in ("zero", "finite") + wv = from_binary("m64", int.from_bytes(want[:8], "little")) + if abs(m80_to_dec(wv)) < Decimal(2) ** -40 or (name == "ptan_to_m64" and abs(m80_to_dec(wv)) > Decimal(2) ** 40): + return classify(from_binary("m64", int.from_bytes(got[:8], "little")))[0] in ("zero", "finite") + return binary_ulp_diff("m64", got[:8], want[:8]) <= 1 + if name in ("sin_to_m32", "cos_to_m32"): + if got[4:] != want[4:]: + return False + if large: + return classify(from_binary("m32", int.from_bytes(got[:4], "little")))[0] in ("zero", "finite") + wv = from_binary("m32", int.from_bytes(want[:4], "little")) + if abs(m80_to_dec(wv)) < Decimal(2) ** -20: + return classify(from_binary("m32", int.from_bytes(got[:4], "little")))[0] in ("zero", "finite") + return binary_ulp_diff("m32", got[:4], want[:4]) <= 1 + if name == "sincos_m80": + if got[10:16] != want[10:16] or got[26:32] != want[26:32] or got[32] != want[32] or got[33:] != want[33:]: + return False + gs, ws = unpack_m80(got[:10]), unpack_m80(want[:10]) + gc, wc = unpack_m80(got[16:26]), unpack_m80(want[16:26]) + if large: + return classify(gs)[0] in ("zero", "finite") and classify(gc)[0] in ("zero", "finite") + ok_s = (classify(gs)[0] in ("zero", "finite")) if abs(m80_to_dec(ws)) < Decimal(2) ** -50 else (m80_ulp_diff(gs, ws) <= 4.0) + ok_c = (classify(gc)[0] in ("zero", "finite")) if abs(m80_to_dec(wc)) < Decimal(2) ** -50 else (m80_ulp_diff(gc, wc) <= 4.0) + return ok_s and ok_c + if name == "sincos_sum": + if got[10:] != want[10:]: + return False + gv, wv = unpack_m80(got[:10]), unpack_m80(want[:10]) + return m80_ulp_diff(gv, wv) <= 4.0 + if name in ("ptan_m80", "ptan_c2_reset"): + if got[10:16] != want[10:16] or got[16:26] != want[16:26] or got[26:32] != want[26:32] or got[32] != want[32] or got[33:] != want[33:]: + return False + gt, wt = unpack_m80(got[:10]), unpack_m80(want[:10]) + if large or abs(m80_to_dec(wt)) < Decimal(2) ** -50 or abs(m80_to_dec(wt)) > Decimal(2) ** 50: + return classify(gt)[0] in ("zero", "finite") + return m80_ulp_diff(gt, wt) <= 4.0 + if name in ("sincos_depth7", "ptan_depth7"): + # St(0) at [0..8] is cos / 1.0, St(1) at [8..16] is sin / tan, rest [16..64] exact. + if got[16:] != want[16:]: + return False + if name == "ptan_depth7" and got[:8] != want[:8]: + return False + if large: + return True + ok0 = True if name == "ptan_depth7" else binary_ulp_diff("m64", got[:8], want[:8]) <= 1 + ok1 = binary_ulp_diff("m64", got[8:16], want[8:16]) <= 1 + return ok0 and ok1 + return False + + +def lifted_matches(name, got, want): + if got == want: + return True + kind, _ = SEQUENCES[name] + if name in ("sin_m80", "cos_m80", "patan_m80", "sincos_sum"): + off_end = 32 if name in ("sin_m80", "cos_m80") else 10 + if got[10:off_end] != want[10:off_end] or got[off_end:] != want[off_end:]: + return False + return m80_ulp_diff(unpack_m80(got[:10]), unpack_m80(want[:10])) <= 1.0 + if name == "sin_c2_readers": + return got[10:] == want[10:] and m80_ulp_diff(unpack_m80(got[:10]), unpack_m80(want[:10])) <= 1.0 + if name in ("sin_to_m64", "cos_to_m64", "ptan_to_m64", "patan_to_m64", "patan_depth8"): + return got[8:] == want[8:] and binary_ulp_diff("m64", got[:8], want[:8]) <= 1 + if name in ("sin_to_m32", "cos_to_m32", "patan_to_m32"): + return got[4:] == want[4:] and binary_ulp_diff("m32", got[:4], want[:4]) <= 1 + if name == "sincos_m80": + return (got[10:16] == want[10:16] and got[26:] == want[26:] + and m80_ulp_diff(unpack_m80(got[:10]), unpack_m80(want[:10])) <= 1.0 + and m80_ulp_diff(unpack_m80(got[16:26]), unpack_m80(want[16:26])) <= 1.0) + if name in ("ptan_m80", "ptan_c2_reset"): + return (got[10:16] == want[10:16] and got[16:] == want[16:] + and m80_ulp_diff(unpack_m80(got[:10]), unpack_m80(want[:10])) <= 1.0) + if name in ("sincos_depth7", "ptan_depth7"): + return (got[16:] == want[16:] + and (got[:8] == want[:8] if name == "ptan_depth7" else binary_ulp_diff("m64", got[:8], want[:8]) <= 1) + and binary_ulp_diff("m64", got[8:16], want[8:16]) <= 1) + return False + + +# ---- Check ----------------------------------------------------------------------------------------- + +def check(harness_path, native_path, lifted_path, *control_paths): + expected = [(name, data, reference(name, data)) for name, data in cases()] + for label, path, matcher in (("native", native_path, lambda n, d, g, w: native_matches(n, d, g, w)), + ("lifted", lifted_path, lambda n, d, g, w: lifted_matches(n, g, w))): + run = base.Runner(harness_path, path) + bad = 0 + for name, data, want in expected: + got, state = run(name, data) + if not base.entry_state_ok(state): + raise AssertionError(f"{label} {name} left state {state:#014x}; the profile requires control " + "0x027f and an empty stack at TOP 0") + if not matcher(name, data, got, want): + if not bad: + print(f"{label} first mismatch: {name}(input {data[:32].hex()})\n got {got[:40].hex()}\n" + f" expected {want[:40].hex()}") + bad += 1 + if bad: + raise AssertionError(f"{label}: {bad}/{len(expected)} mismatches") + print(f"{len(expected)} cases over {len(SEQUENCES)} exports (output block and guards) matched the reference " + "in native and translated DLLs; each export returned with control 0x027f and an empty stack") + # Out-of-range |x| >= 2^63 for FSINCOS/FPTAN is outside the static-depth profile (hardware does not + # push when C2=1); verify the lifted DLL traps via x87_trap() (STATUS_ILLEGAL_INSTRUCTION) before + # writing the output buffer instead of continuing with a divergent stack. + lifted_lib = ctypes.CDLL(str(Path(lifted_path).resolve())) + in_buf = ctypes.create_string_buffer(INPUT) + out_buf = ctypes.create_string_buffer(OUTPUT) + for oor_v in ((J, 16383 + 63), (J, (16383 + 63) | 0x8000), (J, 16383 + 64), (J, 16383 + 100)): + oor_data = m80_bytes(oor_v).ljust(INPUT, b"\0") + for seq_name in ("sincos_m80", "ptan_m80", "ptan_c2_reset"): + fn = getattr(lifted_lib, seq_name) + fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + fn.restype = ctypes.c_uint64 + ctypes.memmove(in_buf, oor_data, INPUT) + ctypes.memset(out_buf, 0xCC, OUTPUT) + try: + fn(ctypes.addressof(in_buf), ctypes.addressof(out_buf)) + except OSError as exc: + if (getattr(exc, "winerror", 0) or 0) & 0xFFFFFFFF != 0xC000001D: + raise AssertionError(f"lifted {seq_name} out-of-range {oor_v} unexpected SEH {exc!r}") from exc + else: + raise AssertionError(f"lifted {seq_name} out-of-range {oor_v} returned instead of trapping") + if out_buf.raw != b"\xcc" * OUTPUT: + raise AssertionError(f"lifted {seq_name} out-of-range {oor_v} wrote output before trapping") + print(f"processor: {platform.processor()}") + first = {} + for name, data, want in expected: + first.setdefault(name, (data, want)) + for label, path in (("native", native_path), ("lifted", lifted_path)): + run = base.Runner(harness_path, path) + failed = [name for name, (data, want) in first.items() if not base.preserved(run, "x87_call", name, data, want)] + if failed: + raise AssertionError(f"x87_call lost a live caller value or control word around {label} {failed}") + print(f"x87_call kept a live caller ST(0) value and control word around all {len(first)} native and " + "translated exports") + for path in control_paths: + control = Path(path).stem.rsplit("_", 1)[-1] + run = base.Runner(harness_path, path) + bad = 0 + for name, data, want in expected: + try: + got, _ = run(name, data) + except OSError as exc: + if (getattr(exc, "winerror", 0) or 0) & 0xFFFFFFFF == 0xC000001D: + bad += 1 + continue + raise + if not lifted_matches(name, got, want): + bad += 1 + print(f"control {control}: {bad}/{len(expected)} mismatches") + if not bad: + raise AssertionError(f"control {control} matched every case") + check_rejections() + + +def check_rejections(): + from iced_x86 import Decoder + from ffx_version_query import lower + + def attempt(hex_bytes): + body = list(Decoder(64, bytes.fromhex(hex_bytes), ip=0x1000)) + try: + lower(body, [], {}, {}, {}, x87=True) + except ValueError as exc: + return str(exc) + return None + + fld, fstp = "db 29", "db 3a" # fld tbyte ptr [rcx]; fstp tbyte ptr [rdx] + sw = "df e0" # fnstsw ax + rejected = { + "fsin on an empty stack": (attempt("d9 fe c3"), "x87 stack underflow"), + "fcos on an empty stack": (attempt("d9 ff c3"), "x87 stack underflow"), + "fsincos on an empty stack": (attempt("d9 fb c3"), "x87 stack underflow"), + "fsincos at depth 8": (attempt(f"{fld} " * 8 + "d9 fb " + f"{fstp} " * 9 + "c3"), "x87 stack overflow"), + "fptan on an empty stack": (attempt("d9 f2 c3"), "x87 stack underflow"), + "fptan at depth 8": (attempt(f"{fld} " * 8 + "d9 f2 " + f"{fstp} " * 9 + "c3"), "x87 stack overflow"), + "fpatan on an empty stack": (attempt("d9 f3 c3"), "x87 stack underflow"), + "fpatan with one value": (attempt(f"{fld} d9 f3 {fstp} c3"), "x87 stack underflow"), + "fsincos with one store": (attempt(f"{fld} d9 fb {fstp} c3"), "x87 stack not empty at return"), + "fptan without popping 1.0": (attempt(f"{fld} d9 f2 {fstp} c3"), "x87 stack not empty at return"), + "fsin then SAHF and JB (C0 unknown)": (attempt(f"{fld} d9 fe {sw} 9e 72 00 {fstp} c3"), + "reads CF, which depends on a status-word bit"), + "fcos then TEST AH, 01h (C0 unknown)": (attempt(f"{fld} d9 ff {sw} f6 c4 01 75 00 {fstp} c3"), + "reads ZF, which depends on a status-word bit"), + "fpatan then SAHF and JP (C2 unknown)": (attempt(f"{fld} {fld} d9 f3 {sw} 9e 7a 00 {fstp} c3"), + "reads PF, which depends on a status-word bit"), + "fsin then FNSTSW m16": (attempt(f"{fld} d9 fe dd 3a {fstp} c3"), "stores status-word bits"), + "f2xm1": (attempt(f"{fld} d9 f0 {fstp} c3"), "unsupported x87 operation"), + } + for case, (message, needle) in rejected.items(): + if message is None or needle not in message: + raise AssertionError(f"{case}: expected a rejection containing {needle!r}, got {message!r}") + print(f"rejected {len(rejected)} sequences outside the profile: " + "; ".join(rejected)) + + +if __name__ == "__main__": + mode, first, second, *rest = sys.argv[1:] + if mode == "asm": + write_asm(first, second) + elif mode == "emit": + emit(Path(first), Path(second), *rest) + elif mode == "check": + check(first, second, *rest) + else: + raise ValueError(mode) diff --git a/tools/x87_lower.py b/tools/x87_lower.py index 4ab9fd9f4..cc03962db 100644 --- a/tools/x87_lower.py +++ b/tools/x87_lower.py @@ -3,6 +3,10 @@ The profile accepts: - FLD and FSTP with an m32, m64 or m80 operand, and FST with an m32 or m64 operand; - FLD, FST, FSTP and FXCH with ST(i), FCHS and FABS, FSQRT and FRNDINT; +- FSIN, FCOS, FSINCOS, FPTAN and FPATAN (64-bit precision; FSIN, FCOS, FSINCOS and FPTAN set C2 when + |ST(0)| >= 2^63 and leave C0, C1 and C3 undefined; FPATAN leaves C0 to C3 undefined; finite |ST(0)| >= 2^63 + for FSINCOS and FPTAN is outside the static-depth profile because hardware leaves the stack unchanged + without pushing, so lowered FSINCOS and FPTAN trap via x87_trap() when |ST(0)| >= 2^63); - FXTRACT, which replaces ST(0) by its exponent and pushes its significand, and FSCALE; - the constant loads FLD1, FLDZ, FLDPI, FLDL2T, FLDL2E, FLDLG2 and FLDLN2; - FILD, FISTP and FISTTP with an m16, m32 or m64 integer operand, and FIST with m16 or m32; @@ -123,7 +127,8 @@ M.FCMOVNE: "!zero", M.FCMOVNBE: "!carry && !zero", M.FCMOVU: "parity", M.FCMOVNU: "!parity"} # 8087/287 interrupt-mask and protected-mode controls; the 80387 and later execute them as FNOP. LEGACY_CONTROLS = {M.FNENI: "fneni", M.FNDISI: "fndisi", M.FNSETPM: "fnsetpm"} -X87_OPS = frozenset({M.FLD, M.FST, M.FSTP, M.FXCH, M.FCHS, M.FABS, M.FSQRT, M.FRNDINT, M.FLD1, M.FLDZ, M.FLDPI, M.FLDL2T, M.FLDL2E, +X87_OPS = frozenset({M.FLD, M.FST, M.FSTP, M.FXCH, M.FCHS, M.FABS, M.FSQRT, M.FRNDINT, M.FSIN, M.FCOS, M.FSINCOS, + M.FPTAN, M.FPATAN, M.FLD1, M.FLDZ, M.FLDPI, M.FLDL2T, M.FLDL2E, M.FLDLG2, M.FLDLN2, M.FILD, M.FIST, M.FISTP, M.FISTTP, M.FXTRACT, M.FSCALE, *FCMOV, M.FCOMI, M.FCOMIP, M.FUCOMI, M.FUCOMIP, M.FADD, M.FADDP, M.FSUB, M.FSUBP, M.FSUBR, M.FSUBRP, M.FMUL, M.FMULP, M.FDIV, M.FDIVP, M.FDIVR, M.FDIVRP, *IARITHMETIC, M.FNSTCW, M.WAIT, M.FLDCW, M.FCOM, M.FINCSTP, @@ -140,6 +145,7 @@ COMPARE_SW = "x87_sw = static_cast(r == 0 ? 0x0100 : r == 1 ? 0x4000 : r == 3 ? 0x4500 : 0);" # Status-word bits: C0, C2 and C3 (the comparison result), C1 (bit 0 of an FPREM quotient), and TOP. C_BITS = 0x4500 +C2_BIT = 0x0400 C1_BIT = 0x0200 TOP_BITS = 0x3800 # IE, DE, ZE, OE, UE, PE, SF and ES (bits 0 to 7) and the busy bit (bit 15): the bits that FNINIT clears and that @@ -157,6 +163,8 @@ STATUS = {"unmasked": 1, "precision": 2, "unrestored": 3, "partial": 4, "nanremainder": 5, "bcddigit": 6} # The checked entry's partial remainders. REMAINDERS = frozenset({M.FPREM, M.FPREM1}) +# Transcendental instructions that leave C2 known (1 when |ST(0)| >= 2^63, 0 otherwise) and C0, C1, C3 undefined. +TRIG_C2 = frozenset({M.FSIN, M.FCOS, M.FSINCOS, M.FPTAN}) # FNSTENV and FNSAVE store the 32-bit protected-mode environment (28 bytes: control word, status word, tag word, # instruction and data pointers); FNSAVE follows it with the eight registers (108 bytes) and then initializes. ENVIRONMENT = {M.FNSTENV: S.FPU_ENV28, M.FNSAVE: S.FPU_STATE108} @@ -166,7 +174,8 @@ def declaration(body, checked=None): """The x87 locals of a lowered function: the slots, the control word and, in a function that compares into the status word or stores it, the condition bits of the status word.""" text = DECLARATION if checked is None else CHECKED_DECLARATION - if any(i.mnemonic in STATUS_WRITERS or i.mnemonic in REMAINDERS or i.mnemonic in (M.FNSTSW, M.FNINIT, *ENVIRONMENT) for i in body): + if any(i.mnemonic in STATUS_WRITERS or i.mnemonic in REMAINDERS or i.mnemonic in TRIG_C2 + or i.mnemonic in (M.FNSTSW, M.FNINIT, *ENVIRONMENT) for i in body): text += " uint16_t x87_sw = 0; (void)x87_sw;" return text @@ -344,17 +353,21 @@ def _effect(i, depth, checked=None, paired=False): if depth < 2: raise ValueError(f"x87 stack underflow at {i.ip:#x}: {i}") return depth - if op == M.FXTRACT: + if op == M.FXTRACT or op in (M.FSINCOS, M.FPTAN): if depth == 0: raise ValueError(f"x87 stack underflow at {i.ip:#x}: {i}") if depth == 8: raise ValueError(f"x87 stack overflow at {i.ip:#x}: {i}") return depth + 1 + if op == M.FPATAN: + if depth < 2: + raise ValueError(f"x87 stack underflow at {i.ip:#x}: {i}") + return depth - 1 if op in CONSTANTS: if depth == 8: raise ValueError(f"x87 stack overflow at {i.ip:#x}: {i}") return depth + 1 - if op in (M.FCHS, M.FABS, M.FSQRT, M.FRNDINT): + if op in (M.FCHS, M.FABS, M.FSQRT, M.FRNDINT, M.FSIN, M.FCOS): if depth == 0: raise ValueError(f"x87 stack underflow at {i.ip:#x}: {i}") return depth @@ -592,6 +605,8 @@ def _after(i, s): c = STATUS_BITS elif op in REMAINDERS: # quotient bits and C2 = 0; the exception flags may be raised c = C_BITS | C1_BIT + elif op in TRIG_C2: # C2 is known; C0, C1, C3 and exception flags are undefined + c = C2_BIT elif op in COMPARES: # FCOMI leaves C0, C2 and C3, but may raise an exception flag c = s.c & ~EXCEPTION_BITS elif not (is_x87(i) or call): # integer instructions change none of it @@ -821,6 +836,18 @@ def _statement(i, depth, address, checked, parity, status_word=False): return f"x87_slot[{depth}] = X87Value{{{sig:#018x}ull, {se:#06x}}}; // {name}" if op in (M.FSQRT, M.FRNDINT): return f"x87_slot[{top}] = {'x87_sqrt' if op == M.FSQRT else 'x87_rndint'}(x87_slot[{top}], x87_cw);" + if op in (M.FSIN, M.FCOS): + fn, name = ("x87_sin", "fsin") if op == M.FSIN else ("x87_cos", "fcos") + return (f"{{ bool c2 = false; x87_slot[{top}] = {fn}(x87_slot[{top}], x87_cw, c2); " + f"x87_sw = static_cast(c2 ? 0x0400 : 0); }} // {name}") + if op == M.FSINCOS: + return (f"{{ bool c2 = false; X87Value c; x87_slot[{top}] = x87_sincos(x87_slot[{top}], c, x87_cw, c2); " + f"if (c2) x87_trap(); x87_slot[{depth}] = c; x87_sw = static_cast(c2 ? 0x0400 : 0); }} // fsincos") + if op == M.FPTAN: + return (f"{{ bool c2 = false; X87Value one; x87_slot[{top}] = x87_ptan(x87_slot[{top}], one, x87_cw, c2); " + f"if (c2) x87_trap(); x87_slot[{depth}] = one; x87_sw = static_cast(c2 ? 0x0400 : 0); }} // fptan") + if op == M.FPATAN: + return f"x87_slot[{top - 1}] = x87_patan(x87_slot[{top - 1}], x87_slot[{top}], x87_cw); // fpatan" if op in (M.FCHS, M.FABS): return f"x87_slot[{top}] = {'x87_chs' if op == M.FCHS else 'x87_abs'}(x87_slot[{top}]);" if op == M.FLD: diff --git a/tools/x87_soft.h b/tools/x87_soft.h index cf2ce9771..445c3a7a1 100644 --- a/tools/x87_soft.h +++ b/tools/x87_soft.h @@ -537,3 +537,435 @@ static inline int x87_prem(X87Value a, X87Value b, bool nearest, X87Value& out) out = {sig, static_cast(((a.se & 0x8000) ^ (flip ? 0x8000 : 0)) | biased)}; return static_cast(q & 7); } + +// 128-bit unsigned fixed-point helpers for the transcendental instructions (pure integer arithmetic). +struct X87U128 { uint64_t hi, lo; }; + +static inline int x87_u128_cmp(X87U128 a, X87U128 b) { + if (a.hi != b.hi) return a.hi < b.hi ? -1 : 1; + if (a.lo != b.lo) return a.lo < b.lo ? -1 : 1; + return 0; +} + +static inline X87U128 x87_u128_add(X87U128 a, X87U128 b) { + X87U128 r; + const unsigned char c = _addcarry_u64(0, a.lo, b.lo, &r.lo); + _addcarry_u64(c, a.hi, b.hi, &r.hi); + return r; +} + +static inline X87U128 x87_u128_sub(X87U128 a, X87U128 b) { + X87U128 r; + const unsigned char c = _subborrow_u64(0, a.lo, b.lo, &r.lo); + _subborrow_u64(c, a.hi, b.hi, &r.hi); + return r; +} + +// Upper 128 bits of the 256-bit product a * b. +static inline X87U128 x87_u128_mul_hi(X87U128 a, X87U128 b) { + uint64_t p0_hi; + _umul128(a.lo, b.lo, &p0_hi); + uint64_t p1_hi; + const uint64_t p1_lo = _umul128(a.hi, b.lo, &p1_hi); + uint64_t p2_hi; + const uint64_t p2_lo = _umul128(a.lo, b.hi, &p2_hi); + uint64_t p3_hi; + uint64_t p3_lo = _umul128(a.hi, b.hi, &p3_hi); + uint64_t s0 = p0_hi; + unsigned char c = _addcarry_u64(0, s0, p1_lo, &s0); + uint64_t c1 = c; + c = _addcarry_u64(0, s0, p2_lo, &s0); + c1 += c; + uint64_t s1 = p1_hi; + c = _addcarry_u64(0, s1, p2_hi, &s1); + uint64_t c2 = c; + c = _addcarry_u64(0, s1, c1, &s1); + c2 += c; + c = _addcarry_u64(0, p3_lo, s1, &p3_lo); + _addcarry_u64(c, p3_hi, c2, &p3_hi); + return {p3_hi, p3_lo}; +} + +static inline X87U128 x87_u128_div_u64(X87U128 a, uint64_t d) { + uint64_t rem = 0; + const uint64_t qhi = _udiv128(0, a.hi, d, &rem); + const uint64_t qlo = _udiv128(rem, a.lo, d, &rem); + return {qhi, qlo}; +} + +static inline X87U128 x87_u128_shr(X87U128 a, int n) { + if (n <= 0) return a; + if (n >= 128) return {0, 0}; + if (n >= 64) return {0, a.hi >> (n - 64)}; + return {a.hi >> n, (a.lo >> n) | (a.hi << (64 - n))}; +} + +static inline void x87_u128_norm(X87U128& v, int& e) { + if (v.hi == 0) { + if (v.lo == 0) return; + const int s = x87_clz(v.lo); + v.hi = v.lo << s; + v.lo = 0; + e -= 64 + s; + } else { + const int s = x87_clz(v.hi); + if (s != 0) { + v.hi = (v.hi << s) | (v.lo >> (64 - s)); + v.lo <<= s; + e -= s; + } + } +} + +// Normalized 128-bit quotient a / b for normalized nonzero operands, returning value = (q / 2^127) * 2^qe. +static inline X87U128 x87_u128_div_norm(X87U128 a, int ea, X87U128 b, int eb, int& qe) { + int e = ea - eb; + X87U128 rem = a; + if (x87_u128_cmp(rem, b) >= 0) { + rem = x87_u128_sub(rem, b); + } else { + --e; + const bool top = (rem.hi >> 63) != 0; + rem.hi = (rem.hi << 1) | (rem.lo >> 63); + rem.lo <<= 1; + if (top || x87_u128_cmp(rem, b) >= 0) rem = x87_u128_sub(rem, b); + } + uint64_t qhi = x87_integer_bit, qlo = 0; + for (int bit = 126; bit >= 0; --bit) { + const bool top = (rem.hi >> 63) != 0; + rem.hi = (rem.hi << 1) | (rem.lo >> 63); + rem.lo <<= 1; + if (top || x87_u128_cmp(rem, b) >= 0) { + rem = x87_u128_sub(rem, b); + if (bit >= 64) qhi |= 1ull << (bit - 64); + else qlo |= 1ull << bit; + } + } + qe = e; + return {qhi, qlo}; +} + +static inline X87Value x87_round_u128(bool sign, int e, X87U128 v, uint16_t cw, bool force_inexact = true) { + if (v.hi == 0 && v.lo == 0) return {0, static_cast(sign ? 0x8000 : 0)}; + x87_u128_norm(v, e); + const uint64_t lo = v.lo | (force_inexact ? 1ull : 0ull); + const X87Rounded r = x87_round(sign, e, v.hi, lo, x87_arith64, x87_rounding(cw)); + return {r.sig, static_cast((sign ? 0x8000 : 0) | r.biased)}; +} + +// 2/pi to 256 bits (value * 2^256) and pi/2 to 128 bits (value * 2^127). +static const uint64_t x87_inv_pi2[4] = { + 0xa2f9836e4e441529ull, 0xfc2757d1f534ddc0ull, 0xdb6295993c439041ull, 0xfe5163abdebbc562ull +}; +static const X87U128 x87_pi2{0xc90fdaa22168c234ull, 0xc4c6628b80dc1cd1ull}; + +// Payne-Hanek range reduction of finite |x| = sig * 2^(e - 63) with e < 63 modulo pi/2. +// Sets r_neg when |x| = k * (pi/2) - r, and normalizes r = (r_val / 2^127) * 2^re in [0, pi/4]. +static inline int x87_reduce_pi2(uint64_t sig, int e, X87U128& r_val, int& re, bool& r_neg) { + r_neg = false; + if (e <= -1 && (e < -1 || sig <= 0xc90fdaa22168c234ull)) { + r_val = {sig, 0}; + re = e; + return 0; + } + uint64_t p[5]{}; + for (int i = 0; i < 4; ++i) { + uint64_t hi; + const uint64_t lo = _umul128(sig, x87_inv_pi2[3 - i], &hi); + unsigned char c = _addcarry_u64(0, p[i], lo, &p[i]); + c = _addcarry_u64(c, p[i + 1], hi, &p[i + 1]); + for (int j = i + 2; c && j < 5; ++j) c = _addcarry_u64(c, p[j], 0, &p[j]); + } + const int s = 63 - e; + uint64_t k = 0; + uint64_t f[4]{}; + if (s == 64) { + f[3] = p[4]; f[2] = p[3]; f[1] = p[2]; f[0] = p[1]; + } else { + const int sh = 64 - s; + k = p[4] >> s; + f[3] = (p[4] << sh) | (p[3] >> s); + f[2] = (p[3] << sh) | (p[2] >> s); + f[1] = (p[2] << sh) | (p[1] >> s); + f[0] = (p[1] << sh) | (p[0] >> s); + } + if (f[3] & x87_integer_bit) { + ++k; + r_neg = true; + unsigned char b = _subborrow_u64(0, 0, f[0], &f[0]); + b = _subborrow_u64(b, 0, f[1], &f[1]); + b = _subborrow_u64(b, 0, f[2], &f[2]); + _subborrow_u64(b, 0, f[3], &f[3]); + } + int top_limb = 3; + while (top_limb >= 0 && f[top_limb] == 0) --top_limb; + if (top_limb < 0) { r_val = {0, 0}; re = 0; return static_cast(k & 3); } + const int lz = x87_clz(f[top_limb]); + const int fe = -1 - (3 - top_limb) * 64 - lz; + uint64_t fhi = f[top_limb] << lz; + uint64_t flo = top_limb >= 1 ? f[top_limb - 1] : 0; + if (lz != 0 && top_limb >= 1) fhi |= f[top_limb - 1] >> (64 - lz); + if (lz != 0) { + flo <<= lz; + if (top_limb >= 2) flo |= f[top_limb - 2] >> (64 - lz); + } + r_val = x87_u128_mul_hi({fhi, flo}, x87_pi2); + re = fe + 1; + x87_u128_norm(r_val, re); + return static_cast(k & 3); +} + +// sin(r) and cos(r) for normalized r in [0, pi/4]. +static inline void x87_sincos_reduced(X87U128 r_val, int re, X87U128& sin_v, int& sin_e, X87U128& cos_v, int& cos_e) { + if (r_val.hi == 0 && r_val.lo == 0) { + sin_v = {0, 0}; sin_e = 0; + cos_v = {x87_integer_bit, 0}; cos_e = 0; + return; + } + if (re <= -65) { + sin_v = r_val; sin_e = re; + cos_v = {0xffffffffffffffffull, 0xffffffffffffffffull}; cos_e = -1; + return; + } + X87U128 r2 = x87_u128_mul_hi(r_val, r_val); + r2 = x87_u128_shr(r2, -2 * re - 2); + const X87U128 one_q126{1ull << 62, 0}; + X87U128 s_sum = one_q126, s_term = one_q126; + X87U128 c_sum = one_q126, c_term = one_q126; + for (uint64_t n = 1; n <= 19; ++n) { + s_term = x87_u128_div_u64(x87_u128_mul_hi(s_term, r2), (2 * n) * (2 * n + 1)); + c_term = x87_u128_div_u64(x87_u128_mul_hi(c_term, r2), (2 * n - 1) * (2 * n)); + if (n & 1) { + s_sum = x87_u128_sub(s_sum, s_term); + c_sum = x87_u128_sub(c_sum, c_term); + } else { + s_sum = x87_u128_add(s_sum, s_term); + c_sum = x87_u128_add(c_sum, c_term); + } + if ((s_term.hi | s_term.lo | c_term.hi | c_term.lo) == 0) break; + } + sin_v = x87_u128_mul_hi(r_val, s_sum); + sin_e = re + 2; + x87_u128_norm(sin_v, sin_e); + cos_v = c_sum; + cos_e = 1; + x87_u128_norm(cos_v, cos_e); +} + +// Trap when an instruction hits a case outside the static-depth profile (such as |ST(0)| >= 2^63 on FSINCOS/FPTAN). +static inline void x87_trap() { +#if defined(_MSC_VER) && !defined(__clang__) + __ud2(); +#else + __builtin_trap(); +#endif +} + +// FSIN, FCOS and FSINCOS: 64-bit extended precision (precision control does not apply), C2 set when |ST(0)| >= 2^63. +static inline void x87_sincos_core(X87Value a, uint16_t cw, bool& c2, X87Value* sin_out, X87Value* cos_out) { + c2 = false; + if (x87_unsupported(a) || x87_is_inf(a)) { + if (sin_out) *sin_out = x87_indefinite; + if (cos_out) *cos_out = x87_indefinite; + return; + } + if (x87_is_nan(a)) { + const X87Value q = x87_quiet(a); + if (sin_out) *sin_out = q; + if (cos_out) *cos_out = q; + return; + } + if (x87_is_zero(a)) { + if (sin_out) *sin_out = a; // trig zero + if (cos_out) *cos_out = {x87_integer_bit, 0x3fff}; + return; + } + const X87Unpacked u = x87_unpack(a); + if (u.e >= 63) { // trig range + c2 = true; + if (sin_out) *sin_out = a; + if (cos_out) *cos_out = sin_out ? x87_indefinite : a; + return; + } + if (u.e <= -65) { + if (sin_out) *sin_out = x87_round_u128(u.sign, u.e, {u.sig, 0}, cw, false); + if (cos_out) *cos_out = x87_round_u128(false, -1, {~0ull, ~0ull}, cw); + return; + } + X87U128 r_val, sv, cv; + int re, se, ce; + bool r_neg; + const int q = x87_reduce_pi2(u.sig, u.e, r_val, re, r_neg); + x87_sincos_reduced(r_val, re, sv, se, cv, ce); + if (sin_out) { + const bool neg = u.sign ^ (q >= 2) ^ ((q & 1) == 0 && r_neg); + *sin_out = (q & 1) ? x87_round_u128(neg, ce, cv, cw) : x87_round_u128(neg, se, sv, cw); + } + if (cos_out) { + const int qc = (q + 1) & 3; + const bool neg = (qc >= 2) ^ ((qc & 1) == 0 && r_neg); + *cos_out = (qc & 1) ? x87_round_u128(neg, ce, cv, cw) : x87_round_u128(neg, se, sv, cw); + } +} + +static inline X87Value x87_sin(X87Value a, uint16_t cw, bool& c2) { + X87Value s{}; + x87_sincos_core(a, cw, c2, &s, nullptr); + return s; +} + +static inline X87Value x87_cos(X87Value a, uint16_t cw, bool& c2) { + X87Value c{}; + x87_sincos_core(a, cw, c2, nullptr, &c); + return c; +} + +static inline X87Value x87_sincos(X87Value a, X87Value& cos_out, uint16_t cw, bool& c2) { + X87Value s{}; + x87_sincos_core(a, cw, c2, &s, &cos_out); + return s; +} + +// FPTAN: replaces ST(0) by tan(ST(0)) and pushes 1.0 (or quiet NaN / indefinite on NaN/Inf/unsupported). +static inline X87Value x87_ptan(X87Value a, X87Value& one_out, uint16_t cw, bool& c2) { + c2 = false; + if (x87_unsupported(a) || x87_is_inf(a)) { one_out = x87_indefinite; return x87_indefinite; } + if (x87_is_nan(a)) { one_out = x87_quiet(a); return one_out; } + one_out = {x87_integer_bit, 0x3fff}; // ptan one + if (x87_is_zero(a)) return a; + const X87Unpacked u = x87_unpack(a); + if (u.e >= 63) { c2 = true; one_out = x87_indefinite; return a; } // trig range + if (u.e <= -65) return x87_round_u128(u.sign, u.e, {u.sig, 0}, cw, false); + X87U128 r_val, sv, cv; + int re, se, ce; + bool r_neg; + const int q = x87_reduce_pi2(u.sig, u.e, r_val, re, r_neg); + x87_sincos_reduced(r_val, re, sv, se, cv, ce); + const bool neg = u.sign ^ ((q & 1) != 0) ^ r_neg; + int te; + const X87U128 tv = (q & 1) ? x87_u128_div_norm(cv, ce, sv, se, te) + : x87_u128_div_norm(sv, se, cv, ce, te); + return x87_round_u128(neg, te, tv, cw); +} + +// tan(k * pi / 16) in Q0.128 for k = 1, 2, 3, and Q0.64 midpoint thresholds for atan reduction. +static const X87U128 x87_tan_k[3] = { + {0x32ebebc0aa62b00full, 0x7ae9b3a20ca321fbull}, + {0x6a09e667f3bcc908ull, 0xb2fb1366ea957d3eull}, + {0xab0dc155bfcc82f5ull, 0x18a42e56cea7698cull}, +}; +static const uint64_t x87_atan_thresh[4] = { + 0x1936bb8c5b2da262ull, 0x4da820d5718f6f14ull, 0x88d5b8c841a75c35ull, 0xd218015721427e59ull +}; + +static inline void x87_atan_unit(X87U128 t_val, int te, X87U128& res, int& re) { + if (te <= -65) { res = t_val; re = te; return; } + const uint64_t t_q64 = te == 0 ? ~0ull : (te >= -64 ? (t_val.hi >> (-te - 1)) : 0); + int k = 0; + while (k < 4 && t_q64 > x87_atan_thresh[k]) ++k; + X87U128 u_val; + int ue; + bool u_neg = false; + if (k == 0) { + u_val = t_val; + ue = te; + } else if (k == 4) { + const X87U128 one_q126{1ull << 62, 0}; + const X87U128 t_q126 = x87_u128_shr(t_val, 1 - te); + X87U128 num = x87_u128_sub(one_q126, t_q126); + X87U128 den = x87_u128_add(one_q126, t_q126); + if (num.hi == 0 && num.lo == 0) { res = x87_pi2; re = -1; return; } + int ne = 1, de = 1; + x87_u128_norm(num, ne); + x87_u128_norm(den, de); + u_val = x87_u128_div_norm(num, ne, den, de, ue); + u_neg = true; + } else { + const X87U128 t_q128 = x87_u128_shr(t_val, -1 - te); + const X87U128 c_q128 = x87_tan_k[k - 1]; + X87U128 num; + if (x87_u128_cmp(t_q128, c_q128) >= 0) { + num = x87_u128_sub(t_q128, c_q128); + u_neg = false; + } else { + num = x87_u128_sub(c_q128, t_q128); + u_neg = true; + } + if (num.hi == 0 && num.lo == 0) { + res = x87_pi2; + re = (k == 1) ? -3 : (k == 2) ? -2 : -1; + if (k == 3) { + res = x87_u128_add(x87_u128_shr(x87_pi2, 1), x87_u128_shr(x87_pi2, 2)); + re = -1; + x87_u128_norm(res, re); + } + return; + } + const X87U128 tc_q128 = x87_u128_mul_hi(t_q128, c_q128); + X87U128 den = x87_u128_add({1ull << 62, 0}, x87_u128_shr(tc_q128, 2)); + int ne = -1, de = 1; + x87_u128_norm(num, ne); + x87_u128_norm(den, de); + u_val = x87_u128_div_norm(num, ne, den, de, ue); + } + X87U128 u_atan; + int ua_e; + if (ue <= -65) { + u_atan = u_val; ua_e = ue; + } else { + X87U128 u2 = x87_u128_mul_hi(u_val, u_val); + u2 = x87_u128_shr(u2, -2 * ue - 2); + const X87U128 one_q126{1ull << 62, 0}; + X87U128 sum = one_q126, pow = one_q126; + for (uint64_t n = 1; n <= 19; ++n) { + pow = x87_u128_mul_hi(pow, u2); + const X87U128 term = x87_u128_div_u64(pow, 2 * n + 1); + if (n & 1) sum = x87_u128_sub(sum, term); + else sum = x87_u128_add(sum, term); + if ((term.hi | term.lo) == 0) break; + } + u_atan = x87_u128_mul_hi(u_val, sum); + ua_e = ue + 2; + x87_u128_norm(u_atan, ua_e); + } + if (k == 0) { res = u_atan; re = ua_e; return; } + const X87U128 pi16 = x87_u128_shr(x87_pi2, 2); + X87U128 base{0, 0}; + for (int i = 0; i < k; ++i) base = x87_u128_add(base, pi16); + const X87U128 u_q128 = x87_u128_shr(u_atan, -1 - ua_e); + res = u_neg ? x87_u128_sub(base, u_q128) : x87_u128_add(base, u_q128); + re = -1; + x87_u128_norm(res, re); +} + +// FPATAN: atan2(y, x) = atan2(ST(1), ST(0)) rounded to 64 significand bits (precision control does not apply). +static inline X87Value x87_patan(X87Value y, X87Value x, uint16_t cw) { + X87Value out; + if (x87_special_operands(y, x, &out)) return out; + const bool sy = x87_sign(y), sx = x87_sign(x); + if (x87_is_zero(y)) return sx ? x87_round_u128(sy, 1, x87_pi2, cw) : X87Value{0, static_cast(sy ? 0x8000 : 0)}; + if (x87_is_inf(y)) { + if (x87_is_inf(x)) { + if (!sx) return x87_round_u128(sy, -1, x87_pi2, cw); + const X87U128 three = x87_u128_add(x87_u128_shr(x87_pi2, 1), x87_u128_shr(x87_pi2, 2)); + return x87_round_u128(sy, 1, three, cw); + } + return x87_round_u128(sy, 0, x87_pi2, cw); + } + if (x87_is_inf(x)) return sx ? x87_round_u128(sy, 1, x87_pi2, cw) : X87Value{0, static_cast(sy ? 0x8000 : 0)}; + if (x87_is_zero(x)) return x87_round_u128(sy, 0, x87_pi2, cw); + const X87Unpacked uy = x87_unpack(y), ux = x87_unpack(x); + const bool swapped = uy.e > ux.e || (uy.e == ux.e && uy.sig > ux.sig); + const X87Unpacked num = swapped ? ux : uy, den = swapped ? uy : ux; + int te; + const X87U128 t_val = x87_u128_div_norm({num.sig, 0}, num.e, {den.sig, 0}, den.e, te); + X87U128 av; + int ae; + x87_atan_unit(t_val, te, av, ae); + if (!swapped && !sx) return x87_round_u128(sy, ae, av, cw); + const X87U128 base = swapped ? x87_u128_shr(x87_pi2, 1) : x87_pi2; + const X87U128 av_q126 = x87_u128_shr(av, 1 - ae); + const bool sub = !swapped || !sx; + const X87U128 res = sub ? x87_u128_sub(base, av_q126) : x87_u128_add(base, av_q126); + return x87_round_u128(sy, 1, res, cw); +} From d2cc0a798f692c679888721d17074393668723de Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 20:39:28 +0200 Subject: [PATCH 084/232] cpu: lower SGDT, SIDT, SLDT, SMSW, and STR under opt-in host-CPU profile (#2064) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 22 ++ tests/cpu/sysdesc.asm | 215 ++++++++++++ tests/cpu/sysdesc.def | 23 ++ tests/cpu/sysdesc_check.py | 689 +++++++++++++++++++++++++++++++++++++ tools/cpu_sysdesc_aot.py | 608 ++++++++++++++++++++++++++++++++ 5 files changed, 1557 insertions(+) create mode 100644 tests/cpu/sysdesc.asm create mode 100644 tests/cpu/sysdesc.def create mode 100644 tests/cpu/sysdesc_check.py create mode 100644 tools/cpu_sysdesc_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 72de7287e..ce30b48bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4961,6 +4961,28 @@ if(EXISTS "${INTAKE_PYTHON}") "$") set_tests_properties(cpu_aot_sse4a PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sse4a.txt") + set(cpu_sysdesc_exports + "op_sgdt,op_sgdt_disp,op_sidt,op_sidt_disp," + "op_sldt_r16,op_sldt_r32,op_sldt_r64,op_sldt_m16,op_sldt_m16_disp," + "op_str_r16,op_str_r32,op_str_r64,op_str_m16,op_str_m16_disp," + "op_smsw_r16,op_smsw_r32,op_smsw_r64,op_smsw_m16,op_smsw_m16_disp," + "op_sysdesc_flags_preserve,op_sysdesc_discarded_stores,op_sysdesc_unused_reg") + string(CONCAT cpu_sysdesc_exports ${cpu_sysdesc_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sysdesc_${variant} sysdesc) + cpu_translation(cpu_sysdesc_${variant} cpu_sysdesc_aot "${cpu_sysdesc_exports}" HOST_CPU) + endforeach() + target_compile_definitions(cpu_sysdesc_altered PRIVATE ALTER_IMM) + add_test(NAME cpu_aot_sysdesc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sysdesc_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_sysdesc PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sysdesc.txt") set(cpu_sse2_exports "op_cmppd_0,op_cmppd_1,op_cmppd_2,op_cmppd_3,op_cmppd_4,op_cmppd_5,op_cmppd_6,op_cmppd_7," "op_cmppd_mem," diff --git a/tests/cpu/sysdesc.asm b/tests/cpu/sysdesc.asm new file mode 100644 index 000000000..5e97b4310 --- /dev/null +++ b/tests/cpu/sysdesc.asm @@ -0,0 +1,215 @@ +; coverage: source cpu_aot_sysdesc +; Source-built MASM fixture for opt-in --host-cpu system-descriptor and machine-status +; store instructions: SGDT, SIDT, SLDT, SMSW, and STR (Windows x64 leaf ABI: +; RCX, RDX, R8 -> RAX). +.code + +; --- SGDT / SIDT (10-byte m16&64 descriptor stores) --- +; ALTER_IMM swaps SGDT <-> SIDT so mutant divergence is directly observed. +op_sgdt PROC FRAME + .endprolog +IFDEF ALTER_IMM + sidt FWORD PTR [r8] +ELSE + sgdt FWORD PTR [r8] +ENDIF + mov rax, rdx + ret +op_sgdt ENDP + +op_sgdt_disp PROC FRAME + .endprolog + sgdt FWORD PTR [r8+16] + mov rax, rdx + ret +op_sgdt_disp ENDP + +op_sidt PROC FRAME + .endprolog +IFDEF ALTER_IMM + sgdt FWORD PTR [r8] +ELSE + sidt FWORD PTR [r8] +ENDIF + mov rax, rdx + ret +op_sidt ENDP + +op_sidt_disp PROC FRAME + .endprolog + sidt FWORD PTR [r8+16] + mov rax, rdx + ret +op_sidt_disp ENDP + +; --- SLDT (r16, r32, r64, m16) --- +op_sldt_r16 PROC FRAME + .endprolog + mov rax, rdx +IFDEF ALTER_IMM + str ax +ELSE + sldt ax +ENDIF + ret +op_sldt_r16 ENDP + +op_sldt_r32 PROC FRAME + .endprolog + mov rax, rdx + sldt eax + ret +op_sldt_r32 ENDP + +op_sldt_r64 PROC FRAME + .endprolog + mov rax, rdx + sldt rax + ret +op_sldt_r64 ENDP + +op_sldt_m16 PROC FRAME + .endprolog +IFDEF ALTER_IMM + str WORD PTR [r8] +ELSE + sldt WORD PTR [r8] +ENDIF + mov rax, rdx + ret +op_sldt_m16 ENDP + +op_sldt_m16_disp PROC FRAME + .endprolog + sldt WORD PTR [r8+4] + mov rax, rdx + ret +op_sldt_m16_disp ENDP + +; --- STR (r16, r32, r64, m16) --- +op_str_r16 PROC FRAME + .endprolog + mov rax, rdx +IFDEF ALTER_IMM + sldt ax +ELSE + str ax +ENDIF + ret +op_str_r16 ENDP + +op_str_r32 PROC FRAME + .endprolog + mov rax, rdx + str eax + ret +op_str_r32 ENDP + +op_str_r64 PROC FRAME + .endprolog + mov rax, rdx + str rax + ret +op_str_r64 ENDP + +op_str_m16 PROC FRAME + .endprolog + str WORD PTR [r8] + mov rax, rdx + ret +op_str_m16 ENDP + +op_str_m16_disp PROC FRAME + .endprolog + str WORD PTR [r8+6] + mov rax, rdx + ret +op_str_m16_disp ENDP + +; --- SMSW (r16, r32, r64, m16) --- +op_smsw_r16 PROC FRAME + .endprolog + mov rax, rdx +IFDEF ALTER_IMM + str ax +ELSE + smsw ax +ENDIF + ret +op_smsw_r16 ENDP + +op_smsw_r32 PROC FRAME + .endprolog + mov rax, rdx + smsw eax + ret +op_smsw_r32 ENDP + +op_smsw_r64 PROC FRAME + .endprolog + mov rax, rdx + smsw rax + ret +op_smsw_r64 ENDP + +op_smsw_m16 PROC FRAME + .endprolog + smsw WORD PTR [r8] + mov rax, rdx + ret +op_smsw_m16 ENDP + +op_smsw_m16_disp PROC FRAME + .endprolog + smsw WORD PTR [r8+8] + mov rax, rdx + ret +op_smsw_m16_disp ENDP + +; --- Flag preservation across all 5 sysdesc instructions --- +op_sysdesc_flags_preserve PROC FRAME + .endprolog + mov r9d, 080000001h + add r9d, 080000002h ; r9d = 3 -> CF=1, OF=1, SF=0, ZF=0, PF=1 + mov r10, rdx + sgdt FWORD PTR [r8+16] + sidt FWORD PTR [r8+32] + sldt r10w + str r10w + smsw r11d + sete BYTE PTR [r8] +IFDEF ALTER_IMM + setae BYTE PTR [r8+1] +ELSE + setb BYTE PTR [r8+1] +ENDIF + sets BYTE PTR [r8+2] + seto BYTE PTR [r8+3] + setp BYTE PTR [r8+4] + mov rax, r11 + ret +op_sysdesc_flags_preserve ENDP + +; --- Volatile store ordering under /O2 (NULL r8 must fault) --- +op_sysdesc_discarded_stores PROC FRAME + .endprolog + sgdt FWORD PTR [r8] + sidt FWORD PTR [r8+16] + sldt WORD PTR [r8+32] + str WORD PTR [r8+34] + smsw WORD PTR [r8+36] + mov rax, rdx + ret +op_sysdesc_discarded_stores ENDP + +; --- Unused register writes compile cleanly under /O2 /W4 /WX --- +op_sysdesc_unused_reg PROC FRAME + .endprolog + sldt r9d + str r10d + smsw r11d + mov rax, rdx + ret +op_sysdesc_unused_reg ENDP + +END diff --git a/tests/cpu/sysdesc.def b/tests/cpu/sysdesc.def new file mode 100644 index 000000000..8a23306db --- /dev/null +++ b/tests/cpu/sysdesc.def @@ -0,0 +1,23 @@ +EXPORTS + op_sgdt + op_sgdt_disp + op_sidt + op_sidt_disp + op_sldt_r16 + op_sldt_r32 + op_sldt_r64 + op_sldt_m16 + op_sldt_m16_disp + op_str_r16 + op_str_r32 + op_str_r64 + op_str_m16 + op_str_m16_disp + op_smsw_r16 + op_smsw_r32 + op_smsw_r64 + op_smsw_m16 + op_smsw_m16_disp + op_sysdesc_flags_preserve + op_sysdesc_discarded_stores + op_sysdesc_unused_reg diff --git a/tests/cpu/sysdesc_check.py b/tests/cpu/sysdesc_check.py new file mode 100644 index 000000000..a5304e5a7 --- /dev/null +++ b/tests/cpu/sysdesc_check.py @@ -0,0 +1,689 @@ +"""Differential, /O2, mutant, UMIP-aware, and rejection tests for cpu_sysdesc_aot.""" + +import ctypes +import os +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_sysdesc_aot import lift_code, translate # noqa: E402 + + +TRANSLATED_EXPORTS = ( + "op_sgdt", + "op_sgdt_disp", + "op_sidt", + "op_sidt_disp", + "op_sldt_r16", + "op_sldt_r32", + "op_sldt_r64", + "op_sldt_m16", + "op_sldt_m16_disp", + "op_str_r16", + "op_str_r32", + "op_str_r64", + "op_str_m16", + "op_str_m16_disp", + "op_smsw_r16", + "op_smsw_r32", + "op_smsw_r64", + "op_smsw_m16", + "op_smsw_m16_disp", + "op_sysdesc_flags_preserve", + "op_sysdesc_discarded_stores", + "op_sysdesc_unused_reg", +) + +SENTINELS = ( + 0x1122334455667788, + 0xA5A5A5A5DEADBEEF, + 0x00000000FFFFFFFF, + 0xFFFFFFFF00000000, +) + +EXPECTED_SLDT = 0x0000 +EXPECTED_STR = 0x0040 +EXPECTED_SMSW32 = 0x80050033 +EXPECTED_LIFTED_GDT_LIMIT = 0x007F +EXPECTED_LIFTED_GDT_BASE = 0xFFFFF80000000000 + + +def bind_lib(path, prefix=""): + lib = ctypes.CDLL(str(Path(path).resolve())) + fns = {} + for name in TRANSLATED_EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p] + fn.restype = ctypes.c_uint64 + fns[name] = fn + if prefix: + umip = lib.host_has_umip + umip.argtypes = [] + umip.restype = ctypes.c_uint32 + fns["host_has_umip"] = umip + return lib, fns + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def logical_cpus(): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetCurrentProcess.restype = ctypes.c_void_p + kernel32.GetCurrentThread.restype = ctypes.c_void_p + kernel32.GetProcessAffinityMask.argtypes = [ + ctypes.c_void_p, + ctypes.POINTER(ctypes.c_size_t), + ctypes.POINTER(ctypes.c_size_t), + ] + kernel32.SetThreadAffinityMask.argtypes = [ctypes.c_void_p, ctypes.c_size_t] + kernel32.SetThreadAffinityMask.restype = ctypes.c_size_t + kernel32.GetCurrentProcessorNumber.restype = ctypes.c_uint32 + process, system = ctypes.c_size_t(), ctypes.c_size_t() + if not kernel32.GetProcessAffinityMask( + kernel32.GetCurrentProcess(), ctypes.byref(process), ctypes.byref(system) + ): + raise OSError(ctypes.get_last_error(), "GetProcessAffinityMask") + cpus = [k for k in range(process.value.bit_length()) if (process.value >> k) & 1] + return kernel32, process.value, cpus + + +def pin_to_cpu(kernel32, cpu): + prev = kernel32.SetThreadAffinityMask(kernel32.GetCurrentThread(), 1 << cpu) + if not prev: + raise OSError(ctypes.get_last_error(), "SetThreadAffinityMask") + for _ in range(200): + running = kernel32.GetCurrentProcessorNumber() + if running == cpu: + return prev + kernel32.Sleep(1) + raise AssertionError(f"pinned to logical processor {cpu}, still running on {running}") + + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret_ins = Instruction.create(Code.RETNQ) + ret_bytes = encode_seq(ret_ins) + ld_rax = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RDX) + + # 1. Default profile (host_cpu=False) MUST reject all 5 sysdesc instructions. + for export_name in ("op_sgdt", "op_sidt", "op_sldt_r32", "op_str_r32", "op_smsw_r32"): + try: + translate(original_path, [export_name]) + except ValueError as exc: + if "requires --host-cpu" not in str(exc): + raise AssertionError(f"default profile {export_name}: unexpected error {exc!r}") from exc + else: + raise AssertionError(f"default profile unexpectedly accepted {export_name}") + + default_unit_cases = [ + ("default_sgdt", encode_seq(Instruction.create_mem(Code.SGDT_M1664, MemoryOperand(R.R8)), ld_rax, ret_ins)), + ("default_sidt", encode_seq(Instruction.create_mem(Code.SIDT_M1664, MemoryOperand(R.R8)), ld_rax, ret_ins)), + ("default_sldt", encode_seq(Instruction.create_reg(Code.SLDT_R32M16, R.EAX), ret_ins)), + ("default_str", encode_seq(Instruction.create_reg(Code.STR_R32M16, R.EAX), ret_ins)), + ("default_smsw", encode_seq(Instruction.create_reg(Code.SMSW_R32M16, R.EAX), ret_ins)), + ] + for label, raw in default_unit_cases: + try: + lift_code(label, 0x1000, raw, host_cpu=False) + except ValueError as exc: + if "requires --host-cpu" not in str(exc): + raise AssertionError(f"{label}: expected 'requires --host-cpu', got {exc!r}") from exc + else: + raise AssertionError(f"{label}: default profile unexpectedly accepted sysdesc instruction") + + # 2. Raw encodings checked via Decoder+Formatter before lift_code(..., host_cpu=True). + formatter = Formatter(FormatterSyntax.INTEL) + raw_checks = [ + ("vex_vpaddw", bytes.fromhex("c5f1fdc2") + ret_bytes, "vpaddw xmm0,xmm1,xmm2", "unsupported VEX instruction"), + ("xop_vpcmov", bytes.fromhex("8fe878a2c230") + ret_bytes, "vpcmov xmm0,xmm0,xmm2,xmm3", "unsupported XOP instruction"), + ("seg_gs_sgdt", bytes.fromhex("65410f0100") + ret_bytes, "sgdt gs:[r8]", "unsupported instruction prefix"), + ("lock_add_mem", bytes.fromhex("f00101") + ret_bytes, "lock add [rcx],eax", "unsupported instruction prefix"), + ("rep_movsb", bytes.fromhex("f3a4") + ret_bytes, "rep movsb [rdi],[rsi]", "unsupported instruction prefix"), + ("repne_sldt", bytes.fromhex("f20f00c0") + ret_bytes, "sldt eax", "unsupported instruction prefix"), + ] + for label, raw, expected_asm, expected_reason in raw_checks: + decoded = formatter.format(next(iter(Decoder(64, raw, ip=0x1000)))) + if decoded != expected_asm: + raise AssertionError(f"{label}: decoded {decoded!r}, expected {expected_asm!r}") + try: + lift_code(label, 0x1000, raw, host_cpu=True) + except ValueError as exc: + if expected_reason not in str(exc): + raise AssertionError(f"{label}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: unexpectedly accepted excluded encoding") + + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDQ_XMM_K1Z_XMM_XMMM128B64, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + # 3. IR-level rejections under host_cpu=True. + unit_cases = [ + ("evex_vpaddq", encode_seq(evex_ins, ret_ins), "unsupported EVEX instruction"), + ("priv_lgdt", encode_seq(Instruction.create_mem(Code.LGDT_M1664, MemoryOperand(R.R8)), ld_rax, ret_ins), + "unsupported instruction"), + ("priv_lidt", encode_seq(Instruction.create_mem(Code.LIDT_M1664, MemoryOperand(R.R8)), ld_rax, ret_ins), + "unsupported instruction"), + ("priv_lldt", encode_seq(Instruction.create_reg(Code.LLDT_RM16, R.CX), ld_rax, ret_ins), + "unsupported instruction"), + ("priv_lmsw", encode_seq(Instruction.create_reg(Code.LMSW_RM16, R.CX), ld_rax, ret_ins), + "unsupported instruction"), + ("priv_ltr", encode_seq(Instruction.create_reg(Code.LTR_RM16, R.CX), ld_rax, ret_ins), + "unsupported instruction"), + ("rip_rel_sgdt", encode_seq(Instruction.create_mem( + Code.SGDT_M1664, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ld_rax, ret_ins), + "RIP-relative memory operand"), + ("bad_base_rax", encode_seq(ld_rax, Instruction.create_mem( + Code.SIDT_M1664, MemoryOperand(R.RAX)), ret_ins), + "bad base register"), + ("bad_base_rsp", encode_seq(ld_rax, Instruction.create_mem( + Code.SLDT_RM16, MemoryOperand(R.RSP)), ret_ins), + "bad base register"), + ("sib_index_sgdt", encode_seq(Instruction.create_mem( + Code.SGDT_M1664, MemoryOperand(R.R8, R.RCX, 2)), ld_rax, ret_ins), + "SIB index memory operand"), + ("sib_index_smsw", encode_seq(Instruction.create_mem( + Code.SMSW_RM16, MemoryOperand(R.R8, R.RDX, 1)), ld_rax, ret_ins), + "SIB index memory operand"), + ("nonvolatile_sldt_rbx", encode_seq(ld_rax, Instruction.create_reg(Code.SLDT_R64M16, R.RBX), ret_ins), + "nonvolatile GPR"), + ("nonvolatile_str_r12", encode_seq(ld_rax, Instruction.create_reg(Code.STR_R64M16, R.R12), ret_ins), + "nonvolatile GPR"), + ("nonvolatile_smsw_rbp", encode_seq(ld_rax, Instruction.create_reg(Code.SMSW_R32M16, R.EBP), ret_ins), + "nonvolatile GPR"), + ("high_byte_ah", encode_seq(ld_rax, Instruction.create_reg_i32(Code.MOV_R8_IMM8, R.AH, 1), ret_ins), + "unsupported high-byte GPR"), + ("nonleaf_jmp", encode_seq(ld_rax, Instruction.create_branch(Code.JMP_REL8_64, 0x1008), ret_ins), + "non-leaf branch or call"), + ("nonleaf_call", encode_seq(ld_rax, Instruction.create_branch(Code.CALL_REL32_64, 0x1020), ret_ins), + "non-leaf branch or call"), + ("nonleaf_je", encode_seq(ld_rax, Instruction.create_branch(Code.JE_REL8_64, 0x1008), ret_ins), + "non-leaf branch or call"), + ("undef_sldt_r16", encode_seq(Instruction.create_reg(Code.SLDT_RM16, R.AX), ret_ins), + "undefined GPR"), + ("undef_ret_rax", encode_seq(Instruction.create_mem(Code.SGDT_M1664, MemoryOperand(R.R8)), ret_ins), + "return with undefined RAX"), + ("undef_flags_sete", encode_seq(ld_rax, Instruction.create_mem(Code.SGDT_M1664, MemoryOperand(R.R8)), + Instruction.create_reg(Code.SETE_RM8, R.AL), ret_ins), + "undefined flags"), + ("xor_mem_dst", encode_seq(ld_rax, Instruction.create_mem_reg( + Code.XOR_RM32_R32, MemoryOperand(R.R8), R.EAX), ret_ins), + "unsupported xor destination"), + ("add_mem_dst", encode_seq(ld_rax, Instruction.create_mem_reg( + Code.ADD_RM32_R32, MemoryOperand(R.R8), R.EAX), ret_ins), + "unsupported add destination"), + ("clobbered_r8_ptr", encode_seq( + ld_rax, + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.R8, R.RDX), + Instruction.create_mem(Code.SGDT_M1664, MemoryOperand(R.R8)), + ret_ins), + "clobbered pointer"), + ("missing_ret", encode_seq(ld_rax), "missing terminal ret"), + ("after_ret", encode_seq(ld_rax, ret_ins, ld_rax), "unreachable instruction after ret"), + ] + for label, raw, expected_reason in unit_cases: + try: + lift_code(label, 0x1000, raw, host_cpu=True) + except ValueError as exc: + if expected_reason not in str(exc): + raise AssertionError(f"{label}: expected {expected_reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: unexpectedly accepted invalid sequence") + + # 4. PE-patched rejections + CLI rejections without --host-cpu and with bad inputs. + pe_bytes = original_path.read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_sysdesc_discarded_stores") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next( + i for i in range(0, len(records), 12) + if struct.unpack_from(" max_len: + raise AssertionError(f"{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off : file_off + len(patch)] = patch + struct.pack_into("> 47) != 0x1FFFF or (base & 7) != 0: + raise AssertionError( + f"{label} native SGDT architectural invariant failed: limit={limit:#06x} base={base:#018x}" + ) + + +def verify_suite(native_fns, target_fns, label, cpus): + kernel32, full_mask, _ = logical_cpus() + saved_affinity = None + buf_n = (ctypes.c_uint8 * 64)() + buf_t = (ctypes.c_uint8 * 64)() + cases = 0 + try: + for cpu in cpus: + prev = pin_to_cpu(kernel32, cpu) + if saved_affinity is None: + saved_affinity = prev + + # 1. SIDT (0 and +16 displacement): exact 10-byte match against pinned native + guard preservation. + for name, offset in (("op_sidt", 0), ("op_sidt_disp", 16)): + ctypes.memset(buf_n, 0xCC, 64) + ctypes.memset(buf_t, 0xCC, 64) + ret_n = native_fns[name](0, SENTINELS[0], ctypes.addressof(buf_n)) + ret_t = target_fns[name](0, SENTINELS[0], ctypes.addressof(buf_t)) + raw_n, raw_t = bytes(buf_n), bytes(buf_t) + if ret_n != SENTINELS[0] or ret_t != SENTINELS[0] or raw_n != raw_t: + raise AssertionError( + f"{label} {name} cpu {cpu}: mismatch native={raw_n[offset:offset+16].hex()} " + f"!= target={raw_t[offset:offset+16].hex()}" + ) + if raw_t[:offset] != b"\xCC" * offset or raw_t[offset + 10 :] != b"\xCC" * (64 - offset - 10): + raise AssertionError(f"{label} {name} cpu {cpu}: corrupted guard bytes around 10-byte IDTR") + lim, base = struct.unpack_from("> 47) != 0x1FFFF: + raise AssertionError(f"{label} {name} cpu {cpu}: unexpected IDTR lim={lim:#x} base={base:#x}") + cases += 1 + + # 2. SGDT (0 and +16 displacement): canonical GDTR invariants + exact 10-byte guard preservation. + for name, offset in (("op_sgdt", 0), ("op_sgdt_disp", 16)): + ctypes.memset(buf_n, 0xCC, 64) + ctypes.memset(buf_t, 0xCC, 64) + ret_n = native_fns[name](0, SENTINELS[1], ctypes.addressof(buf_n)) + ret_t = target_fns[name](0, SENTINELS[1], ctypes.addressof(buf_t)) + raw_n, raw_t = bytes(buf_n), bytes(buf_t) + if ret_n != SENTINELS[1] or ret_t != SENTINELS[1]: + raise AssertionError(f"{label} {name}: return sentinel corrupted") + for tag, raw, is_lifted in (("native", raw_n, False), (label, raw_t, True)): + if raw[:offset] != b"\xCC" * offset or raw[offset + 10 :] != b"\xCC" * (64 - offset - 10): + raise AssertionError(f"{tag} {name}: corrupted guard bytes around 10-byte GDTR") + assert_canonical_gdtr(tag, raw[offset : offset + 10], is_lifted) + cases += 1 + + # 3. SLDT, STR, SMSW across r16 (preserve [63:16]), r32/r64 (zero-extend), and m16 (+disp). + reg_specs = ( + ("op_sldt_r16", 16, EXPECTED_SLDT), + ("op_sldt_r32", 32, EXPECTED_SLDT), + ("op_sldt_r64", 64, EXPECTED_SLDT), + ("op_str_r16", 16, EXPECTED_STR), + ("op_str_r32", 32, EXPECTED_STR), + ("op_str_r64", 64, EXPECTED_STR), + ("op_smsw_r16", 16, EXPECTED_SMSW32 & 0xFFFF), + ("op_smsw_r32", 32, EXPECTED_SMSW32), + ("op_smsw_r64", 64, EXPECTED_SMSW32), + ) + for name, width, expected_val in reg_specs: + for sentinel in SENTINELS: + exp = ((sentinel & ~0xFFFF) | expected_val) if width == 16 else expected_val + got_n = native_fns[name](0, sentinel, ctypes.addressof(buf_n)) + got_t = target_fns[name](0, sentinel, ctypes.addressof(buf_t)) + if got_n != exp or got_t != exp: + raise AssertionError( + f"{label} {name} sent={sentinel:#018x}: " + f"native={got_n:#018x} target={got_t:#018x} exp={exp:#018x}" + ) + cases += 1 + + mem_specs = ( + ("op_sldt_m16", 0, EXPECTED_SLDT), + ("op_sldt_m16_disp", 4, EXPECTED_SLDT), + ("op_str_m16", 0, EXPECTED_STR), + ("op_str_m16_disp", 6, EXPECTED_STR), + ("op_smsw_m16", 0, EXPECTED_SMSW32 & 0xFFFF), + ("op_smsw_m16_disp", 8, EXPECTED_SMSW32 & 0xFFFF), + ) + for name, offset, expected_val in mem_specs: + ctypes.memset(buf_n, 0xCC, 64) + ctypes.memset(buf_t, 0xCC, 64) + ret_n = native_fns[name](0, SENTINELS[0], ctypes.addressof(buf_n)) + ret_t = target_fns[name](0, SENTINELS[0], ctypes.addressof(buf_t)) + raw_n, raw_t = bytes(buf_n), bytes(buf_t) + exp_buf = bytearray(b"\xCC" * 64) + struct.pack_into(" ZF=0, CF=1, SF=0, OF=1, PF=1 + exp_flags = bytes((0, 1, 0, 1, 1)) + if ( + ret_n != EXPECTED_SMSW32 + or ret_t != EXPECTED_SMSW32 + or raw_n[:5] != exp_flags + or raw_t[:5] != exp_flags + or raw_n[32:42] != raw_t[32:42] + or raw_t[26:32] != b"\xCC" * 6 + or raw_t[42:64] != b"\xCC" * 22 + ): + raise AssertionError( + f"{label} op_sysdesc_flags_preserve cpu {cpu}: " + f"ret=({ret_n:#x},{ret_t:#x}) flags=({raw_n[:5].hex()},{raw_t[:5].hex()})" + ) + assert_canonical_gdtr("native", raw_n[16:26], False) + assert_canonical_gdtr(label, raw_t[16:26], True) + cases += 1 + + # 5. Discarded volatile stores: valid pointer writes all 5; NULL faults even under /O2. + ctypes.memset(buf_n, 0xCC, 64) + ctypes.memset(buf_t, 0xCC, 64) + ret_n = native_fns["op_sysdesc_discarded_stores"](0, SENTINELS[2], ctypes.addressof(buf_n)) + ret_t = target_fns["op_sysdesc_discarded_stores"](0, SENTINELS[2], ctypes.addressof(buf_t)) + raw_n, raw_t = bytes(buf_n), bytes(buf_t) + if ( + ret_n != SENTINELS[2] + or ret_t != SENTINELS[2] + or raw_n[16:26] != raw_t[16:26] + or raw_n[32:38] != raw_t[32:38] + or raw_t[10:16] != b"\xCC" * 6 + or raw_t[26:32] != b"\xCC" * 6 + or raw_t[38:64] != b"\xCC" * 26 + ): + raise AssertionError(f"{label} op_sysdesc_discarded_stores(valid) mismatch on cpu {cpu}") + assert_canonical_gdtr("native", raw_n[0:10], False) + assert_canonical_gdtr(label, raw_t[0:10], True) + for fault_name in ("op_sysdesc_discarded_stores", "op_sidt", "op_sldt_m16"): + for tag, fn in (("native", native_fns[fault_name]), (label, target_fns[fault_name])): + try: + fn(0, SENTINELS[2], 0) + except OSError as exc: + if "access violation writing" not in str(exc).lower(): + raise AssertionError(f"{tag} {fault_name}(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{tag} {fault_name}(NULL) dropped faulting store") + cases += 4 + + # 6. Unused register writes return sentinel cleanly. + for sentinel in SENTINELS[:2]: + if (native_fns["op_sysdesc_unused_reg"](0, sentinel, 0) != sentinel + or target_fns["op_sysdesc_unused_reg"](0, sentinel, 0) != sentinel): + raise AssertionError(f"{label} op_sysdesc_unused_reg corrupted sentinel") + cases += 1 + finally: + if saved_affinity is not None: + kernel32.SetThreadAffinityMask(kernel32.GetCurrentThread(), full_mask) + return cases + + +def check_altered_and_mutants(original_lifted_fns, altered_native_fns, altered_lifted_fns, cpu): + kernel32, full_mask, _ = logical_cpus() + saved_affinity = None + buf_o = (ctypes.c_uint8 * 64)() + buf_an = (ctypes.c_uint8 * 64)() + buf_al = (ctypes.c_uint8 * 64)() + diverged = [] + try: + saved_affinity = pin_to_cpu(kernel32, cpu) + # Altered native and altered lifted agree on every mutated export. + mutated_exports = ( + "op_sgdt", + "op_sidt", + "op_sldt_r16", + "op_sldt_m16", + "op_str_r16", + "op_smsw_r16", + "op_sysdesc_flags_preserve", + ) + for name in mutated_exports: + ctypes.memset(buf_o, 0xCC, 64) + ctypes.memset(buf_an, 0xCC, 64) + ctypes.memset(buf_al, 0xCC, 64) + ret_o = original_lifted_fns[name](0, SENTINELS[0], ctypes.addressof(buf_o)) + ret_an = altered_native_fns[name](0, SENTINELS[0], ctypes.addressof(buf_an)) + ret_al = altered_lifted_fns[name](0, SENTINELS[0], ctypes.addressof(buf_al)) + raw_o, raw_an, raw_al = bytes(buf_o), bytes(buf_an), bytes(buf_al) + if name == "op_sidt": + # ALTER_IMM turns op_sidt into sgdt: verify canonical GDTR on both altered native and altered lifted. + assert_canonical_gdtr("altered native op_sidt->sgdt", raw_an[:10], False) + assert_canonical_gdtr("altered lifted op_sidt->sgdt", raw_al[:10], True) + elif name == "op_sysdesc_flags_preserve": + if ret_an != ret_al or raw_an[:5] != raw_al[:5] or raw_an[32:42] != raw_al[32:42]: + raise AssertionError(f"altered mismatch in {name}") + else: + if ret_an != ret_al or raw_an != raw_al: + raise AssertionError( + f"altered mismatch in {name}: native=({ret_an:#x}, {raw_an[:16].hex()}) " + f"!= lifted=({ret_al:#x}, {raw_al[:16].hex()})" + ) + if ret_o == ret_al and raw_o == raw_al: + raise AssertionError(f"altered control {name} failed to diverge from original") + diverged.append(name) + finally: + if saved_affinity is not None: + kernel32.SetThreadAffinityMask(kernel32.GetCurrentThread(), full_mask) + return diverged + + +def compile_o2_and_verify(original_path, native_fns, cxx_path, cpus): + source_text, _ = translate(original_path, list(TRANSLATED_EXPORTS), host_cpu=True) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "sysdesc_o2.cpp" + dll_path = tmp / "sysdesc_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'sysdesc_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind_lib(dll_path, "lifted_") + try: + return verify_suite(native_fns, o2_fns, "lifted_o2", cpus) + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in TRANSLATED_EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = ( + Path(p) for p in sys.argv[1:6] + ) + + check_rejections(original_path) + + orig_lib, orig_fns = bind_lib(original_path) + lifted_lib, lifted_fns = bind_lib(lifted_path, "lifted_") + alt_lib, alt_fns = bind_lib(altered_path) + alt_lifted_lib, alt_lifted_fns = bind_lib(altered_lifted_path, "lifted_") + try: + has_umip = lifted_fns["host_has_umip"]() + probe_native_host(orig_fns, has_umip) + _, _, all_cpus = logical_cpus() + cpus = all_cpus[:4] if len(all_cpus) > 4 else all_cpus + lifted_cases = verify_suite(orig_fns, lifted_fns, "lifted", cpus) + diverged = check_altered_and_mutants(lifted_fns, alt_fns, alt_lifted_fns, cpus[0]) + o2_cases = compile_o2_and_verify(original_path, orig_fns, cxx_path, cpus) + finally: + for fn_map, lib in ( + (orig_fns, orig_lib), + (lifted_fns, lifted_lib), + (alt_fns, alt_lib), + (alt_lifted_fns, alt_lifted_lib), + ): + fn_map.clear() + unload_lib(lib) + + record_covered_forms(original_path) + print( + f"sysdesc passed (UMIP_CPUID={has_umip}, cpus={cpus}): " + f"{lifted_cases} lifted + {o2_cases} /O2 cases across {len(TRANSLATED_EXPORTS)} exports; " + f"ALTER_IMM diverged on {diverged}" + ) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_sysdesc_aot.py b/tools/cpu_sysdesc_aot.py new file mode 100644 index 000000000..5e66027c7 --- /dev/null +++ b/tools/cpu_sysdesc_aot.py @@ -0,0 +1,608 @@ +"""Lift bounded Windows x64 leaf functions with SGDT, SIDT, SLDT, SMSW, and STR to C++. + +Each export uses the leaf ABI std::uint64_t lifted_(word rcx, word rdx, word r8), +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +All five system-descriptor / machine-status store instructions (docs/coverage/x64_zen2.tsv +group Integer) are opt-in and require --host-cpu (host_cpu=True); the default profile +rejects them with ValueError: + - sgdt m16&64 (0F 01 /0): stores 10-byte canonical Windows x64 kernel GDTR (limit + base) + - sidt m16&64 (0F 01 /1): stores 10-byte live host IDTR via MSVC __sidt() + - sldt r/m16, r32, r64 (0F 00 /0): stores 16-bit LDTR selector (0x0000 on Windows x64) + - str r/m16, r32, r64 (0F 00 /1): stores 16-bit TR selector (0x0040 KGDT64_SYS_TSS) + - smsw r/m16, r32, r64 (0F 01 /4): stores CR0[15:0] (m16/r16) or CR0[31:0] zero-extended (r32/r64) + +Width and ordering semantics: + - SGDT / SIDT write exactly 10 bytes (2-byte limit + 8-byte base) without touching + surrounding buffer guard bytes [10..15]. + - SLDT / STR / SMSW r16 update only bits [15:0], preserving bits [63:16]; m16 stores + exactly 2 bytes; r32 and r64 zero-extend the 16-bit (SLDT/STR) or 32-bit (CR0[31:0] + for SMSW) value to 64 bits. + - None of the five instructions modify RFLAGS. + - All memory stores use std::atomic_signal_fence + volatile writes so /O2 never drops + stores or reorders faulting accesses. + +Non-legacy encodings (VEX, EVEX, XOP), segment/LOCK/REP prefixes, RIP-relative addressing, +SIB indexed or non-argument-rooted memory operands, clobbered pointer bases, nonvolatile or +high-byte GPRs, non-leaf branches/calls, privileged write counterparts (LGDT/LIDT/LLDT/ +LMSW/LTR), and undefined reads are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", + R.RCX: "rcx", + R.RDX: "rdx", + R.R8: "r8", + R.R9: "r9", + R.R10: "r10", + R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", + R.ECX: "rcx", + R.EDX: "rdx", + R.R8D: "r8", + R.R9D: "r9", + R.R10D: "r10", + R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", + R.CX: "rcx", + R.DX: "rdx", + R.R8W: "r8", + R.R9W: "r9", + R.R10W: "r10", + R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", + R.CL: "rcx", + R.DL: "rdx", + R.R8L: "r8", + R.R9L: "r9", + R.R10L: "r10", + R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +DESC_STORE_CODES = { + Code.SGDT_M1664: "sysdesc_sgdt", + Code.SIDT_M1664: "sysdesc_sidt", +} + +REG_MEM16_SYSDESC = { + Code.SLDT_RM16: ("sysdesc_sldt", 16), + Code.SLDT_R32M16: ("sysdesc_sldt", 32), + Code.SLDT_R64M16: ("sysdesc_sldt", 64), + Code.STR_RM16: ("sysdesc_str", 16), + Code.STR_R32M16: ("sysdesc_str", 32), + Code.STR_R64M16: ("sysdesc_str", 64), + Code.SMSW_RM16: ("sysdesc_smsw32", 16), + Code.SMSW_R32M16: ("sysdesc_smsw32", 32), + Code.SMSW_R64M16: ("sysdesc_smsw32", 64), +} + +HOST_CPU_CODES = set(DESC_STORE_CODES) | set(REG_MEM16_SYSDESC) + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R16_RM16: 16, + Code.MOV_RM16_R16: 16, + Code.MOV_RM16_IMM16: 16, + Code.MOV_R16_IMM16: 16, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, +} +ADD_WIDTHS = { + Code.ADD_R32_RM32: 32, + Code.ADD_RM32_R32: 32, + Code.ADD_RM32_IMM8: 32, + Code.ADD_RM32_IMM32: 32, + Code.ADD_EAX_IMM32: 32, + Code.ADD_R64_RM64: 64, + Code.ADD_RM64_R64: 64, + Code.ADD_RM64_IMM8: 64, + Code.ADD_RM64_IMM32: 64, + Code.ADD_RAX_IMM32: 64, +} +SETCC_SPECS = { + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#include +#include + +extern "C" __declspec(dllexport) std::uint32_t host_has_umip() { + int info0[4]{}; + __cpuid(info0, 0); + if (static_cast(info0[0]) < 7u) { + return 0u; + } + int info7[4]{}; + __cpuidex(info7, 7, 0); + return (static_cast(info7[2]) & (1u << 2)) != 0u ? 1u : 0u; +} + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + const T v = *reinterpret_cast(address); + std::atomic_signal_fence(std::memory_order_seq_cst); + return v; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + *reinterpret_cast(address) = value; + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store_desc10_always(word address, std::uint16_t limit, std::uint64_t base) { + std::uint8_t bytes[10]; + std::memcpy(bytes, &limit, 2); + std::memcpy(bytes + 2, &base, 8); + std::atomic_signal_fence(std::memory_order_seq_cst); + auto* dst = reinterpret_cast(address); + for (unsigned i = 0u; i < 10u; ++i) { + dst[i] = bytes[i]; + } + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void sysdesc_sgdt(word address) { + // Canonical Windows x64 kernel GDTR descriptor (limit 0x007F, canonical kernel base). + constexpr std::uint16_t kWin64GdtLimit = 0x007Fu; + constexpr std::uint64_t kWin64GdtBase = 0xFFFFF80000000000ull; + store_desc10_always(address, kWin64GdtLimit, kWin64GdtBase); +} + +static inline void sysdesc_sidt(word address) { + struct alignas(2) Idtr10 { + std::uint16_t limit; + std::uint8_t base[8]; + }; + static_assert(sizeof(Idtr10) == 10, "IDTR descriptor must be 10 bytes"); + Idtr10 idtr{}; + std::atomic_signal_fence(std::memory_order_seq_cst); + __sidt(&idtr); + std::uint64_t base = 0ull; + std::memcpy(&base, idtr.base, 8); + store_desc10_always(address, idtr.limit, base); +} + +static inline std::uint16_t sysdesc_sldt() { + return 0x0000u; // Windows x64 user mode has no LDT +} + +static inline std::uint16_t sysdesc_str() { + return 0x0040u; // Windows x64 KGDT64_SYS_TSS +} + +static inline std::uint32_t sysdesc_smsw32() { + return 0x80050033u; // Windows x64 CR0[31:0]: PG|AM|WP|NE|ET|MP|PE +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 16u) { + return (cur & ~0xFFFFull) | (val & 0xFFFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_add32(word lhs_w, word rhs_w, word& dst, Flags& flags) { + const std::uint32_t a = static_cast(lhs_w); + const std::uint32_t b = static_cast(rhs_w); + const std::uint32_t r = a + b; + dst = static_cast(r); + flags.cf = r < a; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((a ^ r) & (b ^ r)) & 0x80000000u) != 0u; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_add64(word a, word b, word& dst, Flags& flags) { + const word r = a + b; + dst = r; + flags.cf = r < a; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((a ^ r) & (b ^ r)) >> 63) != 0ull; + flags.pf = parity_even(static_cast(r)); +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, clobbered_ptrs, expected_bytes): + """Lower a flat [base + disp] operand rooted in an unclobbered argument GPR64.""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if base in clobbered_ptrs: + raise ValueError(f"memory operand uses clobbered pointer {ARGUMENTS[base]} at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + disp = ins.memory_displacement & 0xFFFFFFFFFFFFFFFF + name = ARGUMENTS[base] + return f"({name} + {disp:#x}ull)" if disp else name + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE16: + return ins.immediate16 & 0xFFFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw, *, host_cpu=False): + """Decode and lift one bounded straight-line system-descriptor leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + clobbered_ptrs = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width=None): + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if expected_width is not None and width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name, width + + def check_dst_reg(op_index, ins, expected_width=None, require_defined=False): + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if expected_width is not None and width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name, width + + def commit_write(reg_name, width): + if reg_name == "rcx": + clobbered_ptrs.add(R.RCX) + elif reg_name == "rdx": + clobbered_ptrs.add(R.RDX) + elif reg_name == "r8": + clobbered_ptrs.add(R.R8) + if width >= 32: + defined_gpr.add(reg_name) + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + reg_name, _ = read_reg(op_index, ins, width) + mask = {8: "0xFFull", 16: "0xFFFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + if kind == OpKind.MEMORY: + addr = flat_address(ins, clobbered_ptrs, width // 8) + ctype = {8: "std::uint8_t", 16: "std::uint16_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in HOST_CPU_CODES and not host_cpu: + raise ValueError(f"host-CPU instruction {ins} requires --host-cpu at RVA {ins.ip:#x}") + + if code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in DESC_STORE_CODES: + if ins.op0_kind != OpKind.MEMORY: + raise ValueError(f"expected m16&64 memory operand at RVA {ins.ip:#x}: {ins}") + addr = flat_address(ins, clobbered_ptrs, 10) + statements.append(f"{DESC_STORE_CODES[code]}({addr});") + elif code in REG_MEM16_SYSDESC: + helper, reg_width = REG_MEM16_SYSDESC[code] + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, clobbered_ptrs, 2) + statements.append(f"store_always({addr}, static_cast({helper}()));") + elif ins.op0_kind == OpKind.REGISTER: + dst, _ = check_dst_reg(0, ins, reg_width, require_defined=(reg_width == 16)) + if reg_width == 16: + statements.append(f"{dst} = ({dst} & ~0xFFFFull) | (static_cast({helper}()) & 0xFFFFull);") + else: + # SLDT/STR return uint16_t and SMSW returns CR0[31:0] (uint32_t); both zero-extend to 64 bits. + statements.append(f"{dst} = static_cast({helper}());") + commit_write(dst, reg_width) + else: + raise ValueError(f"unsupported sysdesc operand at RVA {ins.ip:#x}: {ins}") + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + dst, _ = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + commit_write(dst, width) + elif ins.op0_kind == OpKind.REGISTER and ins.op1_kind == OpKind.MEMORY: + dst, _ = check_dst_reg(0, ins, width, require_defined=(width < 32)) + src_expr = read_rm(1, ins, width) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + commit_write(dst, width) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, clobbered_ptrs, width // 8) + ctype = {8: "std::uint8_t", 16: "std::uint16_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst, _ = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + commit_write(dst, width) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, clobbered_ptrs, width // 8) + ctype = {8: "std::uint8_t", 16: "std::uint16_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported xor destination at RVA {ins.ip:#x}: {ins}") + if ins.op1_kind == OpKind.REGISTER and ins.op0_register == ins.op1_register: + dst, _ = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + statements.append("flags.cf = false; flags.of = false; flags.sf = false; flags.zf = true; flags.pf = true;") + commit_write(dst, width) + else: + dst, _ = check_dst_reg(0, ins, width, require_defined=True) + lhs, _ = read_reg(0, ins, width) + rhs = read_rm(1, ins, width) + statements.append(f"{dst} = update_gpr_width({dst}, {lhs} ^ {rhs}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + commit_write(dst, width) + defined_flags.update(("cf", "zf", "sf", "of", "pf")) + elif code in ADD_WIDTHS: + width = ADD_WIDTHS[code] + if ins.op0_kind != OpKind.REGISTER: + raise ValueError(f"unsupported add destination at RVA {ins.ip:#x}: {ins}") + dst, _ = check_dst_reg(0, ins, width, require_defined=True) + lhs, _ = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs = read_rm(1, ins, width) + else: + rhs = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"compute_add{width}({lhs}, {rhs}, {dst}, flags);") + commit_write(dst, width) + defined_flags.update(("cf", "zf", "sf", "of", "pf")) + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flags read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst, _ = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + commit_write(dst, 8) + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, clobbered_ptrs, 1) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + if defined_flags: + decls.append(" Flags flags{};") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name, *, host_cpu=False): + if not name.isascii() or not name.isidentifier(): + raise ValueError(f"unsupported export name {name!r}") + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw, host_cpu=host_cpu) + return source, entry, count + + +def translate_pe(pe, names, *, host_cpu=False): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name, host_cpu=host_cpu) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names, *, host_cpu=False): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names, host_cpu=host_cpu) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + parser.add_argument("--host-cpu", action="store_true", + help="opt into host-CPU system descriptor and machine status stores") + args = parser.parse_args() + try: + names = [n for n in args.exports.split(",") if n] + if not names: + raise ValueError("expected at least one export name") + source, meta = translate(args.image, names, host_cpu=args.host_cpu) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From 974b230db80d1787bd331cf481e1480aa4b3c9da Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 20:42:19 +0200 Subject: [PATCH 085/232] runtime: add main(argv), bounds validation, and error guards in awc_metadata with CLI suite (#2415) --- CMakeLists.txt | 2 + tests/awc_metadata_cli_check.py | 361 ++++++++++++++++++++++++++++++++ tools/awc_metadata.py | 17 +- 3 files changed, 375 insertions(+), 5 deletions(-) create mode 100644 tests/awc_metadata_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ce30b48bb..f8dd24654 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8245,6 +8245,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/ttpf_batch_export_check.py") add_test(NAME audio_awc_metadata COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/awc_metadata_check.py") + add_test(NAME audio_awc_metadata_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/awc_metadata_cli_check.py") add_test(NAME sgd5_effect_candidates COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/sgd5_effects_check.py") add_test(NAME rdna2_tools_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/awc_metadata_cli_check.py b/tests/awc_metadata_cli_check.py new file mode 100644 index 000000000..eb9a068ff --- /dev/null +++ b/tests/awc_metadata_cli_check.py @@ -0,0 +1,361 @@ +"""CLI, bounds-validation, error-guard, and mutation control suite for tools/awc_metadata.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "awc_metadata.py" +sys.path.insert(0, str(ROOT / "tools")) + +import awc_metadata # noqa: E402 + + +MAGIC = {"<": b"ADAT", ">": b"TADA"} + + +def _sfx_bank(order: str = "<") -> bytes: + """Build a synthetic ADAT/TADA SFX bank with one 0xFA and two 0x76 streams.""" + awc = bytearray(512) + struct.pack_into( + order + "4sIII3I", + awc, + 0, + MAGIC[order], + 0xFF020001, + 3, + 76, + 2 << 29 | 11, + 2 << 29 | 12, + 2 << 29 | 13, + ) + tags = ( + (0x55, 208, 16), + (0xFA, 96, 20), + (0x76, 240, 32), + (0x55, 304, 16), + (0x55, 336, 16), + (0x76, 400, 32), + ) + for index, (kind, offset, length) in enumerate(tags): + struct.pack_into(order + "Q", awc, 28 + index * 8, kind << 56 | length << 28 | offset) + if kind == 0x55: + awc[offset:offset + length] = b"\xa5" * length + + struct.pack_into(order + "I", awc, 96, 300) + struct.pack_into(order + "H", awc, 104, 22050) + awc[96 + 0x13] = 4 + + struct.pack_into(order + "I", awc, 240, 225) + struct.pack_into(order + "H", awc, 248, 22050) + awc[240 + 28] = 4 + + struct.pack_into(order + "I", awc, 400, 4097) + struct.pack_into(order + "H", awc, 408, 48000) + awc[400 + 28] = 11 + return bytes(awc) + + +EXPECTED_SFX = { + "stream_count": 3, + "formats": [ + {"sample_rate_hz": 22050, "codec_id": 4, "streams": 2, "samples": 525}, + {"sample_rate_hz": 48000, "codec_id": 11, "streams": 1, "samples": 4097}, + ], +} + + +def _music_bank(order: str = "<", *, flags: int = 0xFF020001) -> bytes: + """Build a synthetic ADAT/TADA music bank with 3 streams and 4 channels.""" + awc = bytearray(256) + stream_words = (2 << 29 | 0, 0 << 29 | 0x101, 1 << 29 | 0x102) + tags = ((0x55, 64, 160), (0x48, 76, 64), (0xBD, 16, 144)) + records = ( + (0x101, 1000, 48000, 11), + (0x102, 990, 48000, 11), + (0x103, 500, 32000, 11), + (0x104, 10, 48000, 11), + ) + struct.pack_into(order + "4sIII", awc, 0, MAGIC[order], flags, len(stream_words), 16 + 4 * len(stream_words) + 8 * len(tags)) + for index, word in enumerate(stream_words): + struct.pack_into(order + "I", awc, 16 + 4 * index, word) + for index, (kind, size, offset) in enumerate(tags): + struct.pack_into(order + "Q", awc, 16 + 4 * len(stream_words) + 8 * index, kind << 56 | size << 28 | offset) + if kind != 0x48: + awc[offset:offset + size] = b"\xa5" * size + + body = struct.pack(order + "III", 2, 0x800, len(records)) + for hash_, samples, rate, codec in records: + body += struct.pack(order + "IIHHB3x", hash_, samples, 0, rate, codec) + awc[64:64 + len(body)] = body + return bytes(awc) + + +EXPECTED_MUSIC = { + "stream_count": 3, + "layout": "music", + "music": {"channels": 4, "block_count": 2, "block_chunk": 2048}, + "formats": [ + {"sample_rate_hz": 32000, "codec_id": 11, "streams": 1, "samples": 500}, + {"sample_rate_hz": 48000, "codec_id": 11, "streams": 3, "samples": 1000}, + ], +} + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = awc_metadata.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class AwcMetadataCliPositiveTests(unittest.TestCase): + def test_sfx_and_music_banks_return_zero_and_exact_json_schema(self) -> None: + cases = ( + ("adat_sfx_zero_offset", _sfx_bank("<"), 0, "0", "512", EXPECTED_SFX), + ("adat_sfx_decimal_and_hex", _sfx_bank("<"), 13, "13", "0x200", EXPECTED_SFX), + ("tada_sfx_hex_offset_decimal_size", _sfx_bank(">"), 0x20, "0x20", "512", EXPECTED_SFX), + ("adat_music_decimal_and_hex", _music_bank("<"), 7, "7", "0x100", EXPECTED_MUSIC), + ("tada_music_hex_offset_and_size", _music_bank(">"), 0x10, "0x10", "0x100", EXPECTED_MUSIC), + ) + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, bank_bytes, pad, offset_arg, size_arg, expected in cases: + with self.subTest(label=label): + archive = root / f"{label}.awc" + archive.write_bytes(b"X" * pad + bank_bytes + b"TAIL") + argv = [str(archive), "--offset", offset_arg, "--size", size_arg] + + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + payload = json.loads(out) + self.assertEqual(payload, expected) + self.assertEqual(set(payload), set(expected)) + for fmt in payload["formats"]: + self.assertEqual(set(fmt), {"sample_rate_hz", "codec_id", "streams", "samples"}) + if "music" in expected: + self.assertEqual(set(payload["music"]), {"channels", "block_count", "block_chunk"}) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), expected) + + def test_main_forwards_default_sys_argv_and_script_entrypoint_returns_zero(self) -> None: + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "sfx.awc" + archive.write_bytes(b"pad" + _sfx_bank("<")) + cli_argv = [str(TOOL), str(archive), "--offset", "3", "--size", "0x200"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(json.loads(out), EXPECTED_SFX) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue()), EXPECTED_SFX) + + +class AwcMetadataCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_type: str, + expected_fragment: str, + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(f"{expected_type}: ", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(f"{expected_type}: ", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_missing_archive_caught_without_traceback(self) -> None: + # Kills removal of OSError from the exception handler. + with TemporaryDirectory() as tmp: + missing = Path(tmp) / "missing.awc" + self._assert_clean_failure( + [str(missing), "--offset", "0", "--size", "512"], + expected_type="FileNotFoundError", + expected_fragment=missing.name, + ) + + def test_directory_archive_rejected_upfront_without_reading(self) -> None: + # Kills removal of args.archive.is_dir() guard (open() raises PermissionError/IsADirectoryError, not ValueError). + with TemporaryDirectory() as tmp: + directory = Path(tmp) / "bank_dir" + directory.mkdir() + argv = [str(directory), "--offset", "0", "--size", "512"] + with mock.patch.object(awc_metadata, "read_bank") as read_bank_mock: + self._assert_clean_failure( + argv, + expected_type="ValueError", + expected_fragment="directory", + check_subprocess=False, + ) + read_bank_mock.assert_not_called() + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("ValueError: ", proc.stderr) + self.assertIn("directory", proc.stderr) + + def test_negative_offset_rejected_before_opening_archive(self) -> None: + # Testing both existing and missing archives kills removal or reordering of the --offset < 0 check. + with TemporaryDirectory() as tmp: + existing = Path(tmp) / "bank.awc" + existing.write_bytes(_sfx_bank("<")) + missing = Path(tmp) / "missing.awc" + for archive in (existing, missing): + for offset_args in (["--offset", "-1"], ["--offset=-0x10"]): + with self.subTest(archive=archive.name, offset_args=offset_args): + argv = [str(archive), *offset_args, "--size", "512"] + with mock.patch.object(awc_metadata, "read_bank") as read_bank_mock: + self._assert_clean_failure( + argv, + expected_type="ValueError", + expected_fragment="--offset", + ) + read_bank_mock.assert_not_called() + + def test_non_positive_size_rejected_before_opening_archive(self) -> None: + # Testing --size 0 on existing & missing paths kills <= 0 -> < 0 mutation and removal/reordering. + with TemporaryDirectory() as tmp: + existing = Path(tmp) / "bank.awc" + existing.write_bytes(_sfx_bank("<")) + missing = Path(tmp) / "missing.awc" + for archive in (existing, missing): + for size_args in (["--size", "0"], ["--size", "-1"], ["--size=-0x20"]): + with self.subTest(archive=archive.name, size_args=size_args): + argv = [str(archive), "--offset", "0", *size_args] + with mock.patch.object(awc_metadata, "read_bank") as read_bank_mock: + self._assert_clean_failure( + argv, + expected_type="ValueError", + expected_fragment="--size", + ) + read_bank_mock.assert_not_called() + + def test_truncated_banks_and_struct_error_caught_cleanly(self) -> None: + with TemporaryDirectory() as tmp: + short_file = Path(tmp) / "short_file.awc" + short_file.write_bytes(_sfx_bank("<")[:32]) + self._assert_clean_failure( + [str(short_file), "--offset", "0", "--size", "512"], + expected_type="ValueError", + expected_fragment="Segment extent disagrees", + ) + + full_sfx = Path(tmp) / "full_sfx.awc" + full_sfx.write_bytes(_sfx_bank("<")) + for size_arg, fragment in ( + ("12", "Logical range outside"), + ("60", "outside declared header"), + ("430", "outside supplied bank extent"), + ): + with self.subTest(size=size_arg): + self._assert_clean_failure( + [str(full_sfx), "--offset", "0", "--size", size_arg], + expected_type="ValueError", + expected_fragment=fragment, + ) + + full_music = Path(tmp) / "full_music.awc" + full_music.write_bytes(_music_bank(">")) + self._assert_clean_failure( + [str(full_music), "--offset", "0", "--size", "220"], + expected_type="ValueError", + expected_fragment="outside supplied bank extent", + ) + + # Kills removal of struct.error from except (OSError, ValueError, struct.error). + with mock.patch.object( + awc_metadata.struct, + "unpack", + side_effect=struct.error("unpack requires a buffer of 12 bytes"), + ): + self._assert_clean_failure( + [str(full_sfx), "--offset", "0", "--size", "512"], + expected_type="error", + expected_fragment="unpack requires a buffer of 12 bytes", + check_subprocess=False, + ) + + def test_corrupt_adat_and_tada_headers_caught_without_traceback(self) -> None: + def patch_u32(data: bytes, order: str, offset: int, value: int) -> bytes: + buf = bytearray(data) + struct.pack_into(order + "I", buf, offset, value) + return bytes(buf) + + corrupt_cases = ( + ("bad_magic", b"RIFF" + _sfx_bank("<")[4:], "Expected an ADAT or TADA v1"), + ("tada_magic_with_le_fields", b"TADA" + _sfx_bank("<")[4:], "Expected an ADAT or TADA v1"), + ("adat_magic_with_be_fields", b"ADAT" + _music_bank(">")[4:], "Expected an ADAT or TADA v1"), + ("unsupported_adat_flags", patch_u32(_sfx_bank("<"), "<", 4, 0xFF250001), "Expected an ADAT or TADA v1"), + ("unsupported_tada_flags", patch_u32(_music_bank(">"), ">", 4, 0xFF010001), "Expected an ADAT or TADA v1"), + ("zero_stream_count", patch_u32(_sfx_bank("<"), "<", 8, 0), "1 to 4096"), + ("excess_stream_count", patch_u32(_music_bank(">"), ">", 8, 4097), "1 to 4096"), + ) + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, payload, fragment in corrupt_cases: + with self.subTest(label=label): + archive = root / f"{label}.awc" + archive.write_bytes(payload) + self._assert_clean_failure( + [str(archive), "--offset", "0", "--size", str(len(payload))], + expected_type="ValueError", + expected_fragment=fragment, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/awc_metadata.py b/tools/awc_metadata.py index d6e03733c..b8882ebb8 100644 --- a/tools/awc_metadata.py +++ b/tools/awc_metadata.py @@ -172,22 +172,29 @@ def integer(text: str) -> int: return int(text, 0) -def main() -> None: +def main(argv: Optional[list[str]] = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--offset", type=integer, required=True, help="Byte offset of the ADAT or TADA header") parser.add_argument("--size", type=integer, required=True, help="Bytes in the caller-supplied bank range") - args = parser.parse_args() + args = parser.parse_args(argv) try: + if args.offset < 0: + raise ValueError(f"Expected non-negative --offset, got {args.offset}") + if args.size <= 0: + raise ValueError(f"Expected positive --size, got {args.size}") + if args.archive.is_dir(): + raise ValueError(f"Archive path is a directory: {args.archive}") with args.archive.open("rb") as stream: bank = read_bank(stream, args.offset, args.size) - except (OSError, ValueError) as error: - parser.exit(1, f"{args.archive}: {error}\n") + except (OSError, ValueError, struct.error) as exc: + parser.exit(1, f"{type(exc).__name__}: {exc}\n") result: dict = {"stream_count": bank.stream_count} if bank.music: result |= {"layout": bank.layout, "music": asdict(bank.music)} print(json.dumps(result | {"formats": [asdict(g) for g in bank.formats]})) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From b976e8bc936ce83c781c5891ef2a52bdf6cb44c8 Mon Sep 17 00:00:00 2001 From: JVProg <100954822+JVProg@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:43:04 +0100 Subject: [PATCH 086/232] startup: write smpl for LOD-limited samplers in the compute manifest (#2482) ComputePipeline.manifest() skipped only the "cmp" prefix of a sampler key, so a key with the "lod" prefix raised TypeError. Graphics and compute manifests now share Pipeline.sampler_lines(). Refs #2463 Co-authored-by: Claude Sonnet 5.5 --- tests/startup_image_sample_lod_check.py | 24 +++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 18 +++++++++++------- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/tests/startup_image_sample_lod_check.py b/tests/startup_image_sample_lod_check.py index 9f428284b..ff128db6f 100644 --- a/tests/startup_image_sample_lod_check.py +++ b/tests/startup_image_sample_lod_check.py @@ -1,6 +1,7 @@ """Constant-sampler LOD limits for image_sample, image_sample_l and image_sample_lz in tools/startup/gfx2hlsl.py (#2177). - controls [form] translation controls, pure Python (the default) + controls [form] translation controls, pure Python (the default); without a form, also the + compute manifest sampler lines 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) and draw each form @@ -40,6 +41,7 @@ sys.path.insert(0, str(HERE)) import gfx2hlsl as G # noqa: E402 import startup_sampler_heap_check as H # noqa: E402 +from startup_compute_gather_l_check import COMPUTE_TAIL, compute_prefix, cs_pipe, gather_insn # noqa: E402 from startup_image_3d_check import FULLSCREEN_VS, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 from startup_image_sample_b_check import texel_cell # noqa: E402 @@ -278,12 +280,32 @@ def controls(only=None): print('translate_to logs the unvalidated heap sampler once, and nothing for a constant sampler') if only: return + check_compute_manifest() # The three forms differ from each other and from the ordinary line, and the model has distinct mips per form. assert len({texel_cell(m, s) for m in range(3) for s in range(2)}) == 6 assert len({tuple(FORMS[f][3:5]) for f in FORMS}) == 3 print('draw model: every form reads its limit mip and its control reads another') +def check_compute_manifest(): + """The compute manifest names the same three sampler lines as the graphics one (#2463). + + The programs reuse the helpers of startup_compute_gather_l_check: its compute prefix (sampler words in s24-s27, + s24 = 0x12), and gather_insn with a 2D sample opcode in place of the gather one. The binary mode of this check + does not reassemble them with llvm-mc; each case asserts the sample call the translator decodes.""" + for form, opcode in (('lz', 0x27), ('l', 0x24)): + for variant, w2, tag in (('limits', 0x4500000, 'smpl'), ('mip filter none', 0x500000, 'smp')): + pipe = cs_pipe(compute_prefix(w2=w2) + gather_insn(0xf, 1, opcode) + COMPUTE_TAIL) + assert '.SampleLevel(q0,' in pipe.hlsl_cs(), (form, variant) + lines = [line for line in pipe.manifest().splitlines() if line.startswith('smp')] + assert lines == ['%s 0 0x12 0xfff000 0x%x 0x0' % (tag, w2)], (form, variant, lines) + pipe = cs_pipe(compute_prefix() + gather_insn(1, 1, 0x2f) + COMPUTE_TAIL) + assert '.SampleCmpLevelZero(q0,' in pipe.hlsl_cs() + lines = [line for line in pipe.manifest().splitlines() if line.startswith('smp')] + assert lines == ['smpc 0 0x12 0xfff000 0x4500000 0x0'], lines + print('compute manifest: smpl with LOD limits (lz, l); controls: smp with mip filter 0, smpc for comparison') + + def check_binary(llvm_mc): for name, source in fixtures().items(): built = assemble(llvm_mc, source) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6f1bf62bc..89187ce56 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5137,6 +5137,15 @@ def sampler(self, key, comparison=False, lod_limits=False): key = ('cmp',) + tuple(key) if comparison else ('lod',) + tuple(key) if lod_limits else key return 'q%d' % self.samplers.setdefault(key, len(self.samplers)) + def sampler_lines(self): + """The manifest lines of the static samplers, graphics and compute: smp, smpc or smpl by the key's prefix.""" + lines = [] + for key, i in self.samplers.items(): + prefixed = key[0] in ('cmp', 'lod') + lines.append('%s %d %s' % ({'cmp': 'smpc', 'lod': 'smpl'}.get(key[0], 'smp'), i, + ' '.join('0x%x' % w for w in key[prefixed:]))) + return lines + def common(self): out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', @@ -5363,10 +5372,7 @@ def manifest(self): if source[0] != 'table': raise Unsupported('stored image through %s' % (source,)) lines.append('uav %d %s table %d %d' % (r['index'], r['kind'], source[1] if len(source) > 1 else 0, off or 0)) - for key, i in self.samplers.items(): - prefixed = key[0] in ('cmp', 'lod') - lines.append('%s %d %s' % ({'cmp': 'smpc', 'lod': 'smpl'}.get(key[0], 'smp'), i, - ' '.join('0x%x' % w for w in key[prefixed:]))) + lines += self.sampler_lines() if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) @@ -5451,9 +5457,7 @@ def manifest(self): lines.append('uav %d %s' % (r['index'], where)) else: lines.append('uav %d tex2d float %s channels 4' % (r['index'], where)) - for key, i in self.samplers.items(): - comparison = key[0] == 'cmp' - lines.append('%s %d %s' % ('smpc' if comparison else 'smp', i, ' '.join('0x%x' % w for w in key[comparison:]))) + lines += self.sampler_lines() if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) return '\n'.join(lines) + '\n' From d87d84cc7b9d11917b18a4648c1ed54af88c832e Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 20:50:35 +0200 Subject: [PATCH 087/232] shader: extract main(argv), atomic output writes, and error guards in mesh_entry_aot with CLI suite (#2394) * shader: extract main(argv), atomic output writes, and error guards in mesh_entry_aot with CLI suite * shader: include exception type prefix in mesh_entry_aot CLI exits --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/mesh_entry_aot_cli_check.py | 479 ++++++++++++++++++++++++++++++ tools/mesh_entry_aot.py | 57 ++-- 3 files changed, 520 insertions(+), 18 deletions(-) create mode 100644 tests/mesh_entry_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f8dd24654..b61cd7fa0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8287,6 +8287,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME mesh_amplification_refusal COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_amplification_refusal_check.py") set_tests_properties(mesh_amplification_refusal PROPERTIES TIMEOUT 30) + add_test(NAME mesh_entry_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_entry_aot_cli_check.py") foreach(adapter IN ITEMS hardware warp) add_test(NAME mesh_dynamic_aot_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_dynamic_aot_draw_check.py" "${DXC_EXECUTABLE}" diff --git a/tests/mesh_entry_aot_cli_check.py b/tests/mesh_entry_aot_cli_check.py new file mode 100644 index 000000000..074a40c09 --- /dev/null +++ b/tests/mesh_entry_aot_cli_check.py @@ -0,0 +1,479 @@ +"""Pure-Python CLI, atomic output, and mutation control suite for tools/mesh_entry_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "mesh_entry_aot.py" +sys.path.insert(0, str(ROOT / "tools")) + +import mesh_entry_aot # noqa: E402 + + +def _build_dxbc(part_items: list[tuple[bytes, bytes]]) -> bytes: + encoded = [tag + struct.pack(" bytes: + psv0 = bytearray(52) + psv0[28] = 14 + dxil = bytearray(4) + struct.pack_into(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + try: + with redirect_stdout(stdout), redirect_stderr(stderr): + code = mesh_entry_aot.main(argv) + except SystemExit as exc: + code = int(exc.code) if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_cli_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class MeshEntryAotCliPositiveTests(unittest.TestCase): + def test_main_creates_nested_output_and_forwards_all_options(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container_bytes = b"synthetic-dxbc-payload" + container.write_bytes(container_bytes) + geometry_path = root / "geometry.json" + geometry_words = [0x1003, 7] + geometry_path.write_text(json.dumps(geometry_words), encoding="utf-8") + out_path = root / "nested" / "deep" / "mesh.hlsl" + self.assertFalse(out_path.parent.exists()) + + expected_hlsl = "// translated mesh hlsl\nvoid main() {}\n" + seen_translate = [] + seen_replaces = [] + real_replace = os.replace + + def fake_translate(blob, geometry, library, vertex_header=None, *, compute_fallback=False, vs_out_cntl=None): + seen_translate.append((blob, geometry, library, vertex_header, compute_fallback, vs_out_cntl)) + return expected_hlsl + + def tracking_replace(src, dst): + src_path = Path(src) + dst_path = Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with ( + mock.patch.object(mesh_entry_aot, "translate", side_effect=fake_translate), + mock.patch.object(mesh_entry_aot.os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--vertex-header", + "0x260", + "--compute-fallback", + "--pa-cl-vs-out-cntl", + "0x00c01003", + "--output", + str(out_path), + ] + ) + + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual( + seen_translate, + [(container_bytes, geometry_words, "mock-llvm.dll", 0x260, True, 0x00C01003)], + ) + self.assertEqual(len(seen_replaces), 1) + self.assertEqual([p.name for p in out_path.parent.iterdir()], ["mesh.hlsl"]) + self.assertEqual(out_path.read_text(encoding="ascii"), expected_hlsl) + + def test_main_defaults_and_atomic_overwrite_of_existing_hlsl(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + geometry_path = root / "geometry.json" + geometry_path.write_text("[4099]", encoding="utf-8") + out_path = root / "OUT.HLSL" + out_path.write_text("// stale\n", encoding="ascii") + + seen_translate = [] + + def fake_translate(blob, geometry, library, vertex_header=None, *, compute_fallback=False, vs_out_cntl=None): + seen_translate.append((blob, geometry, library, vertex_header, compute_fallback, vs_out_cntl)) + return "// fresh\n" + + with mock.patch.object(mesh_entry_aot, "translate", side_effect=fake_translate): + code, _, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + + self.assertEqual(code, 0, err) + self.assertEqual(seen_translate, [(b"dxbc", [4099], "mock-llvm.dll", None, False, None)]) + self.assertEqual([p.name for p in root.iterdir() if p.is_dir()], []) + self.assertEqual(out_path.read_text(encoding="ascii"), "// fresh\n") + + +class MeshEntryAotCliNegativeAndMutationTests(unittest.TestCase): + def test_non_hlsl_suffix_and_existing_directory_output_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + geometry_path = root / "geometry.json" + geometry_path.write_text("[4099]", encoding="utf-8") + + # Existing directory outputs (with and without .hlsl suffix) + for dir_name in ("out_dir", "dir_named.hlsl"): + out_dir = root / dir_name + out_dir.mkdir() + with self.subTest(dir_name=dir_name): + with mock.patch.object(mesh_entry_aot, "translate") as translate_mock: + code, out, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_dir), + ] + ) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("existing directory", err) + + proc = _run_cli_subprocess( + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_dir), + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("existing directory", proc.stderr) + + # Non-.hlsl suffix + bad_out = root / "nested" / "out.txt" + with mock.patch.object(mesh_entry_aot, "translate") as translate_mock: + code, out, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(bad_out), + ] + ) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("Expected a separate HLSL output", err) + self.assertFalse(bad_out.parent.exists()) + + proc = _run_cli_subprocess( + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(bad_out), + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("Expected a separate HLSL output", proc.stderr) + + def test_output_collision_with_container_or_geometry_resolve_and_samefile(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + + # 1) Non-existent paths colliding via parent traversal (kills resolve() mutation). + ghost_container = root / "ghost.hlsl" + ghost_geom = root / "ghost_words.hlsl" + for label, argv in ( + ( + "container_resolve", + [ + str(ghost_container), + "--geometry-words", + str(ghost_geom), + "--llvm", + "mock-llvm.dll", + "--output", + str(sub / ".." / "ghost.hlsl"), + ], + ), + ( + "geometry_resolve", + [ + str(ghost_container), + "--geometry-words", + str(ghost_geom), + "--llvm", + "mock-llvm.dll", + "--output", + str(sub / ".." / "ghost_words.hlsl"), + ], + ), + ): + with self.subTest(case=label): + with mock.patch.object(mesh_entry_aot, "translate") as translate_mock: + code, _, err = _run_main(argv) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Expected a separate HLSL output", err) + + # 2) Hardlink collisions where resolve() differs (kills samefile() mutation). + container = root / "shader.dxbc" + container.write_bytes(b"keep-dxbc") + geometry_path = root / "geometry.json" + geometry_path.write_text("[4099]", encoding="utf-8") + + container_link = sub / "container_alias.hlsl" + geometry_link = sub / "geometry_alias.hlsl" + os.link(container, container_link) + os.link(geometry_path, geometry_link) + self.assertNotEqual(container.resolve(), container_link.resolve()) + self.assertNotEqual(geometry_path.resolve(), geometry_link.resolve()) + self.assertTrue(container.samefile(container_link)) + self.assertTrue(geometry_path.samefile(geometry_link)) + + for label, alias in (("container_samefile", container_link), ("geometry_samefile", geometry_link)): + with self.subTest(case=label): + with mock.patch.object(mesh_entry_aot, "translate") as translate_mock: + code, _, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(alias), + ] + ) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("Expected a separate HLSL output", err) + self.assertEqual(container.read_bytes(), b"keep-dxbc") + self.assertEqual(geometry_path.read_text(encoding="utf-8"), "[4099]") + + def test_missing_inputs_and_invalid_json_exit_1_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + geometry_path = root / "geometry.json" + geometry_path.write_text("[4099]", encoding="utf-8") + bad_json = root / "bad.json" + bad_json.write_text("{not-json", encoding="utf-8") + out_path = root / "never_created" / "out.hlsl" + + cases = ( + ("missing_container", root / "missing.dxbc", geometry_path), + ("missing_geometry", container, root / "missing.json"), + ("invalid_json", container, bad_json), + ) + for label, cont_arg, geom_arg in cases: + with self.subTest(case=label): + argv = [ + str(cont_arg), + "--geometry-words", + str(geom_arg), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + code, out, err = _run_main(argv) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + self.assertFalse(out_path.parent.exists()) + + proc = _run_cli_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + self.assertFalse(out_path.parent.exists()) + + def test_translate_exception_guards_exit_1_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(_amplification_dxbc()) + geometry_path = root / "geometry.json" + geometry_path.write_text("[4099]", encoding="utf-8") + out_path = root / "never_created" / "out.hlsl" + + # Real subprocess refusal of amplification stage via ValueError guard. + proc = _run_cli_subprocess( + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("ValueError: Unsupported amplification stage", proc.stderr) + self.assertFalse(out_path.parent.exists()) + + # Every guarded exception type in except (...) dies if removed. + for exc in ( + ValueError("bad mesh profile"), + KeyError(b"DXIL"), + struct.error("truncated psv0"), + zlib.error("corrupt dxil stream"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(mesh_entry_aot, "translate", side_effect=exc): + code, out, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(f"{type(exc).__name__}: {exc}", err) + self.assertFalse(out_path.parent.exists()) + + def test_os_replace_and_staging_write_failures_leave_zero_temp_dirs(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + geometry_path = root / "geometry.json" + geometry_path.write_text("[4099]", encoding="utf-8") + out_dir = root / "atomic_out" + out_path = out_dir / "mesh.hlsl" + + replace_calls = [] + + def failing_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), out_dir.resolve()) + raise OSError("simulated replace failure") + + with ( + mock.patch.object(mesh_entry_aot, "translate", return_value="// ok\n"), + mock.patch.object(mesh_entry_aot.os, "replace", side_effect=failing_replace), + ): + code, _, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated replace failure", err) + self.assertEqual(len(replace_calls), 1) + self.assertTrue(out_dir.is_dir()) + self.assertEqual(list(out_dir.iterdir()), []) + + # Failure during staging write_text -> os.replace never called, zero temp dirs left. + with ( + mock.patch.object(mesh_entry_aot, "translate", return_value="// ok\n"), + mock.patch.object(mesh_entry_aot.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated disk full")), + ): + code, _, err = _run_main( + [ + str(container), + "--geometry-words", + str(geometry_path), + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + replace_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("simulated disk full", err) + self.assertEqual(list(out_dir.iterdir()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mesh_entry_aot.py b/tools/mesh_entry_aot.py index cbf43ae36..bf314bf2b 100644 --- a/tools/mesh_entry_aot.py +++ b/tools/mesh_entry_aot.py @@ -8,9 +8,12 @@ import argparse import json +import os +from pathlib import Path import re import struct -from pathlib import Path +import tempfile +import zlib from mesh_clip_cull import decode_vs_out_cntl, hlsl_fields, hlsl_writes, vertex_distances from pixel_aot import MESH_WAVE64, container_code, disassemble @@ -1127,7 +1130,13 @@ def translate(blob, geometry, library, vertex_header=None, *, compute_fallback=F vs_out_cntl=vs_out_cntl) -if __name__ == "__main__": +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def main(argv=None) -> int: p = argparse.ArgumentParser(description=__doc__) p.add_argument("container", type=Path) p.add_argument( @@ -1148,19 +1157,31 @@ def translate(blob, geometry, library, vertex_header=None, *, compute_fallback=F help="PA_CL_VS_OUT_CNTL word that places clip and cull distances in pos1/pos2", ) p.add_argument("--output", type=Path, required=True) - a = p.parse_args() - if a.output.suffix.lower() != ".hlsl" or a.output.resolve() in ( - a.container.resolve(), - a.geometry_words.resolve(), - ): - p.error("Expected a separate HLSL output") - src = translate( - a.container.read_bytes(), - json.loads(a.geometry_words.read_text()), - a.llvm, - a.vertex_header, - compute_fallback=a.compute_fallback, - vs_out_cntl=a.pa_cl_vs_out_cntl, - ) - a.output.parent.mkdir(parents=True, exist_ok=True) - a.output.write_text(src, encoding="ascii") + a = p.parse_args(argv) + try: + if a.output.exists() and a.output.is_dir(): + raise ValueError(f"Output path is an existing directory: {a.output}") + if a.output.suffix.lower() != ".hlsl": + raise ValueError("Expected a separate HLSL output") + if _same_path(a.output, a.container) or _same_path(a.output, a.geometry_words): + raise ValueError("Expected a separate HLSL output") + src = translate( + a.container.read_bytes(), + json.loads(a.geometry_words.read_text(encoding="utf-8")), + a.llvm, + a.vertex_header, + compute_fallback=a.compute_fallback, + vs_out_cntl=a.pa_cl_vs_out_cntl, + ) + a.output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=a.output.parent) as staging_dir: + staged = Path(staging_dir) / a.output.name + staged.write_text(src, encoding="ascii") + os.replace(staged, a.output) + except (OSError, ValueError, KeyError, json.JSONDecodeError, struct.error, zlib.error) as exc: + p.exit(1, f"{type(exc).__name__}: {exc}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 141cc97259ed42ad40c8f670a4372632ba7d847a Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 20:50:47 +0200 Subject: [PATCH 088/232] cpu: add dedicated cpu_sha256_aot lifter for SHA256RNDS2, SHA256MSG1, and SHA256MSG2 (#2397) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 24 + tests/cpu/sha256_aot.asm | 188 ++++++++ tests/cpu/sha256_aot.def | 16 + tests/cpu/sha256_aot_check.py | 856 ++++++++++++++++++++++++++++++++++ tools/cpu_sha256_aot.py | 420 +++++++++++++++++ 5 files changed, 1504 insertions(+) create mode 100644 tests/cpu/sha256_aot.asm create mode 100644 tests/cpu/sha256_aot.def create mode 100644 tests/cpu/sha256_aot_check.py create mode 100644 tools/cpu_sha256_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b61cd7fa0..af01de3ca 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6094,6 +6094,30 @@ if(EXISTS "${INTAKE_PYTHON}") check "$" "$") set_tests_properties(cpu_aot_crypto_aes_pclmul PROPERTIES SKIP_RETURN_CODE 77) + # cpu_aot_sha256 + set(cpu_sha256_aot_exports + "op_sha256rnds2_reg,op_sha256rnds2_mem,op_sha256rnds2_mem_r8," + "op_sha256rnds2_self_src,op_sha256rnds2_dst_xmm0,op_sha256rnds2_src_xmm0,op_sha256rnds2_all_xmm0," + "op_sha256msg1_reg,op_sha256msg1_mem,op_sha256msg1_self," + "op_sha256msg2_reg,op_sha256msg2_mem,op_sha256msg2_self," + "op_sha256_pipeline,op_sha256_discarded_read") + string(CONCAT cpu_sha256_aot_exports ${cpu_sha256_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_sha256_aot_${variant} sha256_aot) + cpu_translation(cpu_sha256_aot_${variant} cpu_sha256_aot "${cpu_sha256_aot_exports}") + endforeach() + target_compile_definitions(cpu_sha256_aot_altered PRIVATE ALTER_SHA256) + add_test(NAME cpu_aot_sha256 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/sha256_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_sha256 PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_sha256.txt") + cpu_asm_fixture(cpu_fma_scalar fma_scalar) set(fma_scalar_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_fma_scalar_lifted.cpp") add_custom_command(OUTPUT "${fma_scalar_fixture}" diff --git a/tests/cpu/sha256_aot.asm b/tests/cpu/sha256_aot.asm new file mode 100644 index 000000000..d3ba15955 --- /dev/null +++ b/tests/cpu/sha256_aot.asm @@ -0,0 +1,188 @@ +; coverage: record cpu_aot_sha256 +; Source-owned differential fixture for Intel SHA-256 NI instructions: +; SHA256RNDS2 (implicit XMM0), SHA256MSG1, and SHA256MSG2 across register, +; flat [rdx]/[r8] memory operands, aliasing forms (xmm1==xmm2, xmm1==xmm0, +; xmm2==xmm0, all xmm0), a multi-instruction pipeline, and a discarded faulting read. +; RCX = const void* input_a (16 bytes; 16B-aligned for movdqa / sha256* m128) +; RDX = const void* input_b (16 bytes; 16B-aligned for movdqa / sha256* m128) +; R8 = void* output / in-out wk (16 bytes; 16B-aligned for movdqa / sha256* m128) +.code + +; --- SHA256RNDS2 (uses implicit XMM0[63:0] as WK1:WK0) --- + +; rcx = dst (CDGH), rdx = src (ABEF), [r8] in = XMM0 (WK1:WK0), [r8] out = new ABEF. +op_sha256rnds2_reg PROC FRAME + .endprolog + movdqu xmm1, xmmword ptr [rcx] + movdqu xmm2, xmmword ptr [rdx] + movdqu xmm0, xmmword ptr [r8] +IFDEF ALTER_SHA256 + sha256rnds2 xmm2, xmm1, xmm0 + movdqu xmm1, xmm2 +ELSE + sha256rnds2 xmm1, xmm2, xmm0 +ENDIF + movdqu xmmword ptr [r8], xmm1 + ret +op_sha256rnds2_reg ENDP + +op_sha256rnds2_mem PROC FRAME + .endprolog + movdqa xmm1, xmmword ptr [rcx] + movdqa xmm0, xmmword ptr [r8] +IFDEF ALTER_SHA256 + sha256rnds2 xmm0, xmmword ptr [rdx], xmm0 + movdqa xmm1, xmm0 +ELSE + sha256rnds2 xmm1, xmmword ptr [rdx], xmm0 +ENDIF + movdqa xmmword ptr [r8], xmm1 + ret +op_sha256rnds2_mem ENDP + +op_sha256rnds2_mem_r8 PROC FRAME + .endprolog + movdqa xmm3, xmmword ptr [rcx] + movdqa xmm0, xmmword ptr [rdx] + sha256rnds2 xmm3, xmmword ptr [r8], xmm0 + movdqa xmmword ptr [r8], xmm3 + ret +op_sha256rnds2_mem_r8 ENDP + +; Aliasing: dst == src (xmm1 == xmm2) with xmm0 from [rdx]. +op_sha256rnds2_self_src PROC FRAME + .endprolog + movdqu xmm1, xmmword ptr [rcx] + movdqu xmm0, xmmword ptr [rdx] + sha256rnds2 xmm1, xmm1, xmm0 + movdqu xmmword ptr [r8], xmm1 + ret +op_sha256rnds2_self_src ENDP + +; Aliasing: dst == implicit xmm0 (xmm1 == xmm0) with src from [rdx]. +op_sha256rnds2_dst_xmm0 PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm2, xmmword ptr [rdx] + sha256rnds2 xmm0, xmm2, xmm0 + movdqu xmmword ptr [r8], xmm0 + ret +op_sha256rnds2_dst_xmm0 ENDP + +; Aliasing: src == implicit xmm0 (xmm2 == xmm0) with dst from [rcx]. +op_sha256rnds2_src_xmm0 PROC FRAME + .endprolog + movdqu xmm1, xmmword ptr [rcx] + movdqu xmm0, xmmword ptr [rdx] + sha256rnds2 xmm1, xmm0, xmm0 + movdqu xmmword ptr [r8], xmm1 + ret +op_sha256rnds2_src_xmm0 ENDP + +; Aliasing: dst == src == implicit xmm0. +op_sha256rnds2_all_xmm0 PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + sha256rnds2 xmm0, xmm0, xmm0 + movdqu xmmword ptr [r8], xmm0 + ret +op_sha256rnds2_all_xmm0 ENDP + +; --- SHA256MSG1 --- + +op_sha256msg1_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA256 + sha256msg2 xmm0, xmm1 +ELSE + sha256msg1 xmm0, xmm1 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha256msg1_reg ENDP + +op_sha256msg1_mem PROC FRAME + .endprolog + movdqa xmm4, xmmword ptr [rcx] + sha256msg1 xmm4, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm4 + ret +op_sha256msg1_mem ENDP + +op_sha256msg1_self PROC FRAME + .endprolog + movdqu xmm5, xmmword ptr [rcx] + sha256msg1 xmm5, xmm5 + movdqu xmmword ptr [r8], xmm5 + ret +op_sha256msg1_self ENDP + +; --- SHA256MSG2 (sequential lanes 2..3 depend on updated lanes 0..1) --- + +op_sha256msg2_reg PROC FRAME + .endprolog + movdqu xmm0, xmmword ptr [rcx] + movdqu xmm1, xmmword ptr [rdx] +IFDEF ALTER_SHA256 + sha256msg1 xmm0, xmm1 +ELSE + sha256msg2 xmm0, xmm1 +ENDIF + movdqu xmmword ptr [r8], xmm0 + ret +op_sha256msg2_reg ENDP + +op_sha256msg2_mem PROC FRAME + .endprolog + movdqa xmm2, xmmword ptr [rcx] + sha256msg2 xmm2, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm2 + ret +op_sha256msg2_mem ENDP + +op_sha256msg2_self PROC FRAME + .endprolog + movdqu xmm4, xmmword ptr [rcx] + sha256msg2 xmm4, xmm4 + movdqu xmmword ptr [r8], xmm4 + ret +op_sha256msg2_self ENDP + +; --- Multi-instruction pipeline using XMM0..XMM5, [r8] reload, and chained SHA256RNDS2 --- + +op_sha256_pipeline PROC FRAME + .endprolog + movdqa xmm0, xmmword ptr [rcx] + movdqa xmm1, xmmword ptr [rdx] + movdqa xmm2, xmm0 + sha256msg1 xmm2, xmm1 +IFDEF ALTER_SHA256 + sha256msg1 xmm2, xmm1 +ELSE + sha256msg2 xmm2, xmm1 +ENDIF + movdqa xmmword ptr [r8], xmm2 + movdqu xmm3, xmm0 + movdqa xmm4, xmm1 + movdqa xmm0, xmmword ptr [r8] + sha256rnds2 xmm3, xmm4, xmm0 + movdqa xmm5, xmm4 + sha256rnds2 xmm5, xmm3, xmm0 + movdqa xmmword ptr [r8], xmm5 + ret +op_sha256_pipeline ENDP + +; --- Discarded faulting m128 read must not be dropped under /O2 --- + +op_sha256_discarded_read PROC FRAME + .endprolog + movdqa xmm1, xmmword ptr [rcx] + movdqa xmm5, xmm1 + sha256msg1 xmm5, xmmword ptr [rdx] + movdqa xmmword ptr [r8], xmm1 + ret +op_sha256_discarded_read ENDP + +END diff --git a/tests/cpu/sha256_aot.def b/tests/cpu/sha256_aot.def new file mode 100644 index 000000000..1f971ef8b --- /dev/null +++ b/tests/cpu/sha256_aot.def @@ -0,0 +1,16 @@ +EXPORTS + op_sha256rnds2_reg + op_sha256rnds2_mem + op_sha256rnds2_mem_r8 + op_sha256rnds2_self_src + op_sha256rnds2_dst_xmm0 + op_sha256rnds2_src_xmm0 + op_sha256rnds2_all_xmm0 + op_sha256msg1_reg + op_sha256msg1_mem + op_sha256msg1_self + op_sha256msg2_reg + op_sha256msg2_mem + op_sha256msg2_self + op_sha256_pipeline + op_sha256_discarded_read diff --git a/tests/cpu/sha256_aot_check.py b/tests/cpu/sha256_aot_check.py new file mode 100644 index 000000000..5a76641d8 --- /dev/null +++ b/tests/cpu/sha256_aot_check.py @@ -0,0 +1,856 @@ +"""Differential, NIST FIPS 180-4, aliasing, /O2, mutation, and rejection checks for SHA-256 NI AOT lifting.""" + +import ctypes +import hashlib +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_sha256_aot import lift_code, translate # noqa: E402 + +EXPORTS = ( + "op_sha256rnds2_reg", + "op_sha256rnds2_mem", + "op_sha256rnds2_mem_r8", + "op_sha256rnds2_self_src", + "op_sha256rnds2_dst_xmm0", + "op_sha256rnds2_src_xmm0", + "op_sha256rnds2_all_xmm0", + "op_sha256msg1_reg", + "op_sha256msg1_mem", + "op_sha256msg1_self", + "op_sha256msg2_reg", + "op_sha256msg2_mem", + "op_sha256msg2_self", + "op_sha256_pipeline", + "op_sha256_discarded_read", +) + +UNALIGNED_SAFE_EXPORTS = ( + "op_sha256rnds2_reg", + "op_sha256rnds2_self_src", + "op_sha256rnds2_dst_xmm0", + "op_sha256rnds2_src_xmm0", + "op_sha256rnds2_all_xmm0", + "op_sha256msg1_reg", + "op_sha256msg1_self", + "op_sha256msg2_reg", + "op_sha256msg2_self", +) + +ALTERED_EXPORTS = ( + "op_sha256rnds2_reg", + "op_sha256rnds2_mem", + "op_sha256msg1_reg", + "op_sha256msg2_reg", + "op_sha256_pipeline", +) + +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) +MASK32 = 0xFFFFFFFF + +SHA256_K = ( + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2, +) + + +# --- Independent Python reference for SHA-256 NI instructions --- + +def _ror32(x, n): + x &= MASK32 + return ((x >> n) | (x << (32 - n))) & MASK32 + + +def _unpack4(buf): + return struct.unpack("<4I", buf) + + +def _pack4(w0, w1, w2, w3): + return struct.pack("<4I", w0 & MASK32, w1 & MASK32, w2 & MASK32, w3 & MASK32) + + +def _ch(e, f, g): + return ((e & f) ^ ((~e & MASK32) & g)) & MASK32 + + +def _maj(a, b, c): + return ((a & b) ^ (a & c) ^ (b & c)) & MASK32 + + +def _cap_s0(a): + return _ror32(a, 2) ^ _ror32(a, 13) ^ _ror32(a, 22) + + +def _cap_s1(e): + return _ror32(e, 6) ^ _ror32(e, 11) ^ _ror32(e, 25) + + +def _s0(x): + return _ror32(x, 7) ^ _ror32(x, 18) ^ ((x & MASK32) >> 3) + + +def _s1(x): + return _ror32(x, 17) ^ _ror32(x, 19) ^ ((x & MASK32) >> 10) + + +def ref_sha256rnds2(dst_bytes, src_bytes, wk_bytes): + h, g, d, c = _unpack4(dst_bytes) + f, e, b, a = _unpack4(src_bytes) + wk0, wk1, _, _ = _unpack4(wk_bytes) + + t1_0 = (_ch(e, f, g) + _cap_s1(e) + wk0 + h) & MASK32 + t2_0 = (_maj(a, b, c) + _cap_s0(a)) & MASK32 + a1 = (t1_0 + t2_0) & MASK32 + b1, c1, d1 = a, b, c + e1 = (t1_0 + d) & MASK32 + f1, g1, h1 = e, f, g + + t1_1 = (_ch(e1, f1, g1) + _cap_s1(e1) + wk1 + h1) & MASK32 + t2_1 = (_maj(a1, b1, c1) + _cap_s0(a1)) & MASK32 + a2 = (t1_1 + t2_1) & MASK32 + e2 = (t1_1 + d1) & MASK32 + return _pack4(e1, e2, a1, a2) + + +def ref_sha256msg1(dst_bytes, src_bytes): + w0, w1, w2, w3 = _unpack4(dst_bytes) + w4, _, _, _ = _unpack4(src_bytes) + return _pack4( + (w0 + _s0(w1)) & MASK32, + (w1 + _s0(w2)) & MASK32, + (w2 + _s0(w3)) & MASK32, + (w3 + _s0(w4)) & MASK32, + ) + + +def ref_sha256msg2(dst_bytes, src_bytes): + d0, d1, d2, d3 = _unpack4(dst_bytes) + _, _, s2, s3 = _unpack4(src_bytes) + w0 = (d0 + _s1(s2)) & MASK32 + w1 = (d1 + _s1(s3)) & MASK32 + w2 = (d2 + _s1(w0)) & MASK32 + w3 = (d3 + _s1(w1)) & MASK32 + return _pack4(w0, w1, w2, w3) + + +def reference(name, a, b, c, *, altered=False): + if name == "op_sha256rnds2_reg": + return ref_sha256rnds2(b, a, c) if altered else ref_sha256rnds2(a, b, c) + if name == "op_sha256rnds2_mem": + return ref_sha256rnds2(c, b, c) if altered else ref_sha256rnds2(a, b, c) + if name == "op_sha256rnds2_mem_r8": + return ref_sha256rnds2(a, c, b) + if name == "op_sha256rnds2_self_src": + return ref_sha256rnds2(a, a, b) + if name == "op_sha256rnds2_dst_xmm0": + return ref_sha256rnds2(a, b, a) + if name == "op_sha256rnds2_src_xmm0": + return ref_sha256rnds2(a, b, b) + if name == "op_sha256rnds2_all_xmm0": + return ref_sha256rnds2(a, a, a) + if name == "op_sha256msg1_reg": + return ref_sha256msg2(a, b) if altered else ref_sha256msg1(a, b) + if name == "op_sha256msg1_mem": + return ref_sha256msg1(a, b) + if name == "op_sha256msg1_self": + return ref_sha256msg1(a, a) + if name == "op_sha256msg2_reg": + return ref_sha256msg1(a, b) if altered else ref_sha256msg2(a, b) + if name == "op_sha256msg2_mem": + return ref_sha256msg2(a, b) + if name == "op_sha256msg2_self": + return ref_sha256msg2(a, a) + if name == "op_sha256_pipeline": + x2 = ref_sha256msg1(a, b) + x2 = ref_sha256msg1(x2, b) if altered else ref_sha256msg2(x2, b) + x3 = ref_sha256rnds2(a, b, x2) + return ref_sha256rnds2(b, x3, x2) + if name == "op_sha256_discarded_read": + return a + raise KeyError(name) + + +def all_triples(): + """Edge, carry-wrap, lane-isolation, FIPS IV, dirty-XMM0-upper, and deterministic random 16B triples.""" + z16 = b"\x00" * 16 + f16 = b"\xff" * 16 + fips_abef = _pack4(0x9B05688C, 0x510E527F, 0xBB67AE85, 0x6A09E667) + fips_cdgh = _pack4(0x5BE0CD19, 0x1F83D9AB, 0xA54FF53A, 0x3C6EF372) + triples = [ + (z16, z16, z16), + (f16, f16, f16), + (z16, f16, z16), + (f16, z16, f16), + (fips_cdgh, fips_abef, _pack4((0x61626380 + SHA256_K[0]) & MASK32, SHA256_K[1], 0xDEADBEEF, 0xCAFEBABE)), + # Same WK[63:0] with completely different XMM0[127:64] to prove upper 64 bits are ignored. + (fips_cdgh, fips_abef, _pack4((0x61626380 + SHA256_K[0]) & MASK32, SHA256_K[1], 0x00000000, 0x00000000)), + # Carry wraps and rotation boundaries across all lanes. + (_pack4(0xFFFFFFFF, 0x80000000, 0x00000001, 0x7FFFFFFF), + _pack4(0x00000001, 0x7FFFFFFF, 0xFFFFFFFF, 0x80000000), + _pack4(0xFFFFFFFF, 0x00000001, 0x55555555, 0xAAAAAAAA)), + *[ + (_pack4(*(0xA5A55A5A if j == i else 0 for j in range(4))), + _pack4(*(0x3C3CC3C3 if j == k else 0 for j in range(4))), + _pack4(*(0x96966969 if j == ((i + k) & 3) else 0 for j in range(4)))) + for i in range(4) for k in range(4) + ], + ] + rng = random.Random(0x5A256A07) + for _ in range(72): + triples.append((rng.randbytes(16), rng.randbytes(16), rng.randbytes(16))) + return triples + + +def alloc_guarded(payload, *, misalign=0): + size = 48 + len(GUARD_PRE) + len(payload) + len(GUARD_POST) + raw = ctypes.create_string_buffer(size) + base = ctypes.addressof(raw) + aligned = (base + len(GUARD_PRE) + 15) & ~15 + data_addr = aligned + misalign + pre_off = (data_addr - len(GUARD_PRE)) - base + data_off = data_addr - base + post_off = data_off + len(payload) + raw[pre_off:data_off] = GUARD_PRE + raw[data_off:post_off] = payload + raw[post_off:post_off + len(GUARD_POST)] = GUARD_POST + return raw, pre_off, data_off, post_off, data_addr + + +def invoke(fn, a, b, c=b"\x5a" * 16, *, a_misalign=0, b_misalign=0, out_misalign=0): + buf_a, a_pre, a_off, a_post, a_addr = alloc_guarded(a, misalign=a_misalign) + buf_b, b_pre, b_off, b_post, b_addr = alloc_guarded(b, misalign=b_misalign) + buf_out, o_pre, o_off, o_post, o_addr = alloc_guarded(c, misalign=out_misalign) + fn(a_addr, b_addr, o_addr) + assert buf_a.raw[a_pre:a_off] == GUARD_PRE and buf_a.raw[a_post:a_post + 16] == GUARD_POST, "input A guards corrupted" + assert buf_b.raw[b_pre:b_off] == GUARD_PRE and buf_b.raw[b_post:b_post + 16] == GUARD_POST, "input B guards corrupted" + assert buf_out.raw[o_pre:o_off] == GUARD_PRE and buf_out.raw[o_post:o_post + 16] == GUARD_POST, "output guards corrupted" + assert buf_a.raw[a_off:a_post] == a, "input A mutated unexpectedly" + assert buf_b.raw[b_off:b_post] == b, "input B mutated unexpectedly" + return buf_out.raw[o_off:o_post] + + +def invoke_aliased(fn, a, b, c, mode): + buf_a, a_pre, a_off, a_post, a_addr = alloc_guarded(a) + buf_b, b_pre, b_off, b_post, b_addr = alloc_guarded(b) + buf_out, o_pre, o_off, o_post, o_addr = alloc_guarded(c) + if mode == "rcx==rdx": + fn(a_addr, a_addr, o_addr) + res = buf_out.raw[o_off:o_post] + elif mode == "r8==rcx": + fn(a_addr, b_addr, a_addr) + res = buf_a.raw[a_off:a_post] + elif mode == "r8==rdx": + fn(a_addr, b_addr, b_addr) + res = buf_b.raw[b_off:b_post] + elif mode == "all": + fn(a_addr, a_addr, a_addr) + res = buf_a.raw[a_off:a_post] + else: + raise ValueError(f"unknown alias mode {mode}") + assert buf_a.raw[a_pre:a_off] == GUARD_PRE and buf_a.raw[a_post:a_post + 16] == GUARD_POST, f"{mode}: A guards corrupted" + assert buf_b.raw[b_pre:b_off] == GUARD_PRE and buf_b.raw[b_post:b_post + 16] == GUARD_POST, f"{mode}: B guards corrupted" + assert buf_out.raw[o_pre:o_off] == GUARD_PRE and buf_out.raw[o_post:o_post + 16] == GUARD_POST, f"{mode}: out guards corrupted" + return res + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_sha(lifted_lib): + if hasattr(lifted_lib, "host_has_sha"): + lifted_lib.host_has_sha.argtypes = [] + lifted_lib.host_has_sha.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_sha()) + try: + return " sha_ni" in Path("/proc/cpuinfo").read_text(encoding="ascii", errors="replace") + except OSError: + return False + + +def encode_seq(*instructions): + enc = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += enc.encode(ins, rip) + return enc.take_buffer() + + +def check_translator(original_path): + ret = Instruction.create(Code.RETNQ) + ld0 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld1 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)) + ld2 = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM2, MemoryOperand(R.R8)) + ld0_a = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + ld1_a = Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM1, MemoryOperand(R.R8)) + st0 = Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM0) + st1 = Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.R8), R.XMM1) + st1_a = Instruction.create_mem_reg(Code.MOVDQA_XMMM128_XMM, MemoryOperand(R.R8), R.XMM1) + + # Positive checks for all 3 SHA-256 NI instructions (reg & mem) + no . + accepted = 0 + src_reg, _ = lift_code( + "sha256rnds2_reg", 0x1000, + encode_seq(ld0, ld1, ld2, Instruction.create_reg_reg(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, R.XMM2), st1, ret), + ) + assert "xmm1 = op_sha256rnds2(xmm1, xmm2, xmm0);" in src_reg + assert "" not in src_reg + src_mem, _ = lift_code( + "sha256rnds2_mem", 0x1000, + encode_seq(ld0_a, ld1_a, Instruction.create_reg_mem(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX)), st1_a, ret), + ) + assert "xmm1 = op_sha256rnds2(xmm1, load128(rdx), xmm0);" in src_mem + accepted += 1 + + for code, helper in ( + (Code.SHA256MSG1_XMM_XMMM128, "op_sha256msg1"), + (Code.SHA256MSG2_XMM_XMMM128, "op_sha256msg2"), + ): + s_reg, _ = lift_code(f"{helper}_reg", 0x1000, encode_seq(ld0, ld1, Instruction.create_reg_reg(code, R.XMM0, R.XMM1), st0, ret)) + assert f"xmm0 = {helper}(xmm0, xmm1);" in s_reg + s_mem, _ = lift_code(f"{helper}_mem", 0x1000, encode_seq(ld0_a, Instruction.create_reg_mem(code, R.XMM0, MemoryOperand(R.RDX)), st0, ret)) + assert f"xmm0 = {helper}(xmm0, load128(rdx));" in s_mem + accepted += 1 + + # Negative rejection controls. + rep_ret = Instruction.create(Code.RETNQ) + rep_ret.has_rep_prefix = True + fs_ld = Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)) + fs_ld.segment_prefix = R.FS + + cases = [ + # SHA-1 rejections + ("sha1rnds4", (ld0, ld1, Instruction.create_reg_reg_u32(Code.SHA1RNDS4_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), st0, ret), + "unsupported SHA-1 instruction"), + ("sha1nexte", (ld0, ld1, Instruction.create_reg_reg(Code.SHA1NEXTE_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported SHA-1 instruction"), + ("sha1msg1", (ld0, ld1, Instruction.create_reg_reg(Code.SHA1MSG1_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported SHA-1 instruction"), + ("sha1msg2", (ld0, ld1, Instruction.create_reg_reg(Code.SHA1MSG2_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported SHA-1 instruction"), + # AES / PCLMUL rejections + ("aesenc", (ld0, ld1, Instruction.create_reg_reg(Code.AESENC_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported AES/PCLMUL instruction"), + ("aesdec", (ld0, ld1, Instruction.create_reg_reg(Code.AESDEC_XMM_XMMM128, R.XMM0, R.XMM1), st0, ret), + "unsupported AES/PCLMUL instruction"), + ("aeskeygenassist", (ld0, ld1, Instruction.create_reg_reg_u32(Code.AESKEYGENASSIST_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 1), st0, ret), + "unsupported AES/PCLMUL instruction"), + ("pclmulqdq", (ld0, ld1, Instruction.create_reg_reg_u32(Code.PCLMULQDQ_XMM_XMMM128_IMM8, R.XMM0, R.XMM1, 0), st0, ret), + "unsupported AES/PCLMUL instruction"), + # VEX / EVEX rejections + ("vex_vmovdqu", (Instruction.create_reg_mem(Code.VEX_VMOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), st0, ret), + "unsupported VEX encoding"), + ("vex_vpxor", (ld0, ld1, Instruction.create_reg_reg_reg(Code.VEX_VPXOR_XMM_XMM_XMMM128, R.XMM0, R.XMM0, R.XMM1), st0, ret), + "unsupported VEX encoding"), + ("evex_vmovdqu32", (Instruction.create_reg_mem(Code.EVEX_VMOVDQU32_XMM_K1Z_XMMM128, R.XMM0, MemoryOperand(R.RCX)), st0, ret), + "unsupported EVEX encoding"), + # Nonvolatile XMM6..15 + ("nonvol_xmm6_dst", (ld0, ld1, Instruction.create_reg_reg(Code.SHA256RNDS2_XMM_XMMM128, R.XMM6, R.XMM1), ret), + "nonvolatile vector register"), + ("nonvol_xmm15_src", (ld0, Instruction.create_reg_reg(Code.SHA256MSG1_XMM_XMMM128, R.XMM0, R.XMM15), st0, ret), + "nonvolatile vector register"), + # Undefined XMM reads — including undefined implicit XMM0 on SHA256RNDS2! + ("undef_implicit_xmm0_rnds2", (ld1, ld2, Instruction.create_reg_reg(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, R.XMM2), st1, ret), + "undefined implicit vector register xmm0"), + ("undef_dst_rnds2", (ld0, ld2, Instruction.create_reg_reg(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, R.XMM2), st1, ret), + "undefined vector register xmm1"), + ("undef_src_rnds2", (ld0, ld1, Instruction.create_reg_reg(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, R.XMM3), st1, ret), + "undefined vector register xmm3"), + ("undef_dst_msg1", (ld1, Instruction.create_reg_reg(Code.SHA256MSG1_XMM_XMMM128, R.XMM3, R.XMM1), ret), + "undefined vector register xmm3"), + ("undef_src_msg2", (ld0, Instruction.create_reg_reg(Code.SHA256MSG2_XMM_XMMM128, R.XMM0, R.XMM4), st0, ret), + "undefined vector register xmm4"), + ("undef_store", (st0, ret), "undefined vector register xmm0"), + # Alignment / displacement / addressing / store-base / prefix / control-flow / ret checks + ("unaligned_movdqa_load", (Instruction.create_reg_mem(Code.MOVDQA_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, displ=8, displ_size=1)), st0, ret), + "unaligned 16-byte memory operand"), + ("unaligned_movdqa_store", (ld0, Instruction.create_mem_reg(Code.MOVDQA_XMMM128_XMM, MemoryOperand(R.R8, displ=4, displ_size=1), R.XMM0), ret), + "unaligned 16-byte memory operand"), + ("unaligned_sha256_mem", (ld0, ld1, Instruction.create_reg_mem(Code.SHA256RNDS2_XMM_XMMM128, R.XMM1, MemoryOperand(R.RDX, displ=8, displ_size=1)), st1, ret), + "unaligned 16-byte memory operand"), + ("displaced_movdqu", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, displ=16, displ_size=1)), st0, ret), + "unsupported displaced/out-of-buffer memory operand"), + ("displaced_sha256msg2", (ld0, Instruction.create_reg_mem(Code.SHA256MSG2_XMM_XMMM128, R.XMM0, MemoryOperand(R.RDX, displ=16, displ_size=1)), st0, ret), + "unsupported displaced/out-of-buffer memory operand"), + ("indexed_mem", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX, index=R.RDX)), st0, ret), + "unsupported memory operand"), + ("rip_rel_mem", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RIP, displ=0x1100, displ_size=4)), st0, ret), + "unsupported memory operand"), + ("non_arg_base_rax", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RAX)), st0, ret), + "unsupported memory base"), + ("nonvol_base_rbx", (Instruction.create_reg_mem(Code.MOVDQU_XMM_XMMM128, R.XMM0, MemoryOperand(R.RBX)), st0, ret), + "nonvolatile GPR base"), + ("store_to_rcx", (ld0, Instruction.create_mem_reg(Code.MOVDQU_XMMM128_XMM, MemoryOperand(R.RCX), R.XMM0), ret), + "store outside output buffer r8"), + ("store_to_rdx_movdqa", (ld0_a, Instruction.create_mem_reg(Code.MOVDQA_XMMM128_XMM, MemoryOperand(R.RDX), R.XMM0), ret), + "store outside output buffer r8"), + ("prefix_segment_fs", (fs_ld, st0, ret), "unsupported instruction prefix"), + ("prefix_rep_ret", (ld0, st0, rep_ret), "unsupported instruction prefix"), + ("branch_jmp", (ld0, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), st0, ret), + "unsupported control-flow instruction"), + ("missing_ret", (ld0, ld1, Instruction.create_reg_reg(Code.SHA256MSG1_XMM_XMMM128, R.XMM0, R.XMM1), st0), + "missing terminal ret"), + ("trailing_after_ret", (ld0, st0, ret, ld0), "unreachable instruction after ret"), + ] + for label, seq, reason in cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + # End-to-end PE-patched rejections + CLI non-traceback rejection. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_sha256_pipeline") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("Q", bit_len) + + h = [ + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, + ] + for off in range(0, len(padded), 64): + words = list(struct.unpack(">16I", padded[off:off + 64])) + msgs = [_pack4(*words[4 * i:4 * i + 4]) for i in range(4)] + for k in range(4, 16): + t1 = invoke(msg1, msgs[k - 4], msgs[k - 3]) + # W[4k-7 .. 4k-4] = (msgs[k-2].w[1..3], msgs[k-1].w[0]). + prev2 = _unpack4(msgs[k - 2]) + prev1 = _unpack4(msgs[k - 1]) + w_m7 = _pack4(prev2[1], prev2[2], prev2[3], prev1[0]) + t2 = _add4(t1, w_m7) + msgs.append(invoke(msg2, t2, msgs[k - 1])) + sched = [w for m in msgs for w in _unpack4(m)] + + abef = _pack4(h[5], h[4], h[1], h[0]) + cdgh = _pack4(h[7], h[6], h[3], h[2]) + for r in range(0, 64, 2): + # Put non-zero dirty words in XMM0[127:64] to prove SHA256RNDS2 ignores them. + wk = _pack4( + (sched[r] + SHA256_K[r]) & MASK32, + (sched[r + 1] + SHA256_K[r + 1]) & MASK32, + 0xDEADBEEF ^ r, + 0xCAFEBABE ^ (r << 8), + ) + next_abef = invoke(rnds2, cdgh, abef, wk) + cdgh, abef = abef, next_abef + + f, e, b, a = _unpack4(abef) + hh, g, d, c = _unpack4(cdgh) + for i, delta in enumerate((a, b, c, d, e, f, g, hh)): + h[i] = (h[i] + delta) & MASK32 + + return struct.pack(">8I", *h).hex() + + +FIPS_180_4_VECTORS = ( + (b"", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), + (b"abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"), + ( + b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", + ), + ( + b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" + b"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", + "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1", + ), + (b"a" * 1000, hashlib.sha256(b"a" * 1000).hexdigest()), +) + + +def check_discarded_read(funcs, label): + payload = all_triples()[4][0] + ba, a_pre, a_off, a_post, a_addr = alloc_guarded(payload) + bo_ok, o_pre, o_off, o_post, o_addr = alloc_guarded(b"\x5a" * 16) + funcs["op_sha256_discarded_read"](a_addr, a_addr, o_addr) + assert bo_ok.raw[o_off:o_post] == payload, f"{label} discarded_read(valid) mismatch" + + bo_null, o2_pre, o2_off, o2_post, o2_addr = alloc_guarded(b"\x5a" * 16) + try: + funcs["op_sha256_discarded_read"](a_addr, 0, o2_addr) + except OSError as exc: + if "access violation reading" not in str(exc).lower(): + raise AssertionError(f"{label} discarded_read(NULL) unexpected error: {exc}") from exc + else: + raise AssertionError(f"{label} op_sha256_discarded_read(NULL) dropped faulting m128 read") + assert bo_null.raw[o2_off:o2_post] == b"\x5a" * 16, f"{label} wrote output after fault" + del ba + + +def check_lifted_unconditional(lifted, altered_lifted, triples): + total = 0 + for name in EXPORTS: + for index, (a, b, c) in enumerate(triples): + want = reference(name, a, b, c) + got = invoke(lifted[name], a, b, c) + if got != want: + raise AssertionError(f"lifted {name} case {index}: got {got.hex()} != exp {want.hex()}") + total += 1 + + check_discarded_read(lifted, "lifted") + + # Verify dirty XMM0[127:64] produces identical SHA256RNDS2 results. + a4, b4, c4 = triples[4] + a5, b5, c5 = triples[5] + assert invoke(lifted["op_sha256rnds2_reg"], a4, b4, c4) == invoke(lifted["op_sha256rnds2_reg"], a5, b5, c5) + + # Unaligned buffers on movdqu-only exports. + a, b, c = triples[4] + for name in UNALIGNED_SAFE_EXPORTS: + want = reference(name, a, b, c) + for mis in ((1, 0, 0), (0, 3, 0), (0, 0, 5), (7, 5, 3)): + got = invoke(lifted[name], a, b, c, a_misalign=mis[0], b_misalign=mis[1], out_misalign=mis[2]) + if got != want: + raise AssertionError(f"lifted {name} misalign {mis}: got {got.hex()} != exp {want.hex()}") + total += 1 + + # Pointer aliasing checks (rcx==rdx, r8==rcx, r8==rdx, all). + for name in ( + "op_sha256rnds2_reg", "op_sha256rnds2_mem", "op_sha256rnds2_mem_r8", + "op_sha256msg1_reg", "op_sha256msg1_mem", + "op_sha256msg2_reg", "op_sha256msg2_mem", + "op_sha256_pipeline", + ): + for mode in ("rcx==rdx", "r8==rcx", "r8==rdx", "all"): + ea = a + eb = a if mode in ("rcx==rdx", "all") else b + ec = a if mode in ("r8==rcx", "all") else (b if mode == "r8==rdx" else c) + want = reference(name, ea, eb, ec) + got = invoke_aliased(lifted[name], a, b, c, mode) + if got != want: + raise AssertionError(f"lifted {name} alias {mode}: got {got.hex()} != exp {want.hex()}") + total += 1 + + # Full NIST FIPS 180-4 SHA-256 digests (single-block & multi-block) through reg and mem exports. + for use_mem in (False, True): + for msg, expected_hex in FIPS_180_4_VECTORS: + assert hashlib.sha256(msg).hexdigest() == expected_hex + got_hex = sha256_digest_via_funcs(lifted, msg, use_mem=use_mem) + if got_hex != expected_hex: + raise AssertionError(f"FIPS 180-4 SHA-256 (mem={use_mem}) on len={len(msg)}: {got_hex} != {expected_hex}") + total += 1 + + # Altered lifted build matches altered reference and diverges from original lifted. + for name in ALTERED_EXPORTS: + changed = 0 + for a_in, b_in, c_in in triples[:24]: + orig = invoke(lifted[name], a_in, b_in, c_in) + alt = invoke(altered_lifted[name], a_in, b_in, c_in) + want_alt = reference(name, a_in, b_in, c_in, altered=True) + if alt != want_alt: + raise AssertionError(f"altered_lifted {name}: got {alt.hex()} != exp {want_alt.hex()}") + changed += alt != orig + if not changed: + raise AssertionError(f"altered_lifted did not diverge on {name}") + + # Faulty mutant models (including parallel SHA256MSG2 missing sequential w0/w1 dependency!). + def _mut_msg2_parallel(x, y, _z): + d0, d1, d2, d3 = _unpack4(x) + _, _, s2, s3 = _unpack4(y) + return _pack4( + (d0 + _s1(s2)) & MASK32, + (d1 + _s1(s3)) & MASK32, + (d2 + _s1(d0)) & MASK32, # bug: uses un-updated d0 instead of w0 + (d3 + _s1(d1)) & MASK32, # bug: uses un-updated d1 instead of w1 + ) + + def _mut_msg1_bad_src_lane(x, y, _z): + w0, w1, w2, w3 = _unpack4(x) + _, w5, _, _ = _unpack4(y) + return _pack4((w0 + _s0(w1)) & MASK32, (w1 + _s0(w2)) & MASK32, (w2 + _s0(w3)) & MASK32, (w3 + _s0(w5)) & MASK32) + + def _mut_rnds2_swap_wk(x, y, z): + wk0, wk1, wk2, wk3 = _unpack4(z) + return ref_sha256rnds2(x, y, _pack4(wk1, wk0, wk2, wk3)) + + def _mut_rnds2_swap_state(x, y, z): + return ref_sha256rnds2(y, x, z) + + def _mut_rnds2_wrong_sigma(x, y, z): + h, g, d, c = _unpack4(x) + f, e, b, a = _unpack4(y) + wk0, wk1, _, _ = _unpack4(z) + t1_0 = (_ch(e, f, g) + _cap_s0(e) + wk0 + h) & MASK32 # bug: Sigma0 instead of Sigma1 + t2_0 = (_maj(a, b, c) + _cap_s0(a)) & MASK32 + a1 = (t1_0 + t2_0) & MASK32 + e1 = (t1_0 + d) & MASK32 + t1_1 = (_ch(e1, e, f) + _cap_s1(e1) + wk1 + g) & MASK32 + t2_1 = (_maj(a1, a, b) + _cap_s0(a1)) & MASK32 + return _pack4(e1, (t1_1 + c) & MASK32, a1, (t1_1 + t2_1) & MASK32) + + mutants = ( + ("op_sha256rnds2_reg", _mut_rnds2_swap_wk), + ("op_sha256rnds2_reg", _mut_rnds2_swap_state), + ("op_sha256rnds2_reg", _mut_rnds2_wrong_sigma), + ("op_sha256msg1_reg", lambda x, y, z: ref_sha256msg2(x, y)), + ("op_sha256msg1_reg", _mut_msg1_bad_src_lane), + ("op_sha256msg2_reg", lambda x, y, z: ref_sha256msg1(x, y)), + ("op_sha256msg2_reg", _mut_msg2_parallel), + ("op_sha256_pipeline", lambda x, y, z: ref_sha256rnds2(x, y, z)), + ) + for name, wrong in mutants: + if not any(invoke(lifted[name], x, y, z) != wrong(x, y, z) for x, y, z in triples[:32]): + raise AssertionError(f"mutant on {name} agreed with lifted on every triple") + + return total, len(mutants) + + +def compile_o2_and_verify(original_path, cxx_path, triples): + source_text, _ = translate(original_path, list(EXPORTS)) + with TemporaryDirectory() as folder: + tmp = Path(folder) + cpp_path = tmp / "sha256_aot_o2.cpp" + dll_path = tmp / "sha256_aot_o2.dll" + cpp_path.write_text(source_text, encoding="utf-8") + proc = subprocess.run( + [str(cxx_path), "/nologo", "/O2", "/W4", "/WX", "/LD", str(cpp_path), + f"/Fo{tmp / 'sha256_aot_o2.obj'}", f"/Fe{dll_path}"], + capture_output=True, + text=True, + errors="replace", + ) + if proc.returncode != 0: + raise AssertionError(f"/O2 compile failed:\n{proc.stdout}\n{proc.stderr}") + o2_lib, o2_fns = bind(dll_path, "lifted_") + try: + cases = 0 + for name in EXPORTS: + for idx, (a, b, c) in enumerate(triples[:32]): + want = reference(name, a, b, c) + got = invoke(o2_fns[name], a, b, c) + if got != want: + raise AssertionError(f"lifted_o2 {name} case {idx}: {got.hex()} != {want.hex()}") + cases += 1 + check_discarded_read(o2_fns, "lifted_o2") + assert sha256_digest_via_funcs(o2_fns, FIPS_180_4_VECTORS[2][0], use_mem=False) == FIPS_180_4_VECTORS[2][1] + return cases + finally: + o2_fns.clear() + unload_lib(o2_lib) + + +def check_native_differential(native, lifted, altered, altered_lifted, triples): + total = 0 + for name in EXPORTS: + for index, (a, b, c) in enumerate(triples): + nat = invoke(native[name], a, b, c) + lif = invoke(lifted[name], a, b, c) + if nat != lif: + raise AssertionError(f"native vs lifted {name} case {index}: native={nat.hex()} lifted={lif.hex()}") + total += 1 + + check_discarded_read(native, "native") + + a, b, c = triples[4] + for name in UNALIGNED_SAFE_EXPORTS: + for mis in ((1, 0, 0), (0, 3, 0), (0, 0, 5), (7, 5, 3)): + nat = invoke(native[name], a, b, c, a_misalign=mis[0], b_misalign=mis[1], out_misalign=mis[2]) + lif = invoke(lifted[name], a, b, c, a_misalign=mis[0], b_misalign=mis[1], out_misalign=mis[2]) + if nat != lif: + raise AssertionError(f"native vs lifted {name} misalign {mis}: native={nat.hex()} lifted={lif.hex()}") + total += 1 + + for name in ( + "op_sha256rnds2_reg", "op_sha256rnds2_mem", "op_sha256rnds2_mem_r8", + "op_sha256msg1_reg", "op_sha256msg1_mem", + "op_sha256msg2_reg", "op_sha256msg2_mem", + "op_sha256_pipeline", + ): + for mode in ("rcx==rdx", "r8==rcx", "r8==rdx", "all"): + nat = invoke_aliased(native[name], a, b, c, mode) + lif = invoke_aliased(lifted[name], a, b, c, mode) + if nat != lif: + raise AssertionError(f"native vs lifted {name} alias {mode}: native={nat.hex()} lifted={lif.hex()}") + total += 1 + + for name in ALTERED_EXPORTS: + changed = 0 + for a_in, b_in, c_in in triples[:24]: + alt_nat = invoke(altered[name], a_in, b_in, c_in) + alt_lif = invoke(altered_lifted[name], a_in, b_in, c_in) + if alt_lif != alt_nat: + raise AssertionError(f"altered {name}: lifted={alt_lif.hex()} != native={alt_nat.hex()}") + orig_nat = invoke(native[name], a_in, b_in, c_in) + changed += alt_nat != orig_nat + if not changed: + raise AssertionError(f"altered native build did not diverge on {name}") + + return total + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path, cxx_path = (Path(p) for p in sys.argv[1:6]) + + accepted, rejected, pe_rejected = check_translator(original_path) + print(f"{accepted} SHA-256 NI forms accepted; {rejected} IR + {pe_rejected} PE + CLI rejection controls passed") + + lifted_lib, lifted = bind(lifted_path, "lifted_") + alt_lifted_lib, altered_lifted = bind(altered_lifted_path, "lifted_") + triples = all_triples() + try: + lifted_total, mutant_count = check_lifted_unconditional(lifted, altered_lifted, triples) + o2_total = compile_o2_and_verify(original_path, cxx_path, triples) + print( + f"{lifted_total} portable lifted + {o2_total} /O2 cases (incl. NIST FIPS 180-4 single/multi-block & aliasing) " + f"passed; {mutant_count} mutants + {len(ALTERED_EXPORTS)} altered-build controls caught" + ) + + if not host_has_sha(lifted_lib): + print("Host lacks CPUID.07H.00H:EBX[29] (SHA-NI); skipping native differential check") + sys.exit(77) + + orig_lib, native = bind(original_path, "") + alt_lib, altered = bind(altered_path, "") + try: + native_total = check_native_differential(native, lifted, altered, altered_lifted, triples) + print(f"{native_total} native vs lifted SHA-NI differential cases matched bit for bit") + finally: + native.clear() + altered.clear() + unload_lib(orig_lib) + unload_lib(alt_lib) + finally: + lifted.clear() + altered_lifted.clear() + unload_lib(lifted_lib) + unload_lib(alt_lifted_lib) + + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_sha256_aot.py b/tools/cpu_sha256_aot.py new file mode 100644 index 000000000..109d8a5d3 --- /dev/null +++ b/tools/cpu_sha256_aot.py @@ -0,0 +1,420 @@ +"""Lift bounded Windows x64 leaf functions using Intel SHA-256 NI instructions to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat host pointers to caller-owned 16-byte buffers +(rcx and rdx are inputs, r8 is the output/in-out scratch). XMM0..XMM5 are modeled +as portable 128-bit value structs (four 32-bit lanes, pure portable C++ without +). Only legacy encodings are accepted; VEX, EVEX, and other +non-legacy encodings are rejected. + +Supported SHA-256 NI instructions (docs/coverage/x64_zen2.tsv group Crypto): + - SHA256RNDS2 xmm1, xmm2/m128, (NP 0F 38 CB /r): two SHA-256 rounds + using implicit XMM0[63:0] as (W1+K1 : W0+K0), ignoring XMM0[127:64] + - SHA256MSG1 xmm1, xmm2/m128 (NP 0F 38 CC /r): intermediate SHA-256 + message schedule (adds sigma0(W[i+1]) using src[31:0] for lane 3) + - SHA256MSG2 xmm1, xmm2/m128 (NP 0F 38 CD /r): final SHA-256 message + schedule with sequential lanes 2..3 depending on updated lanes 0..1 + +Transport / ABI glue: + - movdqu (128-bit flat [rcx|rdx|r8] load, [r8] store, reg-reg copy) + - movdqa (16-byte-aligned flat [rcx|rdx|r8] load, [r8] store, reg-reg copy) + - terminal ret + +SHA-1 instructions, AES/PCLMUL instructions, VEX/EVEX encodings, nonvolatile +XMM6..XMM15, undefined XMM reads (including undefined implicit XMM0 on +SHA256RNDS2), unaligned movdqa/m128, non-flat/displaced/indexed/out-of-buffer +memory, stores outside [r8], instruction prefixes, branches, missing ret, and +trailing instructions after ret are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +VOLATILE_XMM = {getattr(R, f"XMM{i}"): i for i in range(6)} +NONVOLATILE_VEC = ( + {getattr(R, f"XMM{i}") for i in range(6, 32)} + | {getattr(R, f"YMM{i}") for i in range(32)} + | {getattr(R, f"ZMM{i}") for i in range(32)} +) +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +SHA256_BINARY_CODES = { + Code.SHA256MSG1_XMM_XMMM128: "op_sha256msg1", + Code.SHA256MSG2_XMM_XMMM128: "op_sha256msg2", +} + +SHA1_REJECT_CODES = { + Code.SHA1RNDS4_XMM_XMMM128_IMM8, + Code.SHA1NEXTE_XMM_XMMM128, + Code.SHA1MSG1_XMM_XMMM128, + Code.SHA1MSG2_XMM_XMMM128, +} + +AES_PCLMUL_REJECT_CODES = { + Code.AESENC_XMM_XMMM128, + Code.AESENCLAST_XMM_XMMM128, + Code.AESDEC_XMM_XMMM128, + Code.AESDECLAST_XMM_XMMM128, + Code.AESIMC_XMM_XMMM128, + Code.AESKEYGENASSIST_XMM_XMMM128_IMM8, + Code.PCLMULQDQ_XMM_XMMM128_IMM8, +} + +LOAD_CODES = { + Code.MOVDQU_XMM_XMMM128: False, + Code.MOVDQA_XMM_XMMM128: True, +} + +STORE_CODES = { + Code.MOVDQU_XMMM128_XMM: False, + Code.MOVDQA_XMMM128_XMM: True, +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.SHA256RNDS2_XMM_XMMM128, + *SHA256_BINARY_CODES, + *LOAD_CODES, + *STORE_CODES, +} + + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_sha() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast(info[1]) & (1u << 29)) != 0u ? 1u : 0u; +} +#endif + +using word = std::uint64_t; + +struct Vec128 { + std::uint32_t w[4]; +}; + +// Guest reads can fault even when the translated result is dead. Keep surrounding guest +// writes on their original side of the read when the compiler inlines these helpers. +static inline Vec128 load128(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + Vec128 out{}; + std::memcpy(out.w, reinterpret_cast(address), sizeof(out.w)); + const volatile Vec128 observed = out; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {{observed.w[0], observed.w[1], observed.w[2], observed.w[3]}}; +} + +static inline void store128(word address, const Vec128& v) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), v.w, sizeof(v.w)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline std::uint32_t ror32(std::uint32_t x, unsigned n) { + return (x >> n) | (x << (32u - n)); +} + +static inline std::uint32_t sha256_ch(std::uint32_t e, std::uint32_t f, std::uint32_t g) { + return (e & f) ^ ((~e) & g); +} + +static inline std::uint32_t sha256_maj(std::uint32_t a, std::uint32_t b, std::uint32_t c) { + return (a & b) ^ (a & c) ^ (b & c); +} + +static inline std::uint32_t sha256_cap_sigma0(std::uint32_t a) { + return ror32(a, 2u) ^ ror32(a, 13u) ^ ror32(a, 22u); +} + +static inline std::uint32_t sha256_cap_sigma1(std::uint32_t e) { + return ror32(e, 6u) ^ ror32(e, 11u) ^ ror32(e, 25u); +} + +static inline std::uint32_t sha256_sigma0(std::uint32_t x) { + return ror32(x, 7u) ^ ror32(x, 18u) ^ (x >> 3u); +} + +static inline std::uint32_t sha256_sigma1(std::uint32_t x) { + return ror32(x, 17u) ^ ror32(x, 19u) ^ (x >> 10u); +} + +static inline Vec128 op_sha256rnds2(const Vec128& dst, const Vec128& src, const Vec128& wk) { + std::uint32_t a = src.w[3]; + std::uint32_t b = src.w[2]; + std::uint32_t c = dst.w[3]; + std::uint32_t d = dst.w[2]; + std::uint32_t e = src.w[1]; + std::uint32_t f = src.w[0]; + std::uint32_t g = dst.w[1]; + std::uint32_t h = dst.w[0]; + + const std::uint32_t t1_0 = sha256_ch(e, f, g) + sha256_cap_sigma1(e) + wk.w[0] + h; + const std::uint32_t t2_0 = sha256_maj(a, b, c) + sha256_cap_sigma0(a); + const std::uint32_t a1 = t1_0 + t2_0; + const std::uint32_t b1 = a; + const std::uint32_t c1 = b; + const std::uint32_t d1 = c; + const std::uint32_t e1 = t1_0 + d; + const std::uint32_t f1 = e; + const std::uint32_t g1 = f; + const std::uint32_t h1 = g; + + const std::uint32_t t1_1 = sha256_ch(e1, f1, g1) + sha256_cap_sigma1(e1) + wk.w[1] + h1; + const std::uint32_t t2_1 = sha256_maj(a1, b1, c1) + sha256_cap_sigma0(a1); + const std::uint32_t a2 = t1_1 + t2_1; + const std::uint32_t e2 = t1_1 + d1; + + return {{e1, e2, a1, a2}}; +} + +static inline Vec128 op_sha256msg1(const Vec128& dst, const Vec128& src) { + return {{ + dst.w[0] + sha256_sigma0(dst.w[1]), + dst.w[1] + sha256_sigma0(dst.w[2]), + dst.w[2] + sha256_sigma0(dst.w[3]), + dst.w[3] + sha256_sigma0(src.w[0]), + }}; +} + +static inline Vec128 op_sha256msg2(const Vec128& dst, const Vec128& src) { + const std::uint32_t w0 = dst.w[0] + sha256_sigma1(src.w[2]); + const std::uint32_t w1 = dst.w[1] + sha256_sigma1(src.w[3]); + const std::uint32_t w2 = dst.w[2] + sha256_sigma1(w0); + const std::uint32_t w3 = dst.w[3] + sha256_sigma1(w1); + return {{w0, w1, w2, w3}}; +} +""" + + +def vec_index(register, ins): + """Map volatile XMM0..XMM5 to an index, rejecting nonvolatile and unsupported registers.""" + if register in VOLATILE_XMM: + return VOLATILE_XMM[register] + if register in NONVOLATILE_VEC: + raise ValueError(f"nonvolatile vector register {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported vector register {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, *, aligned=False, store=False): + """Lower a flat zero-displacement 16-byte [rcx|rdx|r8] memory operand.""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported memory base {base} at RVA {ins.ip:#x}: {ins}") + if MemorySizeExt.size(ins.memory_size) != 16: + raise ValueError(f"unsupported memory width at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"store outside output buffer r8 at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & ((1 << 64) - 1) + if aligned and disp % 16 != 0: + raise ValueError(f"unaligned 16-byte memory operand at RVA {ins.ip:#x}: {ins}") + if disp != 0: + raise ValueError(f"unsupported displaced/out-of-buffer memory operand at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line SHA-256 NI leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + used = set() + defined = set() + statements = [] + returned = False + + def read_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + if idx not in defined: + raise ValueError(f"undefined vector register xmm{idx} at RVA {ins.ip:#x}: {ins}") + used.add(idx) + return f"xmm{idx}" + + def write_vec(op_index, ins): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + idx = vec_index(ins.op_register(op_index), ins) + used.add(idx) + return idx, f"xmm{idx}" + + def vec_src128(op_index, ins, *, aligned=False): + if ins.op_kind(op_index) == OpKind.MEMORY: + return f"load128({flat_address(ins, aligned=aligned, store=False)})" + return read_vec(op_index, ins) + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ( + ins.has_lock_prefix + or ins.has_rep_prefix + or ins.has_repne_prefix + or ins.has_segment_prefix + or ins.has_xacquire_prefix + or ins.has_xrelease_prefix + ): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + op_code = ins.op_code() + if ( + op_code.encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding != EncodingKind.LEGACY: + raise ValueError(f"unsupported non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if ins.code in SHA1_REJECT_CODES: + raise ValueError(f"unsupported SHA-1 instruction at RVA {ins.ip:#x}: {ins}") + if ins.code in AES_PCLMUL_REJECT_CODES: + raise ValueError(f"unsupported AES/PCLMUL instruction at RVA {ins.ip:#x}: {ins}") + if ins.flow_control not in (FlowControl.NEXT, FlowControl.RETURN): + raise ValueError(f"unsupported control-flow instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + statements.append("return;") + returned = True + + elif ins.code == Code.SHA256RNDS2_XMM_XMMM128: + if 0 not in defined: + raise ValueError(f"undefined implicit vector register xmm0 at RVA {ins.ip:#x}: {ins}") + used.add(0) + dst = read_vec(0, ins) + src = vec_src128(1, ins, aligned=True) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = op_sha256rnds2({dst}, {src}, xmm0);") + defined.add(dst_idx) + + elif ins.code in SHA256_BINARY_CODES: + dst = read_vec(0, ins) + src = vec_src128(1, ins, aligned=True) + dst_idx, dst_name = write_vec(0, ins) + helper = SHA256_BINARY_CODES[ins.code] + statements.append(f"{dst_name} = {helper}({dst}, {src});") + defined.add(dst_idx) + + elif ins.code in LOAD_CODES: + aligned = LOAD_CODES[ins.code] + src = vec_src128(1, ins, aligned=aligned) + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + + elif ins.code in STORE_CODES: + aligned = STORE_CODES[ins.code] + src = read_vec(1, ins) + if ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, aligned=aligned, store=True) + statements.append(f"store128({addr}, {src});") + else: + dst_idx, dst_name = write_vec(0, ins) + statements.append(f"{dst_name} = {src};") + defined.add(dst_idx) + + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [f" Vec128 xmm{idx}{{}};" for idx in sorted(used)] + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, args.exports.split(",")) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From 6a1272669763b464827a507e6b9b74041d11f7c1 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 20:50:59 +0200 Subject: [PATCH 089/232] cpu: add dedicated cpu_bmi1_aot lifter for BLSI, BLSMSK, and BLSR (#2409) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 24 ++ tests/cpu/bmi1_aot.asm | 252 ++++++++++++++ tests/cpu/bmi1_aot.def | 22 ++ tests/cpu/bmi1_aot_check.py | 634 ++++++++++++++++++++++++++++++++++++ tools/cpu_bmi1_aot.py | 584 +++++++++++++++++++++++++++++++++ 5 files changed, 1516 insertions(+) create mode 100644 tests/cpu/bmi1_aot.asm create mode 100644 tests/cpu/bmi1_aot.def create mode 100644 tests/cpu/bmi1_aot_check.py create mode 100644 tools/cpu_bmi1_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index af01de3ca..3e4604d1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5919,6 +5919,30 @@ if(EXISTS "${INTAKE_PYTHON}") SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi2_shift.txt") + # cpu_aot_bmi1_bit + set(cpu_bmi1_aot_exports + "op_blsi32,op_blsi64,op_blsmsk32,op_blsmsk64,op_blsr32,op_blsr64," + "op_blsi32_mem,op_blsi64_mem,op_blsmsk32_mem,op_blsmsk64_mem,op_blsr32_mem,op_blsr64_mem," + "op_blsi32_flags,op_blsi64_flags,op_blsmsk32_flags,op_blsmsk64_flags," + "op_blsr32_flags,op_blsr64_flags,op_blsr64_mem_flags," + "op_r8_source_then_store,op_bmi1_discarded_read") + string(CONCAT cpu_bmi1_aot_exports ${cpu_bmi1_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_bmi1_aot_${variant} bmi1_aot) + cpu_translation(cpu_bmi1_aot_${variant} cpu_bmi1_aot "${cpu_bmi1_aot_exports}") + endforeach() + target_compile_definitions(cpu_bmi1_aot_altered PRIVATE ALTER_BMI1) + add_test(NAME cpu_aot_bmi1_bit COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/bmi1_aot_check.py" + "$" + "$" + "$" + "$" + "${CMAKE_CXX_COMPILER}") + set_tests_properties(cpu_aot_bmi1_bit PROPERTIES + SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_bmi1_bit.txt") + cpu_asm_fixture(cpu_sse2_packed_cvt sse2_packed_cvt) target_sources(cpu_sse2_packed_cvt PRIVATE tests/cpu/sse2_mxcsr_test.asm) set(sse2_packed_cvt_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_sse2_packed_cvt_lifted.cpp") diff --git a/tests/cpu/bmi1_aot.asm b/tests/cpu/bmi1_aot.asm new file mode 100644 index 000000000..ab22e5c39 --- /dev/null +++ b/tests/cpu/bmi1_aot.asm @@ -0,0 +1,252 @@ +; coverage: record cpu_aot_bmi1_bit +; Source-built MASM fixture for the three BMI1 bit-isolation/mask/reset forms from +; docs/coverage/x64_zen2.tsv group BMI/ADX: BLSI, BLSMSK, and BLSR in 32-bit and +; 64-bit register and flat [rcx|rdx|r8] memory forms, plus CF/ZF/SF/OF flag-packing, +; 32-bit zero-extension, [r8] source-then-store, and discarded faulting m64 read. +.code + +PACK_CF_ZF_SF_OF MACRO + setb r9b + sete r10b + sets r11b + seto byte ptr [r8] + movzx r9d, r9b + movzx r10d, r10b + shl r10d, 1 + or r9d, r10d + movzx r11d, r11b + shl r11d, 2 + or r9d, r11d + movzx r10d, byte ptr [r8] + shl r10d, 3 + or r9d, r10d + mov dword ptr [r8], r9d +ENDM + +; --- Register forms (32-bit & 64-bit; mov rax,-1 before 32-bit tests [63:32] zero-ext) --- + +op_blsi32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1 + blsr eax, ecx +ELSE + blsi eax, ecx +ENDIF + ret +op_blsi32 ENDP + +op_blsi64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1 + blsr rax, rcx +ELSE + blsi rax, rcx +ENDIF + ret +op_blsi64 ENDP + +op_blsmsk32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1 + blsi eax, ecx +ELSE + blsmsk eax, ecx +ENDIF + ret +op_blsmsk32 ENDP + +op_blsmsk64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1 + blsi rax, rcx +ELSE + blsmsk rax, rcx +ENDIF + ret +op_blsmsk64 ENDP + +op_blsr32 PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1 + blsmsk eax, ecx +ELSE + blsr eax, ecx +ENDIF + ret +op_blsr32 ENDP + +op_blsr64 PROC FRAME + .endprolog +IFDEF ALTER_BMI1 + blsmsk rax, rcx +ELSE + blsr rax, rcx +ENDIF + ret +op_blsr64 ENDP + +; --- Flat [rcx|rdx] m32 / m64 source forms --- + +op_blsi32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1 + blsr eax, dword ptr [rcx] +ELSE + blsi eax, dword ptr [rcx] +ENDIF + ret +op_blsi32_mem ENDP + +op_blsi64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1 + blsr rax, qword ptr [rdx] +ELSE + blsi rax, qword ptr [rdx] +ENDIF + ret +op_blsi64_mem ENDP + +op_blsmsk32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1 + blsi eax, dword ptr [rdx] +ELSE + blsmsk eax, dword ptr [rdx] +ENDIF + ret +op_blsmsk32_mem ENDP + +op_blsmsk64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1 + blsi rax, qword ptr [rcx] +ELSE + blsmsk rax, qword ptr [rcx] +ENDIF + ret +op_blsmsk64_mem ENDP + +op_blsr32_mem PROC FRAME + .endprolog + mov rax, -1 +IFDEF ALTER_BMI1 + blsmsk eax, dword ptr [rcx] +ELSE + blsr eax, dword ptr [rcx] +ENDIF + ret +op_blsr32_mem ENDP + +op_blsr64_mem PROC FRAME + .endprolog +IFDEF ALTER_BMI1 + blsmsk rax, qword ptr [rdx] +ELSE + blsr rax, qword ptr [rdx] +ENDIF + ret +op_blsr64_mem ENDP + +; --- Flag-packing exports: (CF << 0) | (ZF << 1) | (SF << 2) | (OF << 3) stored at [r8] --- + +op_blsi32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + blsi eax, ecx + PACK_CF_ZF_SF_OF + ret +op_blsi32_flags ENDP + +op_blsi64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + blsi rax, rcx + PACK_CF_ZF_SF_OF + ret +op_blsi64_flags ENDP + +op_blsmsk32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + blsmsk eax, ecx + PACK_CF_ZF_SF_OF + ret +op_blsmsk32_flags ENDP + +op_blsmsk64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + blsmsk rax, rcx + PACK_CF_ZF_SF_OF + ret +op_blsmsk64_flags ENDP + +op_blsr32_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + mov rax, -1 + blsr eax, ecx + PACK_CF_ZF_SF_OF + ret +op_blsr32_flags ENDP + +op_blsr64_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + blsr rax, rcx + PACK_CF_ZF_SF_OF + ret +op_blsr64_flags ENDP + +op_blsr64_mem_flags PROC FRAME + .endprolog + xor r9d, r9d + xor r10d, r10d + xor r11d, r11d + blsr rax, qword ptr [rcx] + PACK_CF_ZF_SF_OF + ret +op_blsr64_mem_flags ENDP + +; --- [r8] source-then-store and discarded faulting m64 read --- + +op_r8_source_then_store PROC FRAME + .endprolog + blsi r9, qword ptr [r8] + blsmsk r10, qword ptr [rcx] + blsr r11, qword ptr [rdx] + or r9, r10 + xor r9, r11 + mov qword ptr [r8], r9 + mov rax, r9 + ret +op_r8_source_then_store ENDP + +op_bmi1_discarded_read PROC FRAME + .endprolog + blsi r9, qword ptr [rdx] + mov rax, rcx + ret +op_bmi1_discarded_read ENDP + +END diff --git a/tests/cpu/bmi1_aot.def b/tests/cpu/bmi1_aot.def new file mode 100644 index 000000000..a2f121938 --- /dev/null +++ b/tests/cpu/bmi1_aot.def @@ -0,0 +1,22 @@ +EXPORTS + op_blsi32 + op_blsi64 + op_blsmsk32 + op_blsmsk64 + op_blsr32 + op_blsr64 + op_blsi32_mem + op_blsi64_mem + op_blsmsk32_mem + op_blsmsk64_mem + op_blsr32_mem + op_blsr64_mem + op_blsi32_flags + op_blsi64_flags + op_blsmsk32_flags + op_blsmsk64_flags + op_blsr32_flags + op_blsr64_flags + op_blsr64_mem_flags + op_r8_source_then_store + op_bmi1_discarded_read diff --git a/tests/cpu/bmi1_aot_check.py b/tests/cpu/bmi1_aot_check.py new file mode 100644 index 000000000..bfaa1c9cf --- /dev/null +++ b/tests/cpu/bmi1_aot_check.py @@ -0,0 +1,634 @@ +"""Differential, /O2, flag-modeling, mutant, and rejection checks for cpu_bmi1_aot (BLSI, BLSMSK, BLSR).""" + +import ctypes +import os +from pathlib import Path +import random +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + +from iced_x86 import Code, Decoder, Encoder, Formatter, FormatterSyntax, Instruction, MemoryOperand, Register as R +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_bmi1_aot import lift_code, translate # noqa: E402 +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 + +EXPORTS = ( + "op_blsi32", "op_blsi64", + "op_blsmsk32", "op_blsmsk64", + "op_blsr32", "op_blsr64", + "op_blsi32_mem", "op_blsi64_mem", + "op_blsmsk32_mem", "op_blsmsk64_mem", + "op_blsr32_mem", "op_blsr64_mem", + "op_blsi32_flags", "op_blsi64_flags", + "op_blsmsk32_flags", "op_blsmsk64_flags", + "op_blsr32_flags", "op_blsr64_flags", + "op_blsr64_mem_flags", + "op_r8_source_then_store", + "op_bmi1_discarded_read", +) + +ALTERED_REG_EXPORTS = ( + "op_blsi32", "op_blsi64", + "op_blsmsk32", "op_blsmsk64", + "op_blsr32", "op_blsr64", +) +ALTERED_MEM_EXPORTS = ( + "op_blsi32_mem", "op_blsi64_mem", + "op_blsmsk32_mem", "op_blsmsk64_mem", + "op_blsr32_mem", "op_blsr64_mem", +) + +MASK32 = 0xFFFFFFFF +MASK64 = 0xFFFFFFFFFFFFFFFF +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + + +# --- Independent Python reference model --- + +def ref_bmi1(op, val, bits, *, quirk=None): + """Return (dst, packed_flags) where packed_flags = (CF<<0)|(ZF<<1)|(SF<<2)|(OF<<3).""" + mask = MASK32 if bits == 32 else MASK64 + sign = 1 << (bits - 1) + s = val & mask + if op == "blsi": + d = ((-s) & s) & mask + cf = (s == 0) if quirk == "invert_cf" else (s != 0) + zf = (d == 0) + elif op == "blsmsk": + d = ((s - 1) ^ s) & mask + cf = (s != 0) if quirk == "invert_cf" else (s == 0) + zf = (s == 0) if quirk == "blsmsk_zf_on_zero" else False + elif op == "blsr": + d = ((s - 1) & s) & mask + cf = (s != 0) if quirk == "invert_cf" else (s == 0) + zf = (s == 0) if quirk == "blsr_zf_only_zero" else (d == 0) + else: + raise ValueError(op) + sf = False if quirk == "drop_sf" else ((d & sign) != 0) + of = True if quirk == "set_of" else False + if quirk == "no_zext32" and bits == 32: + d |= 0xFFFFFFFF00000000 + packed = (int(cf) << 0) | (int(zf) << 1) | (int(sf) << 2) | (int(of) << 3) + return d, packed + + +ALTERED_OP = {"blsi": "blsr", "blsmsk": "blsi", "blsr": "blsmsk"} + + +def test_values(): + vals = [ + 0x0000000000000000, + 0x0000000000000001, + 0x0000000000000002, + 0x0000000000000010, + 0x000000007FFFFFFF, + 0x0000000080000000, # INT32_MIN (single high bit in 32-bit!) + 0x0000000080000001, # INT32_MIN | 1 -> blsr leaves INT32_MIN (SF=1) + 0x00000000FFFFFFFE, + 0x00000000FFFFFFFF, + 0xDEADBEEF00000000, # zero in 32-bit, non-zero in 64-bit! + 0xDEADBEEF80000000, # INT32_MIN in 32-bit with dirty high 32 bits + 0x0000000100000000, # single bit 32 + 0x7FFFFFFFFFFFFFFF, + 0x8000000000000000, # INT64_MIN (single high bit in 64-bit!) + 0x8000000000000001, # INT64_MIN | 1 -> blsr leaves INT64_MIN (SF=1) + 0xFFFFFFFFFFFFFFFE, + 0xFFFFFFFFFFFFFFFF, + 0x0123456789ABCDEF, + 0xFEDCBA9876543210, + ] + # Every single-bit mask across 0..63. + vals.extend(1 << b for b in range(64)) + rng = random.Random(0xB111A07) + vals.extend(rng.getrandbits(64) for _ in range(32)) + return vals + + +# --- Guarded memory & DLL helpers --- + +def alloc_guarded(payload): + raw = ctypes.create_string_buffer(GUARD_PRE + payload + GUARD_POST, len(GUARD_PRE) + len(payload) + len(GUARD_POST)) + base = ctypes.addressof(raw) + return raw, base + len(GUARD_PRE), len(GUARD_PRE), len(payload) + + +def read_guarded(buf, off, length, label): + raw = buf.raw + if raw[:off] != GUARD_PRE or raw[off + length:] != GUARD_POST: + raise AssertionError(f"guard bytes corrupted around {label}") + return raw[off:off + length] + + +def bind_exports(dll_path, prefix=""): + lib = ctypes.CDLL(str(Path(dll_path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = ctypes.c_uint64 + funcs[name] = fn + return lib, funcs + + +def unload_lib(lib): + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.FreeLibrary.argtypes = [ctypes.c_void_p] + kernel32.FreeLibrary.restype = ctypes.c_int + handle = getattr(lib, "_handle", None) + if handle: + kernel32.FreeLibrary(handle) + + +def host_has_bmi1(lifted_lib): + if hasattr(lifted_lib, "host_has_bmi1"): + lifted_lib.host_has_bmi1.argtypes = [] + lifted_lib.host_has_bmi1.restype = ctypes.c_uint32 + return bool(lifted_lib.host_has_bmi1()) + return False + + +# --- Rejection & alternate-encoding controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + ip = 0x1000 + for ins in instructions: + ip += enc.encode(ins, ip) + return enc.take_buffer() + + +def check_rejections(original_path): + ret = Instruction.create(Code.RETNQ) + mov_rax_rcx = Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.RCX) + xor_r9 = Instruction.create_reg_reg(Code.XOR_R32_RM32, R.R9D, R.R9D) + blsi_eax_ecx = Instruction.create_reg_reg(Code.VEX_BLSI_R32_RM32, R.EAX, R.ECX) + blsmsk_rax_rcx = Instruction.create_reg_reg(Code.VEX_BLSMSK_R64_RM64, R.RAX, R.RCX) + blsr_rax_rcx = Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RCX) + + # Alternate encodings accepted cleanly. + alt_accept = [ + ("blsi32_r11_r8_mem", (Instruction.create_reg_mem(Code.VEX_BLSI_R32_RM32, R.R11D, MemoryOperand(R.R8)), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R11), ret), + "r11 = op_blsi32(ld_1000_1, flags);"), + ("blsmsk64_r10_rdx", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R64_RM64, R.R10, R.RDX), + Instruction.create_reg_reg(Code.MOV_R64_RM64, R.RAX, R.R10), ret), + "r10 = op_blsmsk64(rdx, flags);"), + ("blsr32_r9_r8d", (Instruction.create_reg_reg(Code.VEX_BLSR_R32_RM32, R.R9D, R.R8D), + Instruction.create_reg_reg(Code.MOV_R32_RM32, R.EAX, R.R9D), ret), + "r9 = op_blsr32((r8 & 0xFFFFFFFFull), flags);"), + ] + for label, seq, expected in alt_accept: + src, count = lift_code(label, 0x1000, encode_seq(*seq)) + assert f"lifted_{label}" in src and count == len(seq), (label, count) + if expected not in src: + raise AssertionError(f"alt {label}: expected {expected!r}") + + seg_blsi = Instruction.create_reg_mem(Code.VEX_BLSI_R64_RM64, R.RAX, MemoryOperand(R.RCX)) + seg_blsi.segment_prefix = R.GS + evex_ins = Instruction.create_reg_reg_reg(Code.EVEX_VPADDD_XMM_K1Z_XMM_XMMM128B32, R.XMM0, R.XMM1, R.XMM2) + evex_ins.op_mask = R.K1 + + unit_cases = [ + # BMI2 rejections + ("bmi2_rorx", (Instruction.create_reg_reg_u32(Code.VEX_RORX_R64_RM64_IMM8, R.RAX, R.RCX, 5), ret), + "unsupported VEX instruction"), + ("bmi2_sarx", (Instruction.create_reg_reg_reg(Code.VEX_SARX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_shlx", (Instruction.create_reg_reg_reg(Code.VEX_SHLX_R32_RM32_R32, R.EAX, R.ECX, R.EDX), ret), + "unsupported VEX instruction"), + ("bmi2_shrx", (Instruction.create_reg_reg_reg(Code.VEX_SHRX_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi2_bzhi", (Instruction.create_reg_reg_reg(Code.VEX_BZHI_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + # Other BMI1 instructions + ("bmi1_tzcnt", (Instruction.create_reg_reg(Code.TZCNT_R64_RM64, R.RAX, R.RCX), ret), + "unsupported instruction"), + ("bmi1_andn", (Instruction.create_reg_reg_reg(Code.VEX_ANDN_R64_R64_RM64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + ("bmi1_bextr", (Instruction.create_reg_reg_reg(Code.VEX_BEXTR_R64_RM64_R64, R.RAX, R.RCX, R.RDX), ret), + "unsupported VEX instruction"), + # EVEX / XOP + ("evex_vpaddd", (evex_ins, mov_rax_rcx, ret), "unsupported EVEX instruction"), + ("xop_blsic", (Instruction.create_reg_reg(Code.XOP_BLSIC_R64_RM64, R.RAX, R.RCX), ret), + "unsupported XOP instruction"), + # Undefined PF / AF reads after BLSI / BLSMSK / BLSR (including after prior XOR defining PF!) + ("undef_pf_after_blsi", (xor_r9, blsi_eax_ecx, Instruction.create_reg(Code.SETP_RM8, R.R9L), ret), + "undefined flag pf read"), + ("undef_pf_after_blsmsk", (xor_r9, blsmsk_rax_rcx, Instruction.create_mem(Code.SETNP_RM8, MemoryOperand(R.R8)), ret), + "undefined flag pf read"), + ("undef_pf_after_blsr", (xor_r9, blsr_rax_rcx, Instruction.create_reg(Code.SETP_RM8, R.R9L), ret), + "undefined flag pf read"), + ("undef_af_lahf_after_blsi", (blsi_eax_ecx, Instruction.create(Code.LAHF), ret), + "unsupported instruction"), + ("undef_flags_pushfq", (blsr_rax_rcx, Instruction.create(Code.PUSHFQ), ret), + "unsupported instruction"), + ("undef_flags_before_bmi1", (mov_rax_rcx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.R8)), ret), + "undefined flag cf read"), + # Nonvolatile GPRs & arg GPR writes & high-byte GPRs + ("nonvol_rbx_dst", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RBX, R.RCX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("nonvol_rsi_src", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.RAX, R.RSI), ret), + "nonvolatile GPR"), + ("nonvol_r12_dst", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R32_RM32, R.R12D, R.ECX), mov_rax_rcx, ret), + "nonvolatile GPR"), + ("write_arg_rcx", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RCX, R.RDX), mov_rax_rcx, ret), + "cannot write argument GPR rcx"), + ("write_arg_edx", (Instruction.create_reg_reg(Code.VEX_BLSR_R32_RM32, R.EDX, R.ECX), mov_rax_rcx, ret), + "cannot write argument GPR rdx"), + ("write_arg_r8", (Instruction.create_reg_reg(Code.VEX_BLSMSK_R64_RM64, R.R8, R.RCX), mov_rax_rcx, ret), + "cannot write argument GPR r8"), + ("high_byte_ah", (mov_rax_rcx, Instruction.create_reg_u32(Code.MOV_R8_IMM8, R.AH, 1), ret), + "unsupported high-byte GPR"), + # Undefined GPRs + ("undef_gpr_r9_src", (Instruction.create_reg_reg(Code.VEX_BLSI_R64_RM64, R.RAX, R.R9), ret), + "undefined GPR r9"), + ("undef_rax_ret", (Instruction.create_reg_reg(Code.VEX_BLSR_R64_RM64, R.R9, R.RCX), ret), + "return with undefined RAX"), + # Displaced / indexed / non-flat memory & non-r8 stores + ("displaced_blsi_rcx", (Instruction.create_reg_mem( + Code.VEX_BLSI_R64_RM64, R.RAX, MemoryOperand(R.RCX, displ=8, displ_size=1)), ret), + "displaced memory operand"), + ("displaced_store_r8", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.R8, displ=8, displ_size=1), R.RAX), ret), + "displaced memory operand"), + ("indexed_blsmsk", (Instruction.create_reg_mem( + Code.VEX_BLSMSK_R64_RM64, R.RAX, MemoryOperand(R.RCX, R.RDX, 8)), ret), + "SIB index memory operand"), + ("rip_rel_blsr", (Instruction.create_reg_mem( + Code.VEX_BLSR_R64_RM64, R.RAX, MemoryOperand(R.RIP, displ=0x1020, displ_size=4)), ret), + "RIP-relative memory operand"), + ("bad_base_rbx", (Instruction.create_reg_mem(Code.VEX_BLSI_R64_RM64, R.RAX, MemoryOperand(R.RBX)), ret), + "bad base register in memory operand"), + ("bad_base_rsp", (Instruction.create_reg_mem(Code.VEX_BLSR_R32_RM32, R.EAX, MemoryOperand(R.RSP)), ret), + "bad base register in memory operand"), + ("non_r8_store_rcx", (mov_rax_rcx, Instruction.create_mem_reg( + Code.MOV_RM64_R64, MemoryOperand(R.RCX), R.RAX), ret), "non-r8 store memory operand"), + ("non_r8_store_setb", (blsi_eax_ecx, Instruction.create_mem(Code.SETB_RM8, MemoryOperand(R.RDX)), ret), + "non-r8 store memory operand"), + # Prefixes, branches, missing/trailing ret + ("seg_prefix_blsi", (seg_blsi, ret), "unsupported instruction prefix"), + ("branch_jmp", (mov_rax_rcx, Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), + "non-leaf branch or call"), + ("missing_ret", (blsi_eax_ecx,), "missing terminal ret"), + ("trailing_after_ret", (blsi_eax_ecx, ret, mov_rax_rcx), "unreachable instruction after ret"), + ] + + raw_cases = [ + ("lock_prefix", bytes.fromhex("f00fb109") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("rep_prefix", bytes.fromhex("f3a4") + encode_seq(mov_rax_rcx, ret), "unsupported instruction prefix"), + ("empty_stream", b"", "truncated instruction stream"), + ("invalid_bytes", bytes.fromhex("fffe") + encode_seq(ret), "invalid instruction"), + ] + + for label, seq, reason in unit_cases: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected control") + + for label, raw, reason in raw_cases: + try: + lift_code(label, 0x1000, raw) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted raw rejected control") + + # End-to-end PE-patched rejections & CLI non-traceback rejection. + pe_bytes = Path(original_path).read_bytes() + with pefile.PE(data=pe_bytes, fast_load=True) as pe: + entry = export_rva(pe, "op_blsi64_flags") + file_off = pe.get_offset_from_rva(entry) + pdata = pe.OPTIONAL_HEADER.DATA_DIRECTORY[3] + records = pe.get_data(pdata.VirtualAddress, pdata.Size) + rec_idx = next(i for i in range(0, len(records), 12) if struct.unpack_from(" max_len: + raise AssertionError(f"pe_{label}: patch ({len(patch)} bytes) exceeds max_len ({max_len})") + damaged = bytearray(pe_bytes) + damaged[file_off:file_off + len(patch)] = patch + struct.pack_into("(word rcx, word rdx, word r8) +where rcx, rdx, and r8 enter as 64-bit integer arguments or flat pointers to caller-owned +buffers and RAX carries the 64-bit return value. + +Supported BMI1 bit-isolation/mask/reset instructions (docs/coverage/x64_zen2.tsv group BMI/ADX): + - BLSI r32, r/m32 | BLSI r64, r/m64 (dst = (-src) & src; CF=(src!=0), ZF=(dst==0), SF=msb(dst), OF=0) + - BLSMSK r32, r/m32 | BLSMSK r64, r/m64 (dst = (src-1) ^ src; CF=(src==0), ZF=0, SF=msb(dst), OF=0) + - BLSR r32, r/m32 | BLSR r64, r/m64 (dst = (src-1) & src; CF=(src==0), ZF=(dst==0), SF=msb(dst), OF=0) + +32-bit destinations zero-extend into bits [63:32]. Per Intel SDM, PF and AF are undefined +after BLSI, BLSMSK, and BLSR; reading PF/AF before a subsequent flag-defining instruction +is rejected. Memory operands are flat zero-displacement [rcx|rdx|r8] loads (m32/m64) read +unconditionally via load_always() so /O2 cannot drop faulting reads. + +Transport / flag-packing glue: + - Volatile scratch GPR (rax/r9/r10/r11) mov, xor, or, shl, movzx, setb/sete/sets/seto + (and inverses, reg or flat [r8]), flat [r8] stores, and terminal ret. + +BMI2 (RORX/SARX/SHLX/SHRX/BZHI), EVEX/XOP, other BMI1 (TZCNT/ANDN/BEXTR), nonvolatile GPRs, +writes to argument GPRs (rcx/rdx/r8), high-byte GPRs, undefined GPR or flag reads (including +PF/AF after BLSI/BLSMSK/BLSR), displaced/indexed/non-flat memory operands, stores outside +[r8], instruction prefixes, branches/calls, and missing or trailing instructions after ret +are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} +ARGUMENT_NAMES = {"rcx", "rdx", "r8"} + +VOLATILE_GPR64 = { + R.RAX: "rax", R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8", + R.R9: "r9", R.R10: "r10", R.R11: "r11", +} +VOLATILE_GPR32 = { + R.EAX: "rax", R.ECX: "rcx", R.EDX: "rdx", R.R8D: "r8", + R.R9D: "r9", R.R10D: "r10", R.R11D: "r11", +} +VOLATILE_GPR16 = { + R.AX: "rax", R.CX: "rcx", R.DX: "rdx", R.R8W: "r8", + R.R9W: "r9", R.R10W: "r10", R.R11W: "r11", +} +VOLATILE_GPR8 = { + R.AL: "rax", R.CL: "rcx", R.DL: "rdx", R.R8L: "r8", + R.R9L: "r9", R.R10L: "r10", R.R11L: "r11", +} +HIGH_BYTE_GPRS = {R.AH, R.CH, R.DH, R.BH} +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +# (width_bits, helper_name) +BMI1_SPECS = { + Code.VEX_BLSI_R32_RM32: (32, "op_blsi32"), + Code.VEX_BLSI_R64_RM64: (64, "op_blsi64"), + Code.VEX_BLSMSK_R32_RM32: (32, "op_blsmsk32"), + Code.VEX_BLSMSK_R64_RM64: (64, "op_blsmsk64"), + Code.VEX_BLSR_R32_RM32: (32, "op_blsr32"), + Code.VEX_BLSR_R64_RM64: (64, "op_blsr64"), +} + +MOV_WIDTHS = { + Code.MOV_R64_RM64: 64, + Code.MOV_RM64_R64: 64, + Code.MOV_RM64_IMM32: 64, + Code.MOV_R64_IMM64: 64, + Code.MOV_R32_RM32: 32, + Code.MOV_RM32_R32: 32, + Code.MOV_RM32_IMM32: 32, + Code.MOV_R32_IMM32: 32, + Code.MOV_R8_RM8: 8, + Code.MOV_RM8_R8: 8, + Code.MOV_RM8_IMM8: 8, + Code.MOV_R8_IMM8: 8, +} +MOVZX_SPECS = { + Code.MOVZX_R32_RM8: (32, 8), + Code.MOVZX_R64_RM8: (64, 8), +} +XOR_WIDTHS = { + Code.XOR_R32_RM32: 32, + Code.XOR_RM32_R32: 32, + Code.XOR_RM32_IMM8: 32, + Code.XOR_R64_RM64: 64, + Code.XOR_RM64_R64: 64, + Code.XOR_RM64_IMM8: 64, +} +OR_WIDTHS = { + Code.OR_R32_RM32: 32, + Code.OR_RM32_R32: 32, + Code.OR_RM32_IMM8: 32, + Code.OR_R64_RM64: 64, + Code.OR_RM64_R64: 64, + Code.OR_RM64_IMM8: 64, +} +SHL_SPECS = { + Code.SHL_RM32_1: (32, True), + Code.SHL_RM32_IMM8: (32, False), + Code.SHL_RM64_1: (64, True), + Code.SHL_RM64_IMM8: (64, False), +} +SETCC_SPECS = { + Code.SETB_RM8: ("cf", "flags.cf"), + Code.SETAE_RM8: ("cf", "!flags.cf"), + Code.SETE_RM8: ("zf", "flags.zf"), + Code.SETNE_RM8: ("zf", "!flags.zf"), + Code.SETS_RM8: ("sf", "flags.sf"), + Code.SETNS_RM8: ("sf", "!flags.sf"), + Code.SETO_RM8: ("of", "flags.of"), + Code.SETNO_RM8: ("of", "!flags.of"), + # PF is tracked solely to reject reading it when undefined (e.g. after BLSI/BLSMSK/BLSR). + Code.SETP_RM8: ("pf", "flags.pf"), + Code.SETNP_RM8: ("pf", "!flags.pf"), +} + +PRELUDE = """#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +using word = std::uint64_t; + +struct Flags { + bool cf = false; + bool zf = false; + bool sf = false; + bool of = false; + bool pf = false; +}; + +template +static inline T load_always(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + T v{}; + std::memcpy(&v, reinterpret_cast(address), sizeof(T)); + const volatile T observed = v; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +template +static inline void store_always(word address, T value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(T)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline bool parity_even(std::uint8_t byte) { + byte ^= static_cast(byte >> 4); + byte &= 0x0Fu; + return ((0x9669u >> byte) & 1u) != 0u; +} + +static inline word update_gpr_width(word cur, std::uint64_t val, unsigned width) { + if (width == 8u) { + return (cur & ~0xFFull) | (val & 0xFFull); + } + if (width == 32u) { + return val & 0xFFFFFFFFull; + } + return val; +} + +static inline void compute_logic_flags(word result, unsigned width, Flags& flags) { + const std::uint64_t masked = (width == 32u) ? (result & 0xFFFFFFFFull) : result; + flags.cf = false; + flags.of = false; + flags.zf = masked == 0ull; + flags.sf = ((masked >> (width - 1u)) & 1ull) != 0ull; + flags.pf = parity_even(static_cast(masked)); +} + +static inline word op_shl(word cur, unsigned width, unsigned count, Flags& flags) { + const unsigned mask = (width == 32u) ? 31u : 63u; + const unsigned c = count & mask; + if (width == 32u) { + const std::uint32_t v = static_cast(cur); + if (c == 0u) return static_cast(v); + const std::uint32_t r = v << c; + flags.cf = ((v >> (32u - c)) & 1u) != 0u; + flags.zf = r == 0u; + flags.sf = (r & 0x80000000u) != 0u; + flags.of = (((r >> 31) & 1u) != (flags.cf ? 1u : 0u)); + flags.pf = parity_even(static_cast(r)); + return static_cast(r); + } + if (c == 0u) return cur; + const word r = cur << c; + flags.cf = ((cur >> (64u - c)) & 1ull) != 0ull; + flags.zf = r == 0ull; + flags.sf = (r >> 63) != 0ull; + flags.of = (((r >> 63) & 1ull) != (flags.cf ? 1ull : 0ull)); + flags.pf = parity_even(static_cast(r)); + return r; +} + +// --- Portable BMI1 BLSI / BLSMSK / BLSR helpers (CF, ZF, SF, OF; PF/AF undefined) --- + +static inline word op_blsi32(word src_w, Flags& flags) { + const std::uint32_t s = static_cast(src_w); + const std::uint32_t d = (~s + 1u) & s; + flags.cf = (s != 0u); + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + flags.of = false; + return static_cast(d); +} + +static inline word op_blsi64(word s, Flags& flags) { + const word d = (~s + 1ull) & s; + flags.cf = (s != 0ull); + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + flags.of = false; + return d; +} + +static inline word op_blsmsk32(word src_w, Flags& flags) { + const std::uint32_t s = static_cast(src_w); + const std::uint32_t d = (s - 1u) ^ s; + flags.cf = (s == 0u); + flags.zf = false; + flags.sf = (d & 0x80000000u) != 0u; + flags.of = false; + return static_cast(d); +} + +static inline word op_blsmsk64(word s, Flags& flags) { + const word d = (s - 1ull) ^ s; + flags.cf = (s == 0ull); + flags.zf = false; + flags.sf = (d >> 63) != 0ull; + flags.of = false; + return d; +} + +static inline word op_blsr32(word src_w, Flags& flags) { + const std::uint32_t s = static_cast(src_w); + const std::uint32_t d = (s - 1u) & s; + flags.cf = (s == 0u); + flags.zf = (d == 0u); + flags.sf = (d & 0x80000000u) != 0u; + flags.of = false; + return static_cast(d); +} + +static inline word op_blsr64(word s, Flags& flags) { + const word d = (s - 1ull) & s; + flags.cf = (s == 0ull); + flags.zf = (d == 0ull); + flags.sf = (d >> 63) != 0ull; + flags.of = false; + return d; +} + +#if defined(_MSC_VER) +extern "C" __declspec(dllexport) std::uint32_t host_has_bmi1() { + int info[4]{}; + __cpuid(info, 0); + if (info[0] < 7) return 0u; + __cpuidex(info, 7, 0); + return (static_cast(info[1]) & (1u << 3)) != 0u ? 1u : 0u; +} +#endif +""" + + +def gpr_info(register, ins): + """Map volatile GPR (64/32/16/8-bit low) to (name, width_bits), rejecting nonvolatile/high-byte.""" + if register in VOLATILE_GPR64: + return VOLATILE_GPR64[register], 64 + if register in VOLATILE_GPR32: + return VOLATILE_GPR32[register], 32 + if register in VOLATILE_GPR16: + return VOLATILE_GPR16[register], 16 + if register in VOLATILE_GPR8: + return VOLATILE_GPR8[register], 8 + if register in HIGH_BYTE_GPRS: + raise ValueError(f"unsupported high-byte GPR {register} at RVA {ins.ip:#x}: {ins}") + if register in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR {register} at RVA {ins.ip:#x}: {ins}") + raise ValueError(f"unsupported GPR {register} at RVA {ins.ip:#x}: {ins}") + + +def flat_address(ins, expected_bytes, *, write=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand (stores only to [r8]).""" + if ins.is_ip_rel_memory_operand or ins.memory_base in (R.RIP, R.EIP): + raise ValueError(f"RIP-relative memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_index != R.NONE: + raise ValueError(f"SIB index memory operand at RVA {ins.ip:#x}: {ins}") + base = ins.memory_base + if base == R.NONE or not RegisterExt.is_gpr64(base) or base not in ARGUMENTS: + raise ValueError(f"bad base register in memory operand at RVA {ins.ip:#x}: {ins}") + if ins.memory_displacement != 0: + raise ValueError(f"displaced memory operand at RVA {ins.ip:#x}: {ins}") + if write and base != R.R8: + raise ValueError(f"non-r8 store memory operand at RVA {ins.ip:#x}: {ins}") + actual_bytes = MemorySizeExt.size(ins.memory_size) + if actual_bytes != expected_bytes: + raise ValueError( + f"unexpected {actual_bytes}-byte memory operand (expected {expected_bytes}) at RVA {ins.ip:#x}: {ins}" + ) + return ARGUMENTS[base] + + +def _immediate_value(ins, op_index, width): + kind = ins.op_kind(op_index) + if kind == OpKind.IMMEDIATE8: + return ins.immediate8 & 0xFF + if kind == OpKind.IMMEDIATE32: + return ins.immediate32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE64: + return ins.immediate64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE8TO32: + return ins.immediate8to32 & 0xFFFFFFFF + if kind == OpKind.IMMEDIATE8TO64: + return ins.immediate8to64 & 0xFFFFFFFFFFFFFFFF + if kind == OpKind.IMMEDIATE32TO64: + return ins.immediate32to64 & 0xFFFFFFFFFFFFFFFF + raise ValueError(f"unsupported immediate kind {kind} for {width}-bit op at RVA {ins.ip:#x}: {ins}") + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line BMI1 BLSI/BLSMSK/BLSR leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + defined_gpr = {"rcx", "rdx", "r8"} + used_scratch = set() + defined_flags = set() + statements = [] + returned = False + + def note_scratch(reg_name): + if reg_name in ("r9", "r10", "r11"): + used_scratch.add(reg_name) + + def read_reg(op_index, ins, expected_width): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register operand {op_index} at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + mask = {8: "0xFFull", 32: "0xFFFFFFFFull"}.get(width) + return f"({reg_name} & {mask})" if mask else reg_name + + def check_dst_reg(op_index, ins, expected_width, *, require_defined=False): + if ins.op_kind(op_index) != OpKind.REGISTER: + raise ValueError(f"expected register destination at RVA {ins.ip:#x}: {ins}") + reg_name, width = gpr_info(ins.op_register(op_index), ins) + if width != expected_width: + raise ValueError(f"unexpected GPR destination width {width} at RVA {ins.ip:#x}: {ins}") + if reg_name in ARGUMENT_NAMES: + raise ValueError(f"cannot write argument GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + if require_defined and reg_name not in defined_gpr: + raise ValueError(f"undefined GPR {reg_name} at RVA {ins.ip:#x}: {ins}") + note_scratch(reg_name) + return reg_name + + def read_rm(op_index, ins, width): + kind = ins.op_kind(op_index) + if kind == OpKind.REGISTER: + return read_reg(op_index, ins, width) + if kind == OpKind.MEMORY: + addr = flat_address(ins, width // 8, write=False) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + load_var = f"ld_{ins.ip:x}_{op_index}" + statements.append(f"const word {load_var} = static_cast(load_always<{ctype}>({addr}));") + return load_var + raise ValueError(f"unsupported operand at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ins.has_lock_prefix or ins.has_rep_prefix or ins.has_repne_prefix or ins.has_segment_prefix: + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + + op_code = ins.op_code() + encoding = op_code.encoding + if encoding == EncodingKind.EVEX or ins.op_mask != R.NONE or ins.zeroing_masking or ins.is_broadcast: + raise ValueError(f"unsupported EVEX instruction at RVA {ins.ip:#x}: {ins}") + if encoding == EncodingKind.XOP: + raise ValueError(f"unsupported XOP instruction at RVA {ins.ip:#x}: {ins}") + if ins.code != Code.RETNQ and ins.flow_control != FlowControl.NEXT: + raise ValueError(f"non-leaf branch or call at RVA {ins.ip:#x}: {ins}") + + code = ins.code + if code in BMI1_SPECS: + if encoding != EncodingKind.VEX: + raise ValueError(f"expected VEX encoding for BMI1 op at RVA {ins.ip:#x}: {ins}") + width, helper = BMI1_SPECS[code] + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = {helper}({src_expr}, flags);") + defined_gpr.add(dst) + # BLSI, BLSMSK, and BLSR define CF, ZF, SF, OF and leave PF/AF undefined. + defined_flags = {"cf", "zf", "sf", "of"} + elif encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX instruction at RVA {ins.ip:#x}: {ins}") + elif code == Code.RETNQ: + if "rax" not in defined_gpr: + raise ValueError(f"return with undefined RAX at RVA {ins.ip:#x}") + statements.append("return rax;") + returned = True + elif code in MOV_WIDTHS: + width = MOV_WIDTHS[code] + if ins.op0_kind == OpKind.REGISTER and ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + src_expr = read_rm(1, ins, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {src_expr}, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY and ins.op1_kind == OpKind.REGISTER: + src_expr = read_rm(1, ins, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({src_expr}));") + elif ins.op0_kind == OpKind.REGISTER: + imm = _immediate_value(ins, 1, width) + dst = check_dst_reg(0, ins, width, require_defined=(width < 32)) + statements.append(f"{dst} = update_gpr_width({dst}, {imm:#x}ull, {width}u);") + if width >= 32: + defined_gpr.add(dst) + elif ins.op0_kind == OpKind.MEMORY: + imm = _immediate_value(ins, 1, width) + addr = flat_address(ins, width // 8, write=True) + ctype = {8: "std::uint8_t", 32: "std::uint32_t", 64: "std::uint64_t"}[width] + statements.append(f"store_always<{ctype}>({addr}, static_cast<{ctype}>({imm:#x}ull));") + else: + raise ValueError(f"unsupported mov operands at RVA {ins.ip:#x}: {ins}") + elif code in MOVZX_SPECS: + dst_width, src_width = MOVZX_SPECS[code] + src_expr = read_rm(1, ins, src_width) + dst = check_dst_reg(0, ins, dst_width, require_defined=False) + statements.append(f"{dst} = {src_expr};") + defined_gpr.add(dst) + elif code in XOR_WIDTHS: + width = XOR_WIDTHS[code] + if ( + ins.op0_kind == OpKind.REGISTER + and ins.op1_kind == OpKind.REGISTER + and ins.op0_register == ins.op1_register + ): + dst = check_dst_reg(0, ins, width, require_defined=False) + statements.append(f"{dst} = 0ull;") + defined_gpr.add(dst) + else: + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} ^ {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in OR_WIDTHS: + width = OR_WIDTHS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + lhs_expr = read_reg(0, ins, width) + if ins.op1_kind in (OpKind.REGISTER, OpKind.MEMORY): + rhs_expr = read_rm(1, ins, width) + else: + rhs_expr = f"{_immediate_value(ins, 1, width):#x}ull" + statements.append(f"{dst} = update_gpr_width({dst}, {lhs_expr} | {rhs_expr}, {width}u);") + statements.append(f"compute_logic_flags({dst}, {width}u, flags);") + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif code in SHL_SPECS: + width, is_one = SHL_SPECS[code] + dst = check_dst_reg(0, ins, width, require_defined=True) + cnt = 1 if is_one else (ins.immediate8 & 0xFF) + eff = cnt & (31 if width == 32 else 63) + statements.append(f"{dst} = op_shl({dst}, {width}u, {cnt}u, flags);") + if eff == 1: + defined_flags = {"cf", "zf", "sf", "of", "pf"} + elif eff > 1: + defined_flags = {"cf", "zf", "sf", "pf"} + elif code in SETCC_SPECS: + flag_name, cond_expr = SETCC_SPECS[code] + if flag_name not in defined_flags: + raise ValueError(f"undefined flag {flag_name} read by {ins} at RVA {ins.ip:#x}") + if ins.op0_kind == OpKind.REGISTER: + dst = check_dst_reg(0, ins, 8, require_defined=True) + statements.append(f"{dst} = update_gpr_width({dst}, ({cond_expr}) ? 1ull : 0ull, 8u);") + elif ins.op0_kind == OpKind.MEMORY: + addr = flat_address(ins, 1, write=True) + statements.append( + f"store_always({addr}, static_cast(({cond_expr}) ? 1u : 0u));" + ) + else: + raise ValueError(f"unsupported setcc operand at RVA {ins.ip:#x}: {ins}") + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" word rax = 0ull;"] + for gpr in ("r9", "r10", "r11"): + if gpr in used_scratch: + decls.append(f" word {gpr} = 0ull;") + decls.append(" Flags flags{};") + decls.append(" (void)flags;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) std::uint64_t lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, [n for n in args.exports.split(",") if n]) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From dc18d44676fc57eb9af5fe272b045b96e29657dd Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Thu, 26 Nov 2026 02:51:14 +0800 Subject: [PATCH 090/232] startup: refuse a short operand list in four single-body handlers (#2396) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * startup: refuse a short operand list in four single-body handlers `v_mov_b32`, `v_cvt_i32_f32`, `v_cndmask_b32` and `s_bfm_b32` read their `ops` without checking the count, so a short list came back as `translator crash in : IndexError` — the batch translator's marker for a translator defect — instead of a refusal. The tables (VEC_F, VEC_U) already have this guard; these four keep their operands in method bodies and were missed. v_mov_b32 / v_cvt_i32_f32 0, 1 operands crash -> refuse with "expected 2" v_cndmask_b32 0, 1, 2 operands crash -> refuse with "expected 3 or 4" s_bfm_b32 0, 1, 2 operands crash -> refuse with "expected 3" `v_cndmask_b32` keeps its optional mask operand, and `s_bfm_b32` keeps its `m0` destination: the count is checked before `ops[0]` is read, and the message names the range rather than a single number where the ISA allows one. `tests/startup_gfx2hlsl_operand_count_check.py` extends the existing rule to these handlers — one fewer operand must refuse, the accepted count must translate — and disables each new condition in a copy of the module to require IndexError to come back, the same negative-control shape the file already uses for VEC_F. All 58 `tests/startup_gfx2hlsl_*_check.py` exit 0. * startup: refuse a short operand list in v_cvt_pkrtz_f16_f32 as well Same defect as the four handlers this branch already guards: the body reads ops[1] and ops[2] without checking the count, so `v_cvt_pkrtz_f16_f32 v0, v1` and `v_cvt_pkrtz_f16_f32 v0` came back as `translator crash in v_cvt_pkrtz_f16_f32: IndexError` instead of a refusal. before: v_cvt_pkrtz_f16_f32 v0, v1 -> translator crash: IndexError after: v_cvt_pkrtz_f16_f32 v0, v1 -> v_cvt_pkrtz_f16_f32 with 2 operands, expected 3 Added to the same BODY_HANDLERS table and covered by the same negative control (disabling the condition in a copy of the module must bring IndexError back): 5 handler checks and 5 controls, `operand count checks: 0 failed`, all 59 `tests/startup_gfx2hlsl_*_check.py` exit 0. Kept on this branch rather than a second PR because it is the same behaviour and the same table. --------- Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- tests/startup_gfx2hlsl_operand_count_check.py | 22 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 10 +++++++++ 2 files changed, 32 insertions(+) diff --git a/tests/startup_gfx2hlsl_operand_count_check.py b/tests/startup_gfx2hlsl_operand_count_check.py index efef827dd..ce21ca473 100644 --- a/tests/startup_gfx2hlsl_operand_count_check.py +++ b/tests/startup_gfx2hlsl_operand_count_check.py @@ -88,5 +88,27 @@ def table_counts(module, table): outcome(unguarded, 'v_med3_f32', 4) == 'ok', outcome(unguarded, 'v_med3_f32', 4)) check('control: without the guard the VEC_F table check fails', bool(table_counts(unguarded, 'VEC_F'))) +# Handlers outside the tables keep their operands in method bodies, so the same rule is asserted here: the +# destination plus exactly its sources, and a short list refused rather than indexed. +BODY_HANDLERS = (('v_mov_b32', 1, 2), ('v_cvt_i32_f32', 1, 2), ('v_cndmask_b32', 2, 3), ('s_bfm_b32', 2, 2), + ('v_cvt_pkrtz_f16_f32', 2, 3)) +for op, sources, operands in BODY_HANDLERS: + got = [outcome(G, op, n) for n in (sources - 1, sources)] + check('%s: translates with %d operands and refuses %d' % (op, operands, operands - 1), + got == ['refused', 'ok'], repr(got)) + +# Negative control: with each guard disabled, the short form raises IndexError again instead of refusing. +stripped = source +for condition in ('if len(ops) != 2:', 'if len(ops) != 3:', 'if len(ops) not in (3, 4):'): + stripped = stripped.replace(' ' + condition, ' if False:') +spec = importlib.util.spec_from_loader('gfx2hlsl_no_body_guards', loader=None) +no_guards = importlib.util.module_from_spec(spec) +no_guards.__dict__['__file__'] = G.__file__ +exec(compile(stripped, G.__file__, 'exec'), no_guards.__dict__) +for op, sources, operands in BODY_HANDLERS: + got = outcome(no_guards, op, sources - 1) + check('control: without its guard %s with %d operands raises IndexError' % (op, operands - 1), + got == 'IndexError', got) + print('operand count checks: %d failed' % len(failures)) sys.exit(1 if failures else 0) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 89187ce56..fdec83252 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2787,6 +2787,8 @@ def op_s_load_dwordx4(self, ops, mods, count=4): def op_s_bfm_b32(self, ops, mods): """Fold constant bitfield masks: titles build inline sampler words with them.""" + if len(ops) != 3: + raise Unsupported('s_bfm_b32 with %d operands, expected 3' % len(ops)) vals = [] for o in ops[1:3]: r = reg_range(o) @@ -3859,6 +3861,8 @@ def op_image_gather4_c_lz(self, ops, mods): def op_v_cvt_i32_f32(self, ops, mods): if mods: raise Unsupported('v_cvt_i32_f32 with modifiers') + if len(ops) != 2: + raise Unsupported('v_cvt_i32_f32 with %d operands, expected 2' % len(ops)) dst = reg_range(ops[0])[1] self.set_v(dst, 'uint(int(F(%s)))' % self.u(ops[1])) @@ -4030,6 +4034,8 @@ def op_v_readlane_b32(self, ops, mods): self.set_s(dst[1], 'sp%d_%d' % (n, lane), sym=sym, uniform=uniform) def op_v_mov_b32(self, ops, mods): + if len(ops) != 2: + raise Unsupported('v_mov_b32 with %d operands, expected 2' % len(ops)) self.set_v(reg_range(ops[0])[1], self.u(ops[1])) def op_v_swap_b32(self, ops, mods): @@ -4062,6 +4068,8 @@ def op_v_cndmask_b32(self, ops, mods): # modifier that reaches here is refused rather than dropped from the emitted text. if mods: raise Unsupported('v_cndmask_b32 with %s' % mods) + if len(ops) not in (3, 4): + raise Unsupported('v_cndmask_b32 with %d operands, expected 3 or 4' % len(ops)) mask = self.u(ops[3]) if len(ops) > 3 else 'vcc' self.set_v(reg_range(ops[0])[1], '(%s & 1) ? %s : %s' % (mask, self.u_src(ops[2]), self.u_src(ops[1]))) @@ -4439,6 +4447,8 @@ def op_v_lshrrev_b64(self, ops, mods): def op_v_ashrrev_i64(self, ops, mods): self.shift64(ops, mods, 'shr64i') def op_v_cvt_pkrtz_f16_f32(self, ops, mods): + if len(ops) != 3: + raise Unsupported('v_cvt_pkrtz_f16_f32 with %d operands, expected 3' % len(ops)) self.set_v(reg_range(ops[0])[1], 'f32tof16(%s) | (f32tof16(%s) << 16)' % (self.f(ops[1]), self.f(ops[2]))) # VOPC with sub-dword addressing (tools/disasm_rdna2.py _decode_vopc_sdwa prints it): each source From b97f603fbe9a4a421371c78369d003e629f82df3 Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Thu, 26 Nov 2026 02:51:28 +0800 Subject: [PATCH 091/232] startup: refuse an image instruction without dim: or dmask: (#2408) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `image()` reads its dimension and dmask with `[0]` after filtering the modifier list, so a form that omits either one reached that index and came back as `translator crash in : IndexError` instead of a refusal — even with a full operand list. Seven handlers share the body: `image_sample`, `image_sample_l`, `image_sample_lz`, `image_sample_b`, `image_get_lod`, `image_load`, `image_load_mip`. Measured through the real `Stage` entry point, on a form with all four operands present: image_sample v[8:11], v0, s[16:19], s[20:23] before: translator crash: IndexError after: image instruction without dim: image_sample v[8:11], v0, s[16:19], s[20:23] dim:SQ_RSRC_IMG_2D before: translator crash: IndexError after: image instruction without dmask: image_load v[8:11], v0, s[16:19] before: translator crash: IndexError after: image instruction without dim: Both modifiers are required by the lowering — `dim:` selects the emitted texture type and `dmask:` the register span — and the disassembler prints both on every image instruction, so a missing one means the text entry, not the ISA. `tests/startup_gfx2hlsl_image_arity_check.py` gains three assertions per form (no modifiers, `dim:` only, `dmask:` only) beside the operand-count ones it already had. Fail-first: removing exactly the guard fails the check with ('image_sample', ('v[8:11]', 'v0', 's[16:19]', 's[20:23]'), '', [('translator crash in image_sample: IndexError', 'ps')]) and restoring it returns exit 0. All 59 `tests/startup_gfx2hlsl_*_check.py` exit 0, and the failing set of all 157 `tests/startup_*_check.py` run with no arguments is identical to `main` (54 each, none added). Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- tests/startup_gfx2hlsl_image_arity_check.py | 38 +++++++++++++-------- tools/startup/gfx2hlsl.py | 8 +++-- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/tests/startup_gfx2hlsl_image_arity_check.py b/tests/startup_gfx2hlsl_image_arity_check.py index 37b64041f..626587cd2 100644 --- a/tests/startup_gfx2hlsl_image_arity_check.py +++ b/tests/startup_gfx2hlsl_image_arity_check.py @@ -1,10 +1,11 @@ -"""Image instructions refuse a short operand list instead of indexing it. +"""Image instructions refuse a short operand list or a missing dimension/dmask instead of indexing it. `image()` reads vdata, an address and a descriptor. A list shorter than three used to reach `ops[1]` or -`ops[2]`, which `Stage.translate` records as `translator crash in : IndexError` -- its marker for a -translator defect rather than for an instruction it does not lower -- and which the single-shader path does -not catch at all. The accepted forms need a bound descriptor, so this check pins the refusal side only; the -accepted shapes are covered by the per-form fixtures. +`ops[2]`, and the `dim:`/`dmask:` modifiers are read with `[0]` after filtering, so a form that omitted one +reached that index instead of refusing. Both are recorded by `Stage.translate` as `translator crash in : +IndexError` -- its marker for a translator defect rather than for an instruction it does not lower -- and the +single-shader path does not catch it at all. The accepted forms need a bound descriptor, so this check pins +the refusal side only; the accepted shapes are covered by the per-form fixtures. """ import sys from pathlib import Path @@ -17,22 +18,23 @@ FORMS = ('image_sample', 'image_sample_l', 'image_sample_lz', 'image_sample_b', 'image_get_lod', 'image_load', 'image_load_mip') +FULL = ('v[8:11]', 'v0', 's[16:19]', 's[20:23]') -def translate(name, operands): +def translate(name, operands, mods=''): pipe = SimpleNamespace(root={'params': [], 'flags': 0}) - text = ' '.join((name, ', '.join(operands))).strip() + text = ' '.join((name, ', '.join(operands), mods)).strip() refusals = [] stage = G.Stage(pipe, 'ps', b'', refusals=refusals, decoded=[(0, 4, name, text)]) return refusals, stage.blocks -def refuse(name, operands, expected): - refusals, blocks = translate(name, operands) - assert len(refusals) == 1, (name, operands, refusals) - assert not blocks, (name, operands, blocks) - assert 'translator crash' not in refusals[0][0], (name, operands, refusals) - assert expected in refusals[0][0], (name, operands, refusals) +def refuse(name, operands, expected, mods=''): + refusals, blocks = translate(name, operands, mods) + assert len(refusals) == 1, (name, operands, mods, refusals) + assert not blocks, (name, operands, mods, blocks) + assert 'translator crash' not in refusals[0][0], (name, operands, mods, refusals) + assert expected in refusals[0][0], (name, operands, mods, refusals) def main(): @@ -40,7 +42,15 @@ def main(): refuse(form, ('v[8:11]',), 'image instruction with 1 operands, expected at least 3') refuse(form, ('v[8:11]', 'v0'), 'image instruction with 2 operands, expected at least 3') - print('startup gfx2hlsl image arity: %d forms refused at 1 and 2 operands' % len(FORMS)) + # The dimension and dmask decide the emitted descriptor type and the register span, and the disassembler + # always prints both, so a form without one comes from the text entry rather than from the ISA. + for form in FORMS: + refuse(form, FULL, 'without dim:') + refuse(form, FULL, 'without dmask:', mods='dim:SQ_RSRC_IMG_2D') + refuse(form, FULL, 'without dim:', mods='dmask:0xf') + + print('startup gfx2hlsl image arity: %d forms refused at 1 and 2 operands and without dim/dmask' + % len(FORMS)) if __name__ == '__main__': diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index fdec83252..8c3d090f2 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3376,8 +3376,12 @@ def image(self, ops, mods, how): if len(ops) < 3: raise Unsupported('image instruction with %d operands, expected at least 3' % len(ops)) dst = reg_range(ops[0]) - dim = [m for m in mods if m.startswith('dim:')][0][4:] - dmask = int([m for m in mods if m.startswith('dmask:')][0][6:], 0) + dims = [m for m in mods if m.startswith('dim:')] + dmasks = [m for m in mods if m.startswith('dmask:')] + if not dims or not dmasks: + raise Unsupported('image instruction without %s' % ('dim:' if not dims else 'dmask:')) + dim = dims[0][4:] + dmask = int(dmasks[0][6:], 0) kinds = {'SQ_RSRC_IMG_1D': 'tex1d', 'SQ_RSRC_IMG_2D': 'tex2d', 'SQ_RSRC_IMG_3D': 'tex3d', 'SQ_RSRC_IMG_2D_ARRAY': 'tex2da'} if dim not in kinds: raise Unsupported('image dimension %s' % dim) From 1405d94536f230df7b08041ef081ba656af10e7b Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Thu, 26 Nov 2026 02:51:40 +0800 Subject: [PATCH 092/232] startup: refuse a short operand list in the scalar ALU handlers (#2469) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * startup: refuse a short operand list in the scalar ALU handlers Every SALU form in `SCA` is written destination, source, and `Stage.scalar` reads `ops[0]` and `ops[1]` before it formats the template. A short list indexed past the end, so the batch translator recorded `translator crash in s_add_u32: IndexError` — its marker for a translator defect, not for text it does not lower — and the single-shader path did not catch it at all. 18 of the 44 `SCA` entries had this shape; `s_cselect_b32`, `s_abs_i32`, `s_bcnt1_i32_b32`, `s_addk_i32` and the `s_cmp*` forms already refused correctly. before: s_add_u32 -> translator crash in s_add_u32: IndexError after: s_add_u32 -> s_add_u32 with 0 operands, expected 2 before: s_add_u32 s0 -> translator crash in s_add_u32: IndexError after: s_add_u32 s0 -> s_add_u32 with 1 operands, expected 2 `op_s_bfm_b32` keeps its own body (it folds constant masks and reads `ops[0]` for the `m0` destination), so it gets the same count check in place rather than through `scalar`. `tests/startup_gfx2hlsl_scalar_arity_check.py` covers one accepted shape per entry, both short forms for all 44 `SCA` entries, the refusal text, and a control that loads the translator with the guard removed and requires `IndexError` for `s_add_u32`, `s_mov_b32`, `s_mul_hi_u32` and `s_not_b64` — so the check cannot pass without the guard: python out/pe-env/Scripts/python.exe -B tests/startup_gfx2hlsl_scalar_arity_check.py scalar ALU operand count checks: 0 failed PASS All 63 `tests/startup_gfx2hlsl_*_check.py` exit 0, and the `startup_gfx2hlsl` ctest subset passes 131/131 on this branch (658 s), so no accepted form changed. * tests: register and prove the scalar ALU arity check The check added by the previous commit needs the three registration points every pure-Python fixture has: `CTest` (name `startup_gfx2hlsl_scalar_arity`, visible in `ctest -N`), the Linux `Run Python checks` list in `.github/workflows/windows.yml`, and the "Pure-Python checks" list in `AGENTS.md`. Both production guards are pinned by removing them one at a time and requiring the new check to fail: scalar guard removed -> exit 1 bfm guard removed -> exit 1 restored -> exit 0 `cmake --preset dev` regenerates and `ctest --preset dev -N -R scalar_arity` finds the test, so it is not a file that exists without being run. * docs: record the rule that a short operand list is refused, not a translator crash `Stage.translate` records any non-`Unsupported` exception as `translator crash in : `, and the refusal census reads that as a translator defect rather than as text the translator does not lower. The count checks that keep it from happening were added one family at a time (#2360 buffers, #2373 images, #2396 single-body VOP bodies, #2469 scalar ALU) without a single place saying why the check exists, so this adds the rule and the four entry points to `docs/experiments.md`. No behaviour change; `tests/docs_links_check.py` passes (19 files, 466 links). --------- Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 22 ++++ tests/startup_gfx2hlsl_scalar_arity_check.py | 122 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 5 + 6 files changed, 154 insertions(+) create mode 100644 tests/startup_gfx2hlsl_scalar_arity_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 10065406a..a3e34e972 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -214,6 +214,7 @@ jobs: tests/startup_image_3d_check.py \ tests/startup_image_load_mip_check.py \ tests/startup_gfx2hlsl_operand_count_check.py \ + tests/startup_gfx2hlsl_scalar_arity_check.py \ tests/startup_image_2d_array_check.py \ tests/startup_image_sample_a16_check.py \ tests/startup_image_load_d16_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2c9e2bdda..126793b0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,6 +162,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_3d_check.py ./out/pe-env/bin/python -B tests/startup_image_load_mip_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_operand_count_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3e4604d1b..4bc735d71 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2969,6 +2969,9 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl refuses a binary32 or integer vector operation with a source too few or too many. add_test(NAME startup_gfx2hlsl_operand_count COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_operand_count_check.py") + # gfx2hlsl refuses a scalar ALU operation whose operand list is too short. + add_test(NAME startup_gfx2hlsl_scalar_arity COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_arity_check.py") # gfx2hlsl lowers v_swap_b32 (VOP1): CPU evaluation of the translated text, refusals of every form llvm-mc rejects. add_test(NAME startup_gfx2hlsl_swap COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_swap_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index b31ebc06b..94c9da18e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14787,3 +14787,25 @@ that names one value (a pointer only if no add touched it), is read at run time read before its next write when a path brings a symbol with no run-time value or no definition at all. `startup_gfx2hlsl_join_symbols_check.py` pins the cases; the `join_symbols_folded_*` tests run the old OUTSIDE statement and must give 3, not 11. Controls are pure Python plus a pixel dispatch on WARP and hardware; `binary` reassembles the fixture words with LLVM 15. + +## Startup translator: a short operand list is refused, never a translator crash + +The batch translator records any non-`Unsupported` exception from a handler as +`translator crash in : `, which its refusal census reads as a translator defect rather than as an +instruction it does not lower; the single-shader path does not catch it at all. Handlers that keep their +operands in method bodies instead of a table therefore need an explicit count check before the first `ops[...]` +read, or text the ISA cannot produce reaches the census as a defect. + +Three families have been closed this way, one pull request per family, each with a control that removes the +check and requires the old exception to come back: + +| family | entry point | short form before | refusal now | +| --- | --- | --- | --- | +| buffer loads and stores | `buffer_address` | `translator crash: IndexError` | ` with N operands, expected 4` | +| image instructions | `image()` | `translator crash: IndexError` | ` with N operands, expected at least 3`, `image instruction without dim:` | +| single-body VOP handlers | the handler body | `translator crash: IndexError` | ` with N operands, expected 2`, `… 3 or 4` | +| scalar ALU (`SCA`) | `Stage.scalar` | `translator crash: IndexError` | ` with N operands, expected 2` | + +The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity_check.py`, +`…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game +data, because a refusal is observable at the `Stage` entry point. diff --git a/tests/startup_gfx2hlsl_scalar_arity_check.py b/tests/startup_gfx2hlsl_scalar_arity_check.py new file mode 100644 index 000000000..6ae07e326 --- /dev/null +++ b/tests/startup_gfx2hlsl_scalar_arity_check.py @@ -0,0 +1,122 @@ +"""Operand counts of the scalar ALU table (SCA) in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_scalar_arity_check.py + +Every SALU form in `SCA` is written as destination, source, so its body reads `ops[0]` and `ops[1]`. +A short list indexed past the end and left `translator crash in : IndexError` in the refusal census, +which is the marker the batch translator uses for a translator defect rather than for an instruction it +does not lower. This checks the accepted shape and the refusal of the two short forms for every binary +and unary entry, then loads the translator with the guard removed and requires `IndexError` to come back, +so the check cannot pass without it. +""" +import importlib.util +import sys +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')) +import gfx2hlsl as G # noqa: E402 + +GUARD = """ if base != 's_movk_i32' and len(ops) < 2: + raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) + if base == 's_movk_i32' and len(ops) != 2:""" +failures = [] + + +def check(label, condition, detail=''): + print('%s: %s' % (label, 'ok' if condition else 'MISMATCH ' + detail)) + if not condition: + failures.append(label) + + +def probe(module): + class Probe(module.Stage): + """A Stage with no pipeline: enough state for one scalar instruction to be translated.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks, self.attrs = set(), {} + self.exec_known = True + + return Probe + + +def outcome(module, line): + """'ok', 'refused' or the name of another exception for one instruction text.""" + try: + probe(module)().one(line.split()[0], line) + except module.Unsupported: + return 'refused' + except Exception as error: # noqa: BLE001 - the name is the observation + return type(error).__name__ + return 'ok' + + +# One accepted shape per entry: the guard must not refuse a complete instruction. +ACCEPTED = { + 's_add_u32': 's_add_u32 s0, s1, s2', + 's_add_i32': 's_add_i32 s0, s1, s2', + 's_sub_u32': 's_sub_u32 s0, s1, s2', + 's_mul_i32': 's_mul_i32 s0, s1, s2', + 's_and_b32': 's_and_b32 s0, s1, s2', + 's_or_b32': 's_or_b32 s0, s1, s2', + 's_xor_b32': 's_xor_b32 s0, s1, s2', + 's_lshl_b32': 's_lshl_b32 s0, s1, 4', + 's_lshr_b32': 's_lshr_b32 s0, s1, 4', + 's_ashr_i32': 's_ashr_i32 s0, s1, 4', + 's_min_i32': 's_min_i32 s0, s1, s2', + 's_max_u32': 's_max_u32 s0, s1, s2', + 's_mul_hi_u32': 's_mul_hi_u32 s0, s1, s2', + 's_bfm_b32': 's_bfm_b32 s0, s1, s2', + 's_pack_hh_b32_b16': 's_pack_hh_b32_b16 s0, s1, s2', + 's_and_b64': 's_and_b64 s[0:1], s[2:3], s[4:5]', + 's_or_b64': 's_or_b64 s[0:1], s[2:3], s[4:5]', + 's_mov_b32': 's_mov_b32 s0, s1', + 's_not_b32': 's_not_b32 s0, s1', + 's_brev_b32': 's_brev_b32 s0, s1', + 's_sext_i32_i8': 's_sext_i32_i8 s0, s1', + 's_mov_b64': 's_mov_b64 s[0:1], s[2:3]', + 's_not_b64': 's_not_b64 s[0:1], s[2:3]', + 's_movk_i32': 's_movk_i32 s0, 0x1', +} + +for name, text in sorted(ACCEPTED.items()): + got = outcome(G, text) + check('translates: %s' % text, got == 'ok', got) + +# Every SCA entry must refuse the two short forms and name the instruction and both counts. +for name in sorted(G.SCA): + for text, count in ((name, 0), (name + ' s0', 1)): + got = outcome(G, text) + check('%s: refuses %d operands' % (name, count), got == 'refused', got) + +# The refusal text names the instruction and both counts, so the census groups it by instruction. +for name in ('s_add_u32', 's_mov_b32', 's_and_b64'): + try: + probe(G)().one(name, name + ' s0') + except G.Unsupported as reason: + check('%s: the refusal names the instruction and both counts' % name, + str(reason) == '%s with 1 operands, expected 2' % name, repr(str(reason))) + +# Negative control: without the guard the same input raises IndexError and a complete form still translates. +source = Path(G.__file__).read_text(encoding='utf-8') +check('control: the guard is in the translator once', source.count(GUARD) == 1, + 'count=%d' % source.count(GUARD)) +unguarded_source = source.replace(GUARD, " if base == 's_movk_i32' and len(ops) != 2:") +spec = importlib.util.spec_from_loader('gfx2hlsl_unguarded_scalar', loader=None) +unguarded = importlib.util.module_from_spec(spec) +unguarded.__dict__['__file__'] = G.__file__ +exec(compile(unguarded_source, G.__file__, 'exec'), unguarded.__dict__) +for name in ('s_add_u32', 's_mov_b32', 's_mul_hi_u32', 's_not_b64'): + got = outcome(unguarded, name) + check('control: without its guard %s with 0 operands raises IndexError' % name, + got == 'IndexError', got) +check('control: without its guard a complete s_add_u32 still translates', + outcome(unguarded, ACCEPTED['s_add_u32']) == 'ok') + +print('scalar ALU operand count checks: %d failed' % len(failures)) +if failures: + raise SystemExit(1) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 8c3d090f2..b065c045e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2365,6 +2365,11 @@ def sdwa(self, base, ops, mods): # scalar ALU with descriptor-word bookkeeping def scalar(self, base, ops): + # Every SALU form in SCA is dst, src (the two templates below use {0} and {1}); a short list would + # index past the end and leave `translator crash in : IndexError` in the census instead of a + # refusal. s_movk_i32 keeps its own exact check for the immediate it folds. + if base != 's_movk_i32' and len(ops) < 2: + raise Unsupported('%s with %d operands, expected 2' % (base, len(ops))) if base == 's_movk_i32' and len(ops) != 2: raise Unsupported('s_movk_i32 with %d operands, expected 2' % len(ops)) text, scc = SCA[base] From adf4e3bfb25cd85b614e37b62b1c1661ef5f62bc Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Thu, 26 Nov 2026 02:53:30 +0800 Subject: [PATCH 093/232] startup: name why s_getpc_b64 is refused instead of reporting the mnemonic alone (#2484) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * startup: name why s_getpc_b64 is refused instead of reporting the mnemonic alone Refs #2463 (third item: `s_getpc_b64` refused in a pixel stage). The refusal for `s_getpc_b64` came from the dispatcher fallthrough, which raises `Unsupported(base)` with the bare mnemonic. For a captured request that reads as "the translator has no handler for this instruction", when the reason is specific: RDNA 2 GETPC returns the address of its successor, i.e. the shader's load address plus a known byte offset, which is not an integer this model can emit. `calculated_pc_proof()` elides the pair, but only for a program that also calculates a branch target; reaching the fallthrough means no such proof exists. before: s_getpc_b64 -> s_getpc_b64 after: s_getpc_b64 -> s_getpc_b64: the shader load address is only elided for a program that also calculates a branch target Same form a captured request carries — `s_getpc_b64 s[a:b]`, one operand, 4-byte encoding — refused in both a pixel and a compute stage, with and without the `s_add_u32`/`s_addc_u32` pair that turns it into a pointer, and with the pair used directly as a descriptor. `tests/startup_gfx2hlsl_getpc_refusal_check.py` pins the text for six forms (3 forms x 2 stages), the "longer than the mnemonic" property, and a control that a program whose `s_setpc_b64` target is proven does not reach this refusal (the GETPC is elided and emits no line). python out/pe-env/Scripts/python.exe -B tests/startup_gfx2hlsl_getpc_refusal_check.py getpc refusal checks: 0 failed PASS The guard removed -> exit 1, restored -> exit 0. All 63 `tests/startup_gfx2hlsl_*_check.py` exit 0, including `startup_gfx2hlsl_calculated_target_check.py`, which pins an exhaustive refusal list containing a bare `s_setpc_b64` — the message is narrowed to `s_getpc_b64` so that list is unchanged. Not done, and stated rather than implied: this does not lower the instruction. Whether the pair can be lowered for a program without `s_setpc_b64` needs the captured requests to see what consumes it; without them the refusal is the honest outcome and the message now says why. * tests: require the proven GETPC control to translate --------- Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + tests/startup_gfx2hlsl_getpc_refusal_check.py | 80 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 6 ++ 5 files changed, 91 insertions(+) create mode 100644 tests/startup_gfx2hlsl_getpc_refusal_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index a3e34e972..a0229f0b0 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -289,6 +289,7 @@ jobs: tests/compute_alu_lane_gaps_check.py \ tests/startup_ngg_slice_check.py \ tests/startup_gfx2hlsl_handler_arity_check.py \ + tests/startup_gfx2hlsl_getpc_refusal_check.py \ tests/startup_gfx2hlsl_image_arity_check.py \ tests/run_checks_parallel_check.py build-and-test: diff --git a/AGENTS.md b/AGENTS.md index 126793b0f..2851ded0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -237,6 +237,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py ./out/pe-env/bin/python -B tests/run_checks_parallel_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py ``` diff --git a/CMakeLists.txt b/CMakeLists.txt index 4bc735d71..443eb1dfb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2984,6 +2984,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_watch PROPERTIES TIMEOUT 120) add_test(NAME startup_gfx2hlsl_handler_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_handler_arity_check.py") + # gfx2hlsl names why s_getpc_b64 is refused instead of reporting the mnemonic alone. + add_test(NAME startup_gfx2hlsl_getpc_refusal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_getpc_refusal_check.py") # Image instructions with fewer than three operands (#2360 follow-up): the handler refused # them as an index error before it checked the count. add_test(NAME startup_gfx2hlsl_image_arity COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_getpc_refusal_check.py b/tests/startup_gfx2hlsl_getpc_refusal_check.py new file mode 100644 index 000000000..df0a9bc07 --- /dev/null +++ b/tests/startup_gfx2hlsl_getpc_refusal_check.py @@ -0,0 +1,80 @@ +"""`s_getpc_b64` names why it is refused instead of reporting the mnemonic alone. + +usage: startup_gfx2hlsl_getpc_refusal_check.py + +RDNA 2 GETPC returns the address of its successor, i.e. the shader's load address plus a known byte offset, which +the HLSL model cannot represent as an integer. `calculated_pc_proof()` elides the pair when the program also +calculates a branch target; a program that reaches the dispatcher without such a proof was refused with the bare +mnemonic, which the refusal census cannot tell apart from an instruction the translator has no handler for. + +This checks the named refusal for the forms a pixel or compute stage can carry, and the negative control: the same +instruction inside a program whose `s_setpc_b64` target is proven is elided, so the message only covers the unproven +case. +""" +import sys +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')) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_calculated_target_check import POSITIVE, assert_result, translate # noqa: E402 + +REASON = ('s_getpc_b64: the shader load address is only elided for a program that also calculates a branch target') +failures = [] + + +def check(label, condition, detail=''): + print('%s: %s' % (label, 'ok' if condition else 'MISMATCH ' + detail)) + if not condition: + failures.append(label) + + +def probe(kind): + class Probe(G.Stage): + """A Stage with no pipeline: enough state for one program to be translated.""" + + def __init__(self): + self.lines, self.sym, self.attrs = [], {}, {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known, self.kind = True, kind + + return Probe() + + +def refusal(lines, kind='ps'): + stage = probe(kind) + stage.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(lines)] + try: + stage.translate() + except G.Unsupported as reason: + return str(reason), stage.lines + return None, stage.lines + + +# The forms a captured request can carry: the instruction alone, with the low/high word arithmetic that makes the +# pair a pointer, and with the pair used directly as a descriptor. +FORMS = ( + ['s_getpc_b64 s[4:5]'], + ['s_getpc_b64 s[4:5]', 's_add_u32 s4, s4, 0x10', 's_addc_u32 s5, s5, 0'], + ['s_getpc_b64 s[4:5]', 's_load_dword s0, s[4:5], 0x0'], +) +for kind in ('ps', 'cs'): + for lines in FORMS: + reason, _ = refusal(lines, kind) + check('%s: %s names the reason' % (kind, ' ; '.join(lines)[:52]), reason == REASON, repr(reason)) + +# The refusal is not the bare mnemonic: that is the regression this check exists for. +reason, _ = refusal(['s_getpc_b64 s[4:5]']) +check('the refusal is longer than the mnemonic', reason != 's_getpc_b64', repr(reason)) +check('the refusal mentions the load address', reason is not None and 'load address' in reason, repr(reason)) + +# A proven control must translate and skip the decoy. +assert_result(translate(POSITIVE), (0, 20, 24), 24) +print('control: the proven calculated jump translates and skips the decoy: ok') + +print('getpc refusal checks: %d failed' % len(failures)) +if failures: + raise SystemExit(1) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index b065c045e..a33bc741f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2196,6 +2196,12 @@ def lower(self, base, asm, ops, mods): return self.set_v(reg_range(ops[0])[1], text.format(*args)) if base in SCA: return self.scalar(base, ops) + if base == 's_getpc_b64': + # RDNA 2 GETPC returns the address of its successor: the shader's load address plus a known byte + # offset, which is not an integer this model can emit. It is elided only when the program also + # calculates a branch target, which calculated_pc_proof() proves and records. Reaching here means no + # such proof was found, so name the reason instead of reporting the mnemonic alone. + raise Unsupported('%s: the shader load address is only elided for a program that also calculates a branch target' % base) raise Unsupported(base) # VOP1/VOP2 with DPP16 quad broadcast (#2125 item A): quad_perm:[k,k,k,k] makes every lane read SRC0 from From ab3f481984a029fce30d234a07007afd620b4943 Mon Sep 17 00:00:00 2001 From: KelboLive <168463230+KelboLive@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:55:17 -0500 Subject: [PATCH 094/232] PR #1924: align not_checked schema and add suite (#2503) Co-authored-by: Kelbo From 374e8b1498fbd38d3214beed6689c2607d015fcd Mon Sep 17 00:00:00 2001 From: SuperCraft3M <69873238+SuperCraft3M@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:00:17 +0100 Subject: [PATCH 095/232] tooling: allow startup diagnostics without time or assertion limits (#1794) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/startup_debug_check.py | 7 +++++++ tools/startup/debug_launch.py | 15 ++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index 02123b3d4..e09524c72 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -130,6 +130,13 @@ def stack_read(address, size): assert "process exited with 0x00000000" in out, out assert "debug-probe heap flags 0x70\n" in text(logdir / "stdout.txt"), missing_heap_flags(logdir) + out, _ = run(probe, work, "unlimited", {}, options=("--timeout", "0", "--continue-asserts", "-1")) + assert "process exited with 0x00000000" in out and "timeout after" not in out, out + out, _ = run(probe, work, "assert-cap", {}, options=("--timeout", "0", "--continue-asserts", "1")) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out, out + out, _ = run(probe, work, "finite", {}, options=("--timeout", "1", "--continue-asserts", "-1")) + assert "timeout after" in out and "process exited with" not in out, out + # X2W_STOP_AT on the second site: the first is still stepped over, the run stops at the second. out, logdir = run(probe, work, "stop", {"X2W_STOP_AT": f"{sites[1]:x}"}) assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out and "first chance" in out, out diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index f5f37bb0c..472bd5289 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -4,7 +4,8 @@ Records module loads, every exception (code, address as module+offset, first/second chance) and, for the stopping exception, the integer registers, the stack words and the code bytes around RIP. -Stops at the first second-chance exception, at a breakpoint inside the main image, or at the timeout. +Stops at a second-chance exception, an uncontinued main-image breakpoint, or the timeout. +A timeout of zero disables the timer. An assertion continuation limit of -1 removes that limit. """ import ctypes import ctypes.wintypes as wt @@ -117,10 +118,13 @@ def main(): def print(*args, **kwargs): summary.append(" ".join(str(a) for a in args)) builtins.print(*args, **kwargs) - timeout = float(opts.get("--timeout", 15)) + timeout = float(opts.get("--timeout", 15)) # zero leaves the session running until exit or a debug stop memory = int(float(opts.get("--memory-gib", 16)) * 2**30) stop_first = opts.get("--stop-first-chance") == "1" - skip_asserts = int(opts.get("--continue-asserts", "0")) # main-image int3s to log and continue past + skip_asserts = int(opts.get("--continue-asserts", "0")) # -1 continues all diagnostic assertions + if timeout < 0 or not timeout < float("inf") or skip_asserts < -1: + print("expected a finite nonnegative timeout and an assertion limit of -1 or greater") + return 2 asserts_seen = {} # X2W_HOST_CPU=1: rewrite main-image instructions the host processor lacks (host_cpu.py). host_cpu_on = os.environ.get("X2W_HOST_CPU") == "1" @@ -610,7 +614,7 @@ def poll_watches(): watch_values[rva] = blob log(f"{time.time() - start:7.3f} watch +{rva:#x} = {blob.hex(' ')}") - while time.time() - start < timeout: + while not timeout or time.time() - start < timeout: if dump_at and time.time() - start >= dump_at[0]: dump_threads(os.path.join(logdir, f"threads_{dump_at.pop(0):g}.txt")) if watches and time.time() >= watch_next: @@ -741,7 +745,8 @@ def poll_watches(): log(f"X2W_LOG_AT ignored {rva:#x}: cannot arm a main-image instruction breakpoint") del log_at[rva] elif (ex_code == 0x80000003 and first and main_base and main_base <= ex_addr < main_base + 0x10000000 - and sum(asserts_seen.values()) < skip_asserts and (ex_addr - main_base) not in stop_at): + and (skip_asserts == -1 or sum(asserts_seen.values()) < skip_asserts) + and (ex_addr - main_base) not in stop_at): asserts_seen[ex_addr] = asserts_seen.get(ex_addr, 0) + 1 status = DBG_CONTINUE # rip is already past the int3 elif (not first) or stop_first or (ex_code == 0x80000003 and main_base and From 394f24f8330c3f85bdfc9b6d9a268086e3c44fd2 Mon Sep 17 00:00:00 2001 From: RenzoWit35 <168984533+RenzoWit35@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:02:35 +0100 Subject: [PATCH 096/232] tooling: add an x87 area to the CPU fuzz test (#1667) * tooling: add an x87 area to the CPU fuzz test Refs #446. Adds cpu_aot_fuzz_x87 with its own seed (0x8087, 40 exports): straight-line x87 code translated through the x87 profile of the shared integer lowering (ffx_version_query.lower with x87=True), as the cpu_aot_x87_* fixtures translate it. The generator loads m32, m64 and m80 floats, m16, m32 and m64 integers, constants and ST(i); runs FADD, FSUB, FSUBR, FMUL, FDIV and FDIVR in their memory, register and popping forms, the FI forms, FCHS, FABS, FSQRT, FRNDINT and FXCH; stores with FST, FSTP, FIST, FISTP and FISTTP; compares with the FCOMI family and SETcc, and into the status word with FNSTSW AX and SAHF or AND AH; and moves with FCMOVcc. It tracks the stack depth, so nothing overflows or underflows and the stack is empty at the RET, and reads PF only where the profile defines it. FNSTCW stores the control word, so a native run under another word would mismatch. Inputs cover denormals, NaN payloads, unsupported m80 encodings and integer-store overflow. Four controls must be refused, and a planted subr_as_sub mutant, which lowers FSUBR and FSUBRP as FSUB and FSUBP, must be detected. The other areas' emitted MASM and translations are unchanged. * docs: name FINCSTP as the fourth refused x87 fuzz control The fourth negative control in X87_CONTROLS is the fld1/fincstp/fdecstp sequence, not FSIN (open PR #1663 lowers FSIN). --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 41 +++++++ docs/experiments.md | 2 + tools/fuzz_cpu.py | 253 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 293 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 443eb1dfb..47eefcc11 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4286,6 +4286,47 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "${cpu_fuzz_loops_o2}" --area loops --mutant "$") set_tests_properties(cpu_aot_fuzz_loops PROPERTIES TIMEOUT 60) + + # Straight-line x87 code through the shared lowering's x87 profile, with FSUBR lowered as FSUB planted. + set(CPU_FUZZ_X87_SEED "0x8087" CACHE STRING "Seed for the CPU differential fuzz x87 test") + set(CPU_FUZZ_X87_FUNCTIONS "40" CACHE STRING "Number of exported functions in the CPU differential fuzz x87 test") + set(cpu_fuzz_x87_asm "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_x87.asm") + set(cpu_fuzz_x87_def "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_x87.def") + add_custom_command(OUTPUT "${cpu_fuzz_x87_asm}" "${cpu_fuzz_x87_def}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" emit + "${CPU_FUZZ_X87_SEED}" "${CPU_FUZZ_X87_FUNCTIONS}" "${cpu_fuzz_x87_asm}" + "${cpu_fuzz_x87_def}" --area x87 + DEPENDS tools/fuzz_cpu.py VERBATIM) + add_library(cpu_fuzz_x87 SHARED "${cpu_fuzz_x87_asm}" "${cpu_fuzz_x87_def}") + set_target_properties(cpu_fuzz_x87 PROPERTIES LINKER_LANGUAGE CXX) + target_link_options(cpu_fuzz_x87 PRIVATE /NOENTRY /NODEFAULTLIB /INCREMENTAL:NO /OPT:NOICF) + set(cpu_fuzz_x87_lifted "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_x87_lifted.cpp") + set(cpu_fuzz_x87_mutant "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_x87_mutant.cpp") + foreach(variant lifted mutant) + set(mutant_flag "") + if(variant STREQUAL "mutant") + set(mutant_flag "--mutant") + endif() + add_custom_command(OUTPUT "${cpu_fuzz_x87_${variant}}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" translate + "${CPU_FUZZ_X87_SEED}" "${CPU_FUZZ_X87_FUNCTIONS}" "$" + "${cpu_fuzz_x87_${variant}}" --area x87 ${mutant_flag} + DEPENDS cpu_fuzz_x87 tools/fuzz_cpu.py tools/ffx_version_query.py tools/x87_lower.py tools/x87_soft.h + tools/cpu_leaf_aot.py tools/cpu_ranges.py VERBATIM) + add_library(cpu_fuzz_x87_${variant} SHARED "${cpu_fuzz_x87_${variant}}") + target_compile_features(cpu_fuzz_x87_${variant} PRIVATE cxx_std_20) + endforeach() + set(cpu_fuzz_x87_o2 "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_x87_lifted_o2.dll") + add_custom_command(OUTPUT "${cpu_fuzz_x87_o2}" + COMMAND "${CMAKE_CXX_COMPILER}" /nologo /O2 /W4 /LD "${cpu_fuzz_x87_lifted}" + "/Fo${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_x87_lifted_o2.obj" "/Fe${cpu_fuzz_x87_o2}" + DEPENDS "${cpu_fuzz_x87_lifted}" VERBATIM) + add_custom_target(cpu_fuzz_x87_lifted_o2 ALL DEPENDS "${cpu_fuzz_x87_o2}") + add_test(NAME cpu_aot_fuzz_x87 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" check "${CPU_FUZZ_X87_SEED}" "${CPU_FUZZ_X87_FUNCTIONS}" + "$" "$" "${cpu_fuzz_x87_o2}" + --area x87 --mutant "$") + set_tests_properties(cpu_aot_fuzz_x87 PROPERTIES TIMEOUT 60) cpu_asm_fixture(cpu_switch_addr32 switch_addr32) cpu_asm_fixture(cpu_switch_strings switch_strings) cpu_asm_fixture(cpu_string_probe string_probe) diff --git a/docs/experiments.md b/docs/experiments.md index 94c9da18e..728f6c991 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3137,6 +3137,8 @@ Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_smoke$' -V`. `CPU_FUZ `cpu_aot_fuzz_loops` (`--area loops`) covers counted loops on the shared [translator](../tools/cpu_switch_aot.py) from its own seed, so the areas above are unchanged (their `emit` output and translations are byte-identical to the previous revision). Every export ends its loop with a backward conditional branch and takes one of four forms: a counter from n down to 1 (`DEC` or `SUB 1`, then `JNZ`) or from n-1 down to 0 (`DEC`, then `JNS`); an index from 0 up to n-1 (`INC`, `CMP` with the count, then `JB`, `JNE` or `JL`); a counter that may start at 0, with a `TEST` and `JZ` in front that skips the loop; and a counter that drops by 2 or 3 while it stays above 0 (`SUB`, then `JG`). The count is x masked to four bits, plus one where the loop has no guard, and only the loop's own update writes the counter, so every input ends after at most 16 iterations. Each iteration updates RAX and one or two other registers from each other and from the counter (64- and 32-bit `ADD`, `SUB`, `XOR`, three-operand `IMUL`, `ROL`, `ROR`, `LEA`, `NOT` and `NEG`), so their values carry from one iteration to the next. Some exports first push one or two of RBX, RSI and RDI, carry a value in the first of them and pop them on both exits. A value also carries through the output buffer: the loop updates the qword at output offset 24 in place, reads it back into a register, adds one to an iteration count at offset 32 and writes RAX into a per-iteration slot from offset 64, indexed by the counter. Half the exports have a data-dependent early exit: a `TEST` of AL or R10D or an unsigned `CMP` of EAX with a constant leads to a second exit that records the counter (the count, in the up form) and returns another combination. Half nest a second loop inside the first: x masked to three bits, plus one, counts the outer loop, and the low three bits of the carried RAX, plus one, count the inner loop, so its trip count changes from one outer iteration to the next (at most 8 by 8). The inner loop adds R10 into a per-iteration slot from offset 192 and ends with `DEC` and `JNZ`. The 32 default exports at seed `0x100F` are the 16 combinations of form, nesting and early exit, twice, in a seeded order: 48 backward branches (32 outer and 16 inner), 16 exports with pushed registers. On its 313 inputs, the native exports take the early exit in 1,573 of 10,016 calls, skip the guarded loop in 632 and run the outer loop more than once in 6,380, up to 16 times. The test makes 20,032 native, default and `/O2` comparisons of RAX and the 256-byte output buffer in about 0.5 s. The planted translator fault, `--mutant` (`back_edge_exit`), retargets every backward conditional branch to its own fallthrough, so each loop body runs once and every input still terminates; the test fails unless that build differs from native. At the default seed it differed in 7,439 of 10,016 calls, in all 32 exports. Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the export's MASM and the reproduction command. `CPU_FUZZ_LOOPS_SEED` and `CPU_FUZZ_LOOPS_FUNCTIONS` select a longer run. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 128 exports each made 80,128 comparisons per seed in about 1.6 s, with no refusal and no mismatch; each has 192 backward branches, and the planted fault differed in 29,248 to 29,894 of 40,064 calls, in all 128 exports. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_loops$' -V`. The generator does not use loops whose count is not bounded by a mask, an unconditional backward `JMP`, `LOOP` or `REP` forms, frames with stack slots, calls inside a loop, or loops that share a head. +`cpu_aot_fuzz_x87` (`--area x87`) covers the x87 profile of the shared integer lowering ([`ffx_version_query.lower`](../tools/ffx_version_query.py) with `x87=True`, documented in [`x87_lower.py`](../tools/x87_lower.py)) from its own seed, so the areas above are unchanged (their `emit` output and translations are byte-identical to the previous revision). The area translates each export as the `cpu_aot_x87_*` fixtures do, one `lower` call per function range with the x87 helpers of `x87_soft.h`, into `lifted_(x, y, out)` like the other areas. Every export is straight-line code. It first writes its operands to the output buffer: x at offset 0 and y at 8 (read as m16, m32 and m64 integers and as m32 and m64 floats), and two m80 values, x with the top word of y as sign and exponent at 16 and y with the top word of x at 32. `FNSTCW` then stores the control word at 48. The lowering fixes that word at 0x027F, so a native run under another control word would mismatch there. The body loads (`FLD` m32, m64, m80 and ST(i), `FILD` m16, m32 and m64, and `FLD1`, `FLDZ`, `FLDPI`, `FLDL2T`, `FLDL2E`, `FLDLG2` and `FLDLN2`), computes (`FADD`, `FSUB`, `FSUBR`, `FMUL`, `FDIV` and `FDIVR` with an m32 or m64 operand, with ST(0), ST(i), with ST(i), ST(0) and in their popping forms, the `FI` forms with an m16 or m32 integer, `FCHS`, `FABS`, `FSQRT`, `FRNDINT` and `FXCH`), stores (`FST` and `FSTP` to m32, m64, m80 and ST(i), `FIST`, `FISTP` and `FISTTP`), compares with `FCOMI`, `FCOMIP`, `FUCOMI` or `FUCOMIP` followed by `SETcc`, compares into the status word (`FCOM`, `FCOMP`, `FCOMPP`, `FUCOM`, `FUCOMP`, `FUCOMPP` with ST(i) or memory, `FTST`, `FICOM`, `FICOMP`, `FXAM`) followed by `FNSTSW AX` and either `SAHF` and `SETcc` or `AND AH, 45h` and a byte store of C0, C2 and C3, and moves with `FCMOVcc` after an `FCOMI`, `SAHF` or `CMP RCX, RDX`. Every result goes to output bytes 64 to 255, and RAX is the first result qword. The generator tracks the stack depth, so every instruction finds the registers it reads occupied, no push exceeds eight and the stack is empty at the `RET`. It reads PF (`SETP`, `SETNP`, `FCMOVU`, `FCMOVNU`) only after `FCOMI` or `SAHF`, and never C1 or the exception flags, which the profile leaves unknown. Values are not restricted: the check inputs are the 17 x 17 combinations of 17 operand words (doubles at every edge, including denormals, infinities, a quiet NaN with a payload and a signalling NaN, words whose halves are two edge floats, and integer edges), then normal m80 values near 1 and random bits, so denormals, NaN payloads, integer-store overflow and the m80 encodings that the processor treats as unsupported all occur; `x87_soft.h` models them bit for bit and nothing is masked. Four negative controls in the same DLL are translated one at a time, and the test fails unless each is refused for its own reason: nine pushes (`x87 stack overflow`), a store from an empty stack (`x87 stack underflow`), a return with a value on the stack (`x87 stack not empty at return`) and `FINCSTP` (`unsupported x87 operation`). The planted translator fault, `--mutant` (`subr_as_sub`), lowers `FSUBR` and `FSUBRP` like `FSUB` and `FSUBP`, so a reversed subtraction gives the negated difference; the code stays straight-line, and the test fails unless that build differs from native. At the default seed `0x8087` the 40 exports hold 688 x87 instructions: 192 loads, 113 arithmetic operations, 57 unary operations and exchanges, 146 stores, 28 `FCOMI`-family and 47 status-word compares, and 18 `FCMOVcc`. Measured on Windows 11 build 26300 with MSVC 19.51 (Visual Studio Build Tools, toolset 14.51) and ML64 14.51: 25,040 native, default and `/O2` comparisons matched in 1.3 to 3.2 s in the `dev` and `release` presets, the four controls were refused, and the planted fault differed in 675 of 12,520 calls, in 7 of the 10 exports that use `FSUBR` or `FSUBRP`. Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the reproduction command. `CPU_FUZZ_X87_SEED` and `CPU_FUZZ_X87_FUNCTIONS` select a longer run, for example `cmake --preset dev -DCPU_FUZZ_X87_SEED=0xBEEF -DCPU_FUZZ_X87_FUNCTIONS=160`, then `cmake --build --preset dev --target cpu_fuzz_x87_lifted cpu_fuzz_x87_lifted_o2 cpu_fuzz_x87_mutant` and the `ctest` command below. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 160 exports each made 100,160 comparisons per seed in about 4 s, with no refusal and no mismatch; the planted fault differed in 4,518, 2,959, 4,679 and 4,686 of 50,080 calls. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_x87$' -V`. The generator does not use `FXTRACT`, `FSCALE`, the checked entry's `FLDCW`, `FNINIT`, `FPREM`, `FPREM1`, `FBLD` and `FBSTP`, `FNSTSW` m16, `FFREE`, `FFREEP`, branches or calls with x87 state, or a caller value on the x87 stack (the `cpu_aot_x87_*` fixtures cover those through `tests/cpu/x87_harness.asm`). + ## Mesh draw fallback The bounded mesh translator can emit `cs_6_0` entry `main` and `vs_6_0` entry diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index cc659c2e9..7d86ed926 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -8,6 +8,7 @@ import re import struct import sys +import types WIDTHS = { "b": ("al", "dl", "BYTE PTR", 1), @@ -1566,16 +1567,243 @@ def generate_loops(seed, count): return [loop_function(f"fuzz_loop_{index}", rng, *shapes[index % len(shapes)]) for index in range(count)] +# Straight-line x87 sequences for the x87 profile of the shared integer lowering (ffx_version_query.lower with +# x87=True, tools/x87_lower.py). Each export is fn(x, y, out) with x in RCX, y in RDX and the output buffer in R8. +# It first writes its operands to the buffer: x at 0 and y at 8 (read as m16, m32, m64 integers and m32 and m64 +# floats), and two m80 values, x with the top word of y at 16 and y with the top word of x at 32. FNSTCW then +# stores the control word at 48, which the lowering fixes at 0x027F, so a native run under another control word +# shows up as a mismatch there. Every later result goes to bytes 64 to 255: FST, FSTP, FIST, FISTP and FISTTP +# stores, SETcc after FCOMI and SAHF, and C0, C2 and C3 after FNSTSW AX. RAX is the first result qword. +# The generator tracks the stack depth, so every instruction finds the registers it reads occupied and no push +# exceeds eight; it leaves the stack empty at the RET, and reads a flag only where the profile defines it (PF only +# after FCOMI or SAHF). Values are not restricted: denormals, NaN payloads, infinities and the m80 encodings that +# the processor treats as unsupported all occur, because x87_soft.h models them bit for bit. +X87_INTEGERS = {"m16": ("WORD PTR", (0, 2, 8, 10)), "m32": ("DWORD PTR", (0, 4, 8, 12)), "m64": ("QWORD PTR", (0, 8))} +X87_FLOATS = {"m32": ("DWORD PTR", (0, 4, 8, 12)), "m64": ("QWORD PTR", (0, 8)), "m80": ("TBYTE PTR", (16, 32))} +X87_SIZES = {"m16": 2, "m32": 4, "m64": 8, "m80": 10} +X87_CONSTANTS = ("fld1", "fldz", "fldpi", "fldl2t", "fldl2e", "fldlg2", "fldln2") +X87_ARITHMETIC = ("fadd", "fsub", "fsubr", "fmul", "fdiv", "fdivr") +X87_UNARY = ("fchs", "fabs", "fsqrt", "frndint") +# FCOMI leaves ZF, CF and PF; CMP RCX, RDX leaves the integer flags, of which the profile models no PF. +X87_SETS = ("e", "ne", "a", "ae", "b", "be", "p", "np") +X87_FCMOV = ("b", "e", "be", "nb", "ne", "nbe", "u", "nu") +X87_RESULTS = 64 +X87_END = 256 +X87_WEIGHTS = {"load": 5, "arith": 6, "unary": 2, "exchange": 1, "store": 3, "fcomi": 2, "status": 2, "fcmov": 1} +X87_COUNT_OPERATIONS = (6, 14) +# Negative controls: a body the profile must refuse and the reason it must give. +X87_CONTROLS = { + "overflow": ([*["fld1"] * 9, *["fstp st(0)"] * 9, "ret"], "x87 stack overflow"), + "underflow": (["fstp QWORD PTR [r8+64]", "ret"], "x87 stack underflow"), + "live": (["fld1", "ret"], "x87 stack not empty at return"), + # FINCSTP and FDECSTP move TOP without a tag change, which the profile documents as outside its model. + "fincstp": (["fld1", "fincstp", "fdecstp", "fstp QWORD PTR [r8+64]", "ret"], "unsupported x87 operation"), +} + + +class X87Builder: + def __init__(self, rng): + self.rng = rng + self.depth = 0 + self.cursor = X87_RESULTS + # The flags a reader may use: "fcomi" after FCOMI or SAHF (ZF, CF and PF), "integer" after CMP, or None. + self.flags = None + self.lines = ["mov QWORD PTR [r8], rcx", "mov QWORD PTR [r8+8], rdx", "mov QWORD PTR [r8+16], rcx", + "mov rax, rdx", "shr rax, 48", "mov WORD PTR [r8+24], ax", "mov QWORD PTR [r8+32], rdx", + "mov rax, rcx", "shr rax, 48", "mov WORD PTR [r8+40], ax", "fnstcw WORD PTR [r8+48]"] + + def result(self, size): + """The next result slot of size bytes; past the end of the buffer the slots start again at 64.""" + if self.cursor + size > X87_END: + self.cursor = X87_RESULTS + offset, self.cursor = self.cursor, self.cursor + size + return f"[r8+{offset}]" + + def other(self): + return self.rng.randrange(1, self.depth) + + def memory(self, table, kinds): + ptr, offsets = table[self.rng.choice(kinds)] + return f"{ptr} [r8+{self.rng.choice(offsets)}]" + + def operation(self, kind): + """Emit one operation of kind if the stack depth allows it; return whether it did.""" + rng, depth = self.rng, self.depth + if kind == "load" and depth < 8: + choice = rng.choice(("float", "float", "integer", "constant", "register")) + if choice == "register" and depth: + self.lines.append(f"fld st({rng.randrange(depth)})") + elif choice == "integer": + self.lines.append(f"fild {self.memory(X87_INTEGERS, ('m16', 'm32', 'm64'))}") + elif choice == "constant": + self.lines.append(rng.choice(X87_CONSTANTS)) + else: + self.lines.append(f"fld {self.memory(X87_FLOATS, ('m32', 'm64', 'm80'))}") + self.depth += 1 + elif kind == "arith" and depth: + op = rng.choice(X87_ARITHMETIC) + form = rng.choice(("memory", "integer") + (("st0", "sti", "pop", "pop") if depth > 1 else ())) + if form == "memory": + self.lines.append(f"{op} {self.memory(X87_FLOATS, ('m32', 'm64'))}") + elif form == "integer": + self.lines.append(f"fi{op[1:]} {self.memory(X87_INTEGERS, ('m16', 'm32'))}") + elif form == "st0": + self.lines.append(f"{op} st, st({self.other()})") + elif form == "sti": + self.lines.append(f"{op} st({self.other()}), st") + else: + self.lines.append(f"{op}p st({self.other()}), st") + self.depth -= 1 + elif kind == "unary" and depth: + self.lines.append(rng.choice(X87_UNARY)) + elif kind == "exchange" and depth > 1: + self.lines.append(f"fxch st({self.other()})") + elif kind == "store" and depth: + self.store(rng.random() < 0.6) + elif kind == "fcomi" and depth > 1: + pop = rng.random() < 0.4 + self.lines.append(f"{rng.choice(('fcomi', 'fucomi'))}{'p' if pop else ''} st, st({self.other()})") + self.depth -= pop + self.flags = "fcomi" + self.lines.append(f"set{rng.choice(X87_SETS)} BYTE PTR {self.result(1)}") + elif kind == "status" and depth: + self.status() + elif kind == "fcmov" and depth > 1: + if self.flags is None or rng.random() < 0.3: + self.lines.append("cmp rcx, rdx") + self.flags = "integer" + conditions = X87_FCMOV if self.flags == "fcomi" else X87_FCMOV[:6] + self.lines.append(f"fcmov{rng.choice(conditions)} st, st({self.other()})") + else: + return False + return True + + def store(self, pop): + rng = self.rng + choice = rng.choice(("float", "float", "integer", "truncate") + (("register",) if self.depth > 1 else ())) + if choice == "register": + self.lines.append(f"{'fstp' if pop else 'fst'} st({self.other()})") + elif choice == "float": + kind = rng.choice(("m32", "m64", "m80") if pop else ("m32", "m64")) + self.lines.append(f"{'fstp' if pop else 'fst'} {X87_FLOATS[kind][0]} {self.result(X87_SIZES[kind])}") + elif choice == "integer" and (pop or rng.random() < 0.5): + kind = rng.choice(("m16", "m32", "m64") if pop else ("m16", "m32")) + self.lines.append(f"{'fistp' if pop else 'fist'} {X87_INTEGERS[kind][0]} {self.result(X87_SIZES[kind])}") + else: + kind = rng.choice(("m16", "m32", "m64")) + self.lines.append(f"fisttp {X87_INTEGERS[kind][0]} {self.result(X87_SIZES[kind])}") + pop = True + self.depth -= pop + + def status(self): + """A comparison into C0, C2 and C3, read through FNSTSW AX and then SAHF or AND AH, 45h.""" + rng, depth = self.rng, self.depth + forms = ["fcom", "fcomp", "fucom", "fucomp", "fcom_memory", "fcomp_memory", "ftst", "ficom", "ficomp", "fxam"] + if depth > 1: + forms += ["fcompp", "fucompp"] + form = rng.choice(forms) + if form in ("fcom", "fcomp", "fucom", "fucomp"): + self.lines.append(f"{form} st({self.other()})" if depth > 1 else f"{form} st(0)") + elif form.endswith("_memory"): + self.lines.append(f"{form.split('_')[0]} {self.memory(X87_FLOATS, ('m32', 'm64'))}") + elif form in ("ficom", "ficomp"): + self.lines.append(f"{form} {self.memory(X87_INTEGERS, ('m16', 'm32'))}") + else: + self.lines.append(form) + self.depth -= {"fcomp": 1, "fucomp": 1, "fcomp_memory": 1, "ficomp": 1, "fcompp": 2, "fucompp": 2}.get(form, 0) + self.lines.append("fnstsw ax") + if rng.random() < 0.5: + self.lines += ["sahf", f"set{rng.choice(X87_SETS)} BYTE PTR {self.result(1)}"] + self.flags = "fcomi" + else: + # C1 (FXAM's sign), the exception flags, TOP and the busy bit are not known to the profile. + # AH cannot be addressed with an R8 base, so MOVZX moves it to AL first. + self.lines += ["and ah, 45h", "movzx eax, ah", f"mov BYTE PTR {self.result(1)}, al"] + self.flags = None + + def finish(self): + while self.depth: + self.store(True) + # AX may still hold status-word bits that the profile does not know; RAX is overwritten before the RET. + self.lines += [f"mov rax, QWORD PTR [r8+{X87_RESULTS}]", "ret"] + + +def x87_function(name, rng, first): + builder = X87Builder(rng) + builder.operation("load") + builder.operation("load") + builder.operation(first) + for _ in range(rng.randint(*X87_COUNT_OPERATIONS)): + for _ in range(12): + if builder.operation(rng.choices(list(X87_WEIGHTS), list(X87_WEIGHTS.values()))[0]): + break + builder.finish() + return Function(name, builder.lines) + + +def generate_x87(seed, count): + """Exports of straight-line x87 code, each starting with an operation of every kind in turn, then four + refused controls.""" + rng = random.Random(seed) + kinds = list(X87_WEIGHTS) + functions = [x87_function(f"fuzz_x87_{index}", rng, kinds[index % len(kinds)]) for index in range(count)] + return [*functions, *(Function(f"fuzz_x87_refused_{kind}", lines, refused=reason) + for kind, (lines, reason) in X87_CONTROLS.items())] + + +# Operand words for the x87 area: doubles at every edge (zeros, denormals, the largest finite value, infinities, a +# quiet NaN with a payload and a signalling NaN, 2^63), words whose halves are two edge floats, and integer edges. +X87_VALUES = (0x0000000000000000, 0x8000000000000000, 0x3ff0000000000000, 0xbff8000000000000, 0x0000000000000001, + 0x800fffffffffffff, 0x7fefffffffffffff, 0x7ff0000000000000, 0xfff8000012345678, 0x7ff0000000000001, + 0x43e0000000000000, 0xc1e0000000200000, 0x3f800000bf800000, 0x7f80000000000001, 0x7fc00000ff7fffff, + 0x4b800001c7000000, 0x00008000ffff7fff) + + +def x87_inputs(seed): + """313 pairs: every combination of the 17 operand words, then normal m80 values near 1 (x with its top bit set + and y with an exponent within 70 of the bias in its top word) and random bits.""" + values = [(a, b) for a in X87_VALUES for b in X87_VALUES] + rng = random.Random(seed ^ 0x8087) + while len(values) < 313: + if len(values) % 2: + values.append((rng.getrandbits(64), rng.getrandbits(64))) + continue + exponents = [(0x3FFF + rng.randint(-70, 70)) | rng.choice((0, 0x8000)) for _ in range(2)] + x = 1 << 63 | rng.getrandbits(47) << 16 | exponents[0] + values.append((x, exponents[1] << 48 | rng.getrandbits(48))) + return values + + +def x87_translate(image, names): + """Lower each export through ffx_version_query.lower with the x87 profile, as the cpu_aot_x87_* fixtures do, + to fn(x, y, out) with the lifted_ prefix of the other areas.""" + import pefile + from cpu_leaf_aot import export_rva + from cpu_ranges import function_ranges + from ffx_version_query import INTEGER_HEADER, lower, region + from x87_lower import X87_HEADER + + parts = [INTEGER_HEADER, X87_HEADER] + with pefile.PE(str(image), fast_load=True) as pe: + for name in names: + (bounds,) = function_ranges(pe, export_rva(pe, name)) + code = lower(region(pe, *bounds), ["rcx = a; rdx = b; r8 = c;"], {}, {}, {}, x87=True) + parts.append(f'extern "C" __declspec(dllexport) word lifted_{name}(word a, word b, word c) {{\n{code}\n}}\n') + return "".join(parts), None + + AREAS = {"leaf": (generate, "cpu_fuzz"), "frames": (generate_frames, "cpu_fuzz_frames"), "calls": (generate_calls, "cpu_fuzz_calls"), "chains": (generate_chains, "cpu_fuzz_chains"), "switches": (generate_switches, "cpu_fuzz_switches"), "scalar_fp": (generate_scalar_fp, "cpu_fuzz_scalar_fp"), "rsp": (generate_rsp, "cpu_fuzz_rsp"), - "loops": (generate_loops, "cpu_fuzz_loops")} + "loops": (generate_loops, "cpu_fuzz_loops"), "x87": (generate_x87, "cpu_fuzz_x87")} def inputs_for(seed, area="leaf", signature=None): if area == "scalar_fp": return fp_inputs(seed, signature.split(":")[1][:2]) + if area == "x87": + return x87_inputs(seed) boundary = [ 0, 1, 2, 3, 7, 0x0F, 0x10, 0x1F, 0x20, 0x3F, 0x40, 0x7F, 0x80, 0x81, 0xFF, 0x100, 0x7FFF, 0x8000, 0xFFFF, 0x10000, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x100000000, @@ -1622,12 +1850,15 @@ def call_symbol(symbol, function, x, y, out): def translator_module(area): - """The module that lifts the functions of an area: the scalar SSE lifter, or the shared one.""" + """The module that lifts the functions of an area: the scalar SSE lifter, the x87 profile of the shared + integer lowering, or the shared one.""" sys.path.insert(0, str(Path(__file__).resolve().parent)) if area == "scalar_fp": import cpu_sse_aot return cpu_sse_aot + if area == "x87": + return types.SimpleNamespace(translate=x87_translate) import cpu_switch_aot return cpu_switch_aot @@ -1932,10 +2163,26 @@ def translate(*args, **kwargs): cpu_switch_aot.translate = translate +def plant_subr_as_sub(lifter, image, functions): + """Lower FSUBR and FSUBRP like FSUB and FSUBP, so that they compute ST(0) minus the other operand. + + This is a planted translator fault for the negative control: the stack, the other operations and FISUBR are + unchanged, but a reversed subtraction of two different values gives the negated difference. The code stays + straight-line, so every input still terminates. + """ + from iced_x86 import Mnemonic as M + import x87_lower + + if not any(re.search(r"^\s+fsubrp? ", function.asm(), re.M) for function in functions if not function.refused): + raise SystemExit("the subr_as_sub fault found no FSUBR or FSUBRP") + x87_lower.ARITHMETIC[M.FSUBR] = x87_lower.ARITHMETIC[M.FSUBRP] = "x87_sub" + + MUTANTS = {"frames": ("reload_shift", plant_reload_shift), "calls": ("call_retarget", plant_call_retarget), "chains": ("swapped_arguments", plant_swapped_arguments), "switches": ("table_rotate", plant_table_rotate), "scalar_fp": ("minmax_swap", plant_minmax_swap), - "rsp": ("stale_rsp", plant_stale_rsp), "loops": ("back_edge_exit", plant_back_edge_exit)} + "rsp": ("stale_rsp", plant_stale_rsp), "loops": ("back_edge_exit", plant_back_edge_exit), + "x87": ("subr_as_sub", plant_subr_as_sub)} def translate(seed, count, image, output, area="leaf", mutant=False): From 2cc59aeeff72a9bc543f3fe232cf6748c2d6ab2a Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:06:28 +0100 Subject: [PATCH 097/232] startup: lower scalar complements whose sources are all lane masks (#2459) s_nand_b32, s_nor_b32 and s_xnor_b32 were refused whenever an operand was a lane mask. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask (vcc_lo, exec_lo or an SGPR holding a compare mask) and an SGPR destination the lane's bit of the result is exact. SCC is (the whole complemented word != 0), which the bits of the other lanes decide. It is not emitted: the write is recorded as an SCC effect that is not modelled, and the existing stale-SCC scan refuses a program that can read it before the next SCC write, through joins and back edges. The mask mark follows program order. At a branch target a marked SGPR stays proven only if its last write dominates the target and no block on a path from that write to the target writes it again; a complement on any other marked SGPR is refused until the register is written again. A mask mixed with a plain word or a constant, and a vcc_lo, exec_lo or m0 destination, stay refused. Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 12 +- .../startup_gfx2hlsl_sop2_complement_check.py | 136 +++++++++++++++++- tools/startup/gfx2hlsl.py | 67 +++++++-- 3 files changed, 199 insertions(+), 16 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 728f6c991..808fa0b99 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7533,11 +7533,15 @@ Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_b64_shift$' -V`. (#870, issue #1919). They now lower as `~(S0 & S1)`, `~(S0 | S1)` and `~(S0 ^ S1)` on 32 bits, the text `pixel_aot` uses, and set SCC when the result is nonzero like the other logic operations. The check decodes SGPR, in-place, inline-constant, literal and m0-destination forms and evaluates the emitted lines against an -integer reference over 0, all ones, alternating bits, every single bit and mixed words. Lane-mask forms (a -vcc_lo/exec_lo operand or destination, or an SGPR holding a compare mask) are refused: guest SCC reads the whole -32-bit mask, which the per-lane projection cannot show. A table +integer reference over 0, all ones, alternating bits, every single bit and mixed words. A table entry without the complement or without the SCC write must fail, and SOP2 operations with no lowering stay -refused by name. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with +refused by name. On lane masks (vcc_lo, exec_lo or an SGPR holding a compare mask) the result is exact per lane +when every source is a mask, because bit i of the complement depends only on bit i of each source: that form +lowers to `(~(a op b)) & 1` into an SGPR, checked on all 32 lanes of the edge words. Guest SCC reads the whole +32-bit result, which the per-lane projection cannot show, so SCC is not emitted and a program that can read it +before the next SCC write is refused, through joins and back edges. A mask mixed with a plain word or a constant +and a vcc_lo or exec_lo destination stay refused, as does a mask source whose last write does not dominate a +branch target crossed since, or which a block on a path to that target writes again. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sop2_complement$' -V`; with LLVM 15, `tests/startup_gfx2hlsl_sop2_complement_check.py binary ` and `decode ` round-trip the same words. diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 2655ba134..6c1b7de02 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -16,9 +16,18 @@ The lowering text and SCC rule equal pixel_aot's SCALAR entries for the same operations (#561). Every numeric form (SGPR, inline, literal or m0 operands) emits the lines of its non-complement sibling (s_and_b32, s_or_b32, s_xor_b32) -with the operation wrapped in ~( ). Lane-mask forms are refused: a vcc_lo or exec_lo operand or destination, or an -SGPR holding a compare mask, is the whole wave's mask, and SCC is set when any bit of the complemented 32-bit result -is; the translator's per-lane projection cannot show that, so no mask lowering is claimed. +with the operation wrapped in ~( ). + +Lane masks: vcc_lo, exec_lo or an SGPR holding a compare mask is the whole wave's mask, of which the translator keeps +one lane's bit. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask and an +SGPR destination the lane's bit of the result is exact: the form is accepted and checked here on every lane of the +edge words. SCC is set when any bit of the complemented 32-bit result is, which the other lanes decide (the bit of an +idle lane is set); the per-lane projection cannot show that, so SCC is not emitted and a program that can read it +before the next SCC write is refused (through branches too). A mask and a plain word mixed, a constant source, and a +vcc_lo or exec_lo destination stay refused. The mask mark follows program order, so a mark is a proof at a branch +target only if the register's last write dominates the target and no block on a path from that write to the target +writes the register again; otherwise the complement is refused until the register is written again. Mutations: the +join rule disabled and the SCC read scan disabled must each accept a refused program. Mutations: the table entry with the complement dropped, and the entry with the SCC write dropped, must each read a wrong result or SCC. Refused: every SOP2 operation the decoder names that still has no lowering. @@ -228,6 +237,124 @@ def first_mismatch(name, reference=None, updates_scc=True): return None +def run_text(*instructions): + """Translate disassembly text with the branch scan of a real stage -> emitted lines.""" + stage = Probe() + stage.attrs = {} + stage.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + stage.translate() + return [line for _, lines, _ in stage.blocks for line in lines] + + +def text_refusal(*instructions): + try: + return 'accepted: %s' % run_text(*instructions) + except G.Unsupported as error: + return str(error) + + +def lane_mask_controls(): + operator = {name: SIBLING_OPERATOR[sibling] for name, (sibling, _) in OPS.items()} + # 1. Every source a lane mask, SGPR destination: one line, the lane's bit of the complement, and no SCC write. + forms = [('s3, s1, s2', 's3', 's1', 's2'), ('s1, s2, s1', 's1', 's2', 's1'), ('s3, vcc_lo, s1', 's3', 'vcc', 's1'), + ('s3, s2, exec_lo', 's3', 's2', 'exec'), ('s3, vcc_lo, exec_lo', 's3', 'vcc', 'exec')] + for name, (_, reference) in OPS.items(): + wrong = [] + for operands, dest, left, right in forms: + stage = Probe() + stage.masks.update((1, 2)) + stage.one(name, '%s %s' % (name, operands)) + expected = ['%s = (~(%s %s %s)) & 1;' % (dest, left, operator[name], right)] + if stage.lines != expected or int(dest[1:]) not in stage.masks or stage.scc_effect != 'a lane-mask complement': + wrong.append((operands, stage.lines, expected, sorted(stage.masks), stage.scc_effect)) + continue + for a, b in ((a, b) for a in SPECIAL for b in SPECIAL): + for lane in range(32): + env = {left: (a >> lane) & 1, right: (b >> lane) & 1, 'scc': SCC_UNSET} + out = run_lines(stage.lines, env) + if (out[dest], out['scc']) != ((reference(a, b) >> lane) & 1, SCC_UNSET): + wrong.append((operands, hex(a), hex(b), lane, out[dest], out['scc'])) + break + check('%s: %d all-mask forms give the lane bit of the reference on 32 lanes x %d pairs, SCC not written' + % (name, len(forms), len(SPECIAL) ** 2), not wrong, str(wrong[:2])) + + # 2. Still refused: a constant or plain-word source next to a mask, a mask destination, a high-half mask name. + for name in OPS: + wrong = [] + for operands in ('s3, s1, s9', 's3, s9, vcc_lo', 's3, s1, -1', 's3, 0, vcc_lo', 'vcc_lo, s1, s2', + 'exec_lo, s1, s2', 's3, s1, vcc_hi', 'm0, s1, s2'): + stage = Probe() + stage.masks.update((1, 2)) + try: + stage.one(name, '%s %s' % (name, operands)) + wrong.append((operands, stage.lines)) + except G.Unsupported as error: + if str(error) != '%s on a lane mask' % name or stage.lines: + wrong.append((operands, str(error), stage.lines)) + check('%s: mixed, constant and mask-destination forms stay refused' % name, not wrong, str(wrong[:2])) + + # 3. Whole programs. SCC after the complement is not the guest's: a read before the next SCC write is refused. + masks = ('v_cmp_eq_f32_e64 s5, 0, v1', 'v_cmp_lt_f32_e64 s4, 0, v2') + for name in OPS: + complement = '%s s4, s5, s4' % name + line = 's4 = (~(s5 %s s4)) & 1;' % operator[name] + lines = run_text(*masks, complement, 's_and_saveexec_b32 s4, s4', 's_endpgm') + at = lines.index(line) if line in lines else -1 + check('%s between two compares and s_and_saveexec_b32 is accepted' % name, + at >= 0 and lines[at + 1:at + 3] == ['w = s4;', 's4 = exec;'] and 'scc = s4 != 0;' not in lines, str(lines)) + lines = run_text(*masks, complement, 's_cmp_eq_u32 s2, 0', 's_cselect_b32 s6, 1, 0', 's_endpgm') + check('%s then an SCC write then a read is accepted' % name, + line in lines and any(text.startswith('s6 = scc ?') for text in lines), str(lines)) + programs = { + 's_cselect_b32': (*masks, complement, 's_cselect_b32 s6, 1, 0', 's_endpgm'), + 's_cbranch_scc1': (*masks, complement, 's_cbranch_scc1 label_0010', 's_endpgm'), + # the read sits behind a jump that skips the SCC write + 's_cmov_b32': (*masks, complement, 's_branch label_0014', 's_cmp_eq_u32 s2, 0', 's_cmov_b32 s6, s7', + 's_endpgm'), + # the read sits at a loop head that the complement reaches over the back edge + 's_cselect_b64': ('s_cmp_eq_u32 s2, 0', 's_cselect_b64 s[6:7], 1, 0', *masks, complement, + 's_cbranch_vccz label_0004', 's_endpgm'), + } + got = {reader: text_refusal(*program) for reader, program in programs.items()} + want = {reader: 'scc from a lane-mask complement in %s' % reader for reader in programs} + check('%s: an SCC read before the next SCC write is refused (%d programs)' % (name, len(programs)), + got == want, str(got)) + + # 4. The mask mark at a branch target. + skip = ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_0010', *masks) # the branch skips both compares + loop = (*masks, 's_nand_b32 s6, s5, s4', 's_mov_b32 s5, s3', 's_cmp_eq_u32 s2, 0', 's_cbranch_scc0 label_0008', + 's_endpgm') # the body overwrites s5 before the back edge + arms = ('v_cmp_eq_f32_e64 s5, 0, v1', 's_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_0014', 'v_cmp_lt_f32_e64 s4, 0, v2', + 's_branch label_0020', 'v_cmp_lt_f32_e64 s4, 0, v3', 's_nand_b32 s4, s5, s4', 's_and_saveexec_b32 s4, s4', + 's_endpgm') # s5 is written before the split only + joined = 's_nand_b32 on a lane mask joined at a branch target' + got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] + check('a mask that another path into the branch target changes is refused (skipped write, loop body write)', + got == [joined, joined], str(got)) + lines = run_text(*arms) + check('a mask written before the split and on no arm crosses the join', 's4 = (~(s5 & s4)) & 1;' in lines, str(lines)) + lines = run_text(*skip, *masks, 's_nand_b32 s6, s5, s4', 's_endpgm') + check('a mask written again after the join is proven again', 's6 = (~(s5 & s4)) & 1;' in lines, str(lines)) + got = text_refusal(*masks, 's_mov_b32 s5, s3', 's_nand_b32 s6, s5, s4', 's_endpgm') + check('an overwritten mask is a plain word: refused', got == 's_nand_b32 on a lane mask', got) + + # 5. Mutations: each rule disabled accepts a program refused above. + saved = G.Stage.unjoined_masks + G.Stage.unjoined_masks = lambda self, target, last_write: set() + try: + got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] + finally: + G.Stage.unjoined_masks = saved + check('mutation without the join rule accepts both programs', all(t.startswith('accepted') for t in got), str(got)) + saved = G.Stage.descriptor_scc_reads + G.Stage.descriptor_scc_reads = lambda self, branches, effects: iter(()) + try: + got = text_refusal(*masks, 's_nand_b32 s4, s5, s4', 's_cselect_b32 s6, 1, 0', 's_endpgm') + finally: + G.Stage.descriptor_scc_reads = saved + check('mutation without the SCC read scan accepts the read', got.startswith('accepted'), got) + + def pack_controls(): def reference(a, b): return (b // 65536) * 65536 + a // 65536 @@ -501,7 +628,7 @@ def controls(): check('%s: %d numeric forms emit the %s lines complemented, same mask and EXEC bookkeeping' % (name, len(VALUE_FORMS), sibling), not wrong, str(wrong[:2])) - # 5b. Lane-mask forms are refused: vcc_lo/exec_lo operands and destinations, and an SGPR holding a compare mask. + # 5b. Refused: a lane mask next to a plain word, or as the destination (lane_mask_controls has the accepted forms). for name in OPS: accepted = [] for form in MASK_FORMS: @@ -560,6 +687,7 @@ def controls(): wrong.append((asm, str(error))) check('%d SOP2 operations without a lowering are refused by name (%s)' % (len(missing), ', '.join(missing)), missing and not wrong and not set(OPS) & set(missing), str(wrong)) + lane_mask_controls() pack_controls() bfe_controls() mul_controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a33bc741f..d38afdbd5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1618,8 +1618,35 @@ def joined_registers(self, with_cfg=False): regs = set().union(*(writes[w] for w in div)) if div else set() affected = ({off_of[w] for w in div} | ({off_of[ipd]} if ipd is not None else set())) & all_targets div_targets[off] = (regs, affected) + self.flow = (index, block_of, succ, dom, writes, {}) return joined, forward_splits, div_targets + def unjoined_masks(self, target, last_write): + """Marked SGPRs whose mark is not proven at a branch target. self.masks follows program order, so a mark + holds on every path into the target only if the block of the register's last write dominates the target and + no block on a path from that write to the target writes the register again.""" + index, block_of, succ, dom, writes, reached = self.flow + if target not in index: + return set(self.masks) + def after(block): # blocks reached from block over at least one edge + if block not in reached: + seen, todo = set(), list(succ[block]) + while todo: + b = todo.pop() + if b not in seen: + seen.add(b) + todo += succ[b] + reached[block] = seen + return reached[block] + t = block_of[index[target]] + into = {b for b in range(len(succ)) if t in after(b)} + out = set() + for reg in self.masks: + w = block_of[index[last_write[reg]]] if reg in last_write else 0 + if w not in dom[t] or any(reg in writes[b] for b in (after(w) & into) - {w}): + out.add(reg) + return out + def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ try: @@ -1671,6 +1698,8 @@ def translate(self): self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.masks = set(init_masks) + self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined_masks) + last_write = {} # SGPR -> offset of its last write in program order self.attrs = dict(init_attrs) self.used_s, self.used_v = set(init_used_s), set(init_used_v) self.exports = {} @@ -1748,6 +1777,7 @@ def translate(self): if reg != 'm0': self.used_s.add(reg) clobber = here if off in joined else every_sgpr + self.join_masks |= self.unjoined_masks(off, last_write) fwd_clobber = forward_splits.get(off, clobber) blocked = force_unproven | force_at.get(off, set()) kept_u = { @@ -1786,6 +1816,7 @@ def translate(self): falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests + last_write.update(dict.fromkeys(dests, off)) try: if off in refused: raise Unsupported(refused[off]) @@ -1815,6 +1846,8 @@ def translate(self): raise refusals.append((handler_error(name, error, refusals), self.kind)) continue + # A write proves the mark again: every path from here on runs it. s_movreld can write any SGPR. + self.join_masks = (self.join_masks | every_sgpr) if 'any' in dests else self.join_masks - dests if self.scc_effect: scc_effects[off] = self.scc_effect if term: @@ -1843,9 +1876,9 @@ def translate(self): if self.lines: self.blocks.append((start, self.lines, None)) self.materialized = materialize # declarations() assigns these before the body (and before any loop) - if 'descriptor' in scc_effects.values(): - for name in self.descriptor_scc_reads(dict(branches), scc_effects): - reason = 'scc from descriptor data in %s' % name + if set(scc_effects.values()) - {'emitted'}: + for kind, name in self.descriptor_scc_reads(dict(branches), scc_effects): + reason = 'scc from %s in %s' % ('descriptor data' if kind == 'descriptor' else kind, name) if refusals is None: raise Unsupported(reason) refusals.append((reason, self.kind)) @@ -1860,7 +1893,7 @@ def translate(self): def descriptor_scc_reads(self, branches, effects): """Find reads reachable with an elided SCC write, including through joins and back edges.""" instructions = {off: (size, name, asm) for off, size, name, asm in self.ins} - pending = [(0, False)] + pending = [(0, None)] # stale: None, or the scc_effect of the write that left the emitted scc behind seen = set() while pending: off, stale = pending.pop() @@ -1869,9 +1902,9 @@ def descriptor_scc_reads(self, branches, effects): seen.add((off, stale)) size, name, asm = instructions[off] if stale and off not in self.calculated_pc and reads_scc(name, asm): - yield name + yield stale, name if off in effects: - stale = effects[off] == 'descriptor' + stale = effects[off] if effects[off] != 'emitted' else None if off in branches: pending.append((branches[off], stale)) if name not in ('s_branch', 's_setpc_b64', 's_endpgm'): @@ -2394,6 +2427,7 @@ def low(tok): srcs = [str(sopk_imm(srcs[0], True))] # D.i32 = signext(SIMM16) shift_add = base in SHIFT_ADD word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') + lane_complement = False # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. word_pack = base in ('s_pack_hh_b32_b16', 's_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') if shift_add or word_complement or word_pack: @@ -2401,8 +2435,19 @@ def low(tok): # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' else self.is_lane_mask(dname)) - if mask_dest or any(self.is_lane_mask(t) for t in srcs): + # Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask the lane's + # bit of the result is exact. Only an SGPR destination is taken; a mixed mask and plain word is not. + def mask_source(tok): + r = reg_range(tok) + return tok in ('vcc', 'vcc_lo', 'exec', 'exec_lo') or bool( + r and r[0] == 's' and r[1] == r[2] and r[1] in self.masks) + lane_complement = (word_complement and bool(dst) and dst[0] == 's' and dst[1] == dst[2] and dst[1] <= 105 + and all(mask_source(t) for t in srcs)) + if not lane_complement and (mask_dest or any(self.is_lane_mask(t) for t in srcs)): raise Unsupported('%s on a lane mask' % base) + if lane_complement and any(reg_range(t) and reg_range(t)[1] in getattr(self, 'join_masks', ()) + for t in srcs): + raise Unsupported('%s on a lane mask joined at a branch target' % base) if shift_add and dname != 'm0' and (not dst or dst[0] != 's' or dst[1] != dst[2] or dst[1] > 105): raise Unsupported('%s destination %s' % (base, dname)) if word_pack: @@ -2542,7 +2587,13 @@ def known(tok): high_source = 's%d' % high if high is not None else srcs[0] high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) - self.set_s(d, expr, scc=scc) + self.set_s(d, expr, scc=None if lane_complement else scc) + if lane_complement: + # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an + # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. + self.scc_effect = 'a lane-mask complement' + if self.tracks_uniformity(): + self.scc_uniform = False if is_mask: self.masks.add(d) if pair and base != 's_mov_b64': From 17821310127a90a3d413ed6ae4b30222c274b7d6 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 03:08:36 +0800 Subject: [PATCH 098/232] tests: draw all overlapping SDWA movrel register pairs (#2472) * tests: draw all overlapping SDWA movrel register pairs AI-assisted with Codex + GPT-6.2 Astra (xhigh). * docs: describe how the SDWA overlap draw enumerates m0 --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 7 +++++++ tests/pixel_aot_check.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 808fa0b99..3dbacf88a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8100,6 +8100,13 @@ The plain VOP1 (`_e32`) and VOP3 (`_e64`) encodings of the same four moves (`v_m The SDWA encodings of the four moves (`v_movreld_b32_sdwa`, `v_movrels_b32_sdwa`, `v_movrelsd_b32_sdwa`, `v_movrelsd_2_b32_sdwa`; LLVM 15 decodes `7e1886f9 00001518` as `v_movrels_b32_sdwa v12, v24 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0` for gfx1013 and gfx1030 alike) lower through the same movrel block (#1917). The source selection, with an optional `sext(...)`, applies to the indexed source word, and the destination selection to each indexed destination, as `v_mov_b32_sdwa` applies them (`sdwa_source`, `sdwa_dest`); that order follows the RDNA 2 naming and the other movrel forms and has not been measured on RDNA hardware. `UNUSED_PAD` zeroes the unselected bits and `UNUSED_PRESERVE` keeps them from that destination's own tracked old value, so under a dynamic `m0` every reachable destination merges its own word. Under a dynamic `m0` every reachable destination must hold a tracked numeric word, also for `UNUSED_PAD`, as for the other movrel forms. `UNUSED_SEXT`, `UNUSED_PRESERVE` into an untracked destination, `clamp`, 16-bit (low-half) values as source or kept destination, SGPR sources and the movrel refusals are refused. `SDWA_MOVREL_BODY` runs each move with a dynamic and a static `m0` over integer banks, mixing BYTE, WORD and DWORD selections, `sext`, `UNUSED_PAD` and `UNUSED_PRESERVE`, and exports four words through the bit-exact R32G32B32A32_UINT target. They must equal an independent SDWA model on both `DPP_MOVREL_SETS`; the expected words are (`0x008856aa 0x3600ffbb 0xffffffdd 0x332143bb` and `0x00cc56aa 0x3600ffb9 0x0048ffdd 0x887743bb`), which they did on WARP (driver 10.0.26100.8972) and an NVIDIA Quadro M1000M (driver 32.0.15.7371) on Windows 11 build 26100. Five controls must mismatch, and did on both adapters: a dropped source selection, `UNUSED_PRESERVE` turned into `UNUSED_PAD`, an ignored dynamic `m0`, the wrong source byte and a missing `sext`. The translation controls check nine refusals, the entry mask and a dynamic `UNUSED_PRESERVE` move inside one bank, where each reachable register merges its own old word, and the body is in the LLVM 15 round trip. The device-free run also pins every selection in the body: `SDWA_MOVREL_PINS` lists the exact expression each source and destination selection produces (temporaries as `\d+`) and how often it must appear, so a dropped source or destination selection, an ignored `sext` or `UNUSED_PRESERVE` treated as `UNUSED_PAD` fails `python -B tests/pixel_aot_check.py`, not only the draw. Reproduce with `ctest --preset dev --no-tests=error -R "^pixel_aot_sdwa_movrel_" -V`. +The SDWA draw also exports all four words of a single VGPR bank after +`v_movrelsd_2_b32_sdwa` copies BYTE_0 of the indexed source to BYTE_1 of +the indexed destination with UNUSED_PRESERVE. One compiled shader runs in +a single renderer batch. Each of the 16 index pairs has its own draw with +`m0 = (dst << 16) | src`, including four draws with `dst == src`. A final +draw repeats the (3, 3) case with the unchanged bank as a negative reference. + The scalar relative moves `s_movrels_b32`, `s_movrels_b64`, `s_movreld_b32`, `s_movreld_b64` and `s_movrelsd_2_b32` (SOP1; LLVM 15 decodes `be942e28` as `s_movrels_b32 s20, s40` and the others alike for gfx1013 and gfx1030) lower with the same `m0` split as the vector forms (#1882): `s_movrels` reads SGPR[src + m0], `s_movreld` writes SGPR[dst + m0], and `s_movrelsd_2_b32` reads with `m0[9:0]` and writes with `m0[25:16]`; `_b64` moves a pair, with `m0` counted in dwords. That reading follows the RDNA 2 naming and the vector forms; it has not been measured on RDNA hardware. With a static `m0` the move is an `s_mov` from or to the indexed SGPR, so its tracked value (constant, expression, descriptor or pointer word) and bit mask carry over: moving the texture descriptor pointer with `s_movrels_b64 s[72:73], s[16:17]` and `m0` = 4 translates exactly like two `s_mov_b32`. A dynamic `m0` with a proven bit mask becomes a bounded select, and only over plain numeric SGPRs, so no resource depends on a runtime index; for `s_movreld` each reachable destination keeps its old value unless selected. An unbounded or non-numeric `m0`, an index past s105, a write into an outstanding scalar load, a symbolic source or destination under a dynamic `m0` and a `_b64` pair base that could be odd (a static odd offset, or a dynamic mask that allows bit 0) are refused. Every source is read before any destination is written: self-moves, overlapping pairs and a dynamic `s_movreld` whose source lies in its own destination bank are pinned by the exported constants or the generated selects. `SMOVREL_BODY` moves cbuffer-indexed words with each form, static and dynamic, and exports weighted sums (60, 67, 805, 193 and 80, 63, 244, 165 on the two `DPP_MOVREL_SETS`) from an independent reference. On WARP (driver 10.0.26100.8972) and an NVIDIA Quadro M1000M (driver 32.0.15.7371) on Windows 11 build 26100, with the debug layer unavailable, all 4096 pixels matched with zero error for both sets. Four controls must mismatch, and did on both adapters: the dynamic `m0` replaced by 0 for `s_movrels_b32`, `s_movreld_b32` and `s_movreld_b64`, and swapped static halves for `s_movrelsd_2_b32`. The translation controls check the descriptor move, the overlaps and ten refusals. Reproduce with `ctest --preset dev --no-tests=error -R "^pixel_aot_smovrel_" -V`. ```powershell diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 545dae486..65c525b64 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -23151,6 +23151,36 @@ def mix(bank): return (r, mix(g), mix(b), mix(a)) +def check_sdwa_movrel_overlap_draw(directory, compiler, renderer, backend): + bank = SDWA_MOVREL_BANK + program = uncompressed_export([ + *(f"v_mov_b32_e32 v{24 + k}, {word:#x}" for k, word in enumerate(bank)), + "s_mov_b32 s84, s47", "s_mov_b32 s85, 0", + "s_and_b64 s[84:85], s[84:85], 0x30003", "s_mov_b32 m0, s84", + "v_movrelsd_2_b32_sdwa v24, v24 dst_sel:BYTE_1 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0", + *(f"v_mov_b32_e32 v{12 + k}, v{24 + k}" for k in range(4)), + ]) + source = directory / "sdwa_movrel_overlap.hlsl" + shader = source.with_suffix(".cso") + source.write_text(translate_int(program), encoding="ascii") + compile_shader(compiler, source, shader) + + cases = [] + for src in range(4): + for dst in range(4): + constants = bytearray(256) + struct.pack_into(" Date: Wed, 25 Nov 2026 21:10:10 +0200 Subject: [PATCH 099/232] shader: extract main(argv), atomic output writes, and OSError/struct guards in mesh_dynamic_aot with CLI suite (#2407) * shader: extract main(argv), atomic output writes, and OSError/struct guards in mesh_dynamic_aot with CLI suite * shader: test ascii HLSL guard and document _same_path ordering --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/mesh_dynamic_aot_cli_check.py | 476 ++++++++++++++++++++++++++++ tools/mesh_dynamic_aot.py | 39 ++- 3 files changed, 509 insertions(+), 8 deletions(-) create mode 100644 tests/mesh_dynamic_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 47eefcc11..ed00bb5c1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8369,6 +8369,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/mesh_clip_cull_check.py") add_test(NAME mesh_dynamic_aot_cpu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_dynamic_aot_check.py") + add_test(NAME mesh_dynamic_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_dynamic_aot_cli_check.py") add_test(NAME mesh_lane_spill_cpu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_lane_spill_check.py") add_test(NAME mesh_entry_skipped_scalar_cpu COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/mesh_dynamic_aot_cli_check.py b/tests/mesh_dynamic_aot_cli_check.py new file mode 100644 index 000000000..c2dc6d6bb --- /dev/null +++ b/tests/mesh_dynamic_aot_cli_check.py @@ -0,0 +1,476 @@ +"""Pure-Python CLI, atomic output, and mutation control suite for tools/mesh_dynamic_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "mesh_dynamic_aot.py" +sys.path.insert(0, str(ROOT / "tools")) + +import mesh_dynamic_aot # noqa: E402 + + +def _build_dxbc(part_items: list[tuple[bytes, bytes]]) -> bytes: + encoded = [tag + struct.pack(" bytes: + psv0 = bytearray(52) + psv0[28] = 14 + dxil = bytearray(4) + struct.pack_into(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + try: + with redirect_stdout(stdout), redirect_stderr(stderr): + code = mesh_dynamic_aot.main(argv) + except SystemExit as exc: + code = int(exc.code) if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_cli_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class MeshDynamicAotCliPositiveTests(unittest.TestCase): + def test_main_creates_nested_output_and_forwards_all_options(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container_bytes = b"synthetic-dxbc-payload" + container.write_bytes(container_bytes) + out_path = root / "nested" / "deep" / "dynamic_mesh.hlsl" + self.assertFalse(out_path.parent.exists()) + + expected_hlsl = "// translated dynamic mesh\nvoid main() {}\n" + seen_translate = [] + seen_replaces = [] + real_replace = os.replace + + def fake_translate(blob, word_count, library, sampler_heap_sgpr=None, vs_out_cntl=None): + seen_translate.append((blob, word_count, library, sampler_heap_sgpr, vs_out_cntl)) + return expected_hlsl + + def tracking_replace(src, dst): + src_path = Path(src) + dst_path = Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with ( + mock.patch.object(mesh_dynamic_aot, "translate", side_effect=fake_translate), + mock.patch.object(mesh_dynamic_aot.os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main( + [ + str(container), + "--geometry-word-count", + "4", + "--llvm", + "mock-llvm.dll", + "--sampler-heap-sgpr", + "5", + "--pa-cl-vs-out-cntl", + "0x00c01003", + "--output", + str(out_path), + ] + ) + + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(seen_translate, [(container_bytes, 4, "mock-llvm.dll", 5, 0x00C01003)]) + self.assertEqual(len(seen_replaces), 1) + self.assertEqual([p.name for p in out_path.parent.iterdir()], ["dynamic_mesh.hlsl"]) + self.assertEqual(out_path.read_text(encoding="ascii"), expected_hlsl) + + def test_main_defaults_and_atomic_overwrite_of_existing_hlsl(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + out_path = root / "OUT.HLSL" + out_path.write_text("// stale\n", encoding="ascii") + + seen_translate = [] + + def fake_translate(blob, word_count, library, sampler_heap_sgpr=None, vs_out_cntl=None): + seen_translate.append((blob, word_count, library, sampler_heap_sgpr, vs_out_cntl)) + return "// fresh\n" + + with mock.patch.object(mesh_dynamic_aot, "translate", side_effect=fake_translate): + code, _, err = _run_main( + [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + + self.assertEqual(code, 0, err) + self.assertEqual(seen_translate, [(b"dxbc", 2, "mock-llvm.dll", None, None)]) + self.assertEqual([p.name for p in root.iterdir() if p.is_dir()], []) + self.assertEqual(out_path.read_text(encoding="ascii"), "// fresh\n") + + +class MeshDynamicAotCliNegativeAndMutationTests(unittest.TestCase): + def test_invalid_sampler_heap_sgpr_exits_2_without_traceback(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + out_path = root / "never_created" / "out.hlsl" + + for bad_sgpr in (-1, 106, *mesh_dynamic_aot.ENTRY_SGPRS): + with self.subTest(sgpr=bad_sgpr): + argv = [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--sampler-heap-sgpr", + str(bad_sgpr), + "--output", + str(out_path), + ] + with mock.patch.object(mesh_dynamic_aot, "translate") as translate_mock: + code, out, err = _run_main(argv) + translate_mock.assert_not_called() + self.assertEqual(code, 2) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("--sampler-heap-sgpr must name a free SGPR", err) + self.assertFalse(out_path.parent.exists()) + + proc = _run_cli_subprocess( + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--sampler-heap-sgpr", + "17", + "--output", + str(out_path), + ) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("--sampler-heap-sgpr must name a free SGPR", proc.stderr) + + def test_non_hlsl_suffix_and_existing_directory_output_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + + for dir_name in ("out_dir", "dir_named.hlsl"): + out_dir = root / dir_name + out_dir.mkdir() + with self.subTest(dir_name=dir_name): + argv = [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_dir), + ] + with mock.patch.object(mesh_dynamic_aot, "translate") as translate_mock: + code, out, err = _run_main(argv) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("ValueError: Output path is an existing directory:", err) + + proc = _run_cli_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("ValueError: Output path is an existing directory:", proc.stderr) + + bad_out = root / "nested" / "out.txt" + argv = [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(bad_out), + ] + with mock.patch.object(mesh_dynamic_aot, "translate") as translate_mock: + code, out, err = _run_main(argv) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("ValueError: Expected a separate HLSL output", err) + self.assertFalse(bad_out.parent.exists()) + + proc = _run_cli_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("ValueError: Expected a separate HLSL output", proc.stderr) + + def test_output_collision_with_container_resolve_and_samefile(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + + # 1) Non-existent container path via parent traversal (kills resolve() mutation). + ghost_container = root / "ghost.hlsl" + with mock.patch.object(mesh_dynamic_aot, "translate") as translate_mock: + code, _, err = _run_main( + [ + str(ghost_container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(sub / ".." / "ghost.hlsl"), + ] + ) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("ValueError: Expected a separate HLSL output", err) + + # 2) Hardlink collision where resolve() differs (kills samefile() mutation). + container = root / "shader.dxbc" + container.write_bytes(b"keep-dxbc") + hardlink = sub / "shader_alias.hlsl" + os.link(container, hardlink) + self.assertNotEqual(container.resolve(), hardlink.resolve()) + self.assertTrue(container.samefile(hardlink)) + + with mock.patch.object(mesh_dynamic_aot, "translate") as translate_mock: + code, _, err = _run_main( + [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(hardlink), + ] + ) + translate_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("ValueError: Expected a separate HLSL output", err) + self.assertEqual(container.read_bytes(), b"keep-dxbc") + + def test_missing_container_and_exception_guards_preserve_type_prefix(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.dxbc" + out_path = root / "never_created" / "out.hlsl" + + # Missing container -> OSError (FileNotFoundError) + argv_missing = [ + str(missing), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + code, out, err = _run_main(argv_missing) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("FileNotFoundError:", err) + self.assertFalse(out_path.parent.exists()) + + proc_missing = _run_cli_subprocess(*argv_missing) + self.assertEqual(proc_missing.returncode, 1, proc_missing.stderr) + self.assertNotIn("Traceback", proc_missing.stderr) + self.assertIn("FileNotFoundError:", proc_missing.stderr) + self.assertFalse(out_path.parent.exists()) + + # Real subprocess refusal of amplification stage -> ValueError: ... + amp = root / "amp.dxbc" + amp.write_bytes(_amplification_dxbc()) + proc_amp = _run_cli_subprocess( + str(amp), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ) + self.assertEqual(proc_amp.returncode, 1, proc_amp.stderr) + self.assertNotIn("Traceback", proc_amp.stderr) + self.assertIn("ValueError: Unsupported amplification stage", proc_amp.stderr) + self.assertFalse(out_path.parent.exists()) + + # Every guarded exception type in except (...) dies if removed. + for exc in ( + ValueError("bad runtime mesh"), + KeyError(b"DXIL"), + struct.error("truncated psv0"), + zlib.error("corrupt dxil stream"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(mesh_dynamic_aot, "translate", side_effect=exc): + code, out, err = _run_main( + [ + str(amp), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(f"{type(exc).__name__}: {exc}", err) + self.assertFalse(out_path.parent.exists()) + + def test_os_replace_and_staging_write_failures_leave_zero_temp_dirs(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + out_dir = root / "atomic_out" + out_path = out_dir / "mesh.hlsl" + + replace_calls = [] + + def failing_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), out_dir.resolve()) + raise OSError("simulated replace failure") + + with ( + mock.patch.object(mesh_dynamic_aot, "translate", return_value="// ok\n"), + mock.patch.object(mesh_dynamic_aot.os, "replace", side_effect=failing_replace), + ): + code, _, err = _run_main( + [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("OSError: simulated replace failure", err) + self.assertEqual(len(replace_calls), 1) + self.assertTrue(out_dir.is_dir()) + self.assertEqual(list(out_dir.iterdir()), []) + + with ( + mock.patch.object(mesh_dynamic_aot, "translate", return_value="// ok\n"), + mock.patch.object(mesh_dynamic_aot.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated disk full")), + ): + code, _, err = _run_main( + [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + replace_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("OSError: simulated disk full", err) + self.assertEqual(list(out_dir.iterdir()), []) + + def test_non_ascii_hlsl_rejected_before_replace_and_preserves_existing_output(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + container = root / "shader.dxbc" + container.write_bytes(b"dxbc") + out_dir = root / "ascii_guard" + out_dir.mkdir() + out_path = out_dir / "mesh.hlsl" + out_path.write_text("// preserve-existing\n", encoding="ascii") + + with ( + mock.patch.object(mesh_dynamic_aot, "translate", return_value="// sym_\u00e9\n"), + mock.patch.object(mesh_dynamic_aot.os, "replace") as replace_mock, + ): + code, out, err = _run_main( + [ + str(container), + "--geometry-word-count", + "2", + "--llvm", + "mock-llvm.dll", + "--output", + str(out_path), + ] + ) + + replace_mock.assert_not_called() + self.assertEqual(code, 1) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("UnicodeEncodeError:", err) + self.assertEqual(out_path.read_text(encoding="ascii"), "// preserve-existing\n") + self.assertEqual([p.name for p in out_dir.iterdir()], ["mesh.hlsl"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mesh_dynamic_aot.py b/tools/mesh_dynamic_aot.py index e2ec68f2d..836c607bd 100644 --- a/tools/mesh_dynamic_aot.py +++ b/tools/mesh_dynamic_aot.py @@ -16,7 +16,11 @@ """ import argparse +import os import re +import struct +import tempfile +import zlib from dataclasses import dataclass from pathlib import Path @@ -452,7 +456,14 @@ def translate(blob, geometry_word_count, library, sampler_heap_sgpr=None, vs_out return lower(decoded, geometry_word_count, limits, sampler_heap_sgpr, vs_out_cntl) -if __name__ == "__main__": +def _same_path(left: Path, right: Path) -> bool: + # resolve() handles a not-yet-existing output path; samefile() handles case/link aliases on Windows. + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("container", type=Path) parser.add_argument("--geometry-word-count", type=int, required=True) @@ -462,16 +473,28 @@ def translate(blob, geometry_word_count, library, sampler_heap_sgpr=None, vs_out parser.add_argument("--pa-cl-vs-out-cntl", type=lambda s: int(s, 0), help="PA_CL_VS_OUT_CNTL word that places clip and cull distances in pos1/pos2") parser.add_argument("--output", type=Path, required=True) - args = parser.parse_args() - if args.output.suffix.lower() != ".hlsl" or args.output.resolve() == args.container.resolve(): - parser.error("Expected a separate HLSL output") + args = parser.parse_args(argv) if args.sampler_heap_sgpr is not None and ( not 0 <= args.sampler_heap_sgpr <= 105 or args.sampler_heap_sgpr in ENTRY_SGPRS): parser.error("--sampler-heap-sgpr must name a free SGPR (s0-s105, not s3, s17, s20 or s21)") try: + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"Output path is an existing directory: {args.output}") + if args.output.suffix.lower() != ".hlsl": + raise ValueError("Expected a separate HLSL output") + if _same_path(args.output, args.container): + raise ValueError("Expected a separate HLSL output") hlsl = translate(args.container.read_bytes(), args.geometry_word_count, args.llvm, args.sampler_heap_sgpr, args.pa_cl_vs_out_cntl) - except (ValueError, KeyError) as error: - parser.exit(1, f"mesh_dynamic_aot: {error}\n") - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(hlsl, encoding="ascii") + args.output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=args.output.parent) as staging_dir: + staged = Path(staging_dir) / args.output.name + staged.write_text(hlsl, encoding="ascii") + os.replace(staged, args.output) + except (OSError, ValueError, KeyError, struct.error, zlib.error) as error: + parser.exit(1, f"{type(error).__name__}: {error}\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From b079f84c2c2a21e12849d59f99d608df7095912d Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Thu, 26 Nov 2026 03:11:36 +0800 Subject: [PATCH 100/232] tests: assert the expected count in the four hand-written operand refusals (#2506) The handlers #2396 guards by hand keep their operand count in a literal message ("... with N operands, expected 3"), while the VEC_F/VEC_U tables derive it from the arity. The refusal census prints that text, so a literal that drifted from the condition raising it would be reported to the reader as the requirement. The fixture checked only that a refusal happens, not what it says. Rewriting `s_bfm_b32 ... expected 3` to `expected 4` and `v_cvt_i32_f32 ... expected 2` to `expected 3` left it green; both are caught now, and so are the equivalent edits for `v_mov_b32` and `v_cndmask_b32`. v_cndmask_b32 accepts a fourth operand, so the long side is checked only where a refusal actually occurs. A separate check pins that the short side always refuses, so the loop cannot pass vacuously if a guard stopped firing there. python -B tests/startup_gfx2hlsl_operand_count_check.py operand count checks: 0 failed Test-only; the guards and every accepted form are unchanged. AI-assisted. Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- tests/startup_gfx2hlsl_operand_count_check.py | 30 ++++++++++++++++--- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/tests/startup_gfx2hlsl_operand_count_check.py b/tests/startup_gfx2hlsl_operand_count_check.py index ce21ca473..1f64f83f9 100644 --- a/tests/startup_gfx2hlsl_operand_count_check.py +++ b/tests/startup_gfx2hlsl_operand_count_check.py @@ -52,6 +52,16 @@ def outcome(module, op, sources): return 'ok' +def refusal(module, op, sources): + """The Unsupported text for op with the given number of sources, or None when it is not refused.""" + line = '%s v1, %s' % (op, ', '.join('v%d' % (2 + i) for i in range(sources))) if sources else '%s v1' % op + try: + probe(module)().one(op, line) + except module.Unsupported as error: + return str(error) + return None + + def table_counts(module, table): wrong = [] for op, (arity, _) in getattr(module, table).items(): @@ -90,12 +100,24 @@ def table_counts(module, table): # Handlers outside the tables keep their operands in method bodies, so the same rule is asserted here: the # destination plus exactly its sources, and a short list refused rather than indexed. -BODY_HANDLERS = (('v_mov_b32', 1, 2), ('v_cvt_i32_f32', 1, 2), ('v_cndmask_b32', 2, 3), ('s_bfm_b32', 2, 2), - ('v_cvt_pkrtz_f16_f32', 2, 3)) -for op, sources, operands in BODY_HANDLERS: +BODY_HANDLERS = (('v_mov_b32', 1, 2, 'expected 2'), ('v_cvt_i32_f32', 1, 2, 'expected 2'), + ('v_cndmask_b32', 2, 3, 'expected 3 or 4'), ('s_bfm_b32', 2, 2, 'expected 3'), + ('v_cvt_pkrtz_f16_f32', 2, 3, 'expected 3')) +for op, sources, operands, expected in BODY_HANDLERS: got = [outcome(G, op, n) for n in (sources - 1, sources)] check('%s: translates with %d operands and refuses %d' % (op, operands, operands - 1), got == ['refused', 'ok'], repr(got)) + # The count in the message is a literal in these bodies, so it can drift from the condition that raises it. + # The census prints this text, so a wrong number would be reported to the reader as the requirement. + # The short list always refuses; the long one refuses only where the handler has no extra form + # (v_cndmask_b32 takes a fourth operand), so only an actual refusal is checked for its text. + for length in (sources - 1, sources + 1): + message = refusal(G, op, length) + if message is not None: + check('%s with %d operands names %r' % (op, length, expected), message.endswith(expected), + repr(message)) + check('%s: the short form is the one the message is checked on' % op, + refusal(G, op, sources - 1) is not None, op) # Negative control: with each guard disabled, the short form raises IndexError again instead of refusing. stripped = source @@ -105,7 +127,7 @@ def table_counts(module, table): no_guards = importlib.util.module_from_spec(spec) no_guards.__dict__['__file__'] = G.__file__ exec(compile(stripped, G.__file__, 'exec'), no_guards.__dict__) -for op, sources, operands in BODY_HANDLERS: +for op, sources, operands, _ in BODY_HANDLERS: got = outcome(no_guards, op, sources - 1) check('control: without its guard %s with %d operands raises IndexError' % (op, operands - 1), got == 'IndexError', got) From 510f7f5bc6498e09257d31e4b8cdec82ed76295a Mon Sep 17 00:00:00 2001 From: sydney-0o <215686885+sydney-0o@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:12:15 +0500 Subject: [PATCH 101/232] startup: trace paired slot 86 input writers and fences (#2504) Refs #870. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 38 ++++ src/startup_stubs/d3d12_xs_device.cpp | 20 ++- src/startup_stubs/list_copy.inl | 6 +- src/startup_stubs/mesh_xmem_handoff.inl | 191 +++++++++++++++++++-- tests/startup_indirect_mesh_cache_check.py | 49 +++++- 6 files changed, 287 insertions(+), 22 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ed00bb5c1..a752d986e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1530,6 +1530,11 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh86_srv_proof_check.py" "${DXC_EXECUTABLE}" "${CMAKE_CURRENT_BINARY_DIR}") set_tests_properties(startup_mesh86_srv_proof PROPERTIES TIMEOUT 60) + add_test(NAME startup_indirect_mesh_lease_warp_dual-trace COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" + "${DXC_EXECUTABLE}" "$" warp + "$" dual-trace) + set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) foreach(backend IN ITEMS warp hardware) add_test(NAME startup_indirect_mesh_cache_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" diff --git a/docs/experiments.md b/docs/experiments.md index 3dbacf88a..fbd5ce72b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8983,6 +8983,44 @@ Both pages are reusable afterward. ctest --preset release --no-tests=error -j1 -R '^startup_indirect_mesh_lease_(warp|hardware)_dual' -V ``` +For a matched local replay, set `X2W_MESH86_WRITER_TRACE=` to select the +one-based index of a slot 61 DispatchMesh attempt with a slot 86 cache key +on the bound pipeline. Use `X2W_MESH86_XMEM_SRV=1` and +`X2W_MESH_INDIRECT_XMEM=1` to exercise both handoffs. Keep the same +initial save, cache, input script and run duration as the baseline. Record +the late surface separately using the same capture timing. + +The `x2w-mesh86-trace` rows identify the selected call and check both +inputs before wrapper validation can reject the draw. With one declared +root SRV and no cache proof, the trace reports a one-byte binding anchor. +A copy covering that anchor may be relevant, and the shader's consumed +extent still needs proof. A `matched` lease covers the +input with the writer's live physical page and byte range. Its +`writer-submit` identifies the publication after a successful writer +completion signal. `fence-submit` identifies the submission whose fence +value 1 orders the consumer. It can be a later access already ordered after +the writer. `order` records a cross-queue wait, a shared wait, same-queue +ordering or an omitted wait in a control. A `recorded` call reaches a +desktop command list. A `forwarded` submission reaches the desktop queue. + +The recent-copy rows search the last 1,024 submitted copy destinations +recorded by the XMem lease tracker. These cover forwarded slot 15 and slot 17 +copies into eligible copied placements. A placement overlap is a candidate +writer. The tracker can prove physical identity and fence ordering through +a matching lease. Absence of a recent copy leaves direct UAV writes, CPU +writes and other unobserved producer paths open. A UAV-capable copy source +alone does not identify the dispatch that populated it. + +The source-built WARP check traces the attempt with an unsubmitted argument +writer, the ordered draw, and the two remap controls. The ordered draw +matches the root copy from COPY and the argument copy from COMPUTE to two +DIRECT waits. The controls report the missing argument writer at recording +and the changed root or argument page at submission. + +```powershell +ctest --preset release --no-tests=error -j1 -R '^startup_indirect_mesh_lease_warp_dual-trace$' -V +``` + A decoded indirect mesh command can publish a fixed slot 57 pipeline as a separate translation request. The descriptor must have a mesh program, an empty vertex slot, and a recorded root signature that matches the bound diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 5df3194f4..d40aaf96f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2688,9 +2688,12 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, Wrapper* sig = as_wrapper(signature); IndirectCommand kind = sig && sig->own().kind == command_signature_kind ? sig->own().indirect_command : IndirectCommand::none; Wrapper* refusal_pipeline = nullptr; - const auto refuse = [&kind, &refusal_pipeline](const char* reason, int outcome = indirect_other, - const char* code = nullptr) { + u64 trace_call = 0; + const auto refuse = [&kind, &refusal_pipeline, &trace_call](const char* reason, int outcome = indirect_other, + const char* code = nullptr) { InterlockedIncrement64(&indirect_calls[outcome][static_cast(kind)]); + if (trace_call) + log("x2w-mesh86-trace call=%llu stage=record outcome=refused reason=%s", trace_call, reason); static LONG refusals; if (outcome == indirect_other) { const u64 key = known_pipeline_key(refusal_pipeline); @@ -2704,6 +2707,11 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, }; auto* list = recording(self); if (!list) return refuse("list is closed", indirect_other, indirect_other_refusal_code::list_closed); + if (kind == IndirectCommand::dispatch_mesh && mesh_xmem_trace_ordinal()) { + const auto& pass = pass_of(self); + if (pass.pipeline && pass.pipeline->own().mesh86_key) trace_call = select_mesh_xmem_trace_call(); + if (trace_call) trace_mesh_xmem_inputs(self, pass, trace_call, argument, offset); + } const auto type = list->GetType(); if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_COMPUTE) return refuse("requires a direct or compute command list", indirect_other, indirect_other_refusal_code::invalid_list_type); @@ -2892,7 +2900,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (leased_arguments) inputs[input_count++] = {base + offset, bytes, argument_state}; if (input_count) { - if (const char* failure = record_mesh_xmem_reads(self, inputs, input_count)) + if (const char* failure = record_mesh_xmem_reads(self, inputs, input_count, trace_call)) return refuse(failure, mesh_srv != UINT_MAX ? indirect_graphics_pipeline : indirect_other, indirect_other_refusal_code::mesh_xmem_read); if (leased_arguments) { @@ -2957,6 +2965,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, list->ExecuteIndirect(static_cast(sig->own().real), count, draw_arguments, draw_offset, counts, counts ? count_offset : 0); red_producer_draw_after(self, red_samples); + if (trace_call) log("x2w-mesh86-trace call=%llu stage=record outcome=recorded", trace_call); if (scratch) x2w_startup::RectIndirectArguments::finish(list, scratch); InterlockedIncrement64(&indirect_calls[indirect_forwarded][static_cast(kind)]); } @@ -3464,6 +3473,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } } auto* queue = static_cast(self->own().real); + bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { const UINT ready_count = static_cast(native_lists.size()); red_producers().execute(queue, native_lists, [&] { @@ -3480,8 +3490,8 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w); InterlockedIncrement(&render_executes); + return trace_mesh_xmem_submission(queue, native_lists, split); }; - bool split = false; if (mesh_xmem_tracking()) { const std::lock_guard lock(mesh_xmem_mutex); reap_mesh_xmem_flights(); @@ -3495,7 +3505,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) for (std::size_t i = 0; i < ready.size(); ++i) { native_list[0] = ready[i]; wrapper[0] = submitted[i]; - execute_mesh_xmem_recording(queue, ready[i], [&] { submit(native_list, wrapper); }); + execute_mesh_xmem_recording(queue, ready[i], [&] { return submit(native_list, wrapper); }); } } else if (!ready.empty()) { submit(ready, submitted); diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 7f5fa07aa..ff2441bf2 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -207,7 +207,9 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti (from_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && SUCCEEDED(from.resource->GetHeapProperties(&source_properties, nullptr)) && source_properties.Type == D3D12_HEAP_TYPE_DEFAULT; - note_mesh_xmem_write(self, to.wrapper, destination_offset, bytes, + const char* source_kind = upload ? "upload" : mesh_record ? "default-uav" : + (from_desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ? "uav-capable-buffer" : "buffer"; + note_mesh_xmem_write(self, to.wrapper, destination_offset, bytes, 15, source_kind, srv_word || mesh_record ? from.resource : nullptr, source_offset); } if (indirect_copy_ranges()) { @@ -237,7 +239,7 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) retire_hold(self, to.wrapper); retire_hold(self, from.wrapper); if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width); + note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width, 17, "buffer"); note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); } else mark_gpu_written(self, to); InterlockedIncrement(&list_resource_copies); diff --git a/src/startup_stubs/mesh_xmem_handoff.inl b/src/startup_stubs/mesh_xmem_handoff.inl index ce80f92c9..930637ef3 100644 --- a/src/startup_stubs/mesh_xmem_handoff.inl +++ b/src/startup_stubs/mesh_xmem_handoff.inl @@ -18,6 +18,42 @@ bool mesh_xmem_tracking() return mesh_xmem_handoff() || mesh_xmem_indirect(); } +// An ordinal selects one slot 86 call per process, keeping replay logs bounded. +UINT mesh_xmem_trace_ordinal() +{ + static const UINT selected = [] { + char value[11]{}; + const DWORD size = GetEnvironmentVariableA("X2W_MESH86_WRITER_TRACE", value, sizeof(value)); + if (!size || size >= sizeof(value)) return 0u; + u64 ordinal = 0; + for (DWORD i = 0; i < size; ++i) { + if (value[i] < '0' || value[i] > '9') return 0u; + ordinal = ordinal * 10 + (value[i] - '0'); + } + return ordinal <= UINT_MAX ? static_cast(ordinal) : 0u; + }(); + return selected; +} + +u64 select_mesh_xmem_trace_call() +{ + static LONG64 calls; + const UINT selected = mesh_xmem_trace_ordinal(); + if (!selected) return 0; + const auto call = static_cast(InterlockedIncrement64(&calls)); + return call == selected ? call : 0; +} + +const char* mesh_xmem_queue_type(ID3D12CommandQueue* queue) +{ + switch (queue->GetDesc().Type) { + case D3D12_COMMAND_LIST_TYPE_DIRECT: return "direct"; + case D3D12_COMMAND_LIST_TYPE_COMPUTE: return "compute"; + case D3D12_COMMAND_LIST_TYPE_COPY: return "copy"; + default: return "other"; + } +} + struct MeshXMemLease { using Release = BOOL (WINAPI*)(UINT, ULONG64); X2WXMemSectionLease lease{}; @@ -31,6 +67,7 @@ struct MeshXMemLease { x2w_startup::ComPtr buffer; x2w_startup::ComPtr last_access; ID3D12CommandQueue* last_queue{}; + u64 trace_writer{}, trace_last_access{}; bool untracked{}; ~MeshXMemLease() @@ -50,7 +87,13 @@ struct MeshXMemLease { }; struct MeshXMemRecording { - struct Write { Wrapper* owner; u64 offset, bytes; bool leased; }; + struct Write { + Wrapper* owner; + u64 offset, bytes; + bool leased; + UINT slot; + const char* source; + }; struct Read { std::shared_ptr lease; u64 address{}; @@ -58,6 +101,7 @@ struct MeshXMemRecording { std::vector writes; std::array readers; std::array, 2> writers; + u64 trace_call{}; }; struct MeshXMemFlight { std::shared_ptr lease; @@ -77,6 +121,34 @@ std::unordered_map mesh_xmem_recordings; std::vector mesh_xmem_flights; bool mesh_xmem_tracking_failed; +struct MeshXMemTraceCopy { + MeshXMemRecording::Write write; + u64 submission; + const char* queue; +}; +std::array mesh_xmem_trace_copies; +u64 mesh_xmem_trace_copy_count, mesh_xmem_trace_submissions; + +// Split submissions already hold mesh_xmem_mutex. A trace never changes which +// recordings are split or adds a completion fence to a normal copy. +u64 trace_mesh_xmem_submission(ID3D12CommandQueue* queue, const std::vector& lists, bool locked) +{ + if (!mesh_xmem_trace_ordinal()) return 0; + std::unique_lock lock(mesh_xmem_mutex, std::defer_lock); + if (!locked) lock.lock(); + const u64 submission = ++mesh_xmem_trace_submissions; + const char* queue_type = mesh_xmem_queue_type(queue); + for (auto* list : lists) { + const auto found = mesh_xmem_recordings.find(list); + if (found == mesh_xmem_recordings.end()) continue; + for (const auto& write : found->second.writes) { + mesh_xmem_trace_copies[mesh_xmem_trace_copy_count++ % mesh_xmem_trace_copies.size()] = + {write, submission, queue_type}; + } + } + return submission; +} + // All functions that mutate publication/flight state hold mesh_xmem_mutex. void reap_mesh_xmem_flights() { @@ -209,7 +281,7 @@ bool mesh_xmem_write_overlaps(const MeshXMemRecording::Write& write, const MeshX // Track other writes to the copied placement too. An overlapping write that // did not update the XMem view invalidates its publication at submission. void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, - ID3D12Resource* source = nullptr, u64 source_offset = 0) + UINT slot, const char* source_kind, ID3D12Resource* source = nullptr, u64 source_offset = 0) { if (!mesh_xmem_tracking() || !owner || !owner->own().title_memory) return; const auto* info = resource_info(owner); @@ -221,7 +293,7 @@ void note_mesh_xmem_write(Wrapper* list, Wrapper* owner, u64 offset, u64 bytes, if (mesh_xmem_tracking_failed) return; try { auto& recorded = mesh_xmem_recordings[desktop_list]; - recorded.writes.push_back({owner, offset, bytes, false}); + recorded.writes.push_back({owner, offset, bytes, false, slot, source_kind}); const u64 base = reinterpret_cast(owner->own().title_memory); const u64 alignment = bytes == sizeof(UINT) ? D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT : sizeof(UINT); if (!source || offset > UINT64_MAX - base || recorded.readers[mesh_xmem_srv_index].lease || @@ -267,8 +339,75 @@ struct MeshXMemRead { u64 offset{}; }; +void trace_mesh_xmem_input(Wrapper* device, u64 call, size_t index, u64 address, u64 bytes, bool needs_lease, + bool anchor_only = false) +{ + const char* input = index == mesh_xmem_srv_index ? "root-srv" : "arguments"; + if (!address || address > UINT64_MAX - bytes) { + log("x2w-mesh86-trace call=%llu input=%s range=unavailable", call, input); + return; + } + const auto placed = placed_buffer_range(device, address, bytes); + const auto& lease = mesh_xmem_publications[index].ready; + const bool match = lease && !placed.reject && placed.owner == lease->owner && + lease->device == device && lease->bytes == bytes && lease->matches(address); + log("x2w-mesh86-trace call=%llu input=%s range=%s bytes=%llu placement=%s lease=%s writer-submit=%llu", + call, input, anchor_only ? "anchor-only" : "fixed-span", bytes, + placed.reject ? "ambiguous" : !placed.owner ? "unresolved" : placed.alias ? "alias" : "copy", + !needs_lease ? "not-checked" : match ? "matched" : lease ? "mismatch" : "absent", + needs_lease && match ? lease->trace_writer : 0ull); + if (placed.reject || !placed.owner) return; + const u64 offset = address - reinterpret_cast(placed.owner->own().title_memory); + const u64 retained = (std::min)(mesh_xmem_trace_copy_count, static_cast(mesh_xmem_trace_copies.size())); + for (u64 i = 0; i < retained; ++i) { + const auto& candidate = mesh_xmem_trace_copies[(mesh_xmem_trace_copy_count - i - 1) % + mesh_xmem_trace_copies.size()]; + const auto& write = candidate.write; + if (write.owner != placed.owner || write.offset >= offset + bytes || offset >= write.offset + write.bytes) + continue; + const bool covers = write.offset <= offset && write.offset + write.bytes >= offset + bytes; + log("x2w-mesh86-trace call=%llu input=%s copy-slot=%u source=%s queue=%s submit=%llu range=%s", + call, input, write.slot, write.source, candidate.queue, candidate.submission, + anchor_only ? "contains-anchor" : covers ? "covers-placement" : "overlaps-placement"); + return; + } + log("x2w-mesh86-trace call=%llu input=%s recent-copy=absent", call, input); +} + +void trace_mesh_xmem_inputs(Wrapper* list, const Pass& pass, u64 call, void* argument, u64 argument_offset) +{ + const UINT proved_srv = pass.indirect_graphics.cached_srv_root; + UINT srv = proved_srv; + if (srv == UINT_MAX && pass.root && pass.root->size() <= std::size(pass.root_address)) { + for (UINT i = 0; i < pass.root->size(); ++i) { + if ((*pass.root)[i].type != D3D12_ROOT_PARAMETER_TYPE_SRV) continue; + if (srv != UINT_MAX) { + srv = UINT_MAX; + break; + } + srv = i; + } + } + const u64 srv_address = srv != UINT_MAX ? pass.root_address[srv] : 0; + const Wrapper* buffer = as_wrapper(argument); + const bool resource = buffer && buffer->own().kind == resource_kind; + const u64 base = resource ? reinterpret_cast(buffer->own().title_memory) : 0; + const u64 arg_address = base && argument_offset <= UINT64_MAX - base && !(argument_offset & 3) + ? base + argument_offset : 0; + const auto* info = resource ? resource_info(buffer) : nullptr; + const bool leased_arguments = mesh_xmem_indirect() && info && info->placement == Placement::copied_buffer && + (!pass.indirect_graphics.cached_mesh || proved_srv != UINT_MAX); + const bool anchor_only = proved_srv == UINT_MAX; + auto* device = list->own().list_device; + const std::lock_guard lock(mesh_xmem_mutex); + trace_mesh_xmem_input(device, call, mesh_xmem_srv_index, srv_address, anchor_only ? 1 : sizeof(UINT), + !anchor_only, anchor_only); + trace_mesh_xmem_input(device, call, mesh_xmem_argument_index, arg_address, sizeof(D3D12_DISPATCH_MESH_ARGUMENTS), + leased_arguments); +} + // Check all inputs to this draw before adding any recording pins or barriers. -const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t count) +const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t count, u64 trace_call) { if (!count) return nullptr; const std::lock_guard lock(mesh_xmem_mutex); @@ -307,6 +446,7 @@ const char* record_mesh_xmem_reads(Wrapper* list, MeshXMemRead* reads, size_t co auto& states = pass_of(list).states; states.reserve(states.size() + count); auto& recorded = mesh_xmem_recordings[desktop_list]; + if (trace_call) recorded.trace_call = trace_call; for (size_t i = 0; i < count; ++i) { auto& read = reads[i]; const auto index = mesh_xmem_index(read.bytes); @@ -364,6 +504,10 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l return; } const auto& work = record->second; + const auto trace_refuse = [&](const char* reason) { + if (work.trace_call) + log("x2w-mesh86-trace call=%llu stage=submit outcome=refused reason=%s", work.trace_call, reason); + }; std::array, 2> accesses{}; size_t access_count = 0; for (size_t i = 0; i < accesses.size(); ++i) { @@ -375,6 +519,7 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l if (mesh_xmem_tracking_failed || lease->untracked || placed.reject || placed.owner != lease->owner || !lease->matches(address) || (read.lease && mesh_xmem_publications[i].ready != lease)) { log("x2w-render mesh XMem submit refused: writer or live page identity changed"); + trace_refuse(i == mesh_xmem_srv_index ? "root-srv-identity-changed" : "arguments-identity-changed"); return; } accesses[i] = lease; @@ -389,32 +534,48 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l return lease && device.Get() != device_of(lease->device); }) || FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)))) { log("x2w-render mesh XMem submit refused: no completion fence on this device"); + trace_refuse("no-completion-fence"); return; } try { mesh_xmem_flights.reserve(mesh_xmem_flights.size() + access_count); } catch (const std::bad_alloc&) { log("x2w-render mesh XMem submit refused: retirement allocation failed"); + trace_refuse("retirement-allocation"); return; } ID3D12Fence* waited = nullptr; for (size_t i = 0; i < accesses.size(); ++i) { const auto& lease = accesses[i]; - if (!lease || !lease->last_access || lease->last_queue == queue || - lease->last_access.Get() == waited || (work.readers[i].lease && mesh_xmem_skip_read_wait(i))) - continue; - if (FAILED(queue->Wait(lease->last_access.Get(), 1))) { - log("x2w-render mesh XMem submit refused: cross-queue wait failed"); - return; + if (!lease) continue; + const char* order; + if (!lease->last_access) order = "no-fence"; + else if (lease->last_queue == queue) order = "same-queue"; + else if (lease->last_access.Get() == waited) order = "shared-wait"; + else if (work.readers[i].lease && mesh_xmem_skip_read_wait(i)) order = "test-omitted"; + else { + if (FAILED(queue->Wait(lease->last_access.Get(), 1))) { + log("x2w-render mesh XMem submit refused: cross-queue wait failed"); + trace_refuse("cross-queue-wait-failed"); + return; + } + order = "wait"; + waited = lease->last_access.Get(); + static LONG reports; + if (first_calls(reports, 16)) log("x2w-render mesh XMem GPU wait for lease %llu", lease->lease.id); } - waited = lease->last_access.Get(); - static LONG reports; - if (first_calls(reports, 16)) log("x2w-render mesh XMem GPU wait for lease %llu", lease->lease.id); + if (work.trace_call && work.readers[i].lease) + log("x2w-mesh86-trace call=%llu input=%s order=%s writer-submit=%llu fence-submit=%llu", + work.trace_call, i == mesh_xmem_srv_index ? "root-srv" : "arguments", order, + lease->trace_writer, lease->trace_last_access); } } - execute(); + const u64 submission = execute(); const bool signalled = !completion || SUCCEEDED(queue->Signal(completion.Get(), 1)); + if (work.trace_call) + log("x2w-mesh86-trace call=%llu stage=submit outcome=forwarded submit=%llu queue=%s signal=%s", + work.trace_call, submission, mesh_xmem_queue_type(queue), signalled ? "enqueued" : "failed"); for (size_t i = 0; i < accesses.size(); ++i) { const auto& lease = accesses[i]; if (!lease) continue; @@ -422,6 +583,7 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l mesh_xmem_flights.push_back({lease, completion}); lease->last_access = completion; lease->last_queue = queue; + lease->trace_last_access = submission; } else { lease->untracked = true; mesh_xmem_publications[i].ready.reset(); @@ -443,6 +605,7 @@ void execute_mesh_xmem_recording(ID3D12CommandQueue* queue, ID3D12CommandList* l const auto index = mesh_xmem_index(write.bytes); const auto& lease = work.writers[index]; mesh_xmem_publications[index].ready = lease; + lease->trace_writer = submission; static LONG reports; if (first_calls(reports, 16)) log("x2w-render mesh XMem writer: lease %llu section page +0x%llx byte +0x%llx, %llu bytes", diff --git a/tests/startup_indirect_mesh_cache_check.py b/tests/startup_indirect_mesh_cache_check.py index d8b4ecbee..2c0664b4e 100644 --- a/tests/startup_indirect_mesh_cache_check.py +++ b/tests/startup_indirect_mesh_cache_check.py @@ -2,6 +2,7 @@ import os from pathlib import Path +import re import struct import subprocess import sys @@ -25,6 +26,50 @@ def source_envelope(stage): return b'DXBC' + bytes(16) + struct.pack(' Date: Wed, 25 Nov 2026 20:14:45 +0100 Subject: [PATCH 102/232] startup: prove a compute formatted load whose table pointer copy is in a block above (#2461) A compute formatted buffer load past the entry block was accepted only when its descriptor words came from a table load in the same block through an entry table pointer, or through a copy of one made in that same block. The copy now may sit in a block above: walking every predecessor path back from the table load, the only write to the pointer register must be one s_mov_b32 from an entry table pointer, no path may reach the entry without that write, and no path into the copy may write the copied register. Graphics stages keep the previous rule. Descriptor words loaded in another block than the formatted load stay refused. Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/startup_gfx2hlsl_compute_check.py | 52 +++++++++++++++++++++ tests/startup_vertex_fetch_formats_check.py | 7 +++ tools/startup/gfx2hlsl.py | 36 ++++++++++++++ 3 files changed, 95 insertions(+) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 4e1e0df44..7d94489d3 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -743,6 +743,58 @@ def check_formatted_loads(): refused('local table load', lambda: translate('L-uint', code=prefix + bytes.fromhex('000082bf') + LOAD_L + end)) local_load = bytes.fromhex('000082bf') + prefix + LOAD_L + end assert 'switch ((ud3 >> 12) & 127u)' in translate('L-uint', code=local_load).hlsl_cs() + check_formatted_pointer_copy() + + +def check_formatted_pointer_copy(): + """The descriptor load sits past the entry block and its pointer is a copy of the table pointer made in a + block above it. The copy must be the last write to the pointer on every path to the load.""" + copy, high, load = (bytes.fromhex(h) for h in ('06038abe', '80038bbe', '05030cf4000000fa')) + assert WORDS_L.startswith(copy + high + load) + tail = WORDS_L[16:WORDS_L.index(LOAD_L)] + LOAD_L + bytes.fromhex('000081bf') + target = bytes.fromhex('000082bf') # s_branch to the next instruction, which becomes a branch target + skip_one = bytes.fromhex('010084bf') # s_cbranch_scc0 over one instruction + again = copy # s_mov_b32 s10, s6: a second write of the same pointer value + same_source = bytes.fromhex('060386be') # s_mov_b32 s6, s6: a write to the copied register + + def proof(code): + """The copy proof for the first table load of this program, without the rest of the translation.""" + stage = G.Stage.__new__(G.Stage) + stage.ins, stage.calculated_pc = list(G.decode(code)), {} + at = next(i for i, ins in enumerate(stage.ins) if ins[2] == 's_load_dwordx8') + return stage.formatted_pointer_copy(10, at) + + switch = 'switch ((ud3 >> 12) & 127u)' + # Copy in the entry block, load and formatted read in the next block. + assert proof(copy + high + target + load + tail) == (6, 0) + assert switch in translate('L-uint', code=copy + high + target + load + tail).hlsl_cs() + # Copy in a later block that every path to the load runs through. + assert proof(target + copy + high + target + load + tail) == (6, 1) + assert switch in translate('L-uint', code=target + copy + high + target + load + tail).hlsl_cs() + # A branch skips the copy: the entry value of s10 reaches the load. + assert proof(skip_one + copy + load + tail) is None + assert proof(load + tail) is None + refused('joined at a branch target', lambda: translate('L-uint', code=skip_one + copy + load + tail)) + # One arm writes the pointer again. The value is the same, so only this proof can refuse it. + assert proof(copy + high + skip_one + again + load + tail) is None + refused('local table load', lambda: translate('L-uint', code=copy + high + skip_one + again + load + tail)) + # A back edge from below the formatted read writes the pointer and re-enters at the load. + loop = copy + high + target + load + tail[:-4] + again + bytes.fromhex('f8ff84bf') + tail[-4:] + assert [ins[2] for ins in G.decode(loop)][-2:] == ['s_cbranch_scc0', 's_endpgm'] + assert proof(loop) is None + refused('local table load', lambda: translate('L-uint', code=loop)) + # One path writes descriptor word 3 between the table load and the formatted read. + word_write = (copy + high + target + load + WORDS_L[16:WORDS_L.index(LOAD_L)] + skip_one + + bytes.fromhex('0f038fbe') + LOAD_L + bytes.fromhex('000081bf')) # s_mov_b32 s15, s15 + refused('local table load', lambda: translate('L-uint', code=word_write)) + # The only writer is not a register copy. + assert proof(bytes.fromhex('80038abe') + high + target + load + tail) is None + # The copied register is written on one path into the block that copies it. + one_path = skip_one + same_source + copy + high + target + load + tail + assert proof(one_path) == (6, 2) + refused('local table load', lambda: translate('L-uint', code=one_path)) + # The same program without that write translates. + assert switch in translate('L-uint', code=skip_one + bytes.fromhex('000080bf') + copy + high + target + load + tail).hlsl_cs() def check_controls(): diff --git a/tests/startup_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 5e9446008..20f6d8823 100644 --- a/tests/startup_vertex_fetch_formats_check.py +++ b/tests/startup_vertex_fetch_formats_check.py @@ -383,6 +383,13 @@ def stage(words): assert 'local table load' in str(error) or 'joined at a branch target' in str(error), error else: raise AssertionError('formatted load accepted after a possibly clobbered root pointer') + # A copy of the table pointer made in a block above the load is proven for compute stages only. + try: + stage((0xbe8a0308, 0xbf820000, 0xf4080405, 0xfa000000, *formatted_tail)) + except gfx2hlsl.Unsupported as error: + assert 'local table load' in str(error), error + else: + raise AssertionError('graphics formatted load accepted through a pointer copy in another block') source = pipeline_mubuf(0).hlsl_vs() for label, old, new in DESC_MUTATIONS: assert old in source, label diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index d38afdbd5..a6be92317 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3329,6 +3329,38 @@ def formatted_pointer_reaches(self, pointer, before): pending.extend(self.descriptor_predecessors[earlier]) return True + def formatted_pointer_copy(self, pointer, before): + """(source register, instruction index) of the one s_mov_b32 that is the last write to this pointer on + every path from the entry to this read, or None. + + One writer found walking back, with no path that reaches the entry without a write, means that the copy is + on every path to the read and that no path from the copy to the read writes the pointer again.""" + self.formatted_pointer_reaches(pointer, before) # builds the predecessor tables + writers, seen, expand = set(), set(), [before] + while expand: + at = expand.pop() + if at == 0 or not self.descriptor_predecessors[at]: + return None # the entry value of the register reaches the read + for earlier in self.descriptor_predecessors[at]: + if earlier in seen: + continue + seen.add(earlier) + _, _, name, asm = self.ins[earlier] + wrote = self.descriptor_writes_by_instruction[earlier] | scalar_destinations(name, asm) + if pointer in wrote or 'any' in wrote: + writers.add(earlier) + else: + expand.append(earlier) + if len(writers) != 1: + return None + index, = writers + _, _, name, asm = self.ins[index] + _, args, _ = parse(asm) + source = reg_range(args[1]) if name == 's_mov_b32' and len(args) == 2 else None + if args[0] != 's%d' % pointer or not source or source[0] != 's' or source[1] != source[2]: + return None + return source[1], index + def formatted_descriptor_from_block(self, reg, first): """Require one untouched local load and a table pointer that no incoming path can rewrite.""" start, end = self.descriptor_block_first, self.descriptor_instruction_index @@ -3359,6 +3391,10 @@ def formatted_descriptor_from_block(self, reg, first): pointer = copied_from[1] read = start + previous break + else: + copy = getattr(self, 'kind', None) == 'cs' and self.formatted_pointer_copy(pointer, read) + if copy: + pointer, read = copy return self.entry_table_pointers.get(pointer) == first[1] and self.formatted_pointer_reaches(pointer, read) return False From 82421b892b8a5e5a8c930fede6cecf506b777e3a Mon Sep 17 00:00:00 2001 From: KomaGuy Date: Wed, 25 Nov 2026 22:16:45 +0300 Subject: [PATCH 103/232] shader: lower quad-local DPP16 and DPP8 binary16 fmac, ldexp and int16 conversions in pixel_aot (#2485) * shader: lower quad-local DPP16 and DPP8 binary16 fmac, ldexp and int16 conversions in pixel_aot Lower the quad-local DPP16 and DPP8 spellings of the six remaining contracted binary16 opcodes (12 forms total across gfx1013 and rdna2): - VOP2 fused/scale: v_fmac_f16_dpp, v_ldexp_f16_dpp - VOP1 int16 <-> f16: v_cvt_f16_i16_dpp, v_cvt_f16_u16_dpp, v_cvt_i16_f16_dpp, v_cvt_u16_f16_dpp Add int16_dpp_source() alongside half16_dpp_source() to enforce the existing #839 contracts: - src0 is quad-swizzled via emit_quad_swizzle_u32 while src1 and the v_fmac_f16_dpp accumulator stay on the current lane. - DPP16 allows bit-15 abs/neg modifiers on float sources only (src0/src1 on v_fmac_f16_dpp, src0 on v_ldexp_f16_dpp and v_cvt_{i16,u16}_f16_dpp); DPP8 and integer operands refuse modifiers. - v_fmac_f16_dpp uses fma16_rne for single-rounding fused multiply-add, v_ldexp_f16_dpp requires a proven signed 16-bit exponent in [-64, 64], v_cvt_f16_i16_dpp accepts runtime i16/low16 sources while v_cvt_f16_u16_dpp requires a static proof < 65520, and v_cvt_{i16,u16}_f16_dpp truncates proven in-range binary16 values into ("low16", alu). - Explicit half_denorm="preserve" and HW_REG_MODE RNE remain required. Extend pixel_aot_dpp_f16_{warp,hardware} with four 4-channel programs (fmac_ldexp_dpp16, fmac_ldexp_dpp8, cvt_int16_dpp16, cvt_int16_dpp8) in both default and -denorm ftz modes plus 13 numerically distinct mutations and a per-lane runtime quad-routing witness (DPP_F16_CVT_I16_LANES), add all five to check_binary, update check_dpp_f16_contract_controls and docs/experiments.md, and add check_dpp_f16_cvt_fmac_ldexp_forms in tests/form_coverage_check.py. * tests: pin |v| and abs(v) refusal on v_ldexp_f16_dpp src1 --------- Co-authored-by: KomaGuy <265821007+KomaGuy@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 +- tests/form_coverage_check.py | 42 ++++- tests/pixel_aot_check.py | 296 ++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 134 ++++++++++++++++ 4 files changed, 464 insertions(+), 12 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index fbd5ce72b..586ca73a0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8035,9 +8035,9 @@ The source-built draw (`pixel_aot_dpp_cvt_{warp,hardware}`) compares all four ch Plain `v_mul_lo_u32` multiplies two full 32-bit operands and keeps the low 32 bits. The `pixel_aot_e64_{warp,hardware}` draw reads back the integer word for `0xffffffff * 0xffffffff` and `0x12345678 * 0x9abcdef0`, whose low words are `0x00000001` and `0x242d2080`. Replacing multiply with addition must fail the same readback. The LLVM 15 binary fixture verifies the opcode through the normal decoding path. -Quad-local `DPP16` (`quad_perm` with `row_mask:0xf bank_mask:0xf`) and `DPP8` (`dpp8` repeating the same 2×2 quad permutation on lanes 0–3 and 4–7) lower `v_cvt_f16_f32_dpp` via the shared quad routing helpers and existing integer-arithmetic `narrow16` nearest-even helper under the shared low-16-only destination contract (#732/#881: bits 15:0 are defined and tagged `("half16", alu)`, while bits 31:16 stay unspecified so no previous high half is merged). The same quad-local `DPP16`/`DPP8` slice also lowers the eight binary16 arithmetic and rounding opcodes (`v_add_f16_dpp`, `v_sub_f16_dpp`, `v_subrev_f16_dpp`, `v_mul_f16_dpp`, `v_floor_f16_dpp`, `v_ceil_f16_dpp`, `v_trunc_f16_dpp`, `v_rndne_f16_dpp`, 16 forms across `DPP16` and `DPP8`) under the static finite-proof contract (#839): VGPR sources must carry a statically proven finite low half (`known_ssa_bits` or `known_half`), `src0` is quad-swizzled via `emit_quad_swizzle_u32` while `src1` stays on the current lane, `DPP16` permits bit-15 `abs`/`neg` modifiers on either source (refused on `DPP8`), overflowing results are refused via `f16_vop2_result`, and destinations are tagged `("half16", alu)` with their proven low-16 bits for chaining. Lowering requires explicit `half_denorm="preserve"` at shader entry and respects `HW_REG_MODE` binary16 rounding (`HALF_RTZ` refuses every form, while restoring `HALF_RNE` matches `s_nop 0`). Unproved `fi:`/`bound_ctrl:`, partial row/bank masks, cross-quad or non-repeated `DPP8`, uninitialized or unproven runtime operands, non-finite inputs, and other binary16 DPP opcodes (`v_min_f16_dpp`, `v_max_f16_dpp`, `v_fract_f16_dpp`, `v_fmac_f16_dpp`, `v_ldexp_f16_dpp`, transcendentals) remain refused. +Quad-local `DPP16` (`quad_perm` with `row_mask:0xf bank_mask:0xf`) and `DPP8` (`dpp8` repeating the same 2×2 quad permutation on lanes 0–3 and 4–7) lower `v_cvt_f16_f32_dpp` via the shared quad routing helpers and existing integer-arithmetic `narrow16` nearest-even helper under the shared low-16-only destination contract (#732/#881: bits 15:0 are defined and tagged `("half16", alu)`, while bits 31:16 stay unspecified so no previous high half is merged). The same quad-local `DPP16`/`DPP8` slice also lowers the eight binary16 arithmetic and rounding opcodes (`v_add_f16_dpp`, `v_sub_f16_dpp`, `v_subrev_f16_dpp`, `v_mul_f16_dpp`, `v_floor_f16_dpp`, `v_ceil_f16_dpp`, `v_trunc_f16_dpp`, `v_rndne_f16_dpp`, 16 forms across `DPP16` and `DPP8`) plus `v_fmac_f16_dpp`, `v_ldexp_f16_dpp`, `v_cvt_f16_i16_dpp`, `v_cvt_f16_u16_dpp`, `v_cvt_i16_f16_dpp`, and `v_cvt_u16_f16_dpp` (12 additional forms across `DPP16` and `DPP8`) under the static finite-proof contract (#839): `src0` is quad-swizzled via `emit_quad_swizzle_u32` while `src1` and the `v_fmac_f16_dpp` accumulator stay on the current lane, `DPP16` permits bit-15 `abs`/`neg` modifiers on float sources only (refused on `DPP8` and on integer operands of `v_ldexp_f16_dpp` and `v_cvt_f16_{i16,u16}_dpp`), `v_fmac_f16_dpp` uses `fma16_rne` for single-rounding fused multiply-add, `v_ldexp_f16_dpp` requires a statically proven signed 16-bit exponent within `[-64, 64]`, `v_cvt_f16_i16_dpp` accepts runtime `i16`/`low16` sources while `v_cvt_f16_u16_dpp` requires a static proof `< 65520`, and `v_cvt_{i16,u16}_f16_dpp` truncates proven in-range binary16 values into `("low16", alu)`. Lowering requires explicit `half_denorm="preserve"` at shader entry and respects `HW_REG_MODE` binary16 rounding (`HALF_RTZ` refuses every form, while restoring `HALF_RNE` matches `s_nop 0`). Unproved `fi:`/`bound_ctrl:`, partial row/bank masks, cross-quad or non-repeated `DPP8`, uninitialized or unproven runtime operands (except `v_cvt_f16_i16_dpp`), non-finite inputs, and other binary16 DPP opcodes (`v_min_f16_dpp`, `v_max_f16_dpp`, `v_fract_f16_dpp`, `v_cvt_norm_{i16,u16}_f16_dpp`, `v_frexp_*_f16_dpp`, transcendentals) remain refused. -The dedicated `pixel_aot_dpp_f16_{warp,hardware}` draw runs `DPP_F16_CVT_LANES`, `DPP_F16_CVT_WORDS`, and four raw low-16 programs (`arith_dpp16`, `arith_dpp8`, `round_dpp16`, `round_dpp8`, all round-tripped through LLVM 15 `check_binary`) covering all 16 arithmetic/rounding DPP forms under noisy upper-16 halves, preloaded destination sentinels, subnormal preservation (tested under both default denorm mode and `-denorm ftz`), `-0.0` sign preservation, ties-to-even rounding, `half16` chaining, and `DPP16` `-`/`|.|`/`-|.|` modifiers. Positive and negative controls verify low-half widening, `QuadRead*` emission on `src0` only, and rejections for `WORD_1`/whole-word reads, unproven runtime sources, overflow, non-finite inputs, `HALF_RTZ`, and mutations (swapping `AcrossX`/`AcrossY`, reversing `dpp8`, dropping `-` or `|.|`, swapping `sub`/`subrev` or `floor`/`ceil`/`trunc`/`rndne`, or altering `narrow16` to truncate or tie-away). Run `ctest --preset dev --no-tests=error -R "^pixel_aot_dpp_f16_(warp|hardware)$" -V`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) +The dedicated `pixel_aot_dpp_f16_{warp,hardware}` draw runs `DPP_F16_CVT_LANES`, `DPP_F16_CVT_WORDS`, `DPP_F16_CVT_I16_LANES` (per-lane quad routing of runtime signed 16-bit integers with noisy upper halves), four raw low-16 arithmetic/rounding programs (`arith_dpp16`, `arith_dpp8`, `round_dpp16`, `round_dpp8`), and four raw low-16 fmac/ldexp/conversion programs (`fmac_ldexp_dpp16`, `fmac_ldexp_dpp8`, `cvt_int16_dpp16`, `cvt_int16_dpp8`, all round-tripped through LLVM 15 `check_binary`) covering all 28 arithmetic/rounding/fmac/ldexp/conversion DPP forms under noisy upper-16 halves, preloaded destination sentinels, fused-vs-non-fused rounding (`0x1c01` vs `0x1c00`), subnormal preservation (tested under both default denorm mode and `-denorm ftz`), `-0.0` sign preservation, ties-to-even rounding, the `65519` max finite `u16` boundary, `half16`/`low16` chaining, and `DPP16` `-`/`|.|`/`-|.|` modifiers. Positive and negative controls verify low-half widening, `QuadRead*` emission on `src0` only, and rejections for `WORD_1`/whole-word reads, unproven runtime sources, overflow, out-of-range conversions/exponents, non-finite inputs, `HALF_RTZ`, and mutations (swapping `AcrossX`/`AcrossY`, reversing `dpp8`, dropping `-` or `|.|`, swapping `sub`/`subrev`, `fmac`/`mul`, `u16`/`i16`, `ldexp` exponents, or `floor`/`ceil`/`trunc`/`rndne`, or altering `narrow16` to truncate or tie-away). Run `ctest --preset dev --no-tests=error -R "^pixel_aot_dpp_f16_(warp|hardware)$" -V`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) Quad-local `DPP16` (`quad_perm` with `row_mask:0xf bank_mask:0xf`) and `DPP8` (`dpp8` repeating the same 2×2 quad permutation on lanes 0–3 and 4–7) lower across 24 32-bit integer, 24-bit multiply, bitwise, shift, bit-scan and saturating-pack `VOP1`/`VOP2` forms (`add_nc_u32`, `sub_nc_u32`, `subrev_nc_u32`, `min`/`max` `i32`/`u32`, `mul`/`mul_hi` `i24`/`u24`, `and`/`or`/`xor`/`xnor`/`not_b32`, `lshlrev`/`lshrrev_b32`, `ashrrev_i32`, `bfrev_b32`, `ffbl_b32`, `ffbh_u32`/`ffbh_i32` and `sat_pk_u8_i16`, which clamps each signed halfword to `[0, 255]` as its e32 form does) via SM 6.0 quad intrinsics, emitting 12-bit-split `dpp_mul_hi_{u,i}24` and MSB-indexed `dpp_ffbh_{u,i}32` helpers only when used. The `dpp_int32` fixture derives integer quad lane ID `{0, 1, 2, 3}` from `uv.x`/`uv.y`, tests all 24 forms across three constant sets (including negative/extreme `i24` products, zero/all-ones bit scans, shift counts `>= 32`, and halfwords that saturate at 0 and at 255 or stay in range), exports all four bytes of the 32-bit accumulator as exact `[0, 255]` integers, and checks six mutations (`AcrossX` vs `AcrossY`, cyclic `dpp8` rotation, `ashrrev` vs `lshrrev`, signed vs unsigned `mul_hi` and `ffbh`, and `sat_pk_u8_i16` of the wrong source) that must each report a mismatch. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 0d99c8739..a902aa14a 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -1438,8 +1438,8 @@ def check_dpp_f16_arith_round_forms(): ("DPP16", "v_min_f16_dpp"), ("DPP8", "v_min_f16_dpp"), ("DPP16", "v_max_f16_dpp"), ("DPP8", "v_max_f16_dpp"), ("DPP16", "v_fract_f16_dpp"), ("DPP8", "v_fract_f16_dpp"), - ("DPP16", "v_fmac_f16_dpp"), ("DPP8", "v_fmac_f16_dpp"), - ("DPP16", "v_ldexp_f16_dpp"), ("DPP8", "v_ldexp_f16_dpp"), + ("DPP16", "v_rcp_f16_dpp"), ("DPP8", "v_rcp_f16_dpp"), + ("DPP16", "v_cvt_norm_i16_f16_dpp"), ("DPP8", "v_cvt_norm_i16_f16_dpp"), ("SDWA", "v_add_f16_sdwa"), ("SDWA", "v_floor_f16_sdwa"), } for name in ("gfx1013.tsv", "rdna2.tsv"): @@ -1458,6 +1458,43 @@ def check_dpp_f16_arith_round_forms(): pixel.ACCEPTED.update(saved) +def check_dpp_f16_cvt_fmac_ldexp_forms(): + """The 12 quad-local DPP16/DPP8 binary16 fmac, ldexp and int16 conversion forms count as covered + once the translator accepts their fixtures; unlowered f16 DPP/SDWA neighbours stay uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for body in pixel.DPP_F16_CVT_FMAC_LDEXP_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + ops = ("v_fmac_f16_dpp", "v_ldexp_f16_dpp", "v_cvt_f16_i16_dpp", + "v_cvt_f16_u16_dpp", "v_cvt_i16_f16_dpp", "v_cvt_u16_f16_dpp") + forms = {(group, op) for group in ("DPP16", "DPP8") for op in ops} + assert len(forms) == 12 + neighbours = { + ("DPP16", "v_cvt_norm_i16_f16_dpp"), ("DPP8", "v_cvt_norm_i16_f16_dpp"), + ("DPP16", "v_cvt_norm_u16_f16_dpp"), ("DPP8", "v_cvt_norm_u16_f16_dpp"), + ("DPP16", "v_frexp_mant_f16_dpp"), ("DPP8", "v_frexp_mant_f16_dpp"), + ("DPP16", "v_frexp_exp_i16_f16_dpp"), ("DPP8", "v_frexp_exp_i16_f16_dpp"), + ("DPP16", "v_rcp_f16_dpp"), ("DPP8", "v_rcp_f16_dpp"), + ("SDWA", "v_ldexp_f16_sdwa"), ("SDWA", "v_cvt_f16_i16_sdwa"), ("SDWA", "v_cvt_i16_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not (neighbours & covered), (name, sorted(neighbours & covered)) + # Control: removing one opcode removes both its DPP16 and DPP8 forms from the count. + stripped = pixel.ACCEPTED - {"v_fmac_f16_dpp"} + assert not {("DPP16", "v_fmac_f16_dpp"), ("DPP8", "v_fmac_f16_dpp")} & fc.gfx_forms( + stripped, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + if __name__ == "__main__": check_denominators() check_example() @@ -1479,6 +1516,7 @@ def check_dpp_f16_arith_round_forms(): check_f16_cvt_int16_forms() check_f16_to_int16_forms() check_dpp_f16_arith_round_forms() + check_dpp_f16_cvt_fmac_ldexp_forms() check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 65c525b64..4f9af6656 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -9942,7 +9942,7 @@ def check_dpp_cvt_refusals(): "DPP operand v255 is read before it is written"), ("v_cvt_pkrtz_f16_f32_dpp v16, v12, v13 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf bound_ctrl:1", "Unsupported DPP16 modifier"), - ("v_cvt_i16_f16_dpp v55, v12 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + ("v_cvt_norm_i16_f16_dpp v55, v12 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "Unsupported instruction"), ("v_cvt_f32_i32_dpp v12, v255 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "DPP operand v255 is read before it is written"), @@ -10234,6 +10234,146 @@ def bits(value): ), } +# Quad-local DPP16 and DPP8 binary16 fused multiply-accumulate (v_fmac_f16_dpp), exponent scaling +# (v_ldexp_f16_dpp), and 16-bit integer conversions (v_cvt_f16_{i16,u16}_dpp, v_cvt_{i16,u16}_f16_dpp) +# fixtures under the low-16-only and static finite-proof contract (#839). All static inputs carry +# noisy upper-16 halves, destinations are preloaded with sentinels, and results cover fused vs +# non-fused rounding (0x1c01 vs 0x1c00), subnormals, ties-to-even, 65519 max finite u16 boundary, +# truncation toward zero, half16 chaining, and DPP16 bit-15 abs/neg modifiers. +DPP_F16_CVT_FMAC_LDEXP_PROGRAMS = { + "fmac_ldexp_dpp16": [ + "v_mov_b32_e32 v20, 0xdeadbc03", # -(1 + 3*2^-10) + "v_mov_b32_e32 v21, 0xbeefbc01", # -(1 + 2^-10) + "v_mov_b32_e32 v22, 0x56784000", # +2.0 + "v_mov_b32_e32 v23, 0x9abc3e00", # +1.5 + "v_mov_b32_e32 v24, 0x1234bc00", # -1.0 accumulator + "v_mov_b32_e32 v25, 0xdead3800", # +0.5 accumulator + "v_mov_b32_e32 v26, 0xc0a00000", + "v_mov_b32_e32 v27, 0x41200000", + "v_mov_b32_e32 v28, 0xbeeffffd", # i16 exponent -3 + "v_mov_b32_e32 v29, 0x1234fff0", # i16 exponent -16 + "v_fmac_f16_dpp v24, -v20, |v21| quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_fmac_f16_dpp v25, v22, -v23 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_ldexp_f16_dpp v26, -v22, v28 quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "v_ldexp_f16_dpp v27, |v23|, v29 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v25 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v26 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v27 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + ], + "fmac_ldexp_dpp8": [ + "v_mov_b32_e32 v20, 0xdead3c03", # +(1 + 3*2^-10) + "v_mov_b32_e32 v21, 0xbeef3c01", # +(1 + 2^-10) + "v_mov_b32_e32 v22, 0x56784100", # +2.5 + "v_mov_b32_e32 v23, 0x9abcbe00", # -1.5 + "v_mov_b32_e32 v24, 0x1234bc00", # -1.0 accumulator + "v_mov_b32_e32 v25, 0x41204200", # +3.0 accumulator + "v_mov_b32_e32 v28, 0xabcd0003", # i16 exponent +3 + "v_mov_b32_e32 v29, 0x77770001", # subnormal 2^-24 + "v_mov_b32_e32 v30, 0x88880002", # i16 exponent +2 + "v_fmac_f16_dpp v24, v20, v21 dpp8:[1,2,3,0,5,6,7,4]", + "v_fmac_f16_dpp v25, v22, v23 dpp8:[2,3,0,1,6,7,4,5]", + "v_ldexp_f16_dpp v26, v25, v28 dpp8:[3,2,1,0,7,6,5,4]", + "v_ldexp_f16_dpp v27, v29, v30 dpp8:[1,0,3,2,5,4,7,6]", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v25 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v26 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v27 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + ], + "cvt_int16_dpp16": [ + "v_mov_b32_e32 v20, 0xdeadf7fd", # i16 -2051 -> ties-to-even -2052 (0xe802) + "v_mov_b32_e32 v21, 0xbeef8002", # u16 32770 -> ties-to-even 32768 (0x7800) + "v_mov_b32_e32 v22, 0x123442e0", # +3.4375 -> -v22 = -3.4375 -> i16 -3 (0xfffd) + "v_mov_b32_e32 v23, 0x5678c4c0", # -4.75 -> |v23| = +4.75 -> u16 4 (0x0004) + "v_mov_b32_e32 v24, 0x3f400000", + "v_mov_b32_e32 v25, 0xdeadbeef", + "v_cvt_f16_i16_dpp v24, v20 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_cvt_f16_u16_dpp v25, v21 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_cvt_i16_f16_dpp v26, -v22 quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "v_cvt_u16_f16_dpp v27, |v23| quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v25 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v26 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v27 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + ], + "cvt_int16_dpp8": [ + "v_mov_b32_e32 v20, 0xdeadf7ff", # i16 -2049 -> ties-to-even -2048 (0xe800) + "v_mov_b32_e32 v21, 0xbeefffef", # u16 65519 -> 65504 (0x7bff) + "v_mov_b32_e32 v22, 0x1234c880", # -9.0 -> i16 -9 (0xfff7) + "v_mov_b32_e32 v23, 0x56787bff", # +65504.0 -> u16 65504 (0xffe0) + "v_mov_b32_e32 v28, 0x9abc4200", # +3.0 (used by mutation) + "v_mov_b32_e32 v24, 0x3f400000", + "v_cvt_f16_i16_dpp v24, v20 dpp8:[1,2,3,0,5,6,7,4]", + "v_cvt_f16_u16_dpp v25, v21 dpp8:[2,3,0,1,6,7,4,5]", + "v_cvt_i16_f16_dpp v26, v22 dpp8:[3,2,1,0,7,6,5,4]", + "v_cvt_u16_f16_dpp v27, v23 dpp8:[1,0,3,2,5,4,7,6]", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v25 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v26 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v27 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + ], +} +DPP_F16_CVT_FMAC_LDEXP_EXPECTED = { + "fmac_ldexp_dpp16": (0x1c01, 0xc100, 0xb400, 0x0180), + "fmac_ldexp_dpp8": (0x1c01, 0xba00, 0xc600, 0x0004), + "cvt_int16_dpp16": (0xe802, 0x7800, 0xfffd, 0x0004), + "cvt_int16_dpp8": (0xe800, 0x7bff, 0xfff7, 0xffe0), +} +DPP_F16_CVT_FMAC_LDEXP_MUTATIONS = { + "fmac_ldexp_dpp16": ( + ("v_fmac_f16_dpp v24, -v20, |v21|", "v_fmac_f16_dpp v24, v20, |v21|"), + ("v_fmac_f16_dpp v24, -v20, |v21|", "v_fmac_f16_dpp v24, -v20, v21"), + ("v_fmac_f16_dpp v24", "v_mul_f16_dpp v24"), + ("v_ldexp_f16_dpp v26, -v22, v28", "v_ldexp_f16_dpp v26, v22, v28"), + ("v_ldexp_f16_dpp v26, -v22, v28", "v_ldexp_f16_dpp v26, -v22, v29"), + ), + "fmac_ldexp_dpp8": ( + ("v_fmac_f16_dpp v24", "v_mul_f16_dpp v24"), + ("v_ldexp_f16_dpp v26, v25, v28", "v_ldexp_f16_dpp v26, v25, v30"), + ), + "cvt_int16_dpp16": ( + ("v_cvt_f16_u16_dpp v25, v21", "v_cvt_f16_i16_dpp v25, v21"), + ("v_cvt_i16_f16_dpp v26, -v22", "v_cvt_i16_f16_dpp v26, v22"), + ("v_cvt_u16_f16_dpp v27, |v23|", "v_cvt_u16_f16_dpp v27, v22"), + ), + "cvt_int16_dpp8": ( + ("v_cvt_f16_u16_dpp v25, v21", "v_cvt_f16_i16_dpp v25, v21"), + ("v_cvt_i16_f16_dpp v26, v22", "v_cvt_i16_f16_dpp v26, v24"), + ("v_cvt_u16_f16_dpp v27, v23", "v_cvt_u16_f16_dpp v27, v28"), + ), +} +# Per-lane quad-routing witness for runtime v_cvt_f16_i16_dpp (DPP16 AcrossX + DPP8 cyclic rotation) +# with noisy upper-16 bits (0x1234) over lanes {0..3} holding signed i16 values {-4, -3, -2, -1}. +DPP_F16_CVT_I16_LANES = [ + *DPP_CVT_LANES, + "v_cvt_i32_f32_e32 v21, v20", + "v_subrev_nc_u32_e32 v21, 4, v21", + "v_and_b32_e32 v21, 0xffff, v21", + "v_or_b32_e32 v21, 0x12340000, v21", + "v_mov_b32_e32 v22, 0x3f400000", + "v_cvt_f16_i16_dpp v22, v21 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_mov_b32_e32 v24, 0xdeadbeef", + "v_cvt_f16_i16_dpp v24, v21 dpp8:[1,2,3,0,5,6,7,4]", + "v_cvt_f32_f16_e32 v23, v22", + "v_cvt_f32_f16_e32 v25, v24", + *[f"v_mov_b32_dpp v{26 + lane}, v23 quad_perm:[{lane},{lane},{lane},{lane}] row_mask:0xf bank_mask:0xf" + for lane in range(4)], + *[f"v_mov_b32_dpp v{30 + lane}, v25 quad_perm:[{lane},{lane},{lane},{lane}] row_mask:0xf bank_mask:0xf" + for lane in range(4)], + "v_fma_f32 v34, 4.0, v27, v26", + "v_fma_f32 v34, 0x41800000, v28, v34", + "v_fma_f32 v34, 0x42800000, v29, v34", + "v_cvt_i32_f32_e32 v12, v34", + "v_fma_f32 v35, 4.0, v31, v30", + "v_fma_f32 v35, 0x41800000, v32, v35", + "v_fma_f32 v35, 0x42800000, v33, v35", + "v_cvt_i32_f32_e32 v13, v35", + "v_mov_b32_sdwa v36, v22 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_dpp v14, v36 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v37, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_dpp v15, v37 quad_perm:[3,3,3,3] row_mask:0xf bank_mask:0xf", +] + def dpp_f16_narrow16_ref(bits): """Exact IEEE-754 binary32-to-binary16 RNE reference matching tools/pixel_aot.py narrow16().""" @@ -10298,7 +10438,7 @@ def check_dpp_f16_contract_controls(): for write, message in (("s_denorm_mode 15", "Unsupported instruction"), ("s_round_mode 0x3", "Unsupported rounding mode"), ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 6, 2), 3", "Unsupported hardware register write")): expect_value_error(translate_f16, [write, *valid], message) - # DPP encoding refusals and out-of-slice binary16 DPP opcodes (including FMAC and transcendentals). + # DPP encoding refusals and out-of-slice binary16 DPP opcodes (transcendentals, min/max, norm/frexp). for bad, message in ( ("v_cvt_f16_f32_dpp v23, v20 row_shl:1 row_mask:0xf bank_mask:0xf", "Unsupported DPP control row_shl:1"), ("v_cvt_f16_f32_dpp v23, v20 quad_perm:[0,1,2,3] row_mask:0x7 bank_mask:0xf", "Unsupported DPP16 modifier row_mask:0x7"), @@ -10309,7 +10449,8 @@ def check_dpp_f16_contract_controls(): ("v_cvt_f16_f32_dpp v23, -v20 dpp8:[1,2,3,0,5,6,7,4]", "Source modifiers are not allowed on -v20"), (f"v_cvt_f16_f32_dpp v23, v70 {identity}", "DPP operand v70 is read before it is written"), (f"v_cvt_f16_f32_dpp v256, v20 {identity}", "Invalid f16 DPP operation"), - (f"v_fmac_f16_dpp v20, v20, v20 {identity}", "Unsupported instruction"), + (f"v_cvt_norm_i16_f16_dpp v23, v20 {identity}", "Unsupported instruction"), + (f"v_rcp_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_min_f16_dpp v23, v20, v20 {identity}", "Unsupported instruction"), (f"v_max_f16_dpp v23, v20, v20 {identity}", "Unsupported instruction"), (f"v_sin_f16_dpp v23, v20 {identity}", "Unsupported instruction"), @@ -10362,6 +10503,99 @@ def check_dpp_f16_contract_controls(): (proven_pair, f"v_floor_f16_dpp v24, v20 {identity} fi:1", "Unsupported DPP16 modifier fi:1"), ): expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) + # Positive and negative controls for binary16 fmac, ldexp, and int16 conversion DPP16/DPP8. + for name, body in DPP_F16_CVT_FMAC_LDEXP_PROGRAMS.items(): + prog = uncompressed_export(body) + hlsl = translate_f16(prog) + if name == "fmac_ldexp_dpp16": + assert "fma16_rne(" in hlsl + assert "QuadReadAcrossX(" in hlsl and "QuadReadAcrossY(" in hlsl and "QuadReadAcrossDiagonal(" in hlsl + src1_lines = [line for line in hlsl.splitlines() if "_1 = " in line and "uint hf" in line] + assert len(src1_lines) == 2 and all("QuadRead" not in line for line in src1_lines), src1_lines + dst_lines = [line for line in hlsl.splitlines() if "_2 = " in line and "uint hf" in line] + assert len(dst_lines) == 2 and all("QuadRead" not in line for line in dst_lines), dst_lines + elif name == "fmac_ldexp_dpp8": + assert "fma16_rne(" in hlsl and "QuadReadLaneAt(" in hlsl + elif name == "cvt_int16_dpp16": + assert "QuadReadAcrossX(" in hlsl and "QuadReadAcrossY(" in hlsl and "QuadReadAcrossDiagonal(" in hlsl + elif name == "cvt_int16_dpp8": + assert "QuadReadLaneAt(" in hlsl + for old, new in DPP_F16_CVT_FMAC_LDEXP_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + assert translate_f16(mutated) != hlsl, (name, old, new) + translate_f16(uncompressed_export(DPP_F16_CVT_I16_LANES)) + # low16 -> v_cvt_f16_i16_dpp chaining and half16 -> v_cvt_u16_f16_dpp chaining are accepted, + # while half16 -> v_cvt_f16_i16_dpp and low16 -> v_cvt_f32_f16 are refused. + translate_f16(uncompressed_export([ + *proven_pair, f"v_cvt_i16_f16_dpp v24, v20 {identity}", + f"v_cvt_f16_i16_dpp v25, v24 {identity}", f"v_mov_b32_sdwa v12, v25 {sdwa}WORD_0"])) + translate_f16(uncompressed_export([ + "v_mov_b32_e32 v20, 0x0005", f"v_cvt_f16_u16_dpp v24, v20 {identity}", + f"v_cvt_u16_f16_dpp v25, v24 {identity}", f"v_mov_b32_sdwa v12, v25 {sdwa}WORD_0"])) + fmac_ok = uncompressed_export([*proven_pair, "v_mov_b32_e32 v24, 0x3c00", + f"v_fmac_f16_dpp v24, v20, v21 {identity}", + f"v_mov_b32_sdwa v12, v24 {sdwa}WORD_0"]) + ldexp_ok = uncompressed_export(["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 0x0002", + f"v_ldexp_f16_dpp v24, v20, v21 {identity}", + f"v_mov_b32_sdwa v12, v24 {sdwa}WORD_0"]) + cvt_i16_ok = uncompressed_export(["v_mov_b32_e32 v20, s44", f"v_cvt_f16_i16_dpp v24, v20 {identity}", + f"v_mov_b32_sdwa v12, v24 {sdwa}WORD_0"]) + to_i16_ok = uncompressed_export([*proven_pair, f"v_cvt_i16_f16_dpp v24, v20 {identity}", + f"v_mov_b32_sdwa v12, v24 {sdwa}WORD_0"]) + for prog, op in ((fmac_ok, "v_fmac_f16_dpp"), (ldexp_ok, "v_ldexp_f16_dpp"), + (cvt_i16_ok, "v_cvt_f16_i16_dpp"), (to_i16_ok, "v_cvt_i16_f16_dpp")): + expect_value_error(translate_int, prog, "binary16 denormal mode unknown at entry") + expect_value_error(translate_f16, [HALF_RTZ, *prog], f"under round toward zero: {op}") + for prefix, bad, message in ( + # v_fmac_f16_dpp: unproven accumulator/src, overflow, DPP8 modifiers, non-finite. + ([*proven_pair, "v_mov_b32_e32 v24, s44"], f"v_fmac_f16_dpp v24, v20, v21 {identity}", + "binary16 operand lacks a finite proof: v24"), + (["v_mov_b32_e32 v20, 0x7bff", "v_mov_b32_e32 v24, 0x3c00"], f"v_fmac_f16_dpp v24, v20, v20 {identity}", + "binary16 result overflows: v_fmac_f16_dpp"), + ([*proven_pair, "v_mov_b32_e32 v24, 0x3c00"], "v_fmac_f16_dpp v24, -v20, v21 dpp8:[1,2,3,0,5,6,7,4]", + "Source modifiers are not allowed on -v20"), + ([*proven_pair, "v_mov_b32_e32 v24, 0x3c00"], "v_fmac_f16_dpp v24, v20, |v21| dpp8:[1,2,3,0,5,6,7,4]", + "Source modifiers are not allowed on |v21|"), + # v_ldexp_f16_dpp: unproven exponent, out-of-range exponent, overflow, src1 modifier, DPP8 src0 modifier. + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, s44"], f"v_ldexp_f16_dpp v24, v20, v21 {identity}", + "binary16 ldexp exponent lacks a proof: v21"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 65"], f"v_ldexp_f16_dpp v24, v20, v21 {identity}", + "binary16 ldexp exponent out of range: 65"), + (["v_mov_b32_e32 v20, 0x7bff", "v_mov_b32_e32 v21, 1"], f"v_ldexp_f16_dpp v24, v20, v21 {identity}", + "binary16 result overflows: v_ldexp_f16_dpp"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], f"v_ldexp_f16_dpp v24, v20, -v21 {identity}", + "Source modifiers are not allowed on -v21"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], f"v_ldexp_f16_dpp v24, v20, |v21| {identity}", + "Source modifiers are not allowed on |v21|"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], f"v_ldexp_f16_dpp v24, v20, abs(v21) {identity}", + "Source modifiers are not allowed on abs(v21)"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], "v_ldexp_f16_dpp v24, -v20, v21 dpp8:[1,2,3,0,5,6,7,4]", + "Source modifiers are not allowed on -v20"), + # v_cvt_f16_{i16,u16}_dpp: runtime u16 refused, 65520 overflow, float modifiers refused on DPP16, half16 refused. + (["v_mov_b32_e32 v20, s44"], f"v_cvt_f16_u16_dpp v24, v20 {identity}", + "binary16 conversion source lacks a range proof: v20"), + (["v_mov_b32_e32 v20, 0xfff0"], f"v_cvt_f16_u16_dpp v24, v20 {identity}", + "binary16 result overflows: v_cvt_f16_u16_dpp"), + (["v_mov_b32_e32 v20, 0x0001"], f"v_cvt_f16_i16_dpp v24, -v20 {identity}", + "Source modifiers are not allowed on -v20"), + (["v_mov_b32_e32 v20, 0x0001"], f"v_cvt_f16_u16_dpp v24, |v20| {identity}", + "Source modifiers are not allowed on |v20|"), + ([*proven_pair, f"v_add_f16_dpp v24, v20, v21 {identity}"], f"v_cvt_f16_i16_dpp v25, v24 {identity}", + "Expected a numeric register"), + # v_cvt_{i16,u16}_f16_dpp: unproven, out-of-range (-1 for u16, 32768 for i16), DPP8 modifier, low16 tag check. + (["v_mov_b32_e32 v20, s44"], f"v_cvt_i16_f16_dpp v24, v20 {identity}", + "binary16 operand lacks a finite proof: v20"), + (["v_mov_b32_e32 v20, 0xbc00"], f"v_cvt_u16_f16_dpp v24, v20 {identity}", + "binary16 value out of range: v_cvt_u16_f16_dpp"), + (["v_mov_b32_e32 v20, 0x7800"], f"v_cvt_i16_f16_dpp v24, v20 {identity}", + "binary16 value out of range: v_cvt_i16_f16_dpp"), + (proven_pair, "v_cvt_i16_f16_dpp v24, -v20 dpp8:[1,2,3,0,5,6,7,4]", + "Source modifiers are not allowed on -v20"), + ([*proven_pair, f"v_cvt_i16_f16_dpp v24, v20 {identity}"], "v_cvt_f32_f16_e32 v12, v24", + "Expected a numeric register"), + ): + expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) # Scheduling: outstanding sample and non-entry EXEC mask must refuse. base = uncompressed_export([]) sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) @@ -10481,6 +10715,55 @@ def check_dpp_f16_draw(directory, compiler, renderer, backend): print(f"dpp_f16 {name} mutation {old!r} -> {new!r}: statuses {statuses}") if "mismatch" not in statuses: raise AssertionError(f"dpp_f16 {name} mutation {old!r} -> {new!r} escaped detection") + + # 4. Binary16 fmac, ldexp, and int16 conversion DPP16 & DPP8 draws, verified in both default + # denorm mode and binary32 -denorm ftz, plus op/modifier mutations and per-lane i16 routing. + for name, body in DPP_F16_CVT_FMAC_LDEXP_PROGRAMS.items(): + prog = uncompressed_export(body) + expected = DPP_F16_CVT_FMAC_LDEXP_EXPECTED[name] + src_path = directory / f"dpp_f16_{name}.hlsl" + cso_path = directory / f"dpp_f16_{name}.cso" + pass_case = directory / f"dpp_f16_{name}_pass.case" + pass_case.write_bytes(bytes(256) + struct.pack("<4I", *expected) * 64 + b"\x01") + src_path.write_text(translate_f16(prog), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + # Binary32 -denorm ftz must preserve binary16 subnormals. + compile_shader(compiler, src_path, cso_path, mode="ftz") + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + for old, new in DPP_F16_CVT_FMAC_LDEXP_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + src_path.write_text(translate_f16(mutated), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cso_path, [pass_case]) + print(f"dpp_f16 {name} mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"dpp_f16 {name} mutation {old!r} -> {new!r} escaped detection") + i16_lanes_prog = uncompressed_export(DPP_F16_CVT_I16_LANES) + i16_lanes_src = directory / "dpp_f16_cvt_i16_lanes.hlsl" + i16_lanes_cso = directory / "dpp_f16_cvt_i16_lanes.cso" + i16_lanes_case = directory / "dpp_f16_cvt_i16_lanes.case" + i16_lanes_src.write_text(translate_f16(i16_lanes_prog), encoding="ascii") + compile_shader(compiler, i16_lanes_src, i16_lanes_cso) + # ch0: (-3)*1 + (-4)*4 + (-1)*16 + (-2)*64 = -163 (0xffffff5d) + # ch1: (-3)*1 + (-2)*4 + (-1)*16 + (-4)*64 = -283 (0xfffffee5) + # ch2: lane 0 of v22 = f16(-3.0) = 0xc200; ch3: lane 3 of v24 = f16(-4.0) = 0xc400 + i16_lanes_expected = (0xffffff5d, 0xfffffee5, 0xc200, 0xc400) + i16_lanes_case.write_bytes(bytes(256) + struct.pack("<4I", *i16_lanes_expected) * 64 + b"\x01") + run_pixel_batch(renderer, backend, i16_lanes_cso, [(i16_lanes_case, "pass")]) + for old, new in ( + ("quad_perm:[1,0,3,2]", "quad_perm:[2,3,0,1]"), + ("dpp8:[1,2,3,0,5,6,7,4]", "dpp8:[3,0,1,2,7,4,5,6]"), + ): + mutated = [line.replace(old, new) for line in i16_lanes_prog] + assert mutated != i16_lanes_prog, old + i16_lanes_src.write_text(translate_f16(mutated), encoding="ascii") + compile_shader(compiler, i16_lanes_src, i16_lanes_cso) + statuses, _ = run_pixel_batch_statuses(renderer, backend, i16_lanes_cso, [i16_lanes_case]) + print(f"dpp_f16 cvt_i16_lanes mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"dpp_f16 cvt_i16_lanes mutation {old!r} -> {new!r} escaped detection") return 0 @@ -15405,7 +15688,6 @@ def refuse(line, message, *lines): translate_f16(program("v_mov_b32_e32 v24, 0x3c00", f"v_{op}_f16_e32 v24, {operands}")) for form in (f"v_{op}_f16_e64 v24, v18, v19", f"v_{op}_f16_e64 v24, v18, v19 clamp", f"v_{op}_f16_e64 v24, v18, v19 mul:2", f"v_{op}_f16_e64 v24, v18, v19 op_sel:[0,1]", f"v_{op}_f16_e32 v24, v18, v19 clamp", - f"v_{op}_f16_dpp v24, v18, v19 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", f"v_{op}_f16_sdwa v24, v18, v19 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", f"v_{op}_f16 v24, v18", f"v_{op}_f16 v24, v18, v19, v19"): refuse(form, "Unsupported instruction") @@ -16260,8 +16542,6 @@ def refuse(line, message, translator=translate_f16): for line in ("v_cvt_f16_i16_e64 v24, v18 clamp", "v_cvt_f16_u16_e64 v24, v18 clamp", "v_cvt_f16_i16_e64 v24, v18 mul:2", "v_cvt_f16_u16_e64 v24, v18 div:2", "v_cvt_f16_i16_e64 v24, v18 op_sel:[0,1]", "v_cvt_f16_i16_e64 v24, -v18 clamp", "v_cvt_f16_i16_e32 v24, v18 clamp", "v_cvt_f16_u16_e32 v24, 1 clamp", - "v_cvt_f16_i16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_cvt_f16_u16_dpp v24, v18 row_shl:1 row_mask:0xf bank_mask:0xf", "v_cvt_f16_i16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_u16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", @@ -16625,8 +16905,6 @@ def refuse(line, message, translator=translate_f16): for line in ("v_cvt_i16_f16_e64 v24, v18 clamp", "v_cvt_u16_f16_e64 v24, v18 clamp", "v_cvt_i16_f16_e64 v24, v18 mul:2", "v_cvt_u16_f16_e64 v24, v18 div:2", "v_cvt_i16_f16_e64 v24, v18 mul:4", "v_cvt_i16_f16_e64 v24, v18 op_sel:[0,1]", "v_cvt_i16_f16_e64 v24, -v18 clamp", "v_cvt_i16_f16_e32 v24, v18 clamp", "v_cvt_u16_f16_e32 v24, 1.0 clamp", - "v_cvt_i16_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_cvt_u16_f16_dpp v24, v18 row_shl:1 row_mask:0xf bank_mask:0xf", "v_cvt_i16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_u16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", @@ -19371,6 +19649,8 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append((uncompressed_export(DPP_F16_CVT_LANES), translate_f16)) fixtures.append((uncompressed_export(DPP_F16_CVT_WORDS), translate_f16)) fixtures.extend((uncompressed_export(body), translate_f16) for body in DPP_F16_ARITH_ROUND_PROGRAMS.values()) + fixtures.extend((uncompressed_export(body), translate_f16) for body in DPP_F16_CVT_FMAC_LDEXP_PROGRAMS.values()) + fixtures.append((uncompressed_export(DPP_F16_CVT_I16_LANES), translate_f16)) fixtures.extend((bit_program(op), translate) for op in BIT_OPERATIONS) fixtures.extend((program, function) for _, program, function, _ in e64_spelling_programs()) fixtures.append((vop1_nop_program(), translate)) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 71bb63dd2..d88a24a2f 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -2378,6 +2378,27 @@ def half16_dpp_source(token, vector, sample_dest, known_ssa_bits, known_half, *, return ssa_var, bits, use_abs, neg +def int16_dpp_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, *, signed): + """Parse one integer VGPR source of a binary16 DPP op (no float modifiers allowed). + + Validates through int16_operand so low16 and numeric VGPRs pass while half16 and non-numeric + tags are rejected. Returns (ssa_var, known_low16_or_None). + """ + if token.startswith(("-", "|", "abs(")): + raise ValueError(f"Source modifiers are not allowed on {token}") + m = re.fullmatch(r"v(\d+)", token) + if not m or not 0 <= int(m.group(1)) <= 255: + raise ValueError(f"DPP operand must be a VGPR, got {token}") + if token not in vector: + raise ValueError(f"DPP operand {token} is read before it is written") + if token in sample_dest: + raise ValueError("Sample used before vmcnt wait") + int16_operand(token, scalar, vector, pending, sample_dest, signed=signed) + ssa_var = low16_name(token, vector) or vector[token] + known = int16_known_value(token, scalar, vector, known_ssa_bits) + return ssa_var, known + + def parse_dpp(rest, operand_count): """Parse operands and quad-local DPP16 (quad_perm) or DPP8 (dpp8) modifiers.""" parts_ = rest.split(", ") @@ -6108,6 +6129,119 @@ def sample_coord(reg): lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result + elif m := match(r"v_(fmac|ldexp)_f16_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 binary16 fused multiply-accumulate (D = S0_swizzled * S1 + D) + # and exponent scaling (D = S0_swizzled * 2^S1) under the static finite-proof contract + # (#839). src0 is quad-swizzled via emit_quad_swizzle_u32; src1 and dst stay on the + # current lane. DPP16 allows bit-15 abs/neg modifiers on float sources (src0 and src1 + # for fmac, src0 only for ldexp); DPP8 and integer src1 refuse modifiers. + name, dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, perm, is_dpp8 = parse_dpp(rest, 2) + s0_val, b0, abs0, neg0 = half16_dpp_source( + tokens[0], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + s0_bits = f"(({emit_quad_swizzle_u32(lines, i, s0_val, perm)}) & 0xffffu)" + if abs0: + s0_bits = f"({s0_bits} & 0x7fffu)" + if neg0: + s0_bits = f"({s0_bits} ^ 0x8000u)" + if name == "fmac": + s1_val, b1, abs1, neg1 = half16_dpp_source( + tokens[1], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + d_val, b2, _, _ = half16_dpp_source( + dst, vector, sample_dest, known_ssa_bits, known_half, allow_mods=False) + result = f16_pk_fmac_lane_result(b0, b1, b2) + if result is None: + raise ValueError("binary16 result overflows: v_fmac_f16_dpp") + s1_bits = f"(asuint({s1_val}) & 0xffffu)" + if abs1: + s1_bits = f"({s1_bits} & 0x7fffu)" + if neg1: + s1_bits = f"({s1_bits} ^ 0x8000u)" + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" uint hf{i}_1 = {s1_bits};") + lines.append(f" uint hf{i}_2 = (asuint({d_val}) & 0xffffu);") + lines.append(f" uint hm{i} = fma16_rne(hf{i}_0, hf{i}_1, hf{i}_2);") + helpers.add("fma16_rne") + lines.append(f" precise float alu{i} = asfloat(hm{i});") + else: + _, known = int16_dpp_source( + tokens[1], scalar, vector, pending, sample_dest, known_ssa_bits, signed=True) + if known is None: + raise ValueError(f"binary16 ldexp exponent lacks a proof: {tokens[1]}") + exponent = known - 0x10000 if known & 0x8000 else known + if abs(exponent) > LDEXP_F16_EXPONENT_LIMIT: + raise ValueError(f"binary16 ldexp exponent out of range: {exponent}") + result = f16_ldexp_result(b0, exponent) + if result is None: + raise ValueError("binary16 result overflows: v_ldexp_f16_dpp") + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = widen16(hf{i}_0) * asfloat({(127 + exponent) << 23}u);") + lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + elif m := match(r"v_cvt_f16_(i16|u16)_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 16-bit integer to binary16 conversion (round to nearest even) + # under the same contract as plain v_cvt_f16_{i16,u16}: runtime i16 is always finite, + # while u16 requires a static proof < 65520. Integer src0 refuses float modifiers. + kind, dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + signed = kind == "i16" + tokens, perm, _ = parse_dpp(rest, 1) + s0_val, known = int16_dpp_source( + tokens[0], scalar, vector, pending, sample_dest, known_ssa_bits, signed=signed) + result = None + if known is not None: + result = f16_cvt_int_result(signed, known) + if result is None: + raise ValueError(f"binary16 result overflows: v_cvt_f16_{kind}_dpp") + elif not signed: + raise ValueError(f"binary16 conversion source lacks a range proof: {tokens[0]}") + swizzled = emit_quad_swizzle_u32(lines, i, s0_val, perm) + word = f"(asint(({swizzled}) << 16) >> 16)" if signed else f"(({swizzled}) & 0xffffu)" + lines.append(f" {'int' if signed else 'uint'} cv{i}_0 = {word};") + lines.append(f" precise float hs{i} = float(cv{i}_0);") + lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + vector[dst] = ("half16", f"alu{i}") + if result is not None: + known_half[f"alu{i}"] = result + elif m := match(r"v_cvt_(i16|u16)_f16_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 binary16 to 16-bit integer conversion (truncation toward zero) + # under the same contract as plain v_cvt_{i16,u16}_f16: statically proven finite src0 + # whose truncated integer lies in range, producing ("low16", alu). DPP16 permits + # bit-15 abs/neg modifiers; DPP8 refuses modifiers. + kind, dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, perm, is_dpp8 = parse_dpp(rest, 1) + s0_val, b0, abs0, neg0 = half16_dpp_source( + tokens[0], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + if f16_to_int_result(kind == "i16", b0) is None: + raise ValueError(f"binary16 value out of range: v_cvt_{kind}_f16_dpp") + s0_bits = f"(({emit_quad_swizzle_u32(lines, i, s0_val, perm)}) & 0xffffu)" + if abs0: + s0_bits = f"({s0_bits} & 0x7fffu)" + if neg0: + s0_bits = f"({s0_bits} ^ 0x8000u)" + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = widen16(hf{i}_0);") + lines.append(f" int cv{i}_0 = int(trunc(hs{i}));") + lines.append(f" precise float alu{i} = asfloat(asuint(cv{i}_0) & 0xffffu);") + vector[dst] = ("low16", f"alu{i}") elif m := match(rf"v_({'|'.join(DPP_INT32)})_dpp (v\d+), (.+)"): op, dst, rest = m.groups() arity, template, helper = DPP_INT32[op] From ab17a5c319d1f56b0c6fb20be96ce2bfb6186b45 Mon Sep 17 00:00:00 2001 From: Louis <59670693+louisdibiasi@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:16:58 -0500 Subject: [PATCH 104/232] tooling: report unreadable layouts in verify_build (#2471) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/layout_chunks_check.py | 22 ++++++++++++++++++++++ tools/verify_build.py | 6 +++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/tests/layout_chunks_check.py b/tests/layout_chunks_check.py index 39e271857..f4b9790b7 100644 --- a/tests/layout_chunks_check.py +++ b/tests/layout_chunks_check.py @@ -51,6 +51,7 @@ def main(): assert chunks["3009"]["absent_from_disk"] == [], chunks check_layout_destination_paths() check_unreadable_torrent_is_a_usage_error() + check_unreadable_layout_is_a_usage_error() check_decode_torrent() check_manifest_selection() check_inventory_layout_selection() @@ -115,6 +116,27 @@ def check_unreadable_torrent_is_a_usage_error() -> None: assert run.returncode == 2 and "Traceback" not in run.stderr, run.stderr +def check_unreadable_layout_is_a_usage_error() -> None: + torrent = (b"d4:infod5:filesld6:lengthi0e4:pathl1:aeee" + b"12:piece lengthi16384e6:pieces0:ee") + for layout in ("", "", + ''): + with tempfile.TemporaryDirectory() as directory: + package = Path(directory) / "package" + package.mkdir() + (package / "layout.xml").write_text(layout, encoding="utf-8") + (package / "payload.torrent").write_bytes(torrent) + report = Path(directory) / "report.json" + run = subprocess.run( + [sys.executable, "-B", str(PROJECT / "tools/verify_build.py"), + str(package), "--output", str(report)], + capture_output=True, text=True, + ) + assert run.returncode == 2, (layout, run.returncode, run.stderr) + assert "layout.xml" in run.stderr and "Traceback" not in run.stderr, run.stderr + assert not report.exists(), layout + + def check_manifest_selection() -> None: for pattern, files, count in ( ("*.torrent", ["layout.xml"], 0), diff --git a/tools/verify_build.py b/tools/verify_build.py index 0d898a54f..3d319607e 100644 --- a/tools/verify_build.py +++ b/tools/verify_build.py @@ -219,13 +219,17 @@ def manifest(pattern: str) -> Path: missing = sorted(payload - sizes.keys()) wrong_size = [row | {"disk_bytes": sizes[row["path"]]} for row in entries if row["path"] in sizes and sizes[row["path"]] != row["bytes"]] + try: + layout_report = compare_layout(layout, payload, sizes.keys()) + except (OSError, ET.ParseError, KeyError) as exc: + parser.error(f"{layout.name!a} is not a readable layout: {type(exc).__name__}: {exc!a}") report = { "started_utc": start.isoformat(), "directory": root.name, "torrent": torrent.name, "torrent_sha256": hashlib.sha256(raw).hexdigest(), "payload_bytes": sum(row["bytes"] for row in entries), "payload_count": len(entries), "disk_file_count": len(sizes), "missing": missing, "size_mismatches": wrong_size, "extra_disk_files": sorted(sizes.keys() - payload), - "layout": compare_layout(layout, payload, sizes.keys()), "torrent_order": entries, + "layout": layout_report, "torrent_order": entries, } print(json.dumps({k: report[k] for k in ("payload_count", "payload_bytes", "missing", "size_mismatches", "layout")}), flush=True) try: From 32a2e2f6f694d839d29baeb6c6aeb94d16690f6d Mon Sep 17 00:00:00 2001 From: Maledetto Date: Wed, 25 Nov 2026 20:18:20 +0100 Subject: [PATCH 105/232] shader: lower flat_load_dwordx4 and global_load_dwordx4 through TitleLookup in pixel_aot (#2419) Refs #319 Co-authored-by: Maledetto <20729264+Makto94@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 6 +- tests/pixel_aot_check.py | 263 ++++++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 46 +++++-- 3 files changed, 296 insertions(+), 19 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 586ca73a0..3c1cb8c51 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -8001,9 +8001,11 @@ Not established: why the driver compiler selects mode 14 for this shape; the `an A case file may carry a trailer after the 64 expected colors: one flags byte, whose bit 0 selects a `R32G32B32A32_UINT` readback target, followed by 64 per-texel mask bytes whose bit ch accepts a NaN of any sign or payload on that channel. A masked channel passes when the expected word and the exported word are both NaN, and the renderer logs a `nan_class` line with both raw words even on pass; masking a channel whose expected word is not NaN is a case-format error. Unmasked channels stay strict bitwise, comparison-predicate results stay strict, and integer moves, bit operations and bitcasts round-trip bit-for-bit through the integer readback. Any normalization observed on the float render target is specific to that path. The fixtures never claim a payload, sign or quieting rule for NaN results, only the class. -`flat_load_dword` and the `off` form of `global_load_dword` (issue #319) read one DWORD through a 64-bit title address with `TitleLookup` from `src/title_va_lookup.hlsli`, which `lower()` inlines when a program loads through it. The address is the VGPR pair plus the instruction offset, sign-extended to 64 bits with the carry or borrow taken into the high word. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned (0 to 2047) and global offsets as 12-bit signed, so a negative offset is only a global load; the flat encodings with bit 11 set, which LLVM prints as offsets 2048 to 4095, are refused. The range table is a `StructuredBuffer` at `t0, space1` and the aliased buffers are `ByteAddressBuffer TitleAliases[8]` at `t1, space1`, indexed with `NonUniformResourceIndex`, on the same `ps_6_0`-compatible path as `tests/gpu_alias_lookup.hlsl`. The range count is fixed at translation time (`lower(..., title_ranges=N)`); without it both forms are refused. Flat loads additionally require `flat_global_only=True`. The caller guarantees that all effective flat addresses name global memory and exclude the scratch and LDS apertures. An address in no range, a DWORD that does not lie inside a single range, a misaligned address and a slot past the eighth all read `0xdeadbeef`, never zero. The word is ready after a `vmcnt` wait that covers it, counted in issue order with image samples. The x3 and x4 loads, sub-DWORD loads, D16 loads, stores, atomics, scratch, the global `saddr` and `lds` forms and cache-policy bits stay refused, each by a control, and the scratch-base writes still translate as no-ops before a flat load. The source-built program reads addresses A and B from constant words 3 to 6 and exports A, A + 2044, B - 2048 and B through the `R32G32B32A32_UINT` target. Six cases cover the first and last whole DWORD of a range, a carry and a borrow across the 32-bit boundary, misses in a hole and below the first range, a DWORD straddling a range end, and four ranges in four slots, two of them adjacent. The address words include quiet-NaN and subnormal patterns, which reach the lookup only through bit copies, as in the integer readback draw. Eight wrong references must report `pixel_mismatch`: the high address word dropped, the immediate ignored, the immediate masked instead of sign-extended, the carry dropped, zero instead of the sentinel, a straddling DWORD accepted, the slot masked to one bit and the range count one short. Each is followed by a passing draw, and the 22 draws run in one `--check-pixel-batch` process. The case trailer's flag bit 2 carries the ranges and the eight slot buffers; the renderer then binds them after the two textures with a root signature that extends the vertex shader's. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_title_loads_(warp|hardware)$' -V`; the LLVM 15 round trip covers the program. The draws show what the translated shader reads from the bound ranges on a desktop GPU, not how the console resolves flat apertures. +`flat_load_dword` and the `off` form of `global_load_dword` (issue #319) read one DWORD through a 64-bit title address with `TitleLookup` from `src/title_va_lookup.hlsli`, which `lower()` inlines when a program loads through it. The address is the VGPR pair plus the instruction offset, sign-extended to 64 bits with the carry or borrow taken into the high word. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned (0 to 2047) and global offsets as 12-bit signed, so a negative offset is only a global load; the flat encodings with bit 11 set, which LLVM prints as offsets 2048 to 4095, are refused. The range table is a `StructuredBuffer` at `t0, space1` and the aliased buffers are `ByteAddressBuffer TitleAliases[8]` at `t1, space1`, indexed with `NonUniformResourceIndex`, on the same `ps_6_0`-compatible path as `tests/gpu_alias_lookup.hlsl`. The range count is fixed at translation time (`lower(..., title_ranges=N)`); without it both forms are refused. Flat loads additionally require `flat_global_only=True`. The caller guarantees that all effective flat addresses name global memory and exclude the scratch and LDS apertures. An address in no range, a DWORD that does not lie inside a single range, a misaligned address and a slot past the eighth all read `0xdeadbeef`, never zero. The word is ready after a `vmcnt` wait that covers it, counted in issue order with image samples. The x3 load, sub-DWORD loads, D16 loads, stores, atomics, scratch, the global `saddr` and `lds` forms and cache-policy bits stay refused, each by a control, and the scratch-base writes still translate as no-ops before a flat load. The source-built program reads addresses A and B from constant words 3 to 6 and exports A, A + 2044, B - 2048 and B through the `R32G32B32A32_UINT` target. Six cases cover the first and last whole DWORD of a range, a carry and a borrow across the 32-bit boundary, misses in a hole and below the first range, a DWORD straddling a range end, and four ranges in four slots, two of them adjacent. The address words include quiet-NaN and subnormal patterns, which reach the lookup only through bit copies, as in the integer readback draw. Eight wrong references must report `pixel_mismatch`: the high address word dropped, the immediate ignored, the immediate masked instead of sign-extended, the carry dropped, zero instead of the sentinel, a straddling DWORD accepted, the slot masked to one bit and the range count one short. Each is followed by a passing draw, and the 22 draws run in one `--check-pixel-batch` process. The case trailer's flag bit 2 carries the ranges and the eight slot buffers; the renderer then binds them after the two textures with a root signature that extends the vertex shader's. Run `ctest --preset dev --no-tests=error -R '^pixel_aot_title_loads_(warp|hardware)$' -V`; the LLVM 15 round trip covers the program. The draws show what the translated shader reads from the bound ranges on a desktop GPU, not how the console resolves flat apertures. -`flat_load_dwordx2 v[d:d+1], v[a:a+1]` and the `off` form of `global_load_dwordx2` (issue #319) take the same address, offset ranges and profile as the DWORD loads and look up 8 bytes at once: `TitleLookup(..., 8, ...)` and `Load2` on the aliased buffer. Both destination words are ready after the same `vmcnt` wait, and each blocks a reuse of its register until then. A QWORD that does not lie inside one range reads `0xdeadbeef` in both words, including a QWORD that starts in one range and ends in the adjacent one, because `TitleLookup` succeeds only when the whole access lies inside one range; the translation does not split such a load. The helper is emitted only when a program uses it, so DWORD-only translations are unchanged. The source-built program reads the QWORDs at A + 2040 (flat) and B - 2048 (global) into channels 0 to 3. Seven cases cover a hit in two slots, the last QWORD of two ranges, a QWORD across the adjacent ranges at `0x2_0000_1000` and one across the end of a range, two misses, a QWORD across the 32-bit boundary inside one range, a QWORD across a range end into a hole, and a negative offset that borrows across the low 32 bits with the QWORD crossing 2^32 inside one range. Four wrong references must report `pixel_mismatch`: the two words swapped, a 4-byte lookup, the range accepted for the first word only (a hit in word 0 and a miss in word 1), and a separate lookup for each word. Each is followed by a passing draw; the 15 draws run in a second `--check-pixel-batch` process of the same `pixel_aot_title_loads_(warp|hardware)` test. The `x3` and `x4` widths, `glc`, `slc` and `dlc`, `saddr`, `lds`, sub-DWORD widths, stores, atomics and scratch stay refused by controls. +`flat_load_dwordx2 v[d:d+1], v[a:a+1]` and the `off` form of `global_load_dwordx2` (issue #319) take the same address, offset ranges and profile as the DWORD loads and look up 8 bytes at once: `TitleLookup(..., 8, ...)` and `Load2` on the aliased buffer. Both destination words are ready after the same `vmcnt` wait, and each blocks a reuse of its register until then. A QWORD that does not lie inside one range reads `0xdeadbeef` in both words, including a QWORD that starts in one range and ends in the adjacent one, because `TitleLookup` succeeds only when the whole access lies inside one range; the translation does not split such a load. The helper is emitted only when a program uses it, so DWORD-only translations are unchanged. The source-built program reads the QWORDs at A + 2040 (flat) and B - 2048 (global) into channels 0 to 3. Seven cases cover a hit in two slots, the last QWORD of two ranges, a QWORD across the adjacent ranges at `0x2_0000_1000` and one across the end of a range, two misses, a QWORD across the 32-bit boundary inside one range, a QWORD across a range end into a hole, and a negative offset that borrows across the low 32 bits with the QWORD crossing 2^32 inside one range. Four wrong references must report `pixel_mismatch`: the two words swapped, a 4-byte lookup, the range accepted for the first word only (a hit in word 0 and a miss in word 1), and a separate lookup for each word. Each is followed by a passing draw; the 15 draws run in a second `--check-pixel-batch` process of the same `pixel_aot_title_loads_(warp|hardware)` test. The `x3` width, `glc`, `slc` and `dlc`, `saddr`, `lds`, sub-DWORD widths, stores, atomics and scratch stay refused by controls. + +`flat_load_dwordx4 v[d:d+3], v[a:a+1]` and the `off` form of `global_load_dwordx4` (issue #319) take the same address, offset ranges and profile as the DWORD and QWORD loads and look up 16 bytes at once: `TitleLookup(..., 16, ...)` and `Load4` on the aliased buffer. The four destination words are ready after the same `vmcnt` wait, the load counts once in `vmcnt`, and each of the four registers blocks a reuse until then. An access that does not lie inside one range reads `0xdeadbeef` in all four words, including one that starts in one range and ends in the adjacent one after one, two or three words, because `TitleLookup` succeeds only when the whole access lies inside one range; the translation does not split such a load. The helper is emitted only when a program uses it, so DWORD-only and QWORD translations are unchanged. Three source-built programs, one flat at A + 2032, one global at B - 2048 and one flat with no offset at A, read the four words of one load into channels 0 to 3. Ten cases run through each; the program with no offset makes the low-word add of the helper add zero, so a carry test that is true on equality would fail it: the first and the last 16 bytes of a range, the last 16 bytes of the last range, an access across the adjacent ranges at `0x2_0000_1000` after one, two and three words, a range that ends inside the access, a hole between ranges, a positive flat offset that carries through the low 32 bits with the access inside one range, and a negative global offset that borrows through the low 32 bits with the access across 2^32 inside one range. Four wrong references must report `pixel_mismatch`: the four words reversed, an 8-byte lookup, the words accepted up to the end of the first range (a hit in the first words and a miss in the rest), and a separate lookup for each word. Each is followed by a passing draw; the 18 draws of each of the three programs run in their own `--check-pixel-batch` process of the same `pixel_aot_title_loads_(warp|hardware)` test. The x4 width extends the rule that the comment of 2026-11-25 on #319 states for two words; the `x3` width, `glc`, `slc` and `dlc`, `saddr`, `lds`, sub-DWORD widths, stores, atomics and scratch stay refused by controls. `v_fmaak_f32` computes S0 × S1 + K and `v_fmamk_f32` computes S0 × K + S1, where K is the 32-bit literal that LLVM prints in that position. Both use the `v_fma_f32` lowering; the translator refuses a register where the literal belongs. The draw computes each instruction twice with inputs 1.5, 2.5, -3.0 and 0.75 and the literals 0.25, 3.0, -0.5 and 0.5. Every product and sum is exact in binary32, so the reference does not depend on fusion. A reference that swaps the literal with S1 must report a mismatch in each channel. diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 4f9af6656..c7f8a45ba 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -19682,6 +19682,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.extend((uncompressed_export(nc_integer_group(group)), translate_int) for group in (1, 2, 3)) fixtures.append((title_program(), translate_title)) fixtures.append((uncompressed_export(TITLE_X2_BODY), translate_title)) + fixtures.extend((uncompressed_export(body), translate_title) for body in TITLE_X4_BODIES.values()) fixtures.append((uncompressed_export(CVT_FLOAT_E64_PLAIN_BODY), translate_int)) fixtures.append((uncompressed_export(CVT_FLOAT_E64_U32_MOD_BODY), translate_int)) fixtures.append((uncompressed_export(CVT_FLOAT_E64_I32_MOD_BODY), translate_int)) @@ -21124,6 +21125,110 @@ def title_x2_controls(): assert title_x2_words(TITLE_X2_CASES[2], "first")[:2] == (title_word(0, 0x3ff), pixel_aot.TITLE_MISS) +# flat_load_dwordx4 and global_load_dwordx4 look up all 16 bytes: the four words come from one range or all read +# TITLE_MISS. An access across two adjacent ranges is a miss, as for the QWORD. One program per form; its four +# channels are the four words of one load, at A + 2032 (flat), B - 2048 (global) or, with no offset, at A (flat0): the +# low-word add of the helper then adds zero, and a carry test that is true on equality would add one to the high word. +TITLE_X4_BODIES = { + "flat": [ + "v_mov_b32_e32 v20, s44", + "v_mov_b32_e32 v21, s45", + "v_mov_b32_e32 v22, s46", + "v_mov_b32_e32 v23, s47", + "flat_load_dwordx4 v[12:15], v[20:21] offset:2032", + "s_waitcnt vmcnt(0) lgkmcnt(0)", + ], + "global": [ + "v_mov_b32_e32 v20, s44", + "v_mov_b32_e32 v21, s45", + "v_mov_b32_e32 v22, s46", + "v_mov_b32_e32 v23, s47", + "global_load_dwordx4 v[12:15], v[22:23], off offset:-2048", + "s_waitcnt vmcnt(0) lgkmcnt(0)", + ], + "flat0": [ + "v_mov_b32_e32 v20, s44", + "v_mov_b32_e32 v21, s45", + "v_mov_b32_e32 v22, s46", + "v_mov_b32_e32 v23, s47", + "flat_load_dwordx4 v[12:15], v[20:21]", + "s_waitcnt vmcnt(0) lgkmcnt(0)", + ], +} +TITLE_X4_OFFSETS = {"flat": 2032, "global": -2048, "flat0": 0} +TITLE_X4_CASES = ( # effective addresses of the 16 bytes, run through both programs + 0x2_0000_0000, # the first 16 bytes of a range + 0x2_0000_0ff0, # the last 16 bytes of a range + 0x2_0000_1ff0, # the last 16 bytes of the last range, in another slot + 0x2_0000_0ffc, # across the adjacent ranges at 0x2_0000_1000, after one word + 0x2_0000_0ff8, # after two words + 0x2_0000_0ff4, # after three words + 0x0_0010_00f8, # a range shorter than the access: two DWORDs inside it, the range ends inside the third + 0x1_8000_0000, # a hole between ranges + 0x1_0000_01fc, # flat: A + 2032 carries through the low 32 bits; all 16 bytes inside one range + 0x0_ffff_fffc, # global: B - 2048 borrows through the low 32 bits; the 16 bytes cross 2^32 inside one range +) +# Wrong references, each with the (case, channel) it changes: the four words reversed, an 8-byte lookup instead of 16, +# the words accepted up to the end of the first range, and a separate lookup for each word. +TITLE_X4_MUTATIONS = {"swap": (0, 0), "narrow": (4, 0), "prefix": (4, 0), "separate": (3, 1)} + + +def title_x4_reference(address, mutation=None): + """The four words a 16-byte load at address returns; mutation names one wrong reference.""" + def hit(where, width): + for begin, end, slot in TITLE_RANGES: + if where % 4 == 0 and begin <= where and where + width <= end: + return slot, (where - begin) // 4 + return None + + miss = [pixel_aot.TITLE_MISS] * 4 + whole = hit(address, 8 if mutation == "narrow" else 16) + words = [title_word(whole[0], whole[1] + k) for k in range(4)] if whole else miss + if mutation == "swap": + words.reverse() + if mutation == "prefix": + first = hit(address, 4) + same = [hit(address + 4 * k, 4) for k in range(4)] + words = [title_word(first[0], first[1] + k) if first and same[k] and same[k][0] == first[0] + else pixel_aot.TITLE_MISS for k in range(4)] + if mutation == "separate": + words = [title_word(*word) if (word := hit(address + 4 * k, 4)) else pixel_aot.TITLE_MISS for k in range(4)] + return tuple(words) + + +def title_x4_constants(segment, address): + """The (A, B) constants that put the 16 bytes of the segment's program at address.""" + base = address - TITLE_X4_OFFSETS[segment] + return (0, base) if segment == "global" else (base, 0) + + +def title_x4_controls(): + """Check that the cases cover a hit, a miss and the straddles, and that each mutation changes its channel.""" + expected = [title_x4_reference(address) for address in TITLE_X4_CASES] + for address in TITLE_X4_CASES: + assert address % 4 == 0 and address >= 0x800 and address < 1 << 64 + miss = (pixel_aot.TITLE_MISS,) * 4 + assert expected[0] == tuple(title_word(0, k) for k in range(4)) + assert expected[1] == tuple(title_word(0, 0x3fc + k) for k in range(4)) + assert expected[2] == tuple(title_word(3, 0x3fc + k) for k in range(4)) + assert expected[3] == expected[4] == expected[5] == expected[6] == expected[7] == miss + assert expected[8] == tuple(title_word(2, 0x27f + k) for k in range(4)) + assert expected[9] == tuple(title_word(2, 0x1ff + k) for k in range(4)) + assert TITLE_X4_OFFSETS["flat0"] == 0 and title_x4_constants("flat0", TITLE_X4_CASES[0])[0] == TITLE_X4_CASES[0] + # The carry and the borrow really happen: A + 2032 overflows the low word, and B - 2048 underflows it. + a, _ = title_x4_constants("flat", TITLE_X4_CASES[8]) + _, b = title_x4_constants("global", TITLE_X4_CASES[9]) + assert (a & 0xffffffff) + TITLE_X4_OFFSETS["flat"] > 0xffffffff + assert (b & 0xffffffff) + TITLE_X4_OFFSETS["global"] < 0 + for mutation, (index, channel) in TITLE_X4_MUTATIONS.items(): + assert title_x4_reference(TITLE_X4_CASES[index], mutation)[channel] != expected[index][channel], mutation + # The words before a straddle are hits for the prefix and for the separate lookup, and all misses for the load. + assert title_x4_reference(TITLE_X4_CASES[4], "prefix") == (title_word(0, 0x3fe), title_word(0, 0x3ff)) + miss[:2] + assert title_x4_reference(TITLE_X4_CASES[3], "separate") == (title_word(0, 0x3ff), title_word(3, 0), title_word(3, 1), + title_word(3, 2)) + assert title_x4_reference(TITLE_X4_CASES[6], "prefix") == (title_word(1, 0x3e), title_word(1, 0x3f)) + miss[:2] + + def translate_title(instructions): """translate_int() with the TITLE_RANGES table bound for flat and global loads.""" return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, @@ -21171,14 +21276,14 @@ def replaced(line): return [line if entry == flat else entry for entry in program] # Wider and narrower neighbours, cache-policy bits, saddr, LDS and out-of-range offsets stay refused. - for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", "flat_load_dwordx4 v[12:15], v[20:21]", + for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", "flat_load_dwordx2 v[12:13], v[20:21] glc", "flat_load_dwordx2 v[12:13], v[20:21] slc", "flat_load_dwordx2 v[12:13], v[20:21] offset:8 glc slc dlc", "flat_load_dwordx2 v[12:13], v[20:21] dlc", "global_load_dwordx2 v[12:13], v[20:21], off glc", "global_load_dwordx2 v[12:13], v[20:21], off slc", "global_load_dwordx2 v[12:13], v[20:21], off dlc", "global_load_dwordx2 v[12:13], v20, s[44:45]", "global_load_dwordx2 v[12:13], v20, s[44:45] offset:-8", "global_load_dwordx2 v[12:13], v[20:21], off lds", "global_load_dwordx3 v[12:14], v[20:21], off", - "global_load_dwordx4 v[12:15], v[20:21], off", "flat_load_ubyte v12, v[20:21]", "flat_load_sshort v12, v[20:21]", + "flat_load_ubyte v12, v[20:21]", "flat_load_sshort v12, v[20:21]", "flat_load_short_d16 v12, v[20:21]", "global_load_ubyte v12, v[20:21], off", "flat_store_dwordx2 v[20:21], v[12:13]", "global_store_dwordx2 v[20:21], v[12:13], off", "flat_atomic_add_x2 v[12:13], v[20:21], v[14:15] glc", @@ -21227,8 +21332,142 @@ def replaced(line): "Sample used before vmcnt wait") +def check_title_load_x4_controls(): + title_x4_controls() + flat_program = uncompressed_export(TITLE_X4_BODIES["flat"]) + global_program = uncompressed_export(TITLE_X4_BODIES["global"]) + x2_program = uncompressed_export(TITLE_X2_BODY) + + def helper(template): + return template.format(slots=pixel_aot.TITLE_ALIAS_SLOTS, count=len(TITLE_RANGES), miss=pixel_aot.TITLE_MISS) + + source = translate_title(flat_program) + assert source.count("bool TitleLookup(") == 1 and source.count("uint4 title_load_dwordx4(") == 1 + assert "address, 16, slot, byteOffset" in source and ".Load4(byteOffset)" in source + assert source.count("title_load_dwordx4(uint2(") == 1 and "title_load_dword(uint2(" not in source + assert "uint2(0x7f0u, 0x0u)" in source + # Word k of the load is channel k of the export, in order. + assert re.search(r"title(\d+)\.x\);\s+precise float alu\1y = asfloat\(title\1\.y\);\s+precise float alu\1z = " + r"asfloat\(title\1\.z\);\s+precise float alu\1w = asfloat\(title\1\.w\);\s+" + r"return uint4\(asuint\(alu\1x\), asuint\(alu\1y\), asuint\(alu\1z\), asuint\(alu\1w\)\);", source) + global_source = translate_title(global_program) + assert global_source.count("title_load_dwordx4(uint2(") == 1 and "uint2(0xfffff800u, 0xffffffffu)" in global_source + # A helper is emitted only for the widths a program uses, so DWORD and QWORD translations do not change. + wide = {2: helper(pixel_aot.TITLE_MEMORY_X2), 4: helper(pixel_aot.TITLE_MEMORY_X4)} + dword_source = translate_title(title_program()) + assert helper(pixel_aot.TITLE_MEMORY) in dword_source and not any(text in dword_source for text in wide.values()) + x2_source = translate_title(x2_program) + assert wide[2] in x2_source and wide[4] not in x2_source and "Load4" not in x2_source + assert wide[4] in source and wide[2] not in source and "Load2" not in source + mixed = uncompressed_export(TITLE_X4_BODIES["flat"][:-1] + ["global_load_dwordx2 v[16:17], v[22:23], off", + TITLE_X4_BODIES["flat"][-1]]) + mixed_source = translate_title(mixed) + assert mixed_source.count(wide[2]) == mixed_source.count(wide[4]) == mixed_source.count("bool TitleLookup(") == 1 + # Both forms need the same profile and range table as the DWORD loads. + expect_value_error(translate_int, flat_program, "Title memory is not bound") + expect_value_error(translate_int, global_program, "Title memory is not bound") + + def without_flat_binding(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, + integer_export=True, title_ranges=len(TITLE_RANGES)) + + expect_value_error(without_flat_binding, flat_program, "Flat loads require the global-only address profile") + assert without_flat_binding(global_program).count("title_load_dwordx4(uint2(") == 1 + flat = "flat_load_dwordx4 v[12:15], v[20:21] offset:2032" + start = flat_program.index(flat) + wait = flat_program.index("s_waitcnt vmcnt(0) lgkmcnt(0)") + + def replaced(line): + return [line if entry == flat else entry for entry in flat_program] + + # The x3 width, cache-policy bits, saddr, LDS, other directions and narrower neighbours stay refused. + for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", "flat_load_dwordx3 v[12:14], v[20:21] offset:16", + "global_load_dwordx3 v[12:14], v[20:21], off", "global_load_dwordx3 v[12:14], v[20:21], off offset:16", + "flat_load_dwordx4 v[12:15], v[20:21] glc", "flat_load_dwordx4 v[12:15], v[20:21] slc", + "flat_load_dwordx4 v[12:15], v[20:21] offset:16 glc slc dlc", "flat_load_dwordx4 v[12:15], v[20:21] dlc", + "global_load_dwordx4 v[12:15], v[20:21], off glc", "global_load_dwordx4 v[12:15], v[20:21], off slc", + "global_load_dwordx4 v[12:15], v[20:21], off dlc", "global_load_dwordx4 v[12:15], v20, s[44:45]", + "global_load_dwordx4 v[12:15], v20, s[44:45] offset:-8", + "global_load_dwordx4 v[12:15], v[20:21], off lds", "flat_load_ubyte v12, v[20:21]", + "flat_load_short_d16 v12, v[20:21]", "global_load_sbyte v12, v[20:21], off", + "flat_store_dwordx4 v[20:21], v[12:15]", "global_store_dwordx4 v[20:21], v[12:15], off", + "scratch_load_dwordx4 v[12:15], v20, off", "scratch_load_dwordx4 v[12:15], off, s48", + "scratch_store_dwordx4 off, v[12:15], s48 offset:16"): + expect_value_error(translate_title, replaced(neighbour), "Unsupported instruction") + # The address form and the offset range of each segment, and a destination of the wrong width for the mnemonic. + for form in ("flat_load_dwordx4 v12, v[20:21]", "flat_load_dword v[12:15], v[20:21]", + "global_load_dword v[12:15], v[20:21], off", "flat_load_dwordx4 v[12:15], v[20:21] offset:2048", + "flat_load_dwordx4 v[12:15], v[20:21] offset:-16", "flat_load_dwordx4 v[12:15], v[20:21], off", + "global_load_dwordx4 v[12:15], v[20:21]", "global_load_dwordx4 v[12:15], v[20:21], off offset:2048", + "global_load_dwordx4 v[12:15], v[20:21], off offset:-2049"): + expect_value_error(translate_title, replaced(form), "load form") + for width in ("flat_load_dwordx4 v[12:13], v[20:21]", "flat_load_dwordx4 v[12:14], v[20:21]", + "flat_load_dwordx4 v[12:16], v[20:21]", "flat_load_dwordx2 v[12:15], v[20:21]", + "global_load_dwordx4 v[12:13], v[20:21], off", "global_load_dwordx2 v[12:15], v[20:21], off"): + expect_value_error(translate_title, replaced(width), "width mismatch") + must_reject(translate_title, replaced("flat_load_dwordx4 v[12:15], v[20:22]")) + must_reject(translate_title, replaced("flat_load_dwordx4 v[12:15], v[24:25]")) # address never written + wqm = flat_program.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(translate_title, flat_program[:wqm] + [flat] + flat_program[wqm:], "Invalid title memory load") + # The last four VGPRs are a valid destination in both segments; one register further is not. + for edge in ("flat_load_dwordx4 v[252:255], v[20:21]", "global_load_dwordx4 v[252:255], v[22:23], off"): + edge_program = flat_program[:wait + 1] + [edge, "s_waitcnt vmcnt(0)"] + flat_program[wait + 1:] + assert translate_title(edge_program).count("title_load_dwordx4(uint2(") == 2 + for edge in ("flat_load_dwordx4 v[253:256], v[20:21]", "global_load_dwordx4 v[253:256], v[22:23], off", + "flat_load_dwordx4 v[255:258], v[20:21]"): + edge_program = flat_program[:wait + 1] + [edge, "s_waitcnt vmcnt(0)"] + flat_program[wait + 1:] + expect_value_error(translate_title, edge_program, "Invalid title memory load") + # All four words are ready only after vmcnt covers the load. + for replacement in ([], ["s_waitcnt lgkmcnt(0)"], ["s_waitcnt vmcnt(1)"]): + must_reject(translate_title, flat_program[:wait] + replacement + flat_program[wait + 1:]) + assert translate_title(flat_program[:wait] + ["s_waitcnt vmcnt(0)"] + flat_program[wait + 1:]) == source + for register in range(12, 16): + expect_value_error(translate_title, flat_program[:wait] + [f"v_add_f32_e32 v16, v{register}, v{register}"] + + flat_program[wait:], "Sample used before vmcnt wait") + # Each destination register in flight blocks a second load, whatever width and position the second one has. + for low in range(9, 16): + expect_value_error(translate_title, flat_program[:wait] + [f"flat_load_dwordx4 v[{low}:{low + 3}], v[20:21]"] + + flat_program[wait:], "Invalid title memory load") + for register in range(12, 16): + expect_value_error(translate_title, flat_program[:wait] + [f"flat_load_dword v{register}, v[20:21]"] + + flat_program[wait:], "Invalid title memory load") + expect_value_error(translate_title, flat_program[:start] + [f"flat_load_dword v{register}, v[20:21]"] + + flat_program[start:], "Invalid title memory load") + for pair in ("v[11:12]", "v[13:14]", "v[15:16]"): + expect_value_error(translate_title, flat_program[:wait] + [f"flat_load_dwordx2 {pair}, v[20:21]"] + + flat_program[wait:], "Invalid title memory load") + # The groups next to the destination are free, and a covered load can be loaded over again. + for low in (8, 16): + free = flat_program[:wait] + [f"flat_load_dwordx4 v[{low}:{low + 3}], v[20:21]"] + flat_program[wait:] + assert translate_title(free).count("title_load_dwordx4(uint2(") == 2 + loaded = flat_program[:wait + 1] + ["flat_load_dwordx4 v[16:19], v[12:13]", "s_waitcnt vmcnt(0)"] + flat_program[wait + 1:] + assert translate_title(loaded).count("title_load_dwordx4(uint2(") == 2 + # A load counts once in vmcnt, not once per word: after vmcnt(1) the older load is ready and the newer is not. + older = flat_program[:wait] + ["flat_load_dwordx4 v[16:19], v[20:21]", "s_waitcnt vmcnt(1)"] + tail = flat_program[wait + 1:] + assert translate_title(older + ["v_add_f32_e32 v24, v12, v15"] + tail).count("title_load_dwordx4(uint2(") == 2 + for register in range(16, 20): + expect_value_error(translate_title, older + [f"v_add_f32_e32 v24, v{register}, v{register}"] + tail, + "Sample used before vmcnt wait") + # Three loads, vmcnt(2): only the oldest is ready, which a count per word would not give. + three = flat_program[:wait] + ["flat_load_dwordx4 v[16:19], v[20:21]", "flat_load_dwordx4 v[28:31], v[20:21]", + "s_waitcnt vmcnt(2)"] + assert translate_title(three + ["v_add_f32_e32 v24, v12, v15"] + tail).count("title_load_dwordx4(uint2(") == 3 + for register in (16, 19, 28, 31): + expect_value_error(translate_title, three + [f"v_add_f32_e32 v24, v{register}, v{register}"] + tail, + "Sample used before vmcnt wait") + # With a DWORD load before the x4 load, vmcnt(1) covers only the DWORD. + partial = flat_program[:start] + ["flat_load_dword v10, v[20:21]", flat, "s_waitcnt vmcnt(1)"] + tail = flat_program[start + 1:] + assert translate_title(partial + ["v_add_f32_e32 v16, v10, v10"] + tail).count("title_load_dword(uint2(") == 1 + for register in range(12, 16): + expect_value_error(translate_title, partial + [f"v_add_f32_e32 v16, v{register}, v{register}"] + tail, + "Sample used before vmcnt wait") + + def check_title_load_controls(): check_title_load_x2_controls() + check_title_load_x4_controls() title_controls() program = title_program() source = translate_title(program) @@ -21259,8 +21498,7 @@ def replaced(line): # Neighbours that stay unsupported: other widths, sub-DWORD and D16 loads, stores, atomics, scratch, the # global saddr and LDS forms, cache-policy bits, and offsets outside each segment's assembler range. - for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", - "flat_load_dwordx4 v[12:15], v[20:21]", "flat_load_ubyte v12, v[20:21]", + for neighbour in ("flat_load_dwordx3 v[12:14], v[20:21]", "flat_load_ubyte v12, v[20:21]", "flat_load_sbyte v12, v[20:21]", "flat_load_ushort v12, v[20:21]", "flat_load_sshort v12, v[20:21]", "flat_load_short_d16 v12, v[20:21]", "flat_load_short_d16_hi v12, v[20:21]", "flat_store_dword v[20:21], v12", @@ -21333,6 +21571,23 @@ def case_x2(name, addresses, words): addresses = TITLE_X2_CASES[index] cases += [(case_x2(mutation, addresses, title_x2_words(addresses, mutation)), "mismatch"), cases[index]] run_pixel_batch(renderer, backend, shader, cases) + # The 16-byte loads: one shader and one batch of 18 draws for each program. + title_x4_controls() + for segment, body in TITLE_X4_BODIES.items(): + source = directory / f"title_loads_x4_{segment}.hlsl" + shader = directory / f"title_loads_x4_{segment}.cso" + source.write_text(translate_title(uncompressed_export(body)), encoding="ascii") + compile_shader(compiler, source, shader) + + def case_x4(name, address, words): + a, b = title_x4_constants(segment, address) + return case(f"x4_{segment}_{name}", a, b, words) + + cases = [(case_x4(n, address, title_x4_reference(address)), "pass") for n, address in enumerate(TITLE_X4_CASES)] + for mutation, (index, _) in TITLE_X4_MUTATIONS.items(): + address = TITLE_X4_CASES[index] + cases += [(case_x4(mutation, address, title_x4_reference(address, mutation)), "mismatch"), cases[index]] + run_pixel_batch(renderer, backend, shader, cases) return 0 diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index d88a24a2f..44b59a0f7 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -654,16 +654,17 @@ def vgpr_span(token, count): HALF_DENORM_PRESERVE = "preserve" # FLAT_SCR_LO and FLAT_SCR_HI hold the scratch base address. Only scratch_* and flat_* memory instructions and # s_getreg_b32 can observe it. scratch_* and s_getreg_b32 of these registers are not lowered, and the lowered flat -# forms, flat_load_dword and flat_load_dwordx2, read only through the title ranges below (no private aperture), -# so a whole-register write (an immediate or any SGPR value) changes no result. +# forms, flat_load_dword, flat_load_dwordx2 and flat_load_dwordx4, read only through the title ranges below (no +# private aperture), so a whole-register write (an immediate or any SGPR value) changes no result. FLAT_SCRATCH = ("HW_REG_FLAT_SCR_LO", "HW_REG_FLAT_SCR_HI") # flat_load_dword and global_load_dword with `off` read one DWORD at a 64-bit title address: the address pair # plus the instruction offset, sign-extended to 64 bits with the carry or borrow taken into the high word. # TitleLookup (src/title_va_lookup.hlsli) finds the range holding the whole DWORD; the load then reads that # range's aliased buffer at the byte offset. An address in no range, a DWORD that does not lie inside a single -# range and a misaligned address read TITLE_MISS instead of zero. The dwordx2 forms look up 8 bytes at once: both -# words read TITLE_MISS unless the whole QWORD lies inside one range, so a QWORD across two ranges is a miss. +# range and a misaligned address read TITLE_MISS instead of zero. The dwordx2 and dwordx4 forms look up 8 and 16 +# bytes at once: every word reads TITLE_MISS unless the whole access lies inside one range, so an access across two +# ranges is a miss. # The range count is fixed at translation time (lower(title_ranges=...)), and TITLE_ALIAS_SLOTS bounds the aliased # descriptors; a slot past it also reads TITLE_MISS. LLVM 15 assembles gfx1013 flat offsets as 11-bit unsigned # and global offsets as 12-bit signed. @@ -701,6 +702,20 @@ def vgpr_span(token, count): }} """ +TITLE_MEMORY_X4 = """// The 16 bytes at base + offset: all four words come from one range, or all read the miss word. +uint4 title_load_dwordx4(uint2 base, uint2 offset) +{{ + const uint low = base.x + offset.x; + const uint2 address = uint2(low, base.y + offset.y + (low < base.x ? 1u : 0u)); + uint slot; + uint byteOffset; + if (!TitleLookup(TitleRanges, TITLE_RANGE_COUNT, address, 16, slot, byteOffset) || slot >= {slots}u) {{ + return uint4({miss:#x}u, {miss:#x}u, {miss:#x}u, {miss:#x}u); + }} + return TitleAliases[NonUniformResourceIndex(slot)].Load4(byteOffset); +}} +""" + ALU = { "log": (1, "log2({0})"), "exp": (1, "exp2({0})"), "rcp": (1, "(1.0f / {0})"), # Same reciprocal; the integer-divide flag it raises has no desktop equivalent. @@ -3346,6 +3361,7 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= vector_loads = 0 # image samples and title loads issued, in vmcnt order title_loads = False title_loads_x2 = False + title_loads_x4 = False sample_dest = {} # VGPR -> issue number of its outstanding image_sample or title load ds_needs_wait = False exported = False @@ -4818,10 +4834,10 @@ def sample_coord(reg): for channel, n in zip("xy", dest): vector[f"v{n}"] = f"sample{i}.{channel}" sample_dest[f"v{n}"] = vector_loads - elif m := match(r"(flat|global)_load_dword(x2)? (?:(v\d+)|v\[(\d+):(\d+)\]), v\[(\d+):(\d+)\](, off)?" + elif m := match(r"(flat|global)_load_dword(x2|x4)? (?:(v\d+)|v\[(\d+):(\d+)\]), v\[(\d+):(\d+)\](, off)?" r"(?: offset:(-?\d+))?"): - # One DWORD, or with x2 one QWORD, through a 64-bit title address. Cache-policy bits, the global - # saddr form and every other width or direction are refused by the fall-through. + # One DWORD, with x2 one QWORD, with x4 16 bytes, through a 64-bit title address. Cache-policy bits, + # the global saddr form and every other width or direction are refused by the fall-through. segment, wide, single, dst_first, dst_last, first, last, off, imm = m.groups() if (wide is None) != (single is not None): raise ValueError(f"Unsupported {segment} load form") @@ -4832,7 +4848,7 @@ def sample_coord(reg): raise ValueError("Title memory is not bound") if segment == "flat" and not flat_global_only: raise ValueError("Flat loads require the global-only address profile") - dests = [single[1:]] if wide is None else registers(dst_first, dst_last, 2) + dests = [single[1:]] if wide is None else registers(dst_first, dst_last, int(wide[1:])) dests = [f"v{n}" for n in dests] if mask != "entry" or int(dests[-1][1:]) > 255 or int(last) > 255 or any(d in sample_dest for d in dests): raise ValueError("Invalid title memory load") @@ -4844,11 +4860,14 @@ def sample_coord(reg): lines.append(f" precise float alu{i} = asfloat(title_load_dword({arguments}));") values = [f"alu{i}"] else: - lines.append(f" const uint2 title{i} = title_load_dwordx2({arguments});") - lines.append(f" precise float alu{i}x = asfloat(title{i}.x);") - lines.append(f" precise float alu{i}y = asfloat(title{i}.y);") - values = [f"alu{i}x", f"alu{i}y"] - title_loads_x2 = True + count = int(wide[1:]) + lines.append(f" const uint{count} title{i} = title_load_dwordx{count}({arguments});") + values = [] + for component in "xyzw"[:count]: + lines.append(f" precise float alu{i}{component} = asfloat(title{i}.{component});") + values.append(f"alu{i}{component}") + title_loads_x2 |= count == 2 + title_loads_x4 |= count == 4 title_loads = True vector_loads += 1 for dst, value in zip(dests, values): @@ -6988,6 +7007,7 @@ def sample_coord(reg): if title_loads: lookup = (Path(__file__).resolve().parents[1] / "src/title_va_lookup.hlsli").read_text() memory = TITLE_MEMORY + (TITLE_MEMORY_X2 if title_loads_x2 else "") + memory += TITLE_MEMORY_X4 if title_loads_x4 else "" lines[:0] = [lookup, memory.format(slots=TITLE_ALIAS_SLOTS, count=title_ranges, miss=TITLE_MISS)] source = "\n".join([*lines, "}", ""]) return (source, channel_mask) if return_write_mask else source From 6d2d3bedda76596e31b39e70e25d68aa80e8e9a5 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:19:51 +0100 Subject: [PATCH 106/232] startup: translate slot 57 mesh requests of one group-memory shape (#2447) * startup: lower s_waitcnt_depctr as a wait without effect in gfx2hlsl LLVM defines S_WAITCNT_DEPCTR with one immediate and no register definition, use or side effect, and emits it only as a hazard delay. The translator now treats it like s_nop. A pure-Python check compares the translation with and without the wait for five immediates, keeps three neighbouring SOPP forms refused, and checks the encodings against llvm-mc. Refs #2413 Co-Authored-By: Claude Fable 5.2 * startup: translate slot 57 mesh requests of one group-memory shape A slot 57 mesh program exchanges its output counts through group memory: lane 0 of wave 0 stores them, every wave passes a barrier, wave 0 sends one allocation request and the other wave reads the counts back. mesh_skeleton proves that exact shape (one writer, the stores and reads at their literal addresses, the barriers, one request built from the two stored registers, branches that stay inside) and replaces it by one store, one GroupMemoryBarrierWithGroupSync and SetMeshOutputCounts. The code around it must be straight-line and export vertex and primitive `thread` under count > thread. Anything else is refused with the first difference. The request path writes .ms57.hlsl/.ps57.hlsl and their ms_6_5/ps_6_0 bytecode. No runtime path loads them. Refs #2413 Co-Authored-By: Claude Fable 5.2 * startup: slot 57 mesh review: null primitives, 9-bit indices, pinned refusals - The primitive export word holds 9-bit indices with an edge flag above each and the null bit 31. The lowering masked 10 bits and drew null primitives; it now masks 9 and gives a null primitive one vertex three times. - The destination of the wave test of the group-index exchange may not be the saved lane-0 mask. - A depth-only pixel stage is refused by name; the watch check expects it. - Controls for the overlap, wave-index and s_endpgm refusals. - The fixture reads the slot of a thread's low four bits, so a draw with all 128 threads stays inside the buffer: triangles on vertices 112..123, one null, one with its edge flags. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 7 + docs/experiments.md | 18 +- tests/startup_gfx2hlsl_watch_check.py | 6 +- tests/startup_mesh57_skeleton.s | 73 +++++ tests/startup_mesh57_skeleton_check.py | 306 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 379 ++++++++++++++++++++++++- 8 files changed, 776 insertions(+), 16 deletions(-) create mode 100644 tests/startup_mesh57_skeleton.s create mode 100644 tests/startup_mesh57_skeleton_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index a0229f0b0..5fb709690 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -82,6 +82,7 @@ jobs: (["tests/startup_sampler_heap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cmp16_check.py", "binary", "llvm-mc-15", "llvm-objcopy-15"], {}), @@ -240,6 +241,7 @@ jobs: tests/compute_container_index_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ + tests/startup_mesh57_skeleton_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2851ded0c..2af9edb75 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -182,6 +182,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a752d986e..4f6fa2722 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3077,6 +3077,9 @@ if(EXISTS "${INTAKE_PYTHON}") # s_waitcnt_depctr is a hazard delay without architectural effect: the translation is unchanged by it (#2413). add_test(NAME startup_gfx2hlsl_waitcnt_depctr COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_waitcnt_depctr_check.py") + # Slot 57 mesh requests (#2413): the one accepted group-memory shape translates; each mutation is refused. + add_test(NAME startup_mesh57_skeleton COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") @@ -8410,6 +8413,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/mesh_pixel_pipeline_check.py" "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(mesh_pixel_pipeline_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_skeleton_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_mesh57_skeleton_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME mesh_cbv_order_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_cbv_order_check.py" "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 3c1cb8c51..931c15d17 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9029,8 +9029,21 @@ empty vertex slot, and a recorded root signature that matches the bound root. The pixel program is optional for depth-only work. The cache stores the root in `.root`, the pixel program (or an empty file) in `.ps57`, and writes the mesh program last in `.m57`. The offline reader validates the -request key and stage exports. It reports unsupported mesh code and leaves -the dispatch unforwarded until mesh code emission and binding are available. +request key and stage exports. It translates a mesh program of one +group-memory shape, with a pixel program, to `.ms57.hlsl` and `.ps57.hlsl` +and compiles them as `ms_6_5` and `ps_6_0`. In that shape lane 0 of wave 0 +stores the primitive and vertex counts, every wave passes a barrier, wave 0 +sends one allocation request and the other wave reads the counts back; the +code around it is straight-line and exports vertex and primitive `thread` +under `count > thread`. `mesh_skeleton` in `tools/startup/gfx2hlsl.py` states +the shape and refuses every other program with the first difference. The +lowering clamps both counts to the 128 threads of a group and each index to +the last vertex. It reads 9-bit indices, ignores the edge flags, and gives a +primitive whose null bit (31) is set one vertex three times, so it covers no +pixel. A depth-only pixel program is refused. The source-built fixture draws +on WARP and a hardware +adapter and matches a CPU rasteriser. The runtime does not load the +translated pair, so the dispatch stays unforwarded. The request fixture checks paired and mesh-only requests, duplicate publication, a mismatched root, a populated vertex slot, and an incomplete pixel span. @@ -9048,6 +9061,7 @@ an unsupported IID still returns `E_NOINTERFACE`. cmake --build --preset release --target startup_indirect_draw_indexed ctest --preset release --no-tests=error -R '^startup_indirect_mesh_(request|create_result)_' -V .\out\pe-env\Scripts\python.exe -B tests/startup_gfx2hlsl_watch_check.py +ctest --preset release --no-tests=error -R '^startup_mesh57_skeleton' -V ``` ```powershell diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index 45cd16405..c756acea9 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -103,12 +103,12 @@ def mesh57_fixture(ms, ps, expected, tamper=False): mesh = struct.pack('<6I', 0xbf900009, *position, *primitive, endpgm) pixel = struct.pack('<3I', 0xf800080f, 0x03020100, endpgm) vertex = struct.pack('<3I', *position, endpgm) -mesh57_fixture(mesh, pixel, 'slot 57 mesh code emission is unavailable') -mesh57_fixture(mesh, b'', 'slot 57 mesh code emission is unavailable') +mesh57_fixture(mesh, pixel, 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') +mesh57_fixture(mesh, b'', 'slot 57 mesh without a pixel stage is not covered') mesh57_fixture(vertex, pixel, 'slot 57 mesh stage has no verified allocation and primitive export') # A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check. null_export = struct.pack('<3I', 0xf8001890, 0, endpgm) -mesh57_fixture(mesh, null_export, 'slot 57 mesh code emission is unavailable') +mesh57_fixture(mesh, null_export, 'slot 57 mesh with a depth-only pixel stage is not covered') # Controls: a position export, or a null export mixed with one, stays refused. mesh57_fixture(mesh, struct.pack('<3I', *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') mesh57_fixture(mesh, struct.pack('<5I', 0xf8001890, 0, *position, endpgm), 'slot 57 pixel stage has an incompatible export or termination') diff --git a/tests/startup_mesh57_skeleton.s b/tests/startup_mesh57_skeleton.s new file mode 100644 index 000000000..c2fedc5c3 --- /dev/null +++ b/tests/startup_mesh57_skeleton.s @@ -0,0 +1,73 @@ +// Source-built slot 57 mesh fixture: the group-memory count exchange and a trivial body. +// Entry: s3 bits 24..27 hold the wave index; root constants s8 = primitive count, s9 = vertex count; +// s[10:11] points at a descriptor table whose first descriptor is a raw buffer: +// 12 float4 positions at byte 0, 12 uint4 parameter words at byte 192, 12 packed index words at byte 384. +// A thread reads the slot of its low four bits, so threads past 15 stay inside the 512 bytes. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py new file mode 100644 index 000000000..4ffaac3ba --- /dev/null +++ b/tests/startup_mesh57_skeleton_check.py @@ -0,0 +1,306 @@ +"""Slot 57 mesh requests of one group-memory shape translate in tools/startup/gfx2hlsl.py (#2413). + +usage: startup_mesh57_skeleton_check.py + startup_mesh57_skeleton_check.py binary + startup_mesh57_skeleton_check.py draw + +The fixture (tests/startup_mesh57_skeleton.s, source-built) holds the accepted shape: lane 0 of wave 0 stores a +word and both waves pass a barrier; later the same lane stores the primitive and vertex counts, both waves pass +a barrier, wave 0 sends one allocation request and wave 1 reads the counts back. Each thread then exports the +position and one parameter of vertex `thread` and the packed indices of primitive `thread`, each under its count. +The data of a thread is the buffer slot of its low four bits. + +Without arguments: the fixture translates through the slot 57 request path, and each mutation of the shape is +refused with its own message. `binary` compares the embedded words with llvm-mc. `draw` compiles the request +path's output (ms_6_5, ps_6_0), draws it and compares the read-back target with a CPU rasteriser written here; +a reference with one wrong pixel must fail. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 7d28000e 3608008f 34080884 e0381000 80041004 e03810c0 80041404' + ' bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f 34080882 e0301180' + ' 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +PIXEL_ASM = ('v_interp_mov_f32 v0, p0, attr0.x\nv_interp_mov_f32 v1, p0, attr0.y\nv_interp_mov_f32 v2, p0, attr0.z\n' + 'v_interp_mov_f32 v3, p0, attr0.w\nexp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n') +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + + +def code(words): + return b''.join(struct.pack(' thread index'), + # v_mov_b32 v7, v1: v1 holds the stored count in wave 0 and the read one elsewhere. + ('a read of a register the exchange leaves different per wave', mutate('bf8c3f70', '7e0e0301'), + 'slot 57 mesh: v1 is read where it is not defined for every lane (an entry value, or left different per wave ' + 'by an exchange)'), + # v_mov_b32 v7, v10; s_mov_b32 s20, s25; s_mov_b32 s20, s3: entry values the model does not define. + ('a read of an entry VGPR', mutate('bf8c3f70', '7e0e030a'), + 'slot 57 mesh: v10 is read where it is not defined for every lane (an entry value, or left different per wave ' + 'by an exchange)'), + ('a read of an entry SGPR', mutate('bf8c3f70', 'be940319'), + 'numeric use of s25 holding an entry value the mesh model does not define'), + ('a read of s3 other than the wave index', mutate('bf8c3f70', 'be940303'), + 'slot 57 mesh: s3 is read other than as the wave index'), + # s_and_b32 s4, s3, 0xf000000: wave 0 would restore a zero mask and store no count. + ('a wave test that overwrites the saved lane-0 mask', mutate('8706ff03', '8704ff03'), + 'slot 57 mesh count exchange: registers of the accepted shape overlap'), + # s_mov_b32 s6, s8 after the thread index is derived: the count compare no longer tells the waves apart. + ('a count compare of a register rewritten after the wave index', mutate('bf8cc07f', 'be860308'), + 'slot 57 mesh count exchange: the compared register is not the wave index'), +) + + +def controls(): + os.environ['X2W_FXC'] = '' # sources and manifest only; the draw mode compiles + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('the fixture translates', result, 'ok') + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('published files', names, ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + expect('a translated request is not pending', G.pending_keys(tmp, False), []) + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + body = [line.strip() for line in text[text.index('void main('):].splitlines()] + want = ['if (tid == 0u) { lds[0] = s13; lds[1] = s14; }', 'GroupMemoryBarrierWithGroupSync();', + 's13 = min(lds[0], 128u);', 's14 = min(lds[1], 128u);', 'if (s14 == 0u) s13 = 0u;', + 'SetMeshOutputCounts(s14, s13);'] + at = body.index(want[0]) if want[0] in body else 0 + expect('one store, one barrier, clamped counts, then the allocation', body[at:at + len(want)], want) + expect('one barrier', text.count('GroupMemoryBarrier'), 1) + expect('one allocation', text.count('SetMeshOutputCounts('), 1) + expect('group memory is the two count words', re.findall(r'groupshared[^;]*;', text), ['groupshared uint lds[2];']) + expect('outputs follow the allocation', + all(body.index(line) > body.index(want[-1]) for line in body if 'verts[tid]' in line or 'tris[tid]' in line), True) + for what, mesh, reason in REFUSALS: + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, mesh) + expect(what, result, 'unsupported: ' + reason) + expect(what + ': only the refusal is published', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), ['%016x.fail' % key]) + with tempfile.TemporaryDirectory() as tmp: + ms, blob = code(MESH), root() + key = G.mesh57_key(ms, b'', blob) + for ext, data in (('.root', blob), ('.ps57', b''), ('.m57', ms)): + (Path(tmp) / ('req_%016x%s' % (key, ext))).write_bytes(data) + expect('no pixel stage', G.translate_request(tmp, key), 'unsupported: slot 57 mesh without a pixel stage is not covered') + # exp null off, off, off, off done vm; s_endpgm: a pixel stage without a colour output. + with tempfile.TemporaryDirectory() as tmp: + expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], + 'unsupported: slot 57 mesh with a depth-only pixel stage is not covered') + # The request path refuses a missing s_endpgm earlier; the walk takes the last instruction as the terminator + # unread, so the pipeline refuses it too (s_nop in its place). + try: + G.MeshPipeline(code(MESH[:-1] + ['bf800000']), code(PIXEL), root()) + expect('a mesh program without s_endpgm', 'ok', 'refused') + except G.Unsupported as refusal: + expect('a mesh program without s_endpgm', str(refusal), 'slot 57 mesh program does not end with s_endpgm') + + +def assemble(mc, text): + r = subprocess.run([mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', '-show-encoding'], + input=text, capture_output=True, text=True, check=True) + data = b''.join(bytes(int(b, 16) for b in m.split(',')) for m in re.findall(r'encoding: \[([^\]]*)\]', r.stdout)) + return ['%08x' % word for word in struct.unpack('<%dI' % (len(data) // 4), data)] + + +def binary(mc): + expect('mesh words match llvm-mc', assemble(mc, (HERE / 'startup_mesh57_skeleton.s').read_text()), MESH) + expect('pixel words match llvm-mc', assemble(mc, PIXEL_ASM), PIXEL) + + +# ---- draw: four triangles in a 32x32 target, vertices stored out of order ---------------------- +SIDE = 32 +TRIANGLES = (((2, 2), (14, 2), (2, 14)), ((18, 3), (30, 5), (21, 14)), ((3, 18), (13, 20), (6, 30)), ((18, 18), (30, 18), (30, 30))) +ORDER = (7, 2, 10, 5, 0, 8, 3, 11, 1, 6, 9, 4) # ORDER[3 * triangle + corner] = vertex slot + + +def geometry(): + points, colours, indices = [None] * 12, [None] * 12, [] + for t, triangle in enumerate(TRIANGLES): + for c, point in enumerate(triangle): + slot = ORDER[3 * t + c] + points[slot] = point + colours[slot] = (40 + 17 * slot, 250 - 19 * slot, (slot * 53) % 256, 255) + indices.append(tuple(ORDER[3 * t:3 * t + 3])) + return points, colours, indices + + +def buffer(points, colours, words): + data = bytearray(512) + for slot, (x, y) in enumerate(points): + struct.pack_into('<4f', data, 16 * slot, x / 16 - 1, 1 - y / 16, 0.5, 1) + struct.pack_into('<4f', data, 192 + 16 * slot, *(channel / 255 for channel in colours[slot])) + for t, word in enumerate(words): + struct.pack_into(' 0 or (edge == 0 and (dy < 0 or (dy == 0 and dx > 0))) + if inside: + image[y * SIDE + x] = colour + return image + + +def draw(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('the fixture translates and compiles', result, 'ok') + if result != 'ok': + return 0 + name = str(Path(tmp) / ('%016x' % key)) + uds = G.MeshPipeline(code(MESH), code(PIXEL), root()).uds + # (vertex count, primitive count, thread of vertex slot 0, flags of the first primitive words): all, fewer + # primitives, fewer vertices (indices clamp), no vertex; every thread, with the triangles on vertices + # 112..123 (wave 1, lanes 48..59), each named by eight primitives and the other 96 primitives on vertex 0 + # alone, the first triangle null (bit 31) and the second with its three edge flags (bits 9, 19, 29). + # Each case is one process and one device, which takes seconds on a hardware adapter. + cases = ((12, 4, 0, ()), (12, 1, 0, ()), (7, 4, 0, ()), (0, 4, 0, ()), + (128, 128, 112, (1 << 31, 1 << 9 | 1 << 19 | 1 << 29))) + for case in cases: + verts, prims, first, flags = case + named = [tuple(first + i for i in triangle) for triangle in indices] + words = [a | b << 10 | c << 20 | flag for (a, b, c), flag in zip(named, flags + (0,) * 4)] + drawn = [(0, 0, 0) if word >> 31 else triangle for triangle, word in zip(named, words)] + constants = bytearray(1024) + struct.pack_into(' 200, True) + wrong = list(image) + at = next(i for i, pixel in enumerate(image) if pixel != (0, 0, 0, 255)) + wrong[at] = (0, 0, 0, 255) + path.write_bytes(head + b''.join(bytes(pixel) for pixel in wrong)) + r = subprocess.run(args, capture_output=True, text=True) + expect('a reference with one wrong pixel fails', + (r.returncode, 'pixels=1024 mismatches=1' in r.stdout, 'Draw reference mismatch' in r.stderr), + (1, True, True)) + return 0 + + +def main(argv): + status = 0 + if argv[1:2] == ['binary'] and len(argv) == 3: + binary(argv[2]) + elif argv[1:2] == ['draw'] and len(argv) == 5: + status = draw(*argv[2:]) + elif len(argv) == 1: + controls() + else: + print(__doc__) + return 2 + if FAILED: + return 1 + print('skip: no mesh shader tier' if status == 77 else 'ok') + return status + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a6be92317..8a76975c9 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1053,6 +1053,240 @@ def check_lds_exchange(ins, group, words): raise Unsupported('LDS exchange needs a fill, a barrier and a completed read') +# ---- slot 57 mesh stage: the group-memory count exchange (#2413) -------------------------------- +# A group is two wave64 waves and thread = wave * 64 + lane. 128 is also D3D12's limit for the numthreads of a mesh +# shader, and the declared size of both output arrays. +MESH_THREADS = 128 +MESH_VREG = re.compile(r'\bv(?:\[(\d+):(\d+)\]|(\d+))') +MESH_EXCHANGE = [ + r's_mov_b64 exec, 1', + r's_mov_b64 (?Ps\[\d+:\d+\]), exec', + r's_and_b32 (?Ps\d+), s3, 0xf000000', + r's_cbranch_scc1 label_(?P\w+)', + r'v_lshrrev_b32_e32 v5, 7, v5', + r'v_mov_b32_e32 (?Pv\d+), 0', + r'ds_write_b32 {a_zero}, v5 offset:8', + r's_waitcnt_depctr 0xffe3', + r's_barrier 0x0', + r's_branch label_(?P\w+)', + r's_barrier 0x0', + r'v_mov_b32_e32 (?Pv\d+), 0', + r'ds_read_b32 v5, {a_zero2} offset:8', +] +MESH_COUNTS = [ + r's_barrier 0x0', + r's_cmp_eq_i32 (?Ps\d+), 0', + r's_cbranch_scc0 label_(?P\w+)', + r's_mov_b64 exec, {lane}', + r's_cbranch_execz label_(?P\w+)', + r'v_mov_b32_e32 (?Pv\d+), (?Ps\d+)', + r'v_mov_b32_e32 (?Pv\d+), 0', + r'v_mov_b32_e32 (?Pv\d+), (?Ps\d+)', + r'ds_write_b32 {b_zero}, {b_p}', + r'ds_write_b32 {b_zero}, {b_v} offset:4', + r's_mov_b64 exec, -1', + r's_waitcnt_depctr 0xffe3', + r's_barrier 0x0', + r's_lshl_b32 (?Ps\d+), {prims}, 12', + r's_or_b32 m0, {b_tmp}, {verts}', + r's_sendmsg 0x9', + r's_branch label_(?P\w+)', + r's_barrier 0x0', + r's_mov_b64 exec, {lane}', + r's_cbranch_execz label_(?P\w+)', + r'v_mov_b32_e32 (?Pv\d+), 0', + r'ds_read_b32 (?Pv\d+), {b_zero2}', + r'ds_read_b32 (?Pv\d+), {b_zero2} offset:4', + r's_waitcnt lgkmcnt\(1\)', + r'v_readfirstlane_b32 {prims}, {b_r0}', + r's_waitcnt lgkmcnt\(0\)', + r'v_readfirstlane_b32 {verts}, {b_r1}', + r's_mov_b64 exec, -1', +] + + +def mesh_vregs(tokens): + out = set() + for m in MESH_VREG.finditer(' '.join(tokens)): + out.update(range(int(m[1] or m[3]), int(m[2] or m[3]) + 1)) + return out + + +def mesh_run(ins, at, what, patterns, env): + """Match consecutive instructions; {name} in a pattern is the text an earlier (?P...) bound.""" + for k, pattern in enumerate(patterns): + text = ins[at + k][3] if at + k < len(ins) else '' + m = re.fullmatch(re.sub(r'\{(\w+)\}', lambda ref: re.escape(env[ref[1]]), pattern), text) + if not m: + raise Unsupported('slot 57 mesh %s: instruction %d of the accepted shape (%s) is absent' + % (what, k + 1, pattern.split()[0])) + env.update(m.groupdict()) + return at + len(patterns) + + +def mesh_skeleton(ins): + """Prove the one accepted group-memory shape of a slot 57 mesh program and replace it by per-thread instructions. + + Accepted shape, in program order (anything else is refused with its own message): + - Exchange: exec = 1 (lane 0 of each wave), the mask saved in an SGPR pair; wave 0 (s3 bits 24..27 zero) stores + entry v5 >> 7 at byte 8, waits and passes a barrier; every other wave passes a barrier and reads byte 8 to v5. + - Straight-line code up to the next barrier. Its only read of v5 may be one v_readfirstlane_b32 under exec = -1. + - Counts: one barrier; the wave whose index (s_bfe_u32 of s3, 4 bits at 24) is zero stores SGPR P at byte 0 and + SGPR V at byte 4 under the saved lane-0 mask, waits, passes a barrier and sends one allocation request with + m0 = P << 12 | V; every other wave passes a barrier and reads both words back into the same P and V. + - Straight-line code to s_endpgm. Exports only here: pos0 and param under exec = -1 narrowed by one + v_cmpx_gt_i32 V, thread; the primitive export likewise with P. thread is the v_mbcnt pair over wave << 6. + Each path therefore passes three barriers, each store has one writer (one lane of one wave), and a wait and a + barrier separate it from every read. The lowering keeps one writer and one barrier: thread 0 stores, all read. + + Registers the two arms leave different, that the lowering does not compute, or that hold an entry value the + model does not define, are refused when read: VGPRs by the scan below, SGPRs by a symbol (setup_entry and the + op_x2w_mesh_* handlers), SCC and m0 after the counts. Of s3 only the wave index is modelled. + """ + env = {} + start = 1 if ins and ins[0][2] == 's_inst_prefetch' else 0 + a_end = mesh_run(ins, start, 'group-index exchange', MESH_EXCHANGE, env) + count_at = next((i for i in range(a_end, len(ins)) if ins[i][2] == 's_barrier'), len(ins)) + b_end = mesh_run(ins, count_at, 'count exchange', MESH_COUNTS, env) + + def lands(key, index, what): + if index >= len(ins) or int(env[key], 16) != ins[index][0]: + raise Unsupported('slot 57 mesh %s: a branch leaves the accepted shape' % what) + lands('a_other', start + 10, 'group-index exchange') + lands('a_join', a_end, 'group-index exchange') + lands('b_reader', count_at + 17, 'count exchange') + lands('b_wskip', count_at + 10, 'count exchange') + lands('b_join', b_end, 'count exchange') + lands('b_rskip', count_at + 27, 'count exchange') + lane = set(range(*(lambda r: (r[1], r[2] + 1))(reg_range(env['lane'])))) + sreg = {key: int(env[key][1:]) for key in ('wave', 'prims', 'verts', 'b_tmp')} + vreg = {key: int(env[key][1:]) for key in ('a_zero', 'a_zero2', 'b_p', 'b_zero', 'b_v', 'b_zero2', 'b_r0', 'b_r1')} + if (len({vreg['b_p'], vreg['b_zero'], vreg['b_v']}) != 3 or len({vreg['b_r0'], vreg['b_r1']}) != 2 + or vreg['b_r0'] == vreg['b_zero2'] or 5 in (vreg['a_zero'], vreg['a_zero2']) + or len({sreg['prims'], sreg['verts'], sreg['b_tmp']}) != 3 or {sreg['prims'], sreg['verts']} & lane + or sreg['wave'] in lane | {3, sreg['prims'], sreg['verts']} or int(env['a_bits'][1:]) in lane): + raise Unsupported('slot 57 mesh count exchange: registers of the accepted shape overlap') + if not ins or ins[-1][2] != 's_endpgm': + raise Unsupported('slot 57 mesh program does not end with s_endpgm') + + out = list(ins[:start]) + span = lambda first, last: (ins[first][0], ins[last][0] + ins[last][1] - ins[first][0]) + out.append(span(start, start + 1) + ('x2w_mesh_lane0', 'x2w_mesh_lane0 ' + env['lane'])) + out.append(ins[start + 2]) + out.append(span(start + 3, a_end - 1) + ('s_nop', 's_nop 0')) + # State of the walk over the code outside the two exchanges. + stale = set(range(256)) # VGPRs the model does not hold for every lane; no entry VGPR is modelled + pending = set() # of those, the ones written only for the lanes of a narrowed exec + mask = 'lane0' # 'lane0', None (all lanes), 'verts' or 'prims' (all lanes narrowed by one compare) + wave_known = False # sreg['wave'] holds s_bfe_u32(s3, 4 bits at 24) + thread = base = None # VGPR of the thread index, SGPR holding wave << 6 + scc_stale = False + exports = [] + for index in list(range(a_end, count_at)) + [None] + list(range(b_end, len(ins) - 1)): + if index is None: + if not wave_known: + raise Unsupported('slot 57 mesh count exchange: the compared register is not the wave index') + out.append(span(count_at, b_end - 2) + ( + 'x2w_mesh_counts', 'x2w_mesh_counts %s, %s, %s' % (env['prims'], env['verts'], env['b_tmp']))) + out.append(ins[b_end - 1]) + stale |= pending | {vreg[k] for k in ('b_p', 'b_zero', 'b_v', 'b_zero2', 'b_r0', 'b_r1')} + pending.clear() + mask, scc_stale = None, True + continue + off, size, name, asm = ins[index] + after = index >= b_end + _, ops, _ = parse(asm) + base_name = re.sub(r'_e(32|64)$', '', name) + if name.startswith(('s_cbranch', 's_branch', 's_setpc', 's_call', 's_swappc')): + raise Unsupported('slot 57 mesh: a branch outside the group-memory exchanges is not covered') + if name.startswith('ds_') or name in ('s_barrier', 's_sendmsg', 's_sendmsghalt'): + raise Unsupported('slot 57 mesh: %s outside the group-memory exchanges' % name) + if name.startswith(('v_readlane', 'v_writelane')): + raise Unsupported('slot 57 mesh: lane spills are not covered') + keep = ins[index] + if base_name == 'v_readfirstlane_b32': + if after or asm != 'v_readfirstlane_b32 %s, v5' % ops[0] or mask is not None or 5 not in stale: + raise Unsupported('slot 57 mesh: v_readfirstlane_b32 outside the group-index read is not covered') + keep = (off, size, 'x2w_mesh_group', 'x2w_mesh_group ' + ops[0]) + ops = ops[:1] + writes_s = set() + if not base_name.startswith(('v_cmpx', 'exp', 'ds_write', 'buffer_store')): + for tok in destinations(name, ops): + r = reg_range(tok) + if r and r[0] == 's': + writes_s.update(range(r[1], r[2] + 1)) + if 3 in writes_s or writes_s & lane: + raise Unsupported('slot 57 mesh: the wave word s3 or the saved lane-0 mask is written') + if writes_s and name.startswith('v_') and keep[2] != 'x2w_mesh_group': + raise Unsupported('slot 57 mesh: %s into an SGPR is not covered' % base_name) + # Only the wave index of s3 is modelled. + if not re.fullmatch(r's_bfe_u32 s\d+, s3, 0x40018', asm) and any( + r and r[0] == 's' and r[1] <= 3 <= r[2] for r in map(reg_range, ops)): + raise Unsupported('slot 57 mesh: s3 is read other than as the wave index') + if after and writes_s & {sreg['prims'], sreg['verts']}: + raise Unsupported('slot 57 mesh: an output count is written after the count exchange') + if after and re.search(r'\bm0\b', asm): + raise Unsupported('slot 57 mesh: m0 is used after the allocation request') + if scc_stale and reads_scc(name, asm): + raise Unsupported('slot 57 mesh: SCC of the count exchange is read') + if name.startswith(('s_cmp', 's_bitcmp')): + scc_stale = False + # EXEC and VCC as wave-wide masks are outside the per-thread model here: only the two forms below touch EXEC. + if asm == 's_mov_b64 exec, -1': + mask = None + stale |= pending + pending.clear() + elif base_name.startswith('v_cmpx'): + count = {env['verts']: 'verts', env['prims']: 'prims'}.get(ops[0] if ops else None) + if (base_name != 'v_cmpx_gt_i32' or not after or mask is not None or count is None + or thread is None or ops[1:] != ['v%d' % thread]): + raise Unsupported('slot 57 mesh: an EXEC compare other than output count > thread index under ' + 'exec = -1 is not covered') + mask = count + elif writes_exec(name, ops) or re.search(r'\bexec(_lo|_hi)?\b', asm) or ( + name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm)): + raise Unsupported('slot 57 mesh: %s on a wave mask is not covered' % base_name) + # The thread index: v_mbcnt_lo(-1, wave << 6) then v_mbcnt_hi(-1, that) under exec = -1. + if asm == 's_bfe_u32 %s, s3, 0x40018' % env['wave']: + wave_known = True + elif sreg['wave'] in writes_s: + wave_known = False + if wave_known and re.fullmatch(r's_lshl_b32 s\d+, %s, 6' % env['wave'], asm) and ops[0] != env['wave']: + base = int(ops[0][1:]) + elif base in writes_s: + base = None + reads_v = mesh_vregs(ops if base_name.startswith(('v_cmp', 'exp', 'ds_write', 'buffer_store')) else ops[1:]) + dest = reg_range(ops[0]) if ops and not base_name.startswith(('v_cmp', 'exp', 'buffer_store')) else None + writes_v = set(range(dest[1], dest[2] + 1)) if dest and dest[0] == 'v' else set() + if base_name == 'v_mbcnt_lo_u32_b32' and base is not None and ops[1:] == ['-1', 's%d' % base] and mask is None \ + and index + 1 < len(ins) and ins[index + 1][3] == 'v_mbcnt_hi_u32_b32 %s, -1, %s' % (ops[0], ops[0]): + thread = dest[1] + elif thread in writes_v and not (base_name == 'v_mbcnt_hi_u32_b32' and ins[index - 1][2].startswith('v_mbcnt_lo')): + raise Unsupported('slot 57 mesh: the thread index register is rewritten') + if keep[2] != 'x2w_mesh_group' and reads_v & stale: + raise Unsupported('slot 57 mesh: v%d is read where it is not defined for every lane (an entry value, or ' + 'left different per wave by an exchange)' % min(reads_v & stale)) + if mask is not None: + pending |= writes_v & stale + else: + pending -= writes_v + stale -= writes_v + if name == 'exp': + target = asm.split()[1].rstrip(',') + want = 'prims' if target == 'target_20' else 'verts' if re.fullmatch(r'pos0|param\d+', target) else None + if want is None: + raise Unsupported('slot 57 mesh: export target %s is not covered' % target) + if not after or mask != want: + raise Unsupported('slot 57 mesh: export %s is not under exec = -1 narrowed by its output count > ' + 'thread index' % target) + exports.append(target) + out.append(keep) + if exports.count('pos0') != 1 or exports.count('target_20') != 1: + raise Unsupported('slot 57 mesh: one pos0 and one primitive export are required') + out.append(ins[-1]) + return out + + class Stage: """Translates one stage. Shares the resource and entry-constant registries of its pipeline.""" @@ -1082,6 +1316,8 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.ins = decode(strip_header(code)) else: self.ins = decode(strip_header(code), refusals) if decoded is None else decoded + if kind == 'ms': + self.ins = mesh_skeleton(self.ins) # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept # there is known only afterwards: translate again with that register read at run time or refused there. A # register only moves from kept to 'run' to 'refuse', so this ends. @@ -1146,6 +1382,13 @@ def setup_entry(self): reg += 1 if self.kind == 'cs': self.setup_compute_entry(reg) + elif self.kind == 'ms': + # The wave index is bits 24..27 of s3 (mesh_skeleton requires the program to read it that way). + self.used_s.add(3) + self.entry = ['s3 = (tid >> 6) << 24;'] + for n in range(105): + if n != 3 and n not in self.sym: + self.sym[n] = ('an entry value the mesh model does not define',) elif self.kind == 'vs': self.sym[0] = ('ptr', ('vbtab',)) self.sym[1] = ('ptrhi', ('vbtab',)) @@ -4018,8 +4261,64 @@ def op_s_ff1_i32_b32(self, ops, mods): # FF1 reports its index and leaves SCC unchanged. self.set_s(dst[1], '0u', ('const', 0)) + # ---- slot 57 mesh stage: instructions mesh_skeleton() puts in place of the group-memory exchanges ---- + def op_x2w_mesh_lane0(self, ops, mods): + # `s_mov_b64 exec, 1` leaves lane 0 of each wave running. The saved copy of that mask is not modelled. + r = reg_range(ops[0]) + for n in range(r[1], r[2] + 1): + self.sym[n] = ('the saved mesh lane-0 mask',) + self.emit('exec = (tid & 63u) == 0u ? 1u : 0u;') + self.exec_known = False + + def op_x2w_mesh_group(self, ops, mods): + # The word is entry v5 >> 7 of wave 0, lane 0. What v5 holds at entry is not verified, so a use is refused. + self.sym[reg_range(ops[0])[1]] = ('the mesh group index',) + + def op_x2w_mesh_counts(self, ops, mods): + prims, verts, temporary = (reg_range(tok)[1] for tok in ops) + self.emit('if (tid == 0u) { lds[0] = %s; lds[1] = %s; }' % (self.S(prims), self.S(verts))) + self.emit('GroupMemoryBarrierWithGroupSync();') + # Thread t writes vertex t and primitive t, so a count above the thread count names outputs that no + # thread writes. The clamp keeps the declared arrays in bounds and changes nothing a thread writes. + for n, word in ((prims, 0), (verts, 1)): + self.set_s(n, 'min(lds[%d], %du)' % (word, MESH_THREADS), uniform=True) + # Without a vertex no index is valid, so no primitive is. + self.emit('if (%s == 0u) %s = 0u;' % (self.S(verts), self.S(prims))) + self.emit('SetMeshOutputCounts(%s, %s);' % (self.S(verts), self.S(prims))) + self.mesh_verts = self.S(verts) + self.sym[temporary] = ('a mesh allocation temporary',) + + def mesh_export(self, asm, target, vals, flags): + if target == 'target_20': + # First word: three 9-bit vertex indices at bits 0, 10 and 20, an edge flag above each (not modelled: + # triangles are filled) and the null bit 31 (Mesa ac_nir_pack_ngg_prim_exp_arg). + if vals[1:] != ['off'] * 3 or [f for f in flags if f != 'done']: + raise Unsupported('mesh primitive export form %r' % asm) + # An index at or past the vertex count has no defined vertex; the clamp keeps it inside the array. + # A null primitive names one vertex three times, which covers no pixel. + self.emit('if (exec & 1) { w = %s; tris[tid] = w >> 31 != 0u ? (uint3)0u : ' + 'min(uint3(w, w >> 10, w >> 20) & 511u, max(%s, 1u) - 1u); }' + % (self.u(vals[0]), self.mesh_verts)) + return None + first = len(self.lines) + self.in_mesh_export = True + try: + self.export(asm) + finally: + self.in_mesh_export = False + self.lines[first:] = ['if (exec & 1) { %s mesh_vertex = true; }' % ' '.join(self.lines[first:])] + return None + def op_v_mbcnt_lo_u32_b32(self, ops, mods, high=False): name = 'v_mbcnt_%s_u32_b32' % ('hi' if high else 'lo') + if self.kind == 'ms': + # V_MBCNT counts the mask bits strictly below the lane, in the low or high half of a wave64 mask. + dst = reg_range(ops[0]) if len(ops) == 3 else None + if mods or not dst or dst[0] != 'v' or dst[1] != dst[2] or ops[1] != '-1': + raise Unsupported('%s in a mesh stage requires a VGPR, the mask -1 and a base' % name) + below = 'max(tid & 63u, 32u) - 32u' if high else 'min(tid & 63u, 32u)' + self.set_v(dst[1], '(%s + %s)' % (self.u(ops[2]), below)) + return if self.kind != 'cs': raise Unsupported(name) if mods or len(ops) != 3: @@ -4779,6 +5078,8 @@ def export(self, asm): if not m: raise Unsupported('export form %r' % asm) target, vals, flags = m.group(1), [v.strip() for v in m.group(2).split(',')], m.group(3).split() + if getattr(self, 'kind', None) == 'ms' and not getattr(self, 'in_mesh_export', False): + return self.mesh_export(asm, target, vals, flags) if any(f.startswith('en:') for f in flags): raise Unsupported('compressed export enable mask %s does not select whole channel pairs' % next(f for f in flags if f.startswith('en:'))[3:]) @@ -5133,6 +5434,7 @@ def read(fmt, data, offset): class Pipeline: + vertex_kind = 'vs' uses_pack16_rne = False uses_gather_2d_lod = False srv_formats = () @@ -5174,11 +5476,11 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.modified = set() self.rect = self.ud(('rect',)) if refusals is None: - self.vs = Stage(self, 'vs', vs_code) + self.vs = Stage(self, self.vertex_kind, vs_code) self.ps = Stage(self, 'ps', ps_code) else: decoded = {} if decoded is None else decoded - self.vs = Stage(self, 'vs', vs_code, refusals=refusals, decoded=decoded.get('vs')) + self.vs = Stage(self, self.vertex_kind, vs_code, refusals=refusals, decoded=decoded.get('vs')) self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded.get('ps')) self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) @@ -5575,6 +5877,27 @@ def manifest(self): return '\n'.join(lines) + '\n' +class MeshPipeline(Pipeline): + """A slot 57 mesh and pixel pair. The mesh stage is the vertex-producing stage of the pair (self.vs).""" + vertex_kind = 'ms' + + def hlsl_ms(self): + s = self.vs + if len(s.blocks) != 1: + raise Unsupported('slot 57 mesh: a branch outside the group-memory exchanges is not covered') + lines = [re.sub(r' o\.fparam(\d+) = [^;]*;', lambda m: m[0] if int(m[1]) in self.flat else '', + re.sub(r' o\.hparam(\d+)_(?:lo|hi) = [^;]*;', + lambda m: m[0] if int(m[1]) in self.f16_plain else '', line)) + for line in s.body()] + return '\n'.join( + self.common() + ['struct VSOut {'] + self.interface(False) + [ + '};', 'groupshared uint lds[2];', '[numthreads(%d, 1, 1)]' % MESH_THREADS, '[outputtopology("triangle")]', + 'void main(uint tid : SV_GroupIndex, out vertices VSOut verts[%d], out indices uint3 tris[%d]) {' + % (MESH_THREADS, MESH_THREADS), ' VSOut o = (VSOut)0; bool mesh_vertex = false;'] + + s.declarations() + [' ' + line for line in s.entry] + lines + + [' if (mesh_vertex) verts[tid] = o;', '}']) + '\n' + + def fnv(data, h=1469598103934665603): for b in data: h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff @@ -5909,8 +6232,11 @@ def mesh57_key(ms, ps, root): return value -def inspect_mesh57_request(out_dir, key): - """Read a fixed-descriptor mesh request without falling back to a vertex translation.""" +def translate_mesh57(out_dir, key): + """Translate a fixed-descriptor mesh request of the accepted shape (mesh_skeleton), or raise Unsupported. + + Writes .ms57.hlsl, .ps57.hlsl, the compiled .ms57.cso and .ps57.cso, and .ms57.txt (last). + No runtime path loads these names yet.""" source = os.path.join(out_dir, 'req_%016x' % key) ms, ps, root = (open(source + ext, 'rb').read() for ext in ('.m57', '.ps57', '.root')) if mesh57_key(ms, ps, root) != key: @@ -5928,10 +6254,40 @@ def inspect_mesh57_request(out_dir, key): null_only = {a.split()[1] for _, _, op, a in pixel if op == 'exp'} == {'null'} if not pixel or pixel[-1][2] != 's_endpgm' or classify_decoded(pixel) != 'ps' and not null_only: raise Unsupported('slot 57 pixel stage has an incompatible export or termination') - for offset, _, op, _ in mesh: - if op.startswith('ds_'): - raise Unsupported('slot 57 mesh workgroup memory: %s at +0x%x' % (op, offset)) - raise Unsupported('slot 57 mesh code emission is unavailable') + if null_only: + raise Unsupported('slot 57 mesh with a depth-only pixel stage is not covered') + if not ps: + raise Unsupported('slot 57 mesh without a pixel stage is not covered') + pipe = MeshPipeline(ms, ps, root) + sources = (('ms', 'ms_6_5', pipe.hlsl_ms()), ('ps', 'ps_6_0', pipe.hlsl_ps())) + manifest = pipe.manifest() + name = os.path.join(out_dir, '%016x' % key) + for stage, _, hlsl in sources: + open('%s.%s57.hlsl' % (name, stage), 'w').write(hlsl) + if os.environ.get('X2W_FXC') != '': + compiler = find_dxc() + if compiler is None: + raise Unsupported('dxc not found (X2W_DXC=%s): a mesh stage needs shader model 6.5' % os.environ.get('X2W_DXC', '')) + import subprocess + # Publish only bytecode from a successful pair. + with tempfile.TemporaryDirectory(prefix='.dxc-', dir=out_dir) as staging: + for stage, profile, _ in sources: + bytecode = os.path.join(staging, stage + '.cso') + r = subprocess.run([compiler, '-Gis', '-T', profile, '-E', 'main', '-Fo', bytecode, '%s.%s57.hlsl' % (name, stage)], + capture_output=True, text=True) + if r.returncode or not has_bytecode(bytecode): + # DXC names the source path; keep only the diagnostic after it. + lines = [re.sub(r'^.*?57\.hlsl(:\d+:\d+)?:\s*', '', line) for line in r.stderr.strip().splitlines()] + raise Unsupported('dxc %s: %s' % (stage, (lines[0] if lines else 'no bytecode produced')[:500])) + for stage, _, _ in sources: + os.replace(os.path.join(staging, stage + '.cso'), '%s.%s57.cso' % (name, stage)) + temporary = '%s.ms57.txt.%d.tmp' % (name, os.getpid()) + with open(temporary, 'w') as result: + result.write(manifest) + os.replace(temporary, name + '.ms57.txt') + with suppress(FileNotFoundError): + os.remove(name + '.fail') + return 'ok' def translate_request(out_dir, key): @@ -5940,7 +6296,7 @@ def translate_request(out_dir, key): return translate_compute(out_dir, key) if os.path.isfile(os.path.join(out_dir, 'req_%016x.m57' % key)): try: - inspect_mesh57_request(out_dir, key) + return translate_mesh57(out_dir, key) except (Unsupported, OSError, UnicodeError, struct.error) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason @@ -6271,9 +6627,10 @@ def pending_keys(out_dir, skip_failed): continue key = int(m.group(1), 16) result = os.path.join(out_dir, '%016x' % key) - stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.vs.cso', '.ps.cso') + mesh = m.group(2) == 'm57' + stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if m.group(2) != 'm57' and os.path.isfile(result + '.txt') and (manifest_only or all(has_bytecode(result + s) for s in stages)): + if os.path.isfile(result + ('.ms57.txt' if mesh else '.txt')) and (manifest_only or all(has_bytecode(result + s) for s in stages)): continue fail = os.path.join(out_dir, '%016x.fail' % key) # A repeated pass retries a failure only once its request is rewritten. From e2faf858c6a0ad8317bff13685eefda3556e5413 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Wed, 25 Nov 2026 21:23:11 +0200 Subject: [PATCH 107/232] tooling: report ExecuteIndirect outcomes in startup triage (#2510) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> --- docs/startup-runtime.md | 7 +++++ tests/startup_triage_run_check.py | 49 +++++++++++++++++++++++++++++ tools/startup/triage_run.py | 51 +++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 18ccd39a0..ac58a53be 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -991,6 +991,13 @@ text is grouped as `other (text omitted)` and never copied; raw snippets stay in outcome (`aliased`, `not_aliased`, `failed`) in a separate table, and a line with an HRESULT other than 0 (or an uncommitted address) still counts as `failed` and as an unhandled `Device::slot133` event. +The `ExecuteIndirect` table reports the highest sampled cumulative count for each outcome and +command-signature kind in the `x2w-render indirect:` census. A repeated snapshot does not increase +any count. Each cell can come from a different sample, so avoid summing the cells as one run's total +when scanning multiple runs. The section appears only after a complete census line and can show zero +forwarded `dispatchmesh` calls alongside a graphics-pipeline refusal count. Forwarded counts describe +the runtime's forwarding path. GPU completion and image readback require separate evidence. + The `Run End-Point` section says how far a run got and how it ended, so that reports of runs with different memory caps can be told apart. It gives the largest `commit peak=` value of the `x2w-dstorage heartbeat` lines (not the last one), the highest heartbeat second, the counts of the last `failed requests by cause` heartbeat line (the diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 48a7bdfac..4f63a8c40 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -513,6 +513,54 @@ def check_every_shader_reason_entry_is_reachable(failures: list[str]) -> None: if triage_run.classify_shader_reason("a reason nobody modelled") != triage_run.OTHER: failures.append("an unmodelled reason did not fall back to the other token") +def check_indirect_outcomes(failures: list[str]) -> None: + initial = ( + "x2w-render indirect: forwarded: draw 2; refused graphics-pipeline: dispatchmesh 5; " + "compute-pipeline: dispatch 3; placeholder-signature: drawindexed 1; other: other 1" + ) + later = initial.replace("dispatchmesh 5", "dispatchmesh 12") + older = initial.replace("dispatchmesh 5", "dispatchmesh 4") + invalid = ( + later.replace("other: other 1", r"other: C:\Users\alice\secret.exe"), + later.replace("draw 2", "draw 2 draw 99"), + later.replace("dispatchmesh 12", "dispatchmesh 99999999999999999999"), + later.replace("dispatchmesh 12", "dispatchmesh -99"), + later.replace("; other: other 1", ""), + later.replace("forwarded: draw 2", "forwarded: draw 2 dispatchmesh 0x00007ff712345678"), + ) + zero = ( + "x2w-render indirect: forwarded: 0; refused graphics-pipeline: 0; " + "compute-pipeline: 0; placeholder-signature: 0; other: 0" + ) + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "stderr.txt").write_text("\n".join((initial, later, later, *invalid)), encoding="utf-8") + (root / "trap.log").write_text(initial + "\n" + older + "\n", encoding="utf-8") + report = triage_run.triage_run(root) + expected = ( + "### `ExecuteIndirect` Outcomes", + "| forwarded | 0 | 0 | 2 | 0 | 0 |", + "| refused graphics-pipeline | 0 | 0 | 0 | 0 | 12 |", + "| compute-pipeline | 0 | 3 | 0 | 0 | 0 |", + "| placeholder-signature | 0 | 0 | 0 | 1 | 0 |", + "| other | 1 | 0 | 0 | 0 | 0 |", + ) + for snippet in expected: + if snippet not in report: + failures.append(f"missing indirect summary line: {snippet!r}") + for secret in ("alice", "secret.exe", "0x00007ff712345678"): + if secret in report: + failures.append(f"indirect summary copied private text: {secret!r}") + log = root / "stderr.txt" + log.write_text(zero + "\n", encoding="utf-8") + if "| forwarded | 0 | 0 | 0 | 0 | 0 |" not in triage_run.triage_run(log): + failures.append("a complete zero snapshot was not reported") + log.write_text("\n".join(invalid), encoding="utf-8") + if "### `ExecuteIndirect` Outcomes" in triage_run.triage_run(log): + failures.append("a malformed snapshot produced an indirect summary") + + def main() -> int: failures: list[str] = [] check_aggregation_and_redaction(failures) @@ -522,6 +570,7 @@ def main() -> int: check_empty_and_missing_dirs(failures) check_cli_invocation(failures) check_slot133_outcomes(failures) + check_indirect_outcomes(failures) check_run_endpoint(failures) check_every_shader_reason_entry_is_reachable(failures) for item in failures: diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index f66087a14..9235f9ee1 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -67,6 +67,13 @@ "zlib failed", } TRAP_TAGS = {"x2w-trap", "x2w-noop", "x2w-continue", "x2w-fail"} +INDIRECT_PREFIX = "x2w-render indirect: " +# Ordered fields emitted by the slot-61 census in d3d12_xs_device.cpp. +INDIRECT_OUTCOMES = ( + "forwarded", "refused graphics-pipeline", "compute-pipeline", "placeholder-signature", "other", +) +INDIRECT_KINDS = ("other", "dispatch", "draw", "drawindexed", "dispatchmesh") +RE_INDIRECT_COUNT = re.compile(r"[0-9]{1,19}\Z") OTHER = "other (text omitted)" RE_DEC = re.compile(r"[0-9]{1,10}\Z") RE_HEX = re.compile(r"0x[0-9a-fA-F]{1,8}\Z") @@ -283,11 +290,34 @@ def iter_log_files(log_target: Path) -> list[Path]: return files +def parse_indirect_snapshot(payload: str) -> dict[tuple[str, str], int] | None: + groups = payload.split("; ") + if len(groups) != len(INDIRECT_OUTCOMES): + return None + snapshot: dict[tuple[str, str], int] = {} + for expected, group in zip(INDIRECT_OUTCOMES, groups): + outcome, _, counts = group.partition(": ") + if outcome != expected: + return None + if counts == "0": + continue + fields = counts.split() + if not fields or len(fields) % 2: + return None + for kind, count in zip(fields[::2], fields[1::2]): + key = (outcome, kind) + if kind not in INDIRECT_KINDS or key in snapshot or not RE_INDIRECT_COUNT.fullmatch(count): + return None + snapshot[key] = int(count) + return snapshot + + def summarize_lines(lines: Iterable[str]) -> dict[str, Any]: """Aggregate startup telemetry counters from an iterable of log lines.""" slot70_refusals: Counter[tuple[str, str, str, str, str, str, str]] = Counter() d3d12_unhandled: Counter[str] = Counter() slot133_outcomes: Counter[str] = Counter() + indirect_peaks: Counter[tuple[str, str]] | None = None d3d12_debug: Counter[tuple[str, str]] = Counter() dstorage_failures: Counter[str] = Counter() dstorage_hresults: Counter[str] = Counter() @@ -300,6 +330,15 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Any]: continue endpoint.observe(line) # reads only; the line is still classified below + if line.startswith(INDIRECT_PREFIX): + snapshot = parse_indirect_snapshot(line.removeprefix(INDIRECT_PREFIX)) + if snapshot is not None: + if indirect_peaks is None: + indirect_peaks = Counter() + # The runtime emits cumulative snapshots. Counter union takes each bucket's maximum. + indirect_peaks |= Counter(snapshot) + continue + # 1. slot70 memory SRV refusals m = RE_SLOT70.search(line) if m: @@ -429,6 +468,7 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Any]: "slot70_refusals": slot70_refusals, "d3d12_unhandled": d3d12_unhandled, "slot133_outcomes": slot133_outcomes, + "indirect_peaks": indirect_peaks, "d3d12_debug": d3d12_debug, "dstorage_failures": dstorage_failures, "dstorage_hresults": dstorage_hresults, @@ -587,6 +627,17 @@ def format_markdown( s133_rows = [[s133[name], name] for name in SLOT133_OUTCOMES if s133[name]] out.extend(_format_table(["Count", "Outcome"], s133_rows, len(s133_rows), sum(s133.values()), max_items)) + indirect = summary["indirect_peaks"] + if indirect is not None: + out.extend([ + "### `ExecuteIndirect` Outcomes", + "", + "Peak sampled cumulative count per cell. Rows and columns can peak in different samples.", + "", + ]) + rows = [[outcome, *(indirect[outcome, kind] for kind in INDIRECT_KINDS)] for outcome in INDIRECT_OUTCOMES] + out.extend(_format_table(["Outcome", *INDIRECT_KINDS], rows, len(rows), 0, len(rows))) + # 3. x2w-d3d12-debug dbg = summary["d3d12_debug"] if dbg: From bfba03c99c66bf7d14aa875fe3e6b273bf18b897 Mon Sep 17 00:00:00 2001 From: Yann Bucaille <83926195+Ybucaille@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:24:20 +0100 Subject: [PATCH 108/232] gfx2hlsl: accept an i1-phi lane mask live across an execz block (#2505) * gfx2hlsl: accept an i1-phi lane mask live across an execz block In compute, a block that s_cbranch_execz skips was refused whenever it defined a mask (vcc_lo or an sN) that is read after the join, as in the compiler's if-conversion: M = 0 before the branch, M = exec_lo (or X & exec_lo) in the block, v_cndmask on M after the join. Accept it when M is zeroed by s_mov_b32 M, 0 with straight-line code up to the branch, every write of M in the block copies or masks exec, and M is only read per lane after the join. Exec only narrows in the block, so a lane the model skips has bit 0 in the wave's M too, which is the model's M. Whole-mask readers (s_cbranch_vccz/vccnz, s_cmp, copies, data operands) keep the refusal, since the one-lane model lacks the other lanes' bits. * gfx2hlsl: pin the s_and_saveexec read of an execz lane mask tedin7's review of #2505 found that removing s_and_saveexec_b32 from per_lane_read left the check green. Read the mask through it after the join, and keep the refusal when the mask is its destination. --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 14 ++++- tests/startup_gfx2hlsl_compute_check.py | 65 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 82 ++++++++++++++++++++++++- 3 files changed, 157 insertions(+), 4 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 931c15d17..ff03adb93 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14049,8 +14049,20 @@ decoder's spelling: - `v_div_fmas` reads `vcc`; - the high half of a mask is tracked apart from the low half. +One live definition is accepted, the lane mask of the compiler's if-conversion: a 32-bit mask M (`vcc_lo` or one +SGPR) that `s_mov_b32 M, 0` zeroes before the branch, with only straight-line code between the zeroing and the +branch, and that the block sets only with `s_mov_b32 M, exec_lo` or `s_and_b32 M, X, exec_lo` (either operand +order). Exec only narrows in the block, so each such write leaves the bit of a lane whose exec bit is clear at 0. +M is 0 at the branch on every path, so a lane the model skips has the bit 0 in the wave too, whether the wave ran +the block or not. This holds only while M is read per lane: after the join, until M is rewritten, every read must +be the lane select of `v_cndmask`, the carry-in of `v_addc`, `v_subb`, `v_add_co_ci` and similar ops, or +`s_and_saveexec_b32` / `s_and_b32` with exec. `s_cbranch_vccz`, `s_cbranch_vccnz`, `s_cmp`, a copy of M and M +as a data operand see the other lanes' bits, which the one-lane model does not have, and keep the refusal. + The block is still refused in these cases: -- a definition that is live at the join; +- a definition that is live at the join, other than the lane mask above (or one of its conditions fails: zeroing + with a value other than 0 or missing, a branch or a branch target between the zeroing and the branch, a write + of M that is not from exec, a `vcc_hi` or 64-bit write, a whole-mask read after the join); - any other exec write: exec set from a compare alone, restored from a mask saved before the block, or written in a block with a branch or entered by one (a proven calculated `s_setpc_b64` jump counts), or restored through a 64-bit move, `s_or` or `s_xor` (the tracked copies name registers, not which exec half they hold); diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 7d94489d3..b32acb0de 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -985,6 +985,71 @@ def check_controls(): refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate( 'A', code=splice('s_getpc_b64 s[22:23]', 's_add_u32 s22, s22, 20', 's_addc_u32 s23, s23, 0', 's_setpc_b64 s[22:23]', *block)).hlsl_cs()) + # The compiler's i1-phi lane mask: M is zeroed before the branch, set from exec in the block, and read per lane + # after the join. For a lane the model skips, the wave's M bit is 0 either way (exec only narrows in the block), + # which is the model's M. Accepted for vcc_lo and for an sN, with a move or an s_and in either operand order. + SPLICE.update({'s_mov_b32 vcc_lo, 0': '8003eabe', 's_mov_b32 vcc_lo, -1': 'c103eabe', 's_mov_b32 s20, 0': '800394be', + 's_mov_b32 s20, -1': 'c10394be', 's_mov_b32 s20, exec_lo': '7e0394be', 's_mov_b32 vcc_lo, s7': '0703eabe', + 's_mov_b32 s20, s7': '070394be', 's_mov_b32 vcc_lo, exec_lo': '7e03eabe', + 's_and_b32 vcc_lo, s7, exec_lo': '077e6a87', 's_and_b32 s20, exec_lo, s7': '7e071487', + 's_and_b32 s20, s7, exec_lo': '077e1487', 's_mov_b64 vcc, exec': '7e04eabe', 'v_cndmask_b32 v5, v5, v6, vcc_lo': '050d0a02', + 'v_cndmask_b32 v5, v5, v6, s20': '050001d5050d5200', 's_cbranch_vccz 1': '010086bf', + 's_cmp_eq_u32 s20, 0': '148006bf', 's_and_b32 s20, vcc_lo, exec_lo': '6a7e1487', 's_mov_b32 s20, vcc_lo': '6a0394be', 's_mov_b32 s7, s20': '140387be', + 's_branch 1': '010082bf', 's_cbranch_scc1 1': '010085bf', 's_cbranch_scc1 0': '000085bf', + 's_cbranch_scc1 2': '020085bf', 's_and_b32 vcc_lo, s7, s7': '07076a87', + 'v_cndmask_b32 v5, vcc_lo, v6, vcc_lo': '050001d56a0caa01'}) + def phi(zero, write, read, between=(), inside=()): + return splice(*enter, *zero, *between, 's_cbranch_execz %d' % (len(write) + len(inside)), *write, *inside, + *leave, *read) + phi_text = lambda code: translate('A', code=code).hlsl_cs() + cnd_vcc, cnd_s = ['v_cndmask_b32 v5, v5, v6, vcc_lo'], ['v_cndmask_b32 v5, v5, v6, s20'] + for zero, write, read in ((['s_mov_b32 vcc_lo, 0'], ['s_mov_b32 vcc_lo, exec_lo'], cnd_vcc), + (['s_mov_b32 s20, 0'], ['s_mov_b32 s20, exec_lo'], cnd_s), + (['s_mov_b32 vcc_lo, 0'], ['s_and_b32 vcc_lo, s7, exec_lo'], cnd_vcc), + (['s_mov_b32 s20, 0'], ['s_and_b32 s20, s7, exec_lo'], cnd_s), + (['s_mov_b32 s20, 0'], ['s_and_b32 s20, exec_lo, s7'], cnd_s)): + text = phi_text(phi(zero, write, read)) + # the lane select reads the mask's lane bit, which the block set from exec (the model runs the block for + # every lane it models, and skips it only where exec is clear, leaving the zeroing) + assert '& 1) ? ' in text and ('vcc = (exec) & 1;' in text or 's20 = ' in text), text + # s_and with exec reads the lane bit only (the result is a lane mask): accepted + phi_text(phi(['s_mov_b32 vcc_lo, 0'], ['s_mov_b32 vcc_lo, exec_lo'], ['s_and_b32 s20, vcc_lo, exec_lo'] + cnd_vcc)) + # so does s_and_saveexec with the mask as its source (exec &= the lane bit); with the mask as its destination + # the saved exec overwrites it, a whole-mask value, and the later lane select is refused + SPLICE.update({'s_and_saveexec_b32 s22, vcc_lo': '6a3c96be', 's_and_saveexec_b32 vcc_lo, vcc_lo': '6a3ceabe'}) + phi_text(phi(['s_mov_b32 vcc_lo, 0'], ['s_mov_b32 vcc_lo, exec_lo'], ['s_and_saveexec_b32 s22, vcc_lo'] + cnd_vcc)) + refused('definition of vcc, live where the block joins', lambda: phi_text(phi( + ['s_mov_b32 vcc_lo, 0'], ['s_mov_b32 vcc_lo, exec_lo'], ['s_and_saveexec_b32 vcc_lo, vcc_lo'] + cnd_vcc))) + # Negative controls: each condition removed keeps the refusal of the live definition. + live = lambda name: 'definition of %s, live where the block joins' % name + wr, rd = ['s_mov_b32 vcc_lo, exec_lo'], cnd_vcc + for zero in (['s_mov_b32 vcc_lo, -1'], [], ['s_mov_b32 vcc_lo, s7']): # zeroing with all ones, absent, not zero + refused(live('vcc'), lambda zero=zero: phi_text(phi(zero, wr, rd))) + # a branch target between the zeroing and the branch: the path through the label did not run the zeroing + SPLICE['s_cbranch_execz 6'] = '060088bf' + refused(live('vcc'), lambda: phi_text(splice(*enter, 's_cbranch_scc1 1', 's_mov_b32 vcc_lo, 0', 's_cbranch_execz 1', + *wr, *leave, *rd))) + refused(live('vcc'), lambda: phi_text(splice(*enter, 's_mov_b32 vcc_lo, 0', 's_cbranch_scc1 0', 's_cbranch_execz 1', + *wr, *leave, *rd))) + # no zeroing of s20 at all; a block write that is an s_and without exec; the mask read as a data word + refused(live('s20'), lambda: phi_text(phi([], ['s_mov_b32 s20, exec_lo'], cnd_s))) + refused(live('vcc'), lambda: phi_text(phi(['s_mov_b32 vcc_lo, 0'], ['s_and_b32 vcc_lo, s7, s7'], rd))) + refused(live('vcc'), lambda: phi_text(phi(['s_mov_b32 vcc_lo, 0'], wr, ['v_cndmask_b32 v5, vcc_lo, v6, vcc_lo']))) + # a branch between the zeroing and the branch, even one to the join; and a branch inside the block (not straight) + refused(live('vcc'), lambda: phi_text(phi(['s_mov_b32 vcc_lo, 0'], wr, rd, between=['s_cbranch_scc1 2']))) + refused(live('vcc'), lambda: phi_text(phi(['s_mov_b32 vcc_lo, 0'], wr, rd, inside=['s_cbranch_scc1 0']))) + # a write in the block that is not from exec, or a second write, or a 64-bit write + for inside in (['s_mov_b32 vcc_lo, -1'], ['s_mov_b32 vcc_lo, s7']): + refused(live('vcc'), lambda inside=inside: phi_text(phi(['s_mov_b32 vcc_lo, 0'], wr, rd, inside=inside))) + # (a vcc_hi write does not translate at all, so the 64-bit move is the wide control) + refused(live('vcc'), lambda: phi_text(phi(['s_mov_b32 vcc_lo, 0'], ['s_mov_b64 vcc, exec'], rd))) + # whole-mask reads after the join see the other lanes' bits, which the one-lane model lacks: refused + for read in (['s_cbranch_vccz 1', 'v_mov_b32 v5, s20'] + cnd_vcc, ['s_mov_b32 s20, vcc_lo'] + cnd_vcc): + refused(live('vcc'), lambda read=read: phi_text(phi(['s_mov_b32 vcc_lo, 0'], wr, read))) + refused(live('s20'), lambda: phi_text(phi(['s_mov_b32 s20, 0'], ['s_mov_b32 s20, exec_lo'], + ['s_cmp_eq_u32 s20, 0'] + cnd_s))) + refused(live('s20'), lambda: phi_text(phi(['s_mov_b32 s20, 0'], ['s_mov_b32 s20, exec_lo'], + ['s_mov_b32 s7, s20'] + cnd_s))) # An implicit-LOD sample has no derivatives in a compute lane; the level-zero form translates. load = ('s_mov_b64 s[20:21], 0', 's_mov_b64 s[22:23], 0', 's_load_dwordx8 s[24:31], s[10:11], 0x40') sample = 'image_sample v[12:15], v[0:1], s[24:31], s[20:23] dmask:0xf dim:SQ_RSRC_IMG_2D' diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 8a76975c9..e09672e92 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1677,7 +1677,20 @@ def execz_refusals(self): straight-line block (no branch in it, none into it) when it cannot set the bit of a lane whose bit is clear (exec_stays_clear): such a lane's bit is clear on entry, so the wave leaves it clear and its exec at the join is the model's. A live definition, another exec write, a refused effect, a branch leaving the block - or a backward s_cbranch_execz is refused.""" + or a backward s_cbranch_execz is refused. + + One live definition is accepted: the i1-phi lane mask of the compiler's if-conversion, a 32-bit M (vcc_lo + or one sN) zeroed before the branch (`s_mov_b32 M, 0`) and set in the block from exec only (`s_mov_b32 M, + exec_lo`, `s_and_b32 M, X, exec_lo` in either operand order). Every write of M in the block yields a value + whose bit is 0 for any lane whose exec bit is clear there: exec can only be narrowed in the block + (exec_stays_clear has accepted each exec write), and a copy of exec, or X & exec, has that bit clear. M is 0 + at the branch on every path (nothing branches or lands between the zeroing and the branch). So for a lane + the model skips, the wave's M has that lane's bit 0 whether the wave ran the block or not, which is the + model's M (0); a lane that runs the block runs it in the model too. This holds only while M is read per + lane. A whole-mask read (s_cbranch_vccz/vccnz, s_cmp, a plain copy, a data operand) sees the other lanes' + bits, which the one-lane model does not have, so any such read of M reachable after the join, before M is + rewritten, keeps the refusal. The reads accepted are the lane select of v_cndmask, the carry-in of v_addc / + v_subb / v_add_co_ci style ops, and s_and_saveexec / s_and_b32 with exec.""" offsets = [ins[0] for ins in self.ins] index = {off: i for i, off in enumerate(offsets)} effects = [scalar_effects(name, asm) for _, _, name, asm in self.ins] @@ -1715,6 +1728,8 @@ def execz_refusals(self): # in it and no branch into it. Elsewhere an exec write is refused. straight = not any(self.ins[k][2].startswith(('s_cbranch', 's_branch')) for k in range(b + 1, t)) and \ not any(index.get(target) in range(b + 1, t) for target in targets) + cand = {k for i in range(b + 1, t) for k in (effects[i][2] - EXEC_KEYS) & live if re.fullmatch(r'vcc|s\d+', k)} + ok_masks = {k for k in cand if straight and self.phi_mask_ok(k, b, t, effects, succ, targets, index)} for i in range(b + 1, t): at, _, inner, inner_asm = self.ins[i] may = effects[i][2] @@ -1726,13 +1741,74 @@ def execz_refusals(self): reason = 'branch out of the block' elif may & EXEC_KEYS and not (straight and exec_stays_clear(inner, inner_asm, saved)): reason = 'exec write' - elif (may - EXEC_KEYS) & live: - reason = 'definition of %s, live where the block joins' % ', '.join(sorted((may - EXEC_KEYS) & live)) + elif (may - EXEC_KEYS - ok_masks) & live: + reason = 'definition of %s, live where the block joins' % ', '.join( + sorted((may - EXEC_KEYS - ok_masks) & live)) saved = exec_copies_after(inner, inner_asm, saved, may) if reason: refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason)) return refused + def phi_mask_ok(self, key, b, t, effects, succ, targets, index): + """True when lane mask `key` ('vcc' for vcc_lo, or 'sN'), live at the join t of the s_cbranch_execz at b, is + the zeroed-then-set-from-exec shape execz_refusals accepts (see its docstring): every write of it in the + block is a 32-bit move of exec_lo or an s_and with exec_lo into it alone, the last write before the branch + is `s_mov_b32 M, 0` with no branch and no branch target after it up to the branch, and after the join it is + only read per lane. The caller has checked that the block is straight-line.""" + name = 'vcc_lo' if key == 'vcc' else key + for i in range(b + 1, t): + if key not in effects[i][2]: + continue + _, ops, _ = parse(self.ins[i][3]) + base = re.sub(r'_e(32|64)$', '', self.ins[i][2]) + if not ops or ops[0] != name: + return False + if base == 's_mov_b32' and ops[1:] == ['exec_lo']: + continue + if base == 's_and_b32' and len(ops) == 3 and 'exec_lo' in ops[1:]: + continue + return False + # The zeroing: the last instruction before the branch that may write M. + z = next((k for k in range(b - 1, -1, -1) if key in effects[k][2]), None) + if z is None: + return False + _, ops, _ = parse(self.ins[z][3]) + if self.ins[z][2] != 's_mov_b32' or ops != [name, '0']: + return False + if any(self.ins[k][2].startswith(('s_cbranch', 's_branch', 's_setpc')) for k in range(z + 1, b)) or \ + any(index.get(x) in range(z + 1, b + 1) for x in targets): + return False + # After the join, until M is rewritten, every read must be per lane. + seen, todo = set(), [t] + while todo: + i = todo.pop() + if i in seen: + continue + seen.add(i) + reads, writes, _ = effects[i] + if key in reads and not self.per_lane_read(i, key): + return False + if key not in writes: + todo.extend(succ[i]) + return True + + def per_lane_read(self, i, key): + """True when instruction i reads mask `key` only as a lane select or carry, or into exec (s_and_saveexec, + s_and with exec): the lane's own bit is all it uses.""" + _, _, name, asm = self.ins[i] + base = re.sub(r'_e(32|64)$', '', name) + _, ops, _ = parse(asm) + if base.startswith(('v_cndmask', 'v_addc', 'v_subb', 'v_add_co_ci', 'v_sub_co_ci', 'v_subrev_co_ci')): + # the mask is the last operand and appears nowhere else (not as a data word, not as the destination) + return len(ops) >= 4 and key in scalar_tokens(ops[-1]) and \ + all(key not in scalar_tokens(op) for op in ops[:-1]) + if base == 's_and_saveexec_b32': + return len(ops) == 2 and key in scalar_tokens(ops[1]) and key not in scalar_tokens(ops[0]) + if base == 's_and_b32': + return len(ops) == 3 and key not in scalar_tokens(ops[0]) and any( + is_exec(scalar_tokens(op)) for op in ops[1:]) + return False + # ---- instruction translation ------------------------------------------------------------- def joined_registers(self, with_cfg=False): """{branch target: registers whose program-order symbol may not hold on every path into it}. From a634b2fabfa82267f919e3ffe7bcf8d4c971b0e2 Mon Sep 17 00:00:00 2001 From: Jess Doit <86271385+Jess-Doit@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:32:02 -0800 Subject: [PATCH 109/232] runtime: stand in for shared-exponent render and UAV textures (#1963) Desktop D3D12 refuses R9G9B9E5_SHAREDEXP (67) as a render target or typed UAV. A single-sample 2D texture or array in that format that asks for either use is now created as R11G11B10_FLOAT (26) when the adapter lacks the use for 67 and has it for 26, through the same table-driven mapping as the 16-bit packed stand-ins. The resource is tagged with 67; RTV, UAV and SRV descriptions naming 67 on it, including SRVs rebuilt for translated draws, use 26, and an optimized clear value follows the created format. Tests: selection rows and two registered controls (format 67 left alone, a UAV-only target left alone) in startup_packed_target_check, and a WARP and hardware readback of RTV and partial UAV clears through the startup device against independently encoded R11G11B10 words. Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 9 +- docs/experiments.md | 14 ++ docs/startup-runtime.md | 22 +++ src/startup_stubs/d3d12_draw.inl | 7 +- src/startup_stubs/d3d12_xs_device.cpp | 43 ++++-- src/startup_stubs/packed_target_format.h | 63 +++++--- tests/offscreen_check.cpp | 10 ++ tests/startup_packed_target_check.cpp | 57 ++++++- tests/startup_sharedexp_target.cpp | 186 +++++++++++++++++++++++ 9 files changed, 372 insertions(+), 39 deletions(-) create mode 100644 tests/startup_sharedexp_target.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f6fa2722..ecd7443eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1799,15 +1799,20 @@ target_compile_features(startup_storage_root_check PRIVATE cxx_std_17) add_test(NAME startup_storage_root COMMAND startup_storage_root_check) add_test(NAME startup_storage_root_separator_control COMMAND startup_storage_root_check --mutate separator) set_tests_properties(startup_storage_root_separator_control PROPERTIES WILL_FAIL TRUE) -# Stand-in format for 16-bit packed targets the adapter cannot use (src/startup_stubs/packed_target_format.h). +# Stand-in formats for packed targets the adapter cannot use (src/startup_stubs/packed_target_format.h). add_executable(startup_packed_target_check tests/startup_packed_target_check.cpp) target_include_directories(startup_packed_target_check PRIVATE src) target_compile_features(startup_packed_target_check PRIVATE cxx_std_17) add_test(NAME startup_packed_target COMMAND startup_packed_target_check) -foreach(mutation IN ITEMS stand-in array b565 view tag) +foreach(mutation IN ITEMS stand-in array b565 sharedexp sharedexp-uav view tag) add_test(NAME startup_packed_target_${mutation}_control COMMAND startup_packed_target_check --mutate ${mutation}) set_tests_properties(startup_packed_target_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() +target_sources(offscreen_check PRIVATE tests/startup_sharedexp_target.cpp) +foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_sharedexp_target_${adapter} COMMAND offscreen_check ${adapter} --startup-sharedexp-target) + set_tests_properties(startup_sharedexp_target_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77) +endforeach() # Static samplers built from smp and smpc manifest lines (src/startup_stubs/translated_sampler_bindings.h). add_executable(startup_sampler_comparison_check tests/startup_sampler_comparison_check.cpp) target_include_directories(startup_sampler_comparison_check PRIVATE src) diff --git a/docs/experiments.md b/docs/experiments.md index ff03adb93..2a812f3e8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -207,6 +207,20 @@ to check RGBA8 texel and alpha values, rebinding, and a mismatched 2D view on ha ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_buffer_store$' --output-on-failure ``` +## Shared-exponent target stand-in + +`startup_packed_target` checks the selection rule with synthetic format support +and verifies view compatibility and tags. `startup_sharedexp_target_*` creates +RTV/UAV textures through the startup device as one 2D texture and one 2D array. +Both name format 67 in their RTV, UAV and SRV. The fixture checks format 26 and +the format-67 tag, then compares raw texels from an RTV clear and a partial UAV +clear. The UAV colour's blue component of `996.0` stores as `992.0` in format 26 +and is exactly representable in format 67. + +```powershell +ctest --preset dev --no-tests=error -R '^(startup_(packed_target|sharedexp_target).*)$' -V +``` + ## Offline store context forwarding The fake-user runtime creates an offline store context token. Unimplemented methods receiving diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ac58a53be..d45f7816d 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -330,6 +330,28 @@ Checks: and never substituted; a packed view of a plain R8G8B8A8_UNORM texture and a B5G5R5A1 view of a B4G4R4A4 target must be refused. +## Shared-exponent render and unordered-access targets + +The packed-target mapping also covers single-sample 2D textures and arrays in +`R9G9B9E5_SHAREDEXP` (67) that request a render target, a typed UAV, or both. +When the adapter lacks one of the requested uses and supports all of them for +`R11G11B10_FLOAT` (26), the stand-in creates format 26. Sampled-only resources, +depth-stencil, multisampled textures and other dimensions keep format 67. +The format query also preserves native format 67 where it supports the requested +uses. [Microsoft Direct3D format specification](https://microsoft.github.io/DirectX-Specs/d3d/D3D12R9G9B9E5Format.html) + +The stand-in carries a format-67 tag. RTVs, UAVs and SRVs naming 67 on that +resource use format 26, including SRVs reconstructed by the translated draw. +An optimized clear value naming 67 follows the replacement format. A format-67 +view on a native format-67 texture is passed through. A format-67 view on an +incompatible texture is refused. + +Both formats use 32 bits per texel and clamp negative values to zero. +Format 26 has 6/6/5 mantissa bits with a separate exponent per channel. +Format 67 has three 9-bit mantissas with a shared exponent. Rendered and +UAV-written values can round differently. Uploads and copies in the format-67 +bit layout are not converted. + ## Descriptor heap starts that are not addresses A console executable treats the CPU start of a descriptor heap as an address. A desktop handle is diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 70019fe00..94b639dae 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2010,13 +2010,14 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (texture && x2w_startup::packed_target_format(desc.Format)) { // The view recorded from the title names a packed format: follow a stand-in texture, // and bind nothing for a texture the view does not fit (packed_target_format.h). - const auto verdict = x2w_startup::packed_view(desc.Format, texture->GetDesc().Format, x2w_startup::packed_stand_in_of(texture)); - if (verdict == x2w_startup::PackedView::stand_in) desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + const auto actual = texture->GetDesc().Format; + const auto verdict = x2w_startup::packed_view(desc.Format, actual, x2w_startup::packed_stand_in_of(texture)); + if (verdict == x2w_startup::PackedView::stand_in) desc.Format = actual; if (verdict == x2w_startup::PackedView::refused) { static LONG refused; if (first_calls(refused, 6)) log("x2w-draw %016llx srv %u: packed format %d on a texture of format %d that does not stand in for it; binding null", - tr->key, i, desc.Format, texture->GetDesc().Format); + tr->key, i, desc.Format, actual); texture = nullptr; desc = {}; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index d40aaf96f..1be331de5 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -748,7 +748,7 @@ D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) } if (desc.Alignment != 0 && desc.Alignment != 0x10000 && desc.Alignment != 0x400000) copy.Alignment = 0; copy.Format = desktop_format(desc.Format); - // A 16-bit packed target the adapter cannot render to or write as a UAV: packed_target_format.h. + // A packed target the adapter cannot render to or write as a UAV: packed_target_format.h. if (the_device && x2w_startup::packed_target_format(copy.Format)) { ID3D12Device* const device = static_cast(the_device->own().real); const DXGI_FORMAT stand_in = x2w_startup::packed_target_stand_in(copy, [device](DXGI_FORMAT format) -> UINT { @@ -767,6 +767,19 @@ D3D12_RESOURCE_DESC sanitized(const D3D12_RESOURCE_DESC& desc) return copy; } +// An optimized clear belongs to the actual texture format, including when the +// wrapper substitutes it. Preserve the caller's clear colour. +const D3D12_CLEAR_VALUE* packed_clear_value(const D3D12_CLEAR_VALUE* clear, DXGI_FORMAT requested, + DXGI_FORMAT created, D3D12_CLEAR_VALUE& copy) +{ + const auto* mapping = x2w_startup::packed_target_mapping(requested); + if (!clear || !mapping || created != mapping->replacement || desktop_format(clear->Format) != requested) + return clear; + copy = *clear; + copy.Format = created; + return © +} + bool release_retired_enabled() { static const bool on = x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED"); @@ -793,11 +806,15 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, u64 args[8] = {a, b, c, d, e, f, g, h}; for (int i = 0; i < R; ++i) args[i] = unwrap(args[i]); D3D12_RESOURCE_DESC desc_copy{}; + D3D12_CLEAR_VALUE clear_copy{}; DXGI_FORMAT requested_format = DXGI_FORMAT_UNKNOWN; if (Desc >= 0 && args[Desc]) { requested_format = desktop_format(reinterpret_cast(args[Desc])->Format); desc_copy = sanitized(*reinterpret_cast(args[Desc])); args[Desc] = reinterpret_cast(&desc_copy); + if constexpr (K == device_kind && (N == 27 || N == 29)) + args[4] = reinterpret_cast(packed_clear_value(reinterpret_cast(args[4]), + requested_format, desc_copy.Format, clear_copy)); } const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); @@ -3882,26 +3899,30 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) return 0; } // The view descriptions of slots 18-21 start with a DXGI_FORMAT. - unsigned char desc_copy[64]; + alignas(D3D12_SHADER_RESOURCE_VIEW_DESC) unsigned char desc_copy[64]; const int desc_index = N == 19 ? 2 : 1; - if (N >= 18 && N <= 21 && args[desc_index] && x2w_local::readable(reinterpret_cast(args[desc_index]), sizeof(desc_copy))) { - std::memcpy(desc_copy, reinterpret_cast(args[desc_index]), sizeof(desc_copy)); + constexpr std::size_t view_bytes = N == 18 ? sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) : + N == 19 ? sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) : + N == 20 ? sizeof(D3D12_RENDER_TARGET_VIEW_DESC) : sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC); + if (N >= 18 && N <= 21 && args[desc_index] && x2w_local::readable(reinterpret_cast(args[desc_index]), view_bytes)) { + std::memcpy(desc_copy, reinterpret_cast(args[desc_index]), view_bytes); DXGI_FORMAT format; std::memcpy(&format, desc_copy, sizeof(format)); DXGI_FORMAT mapped = desktop_format(format); if (args[0] && x2w_startup::packed_target_format(mapped)) { // A packed view follows a stand-in texture and is refused on any other texture of another format. auto* const resource = reinterpret_cast(args[0]); - const auto verdict = x2w_startup::packed_view(mapped, resource->GetDesc().Format, x2w_startup::packed_stand_in_of(resource)); + const auto actual = resource->GetDesc().Format; + const auto verdict = x2w_startup::packed_view(mapped, actual, x2w_startup::packed_stand_in_of(resource)); if (verdict == x2w_startup::PackedView::refused) { record_view(false); static LONG refused; if (first_calls(refused, 6)) log("x2w-d3d12 Device::slot%d view skipped: packed format %d on a texture of format %d that does not stand in for it", - N, mapped, resource->GetDesc().Format); + N, mapped, actual); return 0; } - if (verdict == x2w_startup::PackedView::stand_in) mapped = DXGI_FORMAT_R8G8B8A8_UNORM; + if (verdict == x2w_startup::PackedView::stand_in) mapped = actual; } if (mapped != format) { std::memcpy(desc_copy, &mapped, sizeof(mapped)); @@ -4153,7 +4174,9 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 texture.Height = surface.rows * x2w_startup::Bc16Surface::block_texels; } const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; - const auto* clear_value = static_cast(clear); + D3D12_CLEAR_VALUE clear_copy{}; + const auto* clear_value = packed_clear_value(static_cast(clear), + desktop_format(desc->Format), texture.Format, clear_copy); ID3D12Resource* created = nullptr; HRESULT texture_hr = device_of(self)->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &texture, D3D12_RESOURCE_STATE_COMMON, clear_value, @@ -4862,8 +4885,10 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP const D3D12_RESOURCE_STATES initial = props->Type == D3D12_HEAP_TYPE_UPLOAD ? D3D12_RESOURCE_STATE_GENERIC_READ : props->Type == D3D12_HEAP_TYPE_READBACK ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COMMON; + D3D12_CLEAR_VALUE clear_copy{}; + const auto* clear_value = packed_clear_value(clear, desktop_format(desc->Format), copy.Format, clear_copy); HRESULT hr = kind_for(*iid) == resource_kind - ? device_of(self)->CreateCommittedResource(props, flags, ©, initial, clear, IID_PPV_ARGS(&resource)) + ? device_of(self)->CreateCommittedResource(props, flags, ©, initial, clear_value, IID_PPV_ARGS(&resource)) : E_NOINTERFACE; bool cleared = clear != nullptr; if (FAILED(hr) && clear && kind_for(*iid) == resource_kind) { diff --git a/src/startup_stubs/packed_target_format.h b/src/startup_stubs/packed_target_format.h index ff52d8b4f..4dd8fb0d0 100644 --- a/src/startup_stubs/packed_target_format.h +++ b/src/startup_stubs/packed_target_format.h @@ -1,4 +1,4 @@ -// Experimental (docs/startup-runtime.md): a stand-in format for 16-bit packed render targets that +// Experimental (docs/startup-runtime.md): stand-in formats for packed render and unordered-access targets that // the adapter cannot use the way the description asks. // // A console executable creates B5G5R5A1_UNORM and B4G4R4A4_UNORM 2D textures as render targets, @@ -9,7 +9,12 @@ // texture is created as R8G8B8A8_UNORM and tagged with the format it stands in for; a view that // names that format on that texture is created as R8G8B8A8_UNORM. // -// Limits. The stand-in keeps 8 bits a channel where the packed format keeps 5, 6, 4 or 1; a +// R9G9B9E5_SHAREDEXP can use R11G11B10_FLOAT for a render target, a typed UAV, or both. Both +// use 32 bits per texel and clamp negative values to zero. R11G11B10_FLOAT has 6/6/5 mantissa +// bits and per-channel exponents; format 67 has three 9-bit mantissas with one shared exponent. +// Uploads and copies in the original shared-exponent bit layout are not converted. +// +// For 16-bit formats the stand-in keeps 8 bits a channel where the packed format keeps 5, 6, 4 or 1; a // B5G6R5_UNORM stand-in also has an alpha channel the packed format lacks (it samples as 1): values the // executable renders are not quantized, so a read of the target can differ from the console's in // the low bits (0.45 reads 115 here, 119 from B4G4R4A4). Texel data the executable writes or reads @@ -20,16 +25,36 @@ #include namespace x2w_startup { +struct PackedTargetMapping { + DXGI_FORMAT requested; + DXGI_FORMAT replacement; + UINT trigger_flags; +}; + +inline constexpr PackedTargetMapping packed_target_mappings[] = { + {DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}, + {DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}, + {DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}, + {DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R11G11B10_FLOAT, + UINT{D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET} | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}, +}; + +inline const PackedTargetMapping* packed_target_mapping(DXGI_FORMAT format) +{ + for (const auto& mapping : packed_target_mappings) + if (mapping.requested == format) return &mapping; + return nullptr; +} + inline bool packed_target_format(DXGI_FORMAT format) { - return format == DXGI_FORMAT_B5G5R5A1_UNORM || format == DXGI_FORMAT_B4G4R4A4_UNORM || format == DXGI_FORMAT_B5G6R5_UNORM; + return packed_target_mapping(format) != nullptr; } // The format to create a texture with. support1(format) returns the adapter's -// D3D12_FORMAT_SUPPORT1 bits for a format, or 0 when the query fails. The format changes only for -// the roles that were measured: a single-sample 2D texture or 2D array that is a render -// target, alone or with unordered access, in a packed format for which the adapter lacks one of -// those uses while R8G8B8A8_UNORM has them all. Anything else keeps its format. +// D3D12_FORMAT_SUPPORT1 bits for a format, or 0 when the query fails. For a single-sample 2D +// texture or array the mapping's trigger flags enable the check. Substitute only if the adapter +// lacks a requested target use for the original format and the replacement supports them all. // // An array of 2 to D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION slices is covered the same way: the // stand-in changes the format and nothing else, so slice count, mip count and view dimensions of @@ -38,16 +63,18 @@ inline bool packed_target_format(DXGI_FORMAT format) template DXGI_FORMAT packed_target_stand_in(const D3D12_RESOURCE_DESC& desc, Support1&& support1) { - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.DepthOrArraySize == 0 || + const auto* mapping = packed_target_mapping(desc.Format); + if (!mapping || !(desc.Flags & mapping->trigger_flags) || + desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.DepthOrArraySize == 0 || desc.DepthOrArraySize > D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION || desc.SampleDesc.Count != 1 || - !packed_target_format(desc.Format) || !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) return desc.Format; - UINT required = D3D12_FORMAT_SUPPORT1_RENDER_TARGET; + UINT required = 0; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) required |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) required |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; if ((static_cast(support1(desc.Format)) & required) == required) return desc.Format; - if ((static_cast(support1(DXGI_FORMAT_R8G8B8A8_UNORM)) & required) != required) return desc.Format; - return DXGI_FORMAT_R8G8B8A8_UNORM; + if ((static_cast(support1(mapping->replacement)) & required) != required) return desc.Format; + return mapping->replacement; } // Provenance: a texture created as a stand-in carries the format it was asked for as private data. @@ -57,7 +84,8 @@ inline constexpr GUID packed_stand_in_tag = {0x6b1d3c52, 0x8e0a, 0x4f1b, {0x9c, // Tags `created` when it is a stand-in for `requested` (the description's desktop format). inline void mark_packed_stand_in(ID3D12Resource* created, DXGI_FORMAT requested) { - if (created && packed_target_format(requested) && created->GetDesc().Format == DXGI_FORMAT_R8G8B8A8_UNORM) + const auto* mapping = packed_target_mapping(requested); + if (created && mapping && created->GetDesc().Format == mapping->replacement) created->SetPrivateData(packed_stand_in_tag, sizeof(requested), &requested); } @@ -73,16 +101,17 @@ inline DXGI_FORMAT packed_stand_in_of(ID3D12Resource* resource) enum class PackedView { unchanged, // not a packed view, or a packed view of a texture of that very format - stand_in, // a packed view of the stand-in for that format: create it as R8G8B8A8_UNORM - refused, // a packed view of any other texture; the two packed formats have no compatible format + stand_in, // use the stand-in texture's format + refused, // a packed view of a texture with no compatible format }; // What to do with a view described with view_format on a texture of resource_format that stands in // for stands_in_for (DXGI_FORMAT_UNKNOWN: an ordinary texture). inline PackedView packed_view(DXGI_FORMAT view_format, DXGI_FORMAT resource_format, DXGI_FORMAT stands_in_for) { - if (!packed_target_format(view_format)) return PackedView::unchanged; + const auto* mapping = packed_target_mapping(view_format); + if (!mapping) return PackedView::unchanged; if (stands_in_for == DXGI_FORMAT_UNKNOWN) return resource_format == view_format ? PackedView::unchanged : PackedView::refused; - return stands_in_for == view_format && resource_format == DXGI_FORMAT_R8G8B8A8_UNORM ? PackedView::stand_in : PackedView::refused; + return stands_in_for == view_format && resource_format == mapping->replacement ? PackedView::stand_in : PackedView::refused; } } // namespace x2w_startup diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 12b394a58..57f64c8cf 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1362,6 +1362,15 @@ OperationResult run_startup_image_store(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +const char* check_startup_sharedexp_target(ID3D12Device* device, ID3D12InfoQueue* messages); + +OperationResult run_startup_sharedexp_target(const OperationContext& ctx) +{ + if (const char* reason = check_startup_sharedexp_target(ctx.device, ctx.messages)) + return {OutcomeKind::skip, reason}; + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_startup_packed_position(const OperationContext& ctx) { constexpr UINT width = 13, height = 7; @@ -1580,6 +1589,7 @@ const OperationSpec kOperations[] = { {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, + {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, {"--startup-flat-param", 6, 6, nullptr, kNoGate, run_startup_flat_param}, {"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words}, {"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words}, diff --git a/tests/startup_packed_target_check.cpp b/tests/startup_packed_target_check.cpp index 5cbf361d3..fb23070b7 100644 --- a/tests/startup_packed_target_check.cpp +++ b/tests/startup_packed_target_check.cpp @@ -1,8 +1,10 @@ // Checks src/startup_stubs/packed_target_format.h without a device, against adapters described // by their format-support bits. -// --mutate stand-in | array | b565 | view | tag: the helper's answer perturbed the way a wrong helper -// would answer (a stand-in in another format, arrays left alone as before, B5G6R5_UNORM left alone -// as before, the view format of the stand-in kept packed, the stand-in's tag read back as no tag); +// --mutate stand-in | array | b565 | sharedexp | sharedexp-uav | view | tag: the helper's answer +// perturbed the way a wrong helper would answer (a stand-in in another format, arrays left alone as +// before, B5G6R5_UNORM left alone as before, R9G9B9E5_SHAREDEXP left alone as before, a UAV-only +// R9G9B9E5_SHAREDEXP texture left alone as under a render-target-only trigger, the view format of the +// stand-in kept packed, the stand-in's tag read back as no tag); // each must fail on the rows it concerns. #include "startup_stubs/packed_target_format.h" @@ -18,8 +20,11 @@ constexpr UINT rt = D3D12_FORMAT_SUPPORT1_RENDER_TARGET, uav = D3D12_FORMAT_SUPP struct Adapter { UINT b5g5r5a1, b4g4r4a4, rgba8, b5g6r5; + UINT sharedexp = 0, hdr = 0; UINT operator()(DXGI_FORMAT format) const { + if (format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) return sharedexp; + if (format == DXGI_FORMAT_R11G11B10_FLOAT) return hdr; return format == DXGI_FORMAT_B5G5R5A1_UNORM ? b5g5r5a1 : format == DXGI_FORMAT_B4G4R4A4_UNORM ? b4g4r4a4 : format == DXGI_FORMAT_B5G6R5_UNORM ? b5g6r5 : format == DXGI_FORMAT_R8G8B8A8_UNORM ? rgba8 : rt | uav; } @@ -32,6 +37,10 @@ DXGI_FORMAT stand_in(const D3D12_RESOURCE_DESC& desc, const Adapter& adapter) if (!std::strcmp(mutation, "stand-in") && got == DXGI_FORMAT_R8G8B8A8_UNORM) return DXGI_FORMAT_B8G8R8A8_UNORM; if (!std::strcmp(mutation, "array") && desc.DepthOrArraySize != 1) return desc.Format; if (!std::strcmp(mutation, "b565") && desc.Format == DXGI_FORMAT_B5G6R5_UNORM) return desc.Format; + if (!std::strcmp(mutation, "sharedexp") && desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) return desc.Format; + if (!std::strcmp(mutation, "sharedexp-uav") && desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && + !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) + return desc.Format; return got; } @@ -162,7 +171,7 @@ int main(int argc, char** argv) { if (argc == 3 && !std::strcmp(argv[1], "--mutate")) mutation = argv[2]; else if (argc != 1) { - std::printf("usage: startup_packed_target_check [--mutate stand-in|array|b565|view|tag]\n"); + std::printf("usage: startup_packed_target_check [--mutate stand-in|array|b565|sharedexp|sharedexp-uav|view|tag]\n"); return 2; } const auto packed_target_stand_in = stand_in; @@ -245,6 +254,35 @@ int main(int argc, char** argv) shaped.DepthOrArraySize = 6; expect("rgba8 RT array", packed_target_stand_in(shaped, none), rgba); + constexpr auto sharedexp = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; + constexpr auto hdr = DXGI_FORMAT_R11G11B10_FLOAT; + constexpr UINT sample = D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE; + const Adapter sharedexp_missing{0, 0, rt | uav, 0, sample, rt | uav}; + const Adapter sharedexp_rt_only{0, 0, rt | uav, 0, sample | rt, rt | uav}; + const Adapter sharedexp_supported{0, 0, rt | uav, 0, sample | rt | uav, rt | uav}; + const Adapter hdr_no_rt{0, 0, rt | uav, 0, sample, uav}; + const Adapter hdr_no_uav{0, 0, rt | uav, 0, sample, rt}; + expect("shared exponent RT only", packed_target_stand_in(texture(sharedexp, RT), hdr_no_uav), hdr); + expect("shared exponent UAV only", packed_target_stand_in(texture(sharedexp, UA), hdr_no_rt), hdr); + expect("shared exponent RT|UAV", packed_target_stand_in(texture(sharedexp, RT | UA), sharedexp_missing), hdr); + expect("shared exponent RT supported", packed_target_stand_in(texture(sharedexp, RT), sharedexp_rt_only), sharedexp); + expect("shared exponent RT supported, UAV missing", + packed_target_stand_in(texture(sharedexp, RT | UA), sharedexp_rt_only), hdr); + expect("shared exponent RT|UAV supported", + packed_target_stand_in(texture(sharedexp, RT | UA), sharedexp_supported), sharedexp); + expect("shared exponent RT|UAV replacement missing RT", packed_target_stand_in(texture(sharedexp, RT | UA), hdr_no_rt), sharedexp); + expect("shared exponent RT|UAV replacement missing UAV", packed_target_stand_in(texture(sharedexp, RT | UA), hdr_no_uav), sharedexp); + expect("shared exponent sampled only", packed_target_stand_in(texture(sharedexp, 0), sharedexp_missing), sharedexp); + expect("shared exponent depth stencil", + packed_target_stand_in(texture(sharedexp, RT | UA | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), sharedexp_missing), sharedexp); + expect("shared exponent 3D", packed_target_stand_in(texture(sharedexp, RT | UA, D3D12_RESOURCE_DIMENSION_TEXTURE3D), + sharedexp_missing), sharedexp); + shaped = texture(sharedexp, RT | UA); + shaped.DepthOrArraySize = 6; + expect("shared exponent RT|UAV array", packed_target_stand_in(shaped, sharedexp_missing), hdr); + shaped.SampleDesc.Count = 4; + expect("shared exponent multisampled", packed_target_stand_in(shaped, sharedexp_missing), sharedexp); + // Views: a packed view becomes RGBA8 only on the stand-in for that very format. using x2w_startup::PackedView; constexpr DXGI_FORMAT plain = DXGI_FORMAT_UNKNOWN; @@ -269,9 +307,12 @@ int main(int argc, char** argv) // back that packed format and its packed view becomes the stand-in; a texture created in the // packed format itself carries no tag, so its own view is unchanged; an untagged R8G8B8A8_UNORM // texture refuses the packed view. - for (const DXGI_FORMAT packed : {b5, b4, b565}) { + view("shared exponent view of a tagged rgba8 texture", packed_view(sharedexp, rgba, sharedexp), PackedView::refused); + view("shared exponent view of another stand-in", packed_view(sharedexp, rgba, b5), PackedView::refused); + for (const DXGI_FORMAT packed : {b5, b4, b565, sharedexp}) { + const auto replacement = packed == sharedexp ? hdr : rgba; char name[64]; - Texture stand_in_texture(rgba); + Texture stand_in_texture(replacement); x2w_startup::mark_packed_stand_in(&stand_in_texture, packed); std::snprintf(name, sizeof(name), "format %d stand-in tag", packed); expect(name, packed_stand_in_of(&stand_in_texture), packed); @@ -283,8 +324,8 @@ int main(int argc, char** argv) expect(name, packed_stand_in_of(&described), plain); std::snprintf(name, sizeof(name), "format %d view of a texture created as described", packed); view(name, packed_view(packed, described.GetDesc().Format, packed_stand_in_of(&described)), PackedView::unchanged); - Texture untagged(rgba); - std::snprintf(name, sizeof(name), "format %d view of an untagged rgba8 texture", packed); + Texture untagged(replacement); + std::snprintf(name, sizeof(name), "format %d view of an untagged replacement texture", packed); view(name, packed_view(packed, untagged.GetDesc().Format, packed_stand_in_of(&untagged)), PackedView::refused); } Texture b4_stand_in(rgba); diff --git a/tests/startup_sharedexp_target.cpp b/tests/startup_sharedexp_target.cpp new file mode 100644 index 000000000..97edcdd63 --- /dev/null +++ b/tests/startup_sharedexp_target.cpp @@ -0,0 +1,186 @@ +// Create the shared-exponent target and views through the startup device, then +// clear and read the backing texture on the desktop device. +#include "desktop_gpu.h" +#include "startup_stubs/packed_target_format.h" +#include "startup_stubs/placed_build.h" + +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr auto sharedexp = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; +constexpr auto hdr = DXGI_FORMAT_R11G11B10_FLOAT; +constexpr UINT width = 4, height = 2; +constexpr float rt_color[]{0.5f, 1.0f, 2.0f, 1.0f}; +constexpr float uav_color[]{-1.0f, 0.5f, 996.0f, 1.0f}; + +// The fixture's positive inputs are finite normal values away from rounding ties. +// The biased exponent is 15 for values in [1, 2); quantize the significand at +// that exponent, then pack the red, green and blue fields into a little-endian word. +std::uint32_t encode_channel(float value, int mantissa_bits) +{ + if (value <= 0.0f) return 0; + int exponent; + const double significand = std::frexp(value, &exponent); + const auto rounded = static_cast(std::round(std::ldexp(significand, mantissa_bits + 1))); + return ((exponent + 14u) << mantissa_bits) + rounded - (1u << mantissa_bits); +} + +std::uint32_t encode_rgb(const float (&color)[4]) +{ + return encode_channel(color[0], 6) | (encode_channel(color[1], 6) << 11) | + (encode_channel(color[2], 5) << 22); +} + +ComPtr native_texture(ID3D12Device* device, ID3D12Device* guest, ID3D12Resource* texture) +{ + // The device wrapper unwraps objects passed to SetPrivateDataInterface. + constexpr GUID key{0x029d497b, 0xc94c, 0x42ca, {0xa1, 0xad, 0x0e, 0xe3, 0xa5, 0xd8, 0x66, 0xd1}}; + check(guest->SetPrivateDataInterface(key, texture), "Publish underlying texture"); + ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + check(guest->SetPrivateDataInterface(key, nullptr), "Clear underlying texture"); + check(read, "Retrieve underlying texture"); + ComPtr result; + check(stored.As(&result), "Query underlying texture"); + return result; +} + +ComPtr heap(ID3D12Device* device, D3D12_DESCRIPTOR_HEAP_TYPE type, UINT count, + D3D12_DESCRIPTOR_HEAP_FLAGS flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE) +{ + const D3D12_DESCRIPTOR_HEAP_DESC desc{type, count, flags}; + ComPtr result; + check(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&result)), "Create fixture descriptor heap"); + return result; +} + +template +void create_view(ID3D12InfoQueue* messages, Create&& create, const char* stage) +{ + const UINT64 before = messages ? messages->GetNumStoredMessagesAllowedByRetrievalFilter() : 0; + create(); + if (messages && messages->GetNumStoredMessagesAllowedByRetrievalFilter() != before) + throw std::runtime_error(stage); // offscreen_check prints the debug diagnostics +} + +void check_texture(ID3D12Device* device, ID3D12Device* guest, ID3D12InfoQueue* messages, UINT16 slices) +{ + const D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_DEFAULT}; + const auto flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, slices, 1, sharedexp, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, flags}; + const D3D12_CLEAR_VALUE clear{sharedexp, {rt_color[0], rt_color[1], rt_color[2], rt_color[3]}}; + ComPtr wrapped; + check(guest->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_RENDER_TARGET, + &clear, IID_PPV_ARGS(&wrapped)), "Create shared-exponent RT|UAV texture"); + const auto texture = native_texture(device, guest, wrapped.Get()); + const auto actual = texture->GetDesc(); + const auto tag = x2w_startup::packed_stand_in_of(wrapped.Get()); + if (actual.Format != hdr || actual.Flags != flags || actual.DepthOrArraySize != slices || tag != sharedexp) + throw std::runtime_error("Shared-exponent resource shape, actual format or tag differs"); + const auto targets = heap(device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1); + const auto views = heap(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2); + const auto shader_views = heap(device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE); + const auto rtv_handle = targets->GetCPUDescriptorHandleForHeapStart(); + const auto uav_handle = views->GetCPUDescriptorHandleForHeapStart(); + const auto shader_cpu = shader_views->GetCPUDescriptorHandleForHeapStart(); + const auto shader_gpu = shader_views->GetGPUDescriptorHandleForHeapStart(); + const D3D12_CPU_DESCRIPTOR_HANDLE srv_handle{ + uav_handle.ptr + device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)}; + + const bool array = slices > 1; + D3D12_RENDER_TARGET_VIEW_DESC rtv{sharedexp, array ? D3D12_RTV_DIMENSION_TEXTURE2DARRAY : D3D12_RTV_DIMENSION_TEXTURE2D}; + D3D12_UNORDERED_ACCESS_VIEW_DESC uav{sharedexp, array ? D3D12_UAV_DIMENSION_TEXTURE2DARRAY : D3D12_UAV_DIMENSION_TEXTURE2D}; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{sharedexp, array ? D3D12_SRV_DIMENSION_TEXTURE2DARRAY : D3D12_SRV_DIMENSION_TEXTURE2D, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + srv.Texture2D.MipLevels = 1; + if (array) { + rtv.Texture2DArray.ArraySize = slices; + uav.Texture2DArray.ArraySize = slices; + srv.Texture2DArray.ArraySize = slices; + } + create_view(messages, [&] { guest->CreateRenderTargetView(wrapped.Get(), &rtv, rtv_handle); }, + "Create format-67 RTV reported a debug diagnostic"); + create_view(messages, [&] { + guest->CreateUnorderedAccessView(wrapped.Get(), nullptr, &uav, uav_handle); + guest->CreateUnorderedAccessView(wrapped.Get(), nullptr, &uav, shader_cpu); + }, "Create format-67 UAV reported a debug diagnostic"); + create_view(messages, [&] { guest->CreateShaderResourceView(wrapped.Get(), &srv, srv_handle); }, + "Create format-67 SRV reported a debug diagnostic"); + + std::array footprints{}; + UINT64 bytes; + device->GetCopyableFootprints(&actual, 0, slices, 0, footprints.data(), nullptr, nullptr, &bytes); + auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands commands(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + auto* list = commands.list.Get(); + list->ClearRenderTargetView(rtv_handle, rt_color, 0, nullptr); + transition(list, texture.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* const bound[] = {shader_views.Get()}; + list->SetDescriptorHeaps(1, bound); + const D3D12_RECT right{width / 2, 0, width, height}; + list->ClearUnorderedAccessViewFloat(shader_gpu, uav_handle, texture.Get(), uav_color, 1, &right); + transition(list, texture.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + for (UINT slice = 0; slice < slices; ++slice) { + D3D12_TEXTURE_COPY_LOCATION dst{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + dst.PlacedFootprint = footprints[slice]; + D3D12_TEXTURE_COPY_LOCATION src{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + src.SubresourceIndex = slice; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + } + commands.submit_and_wait(device); + + void* data = nullptr; + const D3D12_RANGE range{0, static_cast(bytes)}, no_writes{}; + check(readback->Map(0, &range, &data), "Map shared-exponent target readback"); + const auto rt_word = encode_rgb(rt_color), uav_word = encode_rgb(uav_color); + for (UINT slice = 0; slice < slices; ++slice) { + const auto& footprint = footprints[slice]; + for (UINT y = 0; y < height; ++y) { + const auto* row = static_cast(data) + footprint.Offset + y * footprint.Footprint.RowPitch; + for (UINT x = 0; x < width; ++x) { + std::uint32_t word; + std::memcpy(&word, row + x * sizeof(word), sizeof(word)); + const auto expected = x < width / 2 ? rt_word : uav_word; + if (word != expected) { + readback->Unmap(0, &no_writes); + std::fprintf(stderr, "slice %u (%u,%u): expected %08x, got %08x\n", slice, x, y, expected, word); + throw std::runtime_error("Shared-exponent stand-in readback differs"); + } + } + } + } + readback->Unmap(0, &no_writes); + std::printf("slices=%u format=%d tag=%d rtv=%08x uav=%08x words=%u\n", + slices, actual.Format, tag, rt_word, uav_word, width * height * slices); +} +} // namespace + +const char* check_startup_sharedexp_target(ID3D12Device* device, ID3D12InfoQueue* messages) +{ + constexpr UINT uses = D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; + D3D12_FEATURE_DATA_FORMAT_SUPPORT original{sharedexp}, fallback{hdr}; + check(check_feature(device, D3D12_FEATURE_FORMAT_SUPPORT, &original, sizeof(original)), "Query format 67"); + check(check_feature(device, D3D12_FEATURE_FORMAT_SUPPORT, &fallback, sizeof(fallback)), "Query format 26"); + std::printf("support1_67=0x%x support1_26=0x%x support2_26=0x%x\n", original.Support1, fallback.Support1, fallback.Support2); + if ((original.Support1 & uses) == uses) return "adapter supports native format-67 RT and UAV views"; + if ((fallback.Support1 & uses) != uses || !(fallback.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE)) + return "adapter lacks format-26 render-target or typed UAV stores"; + + device->AddRef(); + void* wrapped = nullptr; + x2w_startup::attach_device(device, &wrapped); + ComPtr guest; + guest.Attach(static_cast(wrapped)); + check_texture(device, guest.Get(), messages, 1); + check_texture(device, guest.Get(), messages, 2); + return nullptr; +} From 267b4be979a85a7a1e2c4fa21545c2d142d11e78 Mon Sep 17 00:00:00 2001 From: Roan System Date: Wed, 25 Nov 2026 20:33:36 +0100 Subject: [PATCH 110/232] tooling: add bit-operation generators to the CPU fuzz test (#1784) Adds --area bits and the cpu_aot_fuzz_bits CTest (seed 0xB175, 40 exports): BT/BTS/BTR/BTC on register and memory bases, POPCNT/LZCNT/TZCNT, BSF/BSR with zero sources, 32- and 64-bit BSWAP and SHL/SHR/SAR by an immediate, with flags read only under the conditions the translator defines. Six refused controls cover the documented limits, a CPUID probe skips hosts without POPCNT, BMI1 and ABM, and a planted fault that swaps BTS and BTR must mismatch native. The existing areas' emit output and translations are unchanged. --- CMakeLists.txt | 42 ++++++++++ docs/experiments.md | 2 + tools/fuzz_cpu.py | 187 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 227 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ecd7443eb..c9c80cb7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4340,6 +4340,48 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "$" "${cpu_fuzz_x87_o2}" --area x87 --mutant "$") set_tests_properties(cpu_aot_fuzz_x87 PROPERTIES TIMEOUT 60) + + # Bit tests, counts, scans, byte swaps and immediate shifts with their defined flags, with BTS and BTR swapped planted. + set(CPU_FUZZ_BITS_SEED "0xB175" CACHE STRING "Seed for the CPU differential fuzz bit-operation test") + set(CPU_FUZZ_BITS_FUNCTIONS "40" CACHE STRING "Number of exported functions in the CPU differential fuzz bit-operation test") + set(cpu_fuzz_bits_asm "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_bits.asm") + set(cpu_fuzz_bits_def "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_bits.def") + add_custom_command(OUTPUT "${cpu_fuzz_bits_asm}" "${cpu_fuzz_bits_def}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" emit + "${CPU_FUZZ_BITS_SEED}" "${CPU_FUZZ_BITS_FUNCTIONS}" "${cpu_fuzz_bits_asm}" + "${cpu_fuzz_bits_def}" --area bits + DEPENDS tools/fuzz_cpu.py VERBATIM) + add_library(cpu_fuzz_bits SHARED "${cpu_fuzz_bits_asm}" "${cpu_fuzz_bits_def}") + set_target_properties(cpu_fuzz_bits PROPERTIES LINKER_LANGUAGE CXX) + target_link_options(cpu_fuzz_bits PRIVATE /NOENTRY /NODEFAULTLIB /INCREMENTAL:NO /OPT:NOICF) + set(cpu_fuzz_bits_lifted "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_bits_lifted.cpp") + set(cpu_fuzz_bits_mutant "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_bits_mutant.cpp") + foreach(variant lifted mutant) + set(mutant_flag "") + if(variant STREQUAL "mutant") + set(mutant_flag "--mutant") + endif() + add_custom_command(OUTPUT "${cpu_fuzz_bits_${variant}}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" translate + "${CPU_FUZZ_BITS_SEED}" "${CPU_FUZZ_BITS_FUNCTIONS}" "$" + "${cpu_fuzz_bits_${variant}}" --area bits ${mutant_flag} + DEPENDS cpu_fuzz_bits tools/fuzz_cpu.py tools/cpu_switch_aot.py tools/cpu_leaf_aot.py + tools/cpu_call_aot.py tools/cpu_ranges.py VERBATIM) + add_library(cpu_fuzz_bits_${variant} SHARED "${cpu_fuzz_bits_${variant}}") + target_compile_features(cpu_fuzz_bits_${variant} PRIVATE cxx_std_20) + endforeach() + set(cpu_fuzz_bits_o2 "${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_bits_lifted_o2.dll") + add_custom_command(OUTPUT "${cpu_fuzz_bits_o2}" + COMMAND "${CMAKE_CXX_COMPILER}" /nologo /O2 /W4 /LD "${cpu_fuzz_bits_lifted}" + "/Fo${CMAKE_CURRENT_BINARY_DIR}/cpu_fuzz_bits_lifted_o2.obj" "/Fe${cpu_fuzz_bits_o2}" + DEPENDS "${cpu_fuzz_bits_lifted}" VERBATIM) + add_custom_target(cpu_fuzz_bits_lifted_o2 ALL DEPENDS "${cpu_fuzz_bits_o2}") + add_test(NAME cpu_aot_fuzz_bits COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tools/fuzz_cpu.py" check "${CPU_FUZZ_BITS_SEED}" "${CPU_FUZZ_BITS_FUNCTIONS}" + "$" "$" "${cpu_fuzz_bits_o2}" + --area bits --mutant "$") + # A host without POPCNT, BMI1 or ABM cannot run the native exports as the translation describes them. + set_tests_properties(cpu_aot_fuzz_bits PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) cpu_asm_fixture(cpu_switch_addr32 switch_addr32) cpu_asm_fixture(cpu_switch_strings switch_strings) cpu_asm_fixture(cpu_string_probe string_probe) diff --git a/docs/experiments.md b/docs/experiments.md index 2a812f3e8..1561335e0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3153,6 +3153,8 @@ Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_smoke$' -V`. `CPU_FUZ `cpu_aot_fuzz_x87` (`--area x87`) covers the x87 profile of the shared integer lowering ([`ffx_version_query.lower`](../tools/ffx_version_query.py) with `x87=True`, documented in [`x87_lower.py`](../tools/x87_lower.py)) from its own seed, so the areas above are unchanged (their `emit` output and translations are byte-identical to the previous revision). The area translates each export as the `cpu_aot_x87_*` fixtures do, one `lower` call per function range with the x87 helpers of `x87_soft.h`, into `lifted_(x, y, out)` like the other areas. Every export is straight-line code. It first writes its operands to the output buffer: x at offset 0 and y at 8 (read as m16, m32 and m64 integers and as m32 and m64 floats), and two m80 values, x with the top word of y as sign and exponent at 16 and y with the top word of x at 32. `FNSTCW` then stores the control word at 48. The lowering fixes that word at 0x027F, so a native run under another control word would mismatch there. The body loads (`FLD` m32, m64, m80 and ST(i), `FILD` m16, m32 and m64, and `FLD1`, `FLDZ`, `FLDPI`, `FLDL2T`, `FLDL2E`, `FLDLG2` and `FLDLN2`), computes (`FADD`, `FSUB`, `FSUBR`, `FMUL`, `FDIV` and `FDIVR` with an m32 or m64 operand, with ST(0), ST(i), with ST(i), ST(0) and in their popping forms, the `FI` forms with an m16 or m32 integer, `FCHS`, `FABS`, `FSQRT`, `FRNDINT` and `FXCH`), stores (`FST` and `FSTP` to m32, m64, m80 and ST(i), `FIST`, `FISTP` and `FISTTP`), compares with `FCOMI`, `FCOMIP`, `FUCOMI` or `FUCOMIP` followed by `SETcc`, compares into the status word (`FCOM`, `FCOMP`, `FCOMPP`, `FUCOM`, `FUCOMP`, `FUCOMPP` with ST(i) or memory, `FTST`, `FICOM`, `FICOMP`, `FXAM`) followed by `FNSTSW AX` and either `SAHF` and `SETcc` or `AND AH, 45h` and a byte store of C0, C2 and C3, and moves with `FCMOVcc` after an `FCOMI`, `SAHF` or `CMP RCX, RDX`. Every result goes to output bytes 64 to 255, and RAX is the first result qword. The generator tracks the stack depth, so every instruction finds the registers it reads occupied, no push exceeds eight and the stack is empty at the `RET`. It reads PF (`SETP`, `SETNP`, `FCMOVU`, `FCMOVNU`) only after `FCOMI` or `SAHF`, and never C1 or the exception flags, which the profile leaves unknown. Values are not restricted: the check inputs are the 17 x 17 combinations of 17 operand words (doubles at every edge, including denormals, infinities, a quiet NaN with a payload and a signalling NaN, words whose halves are two edge floats, and integer edges), then normal m80 values near 1 and random bits, so denormals, NaN payloads, integer-store overflow and the m80 encodings that the processor treats as unsupported all occur; `x87_soft.h` models them bit for bit and nothing is masked. Four negative controls in the same DLL are translated one at a time, and the test fails unless each is refused for its own reason: nine pushes (`x87 stack overflow`), a store from an empty stack (`x87 stack underflow`), a return with a value on the stack (`x87 stack not empty at return`) and `FINCSTP` (`unsupported x87 operation`). The planted translator fault, `--mutant` (`subr_as_sub`), lowers `FSUBR` and `FSUBRP` like `FSUB` and `FSUBP`, so a reversed subtraction gives the negated difference; the code stays straight-line, and the test fails unless that build differs from native. At the default seed `0x8087` the 40 exports hold 688 x87 instructions: 192 loads, 113 arithmetic operations, 57 unary operations and exchanges, 146 stores, 28 `FCOMI`-family and 47 status-word compares, and 18 `FCMOVcc`. Measured on Windows 11 build 26300 with MSVC 19.51 (Visual Studio Build Tools, toolset 14.51) and ML64 14.51: 25,040 native, default and `/O2` comparisons matched in 1.3 to 3.2 s in the `dev` and `release` presets, the four controls were refused, and the planted fault differed in 675 of 12,520 calls, in 7 of the 10 exports that use `FSUBR` or `FSUBRP`. Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the reproduction command. `CPU_FUZZ_X87_SEED` and `CPU_FUZZ_X87_FUNCTIONS` select a longer run, for example `cmake --preset dev -DCPU_FUZZ_X87_SEED=0xBEEF -DCPU_FUZZ_X87_FUNCTIONS=160`, then `cmake --build --preset dev --target cpu_fuzz_x87_lifted cpu_fuzz_x87_lifted_o2 cpu_fuzz_x87_mutant` and the `ctest` command below. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 160 exports each made 100,160 comparisons per seed in about 4 s, with no refusal and no mismatch; the planted fault differed in 4,518, 2,959, 4,679 and 4,686 of 50,080 calls. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_x87$' -V`. The generator does not use `FXTRACT`, `FSCALE`, the checked entry's `FLDCW`, `FNINIT`, `FPREM`, `FPREM1`, `FBLD` and `FBSTP`, `FNSTSW` m16, `FFREE`, `FFREEP`, branches or calls with x87 state, or a caller value on the x87 stack (the `cpu_aot_x87_*` fixtures cover those through `tests/cpu/x87_harness.asm`). +`cpu_aot_fuzz_bits` (`--area bits`) covers the bit operations of the shared [translator](../tools/cpu_switch_aot.py) from its own seed, so the areas above are unchanged (their `emit` output and translations are byte-identical to the previous revision). Each export is a straight-line run of 8 to 10 steps with every kind of step at least once: `BT`, `BTS`, `BTR` or `BTC` on a 16-, 32- or 64-bit register base with an immediate or register offset; the same on a memory base with an immediate offset; `POPCNT`, `LZCNT` or `TZCNT`, and `BSF` or `BSR`, from a register or memory source; a 32- or 64-bit `BSWAP`, some of them between a bit test and its readers; and `SHL`, `SHR` or `SAR` of an 8- to 64-bit register by an immediate from 1 to the operand width minus 1. About one immediate bit offset in five (21 of 123 at the default seed) is past the operand width, which the processor and the translation both take modulo the width. RAX, R9 and R10 carry values from step to step. Sources are the arguments, R11 masked or shifted from one of them so that it is often zero, or a 32-byte bit string at output offset 128 that is written from the arguments and changed by the memory bit tests. Each flag producer is read by one to three of `SETcc` into the output buffer, `CMOVcc` into a carried register and a forward `Jcc` around an update of one, only under the conditions the translator defines for it: B and AE after a bit test, E and NE after a bit scan, B, AE, E, NE, BE and A after `LZCNT` and `TZCNT`, all sixteen after `POPCNT` and a shift by 1, and all but O, NO, L, GE, LE and G after a larger shift. A scan of a zero source leaves its destination as it was, upper half included, and the step stores that register. The 40 default exports at seed `0xB175` hold 154 bit tests (66 on memory, 31 with a register offset, 21 with an immediate offset past the width), 57 counts, 54 scans, 57 byte swaps and 63 shifts. Replaying their sources on the 313 inputs, 5,515 of 16,902 scans and 2,982 of 10,016 `LZCNT` and `TZCNT` calls have a zero source. The test makes 25,040 native, default and `/O2` comparisons of RAX and the 256-byte output buffer in about 0.8 s. Six controls must be refused for the documented reason: a register bit offset into memory through a 32-bit base register (`BT` on `[R8D]`), `SETZ` after `BT`, `SETS` after `LZCNT`, `SETC` after `BSF`, `SETC` after an 8-bit `SHL` by 8 and `SETO` after `SHR` by 3. A native export reads CPUID first, and the test is skipped (exit 77) on a host without POPCNT, BMI1 and ABM, as `cpu_aot_switch_bit_counts` is. The planted translator fault, `--mutant` (`set_reset_swap`), makes `BTS` clear the selected bit and `BTR` set it, while CF, `BT` and `BTC` stay right; the test fails unless that build differs from native. At the default seed it differed in 11,581 of 12,520 calls, in 37 of the 40 exports (the other three have no `BTS` or `BTR`). Passing the clean translation as `--mutant` fails with `the planted translator fault was not detected`, and passing the mutant as the translation fails at the first mismatch with the export's MASM and the reproduction command. `CPU_FUZZ_BITS_SEED` and `CPU_FUZZ_BITS_FUNCTIONS` select a longer run. Seeds `0x1`, `0x2`, `0xBEEF` and `0xCCD1` at 128 exports each made 80,128 comparisons per seed in about 1.9 s, with no refusal and no mismatch, and the planted fault differed in 33,178 to 35,056 of 40,064 calls. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_fuzz_bits$' -V`. The generator does not use 16-bit `BSWAP` (refused, its result is undefined), shifts by CL, rotates as flag producers, `SHLD` and `SHRD`, or the BMI1 and BMI2 forms beyond `LZCNT` and `TZCNT`. + ## Mesh draw fallback The bounded mesh translator can emit `cs_6_0` entry `main` and `vs_6_0` entry diff --git a/tools/fuzz_cpu.py b/tools/fuzz_cpu.py index 7d86ed926..36823e02e 100644 --- a/tools/fuzz_cpu.py +++ b/tools/fuzz_cpu.py @@ -36,6 +36,9 @@ class Function: narrow: bool = False # A scalar float export: ':' as cpu_sse_aot names it, for example 'd:ffq'. None for three 64-bit integer slots. signature: str | None = None + # A native probe of the host processor: it is exported but neither translated nor compared, and the check + # calls it first and skips the test (exit 77) unless the RAX it returns has every bit of this mask set. + host_features: int | None = None def asm(self): head = [f" {line}" for line in self.prolog] @@ -1792,11 +1795,165 @@ def x87_translate(image, names): return "".join(parts), None +# Bit operations: straight-line leaf functions made of steps, each a bit test, a bit count, a bit scan, a byte +# swap or a shift by an immediate, whose flags are read only under the conditions that cpu_switch_aot defines +# for that producer, through SETcc, CMOVcc or a short forward Jcc. RAX, R9 and R10 carry values from step to +# step; RCX and RDX keep the arguments and R11 holds a source prepared from them, so that zero sources come +# from the zero inputs. The output buffer keeps one qword per step from 0, a 32-byte bit string written from +# the arguments at 128 that memory operands use, the SETcc bytes from 192 and the final R9, R10 and R11 at 224. +BITS_TESTS = ("bt", "bts", "btr", "btc") +BITS_COUNTS = ("popcnt", "lzcnt", "tzcnt") +BITS_SCANS = ("bsf", "bsr") +BITS_SHIFTS = ("shl", "shr", "sar") +BITS_KINDS = ("test_register", "test_memory", "count", "scan", "swap", "shift") +BITS_CARRIED = ("rax", "r9", "r10") +BITS_SOURCES = ("rcx", "rdx", "r11") +BITS_MEMORY, BITS_MEMORY_SIZE, BITS_FLAGS, BITS_FINAL = 128, 32, 192, 224 +BITS_STEPS = (8, 9, 10) +# The conditions each producer defines: CF only after a bit test, ZF only after a bit scan, CF and ZF after +# LZCNT and TZCNT, all of them after POPCNT and a shift by 1, and all but those that read OF after a larger shift. +BITS_CONDITIONS = { + "test": ("b", "ae"), "scan": ("e", "ne"), "lzcnt": ("b", "ae", "e", "ne", "be", "a"), + "tzcnt": ("b", "ae", "e", "ne", "be", "a"), "popcnt": CMP_CONDITIONS, "shift1": CMP_CONDITIONS, + "shift": ("e", "ne", "s", "ns", "p", "np", "b", "ae", "be", "a"), +} +# CPUID bits that the host probe returns: POPCNT (bit 0), BMI1 for TZCNT (bit 1) and ABM for LZCNT (bit 2). +# Without them the native exports would run LZCNT and TZCNT as BSR and BSF, or fault on POPCNT. +BITS_HOST_FEATURES = 0b111 +# Negative controls: a body that the translator must refuse, and the reason it must give. +BITS_CONTROLS = { + # A register bit offset into memory through a 32-bit base: the translator has no wrap proof for that address. + "bit_string": (["bt DWORD PTR [r8d], ecx", "setc al"], "unsupported bit-string operand"), + "test_zero": (["bt rcx, 5", "setz al"], "only CF is defined after BT"), + "count_sign": (["lzcnt rdx, rcx", "sets al"], "OF, SF and PF are undefined after LZCNT"), + "scan_carry": (["bsf rdx, rcx", "setc al"], "only ZF is defined after BSF"), + "shift_width": (["mov eax, ecx", "shl al, 8", "setc al"], "CF is undefined for SHL and SHR"), + "shift_overflow": (["mov eax, ecx", "shr eax, 3", "seto al"], "OF is undefined after a shift by more than 1"), +} + + +def bits_consumers(name, index, conditions, rng): + """One to three readers of the flags of step index, under the given conditions: SETcc into the step's two + flag bytes, CMOVcc into a carried register, and a forward Jcc around an update of one, which comes last.""" + kinds = rng.sample(("set", "set", "cmov", "jump"), rng.choice((1, 2, 3))) + kinds.sort(key=lambda kind: kind == "jump") + lines, flag = [], BITS_FLAGS + 2 * index + for kind in kinds: + cc = rng.choice(conditions) + if kind == "set": + lines.append(f"set{cc} BYTE PTR [r8+{flag}]") + flag += 1 + elif kind == "cmov": + width = rng.choice((4, 8)) + lines.append(f"cmov{cc} {part(rng.choice(BITS_CARRIED), width)}, {part(rng.choice(BITS_SOURCES), width)}") + else: + skip = f"{name}_skip{index}" + update = rng.choice((f"xor {rng.choice(BITS_CARRIED)}, {rng.choice((0x5A5A, 0x1234567))}", + f"not {rng.choice(BITS_CARRIED)}", f"add {rng.choice(BITS_CARRIED)}, rdx")) + lines += [f"j{cc} {skip}", update, f"{skip}:"] + return lines + + +def bits_source(rng, width): + """A source operand of the given width: an argument, R11 prepared from one, or the bit string.""" + choice = rng.choice(("argument", "prepared", "prepared", "memory")) + if choice == "memory": + return [], f"{PTR[width]} [r8+{BITS_MEMORY + rng.randrange(BITS_MEMORY_SIZE - width + 1)}]" + if choice == "argument": + return [], part(rng.choice(("rcx", "rdx")), width) + # Masks and shifts that leave R11 zero for many inputs, not only for zero arguments. + prepare = [f"mov r11, {rng.choice(('rcx', 'rdx'))}"] + prepare += rng.choice(([], [f"and r11, {rng.choice((0xFF00, 0x7FFF0000, -0x10000, 0x10001))}"], + [f"shr r11, {rng.choice((8, 16, 31, 33, 48))}"], [f"shl r11, {rng.choice((16, 32, 48))}"])) + return prepare, part("r11", width) + + +def bits_step(name, index, kind, rng): + """The lines of one step, which leave its result in the step's qword or in the bit string.""" + store = f"QWORD PTR [r8+{8 * index}]" + width = rng.choice((2, 4, 8)) + bits = width * 8 + if kind in ("test_register", "test_memory"): + operation = rng.choice(BITS_TESTS) + # Offsets past the operand width show that the processor and the translation both take them modulo it. + immediate = rng.randrange(bits) if rng.random() < 0.8 else rng.randrange(bits, 256) + if kind == "test_memory": + # A register offset into memory can address bytes outside the 32-byte string, so these take an immediate. + base = f"{PTR[width]} [r8+{BITS_MEMORY + rng.randrange(BITS_MEMORY_SIZE - width + 1)}]" + lines = [f"{operation} {base}, {immediate}"] + else: + base = rng.choice(BITS_CARRIED) + offset = str(immediate) if rng.random() < 0.5 else part(rng.choice(BITS_SOURCES), width) + lines = [f"{operation} {part(base, width)}, {offset}", f"mov {store}, {base}"] + return lines + bits_consumers(name, index, BITS_CONDITIONS["test"], rng) + if kind in ("count", "scan"): + operation = rng.choice(BITS_COUNTS if kind == "count" else BITS_SCANS) + prepare, source = bits_source(rng, width) + # A scan of a zero source leaves the whole destination as it was, so it must hold a defined value. + destination = rng.choice(BITS_CARRIED) + conditions = BITS_CONDITIONS[operation if kind == "count" else "scan"] + return [*prepare, f"{operation} {part(destination, width)}, {source}", f"mov {store}, {destination}", + *bits_consumers(name, index, conditions, rng)] + if kind == "swap": + register = rng.choice(BITS_CARRIED) + swap = f"bswap {part(register, rng.choice((4, 8)))}" + if rng.random() < 0.5: + return [swap, f"mov {store}, {register}"] + # BSWAP leaves the flags alone, so it may sit between a bit test and its readers. + tested = rng.choice([other for other in BITS_CARRIED if other != register]) + return [f"bt {tested}, {rng.randrange(64)}", swap, f"mov {store}, {register}", + *bits_consumers(name, index, BITS_CONDITIONS["test"], rng)] + width = rng.choice((1, 2, 4, 8)) + count = 1 if rng.random() < 0.4 else rng.randrange(2, width * 8) + register = rng.choice(BITS_CARRIED) + return [f"{rng.choice(BITS_SHIFTS)} {part(register, width)}, {count}", f"mov {store}, {register}", + *bits_consumers(name, index, BITS_CONDITIONS["shift1" if count == 1 else "shift"], rng)] + + +def bits_function(name, rng): + """Every kind of step once and a few more, in a seeded order.""" + kinds = [*BITS_KINDS, *(rng.choice(BITS_KINDS) for _ in range(rng.choice(BITS_STEPS) - len(BITS_KINDS)))] + rng.shuffle(kinds) + lines = ["mov rax, rcx", "mov r9, rdx", "lea r10, [rcx+rdx*4+51h]", "mov r11, rdx", "xor r11, rcx", + *(f"mov QWORD PTR [r8+{BITS_MEMORY + 8 * number}], {register}" + for number, register in enumerate(("rcx", "rdx", "r10", "r11")))] + for index, kind in enumerate(kinds): + lines += bits_step(name, index, kind, rng) + lines += [f"mov QWORD PTR [r8+{BITS_FINAL + 8 * number}], {register}" + for number, register in enumerate(("r9", "r10", "r11"))] + return Function(name, [*lines, "add rax, r9", "xor rax, r10", "ret"]) + + +def bits_host(name): + """The native probe of POPCNT, BMI1 and ABM (see BITS_HOST_FEATURES).""" + lines = ["xor eax, eax", "cpuid", "mov r9d, eax", "mov eax, 1", "cpuid", "shr ecx, 23", "and ecx, 1", + "mov r8d, ecx", "cmp r9d, 7", f"jb {name}_extended", "mov eax, 7", "xor ecx, ecx", "cpuid", + "shr ebx, 3", "and ebx, 1", "shl ebx, 1", "or r8d, ebx", f"{name}_extended:", "mov eax, 80000000h", + "cpuid", "cmp eax, 80000001h", f"jb {name}_done", "mov eax, 80000001h", "cpuid", "shr ecx, 5", + "and ecx, 1", "shl ecx, 2", "or r8d, ecx", f"{name}_done:", "mov eax, r8d", "pop rbx", "ret"] + return Function(name, lines, ["push rbx", ".pushreg rbx"], host_features=BITS_HOST_FEATURES) + + +def bits_control(name, kind): + """A negative control: a bit operation or shift whose use the translator must refuse.""" + body, reason = BITS_CONTROLS[kind] + return Function(name, [*body, "movzx eax, al", "mov QWORD PTR [r8], rax", "ret"], refused=reason) + + +def generate_bits(seed, count): + """Exports made of bit-operation steps, then the host probe and six refused controls.""" + rng = random.Random(seed) + functions = [bits_function(f"fuzz_bits_{index}", rng) for index in range(count)] + return [*functions, bits_host("fuzz_bits_host"), *(bits_control(f"fuzz_bits_refused_{kind}", kind) + for kind in BITS_CONTROLS)] + + AREAS = {"leaf": (generate, "cpu_fuzz"), "frames": (generate_frames, "cpu_fuzz_frames"), "calls": (generate_calls, "cpu_fuzz_calls"), "chains": (generate_chains, "cpu_fuzz_chains"), "switches": (generate_switches, "cpu_fuzz_switches"), "scalar_fp": (generate_scalar_fp, "cpu_fuzz_scalar_fp"), "rsp": (generate_rsp, "cpu_fuzz_rsp"), - "loops": (generate_loops, "cpu_fuzz_loops"), "x87": (generate_x87, "cpu_fuzz_x87")} + "loops": (generate_loops, "cpu_fuzz_loops"), "x87": (generate_x87, "cpu_fuzz_x87"), + "bits": (generate_bits, "cpu_fuzz_bits")} def inputs_for(seed, area="leaf", signature=None): @@ -1890,7 +2047,16 @@ def run_check(seed, count, native, lifted, o2, only=None, input_index=None, area functions = AREAS[area][0](seed, count) controls = [function for function in functions if function.refused] - functions = [function for function in functions if not function.refused and function.export] + probes = [function for function in functions if function.host_features is not None] + functions = [function for function in functions + if not function.refused and function.export and function.host_features is None] + for probe in probes: + symbol = getattr(ctypes.CDLL(str(native)), probe.name) + symbol.restype = ctypes.c_uint64 + features = symbol() & probe.host_features + if features != probe.host_features: + print(f"capability skip: {probe.name} reports {features:#b}, not {probe.host_features:#b}") + return 77 libraries = [(native, ""), (lifted, "lifted_"), (o2, "lifted_")] if mutant is not None: libraries.append((mutant, "lifted_")) @@ -2178,11 +2344,23 @@ def plant_subr_as_sub(lifter, image, functions): x87_lower.ARITHMETIC[M.FSUBR] = x87_lower.ARITHMETIC[M.FSUBRP] = "x87_sub" +def plant_set_reset_swap(cpu_switch_aot, image, functions): + """Make BTS clear the selected bit and BTR set it. + + This is a planted translator fault for the negative control: CF is still the selected bit before the + write, and BT and BTC are untouched, but the bit that BTS or BTR leaves in its base differs from native. + """ + from iced_x86 import Mnemonic as M + + tests = cpu_switch_aot.BIT_TESTS + tests[M.BTS], tests[M.BTR] = tests[M.BTR], tests[M.BTS] + + MUTANTS = {"frames": ("reload_shift", plant_reload_shift), "calls": ("call_retarget", plant_call_retarget), "chains": ("swapped_arguments", plant_swapped_arguments), "switches": ("table_rotate", plant_table_rotate), "scalar_fp": ("minmax_swap", plant_minmax_swap), "rsp": ("stale_rsp", plant_stale_rsp), "loops": ("back_edge_exit", plant_back_edge_exit), - "x87": ("subr_as_sub", plant_subr_as_sub)} + "x87": ("subr_as_sub", plant_subr_as_sub), "bits": ("set_reset_swap", plant_set_reset_swap)} def translate(seed, count, image, output, area="leaf", mutant=False): @@ -2193,7 +2371,8 @@ def translate(seed, count, image, output, area="leaf", mutant=False): raise SystemExit(f"no planted translator fault for --area {area}") MUTANTS[area][1](lifter, image, functions) # Negative controls stay in the image for the check to translate on their own. - functions = [function for function in functions if not function.refused and function.export] + functions = [function for function in functions + if not function.refused and function.export and function.host_features is None] names = [export_name(function) for function in functions] try: source, _ = lifter.translate(Path(image), names) From 16c2fd3de08572772e07b13abe5618bb491b6a3c Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:04:11 +0530 Subject: [PATCH 111/232] startup: lower v_sad_u8, v_sad_u16, and v_sad_u32 in gfx2hlsl (#2450) * startup/gfx2hlsl: lower v_sad_u8, v_sad_u16, and v_sad_u32 * tests: pin the v_sad_u* ABS and NEG encoding refusals per source The v_sad_u8/u16/u32 check listed the ABS (VOP3A w0[10:8]) and NEG (w1[31:29]) rows but aggregated them into one boolean, so a mask narrowed to a single bit (w0[8] or w1[29]) still made G.Pipeline() raise: the printed |v1| or -1 was caught later by Stage.one(), not by the encoding guard. Mutation of either mask survived. Read the refusal back from G.decode()'s refusals list, one row per source and modifier, for VGPR and inline-integer sources alike, and assert the exact 'v_sad_* with neg/abs' reason, so narrowing either mask fails. Register tests/startup_gfx2hlsl_sad_check.py in the windows.yml pure-Python job and the AGENTS.md pure-Python list. Refs #2450 AI-assisted. --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 9 + docs/experiments.md | 14 + tests/startup_gfx2hlsl_sad_check.py | 544 ++++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 32 ++ 6 files changed, 601 insertions(+) create mode 100644 tests/startup_gfx2hlsl_sad_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 5fb709690..ffce29783 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -275,6 +275,7 @@ jobs: tests/startup_gfx2hlsl_root_check.py \ tests/startup_gfx2hlsl_sopk_signext_check.py \ tests/startup_gfx2hlsl_mul_hi_check.py \ + tests/startup_gfx2hlsl_sad_check.py \ tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2af9edb75..c9f576236 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -240,6 +240,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_check.py ``` `tests/pixel_aot_check.py binary` additionally needs LLVM with gfx1013 support diff --git a/CMakeLists.txt b/CMakeLists.txt index c9c80cb7a..10e255433 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3460,6 +3460,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_mul_hi_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_sad_u8, v_sad_u16 and v_sad_u32: on-demand helpers, CPU grid evaluation, refusal and mutation controls, then desktop draw (FXC 5_1 and DXC 6_0). + add_test(NAME startup_gfx2hlsl_sad_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sad_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_sad_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sad_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_sad_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_xg_bc_tiling COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc_tiling_check.py" "$") set_tests_properties(startup_xg_bc_tiling PROPERTIES TIMEOUT 30 ENVIRONMENT "X2W_D3D12_PERMISSIVE=1") diff --git a/docs/experiments.md b/docs/experiments.md index 1561335e0..26fc91b4b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14904,3 +14904,17 @@ check and requires the old exception to come back: The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity_check.py`, `…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game data, because a refusal is observable at the `Stage` entry point. +## Startup translator: v_sad_u8, v_sad_u16 and v_sad_u32 + +[`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the gfx1013 VOP3A unsigned sum-of-absolute-differences instructions `v_sad_u8` (`0x15a`), `v_sad_u16` (`0x15c`) and `v_sad_u32` (`0x15d`) in `VEC_U` to three on-demand preamble helpers emitted in `Pipeline.common()` only when referenced by a stage (`sad_u8`, `sad_u16`, `sad_u32`): + +- `sad_u8(uint a, uint b, uint c)` sums `uint(abs(int((a >> shift) & 0xffu) - int((b >> shift) & 0xffu)))` over shifts `0, 8, 16, 24`, plus `c` with 32-bit unsigned wraparound. +- `sad_u16(uint a, uint b, uint c)` computes `uint(abs(int(a & 0xffffu) - int(b & 0xffffu))) + uint(abs(int(a >> 16) - int(b >> 16))) + c` with 32-bit unsigned wraparound. +- `sad_u32(uint a, uint b, uint c)` computes `(a > b ? a - b : b - a) + c` using unsigned comparison rather than signed `int` subtraction. +- Output modifiers (`clamp`, `omod`), `op_sel`, the per-source `abs` bits (VOP3A `w0[10:8]`) and `neg` bits (`w1[31:29]`), and wrong operand counts remain refused: `check_encoding` refuses the `abs`/`neg` bits in the raw word so `neg` on an inline integer cannot print as `-N` and be read as a negative constant, and `Stage.u` refuses the printed `|vN|` and `-vN` forms, the modifier tokens and a wrong operand count. + +[`tests/startup_gfx2hlsl_sad_check.py`](../tests/startup_gfx2hlsl_sad_check.py) decodes synthetic gfx1013 VOP3A bytes via `G.decode()` only (no game data), verifies on-demand helper emission across `Pipeline` and `ComputePipeline`, evaluates the emitted HLSL across 600 edge/grid triples for `v_sad_u8`, 600 for `v_sad_u16` and 605 for `v_sad_u32` (covering `0xffffffff`, `0x80000000`, `0x7fffffff`, byte/halfword boundary carries and `S2` wraparound), checks all modifier/arity/unlowered refusals, and runs mutated-HLSL negative controls (dropped high byte, dropped high halfword, signed `int` subtraction). The encoding guard is pinned per source slot: one row each for `abs` on sources 0, 1 and 2, one for `neg` on each of them, and the same six again with the modifier on an inline `1` (36 rows), and each row reads the refusal back from `G.decode()`'s refusals list and asserts the exact `v_sad_* with neg/abs` reason. That matters because a narrowed mask still ends up refused, just later and by a different guard: with `w0 & 0x700` narrowed to `w0 & 0x100` the `abs` word decodes to `|v1|` and `Stage.u` refuses it, so the pipeline-level control alone passes; the reason check fails, as does the `w1 & 0xe0000000` → `w1 & 0x20000000` narrowing (which silently accepts `neg` on an inline `1` as `-1`). In `draw` mode on Microsoft WARP (`10.0.26100.9818`, DXC `ps_6_0` and FXC `10.0.26100` `ps_5_1`), all 18 good draws (9 per compiler) matched the Python reference and all 6 mutated draws (3 per compiler) produced the exact mutated readback words; the same 18 good and 6 mutated draws also pass on the NVIDIA GeForce GTX 1660 SUPER (driver 32.0.16.1074, Windows build 26200), where the debug layer is not installed and so the `_debug1` variants skip with exit 77. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V +``` diff --git a/tests/startup_gfx2hlsl_sad_check.py b/tests/startup_gfx2hlsl_sad_check.py new file mode 100644 index 000000000..f89588c73 --- /dev/null +++ b/tests/startup_gfx2hlsl_sad_check.py @@ -0,0 +1,544 @@ +"""Unsigned sum-of-absolute-differences (v_sad_u8, v_sad_u16, v_sad_u32) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, on-demand helper, value-evaluation, refusal and mutation + controls, pure Python + draw [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input triples and compare the four result words + +The pixel fixture decodes synthetic gfx1013 VOP3A bytes via G.decode() ONLY (no game data). It reads three flat +parameters (v0..v3, v4..v7, v8..v11), computes v_sad_u* across all four lanes into v12..v15, and exports v12..v15 +to mrt0. The vertex stage supplies the input words through flat parameters so the pixel stage cannot fold them. +""" +import re +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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 compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_WORDS, + PRE_WORDS, + Probe, + check, + refused, + signed, + vs_words, + words_text, +) + +OPCODES = { + 'v_sad_u8': 0x15a, + 'v_sad_u16': 0x15c, + 'v_sad_u32': 0x15d, +} + + +def vop3a(op, vdst, src0, src1, src2, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0, lit=None): + """Encode one synthetic gfx1013 VOP3A 64-bit (or 96-bit with literal) instruction word.""" + w0 = 0xd4000000 | (op << 16) | (clamp << 15) | (op_sel << 11) | (abs_bits << 8) | vdst + w1 = (neg << 29) | (omod << 27) | (src2 << 18) | (src1 << 9) | src0 + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('> shift) & 0xff) - ((b >> shift) & 0xff)) for shift in (0, 8, 16, 24)) + c) & MASK + + +def ref_sad_u16(a, b, c): + a, b, c = a & MASK, b & MASK, c & MASK + return (abs((a & 0xffff) - (b & 0xffff)) + abs(((a >> 16) & 0xffff) - ((b >> 16) & 0xffff)) + c) & MASK + + +def ref_sad_u32(a, b, c): + a, b, c = a & MASK, b & MASK, c & MASK + return (abs(a - b) + c) & MASK + + +REF = { + 'v_sad_u8': ref_sad_u8, + 'v_sad_u16': ref_sad_u16, + 'v_sad_u32': ref_sad_u32, +} + + +def mut_sad_u8(a, b, c): + """Mutated reference: drops the top byte (shift 24).""" + a, b, c = a & MASK, b & MASK, c & MASK + return (sum(abs(((a >> shift) & 0xff) - ((b >> shift) & 0xff)) for shift in (0, 8, 16)) + c) & MASK + + +def mut_sad_u16(a, b, c): + """Mutated reference: drops the top halfword (bits 31:16).""" + a, b, c = a & MASK, b & MASK, c & MASK + return (abs((a & 0xffff) - (b & 0xffff)) + c) & MASK + + +def mut_sad_u32(a, b, c): + """Mutated reference: uses signed 32-bit subtraction inside abs(int(a) - int(b)).""" + a, b, c = a & MASK, b & MASK, c & MASK + return (abs(signed(a) - signed(b)) + c) & MASK + + +MUTATION_REF = { + 'v_sad_u8': mut_sad_u8, + 'v_sad_u16': mut_sad_u16, + 'v_sad_u32': mut_sad_u32, +} + +# Grids with > 500 edge triples per instruction. +U8_WORDS = ( + 0x00000000, 0x01020304, 0x04030201, 0x7f80ff00, 0x807f00ff, + 0x00010000, 0x0000ffff, 0x7fffffff, 0x80000000, 0xffffffff, +) +U8_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xfffffc04, 0xffffffff) +U16_WORDS = ( + 0x00000000, 0x0000ffff, 0xffff0000, 0x0001ffff, 0xffff0001, + 0x7fff8000, 0x80007fff, 0x7fffffff, 0x80000000, 0xffffffff, +) +U16_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xfffe0002, 0xffffffff) +U32_WORDS = ( + 0x00000000, 0x00000001, 0x00000002, 0x12345678, 0x7ffffffe, 0x7fffffff, + 0x80000000, 0x80000001, 0xdeadbeef, 0xfffffffe, 0xffffffff, +) +U32_ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xffffffff) + +GRID = { + 'v_sad_u8': [(a, b, c) for a in U8_WORDS for b in U8_WORDS for c in U8_ADDENDS], + 'v_sad_u16': [(a, b, c) for a in U16_WORDS for b in U16_WORDS for c in U16_ADDENDS], + 'v_sad_u32': [(a, b, c) for a in U32_WORDS for b in U32_WORDS for c in U32_ADDENDS], +} + +# 12 input triples (3 draws of 4 lanes) per instruction. +# The first 4 triples in each list separate the mutation from the reference on every single lane. +DRAW = { + 'v_sad_u8': [ + (0xff000000, 0x00000000, 0), + (0x00123456, 0xff123456, 10), + (0x807f0102, 0x7f800304, 0xfffffc04), + (0x10203040, 0xf0203040, 0xffffffff), + (0x00010000, 0x0000ffff, 0), + (0x01020304, 0x04030201, 1), + (0xffffffff, 0x00000000, 0xfffffc04), + (0x80000000, 0x7fffffff, 0x80000000), + (0x7fffffff, 0x80000000, 0x7fffffff), + (0xdeadbeef, 0xcafebabe, 0x12345678), + (0x00ff00ff, 0xff00ff00, 0), + (0xffffffff, 0xffffffff, 0xffffffff), + ], + 'v_sad_u16': [ + (0xffff0000, 0x00000000, 0), + (0x00001234, 0xffff1234, 10), + (0x80007fff, 0x7fff8000, 0xfffe0002), + (0x1000ffff, 0x2000ffff, 0xffffffff), + (0x00010000, 0x0000ffff, 0), + (0x0001ffff, 0xffff0001, 1), + (0xffffffff, 0x00000000, 0xfffe0002), + (0x80000000, 0x7fffffff, 0x80000000), + (0x7fffffff, 0x80000000, 0x7fffffff), + (0xdeadbeef, 0xcafebabe, 0x12345678), + (0x00000000, 0x00000000, 0), + (0xffffffff, 0xffffffff, 0xffffffff), + ], + 'v_sad_u32': [ + (0xffffffff, 0x00000000, 0), + (0x00000000, 0xffffffff, 0), + (0x80000001, 0x00000000, 5), + (0xfffffffe, 0x00000001, 2), + (0x7fffffff, 0x80000000, 0), + (0x80000000, 0x7fffffff, 0xffffffff), + (0x80000000, 0x00000000, 0x80000000), + (0x00000000, 0x80000000, 0x80000000), + (0xffffffff, 0x00000000, 1), + (0xdeadbeef, 0xcafebabe, 0x12345678), + (0x00000000, 0x00000000, 0xffffffff), + (0xffffffff, 0xffffffff, 0xffffffff), + ], +} + + +# ---- 32-bit HLSL expression evaluator (supports uint/int, abs(), and sad_u* helpers) ------------------------- +TOKEN = re.compile(r'\s*(0x[0-9a-fA-F]+u?|\d+u?|[A-Za-z_]\w*|<<|>>|<=|>=|==|!=|\|\||[-+*&|^~!<>?:(),])') +LEVELS = [['||'], ['|'], ['^'], ['&'], ['==', '!='], ['<', '>', '<=', '>='], ['<<', '>>'], ['+', '-'], ['*']] + + +class HlslExpr: + def __init__(self, text, helpers=None): + self.tokens = TOKEN.findall(text) + assert ''.join(self.tokens) == re.sub(r'\s+', '', text), text + self.pos = 0 + self.helpers = helpers or {} + self.tree = self.ternary() + assert self.pos == len(self.tokens), text + + def peek(self): + return self.tokens[self.pos] if self.pos < len(self.tokens) else None + + def take(self): + self.pos += 1 + return self.tokens[self.pos - 1] + + def ternary(self): + cond = self.binary(0) + if self.peek() != '?': + return cond + self.take() + yes = self.ternary() + assert self.take() == ':' + return ('?', cond, yes, self.ternary()) + + def binary(self, level): + if level == len(LEVELS): + return self.unary() + node = self.binary(level + 1) + while self.peek() in LEVELS[level]: + op = self.take() + node = (op, node, self.binary(level + 1)) + return node + + def unary(self): + token = self.take() + if token in ('~', '-', '!'): + return ('u' + token, self.unary()) + if token == '(': + node = self.ternary() + assert self.take() == ')' + return node + if token[0].isdigit(): + return ('num', int(token.rstrip('u'), 0), not token.endswith('u')) + if self.peek() != '(': + return ('var', token) + self.take() + args = [self.ternary()] + while self.peek() == ',': + self.take() + args.append(self.ternary()) + assert self.take() == ')' + return ('call', token, args) + + def run(self, env, node=None): + node = node or self.tree + kind = node[0] + if kind == 'num': + return node[1] & MASK, node[2] + if kind == 'var': + return env[node[1]] & MASK, False + if kind == '?': + return self.run(env, node[2] if self.run(env, node[1])[0] else node[3]) + if kind == 'call': + return self.call(node[1], [self.run(env, a) for a in node[2]]) + if kind[0] == 'u' and len(node) == 2: + v, s = self.run(env, node[1]) + return {'u~': ~v, 'u-': -v, 'u!': int(v == 0)}[kind] & MASK, s + (a, sa), (b, sb) = self.run(env, node[1]), self.run(env, node[2]) + both = sa and sb + if kind in ('<<', '>>'): + count = b & 31 + return ((a << count) & MASK if kind == '<<' else (signed(a) >> count if sa else a >> count) & MASK), sa + if kind in ('==', '!=', '<', '>', '<=', '>='): + x, y = (signed(a), signed(b)) if both else (a, b) + return int({'==': x == y, '!=': x != y, '<': x < y, '>': x > y, '<=': x <= y, '>=': x >= y}[kind]), True + if kind == '||': + return int(bool(a or b)), True + return {'|': a | b, '^': a ^ b, '&': a & b, '+': a + b, '-': a - b, '*': a * b}[kind] & MASK, both + + def call(self, name, args): + if name in self.helpers: + assert len(args) == 3 and all(not s for _, s in args), (name, args) + return self.helpers[name](*(v for v, _ in args)), False + (v, s), = args + if name in ('asint', 'int'): + return v, True + if name in ('asuint', 'uint'): + return v, False + if name == 'abs': + if s: + val = abs(signed(v)) + assert val <= 0x7fffffff, 'signed abs overflow on %#x' % v + return val & MASK, True + return v, False + raise AssertionError('unexpected call %s' % name) + + +def mutate_hlsl(op, text): + if op == 'v_sad_u8': + pattern = r'\+\s*uint\(abs\(int\(\(a >> 24\) & 0xffu\) - int\(\(b >> 24\) & 0xffu\)\)\)' + mutated = re.sub(pattern, '+ 0u', text) + elif op == 'v_sad_u16': + pattern = r'\+\s*uint\(abs\(int\(a >> 16\) - int\(b >> 16\)\)\)' + mutated = re.sub(pattern, '+ 0u', text) + elif op == 'v_sad_u32': + pattern = r'\(a > b \? a - b : b - a\)' + mutated = re.sub(pattern, 'uint(abs(int(a) - int(b)))', text) + else: + raise AssertionError(op) + assert mutated != text, op + return mutated + + +def translate(op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + if mutate: + text = mutate_hlsl(op, text) + return pipe, text + + +def extract_sad_helpers(hlsl_text): + """Parse emitted sad_u8 / sad_u16 / sad_u32 helper definitions into 32-bit evaluators.""" + helpers = {} + for helper_name in ('sad_u8', 'sad_u16', 'sad_u32'): + m = re.search(r'^uint %s\(uint a, uint b, uint c\) \{ return (.*); \}$' % helper_name, hlsl_text, re.M) + if m: + expr = HlslExpr(m.group(1)) + helpers[helper_name] = lambda a, b, c, e=expr: e.run({'a': a, 'b': b, 'c': c})[0] + return helpers + + +def lane_evaluators(hlsl_text): + helpers = extract_sad_helpers(hlsl_text) + found = re.findall(r'^\s*v(1[2-5]) = (.*);$', hlsl_text, re.M) + assert [r for r, _ in found] == ['12', '13', '14', '15'], found + return helpers, [HlslExpr(rhs, helpers) for _, rhs in found] + + +def eval_lanes(exprs, chunk): + return [expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b, 'v%d' % (8 + lane): c})[0] + for lane, (expr, (a, b, c)) in enumerate(zip(exprs, chunk))] + + +def decode_single_sad(word_bytes): + """Decode synthetic VOP3A bytes via G.decode() and lower through a Stage.""" + ins = G.decode(word_bytes) + assert len(ins) == 1, ins + _, _, name, asm = ins[0] + stage = Probe() + stage.one(name, asm) + return stage.lines + + +def controls(): + # 1. On-demand preamble helpers: none emitted without SAD, only the used helper emitted when used. + base_ps = PRE_WORDS + POST_WORDS + base_pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), base_ps, root_blob()) + base_hlsl_ps = base_pipe.hlsl_ps() + base_hlsl_vs = base_pipe.hlsl_vs() + check('on-demand: baseline pipeline without v_sad_* emits no sad_u* helpers', + all(h not in base_hlsl_ps and h not in base_hlsl_vs for h in ('sad_u8(', 'sad_u16(', 'sad_u32('))) + + for op in OPCODES: + pipe, text = translate(op) + expected_helper = op[2:] # sad_u8 / sad_u16 / sad_u32 + other_helpers = [other[2:] for other in OPCODES if other != op] + helpers, exprs = lane_evaluators(text) + check('%s: on-demand emits only %s helper in PS/VS' % (op, expected_helper), + list(helpers) == [expected_helper] + and all(f'{h}(' not in text and f'{h}(' not in pipe.hlsl_vs() for h in other_helpers)) + + # Verify lane calls in emitted HLSL. + found = re.findall(r'^\s*v(1[2-5]) = %s\(v(\d+), v(\d+), v(\d+)\);$' % expected_helper, text, re.M) + check('%s: four lane calls emitted' % op, + found == [('12', '0', '4', '8'), ('13', '1', '5', '9'), + ('14', '2', '6', '10'), ('15', '3', '7', '11')]) + + # Value-level evaluation of emitted HLSL over 500+ edge/grid triples. + grid = GRID[op] + assert len(grid) >= 500, (op, len(grid)) + ref_fn = REF[op] + mismatch = next(( + (i % 4, triple, + exprs[i % 4].run({'v%d' % (i % 4): triple[0], 'v%d' % (4 + i % 4): triple[1], + 'v%d' % (8 + i % 4): triple[2]})[0], + ref_fn(*triple)) + for i, triple in enumerate(grid) + if exprs[i % 4].run({'v%d' % (i % 4): triple[0], 'v%d' % (4 + i % 4): triple[1], + 'v%d' % (8 + i % 4): triple[2]})[0] != ref_fn(*triple) + ), None) + check('%s: emitted HLSL matches reference on %d edge/grid triples' % (op, len(grid)), + mismatch is None) + + # Mutated HLSL evaluation: must match MUTATION_REF on all non-overflowing grid triples and differ on DRAW[op][:4]. + mutated_text = translate(op, mutate=True)[1] + _, mut_exprs = lane_evaluators(mutated_text) + mut_fn = MUTATION_REF[op] + eval_grid = ( + [t for t in grid if -0x7fffffff <= signed(t[0]) - signed(t[1]) <= 0x7fffffff] + if op == 'v_sad_u32' else grid + ) + mut_mismatch = next(( + (i % 4, triple) + for i, triple in enumerate(eval_grid) + if mut_exprs[i % 4].run({'v%d' % (i % 4): triple[0], 'v%d' % (4 + i % 4): triple[1], + 'v%d' % (8 + i % 4): triple[2]})[0] != mut_fn(*triple) + ), None) + first = DRAW[op][:4] + ref_first = [ref_fn(*t) for t in first] + mut_first = [mut_fn(*t) for t in first] + check('%s: mutated HLSL matches MUTATION_REF on %d triples and differs on draw set 0 (%s != %s)' + % (op, len(eval_grid), words_text(mut_first), words_text(ref_first)), + mut_mismatch is None and eval_lanes(mut_exprs, first) == mut_first + and all(m != r for m, r in zip(mut_first, ref_first))) + + # 2. ComputePipeline on-demand helper check + SGPR / inline constant / literal / exec-masked encodings. + cs_words = vop3a(OPCODES['v_sad_u8'], 1, 4, 129, 255, lit=0x12345678) + struct.pack(' dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -5544,6 +5558,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uses_sampler_heap = False self.uses_pack16_rne = False self.uses_gather_2d_lod = False + self.uses_sad = set() self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index self.uds = [] # entry-constant sources @@ -5764,6 +5779,22 @@ def common(self): ' return result;', '}', )) + if 'v_sad_u8' in self.uses_sad: + out.append( + 'uint sad_u8(uint a, uint b, uint c) {' + ' return uint(abs(int(a & 0xffu) - int(b & 0xffu)))' + ' + uint(abs(int((a >> 8) & 0xffu) - int((b >> 8) & 0xffu)))' + ' + uint(abs(int((a >> 16) & 0xffu) - int((b >> 16) & 0xffu)))' + ' + uint(abs(int((a >> 24) & 0xffu) - int((b >> 24) & 0xffu))) + c; }') + if 'v_sad_u16' in self.uses_sad: + out.append( + 'uint sad_u16(uint a, uint b, uint c) {' + ' return uint(abs(int(a & 0xffffu) - int(b & 0xffffu)))' + ' + uint(abs(int(a >> 16) - int(b >> 16))) + c; }') + if 'v_sad_u32' in self.uses_sad: + out.append( + 'uint sad_u32(uint a, uint b, uint c) {' + ' return (a > b ? a - b : b - a) + c; }') return out def interface(self, for_pixel): @@ -5892,6 +5923,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_gather_2d_lod = False + self.uses_sad = set() self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: anything but a stride clear self.lod_unvalidated = set() From c00697b103f0808283cb92e4b4fe16c6967cac80 Mon Sep 17 00:00:00 2001 From: Chad Hyatt Date: Wed, 25 Nov 2026 13:34:42 -0600 Subject: [PATCH 112/232] shader: lower finite-normal raw buffer floating-point min and max atomics (#2511) - Reuse integer CAS ordering for the explicitly declared finite-normal domain. - Exercise source-built contended and single-value reductions with seeded output and mutation controls. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 40 +++++++ tests/compute_check.cpp | 26 ++++- tests/compute_store_check.py | 204 +++++++++++++++++++++++++++++++++++ tools/compute_store_aot.py | 61 ++++++++--- 6 files changed, 320 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 10e255433..240d27713 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8738,6 +8738,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mubuf_csub_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_csub_${adapter}.txt") + add_test(NAME compute_store_aot_mubuf_float_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mubuf-float "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_mubuf_float_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_float_${adapter}.txt") add_test(NAME compute_store_aot_mubuf_vector_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-mubuf-vector "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 9f2fc036a..657c305a0 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 64-bit atomic buffer reductions | Lower [fixed-address MUBUF integer `_x2` reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-x2-reductions) with SM 6.6 raw UAV atomics. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_x2_'` | | gfx1030 atomic buffer exchanges | Lower [fixed-address MUBUF integer swap and compare-swap](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-exchanges) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_exchange'` | | gfx1030 conditional atomic subtract | Lower [fixed-address `buffer_atomic_csub`](docs/experiments.md#gfx1030-fixed-address-mubuf-conditional-subtract) when the program discards the old value. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_csub_'` | +| gfx1030 atomic buffer float min/max | Lower [fixed-address `buffer_atomic_fmin`/`fmax`](docs/experiments.md#gfx1030-fixed-address-mubuf-float-minmax) under the caller's finite-normal domain and verify the folded word against a CPU float reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float_'` | | gfx1030 atomic buffer counters | Lower [fixed-address MUBUF bounded increment and decrement](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-counters) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_counter'` | | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 26fc91b4b..473ac8843 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5512,6 +5512,46 @@ cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_csub_' -V ``` +### gfx1030 fixed-address MUBUF float min/max + +The compute store profile lowers raw fixed-address `buffer_atomic_fmin` +and `buffer_atomic_fmax` (RDNA 2 MUBUF opcodes 63/64) on the raw `u0` +under an explicit caller contract: `buffer_float_domain="finite-normal"` +(`--buffer-float-domain finite-normal`) states that every stored word and +the operand VGPR hold finite-normal binary32, never NaN, subnormal or +signed zero. Under that domain the sign-magnitude order matches the +order of the sign-adjusted integer keys, so the same +`InterlockedCompareExchange` retry loop the image float min/max path +uses reproduces the ISA result bit-for-bit on the byte-addressed UAV: +`outputData.InterlockedCompareExchange(offset, expected, next, observed)`. +The operand stays 32-bit with `glc` clear, the address stays fixed, and +the atomic remains the sole UAV operation; a missing, misspelled or +unused domain, `_x2`, `glc`, `idxen`/`offen`, and every other reduction +binding violation is rejected with the family's diagnostics. + +Four source-built gfx1030 cases cover both operations with and without +per-lane contention: the uncontended form stores one literal +(`0xbf800011` for fmin, `0x3f800011` for fmax, negative and positive +values), while the contended form derives each lane's word from the +integer reduction fixture's input pattern, which stays finite-normal +across positive and negative magnitudes. One and two 32-lane groups +fold over a declared initial stored word (the op-specific finite extreme +`0x7f7fffff`/`0xff7fffff` or the sentinel) carried in a new flagged +store-case segment, and the readback compares all 320 words +with an independent CPU float reference. Malformed flagged case files +(a truncated initial segment, an unknown header bit and a trailing +partial constants payload) must fail with the parser's exact +diagnostics. A flipped `valueKey` comparison and a removed retry +(`while (false)`) must each fail at word 1 against the mutated +reference. All four new binary cases and the refusal controls passed on +macOS with LLVM 23, including assembly, disassembly and the compute-container +CLI. The full binary suite and DXC/WARP/hardware runs were not run. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float_' -V +``` + ### Indexed gfx1030 raw vector reads The compute store profile also lowers `buffer_load_dwordx2`, diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index a9975c868..5d4da8ae0 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -58,8 +58,10 @@ UINT texture_words_per_texel(DXGI_FORMAT format) static UINT input_word(UINT i) { return 0x8b02a7f1u + i * 0x413b1u; } -// source replaces the generated t0 words when a store case supplies its own. -static void fill_upload(ID3D12Resource* upload, const std::array* source = nullptr) +// source replaces the generated t0 words when a store case supplies its own, and initial +// replaces the sentinel words that seed the output buffer. +static void fill_upload(ID3D12Resource* upload, const std::array* source = nullptr, + const std::array* initial = nullptr) { void* mapped = nullptr; const D3D12_RANGE no_reads{}; @@ -67,7 +69,7 @@ static void fill_upload(ID3D12Resource* upload, const std::array auto* words = static_cast(mapped); for (UINT i = 0; i < capacity; ++i) { words[i] = source ? (*source)[i] : input_word(i); - words[capacity + i] = sentinel; + words[capacity + i] = initial ? (*initial)[i] : sentinel; } auto* cb = static_cast(mapped) + constants_offset; std::memset(cb, 0, 4 * alignment); @@ -193,12 +195,17 @@ static ComPtr bind_tables(ID3D12Device* device, ID3D12Grap struct StoreCase { // Group counts: X in bits 0-7, Y in bits 8-15 and Z in bits 16-23; zero Y or Z means one. + // Bit 31 declares that the case file carries 320 initial output words right after the + // expected words, so the output buffer starts at a caller-chosen nonzero state. UINT groups; std::array expected; std::array root_constants = constants; // Optional t0 words after the constants; otherwise t0 holds input_word(i). std::array source{}; bool has_source = false; + // The flagged case's output words; otherwise every output word starts at the sentinel. + std::array initial{}; + bool has_initial = false; UINT axis(UINT index) const { const UINT n = (groups >> (8 * index)) & 0xff; @@ -226,7 +233,8 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE auto output = make_buffer(device, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); - fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr); + fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr, + store && store->has_initial ? &store->initial : nullptr); ComputeCommands commands(device, pipeline.Get()); auto& list = commands.list; ComPtr texture_upload, texture; @@ -325,11 +333,21 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ std::ifstream file(reference, std::ios::binary); file.read(reinterpret_cast(&store.groups), sizeof(store.groups)); file.read(reinterpret_cast(store.expected.data()), sizeof(store.expected)); + // Bit 31 declares the trailing initial output segment; no other bit above the + // group counts is known, so an unflagged case keeps its historic bounds check. + constexpr UINT initial_data_flag = 1u << 31; + store.has_initial = (store.groups & initial_data_flag) != 0; + store.groups &= ~initial_data_flag; if (!file || store.groups >> 24 || !store.axis(0) || store.axis(0) > 5 || store.axis(1) > 5 || store.axis(2) > 5) throw std::runtime_error("Invalid compute store reference"); if (dpp_case && store.groups != 1) throw std::runtime_error("Invalid compute DPP reference dispatch"); + if (store.has_initial) { + file.read(reinterpret_cast(store.initial.data()), sizeof(store.initial)); + if (!file) + throw std::runtime_error("Invalid compute store initial words"); + } if (file.peek() != std::char_traits::eof()) { file.read(reinterpret_cast(store.root_constants.data()), sizeof(store.root_constants)); if (!file) diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index a970f8737..fd6e3e713 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -5883,6 +5883,205 @@ def mubuf_counter_draw(directory, compiler, renderer, backend, wide=False, csub= path.write_text("\n".join(accepted) + "\n", encoding="utf-8") return 0 +# Raw fixed-address buffer_atomic_fmin/fmax on gfx1030, under the caller's buffer_float_domain +# "finite-normal" contract. Like the integer reductions, the address is fixed (off, no idxen/offen) +# and the atomic is the sole UAV operation; the offset selects the word (1 = byte offset 4). +MUBUF_FLOAT_DOMAIN = "finite-normal" +MUBUF_FLOAT_LITERAL = {"fmin": 0xbf800011, "fmax": 0x3f800011} # -1.000002 and +1.000002 +# Every lane's contended word is MUBUF_REDUCTION_INPUT ^ gid ^ ((gid % 4) << 30), the integer +# reduction fixture's per-lane value: it stays finite-normal binary32 for all gids and spans +# positive and negative magnitudes across six orders of magnitude, so lanes genuinely compete. +MUBUF_FLOAT_INITIAL = {"fmin": 0x7f7fffff, "fmax": 0xff7fffff} # the largest and smallest finite float +MUBUF_FLOAT_INITIAL_FLAG = 1 << 31 # store-case header bit declaring initial output words + + +def mubuf_float_cases(): + for op in ("fmin", "fmax"): + for contended in (False, True): + name = f"buffer_atomic_{op}{'_contended' if contended else ''}" + lines = ["s_mov_b32 s12, s7", "s_mov_b32 s13, 0", + "s_load_dwordx4 s[20:23], s[12:13], 0x30"] + if contended: + # gid = group.x * 32 + local.x; the word is the reduction fixture's per-lane value. + lines += ["v_lshl_add_u32 v8, s11, 5, v0", "s_waitcnt lgkmcnt(0)", + f"v_xor_b32_e32 v10, {MUBUF_REDUCTION_INPUT:#x}, v8", + "v_and_b32_e32 v12, 3, v8", "v_lshlrev_b32_e32 v12, 30, v12", + "v_xor_b32_e32 v10, v12, v10"] + else: + lines += ["s_waitcnt lgkmcnt(0)", + f"v_mov_b32_e32 v10, {MUBUF_FLOAT_LITERAL[op]:#x}"] + lines += [f"buffer_atomic_{op} v10, off, s[20:23], 0 offset:4", "s_endpgm"] + yield name, op, contended, lines, {k: v for k, v in DS_BINDING.items() if k != "stride"} | { + "buffer_float_domain": MUBUF_FLOAT_DOMAIN} + + +def mubuf_float_word(gid): + """The contended per-lane word, the integer reduction fixture's input pattern.""" + return (MUBUF_REDUCTION_INPUT ^ gid ^ ((gid % 4) * 0x40000000)) & 0xffffffff + + +def mubuf_float_reference(op, contended, groups, *, initial=SENTINEL, reversed_values=False): + """Independent CPU float reference: fold min/max over the stored word and the lanes' words. + + The values are finite-normal binary32, so Python's float comparison is the ISA's ordering; + the winner keeps its exact bit pattern because distinct finite-normal floats are distinct words. + reversed_values models a translation that compares with the wrong operator. + """ + words = [initial] + if contended: + # tid.x is the dispatch X index, so two 32-lane groups offer two distinct 32-word + # spans and every lane's word competes. + words += [mubuf_float_word(gid) for gid in range(32 * groups)] + else: + words += [MUBUF_FLOAT_LITERAL[op]] * 32 * groups + choose = min if (op == "fmin") != reversed_values else max + result = choose(words, key=lambda word: struct.unpack("> 23) & 0xff) < 0xff, hex(word) + return result + + +def mubuf_float_controls(): + for name, op, contended, lines, binding in mubuf_float_cases(): + atomic = lines[-2] + # The domain contract: missing, unneeded and misspelled. + rejects("buffer_atomic fmin/fmax require a finite-normal domain, a single 32-bit operand and no glc", + aot.lower, lines, 32, **(binding | {"buffer_float_domain": None})) + rejects("Invalid buffer float domain", aot.lower, lines, 32, + **(binding | {"buffer_float_domain": "all-floats"})) + rejects("Unused buffer float domain", aot.lower, variant(lines, (atomic, atomic.replace( + f"buffer_atomic_{op}", "buffer_atomic_umin"))), 32, **binding) + # A plain store replacing the atomic is a mixed target, not a float atomic. + rejects("Unsupported store address", aot.lower, variant( + lines, (atomic, "buffer_store_dword v10, off, s[20:23], 0 offset:4")), 32, **binding) + # Mixed operations: an integer atomic or a plain store next to the float atomic. + rejects("An atomic reduction must be the only UAV operation", aot.lower, + variant(lines, (atomic, atomic + "\nbuffer_atomic_umin v11, off, s[20:23], 0 offset:8")), + 32, **binding) + # The single 32-bit no-glc operand form. + rejects("buffer_atomic fmin/fmax require a finite-normal domain, a single 32-bit operand and no glc", + aot.lower, variant(lines, (atomic, atomic + " glc")), 32, **binding) + rejects("Unverified atomic reduction data range", aot.lower, + variant(lines, (atomic, atomic.replace("v10,", "v[10:11],"))), 32, **binding) + # The other profile guards: target, descriptor, address and sole-UAV-operation. + rejects("Unsupported atomic reduction target or binding", aot.lower, lines, 32, + **(binding | {"cpu": "gfx1013"})) + rejects("Unsupported atomic reduction target or binding", aot.lower, lines, 32, + **(binding | {"stride": 4})) + rejects("Unverified atomic reduction descriptor", aot.lower, + variant(lines, (atomic, atomic.replace("s[20:23]", "s[21:24]"))), 32, **binding) + rejects("Unverified atomic reduction address", aot.lower, + variant(lines, (atomic, atomic.replace("offset:4", "offset:2"))), 32, **binding) + rejects("Unverified atomic reduction address", aot.lower, + variant(lines, (atomic, atomic.replace("offset:4", "offset:4096"))), 32, **binding) + rejects("Unverified atomic reduction descriptor", aot.lower, + variant(lines, ("s_waitcnt lgkmcnt(0)", "")), 32, **binding) + + +def mubuf_float_case_bytes(groups, expected, initial_words, *, constants_words=None, source_words=None): + """Pack a store-case file: header flag, 320 expected words, then the flagged initial + segment, then the historic optional constants and t0 source segments in order.""" + data = struct.pack("<321I", groups | MUBUF_FLOAT_INITIAL_FLAG, *expected) + data += struct.pack("<320I", *initial_words) + if constants_words is not None or source_words is not None: + data += struct.pack("<16I", *(constants_words or [0] * 16)) + if source_words is not None: + data += struct.pack("<320I", *source_words) + return data + + +def mubuf_float_case_controls(cmd, case): + """Malformed flagged case files through the actual runner's parser, before any dispatch: + a truncated initial segment, an unknown header bit, and a trailing partial constants + payload. Each must fail with the parser's exact diagnostic on an admitted backend; an + unavailable one propagates the runner's 77 skip.""" + expected, initial_words = [SENTINEL] * 320, [SENTINEL] * 320 + expected[1], initial_words[1] = 0x3f800011, 0x7f7fffff + good = mubuf_float_case_bytes(2, expected, initial_words) + for malformed, diagnostic in ( + (good[:4 + 1280 + 640], "Invalid compute store initial words"), + (struct.pack("<321I", 2 | (1 << 30), *expected) + struct.pack("<320I", *initial_words), + "Invalid compute store reference"), + (good + struct.pack("<4s", b"junk"), "Invalid compute store constants"), + ): + case.write_bytes(malformed) + bad = subprocess.run(cmd, capture_output=True, text=True) + if bad.returncode == 77: + print(bad.stdout, end="") + return 77 + if bad.returncode != 1 or diagnostic not in bad.stderr: + raise AssertionError(f"Malformed case escaped the parser\n{bad.stdout}\n{bad.stderr}") + print(bad.stderr.strip(), flush=True) + return 0 + + +def mubuf_float_mutation(op, contended): + """Source-text mutations of the emitted CAS that a wrong lowering would produce.""" + if contended: + return ("while (observed != expected)", "while (false)") + comparison, opposite = ("<", ">") if op == "fmin" else (">", "<") + return (f"valueKey {comparison} oldKey", f"valueKey {opposite} oldKey") + + +def mubuf_float_draw(directory, compiler, renderer, backend): + mubuf_float_controls() + src, cso, case = (directory / f"mubuf-float.{ext}" for ext in ("hlsl", "cso", "case")) + compile_shader = [compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, src] + run = [renderer, backend, "--compute-store-case", cso, case] + accepted = set() + for name, op, contended, lines, binding in mubuf_float_cases(): + print(name, flush=True) + kernel = aot.lower(lines, 32, **binding) + src.write_text(kernel, encoding="ascii") + subprocess.run(compile_shader, check=True) + if not accepted: + # The malformed-case controls run through the actual CLI parser before any + # dispatch; a hardware capability skip propagates out of the draw entry. + skipped = mubuf_float_case_controls(run, case) + if skipped: + return skipped + for groups in (1, 2): + # One and two 32-lane groups: tid.x spans the whole dispatch X, so the second + # group's contended words are distinct from the first group's. + for initial in (MUBUF_FLOAT_INITIAL[op], SENTINEL): + # The op-specific extreme is the value the winning lane must beat; the sentinel + # run keeps the untouched-seed profile the integer reductions use. The stored + # word starts at the declared seed, so the CPU oracle matches the buffer. + expected = [SENTINEL] * 320 + initial_words = [SENTINEL] * 320 + initial_words[1] = initial + expected[1] = mubuf_float_reference(op, contended, groups, initial=initial) + case.write_bytes(mubuf_float_case_bytes(groups, expected, initial_words)) + result = subprocess.run(run) + if result.returncode: + return result.returncode + correct, wrong = mubuf_float_mutation(op, contended) + assert kernel.count(correct) == 1 + mutant = mubuf_float_reference(op, contended, 2, initial=MUBUF_FLOAT_INITIAL[op], + reversed_values=True) + src.write_text(kernel.replace(correct, wrong), encoding="ascii") + subprocess.run(compile_shader, check=True) + # The mutated kernel keeps the extreme initial word: the contended while (false) form stops + # after one failed compare against the never-zero stored word, and the uncontended flipped + # comparison prefers the initial extreme over the single lane value, so the observed word + # is the mutated reference either way. + expected = [SENTINEL] * 320 + expected[1] = mubuf_float_reference(op, contended, 2, initial=MUBUF_FLOAT_INITIAL[op]) + initial_words = [SENTINEL] * 320 + initial_words[1] = MUBUF_FLOAT_INITIAL[op] + case.write_bytes(mubuf_float_case_bytes(2, expected, initial_words)) + bad = subprocess.run(run, capture_output=True, text=True) + if (bad.returncode != 1 or f"word=1 expected={expected[1]:08x} actual={mutant:08x}" + not in bad.stderr): + raise AssertionError(f"{name}: incorrect float min/max escaped detection\n{bad.stderr}") + print(bad.stderr, end="") + accepted.add(name) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(sorted(accepted)) + "\n", encoding="utf-8") + return 0 + def scalar_alu_binary(directory, assembler, objcopy, library): """The assembled scalar chain decodes to the same program as its text.""" @@ -5961,6 +6160,10 @@ def binary(directory, assembler, objcopy, library): gfx1030_binary(directory, assembler, objcopy, library, mubuf_counter_cases(wide), "buffer_atomic_") mubuf_csub_controls() gfx1030_binary(directory, assembler, objcopy, library, mubuf_csub_cases(), "buffer_atomic_") + mubuf_float_controls() + gfx1030_binary(directory, assembler, objcopy, library, + [(name, lines, binding) for name, _, _, lines, binding in mubuf_float_cases()], + "buffer_atomic_") mubuf_subword_controls() gfx1030_binary(directory, assembler, objcopy, library, mubuf_subword_cases(), "buffer_load_") mubuf_vector_controls() @@ -9305,6 +9508,7 @@ def descriptor_store_draw(directory, compiler, renderer, backend): "draw-mubuf-subword": mubuf_subword_draw, "draw-mubuf-reduction": mubuf_reduction_draw, "draw-mubuf-csub": lambda d, *a: mubuf_counter_draw(d, *a, csub=True), + "draw-mubuf-float": mubuf_float_draw, "draw-mubuf-counter": mubuf_counter_draw, "draw-mubuf-counter-x2": lambda d, *a: mubuf_counter_draw(d, *a, wide=True), "draw-mubuf-exchange": mubuf_exchange_draw, diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 597071db1..1046987c9 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -243,9 +243,33 @@ "smin": "Min", "umin": "Min", "smax": "Max", "umax": "Max", "swap": "Exchange", "cmpswap": "CompareExchange", "inc": "CompareExchange", "dec": "CompareExchange", "csub": "CompareExchange", + "fmin": "CompareExchange", "fmax": "CompareExchange", } IMAGE_FLOAT_ATOMIC_OPS = ("fcmpswap", "fmin", "fmax") + +def float_min_max_cas(cas_prefix, value, op): + """Raw-word finite-normal binary32 min/max as an InterlockedCompareExchange loop. + + Shared by the image (texel) and MUBUF (byte-address) atomic profiles; cas_prefix is the + call up to the opening parenthesis: the free intrinsic `InterlockedCompareExchange(dest)` + for a texel destination and the raw UAV method `outputData.InterlockedCompareExchange(off)` + for the byte-address destination. The caller guarantees every stored word and the operand + are finite-normal binary32, never NaN, subnormal or signed zero. The sign-dependent key + orders those values exactly as unsigned integers, so integer CAS reproduces the fmin/fmax + result bit-for-bit. The zero seed is outside the caller's domain and can only fetch the + observed word; it never writes. + """ + comparison = "<" if op == "fmin" else ">" + return (f" uint value = {value};", + " uint valueKey = value ^ ((value & 0x80000000u) ? 0xffffffffu : 0x80000000u);", + " uint observed = 0u;", " uint expected;", + " [allow_uav_condition] do {", " expected = observed;", + " uint oldKey = expected ^ ((expected & 0x80000000u) ? 0xffffffffu : 0x80000000u);", + f" uint next = (valueKey {comparison} oldKey) ? value : expected;", + f" {cas_prefix}, expected, next, observed);", + " } while (observed != expected);") + IMAGE_ATOMIC_OPS = "add|sub|and|or|xor|smin|smax|umin|umax|swap|cmpswap|inc|dec|" + "|".join(IMAGE_FLOAT_ATOMIC_OPS) IMAGE_ATOMIC_TYPES = {"R32_UINT": "uint", "R32_SINT": "int", "R32_FLOAT": "uint"} @@ -747,7 +771,7 @@ def heap_store_view_hlsl(table_offset, view_count, output_bytes, *, components=4 def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=None, stride=None, image_srv_descriptor=None, constant_descriptor=None, group_reg_y=None, group_reg_z=None, source_descriptor=None, source_stride=None, source_format=None, output_format=None, image_descriptor=None, image_format=None, - image_uav_mip=None, image_float_domain=None, cpu="gfx1013", lds_bytes=0, + image_uav_mip=None, image_float_domain=None, buffer_float_domain=None, cpu="gfx1013", lds_bytes=0, lds_f32_mode=None, lds_f64_mode=None, mubuf_d16_xyz_mode=None, descriptor_format_constant=None, rsrc2=None, wave_size=None, load_format_constant=None, heap_view=None, heap_store_view=None, gather_mips=None): @@ -788,6 +812,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N and selects signed min/max. R32_FLOAT declares a native atomic image carried as raw words in a desktop R32_UINT UAV. The caller guarantees finite-normal binary32 in the accessed texels and operand VGPRs by setting image_float_domain="finite-normal". + A raw fixed-address buffer_atomic_fmin/fmax also requires the caller's + buffer_float_domain="finite-normal" statement: every stored word and the operand VGPR + hold finite-normal binary32, never NaN, subnormal or signed zero. gather_mips declares the visible mip count of matching gfx1013 RGBA32 FLOAT native and desktop 2D views at t0 for one image_gather4_l (see GATHER_HLSL). """ @@ -810,6 +837,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if (image_float and (not image_output or image_float_domain != "finite-normal") or (not image_float and image_float_domain is not None)): raise ValueError("The finite-normal image domain requires an R32_FLOAT atomic UAV and vice versa") + if buffer_float_domain is not None and buffer_float_domain != "finite-normal": + raise ValueError("Invalid buffer float domain") image_msaa = not image_output and image_format == "R32_UINT" if image_msaa and cpu != "gfx1030": raise ValueError("The R32_UINT MSAA image binding requires gfx1030") @@ -948,6 +977,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N heap_store_components = 4 format_store_index = 0 atomic_update = False + buffer_float_update = False # DS operations and image loads can consume each other's temporaries. Keep them in instruction order. staged_steps = [] ds_step_count = 0 @@ -2442,17 +2472,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N f" InterlockedCompareExchange({destination}, expected, next, observed);", " } while (observed != expected);")) elif op in ("fmin", "fmax"): - comparison = "<" if op == "fmin" else ">" - # The sign-dependent key orders finite-normal binary32 as unsigned integers. - # The zero seed is outside the caller's domain and can only fetch the old word. - stores.extend((f" uint value = {value};", - " uint valueKey = value ^ ((value & 0x80000000u) ? 0xffffffffu : 0x80000000u);", - " uint observed = 0u;", " uint expected;", - " [allow_uav_condition] do {", " expected = observed;", - " uint oldKey = expected ^ ((expected & 0x80000000u) ? 0xffffffffu : 0x80000000u);", - f" uint next = (valueKey {comparison} oldKey) ? value : expected;", - f" InterlockedCompareExchange({destination}, expected, next, observed);", - " } while (observed != expected);")) + stores.extend(float_min_max_cas(f"InterlockedCompareExchange({destination}", value, op)) elif compare_swap: # RDNA stores VDATA on a match against VDATA+1. HLSL takes the comparison first. # Numeric equality and bit equality agree for finite-normal binary32. @@ -2656,6 +2676,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if stores: raise ValueError("An atomic reduction must be the only UAV operation") op, wide = m[1], bool(m[2]) + if op in ("fmin", "fmax") and (buffer_float_domain != "finite-normal" or wide or m[7]): + raise ValueError("buffer_atomic fmin/fmax require a finite-normal domain, " + "a single 32-bit operand and no glc") if op == "csub" and (wide or not m[7]): raise ValueError("Conditional subtract requires 32-bit glc") if op != "csub" and m[7]: @@ -2690,7 +2713,11 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if op == "cmpswap": # The ISA places replacement before compare, unlike the HLSL argument order. word = f"{operands[1]}, {word}" - if op in ("inc", "dec", "csub"): + if op in ("fmin", "fmax"): + # Raw-word finite-normal binary32 min/max on the raw UAV, under the caller's + # finite-normal domain statement. Reuses the image ordering. + stores.extend(float_min_max_cas(f"outputData.InterlockedCompareExchange({offset}u", word, op)) + elif op in ("inc", "dec", "csub"): one, zero = ("1ull", "0ull") if wide else ("1u", "0u") if op == "inc": desired = f"expected >= limit ? {zero} : expected + {one}" @@ -2712,6 +2739,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N stores.extend((f" {kind} ignoredAtomic;", f" outputData.Interlocked{method}({offset}u, {word}, ignoredAtomic);")) atomic_update = True + if op in ("fmin", "fmax"): + buffer_float_update = True elif m := re.fullmatch(r"(?:buffer_store_(?:dword(?:x(?P[234]))?|(?Pbyte|short)(?P_d16_hi)?)|" r"(?Pt)?buffer_store_format_(?P(?:d16_)?(?:x|xy|xyz|xyzw))) " r"(?Pv\d+|v\[\d+:\d+\]), (?Poff|v\d+|v\[\d+:\d+\]), " @@ -2901,6 +2930,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unused buffer descriptor format constant") if load_format_words is not None and format_load_index != len(load_format_words): raise ValueError("Unused buffer load format constant") + if buffer_float_domain is not None and not buffer_float_update: + raise ValueError("Unused buffer float domain") if heap_view is not None and not format_load_index: raise ValueError("Unused heap view binding") if heap_store_view is not None and (not layout or layout[0] != "heap_index" or len(stores) != 1): @@ -3027,6 +3058,9 @@ def main(): "R16G16B16A16_FLOAT for gfx1013 D16 image stores)") parser.add_argument("--image-float-domain", choices=("finite-normal",), help="Required for R32_FLOAT atomics. All accessed texels and operands are finite normals.") + parser.add_argument("--buffer-float-domain", choices=("finite-normal",), + help="Required for raw fixed-address buffer_atomic_fmin/fmax. Every stored word " + "and the operand is finite-normal binary32, never NaN, subnormal or signed zero.") parser.add_argument("--wave-size", type=int, choices=(32,), help="Caller's statement that the program runs as wave32, for lane indices in larger groups") parser.add_argument("--gather-mips", type=int, @@ -3049,6 +3083,7 @@ def main(): source_stride=args.source_stride, source_format=args.source_format, output_format=args.output_format, image_descriptor=args.image_descriptor, image_format=args.image_format, + buffer_float_domain=args.buffer_float_domain, image_uav_mip=args.image_uav_mip, image_float_domain=args.image_float_domain, cpu=args.cpu, lds_bytes=args.lds_bytes, lds_f32_mode=args.lds_f32_mode, lds_f64_mode=args.lds_f64_mode, From 822d9df00c0fc643c36dfcceea28a96a4dd1b7e2 Mon Sep 17 00:00:00 2001 From: nanyoudegege <132808593+nanyoudegege@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:36:18 +0800 Subject: [PATCH 113/232] docs: clarify the DXC timing skip on older SDKs (#2516) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 657c305a0..f57a5719e 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Both Windows jobs on `main` must pass before CI publishes a new chart. The image On x64 Windows, install Python 3.11 or newer and Visual Studio's **Desktop development with C++** workload, including x64 MSVC, CMake, Ninja, and the Windows SDK with DXC. Windows CI uses Python 3.12. -Use Windows SDK 10.0.26100 for new installations. A contributor using SDK 10.0.22621.0, MSVC 19.44 and the bundled DXC 1.6.2112.16 [completed `cmake --build --preset dev`](https://github.com/R0Y00/Xbox2Windows/pull/1369). In the full test suite, `dxc_compile_time_gvn` failed because that DXC rejects `-ftime-report`. See [Windows build notes](#windows-build-notes) to select a different DXC. +Use Windows SDK 10.0.26100 for new installations. A contributor using SDK 10.0.22621.0, MSVC 19.44 and the bundled DXC 1.6.2112.16 [completed `cmake --build --preset dev`](https://github.com/R0Y00/Xbox2Windows/pull/1369). In that run, `dxc_compile_time_gvn` failed because DXC reported `-ftime-report` as an unknown argument. The test now [returns 77 for that diagnostic](https://github.com/R0Y00/Xbox2Windows/pull/1393), so CTest reports it as skipped. See [Windows build notes](#windows-build-notes) to select a different DXC. Visual Studio 2019 Build Tools (MSVC 14.29) build every target except the five CRT-free TLS EXE fixtures (`cpu_exe_tls*`), because that compiler leaves their thread-local initializers to the C runtime. For the same reason `cpu_native_tls_value` fails there, `cpu_package_main_image` lacks its fixture, and `xmem_attribute_scan` also sees the unused delay-load jump thunk that the 14.29 linker emits. Open PowerShell and run the following commands. If you already have a clone, start at `.\tools\dev.ps1`. From 47490bd6e3615a595fd8eee3fe0b83d54d24233e Mon Sep 17 00:00:00 2001 From: rdx <123564405+R0D4X@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:37:21 +0100 Subject: [PATCH 114/232] startup: lower v_mul_i32_i24 and v_mad_i32_i24 in gfx2hlsl (#2410) Co-authored-by: R0D4X Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 9 + tests/startup_gfx2hlsl_mul_mad_i24_check.py | 248 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 2 + 4 files changed, 261 insertions(+) create mode 100644 tests/startup_gfx2hlsl_mul_mad_i24_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index ffce29783..a4b349932 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -115,6 +115,7 @@ jobs: (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_mul_mad_i24_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_sop2_complement_check.py", "binary", "llvm-mc-15"], {}), @@ -263,6 +264,7 @@ jobs: tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ + tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ tests/startup_gfx2hlsl_cmp16_check.py \ tests/startup_gfx2hlsl_draw_skip_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 2ad30cc58..e913e8013 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3442,6 +3442,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_shift64_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl signed 24-bit multiply/multiply-add (v_mul_i32_i24, v_mad_i32_i24): evaluator, refusals and draws. + add_test(NAME startup_gfx2hlsl_mul_mad_i24_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_mad_i24_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mul_mad_i24_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_mad_i24_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mul_mad_i24_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # XG slots 2 and 8 for a texture given the 4 KiB allocation answer (src/startup_stubs/small_texture_4k.h): # the copy must stay in front of a guard page; the mutated run is not limited and must fail. add_test(NAME startup_small_texture_4k_xg COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_gfx2hlsl_mul_mad_i24_check.py b/tests/startup_gfx2hlsl_mul_mad_i24_check.py new file mode 100644 index 000000000..24a3de4e4 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul_mad_i24_check.py @@ -0,0 +1,248 @@ +"""Signed 24-bit vector multiply and multiply-add (v_mul_i32_i24, v_mad_i32_i24) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, evaluator, refusal and mutation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + draw [fxc] + compile the translated pairs with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input sets and compare the four result words + +Each pixel fixture reads three flat parameters (v0..v3, v4..v7, v8..v11), applies v_mul_i32_i24 (alternating VOP2 e32 +and VOP3A e64 across the four lanes) or v_mad_i32_i24 (VOP3A) into v12..v15, and exports v12..v15 to mrt0. + +Every result is compared with an independent Python signed 24-bit reference (signext24(a) * signext24(b) [+ c]) & +0xffffffff. Controls verify that bits[31:24] of S0/S1 are ignored, bit 23 sign-extends to 32 bits, exec-masked +emission guards the destination, modifiers (including integer clamp) and wrong operand counts stay refused, and +unsigned-24-bit mutations ((a & 0xffffffu) * (b & 0xffffffu) [+ c]) fail with exact expected wrong words on both CPU +evaluation and desktop GPU draws. +""" +import re +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + Expr, + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + Probe, + check, + refused, + vs_source, + vs_words, + words_text, +) + +OPS = ('v_mul_i32_i24', 'v_mad_i32_i24') + +BODY_SOURCE = { + 'v_mul_i32_i24': ''.join( + 'v_mul_i32_i24_%s v%d, v%d, v%d\n' % ('e64' if lane % 2 else 'e32', 12 + lane, lane, 4 + lane) + for lane in range(4) + ), + 'v_mad_i32_i24': ''.join( + 'v_mad_i32_i24 v%d, v%d, v%d, v%d\n' % (12 + lane, lane, 4 + lane, 8 + lane) + for lane in range(4) + ), +} +BODY_WORDS = { + 'v_mul_i32_i24': bytes.fromhex('000918120d0009d5010b0200020d1c120f0009d5030f0200'), + 'v_mad_i32_i24': bytes.fromhex('0c0042d5000922040d0042d5010b26040e0042d5020d2a040f0042d5030f2e04'), +} + +# Edge values covering 24-bit sign boundary (0x7fffff, 0x800000), -1 (0xffffff), upper-byte noise (0xab..., 0xff...), +# and 32-bit wraparound. +SPECIAL = ( + 0x00000000, 0x00000001, 0x00000002, 0x007fffff, 0x00800000, 0x00800001, 0x00ffffff, + 0x01000000, 0x557fffff, 0xaa800000, 0xdeadbeef, 0xcafebabe, 0x7fffffff, 0x80000000, + 0xff7fffff, 0xffffffff, +) +ADDENDS = (0, 1, 0x7fffffff, 0x80000000, 0xffffffff, 0x12345678) + +# Four (src0, src1, src2) tuples per draw. Set 0 separates signed 24-bit from unsigned 24-bit on every lane. +DRAW = { + 'v_mul_i32_i24': [ + (0x00ffffff, 0x00000002, 0), # -1 * 2 = -2 (unsigned24: 0x01fffffe) + (0x00800000, 0x00000003, 0), # -8388608 * 3 = -25165824 (unsigned24: 0x01800000) + (0xaa800000, 0x55ffffff, 0), # upper bytes ignored: -8388608 * -1 = +8388608 + (0x00800000, 0x00800000, 0), # INT24_MIN * INT24_MIN = 0 (mod 2^32) -> wait: 2^46 mod 2^32 = 0 + (0x007fffff, 0x007fffff, 0), # +8388607^2 + (0xab000005, 0xcdffffff, 0), # upper bytes ignored: 5 * -1 = -5 + (0x00ffffff, 0x00ffffff, 0), # -1 * -1 = 1 (unsigned24: 0xfe000001) + (0x01000000, 0xdeadbeef, 0), # low 24 bits of src0 are 0 -> 0 + ], + 'v_mad_i32_i24': [ + (0x00ffffff, 0x00000002, 0x00000005), # -1 * 2 + 5 = 3 (unsigned24: 0x02000003) + (0x00800000, 0x00000003, 0x80000000), # -25165824 + INT32_MIN + (0xaa800000, 0x55ffffff, 0xffffffff), # +8388608 + (-1) = 0x007fffff + (0x00ffffff, 0x00ffffff, 0x7fffffff), # 1 + INT32_MAX wraps to 0x80000000 + (0x007fffff, 0x007fffff, 0x12345678), # positive * positive + addend + (0xab000005, 0xcdffffff, 0x00000005), # -5 + 5 = 0 + (0x01000000, 0xdeadbeef, 0xcafebabe), # 0 * x + addend = addend + (0x00800001, 0x00ffffff, 0x00000001), # (-8388607) * (-1) + 1 = 0x00800000 + ], +} + + +def s24(v): + v &= 0xffffff + return v - (1 << 24) if v & 0x800000 else v + + +def ref_op(op, a, b, c): + prod = s24(a) * s24(b) + return (prod + (c & MASK) if op == 'v_mad_i32_i24' else prod) & MASK + + +def mut_unsigned24(op, a, b, c): + prod = (a & 0xffffff) * (b & 0xffffff) + return (prod + (c & MASK) if op == 'v_mad_i32_i24' else prod) & MASK + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +def translate(op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + if mutate: + mutated = re.sub(r'asuint\(asint\((v\d+) << 8\) >> 8\)', r'(\1 & 0xffffffu)', text) + assert mutated != text, text + text = mutated + return pipe, text + + +def controls(): + for op in OPS: + _, text = translate(op) + lanes = re.findall(r'^\s*v(1[2-5]) = (.*);$', text, re.M) + check('%s: four lane assignments emitted' % op, [r for r, _ in lanes] == ['12', '13', '14', '15']) + exprs = [Expr(rhs) for _, rhs in lanes] + + # Evaluate emitted HLSL text on CPU across edge grid. + if op == 'v_mul_i32_i24': + cases = [(a, b, 0) for a in SPECIAL for b in SPECIAL] + else: + cases = [(a, b, c) for a in SPECIAL[:8] for b in SPECIAL[:8] for c in ADDENDS] + mismatch = None + for lane, expr in enumerate(exprs): + for a, b, c in cases: + got = expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b, 'v%d' % (8 + lane): c})[0] + want = ref_op(op, a, b, c) + if got != want: + mismatch = (lane, a, b, c, got, want) + break + if mismatch: + break + check('%s: emitted expressions match reference on %d cases x 4 lanes' % (op, len(cases)), mismatch is None) + + # Unsigned-24-bit mutation control on draw set 0. + mut_text = translate(op, mutate=True)[1] + mut_lanes = re.findall(r'^\s*v(1[2-5]) = (.*);$', mut_text, re.M) + mut_exprs = [Expr(rhs) for _, rhs in mut_lanes] + first = DRAW[op][:4] + ref_first = [ref_op(op, a, b, c) for a, b, c in first] + mut_first = [mut_unsigned24(op, a, b, c) for a, b, c in first] + eval_mut = [expr.run({'v%d' % lane: a, 'v%d' % (4 + lane): b, 'v%d' % (8 + lane): c})[0] + for lane, (expr, (a, b, c)) in enumerate(zip(mut_exprs, first))] + check('%s: draw set 0 unsigned24 mutation reads %s (differs from %s)' + % (op, words_text(mut_first), words_text(ref_first)), + mut_first != ref_first and eval_mut == mut_first) + + # Accepted operand forms (VGPR, SGPR, inline constant, literal, _e32/_e64) and exec-masked emission. + check('accepted operand forms translate', not any(refused(a) for a in ( + 'v_mul_i32_i24 v1, v2, v3', 'v_mul_i32_i24_e32 v1, v2, v3', 'v_mul_i32_i24_e64 v1, s0, v3', + 'v_mul_i32_i24 v1, -1, v3', 'v_mul_i32_i24 v1, 0xaa800000, v3', + 'v_mad_i32_i24 v1, v2, v3, v4', 'v_mad_i32_i24 v1, s0, v3, -1', + 'v_mad_i32_i24 v1, v2, 0x00ffffff, v4'))) + for op, line, suffix in ( + ('v_mul_i32_i24', 'v_mul_i32_i24 v1, v2, v3', ''), + ('v_mad_i32_i24', 'v_mad_i32_i24 v1, v2, v3, v4', ' + v4'), + ): + masked = Probe() + masked.exec_known = False + masked.one(op, line) + check('exec-masked %s guards assignment' % op, + masked.lines == ['if (exec & 1) v1 = asuint(asint(v2 << 8) >> 8) * asuint(asint(v3 << 8) >> 8)%s;' % suffix]) + + # Unmodeled modifiers (including integer clamp) and wrong operand counts stay refused. + check('modifiers and operand modifiers refused', all(refused(a) for a in ( + 'v_mul_i32_i24 v1, v2, v3 clamp', 'v_mul_i32_i24 v1, v2, v3 mul:2', + 'v_mul_i32_i24 v1, v2, v3 div:2', 'v_mul_i32_i24 v1, v2, v3 op_sel:[1,0,0,0]', + 'v_mul_i32_i24 v1, -v2, v3', 'v_mul_i32_i24 v1, |v2|, v3', + 'v_mad_i32_i24 v1, v2, v3, v4 clamp', 'v_mad_i32_i24 v1, v2, v3, v4 mul:2', + 'v_mad_i32_i24 v1, v2, v3, v4 op_sel:[1,0,0,0]', 'v_mad_i32_i24 v1, -v2, v3, v4', + 'v_mad_i32_i24 v1, v2, |v3|, v4', 'v_mad_i32_i24 v1, v2, v3, -v4'))) + check('wrong operand counts refused', all(refused(a) for a in ( + 'v_mul_i32_i24 v1', 'v_mul_i32_i24 v1, v2', 'v_mul_i32_i24 v1, v2, v3, v4', + 'v_mad_i32_i24 v1', 'v_mad_i32_i24 v1, v2, v3', 'v_mad_i32_i24 v1, v2, v3, v4, v5'))) + + +def check_binary(llvm_mc): + for op in OPS: + built = assemble(llvm_mc, BODY_SOURCE[op]) + if built != BODY_WORDS[op]: + raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), BODY_WORDS[op].hex())) + for name, source, words in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + if assemble(llvm_mc, source) != words: + raise AssertionError('%s fixture differs from llvm-mc' % name) + for op in OPS: + for index in range(0, len(DRAW[op]), 4): + chunk = DRAW[op][index:index + 4] + if assemble(llvm_mc, vs_source(chunk)) != vs_words(chunk): + raise AssertionError('vertex fixture for %s %s differs from llvm-mc' % (op, chunk)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op in OPS: + good_ps = compile_hlsl(compiler, kind, translate(op)[1], 'ps_%s_%s' % (op, kind), ps_profile, directory) + for index in range(0, len(DRAW[op]), 4): + chunk = DRAW[op][index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + expected = words_text(ref_op(op, a, b, c) for a, b, c in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, op, chunk, run.stdout, run.stderr)) + print('%s %s draw %d: %s' % (kind, op, index // 4, expected), flush=True) + if index: + continue + wrong = words_text(mut_unsigned24(op, a, b, c) for a, b, c in chunk) + bad_ps = compile_hlsl(compiler, kind, translate(op, mutate=True)[1], + 'mutated_%s_%s' % (op, kind), ps_profile, directory) + run = draw(renderer, adapter, vs, bad_ps, expected) + if run.returncode == 0 or 'actual=%s' % wrong not in run.stderr: + raise AssertionError('%s %s mutation did not read %s\n%s\n%s' + % (kind, op, wrong, run.stdout, run.stderr)) + print('%s %s mutation: fails as expected, reads %s' % (kind, op, wrong), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 81b2fbeae..a810cee6f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5353,10 +5353,12 @@ def declarations(self): 'v_cvt_u32_f32': (1, 'uint(max(F({0}), 0.0))'), 'v_cvt_f16_f32': (1, 'f32tof16(F({0}))'), 'v_bfe_u32': (3, '({0} >> ({1} & 31)) & ((1u << ({2} & 31)) - 1)'), 'v_mad_u32_u24': (3, '({0} & 0xffffffu) * ({1} & 0xffffffu) + {2}'), + 'v_mad_i32_i24': (3, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8) + {2}'), 'v_lshl_add_u32': (3, '({0} << ({1} & 31)) + {2}'), 'v_add_lshl_u32': (3, '({0} + {1}) << ({2} & 31)'), 'v_add3_u32': (3, '{0} + {1} + {2}'), 'v_or3_b32': (3, '{0} | {1} | {2}'), 'v_xor3_b32': (3, '{0} ^ {1} ^ {2}'), 'v_and_or_b32': (3, '({0} & {1}) | {2}'), 'v_lshl_or_b32': (3, '({0} << ({1} & 31)) | {2}'), 'v_xad_u32': (3, '({0} ^ {1}) + {2}'), 'v_bfi_b32': (3, '({0} & {1}) | (~{0} & {2})'), 'v_mul_u32_u24': (2, '({0} & 0xffffffu) * ({1} & 0xffffffu)'), + 'v_mul_i32_i24': (2, 'asuint(asint({0} << 8) >> 8) * asuint(asint({1} << 8) >> 8)'), # Per-lane bit operations (AMD RDNA 2 ISA reference). The bitscan results count from the most significant # bit for the "h" forms and read 0xffffffff when no bit qualifies; firstbitlow(0) is already 0xffffffff. # v_bfe_i32 extracts a field at S1[4:0] of width S2[4:0] (0 reads 0) and sign-extends it from its top bit, From 82bb67ef70221f5c2d9a714f1ce379903258793a Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:39:29 +0100 Subject: [PATCH 115/232] shader: lower s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 in gfx2hlsl (continues #2086, Part of #1723) (#2512) * shader: lower s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 in gfx2hlsl Part of #1723. s_absdiff_i32 subtracts the smaller signed source from the larger, so an overflowing difference wraps like the hardware. SCC is unchanged by the pack forms and is result != 0 for s_absdiff_i32. * shader: wrap s_absdiff_i32 difference, refuse lane-mask and descriptor sources * tests: require a signed argument for abs in the gfx2hlsl integer evaluator HLSL abs of a uint is the identity, so an s_absdiff_i32 lowering that dropped asint would still have passed the evaluator. Assert that abs gets a signed value. AI-assisted. * tests: list startup_gfx2hlsl_pack_absdiff_check with the other pure-Python checks Add it to the Linux CI Python list and the AGENTS.md list next to startup_gfx2hlsl_sop2_complement_check, whose helpers it imports. AI-assisted. --------- Co-authored-by: tedin7 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + tests/startup_gfx2hlsl_bit_alu_check.py | 3 + tests/startup_gfx2hlsl_pack_absdiff_check.py | 67 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 13 +++- 6 files changed, 85 insertions(+), 3 deletions(-) create mode 100644 tests/startup_gfx2hlsl_pack_absdiff_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index a4b349932..b3672e430 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -270,6 +270,7 @@ jobs: tests/startup_gfx2hlsl_draw_skip_check.py \ tests/startup_gfx2hlsl_sdwa_cvt_check.py \ tests/startup_gfx2hlsl_sop2_complement_check.py \ + tests/startup_gfx2hlsl_pack_absdiff_check.py \ tests/startup_gfx2hlsl_sopk_accum_check.py \ tests/startup_gfx2hlsl_f32_lg_check.py \ tests/startup_gfx2hlsl_f32_nan_check.py \ diff --git a/AGENTS.md b/AGENTS.md index c9f576236..f7b9d1bea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -188,6 +188,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_recompute_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sop2_complement_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_absdiff_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sdwa_cvt_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_accum_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_int_med3_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e913e8013..8bdce47f1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3088,6 +3088,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") + # s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 against an integer reference (#1723). + add_test(NAME startup_gfx2hlsl_pack_absdiff COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_absdiff_check.py") # gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with # DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with. find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") diff --git a/tests/startup_gfx2hlsl_bit_alu_check.py b/tests/startup_gfx2hlsl_bit_alu_check.py index 3018f12a7..75f4e5e2a 100644 --- a/tests/startup_gfx2hlsl_bit_alu_check.py +++ b/tests/startup_gfx2hlsl_bit_alu_check.py @@ -267,6 +267,9 @@ def call(name, args): return v, True if name in ('asuint', 'uint'): return v, False + if name == 'abs': + assert s, 'abs of an unsigned value' # HLSL abs of a uint is the identity + return (-v if v & 0x80000000 else v) & MASK, True if name == 'min': assert not s and not rest[0][1] return min(v, rest[0][0]), False diff --git a/tests/startup_gfx2hlsl_pack_absdiff_check.py b/tests/startup_gfx2hlsl_pack_absdiff_check.py new file mode 100644 index 000000000..15a4fd0bd --- /dev/null +++ b/tests/startup_gfx2hlsl_pack_absdiff_check.py @@ -0,0 +1,67 @@ +"""s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 in tools/startup/gfx2hlsl.py (Part of #1723). + +Pure Python. Each form is built as a SOP2 word, decoded, translated, and the emitted lines run on the integer +evaluator of startup_gfx2hlsl_bit_alu_check.py over edge values (the encoder, forms and value set come from +startup_gfx2hlsl_sop2_complement_check.py). The references use plain integer arithmetic from the ISA meaning: + + s_pack_ll_b32_b16: D = (S0 & 0xffff) | (S1 << 16) SCC unchanged + s_pack_lh_b32_b16: D = (S0 & 0xffff) | (S1 & 0xffff0000) SCC unchanged + s_pack_hh_b32_b16: D = (S0 >> 16) | (S1 & 0xffff0000) SCC unchanged + s_absdiff_i32: D = |wrap32(S0 - S1)| (INT_MIN stays INT_MIN); SCC = (D != 0) + +Lane-mask operands of the pack forms and s_absdiff_i32 are refused (the per-lane projection has no whole word to read). +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import startup_gfx2hlsl_sop2_complement_check as C # noqa: E402 + +MASK = C.MASK + + +def signed(x): + return x - (1 << 32) if x & 0x80000000 else x + + +REFERENCES = { + 's_pack_ll_b32_b16': (lambda a, b: (a & 0xffff) | ((b << 16) & MASK), False), + 's_pack_lh_b32_b16': (lambda a, b: (a & 0xffff) | (b & 0xffff0000), False), + 's_pack_hh_b32_b16': (lambda a, b: (a >> 16) | (b & 0xffff0000), False), + 's_absdiff_i32': (lambda a, b: abs(signed((a - b) & MASK)) & MASK, True), +} + + +def main(): + for name, (reference, scc) in REFERENCES.items(): + C.OPCODE[name] = next(op for op, (n, _) in C.D.SOP2_OPS.items() if n == name) + bad = C.first_mismatch(name, reference, updates_scc=scc) + C.check('%s value and SCC' % name, bad is None, str(bad)) + if name.startswith('s_pack') or name == 's_absdiff_i32': + for form in C.MASK_FORMS: + _, stage = C.attempt(C.code(name, form)) + C.check('%s refuses lane mask form %r' % (name, form), stage.lines[0].startswith('refused: ')) + # the wrapped difference of 0x80000000 and 1 is 0x7fffffff; a compare-first lowering gives 0x80000001 + C.check('absdiff overflow reference', REFERENCES['s_absdiff_i32'][0](0x80000000, 1) == 0x7fffffff) + # a symbolic descriptor source must be refused before SCC is left stale + for name in REFERENCES: + stage = C.Probe() + stage.sym[1] = ('ptr', 0, 0) + try: + stage.one(name, '%s s3, s1, s2' % name) + except C.G.Unsupported: + C.check('%s refuses a descriptor source' % name, not stage.lines) + else: + C.check('%s refuses a descriptor source' % name, False, str(stage.lines)) + # a wrong reference must be caught: swapped sources + swapped = C.first_mismatch('s_pack_lh_b32_b16', lambda a, b: REFERENCES['s_pack_lh_b32_b16'][0](b, a), False) + C.check('swapped pack_lh reference is caught', swapped is not None) + if C.failures: + print('FAILED: %s' % ', '.join(C.failures)) + sys.exit(1) + print('startup_gfx2hlsl_pack_absdiff_check: ok') + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a810cee6f..826ed642b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2758,8 +2758,9 @@ def low(tok): word_complement = base in ('s_nand_b32', 's_nor_b32', 's_xnor_b32') lane_complement = False # s_mul_hi_u32 needs the whole 32-bit word of each source, like the halfword pack. - word_pack = base in ('s_pack_hh_b32_b16', 's_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') - if shift_add or word_complement or word_pack: + word_pack = base in PACK_B16 or base in ('s_sext_i32_i8', 's_sext_i32_i16', 's_mul_hi_u32') + word_absdiff = base == 's_absdiff_i32' + if shift_add or word_complement or word_pack or word_absdiff: # The per-lane mask cannot supply the full word needed by these operations. s_mul_hi_u32 into an # SGPR that held a mask replaces it with a plain word (set_s drops the mark), so only vcc/exec count. mask_dest = (dname in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') if base == 's_mul_hi_u32' @@ -2799,7 +2800,7 @@ def src_sym(t): self.scc_effect = 'descriptor' if self.tracks_uniformity(): self.scc_uniform = False - if shift_add or word_complement: + if shift_add or word_complement or word_absdiff: raise Unsupported('scc from descriptor data') if word_pack: raise Unsupported('%s on descriptor data' % base) @@ -5380,6 +5381,7 @@ def declarations(self): SCC_UNMODELLED = frozenset(('s_add_i32', 's_add_u32', 's_sub_i32', 's_sub_u32', 's_min_i32', 's_min_u32', 's_max_i32', 's_max_u32')) +PACK_B16 = frozenset(('s_pack_ll_b32_b16', 's_pack_lh_b32_b16', 's_pack_hh_b32_b16')) SCA = { 's_mov_b32': ('{0}', None), 's_mov_b64': ('{0}', None), 's_movk_i32': ('{0}', None), 's_and_b32': ('{0} & {1}', '$ != 0'), 's_or_b32': ('{0} | {1}', '$ != 0'), 's_xor_b32': ('{0} ^ {1}', '$ != 0'), @@ -5400,7 +5402,12 @@ def declarations(self): # s_sext_i32_iN: sign-extend the low N bits of S0; SCC unchanged. 's_sext_i32_i8': ('uint(int({0} << 24) >> 24)', None), 's_sext_i32_i16': ('uint(int({0} << 16) >> 16)', None), + # s_pack_*_b32_b16: two halfwords of the sources into one word; SCC unchanged. + 's_pack_ll_b32_b16': ('({0} & 0xffffu) | ({1} << 16)', None), + 's_pack_lh_b32_b16': ('({0} & 0xffffu) | ({1} & 0xffff0000u)', None), 's_pack_hh_b32_b16': ('({0} >> 16) | ({1} & 0xffff0000u)', None), + # s_absdiff_i32: D = S0 - S1 wrapped to 32 bits, negated if negative (INT_MIN stays); SCC = result != 0. + 's_absdiff_i32': ('asuint(abs(asint({0} - {1})))', '$ != 0'), # s_bfm_b32: a mask of S0[4:0] ones shifted left by S1[4:0]; SCC unchanged. 's_bfm_b32': ('(((1u << ({0} & 31)) - 1) << ({1} & 31))', None), # s_lshlN_add_u32: low 32 bits of (S0 << N) + S1. SHIFT_ADD also supplies SCC for wide overflow. From 29f988a8bb4c58d376e8bed4670bfbd16d533955 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 21:40:54 +0200 Subject: [PATCH 116/232] runtime: add main(argv), csv.Error/directory guards, and CLI suite in startup_audio_timeline (#2440) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/startup_audio_timeline_cli_check.py | 314 ++++++++++++++++++++++ tools/startup_audio_timeline.py | 13 +- 3 files changed, 325 insertions(+), 4 deletions(-) create mode 100644 tests/startup_audio_timeline_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8bdce47f1..149459b4f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1177,6 +1177,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_audio_timeline COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_audio_timeline_check.py") set_tests_properties(startup_audio_timeline PROPERTIES TIMEOUT 60) + add_test(NAME startup_audio_timeline_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_audio_timeline_cli_check.py") endif() target_compile_features(startup_dump_fence_check PRIVATE cxx_std_17) target_include_directories(startup_dump_fence_check PRIVATE src) diff --git a/tests/startup_audio_timeline_cli_check.py b/tests/startup_audio_timeline_cli_check.py new file mode 100644 index 000000000..18fe157a0 --- /dev/null +++ b/tests/startup_audio_timeline_cli_check.py @@ -0,0 +1,314 @@ +"""CLI, csv.Error/directory guard, and mutation control suite for tools/startup_audio_timeline.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import csv +import io +import json +import math +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "startup_audio_timeline.py" +sys.path.insert(0, str(ROOT / "tools")) + +import startup_audio_timeline as timeline # noqa: E402 + + +EVENT_KEYS = { + "action", + "qpc", + "start_qpc", + "end_qpc", + "coverage", + "packets", + "discontinuities", + "rms_estimate", + "packet_peak", +} + + +def _csv_bytes(rows: list[list[object]], *, bom: bool = True) -> bytes: + buf = io.StringIO() + writer = csv.writer(buf, lineterminator="\n") + writer.writerow(["process_s", "frames", "rms", "peak", "flags"]) + writer.writerows(rows) + return buf.getvalue().encode("utf-8-sig" if bom else "utf-8") + + +def _jsonl_bytes(events: list[dict[str, object]], *, bom: bool = True) -> bytes: + text = "\n\n".join(json.dumps(item) for item in events) + "\n" + return text.encode("utf-8-sig" if bom else "utf-8") + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = timeline.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class StartupAudioTimelineCliPositiveTests(unittest.TestCase): + def test_bom_csv_multiple_actions_flags4_skip_silence_and_json_schema(self) -> None: + # sample_rate=2000 -> 500 frames = 0.25 s. + packets_bytes = _csv_bytes( + [ + [1.0, 500, 0.4, 0.8, 1], # 101.00..101.25 (discontinuity) + [1.25, 500, 0.2, 0.5, 0], # 101.25..101.50 + [2.0, 500, 0.9, 0.95, 4], # flags & 4: WASAPI timestamp error -> skipped! + ], + bom=True, + ) + inputs_bytes = _jsonl_bytes( + [ + {"action": "jump", "qpc": 101.25}, + {"action": "ignored", "qpc": 101.25}, + {"action": "silence", "qpc": 102.25}, + ], + bom=True, + ) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + packets = root / "packets.csv" + inputs = root / "inputs.jsonl" + packets.write_bytes(packets_bytes) + inputs.write_bytes(inputs_bytes) + + argv = [ + str(packets), + str(inputs), + "--process-origin-qpc", "100", + "--sample-rate", "2000", + "--before", "0.25", + "--after", "0.25", + "--action", "jump", + "--action", "silence", + ] + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(set(doc), {"events"}) + self.assertEqual(len(doc["events"]), 2) + for row in doc["events"]: + self.assertEqual(set(row), EVENT_KEYS) + + by_action = {row["action"]: row for row in doc["events"]} + jump = by_action["jump"] + self.assertAlmostEqual(jump["start_qpc"], 101.0) + self.assertAlmostEqual(jump["end_qpc"], 101.5) + self.assertAlmostEqual(jump["coverage"], 1.0) + self.assertEqual(jump["packets"], 2) + self.assertEqual(jump["discontinuities"], 1) + self.assertAlmostEqual(jump["rms_estimate"], math.sqrt((0.4**2 + 0.2**2) / 2)) + self.assertEqual(jump["packet_peak"], 0.8) + + silence = by_action["silence"] + self.assertAlmostEqual(silence["coverage"], 0.0) + self.assertEqual(silence["packets"], 0) + self.assertEqual(silence["discontinuities"], 0) + self.assertIsNone(silence["rms_estimate"]) + self.assertIsNone(silence["packet_peak"]) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), doc) + + def test_main_forwards_sys_argv_and_script_entrypoint_returns_zero(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + packets = root / "packets.csv" + inputs = root / "inputs.jsonl" + packets.write_bytes(_csv_bytes([[0.5, 4800, 0.25, 0.5, 0]])) + inputs.write_bytes(_jsonl_bytes([{"action": "fire", "qpc": 10.5}])) + cli_argv = [ + str(TOOL), + str(packets), + str(inputs), + "--process-origin-qpc", "10", + "--action", "fire", + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(json.loads(out)["events"]), 1) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(len(json.loads(stdout.getvalue())["events"]), 1) + + +class StartupAudioTimelineCliNegativeAndMutationTests(unittest.TestCase): + def _assert_exit_2(self, argv: list[str], *, expected_fragment: str = "", check_subprocess: bool = True) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip()) + if expected_fragment: + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + if expected_fragment: + self.assertIn(expected_fragment, proc.stderr) + + def test_missing_and_directory_paths_rejected_upfront_exit_2(self) -> None: + # Kills removal of OSError guard and removal of is_dir() guards for packets and inputs. + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_csv = root / "packets.csv" + valid_jsonl = root / "inputs.jsonl" + valid_csv.write_bytes(_csv_bytes([[0.0, 4800, 0.1, 0.2, 0]])) + valid_jsonl.write_bytes(_jsonl_bytes([{"action": "a", "qpc": 100.0}])) + missing = root / "missing" + dir_path = root / "a_dir" + dir_path.mkdir() + + base_flags = ["--process-origin-qpc", "100", "--action", "a"] + + self._assert_exit_2([str(missing), str(valid_jsonl), *base_flags], expected_fragment=missing.name) + self._assert_exit_2([str(valid_csv), str(missing), *base_flags], expected_fragment=missing.name) + + with ( + mock.patch.object(timeline, "read_packets") as read_packets_mock, + mock.patch.object(timeline, "read_events") as read_events_mock, + ): + self._assert_exit_2( + [str(dir_path), str(valid_jsonl), *base_flags], + expected_fragment="Packets path is a directory", + check_subprocess=False, + ) + self._assert_exit_2( + [str(valid_csv), str(dir_path), *base_flags], + expected_fragment="Inputs path is a directory", + check_subprocess=False, + ) + read_packets_mock.assert_not_called() + read_events_mock.assert_not_called() + + self._assert_exit_2([str(dir_path), str(valid_jsonl), *base_flags], + expected_fragment="Packets path is a directory") + self._assert_exit_2([str(valid_csv), str(dir_path), *base_flags], + expected_fragment="Inputs path is a directory") + + def test_csv_error_and_non_utf8_inputs_exit_2_without_traceback(self) -> None: + # NUL byte triggers csv.Error in csv.DictReader (kills removal of csv.Error from except tuple). + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_csv = root / "valid.csv" + valid_jsonl = root / "valid.jsonl" + valid_csv.write_bytes(_csv_bytes([[0.0, 4800, 0.1, 0.2, 0]])) + valid_jsonl.write_bytes(_jsonl_bytes([{"action": "a", "qpc": 100.0}])) + flags = ["--process-origin-qpc", "100", "--action", "a"] + + nul_csv = root / "nul.csv" + nul_csv.write_bytes(b"process_s,frames,rms,peak,flags\n0.0,4800,\x000.1,0.2,0\n") + self._assert_exit_2([str(nul_csv), str(valid_jsonl), *flags], expected_fragment="nul.csv:2:") + + # Field larger than csv.field_size_limit() triggers real csv.Error in both in-process & subprocess. + oversized_csv = root / "oversized.csv" + oversized_csv.write_bytes( + b"process_s,frames,rms,peak,flags\n" + b"0." + b"1" * (csv.field_size_limit() + 16) + b",4800,0.1,0.2,0\n" + ) + self._assert_exit_2([str(oversized_csv), str(valid_jsonl), *flags], expected_fragment="field limit") + + with mock.patch.object(timeline, "read_packets", side_effect=csv.Error("malformed CSV record")): + self._assert_exit_2( + [str(valid_csv), str(valid_jsonl), *flags], + expected_fragment="malformed CSV record", + check_subprocess=False, + ) + + bad_utf8_csv = root / "bad_utf8.csv" + bad_utf8_csv.write_bytes(b"\xff\xfe\x80") + self._assert_exit_2([str(bad_utf8_csv), str(valid_jsonl), *flags]) + + bad_utf8_jsonl = root / "bad_utf8.jsonl" + bad_utf8_jsonl.write_bytes(b"\xff\xfe\x80") + self._assert_exit_2([str(valid_csv), str(bad_utf8_jsonl), *flags]) + + def test_malformed_jsonl_nan_inf_and_window_bounds_exit_2(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_csv = root / "valid.csv" + valid_jsonl = root / "valid.jsonl" + valid_csv.write_bytes(_csv_bytes([[0.0, 4800, 0.1, 0.2, 0]])) + valid_jsonl.write_bytes(_jsonl_bytes([{"action": "a", "qpc": 100.0}])) + flags = ["--process-origin-qpc", "100", "--action", "a"] + + for label, content in ( + ("non_object_list", "[1, 2]\n"), + ("non_object_int", "42\n"), + ("bad_json", "{broken\n"), + ("nan_qpc", '{"action": "a", "qpc": NaN}\n'), + ("inf_qpc", '{"action": "a", "qpc": Infinity}\n'), + ): + with self.subTest(jsonl=label): + bad_jsonl = root / f"{label}.jsonl" + bad_jsonl.write_text(content, encoding="utf-8") + self._assert_exit_2([str(valid_csv), str(bad_jsonl), *flags], expected_fragment=bad_jsonl.name) + + for label, row in ( + ("nan_process_s", ["nan", 4800, 0.1, 0.2, 0]), + ("inf_rms", [0.0, 4800, "inf", 0.2, 0]), + ("nan_peak", [0.0, 4800, 0.1, "nan", 0]), + ("bad_header", None), + ): + with self.subTest(csv_case=label): + bad_csv = root / f"{label}.csv" + bad_csv.write_bytes( + b"wrong,columns\n1,2\n" if row is None else _csv_bytes([row]) + ) + self._assert_exit_2([str(bad_csv), str(valid_jsonl), *flags]) + + for bad_opts in ( + ["--process-origin-qpc", "nan", "--action", "a"], + ["--process-origin-qpc", "inf", "--action", "a"], + ["--process-origin-qpc", "100", "--action", "a", "--before", "0", "--after", "0"], + ["--process-origin-qpc", "100", "--action", "a", "--before", "-0.1"], + ["--process-origin-qpc", "100", "--action", "a", "--sample-rate", "0"], + ): + with self.subTest(opts=bad_opts): + self._assert_exit_2([str(valid_csv), str(valid_jsonl), *bad_opts]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup_audio_timeline.py b/tools/startup_audio_timeline.py index 23ea926ee..bb80d4422 100644 --- a/tools/startup_audio_timeline.py +++ b/tools/startup_audio_timeline.py @@ -94,7 +94,7 @@ def window(packets, start, end): } -def main(): +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("packets", type=Path, help="CSV with seconds relative to process creation") parser.add_argument("inputs", type=Path, help="JSONL with QPC seconds and action names") @@ -103,19 +103,24 @@ def main(): parser.add_argument("--action", required=True, action="append", help="action to include, repeatable") parser.add_argument("--before", type=finite, default=0.44, help="seconds before the event") parser.add_argument("--after", type=finite, default=0.30, help="seconds after the event") - args = parser.parse_args() + args = parser.parse_args(argv) if args.sample_rate < 1 or min(args.before, args.after) < 0 or args.before + args.after == 0: parser.error("sample rate and total window length must be positive, and endpoints nonnegative") try: + if args.packets.is_dir(): + raise ValueError(f"Packets path is a directory: {args.packets}") + if args.inputs.is_dir(): + raise ValueError(f"Inputs path is a directory: {args.inputs}") packets = read_packets(args.packets, args.process_origin_qpc, args.sample_rate) events = [ {"action": name, "qpc": at, **window(packets, at - args.before, at + args.after)} for name, at in read_events(args.inputs, set(args.action)) ] - except (OSError, ValueError) as error: + except (OSError, ValueError, csv.Error) as error: parser.error(str(error)) print(json.dumps({"events": events}, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From e864213ae72016c3deb52a388576bd64addc2fae Mon Sep 17 00:00:00 2001 From: Roan System Date: Wed, 25 Nov 2026 20:41:12 +0100 Subject: [PATCH 117/232] shader: lower compute DPP16 row_shr for OR and ADD (#1884) v_or_b32_dpp and v_add_nc_u32_dpp with row_shr:1..15 and full row and bank masks read src0 from lane - n of the same 16-lane row of logical 1D lanes, staged in group-shared memory by SV_GroupThreadID.x. A lane whose source is before its row start uses 0 as src0 with BOUND_CTRL and keeps its old destination without it. Only 1D groups divisible by 16 and uniform participation are accepted. The source-built gfx1013 fixture runs shifts 1, 8 and 15 with and without BOUND_CTRL against a per-lane CPU reference; a cross-row mutant and a zero-instead-of-old mutant must fail at their predicted first word. Refs #1543. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 6 + README.md | 2 +- docs/experiments.md | 12 +- tests/compute_dpp_row_shr_check.py | 308 +++++++++++++++++++++++++++++ tools/compute_store_aot.py | 30 +++ 6 files changed, 358 insertions(+), 2 deletions(-) create mode 100644 tests/compute_dpp_row_shr_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index b3672e430..e2c37d2a4 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -131,6 +131,7 @@ jobs: (["tests/startup_smem_address_check.py", "binary", "llvm-mc-15"], {}), (["tests/compute_entry_layout_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_ngg_slice_check.py", "binary", "llvm-mc-15"], {}), + (["tests/compute_dpp_row_shr_check.py", *COMMON_LLVM], {}), ] sys.exit(runpy.run_path("tools/run_checks_parallel.py", run_name="run_checks_parallel")["run_checks"](CHECKS)) @@ -192,6 +193,7 @@ jobs: tests/mesh_lane_spill_check.py \ tests/mesh_join_descriptor_check.py \ tests/mesh_loop_census_check.py \ + tests/compute_dpp_row_shr_check.py \ tests/pso_readiness_check.py \ tests/xmem_attribute_scan_check.py \ tests/xgameruntime_table_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 149459b4f..2cf03b092 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8629,6 +8629,12 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_readlane_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_readlane_${adapter}.txt") + # DPP16 row_shr with and without BOUND_CTRL on 16-lane logical rows (#1543). + add_test(NAME compute_store_aot_dpp_row_shr_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_dpp_row_shr_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_dpp_row_shr_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_dpp_row_shr_${adapter}.txt") add_test(NAME compute_store_aot_guard_read_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_store_check.py" draw-guard-read "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index f57a5719e..8ee064816 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | Texture recovery | [Decode MDU rANS symbols](docs/experiments.md#decoding-mdu-rans-symbol-streams) using [bcpack-rs by Ahmet Dedeler](https://github.com/Ahmet-Dedeler/bcpack-rs), or check a packed mip tail, a first refill byte, the fields of a generated BC7 block, or a resident mip drawn on the software adapter. [Look up a texture key across archives and inspect a matching descriptor](docs/experiments.md#reading-logical-ranges-and-probing-structured-resources). [Batch export TTPF textures with optional Rust kernels](docs/experiments.md#batch-export-ttpf-textures-to-dds). | `ctest --preset dev --no-tests=error -R '^(bcpack_prefix_and_mip_tail\|bcpack_rans_symbols\|bc7_block_reference\|bc7_draw_warp\|resource_range_controls)$' -V` | | Audio metadata | Inventory stream counts, codec IDs and sample rates in a bounded [AWC sound-effect or music bank](docs/experiments.md#awc-sound-effect-format-metadata) with flag word `0xff000001` or `0xff020001`. | `ctest --preset dev --no-tests=error -R '^audio_awc_metadata$' -V` | | Compute shader recompilation | Translate fixed, indexed and row-pitch raw UAV stores for 1D, 2D and 3D thread groups, including an optional runtime constant buffer, and compare the complete buffer on D3D12. [Bindings and commands](docs/experiments.md#compute-uav-stores-from-a-native-container) · [Bounded gfx1030 DS lane routing](docs/experiments.md#bounded-gfx1030-ds-lane-routing) · [Private gfx1030 LDS access and updates, including 64-bit min/max and xor](docs/experiments.md#private-gfx1030-lds-word-access) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_'` | -| gfx1013 compute DPP16 | Lower `v_or_b32_dpp` with `quad_perm` and full row/bank masks; compare a source-built fixture with a logical-thread reference. [Scope and limits](docs/experiments.md#gfx1013-compute-dpp16-quad-permutation) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_dpp_' -V` | +| gfx1013 compute DPP16 | Lower `v_or_b32_dpp` with `quad_perm`, and `v_or_b32_dpp`/`v_add_nc_u32_dpp` with `row_shr:1`–`15` with or without `bound_ctrl`, under full row/bank masks; compare source-built fixtures with logical-thread references. Scope and limits: [quad_perm](docs/experiments.md#gfx1013-compute-dpp16-quad-permutation), [row_shr](docs/experiments.md#gfx1013-compute-dpp16-row-shift-right) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_dpp_' -V` | | gfx1013 pixel DPP quad broadcast | Lower `quad_perm:[k,k,k,k]` on VOP1/VOP2 after `s_wqm exec, exec` in a straight-line pixel stage to `QuadReadLaneAt` (`ps_6_0`, DXC); draw 16 x 16 pixels and compare with a CPU reference. [Scope and limits](docs/experiments.md#gfx1013-pixel-dpp16-quad-broadcast) | `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V` | | gfx1013 compute readlane | Lower a statically selected, defined `v_readlane_b32` source through logical wave32 group-shared staging. [Scope and limits](docs/experiments.md#gfx1013-compute-readlane) | `ctest --preset dev --no-tests=error -R '^compute_store_aot_readlane_' -V` | | gfx1030 typed-buffer writes | Lower [indexed UINT `tbuffer_store_format_*`](docs/experiments.md#indexed-gfx1030-typed-buffer-writes) for one to four 32-bit or packed 16-bit components. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mtbuf_store_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 502854cee..56530e069 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4089,7 +4089,7 @@ With `--rsrc2 ` (`rsrc2=` in `lower`), the translation places ### gfx1013 compute DPP16 quad permutation -The compute profile lowers `v_or_b32_dpp` only when it has a 32-bit VGPR destination and sources, `quad_perm:[a,b,c,d]`, and both full masks (`row_mask:0xf bank_mask:0xf`). It selects the source from a logical four-thread quad using SV_GroupThreadID.x and group-shared staging. The other OR operand is local to the current thread. Only 1D groups with X divisible by four are accepted, and DPP inside a lane-guarded region is refused. Other DPP opcodes, row/bank shifts, partial masks and DPP8 remain unsupported. +The compute profile lowers `v_or_b32_dpp` only when it has a 32-bit VGPR destination and sources, `quad_perm:[a,b,c,d]`, and both full masks (`row_mask:0xf bank_mask:0xf`). It selects the source from a logical four-thread quad using SV_GroupThreadID.x and group-shared staging. The other OR operand is local to the current thread. Only 1D groups with X divisible by four are accepted, and DPP inside a lane-guarded region is refused. Other DPP opcodes, partial masks and DPP8 remain unsupported; `row_shr` is described in [its own section](#gfx1013-compute-dpp16-row-shift-right), and the other row controls remain unsupported. The binary-mode check assembles and disassembles the source-built gfx1013 program through LLVM 15 in CI, then compares lowering of the disassembly with lowering of the assembly text. @@ -4109,6 +4109,16 @@ The source-built gfx1013 fixture uses distinct input words and checks both one-w ctest --preset dev --no-tests=error -R '^compute_store_aot_readlane_(warp|hardware)$' -V ``` +### gfx1013 compute DPP16 row shift right + +The compute profile lowers `v_or_b32_dpp` and `v_add_nc_u32_dpp` with `row_shr:1` to `row_shr:15`, 32-bit VGPR operands and both full masks (`row_mask:0xf bank_mask:0xf`). Rows are 16 of the guest's logical 1D lanes: lane `x` reads src0 from lane `x - n` through group-shared staging indexed by `SV_GroupThreadID.x`, so the result does not depend on the desktop wave width. A lane whose source falls before the start of its row uses 0 as src0 when `BOUND_CTRL` is set and keeps its old destination when it is not; the old destination must then be a known word. LLVM 15 assembles `bound_ctrl:0` and `bound_ctrl:1` to the same set bit and prints `bound_ctrl:1`; the lowering accepts both spellings. Only 1D groups with X divisible by 16 are accepted, and uniform participation is required: DPP after a lane guard is refused. `row_shl`, `row_ror`, `row_share`, `row_xmask`, the other DPP16 controls, `fi:1`, partial masks and other opcodes remain unsupported. + +`tests/compute_dpp_row_shr_check.py` uses an original source-built gfx1013 program. One group of 64 threads (four rows) loads a word that is unique for each lane and row and stores four words per thread: OR and ADD, each with and without `BOUND_CTRL`. ADD shifts that word XOR a key, so a step that read another step's staged words would differ. Without `BOUND_CTRL` the old destination is the dispatch index XOR a key. The program runs with shifts 1, 8 and 15, and all 320 words are compared with a per-lane CPU reference, including the 64 sentinel words after the records. Two mutants of the generated HLSL must fail at a predicted first word: reading across the row boundary fails at word 64 (thread 16), and writing 0 instead of keeping the old destination fails at word 1 (thread 0). The binary mode assembles the program with LLVM 15 using both `bound_ctrl` spellings, requires identical encodings with bit 19 set, decodes them and requires the same translation. + +```powershell +ctest --preset dev --no-tests=error -R '^compute_store_aot_dpp_row_shr_(warp|hardware)$' -V +``` + ### gfx1030 MUBUF cache-invalidation rejection The compute store profile rejects `buffer_gl0_inv` and `buffer_gl1_inv` diff --git a/tests/compute_dpp_row_shr_check.py b/tests/compute_dpp_row_shr_check.py new file mode 100644 index 000000000..f83e81206 --- /dev/null +++ b/tests/compute_dpp_row_shr_check.py @@ -0,0 +1,308 @@ +"""DPP16 row_shr in tools/compute_store_aot.py for gfx1013 compute (#1543). + + (no arguments) translation and refusal controls, pure Python + binary + assemble and decode the fixture with LLVM 15, translate both + draw + translate, dispatch and compare the readback + +`v_or_b32_dpp` and `v_add_nc_u32_dpp` with `row_shr:n` (1..15) and full row and bank masks read +src0 from lane - n of the same 16-lane row. A lane whose source is before its row start uses 0 as +src0 when BOUND_CTRL is set and keeps its old destination when it is not. The translation indexes +the guest's logical 1D lanes (SV_GroupThreadID.x) through group-shared memory, as the quad_perm +slice does, so the result does not depend on the desktop wave width. + +The fixture is an original program, source-built for gfx1013. One group of 64 threads (four rows) +loads a word that is unique for each lane and each row, and stores four words per thread: OR and +ADD, each with and without BOUND_CTRL. It runs with shifts 1, 8 and 15. A per-lane CPU reference +gives all 320 words, including the 64 sentinel words after the records. Two mutants of the +generated HLSL must fail at a predicted first word: one reads across the row boundary, one writes +0 where the old destination must be kept. +""" +import os +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")) +import compute_store_aot as aot # noqa: E402 +from pixel_aot import disassemble # noqa: E402 + +SENTINEL = 0xc5c5c5c5 +WORDS = 320 +THREADS = 64 +SHIFTS = (1, 8, 15) +# Each thread keeps these words before the DPP without BOUND_CTRL: its dispatch index XOR a key. +OLD_KEYS = {"or": 0x6b000000, "add": 0x6c000000} +# ADD reads src0 = source word XOR this key, so a step that read another step's staged words would differ. +ADD_SOURCE_KEY = 0x00a50000 +# The four stored words of each thread, in store order: (operation, BOUND_CTRL). +STEPS = (("or", True), ("or", False), ("add", True), ("add", False)) +BINDING = dict(table_reg=0, descriptor_offset=0, constant_descriptor=32, group_reg=1, stride=16, + source_descriptor=16) + + +def program(shift, spelling="bound_ctrl:1"): + """v1 = source word tid, v7 = v1 ^ key, v0 = tid; OR shifts v1 and ADD shifts v7. + + v5/v6 are written with BOUND_CTRL; v2/v4 keep tid ^ key without it. + """ + masks = f"row_shr:{shift} row_mask:0xf bank_mask:0xf" + return [ + "s_mov_b32 s2, s1", + "s_mov_b32 s1, 0", + "v_lshl_add_u32 v0, s2, 6, v0", + "s_load_dwordx4 s[4:7], s[0:1], 0x20", + "s_waitcnt lgkmcnt(0)", + "s_load_dwordx8 s[8:15], s[0:1], 0x0", + "s_waitcnt lgkmcnt(0)", + "v_lshlrev_b32_e32 v3, 2, v0", + "buffer_load_dword v1, v3, s[12:15], 0 offen", + "s_waitcnt vmcnt(0)", + f"v_xor_b32_e32 v2, 0x{OLD_KEYS['or']:x}, v0", + f"v_xor_b32_e32 v4, 0x{OLD_KEYS['add']:x}, v0", + f"v_xor_b32_e32 v7, 0x{ADD_SOURCE_KEY:x}, v1", + f"v_or_b32_dpp v5, v1, v0 {masks} {spelling}", + f"v_or_b32_dpp v2, v1, v0 {masks}", + f"v_add_nc_u32_dpp v6, v7, v0 {masks} {spelling}", + f"v_add_nc_u32_dpp v4, v7, v0 {masks}", + "buffer_store_dword v5, v0, s[8:11], 0 idxen", + "buffer_store_dword v2, v0, s[8:11], 0 idxen offset:4", + "buffer_store_dword v6, v0, s[8:11], 0 idxen offset:8", + "buffer_store_dword v4, v0, s[8:11], 0 idxen offset:12", + "s_endpgm", + ] + + +def translate(lines, group=THREADS, **change): + return aot.lower(lines, group, **(BINDING | change)) + + +def source_word(i): + """t0 as offscreen_check fills it: 320 known words.""" + return (0x8b02a7f1 + i * 0x413b1) & 0xffffffff + + +def expected(shift, mutant=None): + """The readback from a per-lane model of row_shr, independent of the translator. + + mutant "cross_row" bounds the source by the group start instead of the row start; + mutant "zero" writes 0 where a lane without BOUND_CTRL keeps its old destination. + """ + words = [SENTINEL] * WORDS + for tid in range(THREADS): + inside = (tid if mutant == "cross_row" else tid % 16) >= shift + for k, (op, bound) in enumerate(STEPS): + key = ADD_SOURCE_KEY if op == "add" else 0 + src0 = source_word(tid - shift) ^ key if inside else 0 + result = (src0 | tid) if op == "or" else (src0 + tid) & 0xffffffff + if not (inside or bound): + result = 0 if mutant == "zero" else tid ^ OLD_KEYS[op] + words[4 * tid + k] = result + return words + + +def mutate(source, mutant): + """Apply one mutant to every DPP step of the generated HLSL.""" + if mutant == "cross_row": + pattern, replacement = r"bool (dpp\d+)_inside = \1_row_lane >= ", r"bool \1_inside = local.x >= " + else: + pattern, replacement = r"(uint dpp\d+_value = dpp\d+_inside \? .+) : \(.+\);", r"\1 : 0u;" + mutated, count = re.subn(pattern, replacement, source) + assert count == (4 if mutant == "cross_row" else 2), (mutant, count) + return mutated + + +def first_difference(left, right): + return next(i for i, (a, b) in enumerate(zip(left, right)) if a != b) + + +def rejects(message, function, *args, **kwargs): + try: + function(*args, **kwargs) + except ValueError as error: + assert message in str(error), (message, error) + return + raise AssertionError(f"accepted; expected {message!r}") + + +def variant(lines, old, new): + assert sum(old in line for line in lines) == 1, old + return [line.replace(old, new) for line in lines] + + +def controls(): + # The fixture words are unique for every lane of every row. + words = [source_word(i) for i in range(THREADS)] + assert len(set(words)) == THREADS and all(len(set(words[r:r + 16])) == 16 for r in range(0, THREADS, 16)) + + lines = translate(program(8)).splitlines() + assert "groupshared uint dpp_stage[64];" in lines, lines + step = lines.index(" uint dpp0_row_lane = local.x & 15u;") + assert lines[step:step + 8] == [ + " uint dpp0_row_lane = local.x & 15u;", + " bool dpp0_inside = dpp0_row_lane >= 8u;", + " dpp_stage[local.x] = inputData.Load((tid.x << 2u) + 0u);", + " GroupMemoryBarrierWithGroupSync();", + " uint dpp0_source_thread = dpp0_inside ? local.x - 8u : local.x;", + " uint dpp0_source = dpp0_inside ? dpp_stage[dpp0_source_thread] : 0u;", + " GroupMemoryBarrierWithGroupSync();", + " uint dpp0_value = (dpp0_source | (tid.x));", + ], lines + text = "\n".join(lines) + # Without BOUND_CTRL an out-of-row lane keeps the old destination, tid ^ key. + assert " uint dpp1_value = dpp1_inside ? (dpp1_source | (tid.x)) : ((0x6b000000u ^ tid.x));" in lines, text + assert " uint dpp2_value = (dpp2_source + (tid.x));" in lines, text + # ADD stages its own source, different from OR's. + assert f" dpp_stage[local.x] = (0x{ADD_SOURCE_KEY:08x}u ^ inputData.Load((tid.x << 2u) + 0u));" in lines, text + assert " uint dpp3_value = dpp3_inside ? (dpp3_source + (tid.x)) : ((0x6c000000u ^ tid.x));" in lines, text + assert text.count("GroupMemoryBarrierWithGroupSync();") == 8, text + assert "Wave" not in text, "the logical-lane model must not use wave intrinsics" + # Every shift from 1 to 15 is accepted, and both LLVM 15 spellings of the set bit lower identically. + for shift in range(1, 16): + assert f"bool dpp0_inside = dpp0_row_lane >= {shift}u;" in translate(program(shift)) + assert translate(program(shift, "bound_ctrl:0")) == translate(program(shift)) + # A group of 16 (one row) and of 1024 are accepted. + assert "groupshared uint dpp_stage[16];" in translate(variant(program(1), "s2, 6, v0", "s2, 4, v0"), 16) + assert "groupshared uint dpp_stage[1024];" in translate(variant(program(1), "s2, 6, v0", "s2, 10, v0"), 1024) + print("row_shr: shifts 1-15, OR and ADD, BOUND_CTRL set and clear, groups of 16 to 1024") + + # With BOUND_CTRL the old destination is never read, so an unwritten one is accepted. + no_old = variant(program(1), f"v_xor_b32_e32 v2, 0x{OLD_KEYS['or']:x}, v0", "s_nop 0") + rejects("Unverified DPP16 operand", translate, no_old) + bound_only = variant(no_old, "v_or_b32_dpp v2, v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf", + "v_or_b32_dpp v2, v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1") + translate(bound_only) + + dpp = "v_or_b32_dpp v5, v1, v0 row_shr:8 row_mask:0xf bank_mask:0xf bound_ctrl:1" + unsupported = "Unsupported compute instruction: v_" + for form in (dpp.replace("row_shr:8", "row_shl:8"), dpp.replace("row_shr:8", "row_ror:8"), + dpp.replace("row_shr:8", "row_share:8"), dpp.replace("row_shr:8", "row_xmask:8"), + dpp.replace("row_shr:8", "row_mirror"), dpp.replace("row_shr:8", "row_half_mirror"), + dpp.replace("row_shr:8", "row_bcast:15"), dpp.replace("row_shr:8", "wave_shr:1"), + dpp + " fi:1", dpp.replace("row_mask:0xf", "row_mask:0x7"), + dpp.replace("bank_mask:0xf", "bank_mask:0xe"), dpp.replace("v1, v0 row_shr", "s1, v0 row_shr"), + dpp.replace("v_or_b32_dpp", "v_xor_b32_dpp"), dpp.replace("v_or_b32_dpp", "v_add_f32_dpp"), + dpp.replace("v_or_b32_dpp", "v_sub_nc_u32_dpp"), dpp.replace("v_or_b32_dpp", "v_mov_b32_dpp")): + rejects(unsupported, translate, variant(program(8), dpp, form)) + shift = "Unsupported or masked DPP16 row shift" + for bad in ("row_shr:0", "row_shr:16"): + rejects(shift, translate, variant(program(8), dpp, dpp.replace("row_shr:8", bad))) + rejects(shift, translate, variant(program(8), dpp, dpp.replace("v5, v1", "v256, v1"))) + rejects(shift, translate, program(8), cpu="gfx1030") + # Groups of 8 (part of a row) and two-dimensional groups are refused. + rejects(shift, translate, variant(program(8), "s2, 6, v0", "s2, 3, v0"), 8) + rejects(shift, translate, variant(program(8), "s2, 6, v0", "s2, 5, v0"), (32, 2, 1)) + # A lane guard before the DPP is refused (READ_COMPUTE's guard with the DPP after it). + guarded = [ + "s_mov_b32 s2, s1", "s_mov_b32 s1, 0", "v_lshl_add_u32 v0, s2, 6, v0", + "s_load_dwordx4 s[4:7], s[0:1], 0x20", "s_waitcnt lgkmcnt(0)", "s_buffer_load_dword s3, s[4:7], 0x0", + "s_waitcnt lgkmcnt(0)", "v_cmp_gt_u32_e32 vcc_lo, s3, v0", "s_and_saveexec_b32 s2, vcc_lo", + "s_cbranch_execz .LBB0_2", "s_load_dwordx8 s[8:15], s[0:1], 0x0", "v_lshlrev_b32_e32 v3, 2, v0", + "s_waitcnt lgkmcnt(0)", "buffer_load_dword v1, v3, s[12:15], 0 offen", "s_waitcnt vmcnt(0)", dpp, + "buffer_store_dword v5, v0, s[8:11], 0 idxen", ".LBB0_2:", "s_endpgm"] + rejects(shift, translate, guarded, stride=4) + print("controls: row_shl, row_ror, row_share, row_xmask, other DPP16 controls, fi:1, partial masks,") + print(" other opcodes, an SGPR source, shifts 0 and 16, gfx1030, groups of 8, 2D groups, a lane guard") + print(" and a missing old destination without BOUND_CTRL are refused") + + # The reference and its mutants differ at the predicted first word, for each shift. + for shift in SHIFTS: + assert first_difference(expected(shift), expected(shift, "cross_row")) == 64, shift + assert first_difference(expected(shift), expected(shift, "zero")) == 1, shift + source = translate(program(shift)) + for mutant in ("cross_row", "zero"): + assert mutate(source, mutant) != source + print("mutants: cross_row first differs at word 64 (thread 16), zero at word 1 (thread 0)") + + +def check_binary(llvm_mc, objcopy, library, directory): + """Assemble with LLVM 15, decode, and require the same translation as the source text.""" + for shift in SHIFTS: + encoded = {} + for spelling in ("bound_ctrl:0", "bound_ctrl:1"): + src, obj, raw = (directory / f"row_shr_{shift}.{ext}" for ext in ("s", "o", "bin")) + src.write_text("\n".join(program(shift, spelling)) + "\n", encoding="ascii") + subprocess.run([llvm_mc, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-filetype=obj", str(src), + "-o", str(obj)], check=True) + subprocess.run([objcopy, "-O", "binary", "--only-section=.text", str(obj), str(raw)], check=True) + encoded[spelling] = raw.read_bytes() + assert encoded["bound_ctrl:0"] == encoded["bound_ctrl:1"], shift + code = encoded["bound_ctrl:1"] + decoded = aot.labelled(disassemble(code, library, offsets=True)) + dpp = [(offset, line) for offset, line in disassemble(code, library, offsets=True) if "_dpp " in line] + assert [line for _, line in dpp] == [line for line in program(shift) if "_dpp " in line], dpp + for (offset, line), bound, src0 in zip(dpp, (True, False, True, False), (1, 1, 7, 7)): + # The DPP16 dword: src0 [7:0], DPP_CTRL [16:8], FI [18], BOUND_CTRL [19], masks [31:24]. + word = struct.unpack_from("> 8) & 0x1ff == 0x110 + shift, (line, hex(word)) + assert (word >> 18) & 1 == 0 and (word >> 19) & 1 == bound and word >> 24 == 0xff, (line, hex(word)) + assert translate(decoded) == translate(program(shift)), shift + print("binary: LLVM 15 encodes bound_ctrl:0 and bound_ctrl:1 alike (bit 19 set) and decodes them as") + print(" bound_ctrl:1; DPP_CTRL 0x111, 0x118 and 0x11f; the decoded programs translate as the source") + + +def dispatch(directory, dxc, renderer, backend, label, source, words): + src, cso, case = (directory / f"{label}.{ext}" for ext in ("hlsl", "cso", "case")) + src.write_text(source, encoding="ascii") + subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(src)], check=True) + case.write_bytes(struct.pack(f"<{1 + WORDS}I", 1, *words)) + return subprocess.run([renderer, backend, "--compute-store-case", str(cso), str(case)], + capture_output=True, text=True) + + +def check_draw(directory, dxc, renderer, backend): + controls() + for shift in SHIFTS: + source, words = translate(program(shift)), expected(shift) + run = dispatch(directory, dxc, renderer, backend, f"row_shr_{shift}", source, words) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + if run.returncode: + raise AssertionError(f"row_shr:{shift}\n{run.stdout}\n{run.stderr}") + output = (run.stdout + run.stderr).splitlines() + if shift == SHIFTS[0]: + print(" ".join(line.strip() for line in output if line.startswith(("adapter=", "driver=")))) + debug = next((line for line in output if "debug_errors=" in line), "") + result = next((line for line in run.stdout.splitlines() if "compared_words=" in line), "") + print(f"row_shr:{shift}: {result.strip()} {debug.strip()}") + for mutant in ("cross_row", "zero"): + bad_words = expected(shift, mutant) + first = first_difference(words, bad_words) + run = dispatch(directory, dxc, renderer, backend, f"row_shr_{shift}_{mutant}", mutate(source, mutant), + words) + line = f"word={first} expected={words[first]:08x} actual={bad_words[first]:08x}" + if run.returncode != 1 or line not in run.stderr: + raise AssertionError(f"row_shr:{shift} {mutant}: expected first mismatch {line}\n" + f"{run.stdout}\n{run.stderr}") + print(f"row_shr:{shift} {mutant}: first mismatch {line}, as predicted") + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + opcodes = sorted({line.split()[0] for shift in SHIFTS for line in program(shift)}) + path.write_text("".join(f"{op}\n" for op in opcodes), encoding="utf-8") + return 0 + + +def main(): + if len(sys.argv) == 1: + controls() + return 0 + mode, *args = sys.argv[1:] + with tempfile.TemporaryDirectory() as tmp: + if mode == "binary": + controls() + check_binary(*args, Path(tmp)) + return 0 + if mode == "draw": + return check_draw(Path(tmp), *args) + raise SystemExit(__doc__) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index 1046987c9..d58135549 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -2142,6 +2142,36 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N " GroupMemoryBarrierWithGroupSync();\n" f" uint {value} = {source} | {hlsl_word(values[1])};")) vector[dst] = ("alu", value) + elif m := re.fullmatch(r"v_(or_b32|add_nc_u32)_dpp v(\d+), v(\d+), v(\d+) row_shr:(\d+) " + r"row_mask:0xf bank_mask:0xf( bound_ctrl:[01])?", line): + op, dst, src0, src1, shift = m[1], *map(int, m.groups()[1:5]) + # LLVM 15 assembles bound_ctrl:0 and bound_ctrl:1 to the same set BOUND_CTRL bit and prints :1. + bound = m[6] is not None + # Rows are 16 of the guest's logical 1D lanes, indexed through group-shared memory. + if (cpu != "gfx1013" or max(dst, src0, src1) > 255 or not 1 <= shift <= 15 + or guard_span is not None or dims[1] != 1 or dims[2] != 1 or dims[0] % 16): + raise ValueError("Unsupported or masked DPP16 row shift") + # Without BOUND_CTRL a lane whose source is before its row start keeps its old destination. + values = [vector.get(reg) for reg in (src0, src1) + (() if bound else (dst,))] + if not all(is_word(value) for value in values): + raise ValueError("Unverified DPP16 operand") + step = dpp_step_count + dpp_step_count += 1 + row_lane, inside = f"dpp{step}_row_lane", f"dpp{step}_inside" + source_thread = f"dpp{step}_source_thread" + source, value = f"dpp{step}_source", f"dpp{step}_value" + result = f"({source} {'|' if op == 'or_b32' else '+'} ({hlsl_word(values[1])}))" + slot = "dpp_stage" + staged_steps.append((slot, f" uint {row_lane} = local.x & 15u;\n" + f" bool {inside} = {row_lane} >= {shift}u;\n" + f" {slot}[local.x] = {hlsl_word(values[0])};\n" + " GroupMemoryBarrierWithGroupSync();\n" + f" uint {source_thread} = {inside} ? local.x - {shift}u : local.x;\n" + f" uint {source} = {inside} ? {slot}[{source_thread}] : 0u;\n" + " GroupMemoryBarrierWithGroupSync();\n" + f" uint {value} = " + + (f"{result};" if bound else f"{inside} ? {result} : ({hlsl_word(values[2])});"))) + vector[dst] = ("alu", value) elif ((m := re.fullmatch(rf"(v_(?:and_b32|lshrrev_b32|min_u32|max_u32|add_nc_u32|or_b32|xor_b32|lshlrev_b32|ashrrev_i32|sub_nc_u32|subrev_nc_u32)_e32) v(\d+), {ALU_SOURCE}, (v\d+)", line)) or (m := re.fullmatch(rf"(v_mul_lo_u32|v_add_nc_i32|v_sub_nc_i32|v_bcnt_u32_b32) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}", line)) or (m := re.fullmatch(rf"(v_mad_u32_u24|v_xor3_b32|v_max3_u32|v_min3_u32|v_med3_u32|v_med3_i32|v_mad_i32_i24) v(\d+), {ALU_SOURCE}, {ALU_SOURCE}, {ALU_SOURCE}", line)) From 396e7e2e002ba45dc784a1ddbe5210140599f7a6 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Wed, 25 Nov 2026 21:41:25 +0200 Subject: [PATCH 118/232] tooling: summarize startup GPU memory budget pressure (#2518) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> --- docs/startup-runtime.md | 8 ++++ tests/startup_triage_run_check.py | 45 +++++++++++++++++++ tools/startup/triage_run.py | 75 +++++++++++++++++++++++++++++++ 3 files changed, 128 insertions(+) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d45f7816d..6c559e17b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1020,6 +1020,14 @@ when scanning multiple runs. The section appears only after a complete census li forwarded `dispatchmesh` calls alongside a graphics-pipeline refusal count. Forwarded counts describe the runtime's forwarding path. GPU completion and image readback require separate evidence. +The GPU Memory Budget section uses complete `x2w-budget` heartbeat lines from +`X2W_D3D12_BUDGET=1`. It counts samples above the local DXGI budget and prints +the sample with the highest usage-to-budget ratio, plus the sample with the most +retained texture bytes. Each row keeps the usage, budget and texture counters +from that same heartbeat. Samples with an unavailable or zero local budget +still contribute texture counts. The over-budget count describes observations +in the supplied logs. + The `Run End-Point` section says how far a run got and how it ended, so that reports of runs with different memory caps can be told apart. It gives the largest `commit peak=` value of the `x2w-dstorage heartbeat` lines (not the last one), the highest heartbeat second, the counts of the last `failed requests by cause` heartbeat line (the diff --git a/tests/startup_triage_run_check.py b/tests/startup_triage_run_check.py index 4f63a8c40..c2fcba5db 100644 --- a/tests/startup_triage_run_check.py +++ b/tests/startup_triage_run_check.py @@ -561,6 +561,50 @@ def check_indirect_outcomes(failures: list[str]) -> None: failures.append("a malformed snapshot produced an indirect summary") +def check_gpu_memory_budget(failures: list[str]) -> None: + def sample(local, texture): + return ( + f'x2w-budget local={local} nonlocal=2/8 placed=10000/2+20000/3 texture={texture} ' + 'buffer=1/1+0/0 upload=0/0+0/0 readback=0/0+0/0 heap=0/0+0/0 unmeasured=0' + ) + + high_usage = sample("2500/3000", "100/5+40/2") + high_ratio = sample("1800/1000", "150/7+50/3") + high_retained = sample("n/a", "250/8+900/40").replace("nonlocal=2/8", "nonlocal=n/a") + malformed = ( + sample("4000/1", "500/7+950/4").replace(" unmeasured=0", ""), + sample("9000/1", "900/1+999/1").replace(" buffer=1/1+0/0", r" buffer=C:\Users\alice"), + sample("9000/1", "900/1+999/1") + " path=secret.exe", + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + log = root / "stderr.txt" + samples = (high_usage, high_ratio, sample("2100/1800", "170/8+80/4"), high_retained, + sample("5000/0", "300/9+10/3"), sample("1000/1000", "90/6+20/1"), *malformed) + log.write_text("\n".join(samples), encoding="utf-8") + (root / "trap.log").write_text(high_ratio + "\n", encoding="utf-8") + report = triage_run.triage_run(root) + for snippet in ( + "### GPU Memory Budget", + "Complete samples: `6`", + "Samples above local budget: `2` of `4`", + "| Highest local usage-to-budget ratio | 1800 | 1000 | 150 | 50 | 3 |", + "| Most retained texture bytes | n/a | n/a | 250 | 900 | 40 |", + ): + if snippet not in report: + failures.append(f"missing memory budget line: {snippet!r}") + for private in ("alice", "secret.exe"): + if private in report: + failures.append(f"memory budget copied private text: {private!r}") + log.write_text("\n".join(malformed), encoding="utf-8") + if "### GPU Memory Budget" in triage_run.triage_run(log): + failures.append("incomplete or malformed budget rows produced a section") + log.write_text(high_retained, encoding="utf-8") + report = triage_run.triage_run(log) + if "Highest local usage-to-budget ratio" in report or "Most retained texture bytes" not in report: + failures.append("an unavailable DXGI budget hid the retained-texture sample or produced a ratio") + + def main() -> int: failures: list[str] = [] check_aggregation_and_redaction(failures) @@ -571,6 +615,7 @@ def main() -> int: check_cli_invocation(failures) check_slot133_outcomes(failures) check_indirect_outcomes(failures) + check_gpu_memory_budget(failures) check_run_endpoint(failures) check_every_shader_reason_entry_is_reachable(failures) for item in failures: diff --git a/tools/startup/triage_run.py b/tools/startup/triage_run.py index 9235f9ee1..fee383915 100644 --- a/tools/startup/triage_run.py +++ b/tools/startup/triage_run.py @@ -74,6 +74,18 @@ ) INDIRECT_KINDS = ("other", "dispatch", "draw", "drawindexed", "dispatchmesh") RE_INDIRECT_COUNT = re.compile(r"[0-9]{1,19}\Z") +# The budget heartbeat is produced by report_budget() in d3d12_xs_device.cpp. +BUDGET_DECIMAL = r"[0-9]{1,20}" +BUDGET_SEGMENT = rf"(?:{BUDGET_DECIMAL}/{BUDGET_DECIMAL}|n/a)" +BUDGET_CATEGORY = rf"{BUDGET_DECIMAL}/{BUDGET_DECIMAL}\+{BUDGET_DECIMAL}/{BUDGET_DECIMAL}" +RE_GPU_BUDGET = re.compile( + rf"x2w-budget local=(?:(?P{BUDGET_DECIMAL})/(?P{BUDGET_DECIMAL})|n/a)" + rf" nonlocal={BUDGET_SEGMENT} placed={BUDGET_CATEGORY}" + rf" texture=(?P{BUDGET_DECIMAL})/{BUDGET_DECIMAL}" + rf"\+(?P{BUDGET_DECIMAL})/(?P{BUDGET_DECIMAL})" + + "".join(rf" {name}={BUDGET_CATEGORY}" for name in ("buffer", "upload", "readback", "heap")) + + rf" unmeasured={BUDGET_DECIMAL}" +) OTHER = "other (text omitted)" RE_DEC = re.compile(r"[0-9]{1,10}\Z") RE_HEX = re.compile(r"0x[0-9a-fA-F]{1,8}\Z") @@ -312,12 +324,45 @@ def parse_indirect_snapshot(payload: str) -> dict[tuple[str, str], int] | None: return snapshot +@dataclass(frozen=True) +class GpuBudgetSample: + local: tuple[int, int] | None + live_texture_bytes: int + retained_texture_bytes: int + retained_textures: int + + +@dataclass +class GpuBudgetSummary: + samples: int = 0 + known_local_budget: int = 0 + above_local_budget: int = 0 + local_peak: GpuBudgetSample | None = None + texture_peak: GpuBudgetSample | None = None + + def observe(self, match: re.Match[str]) -> None: + local = (int(match["usage"]), int(match["budget"])) if match["usage"] is not None else None + sample = GpuBudgetSample(local, int(match["live"]), int(match["retained"]), int(match["objects"])) + self.samples += 1 + if self.texture_peak is None or sample.retained_texture_bytes > self.texture_peak.retained_texture_bytes: + self.texture_peak = sample + if local is None or local[1] == 0: + return + usage, budget = local + self.known_local_budget += 1 + self.above_local_budget += usage > budget + peak = self.local_peak.local if self.local_peak else None + if peak is None or usage * peak[1] > peak[0] * budget: + self.local_peak = sample + + def summarize_lines(lines: Iterable[str]) -> dict[str, Any]: """Aggregate startup telemetry counters from an iterable of log lines.""" slot70_refusals: Counter[tuple[str, str, str, str, str, str, str]] = Counter() d3d12_unhandled: Counter[str] = Counter() slot133_outcomes: Counter[str] = Counter() indirect_peaks: Counter[tuple[str, str]] | None = None + gpu_budget = GpuBudgetSummary() d3d12_debug: Counter[tuple[str, str]] = Counter() dstorage_failures: Counter[str] = Counter() dstorage_hresults: Counter[str] = Counter() @@ -330,6 +375,11 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Any]: continue endpoint.observe(line) # reads only; the line is still classified below + budget_match = RE_GPU_BUDGET.fullmatch(line) + if budget_match: + gpu_budget.observe(budget_match) + continue + if line.startswith(INDIRECT_PREFIX): snapshot = parse_indirect_snapshot(line.removeprefix(INDIRECT_PREFIX)) if snapshot is not None: @@ -469,6 +519,7 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Any]: "d3d12_unhandled": d3d12_unhandled, "slot133_outcomes": slot133_outcomes, "indirect_peaks": indirect_peaks, + "gpu_budget": gpu_budget, "d3d12_debug": d3d12_debug, "dstorage_failures": dstorage_failures, "dstorage_hresults": dstorage_hresults, @@ -638,6 +689,30 @@ def format_markdown( rows = [[outcome, *(indirect[outcome, kind] for kind in INDIRECT_KINDS)] for outcome in INDIRECT_OUTCOMES] out.extend(_format_table(["Outcome", *INDIRECT_KINDS], rows, len(rows), 0, len(rows))) + gpu_budget = summary["gpu_budget"] + if gpu_budget.samples: + out.extend([ + "### GPU Memory Budget", + "", + f"- Complete samples: `{gpu_budget.samples}`", + f"- Samples above local budget: `{gpu_budget.above_local_budget}` of `{gpu_budget.known_local_budget}` " + "with a positive reported local budget", + "", + ]) + rows = [] + for label, sample in ( + ("Highest local usage-to-budget ratio", gpu_budget.local_peak), + ("Most retained texture bytes", gpu_budget.texture_peak), + ): + if sample is not None: + rows.append([ + label, *(sample.local if sample.local is not None else ("n/a", "n/a")), + sample.live_texture_bytes, sample.retained_texture_bytes, sample.retained_textures, + ]) + headers = ["Sample", "Local usage bytes", "Local budget bytes", "Live texture bytes", + "Retained texture bytes", "Retained textures"] + out.extend(_format_table(headers, rows, len(rows), 0, len(rows))) + # 3. x2w-d3d12-debug dbg = summary["d3d12_debug"] if dbg: From 15ff2cf67ab3d576cba3280cfb7ed8f2d6f92bc4 Mon Sep 17 00:00:00 2001 From: RenzoWit35 <168984533+RenzoWit35@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:45:03 +0100 Subject: [PATCH 119/232] shader: scan pipelines for the pixel input mask location (#1669) Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 3 + docs/experiments.md | 61 ++ tests/startup_ps_input_scan_check.py | 696 +++++++++++++++++ tools/startup/ps_input_scan.py | 1033 ++++++++++++++++++++++++++ 5 files changed, 1794 insertions(+) create mode 100644 tests/startup_ps_input_scan_check.py create mode 100644 tools/startup/ps_input_scan.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index e2c37d2a4..8f0e90964 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -256,6 +256,7 @@ jobs: tests/startup_run_ps1_check.py \ tests/startup_run_sh_check.py \ tests/startup_flat_param_check.py \ + tests/startup_ps_input_scan_check.py \ tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_gfx2hlsl_interp_f16_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 2cf03b092..50df6b9ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3289,6 +3289,9 @@ if(EXISTS "${INTAKE_PYTHON}") # draw of the translated pair with FXC 5_1 (the --pending path) and DXC 6_0. add_test(NAME startup_flat_param_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_flat_param_check.py") + # The pixel input mask scan finds where a pipeline stores the two masks, from shader register use (#1629). + add_test(NAME startup_ps_input_scan COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_packed_screen_position_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_check.py" "${DXC_EXECUTABLE}" diff --git a/docs/experiments.md b/docs/experiments.md index 56530e069..3adb253f1 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -177,6 +177,67 @@ a different input register, and a disabled position input each produce a detecta The fixture rejects differing enable/address masks. Production startup requests still omit these arguments. Identifying both masks for the affected pipeline remains open. [Refs #1629](https://github.com/R0Y00/Xbox2Windows/issues/1629) +### Locating the pixel input masks from shader register use + +Run `python -B tools/startup/ps_input_scan.py [] [--capture ] [--pixel-dir ] [--json ] [--list] [--top N]`. +At least one input is required and they can be combined. A request directory holds +`req_.a/.b/.root` files. In a `--pixel-dir` every regular file is one pixel shader, either a +DXBC container or a raw blob; pipelines are numbered `p000001` upward in sorted file-name order and +file names are never printed. The check is +`ctest --preset dev --no-tests=error -R '^startup_ps_input_scan$' -V`. + +For each pixel shader the tool reads only the disassembly and records a contract: the vector +registers read before any write (live-in), the I/J register pairs that feed attribute +interpolation, and the live-in registers split into low and high 16-bit halves. Compare forms give +no half evidence. A first read is a live-in register unless a backward branch spans it and the +register is written later in program order: that value can be loop-carried, so the register is +reported as ambiguous and takes no part in any rule, and evidence taken from such a read is +dropped. Aliases made by `v_mov_b32` do not cross a branch or a branch target. A branch whose +target the text does not give, and an indirect branch, make every first read of a register that is +written somewhere ambiguous. A contract that no address mask satisfies at all (for example a +definite live-in register above v23) is excluded from every tally and reported on its own line. A +candidate address mask is consistent when every live-in register is covered by +its register layout (C1) and every pair starts at a two-register input (C2); a value above 0xffff +fails C0. Inputs that are enabled but never read are expected, so a layout may be larger than +the highest live-in register needs. A consistent pipeline is tight when the layout has exactly as many registers as the +highest live-in register needs. A mask with every bit set is consistent with every shader but never +tight, so tight separates it from a real mask. + +The candidate locations are the byte regions of each pipeline: the bytes before the prefetch marker +of a raw pixel blob; for a container the FSSM image head and tail, the other XDAT entries and every +part other than the DXIL part (`ps.part.`, for example `ps.part.PSV0`); with `--capture` the +pipeline description and its two state blocks. The capture stores only the 96-byte description in +its PSO record, so the state blocks are scanned only when the capture also holds that memory. In a +request directory every other regular file `req_.` (not `a`, `b`, `root` or `rtv`, at +most 1 MiB) is a region `req.`; this is the way to scan a recorded description or state block +without changing the tool. In each region the tool tries every aligned pair or +single value, plus words that follow the register byte addresses 0x286CC/0x286D0 or the context +indices 0x1B3/0x1B4 (0xA1B3/0xA1B4 as "mm" indices). Candidates that read the same address +everywhere are listed once with a count of equivalents. Only the first `--region-limit` bytes +(0x1000) of each region are searched. + +Read the verdict line. `unique full match` means one location is consistent in every pipeline with +a live-in register and has more tight pipelines than any other full match. `N full matches +(ambiguous)` means several distinct locations fit equally and tie on the number of tight pipelines. `no location is consistent with all +pipelines` means none fits. `uninformative corpus` means no shader reads a live-in register, so +nothing can be told apart. Two separate lines follow for the top candidate. `mask agreement` counts +pipelines that satisfy the coverage and pair rules, those that are tight and the failures per rule. +`packed-position agreement` counts the pipelines that split a live-in register into 16-bit halves +and have it at the register the address mask predicts for bit 15. The second line never votes: it +tests the assumed register widths, not a location, and does not prove the hardware register order. +When any shader splits a register, `full matches that also agree on every packed split` names the +full matches whose predicted bit-15 register matches every such split, or `none`; it does not +change the ranking or the verdict. +The scan takes the layout from the address mask and reports, in the relation counts, where the +enable value differs from it. + +The header counts the pipelines with ambiguous live-in reads and the excluded unsatisfiable contracts. +By default stdout holds aggregates only: counts, reasons and ranked candidates, no pipeline ids. +`--list` adds the per-pipeline table (id, enable, address, predicted packed register, live-in, split and +ambiguous registers); `--json` always keeps the ids. The tool and its check have run on synthetic blobs +only; no result for real pipelines is claimed. +[Refs #1629](https://github.com/R0Y00/Xbox2Windows/issues/1629) + Run commands from the repository root. Start with the [project overview](../README.md) and [contribution guide](../CONTRIBUTING.md). Package-specific observations below used local inputs. Community regression tests use fixtures built from this repository. ## Resuming startup shader compilation diff --git a/tests/startup_ps_input_scan_check.py b/tests/startup_ps_input_scan_check.py new file mode 100644 index 000000000..52771d87a --- /dev/null +++ b/tests/startup_ps_input_scan_check.py @@ -0,0 +1,696 @@ +"""Check tools/startup/ps_input_scan.py on synthetic pixel shaders and synthetic request directories. + +Every hand-encoded word sequence is disassembled and compared with the text it is meant to be, so a +wrong encoding cannot pass silently. The corpora are built here; no capture or title data is used. +""" +import json +import os +import struct +import subprocess +import sys +import tempfile +import zlib +from pathlib import Path +from unittest import mock + +from startup_capture_check import chunk, mem +from startup_image_3d_check import VS_WORDS, G, root_blob + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import ps_input_scan as S # noqa: E402 + +TOOL = HERE.parent / 'tools' / 'startup' / 'ps_input_scan.py' +END = 0xbf810000 + + +def w(*words): + return struct.pack('<%dI' % len(words), *words) + + +# gfx1013 encodings (VOP1, VOP2, VOPC, VINTRP, SDWA, VOP3 and exp). +def vop2(op, vdst, vsrc1, src0): + return (op << 25) | (vdst << 17) | (vsrc1 << 9) | src0 + + +def vop1(op, vdst, src0): + return 0x7e000000 | (vdst << 17) | (op << 9) | src0 + + +def vintrp(op, vdst, vsrc, attr): + return 0xc8000000 | (vdst << 18) | (op << 16) | (attr << 10) | vsrc + + +def v(n): + return 256 + n + + +def and_low(vdst, src): # v_and_b32 vdst, 0xffff, src + return w(vop2(0x1b, vdst, src, 255), 0xffff), 'v_and_b32_e32 v%d, 0xffff, v%d' % (vdst, src) + + +def shr_high(vdst, src): # v_lshrrev_b32 vdst, 16, src + return w(vop2(0x16, vdst, src, 144)), 'v_lshrrev_b32_e32 v%d, 16, v%d' % (vdst, src) + + +def sdwa_low(vdst, src): # v_and_b32_sdwa, WORD_0 of src0 + return (w(vop2(0x1b, vdst, src, 249), src | (6 << 8) | (4 << 16) | (6 << 24)), + 'v_and_b32_sdwa v%d, v%d, v%d dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 ' + 'src1_sel:DWORD' % (vdst, src, src)) + + +def sdwa_high(vdst, src): # v_mov_b32_sdwa, WORD_1 of src0 + return (w(vop1(1, vdst, 249), src | (6 << 8) | (5 << 16)), + 'v_mov_b32_sdwa v%d, v%d dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1' % (vdst, src)) + + +def bfe(vdst, src, offset, width): + return (w(0xd4000000 | (0x148 << 16) | vdst, v(src) | ((128 + offset) << 9) | ((128 + width) << 18)), + 'v_bfe_u32 v%d, v%d, %d, %d' % (vdst, src, offset, width)) + + +def mov(vdst, src): + return w(vop1(1, vdst, v(src))), 'v_mov_b32_e32 v%d, v%d' % (vdst, src) + + +def mov_zero(vdst): + return w(vop1(1, vdst, 128)), 'v_mov_b32_e32 v%d, 0' % vdst + + +def add(vdst, a, b): + return w(vop2(0x03, vdst, b, v(a))), 'v_add_f32_e32 v%d, v%d, v%d' % (vdst, a, b) + + +def cmp_lt(a, b): + return w(0x7c000000 | (1 << 17) | (b << 9) | v(a)), 'v_cmp_lt_f32_e32 vcc_lo, v%d, v%d' % (a, b) + + +def interp(vdst, src, attr, second): + return (w(vintrp(1 if second else 0, vdst, src, attr)), + 'v_interp_p%d_f32_e32 v%d, v%d, attr%d.x' % (2 if second else 1, vdst, src, attr)) + + +def exp(*regs): + return (w(0xf800180f, *[sum(r << (8 * i) for i, r in enumerate(regs))]), + 'exp mrt0 v%d, v%d, v%d, v%d done vm' % regs) + + +def br(name, here, target): + """s_branch or s_cbranch_scc1 at byte offset `here` to byte offset `target`.""" + opcode = {'s_branch': 0xbf820000, 's_cbranch_scc1': 0xbf850000}[name] + return w(opcode | (((target - (here + 4)) // 4) & 0xffff)), '%s label_0x%x' % (name, target) + + +def shader(*items): + """Assemble (words, expected disassembly) items, then an end; assert the text.""" + code = b''.join(item[0] for item in items) + w(END) + decoded = [x[3] for x in G.decode(code)] + expected = [item[1] for item in items] + ['s_endpgm'] + assert decoded == expected, (decoded, expected) + return code + + +def contract_of(code): + return S.contract(code) + + +def sets(contract): + return sorted(contract.live_in), sorted(contract.ij_pairs), sorted(contract.split16) + + +SHADERS = { + 'packed_only@v1': shader(and_low(4, 1), shr_high(5, 1), exp(4, 5, 4, 5)), + 'packed_sdwa@v1': shader(sdwa_low(4, 1), sdwa_high(5, 1), exp(4, 5, 4, 5)), + 'packed_bfe@v1': shader(bfe(4, 1, 0, 16), bfe(5, 1, 16, 16), exp(4, 5, 4, 5)), + 'packed_alias@v1': shader(mov(6, 1), and_low(4, 6), shr_high(5, 6), exp(4, 5, 4, 5)), + 'pair_then_packed@v2': shader(interp(4, 0, 0, False), interp(4, 1, 0, True), + and_low(5, 2), shr_high(6, 2), exp(4, 5, 6, 4)), + 'two_pairs': shader(interp(4, 0, 0, False), interp(4, 1, 0, True), + interp(5, 2, 1, False), interp(5, 3, 1, True), exp(4, 5, 4, 5)), + 'no_inputs': shader(mov_zero(0), exp(0, 0, 0, 0)), + 'write_first': shader(mov_zero(1), add(2, 1, 1), exp(2, 2, 2, 2)), + 'cmp_and_exp': shader(cmp_lt(1, 2), exp(3, 4, 3, 4)), + 'packed_misfire': shader(and_low(4, 0), shr_high(5, 0), add(6, 1, 1), exp(4, 5, 6, 6)), + 'overwritten': shader(and_low(4, 1), mov_zero(1), shr_high(5, 1), exp(4, 5, 4, 5)), + # Control flow; branch targets are byte offsets inside the shader. + # entry -> B (writes v5, branches back) -> A (reads v5): v5 is loop-carried, not live-in. + 'loop_ambiguous': shader(br('s_branch', 0, 20), add(6, 5, 5), exp(6, 6, 6, 6), br('s_branch', 16, 28), + mov_zero(5), br('s_branch', 24, 4)), + 'loop_definite': shader(add(6, 1, 1), br('s_cbranch_scc1', 4, 0), exp(6, 6, 6, 6)), + 'loop_rmw': shader(add(5, 5, 1), br('s_cbranch_scc1', 4, 0), exp(5, 5, 5, 5)), + # A move inside a skipped block, an interpolation after the join: the alias must not survive. + 'alias_block': shader(br('s_cbranch_scc1', 0, 8), mov(4, 0), interp(7, 4, 0, False), + interp(7, 1, 0, True), exp(7, 7, 7, 7)), + 'alias_straight': shader(mov(4, 0), interp(7, 4, 0, False), interp(7, 1, 0, True), exp(7, 7, 7, 7)), + 'unsat_v40': shader(add(6, 40, 40), exp(6, 6, 6, 6)), +} + +# The address mask each informative shader needs, and one that satisfies it. +MASKS = {'packed_only@v1': 0x8100, 'packed_sdwa@v1': 0x8080, 'packed_bfe@v1': 0x8200, + 'packed_alias@v1': 0x8100, 'pair_then_packed@v2': 0x8002, 'two_pairs': 0x0012, + 'no_inputs': 0x0004, 'write_first': 0x0001, 'packed_misfire': 0x8100, + 'loop_ambiguous': 0x0001, 'unsat_v40': 0x0001} + + +def empty_contract(): + return S.Contract(frozenset(), frozenset(), frozenset()) + + +def unit_checks(): + expected = { + 'packed_only@v1': ([1], [], [1]), 'packed_sdwa@v1': ([1], [], [1]), + 'packed_bfe@v1': ([1], [], [1]), 'packed_alias@v1': ([1], [], [1]), + 'pair_then_packed@v2': ([0, 1, 2], [0], [2]), 'two_pairs': ([0, 1, 2, 3], [0, 2], []), + 'no_inputs': ([], [], []), 'write_first': ([], [], []), + 'cmp_and_exp': ([1, 2, 3, 4], [], []), 'packed_misfire': ([0, 1], [], [0]), 'overwritten': ([1], [], []), + 'loop_ambiguous': ([], [], []), 'loop_definite': ([1], [], []), 'loop_rmw': ([1, 5], [], []), + 'alias_block': ([0, 1], [], []), 'alias_straight': ([0, 1], [0], []), 'unsat_v40': ([40], [], []), + } + for name, code in SHADERS.items(): + assert sets(contract_of(code)) == expected[name], (name, sets(contract_of(code))) + assert sorted(contract_of(SHADERS['loop_ambiguous']).ambiguous) == [5] + assert all(not contract_of(code).ambiguous for name, code in SHADERS.items() if name != 'loop_ambiguous') + print('loop rule: loop-carried v5 is ambiguous, not live-in; unwritten and read-modify-write ' + 'loop registers stay live-in; no alias across a block boundary') + with mock.patch.object(G, 'decode', side_effect=G.Unsupported('undecodable word at +0x4: fixture')): + try: + S.make_record('0', b'', {}) + except S.Skip as skip: + assert str(skip).startswith('undecodable: undecodable word at +0x4'), skip + else: + raise AssertionError('an undecodable shader was not skipped') + print('contract: %d shapes (and/shift, SDWA, bfe, alias, interp pairs, no inputs, write-first, ' + 'cmp/exp sources, overwrite)' % len(SHADERS)) + + # Destination rule on decoded text: all-source forms and the read-before-write order. + def lines(*asm): + return [(4 * i, 4, a.split()[0], a) for i, a in enumerate(asm)] + cases = ( + (['v_cmpx_lt_f32_e64 v1, v2, v3'], [1, 2, 3]), + (['global_store_dword v[1:2], v3, off'], [1, 2, 3]), + (['buffer_store_dword v4, v5, s[0:3], 0 offen'], [4, 5]), + (['ds_write_b32 v4, v5'], [4, 5]), + (['v_swap_b32 v7, v8', 'v_add_f32_e32 v9, v7, v8'], [7, 8]), + (['v_add_f32_e32 v9, v10, v9'], [9, 10]), + (['v_mad_f32 v1, |v2|, -v3, 0', 'v_add_f32_e32 v4, v1, v1'], [2, 3]), + (['v_mov_b32_e32 v1, 0', 'image_sample v[4:7], v[1:2], s[8:15], s[16:19] dmask:0xf'], [2]), + (['image_sample v[4:7], v[0:1], s[8:15], s[16:19] dmask:0xf'], [0, 1]), + (['v_and_b32_e32 v2, 0xffff, sext(v1)'], [1]), + (['exp mrt0 off, off, v6, v7 done vm'], [6, 7]), + (['exp mrt0 v5, v6, v7, v8 done vm'], [5, 6, 7, 8]), + (['v_cmpx_lt_f32_sdwa v1, v2 src0_sel:WORD_0 src1_sel:WORD_1'], [1, 2]), + ) + for asm, live in cases: + got = sorted(S.contract_of_decoded(lines(*asm)).live_in) + assert got == live, (asm, got, live) + print('destination rule: %d decoded-text cases' % len(cases)) + + # A flow the text cannot resolve makes every written-later first read ambiguous. + for flow in ('s_setpc_b64 s[2:3]', 's_branch 0x4', 's_cbranch_join s2'): + got = S.contract_of_decoded(lines('v_add_f32_e32 v6, v5, v5', flow, 'v_mov_b32_e32 v5, 0')) + assert 5 in got.ambiguous and 5 not in got.live_in, (flow, got) + got = S.contract_of_decoded(lines('v_add_f32_e32 v6, v5, v5', 's_branch label_0x8', 'v_mov_b32_e32 v5, 0')) + assert 5 in got.live_in and not got.ambiguous, got # forward flow only: the linear rule holds + print('control flow: unresolved or indirect branches fall back to ambiguous') + + # Compare forms give no SDWA half evidence: with the second half taken from a shift, the + # register must not count as split. + for compare in ('v_cmp_lt_f32_sdwa vcc_lo, v1, v2 src0_sel:WORD_0 src1_sel:WORD_1', + 'v_cmpx_lt_f32_sdwa v1, v2 src0_sel:WORD_0 src1_sel:WORD_1'): + got = S.contract_of_decoded(lines(compare, 'v_lshrrev_b32_e32 v3, 16, v1')) + assert sorted(got.live_in) == [1, 2] and not got.split16, (compare, got) + print('soundness: compare forms record no SDWA half evidence') + + # The VOP3 interpolation spelling takes the same operands. + e64 = (w(0xd4000000 | (0x200 << 16) | 4, 0 | (256 << 9)) + w(0xd4000000 | (0x201 << 16) | 4, 0 | (257 << 9)) + + w(END)) + asm = [x[3] for x in G.decode(e64)] + assert asm[:2] == ['v_interp_p1_f32_e64 v4, v0, attr0.x', 'v_interp_p2_f32_e64 v4, v1, attr0.x'], asm + assert sets(S.contract(e64)) == ([0, 1], [0], []), sets(S.contract(e64)) + print('interpolation: VOP3 spelling gives the same pair') + + # Layout against the translator's own packed-position register, for several masks. + assert S.layout(0x8100) == (2, {8: 0, 15: 1}) and S.layout(0x8002)[1][15] == 2 + assert S.layout(0x800F)[1][15] == 2 + 2 + 2 + 3 == 9 + assert S.layout(0x0000) == (0, {}) and S.layout(0xffff)[0] == 6 + 3 + 6 + 9 + probe = struct.pack(' 0.3 + assert S.selectivity(S.contract(SHADERS['packed_only@v1'])) == S.selectivity(S.Contract(frozenset({1}), frozenset(), frozenset())) + for name, code in SHADERS.items(): + if name in MASKS and name != 'unsat_v40': + assert S.consistent(S.contract(code), MASKS[name])[0], (name, hex(MASKS[name])) + print('selectivity: empty contract 1.0; two-pair contract %.4f (%.2f bits)' + % (S.selectivity(tight), S.contract_bits(tight))) + + +# ---- end to end ---------------------------------------------------------------------------------- + +def blob_with_header(header, code): + assert len(header) % 4 == 0 and len(header) <= 0x7c and G.PREFETCH not in header + blob = header + G.PREFETCH + code + assert G.strip_header(blob) == G.PREFETCH + code + return blob + + +def header_words(index, ena, addr, at=2, ones=False): + words = [0] * 12 + words[0] = 2 # constant decoy (a version number) + words[1] = index + 1 # per-shader decoy (a counter) + words[at], words[at + 1] = ena, addr + words[8] = 0x0001 # constant decoy that looks like a small mask + if ones: + words[9], words[10] = 0x0000ffff, 0xffff0000 # all-ones decoys: a u32 and a u16 0xffff + return w(*words) + + +def vs_blob(): + return VS_WORDS + + +def write_request(folder, index, ps_blob, swap=False): + key = '%016x' % (0x1000 + index) + a, b = (ps_blob, vs_blob()) if swap else (vs_blob(), ps_blob) + (folder / ('req_%s.a' % key)).write_bytes(a) + (folder / ('req_%s.b' % key)).write_bytes(b) + (folder / ('req_%s.root' % key)).write_bytes(root_blob()) + return key + + +ORDER = ('packed_only@v1', 'pair_then_packed@v2', 'two_pairs', 'packed_sdwa@v1', 'packed_bfe@v1', + 'packed_alias@v1', 'no_inputs', 'write_first') + + +def build(folder, maker, names=ORDER, repeat=1): + folder.mkdir() + index = 0 + for _ in range(repeat): + for name in names: + write_request(folder, index, maker(index, name), swap=index % 2 == 1) + index += 1 + return index + + +def run_tool(*args, env=None): + run = subprocess.run([sys.executable, '-B', str(TOOL), *map(str, args)], capture_output=True, text=True, + env=env) + return run + + +def scan(folder, tmp, label): + out = tmp / (label + '.json') + run = run_tool(folder, '--json', out, '--top', 12) + assert run.returncode == 0, (run.stdout, run.stderr) + return run.stdout, json.loads(out.read_text()) + + +def by_name(data, region, name): + for entry in data['candidates']: + if entry['region'] == region and name in [entry['candidate']] + entry['equivalent']: + return entry + raise AssertionError('candidate %s %s not in the JSON' % (region, name)) + + +def simple_maker(index, name, at=2, extra=0): + mask = MASKS[name] + ena = mask | (extra if index == 1 else 0) + return blob_with_header(header_words(index, ena, mask, at), SHADERS[name]) + + +def end_to_end(tmp): + # Corpus A: masks at header +8 and +12, a constant decoy and a counter decoy. + text, data = scan(tmp / 'a', tmp, 'a') if build(tmp / 'a', simple_maker) else None + assert 'pipelines: 8 scanned, 0 skipped' in text, text + assert 'informative contracts: 6 of 8; distinct contracts' in text, text + assert 'verdict: unique full match ps.header pair32@8' in text, text + assert data['verdict'] == 'unique full match ps.header pair32@8' + top = data['candidates'][0] + assert (top['region'], top['candidate'], top['inconsistent'], top['full_match']) == \ + ('ps.header', 'pair32@8', 0, True), top + assert top['relations'] == {'equal': 8, 'ena_subset': 0, 'addr_subset': 0, 'other': 0}, top + assert top['tight'] == 6 and top['packed_total'] == 5 and top['packed_agree'] == 5, top + for decoy in ('addr32@0', 'addr32@4', 'addr32@32'): + entry = by_name(data, 'ps.header', decoy) + assert entry['rank'] > top['rank'] and entry['inconsistent'] >= 1 and not entry['full_match'], entry + assert 'mask agreement: 8 of 8 pipelines consistent (coverage and pair rules), 6 tight, ' 'failures C0=0 C1=0 C2=0' in text, text + assert 'packed-position agreement: 5 of 5 pipelines that split a live-in register into 16-bit halves' in text + assert text.rstrip().endswith('does not prove hardware behaviour'), text + assert data['top_candidate_pipelines'][0]['addr'] in (0x8100, 0x8002, 0x0012) + assert len(data['top_candidate_pipelines']) == 8 + print('positive control (corpus A): unique full match ps.header pair32@8; decoy controls +0, +4, +32 rank lower and fail') + corpus_a = text + + # Corpus B: one enable mask differs from its address mask (an extra bit below bit 15). + build(tmp / 'b', lambda i, n: simple_maker(i, n, extra=0x0080)) + text, data = scan(tmp / 'b', tmp, 'b') + assert data['verdict'] == 'unique full match ps.header pair32@8', text + top = data['candidates'][0] + assert top['relations'] == {'equal': 7, 'ena_subset': 0, 'addr_subset': 1, 'other': 0}, top + print('enable/address disagreement (corpus B): same unique full match; relations show 1 enable mask that differs from its address') + + # Corpus C: masks at +8/+12 in half of the shaders, at +16/+20 in the other half. + build(tmp / 'c', lambda i, n: blob_with_header( + header_words(i, MASKS[n], MASKS[n], at=2 if i % 2 == 0 else 4), SHADERS[n]), repeat=2) + text, data = scan(tmp / 'c', tmp, 'c') + assert data['verdict'] == 'no location is consistent with all pipelines', text + assert not any(entry['full_match'] for entry in data['candidates']) + print('wrong-location control (corpus C): masks at two different offsets give no location consistent with all pipelines') + + # Corpus D: tagged byte addresses at different offsets per shader. + def tagged(index, name): + words = [0] * 28 + words[0] = 2 + words[1] = index + 1 + first, second = 2 + 2 * (index % 4), 14 + 2 * ((index // 2) % 4) + words[first:first + 2] = [0x000286CC, MASKS[name]] + words[second:second + 2] = [0x000286D0, MASKS[name]] + return blob_with_header(w(*words), SHADERS[name]) + build(tmp / 'd', tagged, repeat=2) + text, data = scan(tmp / 'd', tmp, 'd') + assert data['verdict'] == 'unique full match ps.header tag:byteaddr', text + print('corpus D: unique full match ps.header tag:byteaddr with varying word offsets') + + # Corpus E: only shaders without live-in registers. + build(tmp / 'e', simple_maker, names=('no_inputs', 'write_first'), repeat=4) + text, data = scan(tmp / 'e', tmp, 'e') + assert 'corpus is uninformative' in text and 'unique full match' not in text, text + assert data['verdict'].startswith('uninformative corpus') and data['informative'] == 0 + print('corpus E: uninformative corpus reported, no match claimed') + + # Corpus F: skipped entries are counted with their reason and do not stop the scan. + build(tmp / 'f', simple_maker) + (tmp / 'f' / 'req_00000000000fffff.a').write_bytes(vs_blob()) # two vertex shaders + (tmp / 'f' / 'req_00000000000fffff.b').write_bytes(vs_blob()) + (tmp / 'f' / 'req_00000000000ffffe.a').write_bytes(vs_blob()) # no .b file + (tmp / 'f' / 'req_00000000000ffffd.a').write_bytes(vs_blob()) # a broken container + (tmp / 'f' / 'req_00000000000ffffd.b').write_bytes(b'DXBC' + bytes(60)) + text, data = scan(tmp / 'f', tmp, 'f') + assert 'pipelines: 8 scanned, 3 skipped' in text, text + for category in ('stages', 'unreadable', 'container'): + assert 'skipped %s: 1' % category in text, text + assert data['verdict'] == 'unique full match ps.header pair32@8' + print('corpus F: stage, unreadable and container failures skipped with reasons, scan continues') + + # All-ones decoy: 0x0000ffff (u32) and 0xffff (u16) in every header fit every contract, so they + # are a full match too; they must lose to the planted location on tight. + build(tmp / 'g', lambda i, n: blob_with_header( + header_words(i, MASKS[n], MASKS[n], ones=True), SHADERS[n])) + text, data = scan(tmp / 'g', tmp, 'g') + assert data['verdict'] == 'unique full match ps.header pair32@8', text + top = data['candidates'][0] + ones = by_name(data, 'ps.header', 'addr32@36') + assert 'addr16@42' in [ones['candidate']] + ones['equivalent'], ones + assert ones['full_match'] and ones['tight'] == 0 and ones['rank'] > top['rank'], ones + assert top['tight'] == 6 and top['full_match'], top + print('decoy control (all-ones u32 and u16 words): also a full match with tight 0; the planted ' + 'location wins on tight') + + # Packed misfire: one shader splits v0 into halves while its mask puts bit 15 at v1. Packed + # evidence does not vote, so the planted location stays the unique full match; the packed line + # shows the one disagreement. + build(tmp / 'h', simple_maker, names=ORDER + ('packed_misfire',)) + text, data = scan(tmp / 'h', tmp, 'h') + assert data['verdict'] == 'unique full match ps.header pair32@8', text + top = data['candidates'][0] + assert (top['packed_total'], top['packed_agree']) == (6, 5), top + assert 'packed-position agreement: 5 of 6 pipelines' in text, text + assert 'mask agreement: 9 of 9 pipelines consistent' in text, text + print('packed misfire control: planted location stays the unique full match; packed line 5 of 6') + + # Loop-carried register and an unsatisfiable contract: neither may break the planted match. + build(tmp / 'i', simple_maker, names=ORDER + ('loop_ambiguous', 'unsat_v40')) + text, data = scan(tmp / 'i', tmp, 'i') + assert data['verdict'] == 'unique full match ps.header pair32@8', text + assert 'pipelines: 10 scanned, 0 skipped' in text and 'informative contracts: 6 of 9' in text, text + assert ('ambiguous live-in reads (inside a loop, written later): 1 pipelines, excluded registers ' + 'do not vote') in text, text + assert 'contracts no mask can satisfy: 1 pipelines (excluded)' in text, text + assert len(data['excluded_unsatisfiable']) == 1 and len(data['ambiguous_pipelines']) == 1, data + print('loop control: a loop-carried register is ambiguous and the planted location stays the unique ' + 'full match; an unsatisfiable contract (v40) is excluded and counted') + + # Packed lens: two full matches tie on tight; only the real one agrees on every packed split. + alternatives = {'pair_then_packed@v2': 0x0102, 'packed_only@v1': 0x0300, 'two_pairs': 0x0012, + 'no_inputs': 0x0004} + + def lens_maker(index, name): + words = list(struct.unpack('<12I', header_words(index, MASKS[name], MASKS[name], ones=True))) + words[4] = words[5] = alternatives[name] + return blob_with_header(w(*words), SHADERS[name]) + build(tmp / 'j', lens_maker, names=tuple(alternatives)) + text, data = scan(tmp / 'j', tmp, 'j') + assert data['verdict'].startswith('2 full matches (ambiguous): ps.header pair32@8, ps.header pair32@16'), text + assert 'full matches that also agree on every packed split: ps.header pair32@8\n' in text + '\n', text + print('packed lens: 2 full matches tie on tight; only the real location agrees on every packed split') + + # Sibling request files become regions req.. + folder = tmp / 'k' + build(folder, lambda i, n: blob_with_header(header_words(i, 0, 0), SHADERS[n])) + for index, name in enumerate(ORDER): + key = '%016x' % (0x1000 + index) + (folder / ('req_%s.desc' % key)).write_bytes(w(0, 0, MASKS[name], MASKS[name], 0x0001, index)) + (folder / ('req_%016x.big' % 0x1000)).write_bytes(bytes(S.SIBLING_LIMIT + 1)) + (folder / ('req_%016x.rtv' % 0x1000)).write_bytes(b'rtv1 1 2') + records, skipped = [], [] + S.scan_requests(str(folder), records, skipped) + assert not skipped and sorted(records[0].regions) == ['ps.header', 'req.desc'], sorted(records[0].regions) + text, data = scan(folder, tmp, 'k') + assert data['verdict'] == 'unique full match req.desc pair32@8', text + print('sibling files: masks in req_.desc give a unique full match in region req.desc; ' + 'oversized and reserved extensions are not regions') + + pixel_dir_cases(tmp) + + container_case(tmp) + capture_case(tmp) + + determinism(tmp) + count = reference_check(tmp / 'a') + reference_check(tmp / 'd') + reference_check(tmp / 'h') + print('reference: %d candidate summaries equal a direct per-candidate evaluation' % count) + + # Usage errors exit 2; an empty directory still completes. + assert run_tool().returncode == 2 + assert run_tool(tmp / 'missing').returncode == 2 + assert run_tool(tmp / 'a', '--top', 0).returncode == 2 + (tmp / 'empty').mkdir() + assert run_tool(tmp / 'empty').returncode == 0 + print('usage: missing input, missing directory and bad --top exit 2; empty directory exits 0') + return corpus_a + + +def reference_check(folder, limit=0x1000): + """Compare the two-pass tallies with a direct per-candidate evaluation of every pipeline.""" + records, skipped = [], [] + S.scan_requests(str(folder), records, skipped) + assert records and not skipped + reference = {} + for record in records: + shader = record.contract + for region, data in record.regions.items(): + words, halves = S.unpack(data[:limit]) + tags = S.tag_values(words) + names = [(k, o) for k in ('addr32', 'pair32', 'pair32r') for o in range(0, len(words) * 4, 4)] + names += [(k, o) for k in ('addr16', 'pair16', 'pair16r') for o in range(0, len(halves) * 2, 2)] + names += [(k, -1) for k in tags] + for kind, offset in names: + value = S.candidate_value(words, halves, tags, kind, offset) + if value is None: + continue + addr = value[1] + ok, reason = S.consistent(shader, addr) + item = reference.setdefault((region, kind, offset), dict( + present=0, consistent=0, tight=0, packed_total=0, packed_agree=0, fails=[0, 0, 0], bits=0.0)) + item['present'] += 1 + item['consistent'] += ok + if ok and S.informative(shader): + item['bits'] += S.contract_bits(shader) + if S.layout(addr)[0] == max(shader.live_in) + 1: + item['tight'] += 1 + if not ok: + item['fails'][{'C0': 0, 'C1': 1, 'C2': 2}[reason[:2]]] += 1 + agrees = S.packed_agrees(shader, addr) + if agrees is not None: + item['packed_total'] += 1 + item['packed_agree'] += agrees + stats = S.candidate_stats(*S.tally(records, limit)) + assert len(stats) == len(reference), (len(stats), len(reference)) + for stat in stats: + item = reference[(stat.region, stat.kind, stat.offset)] + got = dict(present=stat.present, consistent=stat.consistent, tight=stat.tight, + packed_total=stat.packed_total, packed_agree=stat.packed_agree, fails=stat.fails) + assert got == {k: item[k] for k in got} and abs(stat.bits - item['bits']) < 1e-9, (stat.name, got, item) + return len(stats) + + +def pixel_dir_cases(tmp): + """--pixel-dir: raw blobs and containers; ids are positions, file names never printed.""" + secret = 'localname' + raw = tmp / 'pd_raw' + raw.mkdir() + for index, name in enumerate(ORDER): + (raw / ('%s_%02d.bin' % (secret, index))).write_bytes(simple_maker(index, name)) + (raw / ('%s_99.bin' % secret)).write_bytes(vs_blob()) # a vertex shader: skipped + (raw / 'subdirectory').mkdir() # not a regular file: ignored + out = tmp / 'pd_raw.json' + run = run_tool('--pixel-dir', raw, '--json', out) + assert run.returncode == 0, run.stderr + data = json.loads(out.read_text()) + assert data['verdict'] == 'unique full match ps.header pair32@8', run.stdout + assert 'pipelines: 8 scanned, 1 skipped' in run.stdout and 'skipped stages: 1' in run.stdout, run.stdout + assert [c['id'] for c in data['contracts']] == ['p%06d' % n for n in range(1, 9)], data['contracts'] + assert data['skipped'][0]['id'] == 'p000009', data['skipped'] + assert secret not in run.stdout and secret not in out.read_text() + assert 'p0000' not in run.stdout, run.stdout # aggregates only without --list + listed = run_tool('--pixel-dir', raw, '--list') + assert 'p000001 0x8100 0x8100 1 v1 v1' in listed.stdout and secret not in listed.stdout, listed.stdout + assert 'id ena addr packed_register live_in split16' in listed.stdout + print('pixel-dir: raw blobs give ids p000001..p000008, no file name in stdout or JSON; --list ' + 'adds the per-pipeline table, default output has no ids') + + # Containers with the masks in the PSV0 part; the image head holds all-ones decoys that sort first. + boxes = tmp / 'pd_box' + boxes.mkdir() + for index, name in enumerate(ORDER): + mask = MASKS[name] + blob = container(SHADERS[name], (0xffff, 0xffff), index + 1, + extra=[(b'PSV0', struct.pack('<2I', mask, mask) + bytes(8)), + (b'ISG1', struct.pack('<4I', index, 0x0001, 7, 0))]) + (boxes / ('%s_%02d.dxbc' % (secret, index))).write_bytes(blob) + run = run_tool('--pixel-dir', boxes, '--json', tmp / 'pd_box.json') + data = json.loads((tmp / 'pd_box.json').read_text()) + assert data['verdict'] == 'unique full match ps.part.PSV0 pair32@0', run.stdout + first = data['candidates'][0] + assert (first['region'], first['tight']) == ('ps.part.PSV0', 6), first + ones = by_name(data, 'ps.fssm.head', 'addr32@64') # all-ones decoy in an earlier region + assert ones['full_match'] and ones['tight'] == 0 and ones['rank'] > first['rank'], ones + regions = {c['region'] for c in data['candidates']} + assert {'ps.part.PSV0', 'ps.part.ISG1', 'ps.fssm.head', 'ps.xdat.7'} <= regions, regions + assert secret not in run.stdout and secret not in (tmp / 'pd_box.json').read_text() + print('pixel-dir: containers give a ps.part.PSV0 location; ps.part.ISG1, ps.fssm.head and ' + 'ps.xdat.7 regions are scanned') + both = run_tool(tmp / 'a', '--pixel-dir', raw) + assert both.returncode == 0 and 'pipelines: 16 scanned, 1 skipped' in both.stdout, both.stdout + print('inputs: a request directory and --pixel-dir combine') + + +def determinism(tmp): + outputs = [] + for seed in ('1', '2', '12345'): + env = dict(os.environ, PYTHONHASHSEED=seed) + outputs.append(run_tool(tmp / 'a', '--top', 50, env=env).stdout) + assert outputs[0] == outputs[1] == outputs[2] and outputs[0].count(chr(10)) > 10 + print('determinism: identical stdout under three PYTHONHASHSEED values') + + +def container(code, masks, decoy, extra=()): + """A DXBC container (DXIL part, XDAT table with a native FSSM entry and one more entry), plus + any extra (tag, payload) parts after the DXIL part.""" + image = bytearray(256) + code + image[:4] = b'FSSM' + struct.pack_into('] [--capture ] + [--pixel-dir ] [--json ] [--list] [--top N] [--region-limit BYTES] + --pixel-dir: every regular file directly in the directory is one pixel shader (a DXBC container + or a raw blob). Pipelines are numbered p000001... in sorted file-name order; names are never printed. +""" +import argparse +import json +import math +import os +import re +import struct +import sys +from collections import Counter, namedtuple + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as G # noqa: E402 (also puts tools/ on sys.path) + +# Register count of each address-mask bit 0..15 (the same table as Pipeline.ps_hw_inputs). +WIDTHS = (2, 2, 2, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1) +PAIR_BITS = (0, 1, 2, 4, 5, 6) # the two-register I/J inputs that interpolation can read +PACKED_BIT = 15 # POS_FIXED_PT: two 16-bit halves in one register + +BYTE_ADDRESS = {'ena': 0x286CC, 'addr': 0x286D0} +CONTEXT_INDEX = {'ena': 0x1B3, 'addr': 0x1B4} +MM_INDEX = {'ena': 0xA1B3, 'addr': 0xA1B4} + +Contract = namedtuple('Contract', 'live_in ij_pairs split16 ambiguous', defaults=(frozenset(),)) + +# Forms whose operands are all sources even though the first one may be a vector register. +ALL_SOURCE_PREFIXES = ('v_cmp', 'ds_write', 'v_nop') +READ_WRITE = ('v_swap_b32', 'v_swaprel_b32') +UNKNOWN_FLOW = ('s_setpc_b64', 's_swappc_b64', 's_rfe_b64', 's_call_b64') + + +# ---- A. contract of one pixel shader ------------------------------------------------------------- + +def base_name(name): + while True: + stripped = re.sub(r'_(e32|e64|sdwa|dpp16|dpp8|dpp)$', '', name) + if stripped == name: + return name + name = stripped + + +def operand_vregs(token): + """'v1', '|v1|', '-v1', 'sext(v1)', 'v[4:6]' -> (first, last) VGPR numbers, else None.""" + text = token.strip() + while True: + previous = text + text = text.strip('-~!|') + m = re.fullmatch(r'(?:sext|abs|neg)\((.*)\)', text) + if m: + text = m.group(1) + if text == previous: + break + parsed = G.reg_range(text) + if parsed and parsed[0] == 'v': + return parsed[1], parsed[2] + return None + + +def constant(token): + try: + return int(token.strip(), 0) + except ValueError: + return None + + +def all_source(base): + return base == 'exp' or 'store' in base or base.startswith(ALL_SOURCE_PREFIXES) + + +def parse_instruction(asm): + """-> (mnemonic, base, operands, modifiers, destination span, source tokens, written spans).""" + mnemonic, ops, mods = G.parse(asm) + base = base_name(mnemonic) + if mnemonic == 'exp' and ops: + ops[0] = ops[0].partition(' ')[2] + destination = operand_vregs(ops[0]) if ops else None + has_destination = destination is not None and not all_source(base) and base not in READ_WRITE + sources = ops[1:] if has_destination else ops + if base in READ_WRITE: # both operands are read, then both are rewritten + writes = [span for span in map(operand_vregs, ops) if span] + else: + writes = [destination] if has_destination else [] + return mnemonic, base, ops, mods, destination if has_destination else None, sources, writes + + +def control_flow(decoded): + """-> (branch targets, backward spans (target, source), unknown): offsets from the label text. + `unknown` is set for a branch whose target the text does not give and for indirect forms.""" + targets, spans, unknown = set(), [], False + for off, _, name, asm in decoded: + base = base_name(name) + if base == 's_branch' or base.startswith('s_cbranch'): + m = re.search(r'label_0x([0-9a-f]+)', asm) + if m is None or 'fork' in base or 'join' in base: + unknown = True + else: + target = int(m.group(1), 16) + targets.add(target) + if target <= off: + spans.append((target, off)) + elif base in UNKNOWN_FLOW: + unknown = True + return targets, spans, unknown + + +def contract_of_decoded(decoded): + """Scan decoded instructions, (offset, length, name, asm) as gfx2hlsl.decode returns them. + + A register first read before any write is live-in, unless the read sits inside a loop (a + backward branch spans it) and the register is written later in program order: then the value may + be loop-carried, the register is `ambiguous` and takes no part in any rule. Evidence taken from + a read that is unsafe in that sense is dropped, and aliases do not cross basic blocks.""" + parsed = [(off,) + parse_instruction(asm) for off, _, _, asm in decoded] + targets, spans, unknown = control_flow(decoded) + last_write = {} + for item in parsed: + for first, last in item[-1]: + for register in range(first, last + 1): + last_write[register] = item[0] + written, holds = set(), {} + live_in, ambiguous = set(), set() + interp_i, interp_j = {}, {} + low, high = set(), set() + + def entry(register): + """The live-in register whose entry value `register` still holds, else None.""" + return register if register not in written else holds.get(register) + + def single(token): + span = operand_vregs(token) + return span[0] if span and span[0] == span[1] else None + + for off, mnemonic, base, ops, mods, destination, sources, writes in parsed: + if off in targets: + holds.clear() + if not ops: + continue + in_loop = unknown or any(t <= off <= s for t, s in spans) + + def unsafe(register): + later = last_write.get(register) + return in_loop and later is not None and later > off + + for token in sources: + span = operand_vregs(token) + if span: + for register in range(span[0], span[1] + 1): + if register not in written: + (ambiguous if unsafe(register) else live_in).add(register) + + fields = {} + for modifier in mods: + key, _, value = modifier.partition(':') + if value: + fields[key] = value + + def held_by(token): + register = single(token) + if register is None or unsafe(register): + return None + return entry(register) + + # Interpolation: I feeds p1, J feeds p2 (operands: destination, I or J, attribute). + if base in ('v_interp_p1_f32', 'v_interp_p2_f32') and len(ops) >= 3: + held = held_by(ops[1]) + if held is not None: + (interp_i if base == 'v_interp_p1_f32' else interp_j).setdefault(ops[2], set()).add(held) + + # 16-bit half evidence on a register that still holds a live-in value. + def note(token, found): + held = held_by(token) + if held is not None: + found.add(held) + + args = ops[1:] if destination is not None else ops + # No SDWA evidence from compare forms: v_cmp has a scalar destination and v_cmpx none, so + # the source index of a selection would be ambiguous. Losing evidence is acceptable. + for index, token in enumerate(args[:3] if not base.startswith('v_cmp') else ()): + selection = fields.get('src%d_sel' % index) + if selection == 'WORD_0': + note(token, low) + elif selection == 'WORD_1': + note(token, high) + if base == 'v_and_b32' and len(args) == 2: + for a, b in ((0, 1), (1, 0)): + if constant(args[a]) == 0xffff: + note(args[b], low) + elif base in ('v_lshrrev_b32', 'v_ashrrev_i32') and len(args) == 2: + if constant(args[0]) == 16: + note(args[1], high) + elif base in ('v_bfe_u32', 'v_bfe_i32') and len(args) == 3 and constant(args[2]) == 16: + if constant(args[1]) == 0: + note(args[0], low) + elif constant(args[1]) == 16: + note(args[0], high) + + moved = None + if (destination is not None and mnemonic in ('v_mov_b32', 'v_mov_b32_e32') and len(ops) == 2 + and not mods and re.fullmatch(r'v\d+', ops[1].strip())): + moved = held_by(ops[1]) + for first, last in writes: + for register in range(first, last + 1): + written.add(register) + holds.pop(register, None) + if moved is not None and destination[0] == destination[1]: + holds[destination[0]] = moved + if base == 's_branch' or base.startswith('s_cbranch') or base in UNKNOWN_FLOW: + holds.clear() + + pairs = set() + for attribute, registers in interp_i.items(): + pairs.update(r for r in registers if r + 1 in interp_j.get(attribute, ())) + return Contract(frozenset(live_in), frozenset(pairs), frozenset(low & high), + frozenset(ambiguous - live_in)) + + +def contract(code): + """Contract of a pixel shader's instruction stream. Raises gfx2hlsl.Unsupported if undecodable.""" + return contract_of_decoded(G.decode(code)) + + +# ---- B. layout and consistency ------------------------------------------------------------------- + +def layout(addr): + """-> (register count, {bit: first register}) for the set bits of an address mask.""" + registers, position = {}, 0 + for bit in range(16): + if addr >> bit & 1: + registers[bit] = position + position += WIDTHS[bit] + return position, registers + + +_INFO = {} + + +def mask_info(addr): + """-> (register count, bit mask of pair-start registers, bit-15 register or -1), cached.""" + info = _INFO.get(addr) + if info is None: + count, registers = layout(addr) + info = _INFO[addr] = (count, sum(1 << registers[b] for b in PAIR_BITS if b in registers), + registers.get(PACKED_BIT, -1)) + return info + + +def consistent(shader, addr): + """Mask agreement: -> (True, '') or (False, first failing rule C0, C1 or C2). Packed does not vote.""" + if not 0 <= addr <= 0xffff: + return False, 'C0 range' + count, registers = layout(addr) + if any(r >= count for r in shader.live_in): + return False, 'C1 coverage' + starts = {registers[bit] for bit in PAIR_BITS if bit in registers} + if any(r not in starts for r in shader.ij_pairs): + return False, 'C2 pairs' + return True, '' + + +def packed_agrees(shader, addr): + """None without a split register; else whether every split register is the bit-15 register.""" + if not shader.split16: + return None + if not 0 <= addr <= 0xffff: + return False + register = layout(addr)[1].get(PACKED_BIT) + return register is not None and all(r == register for r in shader.split16) + + +_COMBOS = [] + + +def combos(): + """Counter of (register count, pair-start mask) over all 65536 address masks.""" + if not _COMBOS: + counter = Counter() + for addr in range(0x10000): + count, starts, _ = mask_info(addr) + counter[(count, starts)] += 1 + _COMBOS.append(counter) + return _COMBOS[0] + + +_SELECTIVITY = {} + + +def selectivity(shader): + """Fraction of all 65536 address masks that satisfy C1 and C2 for the contract.""" + if shader not in _SELECTIVITY: + need = sum(1 << r for r in shader.ij_pairs) + top = max(shader.live_in, default=-1) + hits = sum(n for (count, starts), n in combos().items() if count > top and need & ~starts == 0) + _SELECTIVITY[shader] = hits / 0x10000 + return _SELECTIVITY[shader] + + +def contract_bits(shader): + """-log2 of the selectivity; 16 bits when no mask at all satisfies the contract.""" + fraction = selectivity(shader) + return -math.log2(fraction) if fraction else 16.0 + + +def informative(shader): + return bool(shader.live_in) + + +# Per (contract, address) verdict packed in one small integer for the scan's inner loop. +RULE_MASK, TIGHT, PACKED_APPLIES, PACKED_OK, INFORMATIVE, CONSISTENT_INFORMATIVE = 3, 4, 8, 16, 32, 64 +RULES = ('', 'C1 coverage', 'C2 pairs', 'C0 range') # rule code 0 = consistent, 3 = C0 + + +_IDS = [] + + +def address_ids(): + """-> (ids, infos): ids[addr] indexes infos, the distinct (count, pair starts, bit-15 register) + triples over all 65536 masks. Index 0 stands for a value above 0xffff (rule C0).""" + if not _IDS: + index, infos, ids = {}, [None], [] + for addr in range(0x10000): + info = mask_info(addr) + if info not in index: + index[info] = len(infos) + infos.append(info) + ids.append(index[info]) + _IDS.extend((ids, infos)) + return _IDS + + +class Judge: + """The verdict code of one contract for every kind of mask value, filled in on demand.""" + __slots__ = ('max_live', 'need', 'split', 'inf', 'weight', 'codes', 'ids', 'infos') + + def __init__(self, shader): + self.max_live = max(shader.live_in, default=-1) + self.need = sum(1 << r for r in shader.ij_pairs) + self.split = tuple(shader.split16) + self.inf = informative(shader) + self.weight = contract_bits(shader) if self.inf else 0.0 + self.ids, self.infos = address_ids() + self.codes = [None] * len(self.infos) + + def code(self, addr): + index = self.ids[addr] if 0 <= addr <= 0xffff else 0 + code = self.codes[index] + return code if code is not None else self.code_of(index) + + def code_of(self, index): + code = INFORMATIVE if self.inf else 0 + if self.split: + code |= PACKED_APPLIES + if index == 0: + code |= 3 + else: + count, starts, packed = self.infos[index] + if self.max_live >= count: + code |= 1 + elif self.need & ~starts: + code |= 2 + elif self.inf: + code |= CONSISTENT_INFORMATIVE + if count == self.max_live + 1: + code |= TIGHT + if self.split and packed >= 0 and all(r == packed for r in self.split): + code |= PACKED_OK + self.codes[index] = code + return code + + +# ---- C. pipelines and regions -------------------------------------------------------------------- + +class Skip(Exception): + pass + + +class PipelineRecord: + def __init__(self, ident, shader, regions): + self.ident = ident + self.contract = shader + self.regions = regions + + +def raw_regions(blob): + at = blob.find(G.PREFETCH, 0, 0x80) + return {'ps.header': blob[:at] if at >= 0 and at % 4 == 0 else b''} + + +def part_name(tag): + printable = len(tag) == 4 and all(0x20 < c < 0x7f for c in tag) + return 'ps.part.' + (tag.decode('ascii') if printable else tag.hex()) + + +def container_regions(blob): + """Mirror pixel_aot.container_code to also keep the bytes around the pixel code.""" + import zlib + from pixel_aot import container_code, inflate + from resource_inventory import parts + try: + container = parts(blob) + program = container[b'DXIL'] + code = container_code(program, stage=0) + table = program.index(b'XDAT', 24) + count, = struct.unpack_from(' len(program): + raise ValueError('XDAT entry outside the program part') + seen[tag] += 1 + name = 'ps.xdat.%d' % tag + ('' if seen[tag] == 1 else '.%d' % seen[tag]) + regions[name] = program[o:o + n] + for tag, payload in container.items(): + if tag != b'DXIL': + regions[part_name(tag)] = payload + except (KeyError, ValueError, struct.error, zlib.error) as error: + raise Skip('container: %s' % error) + return code, regions + + +def pixel_blob(blob): + """-> (pixel code, regions) for one pixel shader that is a container or a raw blob.""" + try: + if blob.startswith(b'DXBC'): + code, regions = container_regions(blob) + else: + code, regions = G.strip_header(blob), raw_regions(blob) + kind = G.classify(code) + except G.Unsupported as error: + raise Skip('undecodable: %s' % error) + if kind != 'ps': + raise Skip('stages: [%r]' % kind) + return code, regions + + +def request_pixel_blob(a, b): + """-> (pixel code, regions), choosing the pixel blob the way gfx2hlsl.translate_request does.""" + try: + if a.startswith(b'DXBC') or b.startswith(b'DXBC'): + if not b.startswith(b'DXBC'): + raise Skip('container: pixel blob is not a container') + code, regions = container_regions(b) + if G.classify(code) != 'ps': + raise Skip('stages: container pixel blob does not classify as pixel') + return code, regions + kinds = {G.classify(a): a, G.classify(b): b} + except G.Unsupported as error: + raise Skip('undecodable: %s' % error) + if set(kinds) != {'vs', 'ps'}: + raise Skip('stages: %s' % sorted(kinds)) + blob = kinds['ps'] + return G.strip_header(blob), raw_regions(blob) + + +def make_record(ident, code, regions): + try: + shader = contract(code) + except G.Unsupported as error: + raise Skip('undecodable: %s' % error) + return PipelineRecord(ident, shader, regions) + + +SIBLING_LIMIT = 1 << 20 + + +def scan_requests(directory, records, skipped): + listing = sorted(os.listdir(directory)) + siblings = {} + for name in listing: + m = re.fullmatch(r'req_([0-9a-f]{16})\.(.+)', name) + if m and m.group(2) not in ('a', 'b', 'root', 'rtv'): + siblings.setdefault(m.group(1), []).append((m.group(2), name)) + for name in listing: + m = re.fullmatch(r'req_([0-9a-f]{16})\.a', name) + if not m: + continue + ident = m.group(1) + try: + base = os.path.join(directory, 'req_' + ident) + try: + a, b = (open(base + ext, 'rb').read() for ext in ('.a', '.b')) + except OSError as error: + raise Skip('unreadable: %s' % error.strerror) + code, regions = request_pixel_blob(a, b) + for rest, sibling in siblings.get(ident, ()): + path = os.path.join(directory, sibling) + try: + if os.path.isfile(path) and os.path.getsize(path) <= SIBLING_LIMIT: + with open(path, 'rb') as file: + regions['req.' + rest] = file.read() + except OSError: + pass + records.append(make_record(ident, code, regions)) + except Skip as reason: + skipped.append((ident, str(reason))) + + +def scan_pixel_dir(directory, records, skipped): + """One pixel shader per regular file; ids are 1-based positions, never the file names.""" + names = sorted(n for n in os.listdir(directory) if os.path.isfile(os.path.join(directory, n))) + for index, name in enumerate(names, 1): + ident = 'p%06d' % index + try: + try: + with open(os.path.join(directory, name), 'rb') as file: + blob = file.read() + except OSError as error: + raise Skip('unreadable: %s' % error.strerror) + code, regions = pixel_blob(blob) + records.append(make_record(ident, code, regions)) + except Skip as reason: + skipped.append((ident, str(reason))) + + +def scan_capture(path, records, skipped): + import capture + cap = capture.Capture(path) + done = set() + for call in cap.calls: + w = call['args'][0] + if call['slot'] != 25 or w in done: + continue + done.add(w) + ident = '%x' % (w & 0xffffff) + pso = cap.psos.get(w) + seen = {w} + while pso and pso['path'] == 55 and pso['base']: + if pso['base'] in seen: + pso = None + break + seen.add(pso['base']) + pso = cap.psos.get(pso['base']) + if not pso or pso['path'] != 57: + continue + try: + desc = pso['desc'] + if len(desc) < 96: + raise Skip('pso: description is %d bytes, need 96' % len(desc)) + q = struct.unpack_from('<12Q', desc, 0) + a, b = cap.memory.read(q[5], q[6]), cap.memory.read(q[9], q[10]) + if not a or not b or len(a) != q[6] or len(b) != q[10]: + raise Skip('pso: code not captured') + code, regions = request_pixel_blob(a, b) + regions['pso.desc'] = bytes(desc) + for label, (pointer, size) in (('pso.state_a', q[1:3]), ('pso.state_b', q[3:5])): + if 0 < size <= 0x1000: + data = cap.memory.read(pointer, size) + if data is not None and len(data) == size: + regions[label] = bytes(data) + records.append(make_record(ident, code, regions)) + except Skip as reason: + skipped.append((ident, str(reason))) + + +# ---- D. candidate locations ---------------------------------------------------------------------- + +KIND_RANK = {'tag:byteaddr': 0, 'tag:ctxindex': 0, 'tag:ctxrun': 0, 'tag:mmindex': 0, + 'pair32': 1, 'pair32r': 2, 'pair16': 3, 'pair16r': 4, 'addr32': 5, 'addr16': 6} +TAG_KINDS = ('tag:byteaddr', 'tag:ctxindex', 'tag:ctxrun', 'tag:mmindex') + + +def candidate_name(kind, offset): + return kind if offset < 0 else '%s@%d' % (kind, offset) + + +def find_word(words, value): + for index, word in enumerate(words): + if word == value: + return index + return None + + +def unpack(data): + return (list(struct.unpack('<%dI' % (len(data) // 4), data[:len(data) // 4 * 4])), + list(struct.unpack('<%dH' % (len(data) // 2), data[:len(data) // 2 * 2]))) + + +def tag_values(words): + """{tag kind: (ena, addr)} for the tagged candidates found in a region's words.""" + found = {} + + def following(tags): + values = [] + for key in ('ena', 'addr'): + at = find_word(words, tags[key]) + if at is None or at + 1 >= len(words): + return None + values.append(words[at + 1]) + return tuple(values) + + for kind, tags in (('tag:byteaddr', BYTE_ADDRESS), ('tag:ctxindex', CONTEXT_INDEX), + ('tag:mmindex', MM_INDEX)): + values = following(tags) + if values: + found[kind] = values + at = find_word(words, CONTEXT_INDEX['ena']) + if at is not None and at + 2 < len(words): + found['tag:ctxrun'] = (words[at + 1], words[at + 2]) + return found + + +def candidate_value(words, halves, tags, kind, offset): + """(ena, addr) a candidate reads in one region, or None when it is absent.""" + if kind in TAG_KINDS: + return tags.get(kind) + wide = kind.endswith(('32', '32r')) + values = words if wide else halves + i = offset // (4 if wide else 2) + if kind.startswith('addr'): + return (None, values[i]) if i < len(values) else None + if i + 1 >= len(values): + return None + return (values[i], values[i + 1]) if not kind.endswith('r') else (values[i + 1], values[i]) + + +def relation(ena, addr): + if ena == addr: + return 0 + if ena & ~addr == 0: + return 1 + if addr & ~ena == 0: + return 2 + return 3 + + +class Counts: + """Verdict-code histogram and consistent-informative bit total of one candidate.""" + __slots__ = ('c', 'bits') + + def __init__(self): + self.c = [0] * 128 + self.bits = 0.0 + + +class Judges(dict): + def __missing__(self, shader): + value = self[shader] = Judge(shader) + return value + + +def tally(records, limit): + """Pass 1: per (region, kind) a list of Counts by position. Pair kinds are derived from the + address-reading kinds: pair32@i reads the address word of addr32@(i+1), and pair32r@i reads that + of addr32@i except at a region's last position, which is counted separately in `last`.""" + judges = Judges() + reads = {} # (region, 'addr32' | 'addr16') -> [Counts per position] + last = {} # the same, for the final position of each region only + tags = {} # (region, tag kind) -> Counts + for record in records: + judge = judges[record.contract] + codes, weight, ids = judge.codes, judge.weight, judge.ids + for region, data in record.regions.items(): + words, halves = unpack(data[:limit]) + for kind, values in (('addr32', words), ('addr16', halves)): + if not values: + continue + table = reads.setdefault((region, kind), []) + if len(table) < len(values): + table.extend(Counts() for _ in range(len(values) - len(table))) + for index, addr in enumerate(values): + code = codes[ids[addr] if addr < 0x10000 else 0] + if code is None: + code = judge.code(addr) + entry = table[index] + entry.c[code] += 1 + if code & CONSISTENT_INFORMATIVE: + entry.bits += weight + end = len(values) - 1 + tail = last.setdefault((region, kind), {}) + entry = tail.get(end) + if entry is None: + entry = tail[end] = Counts() + code = judge.code(values[end]) + entry.c[code] += 1 + if code & CONSISTENT_INFORMATIVE: + entry.bits += weight + for kind, (_, addr) in tag_values(words).items(): + entry = tags.get((region, kind)) + if entry is None: + entry = tags[(region, kind)] = Counts() + code = judge.code(addr) + entry.c[code] += 1 + if code & CONSISTENT_INFORMATIVE: + entry.bits += weight + return reads, last, tags + + +class Stat: + """Summary of one candidate over the pipelines where it is present.""" + + def __init__(self, region, kind, offset, counts): + self.region, self.kind, self.offset = region, kind, offset + self.bits = counts.bits + self.present = self.present_informative = self.consistent = 0 + self.informative_consistent = self.tight = self.packed_total = self.packed_agree = 0 + self.fails = [0, 0, 0] # C0, C1, C2 + for code, n in enumerate(counts.c): + if not n: + continue + self.present += n + rule = code & RULE_MASK + if code & INFORMATIVE: + self.present_informative += n + if rule == 0: + self.consistent += n + if code & CONSISTENT_INFORMATIVE: + self.informative_consistent += n + if code & TIGHT: + self.tight += n + else: + self.fails[{3: 0, 1: 1, 2: 2}[rule]] += n + if code & PACKED_APPLIES: + self.packed_total += n + if code & PACKED_OK: + self.packed_agree += n + self.inconsistent = self.present - self.consistent + # filled by the detail pass + self.addrs = set() + self.relations = [0, 0, 0, 0] # ena==addr, ena subset of addr, addr subset of ena, other + self.example = None + self.signature = 0xcbf29ce484222325 + + @property + def name(self): + return candidate_name(self.kind, self.offset) + + def key(self): + return (self.inconsistent, -self.tight, -round(self.bits, 6), -self.informative_consistent) + + +def subtract(counts, other): + result = Counts() + result.c = [a - b for a, b in zip(counts.c, other.c)] + result.bits = counts.bits - other.bits + return result + + +def candidate_stats(reads, last, tags): + stats = [] + for (region, kind), table in reads.items(): + step = 4 if kind == 'addr32' else 2 + pair = kind.replace('addr', 'pair') + for index, counts in enumerate(table): + stats.append(Stat(region, kind, index * step, counts)) + if index: + stats.append(Stat(region, pair, (index - 1) * step, counts)) + tail = last[(region, kind)].get(index) + reduced = subtract(counts, tail) if tail else counts + if any(reduced.c): + stats.append(Stat(region, pair + 'r', index * step, reduced)) + for (region, kind), counts in tags.items(): + stats.append(Stat(region, kind, -1, counts)) + return stats + + +SELECT_MIN, SELECT_MAX = 300, 1500 +FNV_PRIME, FNV_MASK = 0x100000001b3, (1 << 64) - 1 + + +def detail(records, stats, limit): + """Pass 2 for the best-ranked candidates: addresses, relations, example failure, signature.""" + stats.sort(key=lambda s: s.key() + (s.region, KIND_RANK[s.kind], s.offset)) + selected, truncated = [], False + for stat in stats: + if len(selected) >= SELECT_MIN and stat.key() != selected[-1].key(): + break + if len(selected) >= SELECT_MAX: + truncated = True + break + selected.append(stat) + by_region = {} + for stat in selected: + by_region.setdefault(stat.region, []).append(stat) + judges = Judges() + for index, record in enumerate(records): + judge = judges[record.contract] + for region, wanted in by_region.items(): + data = record.regions.get(region) + if data is None: + continue + words, halves = unpack(data[:limit]) + tags = tag_values(words) + for stat in wanted: + value = candidate_value(words, halves, tags, stat.kind, stat.offset) + if value is None: + continue + ena, addr = value + code = judge.code(addr) + h = ((stat.signature ^ (index + 1)) * FNV_PRIME) & FNV_MASK + stat.signature = ((h ^ addr) * FNV_PRIME) & FNV_MASK + if code & RULE_MASK == 0: + stat.addrs.add(addr) + elif stat.example is None: + stat.example = (record.ident, RULES[code & RULE_MASK]) + if ena is not None: + stat.relations[relation(ena, addr)] += 1 + return selected, truncated + + +def group(selected): + """Group candidates that read the same address value everywhere; rank the groups.""" + classes = {} + for stat in selected: + classes.setdefault((stat.region, stat.signature), []).append(stat) + ranked = [] + for members in classes.values(): + # The member whose enable value agrees best with the address is the representative. + members.sort(key=lambda s: (s.relations[3], -s.relations[0], KIND_RANK[s.kind], s.offset)) + ranked.append(members) + ranked.sort(key=lambda m: m[0].key() + (m[0].region, KIND_RANK[m[0].kind], m[0].offset)) + return ranked + + +def is_full(stat, informative_count): + return (informative_count > 0 and stat.inconsistent == 0 and stat.informative_consistent >= 1 + and stat.present_informative == informative_count) + + +def verdict_of(ranked, informative_count): + if informative_count == 0: + return 'uninformative corpus (no live-in vector registers)', [] + full = [m for m in ranked if is_full(m[0], informative_count)] + if not full: + return 'no location is consistent with all pipelines', [] + best = max(m[0].tight for m in full) + leaders = [m for m in full if m[0].tight == best] + if len(leaders) == 1: + return 'unique full match %s %s' % (leaders[0][0].region, leaders[0][0].name), full + listing = ', '.join('%s %s' % (m[0].region, m[0].name) for m in leaders) + return '%d full matches (ambiguous): %s' % (len(leaders), listing), full + + +# ---- E. report ----------------------------------------------------------------------------------- + +def row(stat): + return {'region': stat.region, 'candidate': stat.name, 'present': stat.present, + 'consistent': stat.consistent, 'inconsistent': stat.inconsistent, + 'informative_consistent': stat.informative_consistent, 'tight': stat.tight, + 'bits': round(stat.bits, 1), 'distinct_addr': len(stat.addrs), + 'packed_total': stat.packed_total, 'packed_agree': stat.packed_agree, + 'fail_c0': stat.fails[0], 'fail_c1': stat.fails[1], 'fail_c2': stat.fails[2], + 'relations': dict(zip(('equal', 'ena_subset', 'addr_subset', 'other'), stat.relations)), + 'example_inconsistent': list(stat.example) if stat.example else None} + + +def hex_or_dash(value): + return '-' if value is None else '0x%x' % value + + +FOOTER = 'agreement is evidence about where the masks are stored; it does not prove hardware behaviour' + + +def run(directory, capture_path, pixel_dir, top, limit, listing): + records, skipped = [], [] + if directory: + scan_requests(directory, records, skipped) + if pixel_dir: + scan_pixel_dir(pixel_dir, records, skipped) + if capture_path: + scan_capture(capture_path, records, skipped) + records.sort(key=lambda r: r.ident) + scanned = len(records) + excluded = [r for r in records if informative(r.contract) and selectivity(r.contract) == 0] + records = [r for r in records if not (informative(r.contract) and selectivity(r.contract) == 0)] + informative_count = sum(informative(r.contract) for r in records) + distinct = {r.contract for r in records} + stats = candidate_stats(*tally(records, limit)) + selected, truncated = detail(records, stats, limit) + ranked = group(selected) + verdict, full = verdict_of(ranked, informative_count) + + lines = ['pipelines: %d scanned, %d skipped' % (scanned, len(skipped))] + categories = Counter(reason.split(':')[0] for _, reason in skipped) + for category, count in sorted(categories.items()): + first = next(r for _, r in skipped if r.split(':')[0] == category) + lines.append(' skipped %s: %d (first reason: %s)' % (category, count, first)) + lines.append('informative contracts: %d of %d; distinct contracts: %d' + % (informative_count, len(records), len(distinct))) + lines.append('ambiguous live-in reads (inside a loop, written later): %d pipelines, excluded registers ' + 'do not vote' % sum(bool(r.contract.ambiguous) for r in records)) + lines.append('contracts no mask can satisfy: %d pipelines (excluded)' % len(excluded)) + if records and informative_count == 0: + lines.append('corpus is uninformative: no pixel shader reads a live-in vector register, ' + 'so no location can be told apart') + lines.append('rank region candidate present consistent inconsistent informative tight bits ' + 'distinct_addr packed(agree/total) relations(eq,ena 1 else '-')) + if truncated: + lines.append('note: the detail pass stopped at %d candidates inside a tie; equivalent counts ' + 'for tied candidates may be partial' % SELECT_MAX) + lines.append('verdict: ' + verdict) + per_pipeline = [] + top_stat = ranked[0][0] if ranked else None + if top_stat: + lines.append('mask agreement: %d of %d pipelines consistent (coverage and pair rules), %d tight, ' + 'failures C0=%d C1=%d C2=%d' % (top_stat.consistent, top_stat.present, top_stat.tight, + *top_stat.fails)) + lines.append('packed-position agreement: %d of %d pipelines that split a live-in register into ' + '16-bit halves have it at the register the address mask predicts for bit 15 ' + '(agreement with the assumed register widths, not a proof of the hardware ' + 'register order)' % (top_stat.packed_agree, top_stat.packed_total)) + if any(r.contract.split16 for r in records): + agreeing = ['%s %s' % (m[0].region, m[0].name) for m in full + if m[0].packed_total and m[0].packed_agree == m[0].packed_total] + lines.append('full matches that also agree on every packed split: %s' % (', '.join(agreeing) or 'none')) + for record in records: + data = record.regions.get(top_stat.region) + value = None + if data is not None: + words, halves = unpack(data[:limit]) + value = candidate_value(words, halves, tag_values(words), top_stat.kind, top_stat.offset) + ena, addr = value if value else (None, None) + predicted = None + if addr is not None and 0 <= addr <= 0xffff: + predicted = layout(addr)[1].get(PACKED_BIT) + per_pipeline.append({'id': record.ident, 'present': value is not None, 'ena': ena, 'addr': addr, + 'packed_register': predicted, + 'live_in': sorted(record.contract.live_in), + 'split16': sorted(record.contract.split16), + 'ambiguous': sorted(record.contract.ambiguous)}) + if listing: + lines.append('top candidate %s %s per pipeline:' % (top_stat.region, top_stat.name)) + lines.append('id ena addr packed_register live_in split16 ambiguous') + for item in per_pipeline: + lines.append('%s %s %s %s %s %s %s' % ( + item['id'], hex_or_dash(item['ena']), + 'absent' if not item['present'] else hex_or_dash(item['addr']), + '-' if item['packed_register'] is None else item['packed_register'], + ','.join('v%d' % r for r in item['live_in']) or '-', + ','.join('v%d' % r for r in item['split16']) or '-', + ','.join('v%d' % r for r in item['ambiguous']) or '-')) + if top_stat.example: + lines.append('first inconsistent pipeline for the top candidate: %s (%s)' % top_stat.example) + lines.append(FOOTER) + result = { + 'pipelines': scanned, 'skipped': [{'id': i, 'reason': r} for i, r in skipped], + 'informative': informative_count, 'distinct_contracts': len(distinct), + 'excluded_unsatisfiable': [r.ident for r in excluded], + 'ambiguous_pipelines': [r.ident for r in records if r.contract.ambiguous], + 'contracts': [{'id': r.ident, 'live_in': sorted(r.contract.live_in), + 'ambiguous': sorted(r.contract.ambiguous), + 'ij_pairs': sorted(r.contract.ij_pairs), 'split16': sorted(r.contract.split16), + 'informative': informative(r.contract), + 'bits': round(contract_bits(r.contract), 3) if informative(r.contract) else 0.0} + for r in records], + 'candidates': [dict(row(m[0]), rank=n, full_match=is_full(m[0], informative_count), + equivalent=[s.name for s in m[1:]]) + for n, m in enumerate(ranked[:max(top, 1000)], 1)], + 'detail_truncated': truncated, + 'verdict': verdict, 'top_candidate_pipelines': per_pipeline, 'footer': FOOTER, + } + return lines, result + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) + parser.add_argument('request_dir', nargs='?', help='directory with req_.a/.b/.root files') + parser.add_argument('--capture', help='capture.bin whose path-57 PSOs are scanned') + parser.add_argument('--pixel-dir', help='directory in which every regular file is one pixel shader') + parser.add_argument('--json', help='also write the full result (with pipeline ids) to this file') + parser.add_argument('--list', action='store_true', help='print pipeline ids and the per-pipeline table') + parser.add_argument('--top', type=int, default=10, help='ranked rows to print (default 10)') + parser.add_argument('--region-limit', type=int, default=0x1000, + help='bytes of each region searched for candidates (default 0x1000)') + args = parser.parse_args(argv) + if not (args.request_dir or args.capture or args.pixel_dir): + parser.error('give a request directory, --pixel-dir, --capture, or a combination') + for label, path in (('request directory', args.request_dir), ('--pixel-dir', args.pixel_dir)): + if path and not os.path.isdir(path): + parser.error('%s is not a directory' % label) + if args.capture and not os.path.isfile(args.capture): + parser.error('--capture is not a file') + if args.top < 1 or args.region_limit < 8: + parser.error('--top must be positive and --region-limit at least 8') + lines, result = run(args.request_dir, args.capture, args.pixel_dir, args.top, args.region_limit, args.list) + print('\n'.join(lines)) + if args.json: + with open(args.json, 'w', encoding='utf-8') as file: + json.dump(result, file, indent=1) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From d87e840ed6c29220dad8be09c7f88012bb2cff46 Mon Sep 17 00:00:00 2001 From: John Connor <128232619+JohnConnorNPC@users.noreply.github.com> Date: Thu, 26 Nov 2026 05:45:44 +1000 Subject: [PATCH 120/232] startup: re-key saved shader requests after a cache revision change (#2401) * startup: add an offline shader cache re-key tool shader_cache_rekey.py copies the graphics, RTV variant and slot 67 compute requests of an older cache under the keys of the current cache revision, using gfx2hlsl's own pipeline_key and compute_key, so --pending can fill the new cache without a running title. It only reads the old cache, writes request files only and writes nothing when a request is incomplete. * tests: check the shader cache re-key tool on synthetic requests Requests of an older revision (from a copy of gfx2hlsl with the revision number changed) are re-keyed to pipeline_key and compute_key of the current one, RTV variants follow their new base, a second run writes nothing, current requests keep their names, a missing part, a truncated RTV variant or an RTV variant without its base request exits 1 and writes nothing, and the old cache is unchanged. Registered in CMake, the Linux Python job and AGENTS.md. * docs: describe re-keying a cold shader cache after a revision change Re-key, translate offline and merge without overwriting (robocopy on Windows, cp -rn on Linux), what the re-key tool refuses and what its check covers. --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/startup-runtime.md | 14 ++ tests/startup_shader_cache_rekey_check.py | 235 ++++++++++++++++++++++ tools/startup/shader_cache_rekey.py | 180 +++++++++++++++++ 6 files changed, 434 insertions(+) create mode 100644 tests/startup_shader_cache_rekey_check.py create mode 100644 tools/startup/shader_cache_rekey.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 8f0e90964..d858e7d68 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -242,6 +242,7 @@ jobs: tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_compute_request_offline_check.py \ tests/compute_container_index_check.py \ + tests/startup_shader_cache_rekey_check.py \ tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_mesh57_skeleton_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f7b9d1bea..2c837487f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,6 +180,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py ./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py +./out/pe-env/bin/python -B tests/startup_shader_cache_rekey_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 50df6b9ee..b7bdc1407 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3785,6 +3785,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_offline_check.py") add_test(NAME compute_container_index COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/compute_container_index_check.py") + # Offline re-key of saved shader requests under the current cache revision (pure Python). + add_test(NAME startup_shader_cache_rekey COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_check.py") # Partial colour exports carry their channel mask to the manifest; compressed exports of whole pairs lower (#1674). add_test(NAME startup_gfx2hlsl_export_mask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_export_mask_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 6c559e17b..ec92ff4b8 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1092,6 +1092,20 @@ Archive each run's logs together with a copy of `shader_cache/`, and leave the c When the translator handles more, the next `--pending` pass retries the waiting requests from the same cache. This holds only while the pipeline key is unchanged. The key hashes a translation revision string (`x2w-startup-shader-N`, in `pipeline_key` in `gfx2hlsl.py` and in the runtime). After a revision change the runtime asks for new keys, and the old requests stay in the cache. +**Re-key the old requests after a revision change.** The new cache is cold, so a run would have to request every pipeline again. `tools/startup/shader_cache_rekey.py` copies the graphics, RTV variant and slot 67 compute requests of the old cache under the keys of the current revision, computed with `pipeline_key` and `compute_key` of the `gfx2hlsl.py` next to it. Stop the title and any `--pending` loop first; nothing else may write the cache. Then: + +```powershell +.\out\pe-env\Scripts\python.exe -B tools\startup\shader_cache_rekey.py out\startup\shader_cache out\startup\shader_cache_rekeyed +.\out\pe-env\Scripts\python.exe -B tools\startup\gfx2hlsl.py --pending out\startup\shader_cache_rekeyed +robocopy out\startup\shader_cache_rekeyed out\startup\shader_cache /XC /XN /XO +``` + +1. The re-key step only reads the old cache and writes request files (`req_*`) only, never results or `.fail`. A file already in the new directory is left as it is, so a second run writes nothing. It reads every request before it writes: if a part is missing or unreadable, or an RTV variant is malformed or names a base that is not in the cache, it prints how many, writes nothing and exits with 1. Slot 57 and slot 86 mesh requests have their own key strings and are not re-keyed. `X2W_TRANSLATE_JOBS` sets the number of hashing processes. +2. `--pending` translates the re-keyed requests offline, as it does for a running title's cache. +3. The `robocopy` switches skip every file that already exists in the cache, so results the runtime or a later pass wrote are kept. A `robocopy` exit code below 8 means success: 1 is set when files were copied, and 2 is set because the cache holds files that the new directory does not. A code of 8 or more is a failure. On Linux, run the same steps with `./out/pe-env/bin/python` and merge with `cp -rn out/startup/shader_cache_rekeyed/. out/startup/shader_cache/`, which also keeps existing files. + +`tests/startup_shader_cache_rekey_check.py` checks the tool on synthetic requests only: the names match the current keys, a newer revision gives other names, a second run and a current cache change nothing, and an incomplete request or an RTV variant without its base writes nothing. Re-keying recovers the requests, not the translations: some re-keyed pipelines can still fail to translate, which is separate from the cache key. Nothing here shows that a title runs. + When `fxc` is available, a request that later translates loses its `.fail`. In manifest-only mode (`X2W_FXC` empty) the old `.fail` stays, so on a kept cache the `.fail` categories in `triage.md` can include pipelines that now have a `.txt`. That table counts category tokens over all `.fail` files, up to `--max-items`. ### 3. Measure a run against the previous one diff --git a/tests/startup_shader_cache_rekey_check.py b/tests/startup_shader_cache_rekey_check.py new file mode 100644 index 000000000..fc9a5ffa1 --- /dev/null +++ b/tests/startup_shader_cache_rekey_check.py @@ -0,0 +1,235 @@ +"""tools/startup/shader_cache_rekey.py on synthetic shader requests, pure Python (no Windows, D3D12, Wine or DXC). + +The requests are fabricated byte strings, not shaders: the tool only hashes them. "Older" and "newer" cache +revisions come from a copy of gfx2hlsl.py's source with the revision number in its two key strings changed by +one, so the check follows the next revision bump without an edit. + +- An old cache holds requests of the older revision (two graphics requests, one with an input layout, one + compute request, an RTV variant of the first graphics request), one current-revision graphics request, the same + pipeline as the first at the current revision, a mesh request, a result and a .fail. Their old names differ + from pipeline_key / compute_key of the current revision. +- The tool, run as a script with two hashing processes, writes exactly the current names with the same bytes + (the RTV variant re-keyed to its new base), no results or .fail, and gfx2hlsl.pending_keys lists them. +- With the newer revision the same requests get other names again. +- A second run writes nothing; re-keying a current cache keeps every name. +- A missing request part, a truncated RTV variant or an RTV variant whose base request is missing exits with 1 + and creates nothing. +- The old cache is unchanged: names, bytes and modification times. +""" +import hashlib +import importlib.util +import os +from pathlib import Path +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +STARTUP = ROOT / 'tools' / 'startup' +TOOL = STARTUP / 'shader_cache_rekey.py' +sys.path.insert(0, str(STARTUP)) +import gfx2hlsl as G # noqa: E402 +import shader_cache_rekey as R # noqa: E402 + +failures = [] + + +def check(name, ok, detail=''): + print('%s: %s%s' % ('ok' if ok else 'FAIL', name, (' (%s)' % detail) if detail and not ok else '')) + if not ok: + failures.append(name) + + +def revision_module(delta): + """gfx2hlsl with the cache revision number changed by delta, and that number.""" + text = (STARTUP / 'gfx2hlsl.py').read_text(encoding='utf-8') + literal = re.compile(r"b'x2w-startup-shader-([0-9]+)(cs)?'") + found = literal.findall(text) + assert sorted(suffix for _, suffix in found) == ['', 'cs'] and len({n for n, _ in found}) == 1, ( + "gfx2hlsl.py no longer spells the cache revision as one b'x2w-startup-shader-N' and one " + "b'x2w-startup-shader-Ncs' literal; update revision_module (found %r)" % (found,)) + number = int(found[0][0]) + delta + module = importlib.util.module_from_spec(importlib.util.spec_from_loader('gfx2hlsl_%d' % number, loader=None)) + module.__file__ = str(STARTUP / 'gfx2hlsl.py') + exec(compile(literal.sub(lambda m: "b'x2w-startup-shader-%d%s'" % (number, m.group(2) or ''), text), + module.__file__, 'exec'), module.__dict__) + return module, number + + +def graphics(index, layout=b''): + vs = struct.pack('<4I', 0x7e000280 + index, 0x01020304, index, 0xbf810000) + ps = struct.pack('<3I', 0x7e020281, index * 7, 0xbf810000) + parts = {'.b': ps, '.root': b'RTS0 synthetic root %d' % index, '.a': vs} + if layout: + parts['.ia'] = layout + return parts + + +def gkey(module, parts): + return module.pipeline_key(parts['.a'], parts['.b'], parts['.root'], parts.get('.ia', b'')) + + +COMPUTE = {'.desc': struct.pack('<12Q', *range(12)), '.sa': struct.pack('<7I', *range(7)), '.sb': b'\x05' * 20, + '.data': struct.pack('<2Q', 0x1122334455667788, 0x99), '.root': b'RTS0 synthetic compute root', + '.c67': struct.pack('<2I', 0x7e020280, 0xbf810000)} + + +def ckey(module, parts): + return module.compute_key(parts['.c67'], parts['.data'], parts['.root'], parts['.desc'], parts['.sa'], parts['.sb']) + + +def rtv_text(base): + return 'rtv1 %d 28 87' % base + + +def write_request(directory, key, parts): + for ext, data in parts.items(): + (directory / ('req_%016x%s' % (key, ext))).write_bytes(data) + + +def write_rtv(directory, base): + text = rtv_text(base).encode('ascii') + key = G.fnv(text) + (directory / ('req_%016x.rtv' % key)).write_bytes(text) + return key + + +def snapshot(directory): + return {p.name: (hashlib.sha256(p.read_bytes()).hexdigest(), p.stat().st_mtime_ns) + for p in sorted(directory.iterdir())} + + +def run(src, dst, jobs='2'): + env = dict(os.environ, X2W_TRANSLATE_JOBS=jobs) + return subprocess.run([sys.executable, '-B', str(TOOL), str(src), str(dst)], capture_output=True, text=True, + env=env, timeout=120) + + +def expected_files(module, requests, computes, rtv_bases): + """{name: bytes} of the requests named under module's revision.""" + files = {} + for parts in requests: + for ext, data in parts.items(): + files['req_%016x%s' % (gkey(module, parts), ext)] = data + for parts in computes: + for ext, data in parts.items(): + files['req_%016x%s' % (ckey(module, parts), ext)] = data + for parts in rtv_bases: + text = rtv_text(gkey(module, parts)).encode('ascii') + files['req_%016x.rtv' % G.fnv(text)] = text + return files + + +def contents(directory): + return {p.name: p.read_bytes() for p in sorted(directory.iterdir())} + + +def main(): + older, old_number = revision_module(-1) + newer, new_number = revision_module(+1) + g1, g2, g3 = graphics(1), graphics(2, b'synthetic layout POSITION 0 R32G32B32_FLOAT'), graphics(3) + print('revisions: older %d, newer %d' % (old_number, new_number)) + + with tempfile.TemporaryDirectory(prefix='x2w-rekey-') as tmp: + tmp = Path(tmp) + src = tmp / 'old_cache' + src.mkdir() + for parts in (g1, g2): + write_request(src, gkey(older, parts), parts) + write_request(src, ckey(older, COMPUTE), COMPUTE) + old_rtv = write_rtv(src, gkey(older, g1)) + write_request(src, gkey(G, g1), g1) # the same pipeline at the current revision + write_request(src, gkey(G, g3), g3) # current only + write_request(src, 0x123456789abcdef0, {'.ps57': b'', '.root': b'RTS0 mesh', '.m57': b'\x01' * 8}) + (src / ('%016x.txt' % gkey(older, g1))).write_text('synthetic result\n') + (src / ('%016x.fail' % gkey(older, g2))).write_text('synthetic refusal\n') + before = snapshot(src) + + old_names = {gkey(older, g1), gkey(older, g2), ckey(older, COMPUTE)} + current_names = {gkey(G, g1), gkey(G, g2), ckey(G, COMPUTE)} + check('older-revision names differ from the current keys', not old_names & current_names) + + # (a) re-keyed names are pipeline_key / compute_key of the current revision, with the same bytes. + dst = tmp / 'rekeyed' + first = run(src, dst) + check('re-key exits 0', first.returncode == 0, first.stderr.strip()) + want = expected_files(G, (g1, g2, g3), (COMPUTE,), (g1,)) + got = contents(dst) if dst.is_dir() else {} + check('re-keyed files are exactly the current requests', got == want, + 'extra %s missing %s' % (sorted(set(got) - set(want)), sorted(set(want) - set(got)))) + check('no results or .fail written', all(name.startswith('req_') for name in got)) + check('graphics summary counts the duplicate and the current request', + 'graphics: 4 requests, 2 already current -> 3 keys' in first.stdout, first.stdout) + check('mesh request counted, not re-keyed', 'm57 1, m86 0' in first.stdout, first.stdout) + pending = G.pending_keys(str(dst), False) + rtv_new = G.fnv(rtv_text(gkey(G, g1)).encode('ascii')) + check('gfx2hlsl.pending_keys lists the re-keyed requests', + pending == sorted({gkey(G, g1), gkey(G, g2), gkey(G, g3), ckey(G, COMPUTE), rtv_new}), pending) + + # (e) the RTV variant names the new base and is named by the hash of its new text. + rtv_file = dst / ('req_%016x.rtv' % rtv_new) + check('RTV variant re-keyed to its new base', rtv_file.is_file() and rtv_new != old_rtv + and rtv_file.read_bytes() == rtv_text(gkey(G, g1)).encode('ascii')) + + # (c) a second run writes nothing and changes nothing. + after_first = snapshot(dst) + second = run(src, dst) + check('second run exits 0 and writes nothing', second.returncode == 0 + and 'files: 0 written, %d already present' % len(want) in second.stdout, second.stdout + second.stderr) + check('second run leaves the re-keyed files unchanged', snapshot(dst) == after_first) + + # (d) re-keying a current cache keeps every name and byte. + again = tmp / 'again' + third = run(dst, again, jobs='1') + check('current requests keep their names', third.returncode == 0 and contents(again) == want + and 'graphics: 3 requests, 3 already current -> 3 keys' in third.stdout + and 'compute: 1 requests, 1 already current -> 1 keys' in third.stdout, third.stdout + third.stderr) + + # (b) under a newer revision the same requests get other names (in process: one job keeps the patch). + R.g, saved = newer, R.g + newest = tmp / 'newer' + try: + with open(os.devnull, 'w') as sink: + code = R.rekey(str(src), str(newest), jobs=1, out=sink) + finally: + R.g = saved + got_newer = contents(newest) if newest.is_dir() else {} + check('newer revision re-keys to its own names', code == 0 + and got_newer == expected_files(newer, (g1, g2, g3), (COMPUTE,), (g1,))) + check('newer names differ from the current names', not set(got_newer) & set(want)) + + # (f) negative controls: an incomplete request, a truncated RTV variant or an RTV variant without its base + # request writes nothing. Without the base's ready marker (.a) there is one graphics request less: 5, not 6. + for label, total, reason, damage in ( + ('missing .root', 6, 'unreadable req_%016x.root' % gkey(older, g2), + lambda d: (d / ('req_%016x.root' % gkey(older, g2))).unlink()), + ('truncated RTV variant', 6, '.rtv text does not hash to its name', + lambda d: (d / ('req_%016x.rtv' % old_rtv)).write_bytes( + rtv_text(gkey(older, g1)).encode('ascii')[:-3])), + ('missing RTV base', 5, '.rtv base request %016x is not a complete graphics request' % gkey(older, g1), + lambda d: (d / ('req_%016x.a' % gkey(older, g1))).unlink())): + bad = tmp / ('bad_' + label.replace(' ', '_')) + shutil.copytree(src, bad) + damage(bad) + out = tmp / ('out_' + label.replace(' ', '_')) + result = run(bad, out) + check('%s exits 1' % label, result.returncode == 1, '%d %s' % (result.returncode, result.stderr)) + check('%s is counted' % label, 'error: 1 of %d requests are incomplete or unreadable; nothing written' + % total in result.stderr and reason in result.stderr, result.stderr) + check('%s writes nothing' % label, not out.exists()) + + refused = run(src, src) + check('the old cache is refused as the destination', refused.returncode == 2, refused.stderr) + + # (g) the old cache is unchanged. + check('old cache unchanged (names, bytes, mtimes)', snapshot(src) == before) + + print('%d failed' % len(failures) if failures else 'all checks passed') + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py new file mode 100644 index 000000000..24585fb55 --- /dev/null +++ b/tools/startup/shader_cache_rekey.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Copy the shader requests of an older cache under the keys of the current cache revision. + +usage: shader_cache_rekey.py + +The key of a graphics request (req_.a), of an RTV variant (req_.rtv) and of a device slot 67 compute +request (req_.c67) hashes the translation revision string (pipeline_key and compute_key in gfx2hlsl.py). +After a revision change the runtime asks for new keys, so a kept cache is cold again. This tool recomputes the +key of every such request with the gfx2hlsl.py next to it and copies the request files under the new names into +. `gfx2hlsl.py --pending ` can then translate them without a running title. + +The old cache is only read. Only request files (req_*) are written; results and .fail files are not, and a file +that already exists in is left as it is. Each file is written to a temporary name and renamed; +the ready marker (.a, .c67) goes last, as the runtime writes it. Slot 57 and slot 86 mesh requests have their own +key strings and are only counted. + +All requests are read before anything is written. When a request part is missing or unreadable, or an RTV +variant is malformed, does not match its own name or names a base request that is not in the cache, the tool +prints how many, writes nothing and exits with 1. Usage errors exit with 2. X2W_TRANSLATE_JOBS sets the +number of hashing processes (default: the processor count, at most 61 on Windows). +""" +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import gfx2hlsl as g # noqa: E402 + +REQUEST = re.compile(r'req_([0-9a-f]{16})\.(a|rtv|c67|m57|m86)') +# Request files of each kind; the ready marker is last. +PARTS = {'g': ('.b', '.root', '.ia', '.a'), 'c': ('.desc', '.sa', '.sb', '.data', '.root', '.c67')} +OPTIONAL = {'.ia'} # a graphics request without an input layout has no .ia + + +class Incomplete(Exception): + pass + + +def request_name(directory, key, ext=''): + return os.path.join(directory, 'req_%016x%s' % (key, ext)) + + +def read_parts(src, kind, key): + parts = {} + for ext in PARTS[kind]: + path = request_name(src, key, ext) + if ext in OPTIONAL and not os.path.isfile(path): + continue + with open(path, 'rb') as file: + parts[ext] = file.read() + return parts + + +def current_key(job): + """(kind, old key, new key, None) or (kind, old key, None, reason).""" + src, kind, key = job + try: + p = read_parts(src, kind, key) + except OSError as error: + return kind, key, None, 'unreadable %s: %s' % (os.path.basename(error.filename or ''), error.strerror) + if kind == 'g': + return kind, key, g.pipeline_key(p['.a'], p['.b'], p['.root'], p.get('.ia', b'')), None + return kind, key, g.compute_key(p['.c67'], p['.data'], p['.root'], p['.desc'], p['.sa'], p['.sb']), None + + +def rtv_request(src, key, new_base): + """The re-keyed text of an RTV variant "rtv1 ...", or raise Incomplete.""" + try: + with open(request_name(src, key, '.rtv'), 'rb') as file: + text = file.read().decode('ascii') + except (OSError, UnicodeError) as error: + raise Incomplete('unreadable .rtv: %s' % error) from error + fields = text.split(' ') + # Looser than the RTV pattern in gfx2hlsl.py (no limit on formats or digits); --pending refuses such a variant. + if len(fields) < 3 or fields[0] != 'rtv1' or not all(f.isdigit() for f in fields[1:]): + raise Incomplete('malformed .rtv') + if g.fnv(text.encode('ascii')) != key: + raise Incomplete('.rtv text does not hash to its name') + base = new_base.get(int(fields[1])) + if base is None: + raise Incomplete('.rtv base request %016x is not a complete graphics request' % int(fields[1])) + return ' '.join(['rtv1', str(base)] + fields[2:]) + + +def publish(path, data, stats): + if os.path.exists(path): + stats['kept'] += 1 + return + tmp = path + '.tmp' + try: + with open(tmp, 'wb') as file: + file.write(data) + os.replace(tmp, path) + except BaseException: + if os.path.exists(tmp): + os.remove(tmp) + raise + stats['written'] += 1 + + +def rekey(src, dst, jobs=None, out=sys.stdout): + """Re-key the requests of src into dst; return the exit code.""" + if not os.path.isdir(src): + print('error: %s is not a directory' % src, file=sys.stderr) + return 2 + if os.path.exists(dst) and os.path.samefile(src, dst): + print('error: the new request dir must not be the old cache', file=sys.stderr) + return 2 + found = {'g': [], 'c': [], 'rtv': [], 'm57': 0, 'm86': 0} + for name in sorted(os.listdir(src)): + m = REQUEST.fullmatch(name) + if not m: + continue + key, ext = int(m.group(1), 16), m.group(2) + if ext in ('m57', 'm86'): + found[ext] += 1 + else: + found[{'a': 'g', 'c67': 'c', 'rtv': 'rtv'}[ext]].append(key) + + work = [(src, kind, key) for kind in ('g', 'c') for key in found[kind]] + jobs = min(jobs or g.translation_jobs(), len(work)) + if jobs < 2: + results = [current_key(job) for job in work] + else: + from concurrent.futures import ProcessPoolExecutor + with ProcessPoolExecutor(max_workers=jobs) as pool: + results = list(pool.map(current_key, work, chunksize=max(1, len(work) // (jobs * 4)))) + + new = {'g': {}, 'c': {}} + bad = [] + for kind, old, key, reason in results: + if reason: + bad.append('req_%016x: %s' % (old, reason)) + else: + new[kind][old] = key + rtv = {} + for old in found['rtv']: + try: + text = rtv_request(src, old, new['g']) + except Incomplete as reason: + bad.append('req_%016x.rtv: %s' % (old, reason)) + continue + rtv[g.fnv(text.encode('ascii'))] = text + if bad: + print('error: %d of %d requests are incomplete or unreadable; nothing written' % ( + len(bad), len(work) + len(found['rtv'])), file=sys.stderr) + for line in bad[:10]: + print(' ' + line, file=sys.stderr) + return 1 + + os.makedirs(dst, exist_ok=True) + stats = {'written': 0, 'kept': 0} + for kind, label in (('g', 'graphics'), ('c', 'compute')): + done = set() + for old, key in sorted(new[kind].items()): + if key in done: # requests of the same pipeline from several revisions + continue + done.add(key) + # Read again, not checked against the hashing pass: nothing may write the old cache meanwhile. + for ext, data in read_parts(src, kind, old).items(): + publish(request_name(dst, key, ext), data, stats) + current = sum(old == key for old, key in new[kind].items()) + print('%s: %d requests, %d already current -> %d keys' % (label, len(new[kind]), current, len(done)), file=out) + for key, text in sorted(rtv.items()): + publish(request_name(dst, key, '.rtv'), text.encode('ascii'), stats) + print('rtv variants: %d requests -> %d keys' % (len(found['rtv']), len(rtv)), file=out) + print('not re-keyed (own key strings): m57 %d, m86 %d' % (found['m57'], found['m86']), file=out) + print('files: %d written, %d already present in %s' % (stats['written'], stats['kept'], dst), file=out) + return 0 + + +def main(argv): + if len(argv) != 2 or argv[0].startswith('-'): + print(__doc__.split('\n\n')[1], file=sys.stderr) + return 2 + return rekey(argv[0], argv[1]) + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) From 6b9fb9d949155564dee9345fb329d789aa82ca33 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:17:18 +0530 Subject: [PATCH 121/232] startup: release retired slot-133 title-memory textures and track slot-18 SRV reuse (slice 2) (#2468) * startup: release retired slot-133 title-memory textures and track slot-18 SRV reuse (slice 2) * startup: guard the retire-class upload gate, hold lock and view recording (review follow-up) * tests: cover the retire-class upload gate, newer written generations and retire bookkeeping * docs: record the retire upload gate, view recording and hold fallback (review follow-up) * tests: cover the translated draw hold and SRV token resolution in the retire fixture (B1) startup_resource_retire_title had no draw path, so draw_translated's retire_hold and the slot-133 view-token resolution were untested. Case 7 samples a slot 133 title-memory texture through a descriptor table with a host-built translated pipeline and asserts the exact readback (including a clear sentinel row and column). The closed recording must keep the released texture retained until it is dropped, which is the hold; a skipped token resolve binds no view and fails the readback. * runtime: preserve write metadata for same-address live SRVs --------- Co-authored-by: triggered02 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 16 + docs/experiments.md | 16 + docs/startup-runtime.md | 80 +- src/startup_stubs/d3d12_capture.inl | 44 +- src/startup_stubs/d3d12_draw.inl | 5 +- src/startup_stubs/d3d12_xs_device.cpp | 234 ++++- src/startup_stubs/list_copy.inl | 16 +- src/startup_stubs/list_copy_texture.inl | 16 +- tests/startup_resource_retire.cpp | 5 +- tests/startup_resource_retire_title.cpp | 1082 +++++++++++++++++++++++ 10 files changed, 1453 insertions(+), 61 deletions(-) create mode 100644 tests/startup_resource_retire_title.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b7bdc1407..c990663d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1346,6 +1346,22 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") endforeach() +add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) +target_include_directories(startup_resource_retire_title PRIVATE src) +target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire_title PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(retire_title_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_RESOURCE_INDEX_CHECK=1;X2W_D3D12_DEBUG=${debug}") + add_test(NAME startup_resource_retire_title_${backend}_debug${debug} COMMAND startup_resource_retire_title ${backend}) + set_tests_properties(startup_resource_retire_title_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_title_env};X2W_D3D12_RELEASE_RETIRED=1") + endforeach() + add_test(NAME startup_resource_retire_title_off_${backend} COMMAND startup_resource_retire_title ${backend} off) + set_tests_properties(startup_resource_retire_title_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_RESOURCE_INDEX_CHECK=1;X2W_D3D12_DEBUG=0") +endforeach() + # GPU writes the dispatch record that the desktop command processor consumes (Refs #1412). add_executable(startup_compute_binding_trace tests/startup_compute_binding_trace.cpp) target_compile_features(startup_compute_binding_trace PRIVATE cxx_std_20) diff --git a/docs/experiments.md b/docs/experiments.md index 3adb253f1..40f37230f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15046,6 +15046,7 @@ check and requires the old exception to come back: The checks are `tests/startup_gfx2hlsl_handler_arity_check.py`, `…_image_arity_check.py`, `…_operand_count_check.py` and `…_scalar_arity_check.py`. They run on Linux and Windows without D3D12 or game data, because a refusal is observable at the `Stage` entry point. + ## Startup translator: v_sad_u8, v_sad_u16 and v_sad_u32 [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) now lowers the gfx1013 VOP3A unsigned sum-of-absolute-differences instructions `v_sad_u8` (`0x15a`), `v_sad_u16` (`0x15c`) and `v_sad_u32` (`0x15d`) in `VEC_U` to three on-demand preamble helpers emitted in `Pipeline.common()` only when referenced by a stage (`sad_u8`, `sad_u16`, `sad_u32`): @@ -15060,3 +15061,18 @@ data, because a refusal is observable at the `Stage` entry point. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V ``` + +## Opt-in release of retired slot-133 title-memory textures (Slice 2) + +Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop object retirement to device slot 133 (`CreatePlacedResourceX`) committed 2D textures with `title_memory` (non-RT/DS/UAV, 1-sample, `DEFAULT` heap), while keeping slot 127 `__XMemAllocationHooks__` resources out of the class: + +- `drain_retired_resources()` erases the retired wrapper from `resource_address_index()` (under `note_lock`), erases its desktop pointer from `texture_uploads()` (under `draw_lock`), and cleans stale `written_textures()` entries whose generation was not bumped by a newer allocation/write at the same title address (also cleared immediately on final `Release` when no view or live sibling shares the address). +- `list_copy_texture.inl` calls `upload_texture()` for a subresource copy only when the resource is not in the retire class or has title memory (`!retire_when_idle || title_memory`), so with the switch off every resource uploads exactly as before; `texture_uploads()` accesses in `list_copy.inl` / `list_copy_texture.inl` are guarded with `draw_lock`. +- `view_slot` records a view only when the desktop created it: desktop view creation returns `void`, so a removed device is the only failure it reports, and a failed slot is recorded unmaterialized (releasing its previous view reference and adding none). `retire_hold` reads the wrapper's desktop pointer under the retire lock and marks a use it cannot record, which makes the drain keep that desktop object for the process instead of dropping one a list still names. +- `view_slot<18>` (SRV) tracks descriptor slots via `HeapInfo::shadow` across `note_view`, `note_copy`, and heap destruction (falling back to `retire_leave_class` for untracked slots or slots 19–21), and `draw_translated` holds bound textures with `retire_hold`. + +[`tests/startup_resource_retire_title.cpp`](../tests/startup_resource_retire_title.cpp) (`startup_resource_retire_title_{warp,hardware}_debug0` and `_off_`) verifies slot 133 copy/upload holds and readbacks, same-address slot 70 (`existing_memory_texture`) reuse under `X2W_RESOURCE_INDEX_CHECK=1`, stale `bc7_width` `written_textures` cleanup on RGBA8 reuse, `CopyDescriptorsSimple` / overwrite / heap-release SRV retirement, the switch-off control that an ordinary committed texture (no title memory) copy still records its upload, and that a newer `written_textures` generation survives the older generation's retirement across WARP (`Microsoft Basic Render Driver`) and `NVIDIA GeForce GTX 1660 SUPER`. Case 7 closes the fixture's draw-path gap (review finding B1): a host-built translated pixel shader samples a slot 133 title-memory texture through a descriptor table, its view token must resolve to that texture (a skipped resolve binds a null view and the readback reports `pixel (0,0) got 00000000`), and `retire_hold` in the draw keeps the released texture retained while the closed recording names it (removed, the budget reports `retained=0/0 expected=65536/1` before the recording is dropped); the readback holds the exact sampled words plus a clear sentinel row and column throughout, including after the texture leaves the budget. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V +``` diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ec92ff4b8..fe910c39b 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1395,33 +1395,54 @@ those lifetimes intact. `unmeasured` counts tracking failures. DXGI usage can also include allocations outside these categories, such as swap chain and descriptor heap backing. -`X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for one class: a -texture created by device slot 27 or 127 that is two-dimensional, has one -sample, no render-target, depth-stencil or unordered-access flag, lives in a -default heap without heap flags and has no title memory. If the title exports -`__XMemAllocationHooks__`, every slot 127 resource gets title memory and none is in the class; the fixture runs -without that export. Every other resource -keeps the lifetime described above. A resource leaves the class for good when a -view is created for it (slots 18 to 21, also a refused one), when it is passed -to MakeResident or Evict (slots 34 and 35), or when it is presented. Only -wrappers can be in the class; a raw desktop pointer never is. Sampler feedback -is not checked: no device slot of the stand-in reaches it. +`X2W_D3D12_RELEASE_RETIRED=1` ends the retained lifetime for committed +2D textures that have one sample, no render-target, depth-stencil or +unordered-access flag, and live in a default heap without heap flags: +- **Slice 1**: slot 27 and slot 127 textures without title memory (if the title + exports `__XMemAllocationHooks__`, every slot 127 resource gets title memory + and stays out of the class). +- **Slice 2**: slot 133 (`CreatePlacedResourceX`) committed 2D textures with + title memory. Before their desktop `ID3D12Resource` is destroyed, they are + erased from `resource_address_index` and `texture_uploads`, and stale + `written_textures` entries whose generation has not changed are cleared so + reusing the same title address or desktop pointer does not skip uploads or + resolve a retired wrapper. + +Every other resource (buffers, placed buffers, reserved resources, render/depth/UAV +targets, and slot 127 `__XMemAllocationHooks__` textures) keeps the lifetime +described above. A resource leaves the class for good when a UAV/RTV/DSV view is +created for it (slots 19 to 21, also a refused one), when a slot 18 SRV targets +an untracked descriptor slot or is copied out of tracked heaps, when it is passed +to MakeResident or Evict (slots 34 and 35), or when it is presented. A slot 18 +SRV keeps the resource only when the desktop created the view: desktop view +creation returns `void`, so a removed device is the only failure it reports, and +a slot whose creation failed is recorded without a reference. Tracked +slot 18 SRVs (including slot 70 `device_memory_srv`) keep the resource retained +while any descriptor slot in `HeapInfo::shadow` names it (updated across +`note_view`, `CopyDescriptors*`, and heap `Release`), and translated draws hold +bound textures via `retire_hold`. Only wrappers can be in the class; a raw +desktop pointer never is. Sampler feedback is not checked: no device slot of the +stand-in reaches it. The final guest release signals a private desktop fence on every queue the stand-in created. The desktop object is released when all of those fences have -passed and nothing else names it. A copy (list slot 17), texture copy (16) or -resolve destination (19) that the stand-in forwards makes the list hold a -desktop reference to each resource of the class it names, source and -destination, until the list is Reset, fails to Close or is destroyed. A list +passed, all tracked slot 18 SRV descriptor refs have dropped to zero, and no +recorded list or submission still holds it. A copy (list slot 17), texture copy (16), +resolve destination (19), or translated draw SRV bind that the stand-in forwards +makes the list hold a desktop reference to each resource of the class it names, +source and destination, until the list is Reset, fails to Close or is destroyed. A list that is closed and never submitted is thus discarded without any submission. Each submission holds the same references until its queue passes a fence signalled behind it. A release with no registered queue, and a hold, marker or -submission fence that cannot be recorded, keep the resource retained. Nothing -waits: `ExecuteCommandLists` and `Present` check and release without blocking. +submission fence that cannot be recorded, keep the resource retained. A use that +`retire_hold` cannot record (no desktop object left, or no room for the entry) +leaves the class and marks the resource so the drain keeps its desktop object for +the process, as an unfenced submission is kept, instead of dropping an object a +list still names. Nothing waits: `ExecuteCommandLists` and `Present` check and +release without blocking. The wrapper stays allocated, and a guest that uses a resource after its final -release is not supported with the switch. Buffers, placed and reserved -resources, slot 133 and all resources with title memory are not in the class. -Slot 18 (`CopyTiles`) is not forwarded at all and is outside this change. +release is not supported with the switch. Slot 18 (`CopyTiles`) is not +forwarded at all and is outside this change. The source-built fixture reads the process-wide counters through `x2w_d3d12_budget_snapshot` and checks allocation sizes, final guest release, @@ -1437,10 +1458,21 @@ its own fence, a destination released after recording (slots 17, 16 and 19), a list destroyed while its submission is held, a copy queue, an open list that D3D12 refuses to Reset and one that is destroyed, a release that no list refers to behind a held queue, and, in one run with the class, a buffer, -render target, title-memory texture, viewed texture, resident texture and -presented texture that must stay retained. The fixture-only export -`x2w_d3d12_retire_probe` returns FALSE without the switch, like -`x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` +render target, viewed texture (while its slot-18 SRV stays live), resident texture and +presented texture that must stay retained, alongside slot 133 title-memory textures. +`startup_resource_retire_title_{warp,hardware}_debug{0,1}` additionally test slot 133 +`CopyTextureRegion`/`CopyResource` upload holds, same-address slot 70 (`existing_memory_texture`) +reuse with `X2W_RESOURCE_INDEX_CHECK=1`, stale `written_textures` `bc7_width` cleanup, +slot-18 SRV `CopyDescriptorsSimple` / overwrite / heap-release lifetime, and, with the +switch on, a newer `written_textures` generation kept when the older generation retires +and a translated draw that samples such a texture through a descriptor table (the view +token's resolution and the draw's `retire_hold`: the readback holds the sampled texels and +a clear sentinel corner, and the texture leaves the budget only after the closed draw +recording is dropped); the `_off_` case checks that an ordinary committed texture (no +title memory) still records its upload. The fixture-only exports `x2w_d3d12_retire_probe`, +`x2w_d3d12_resource_index_probe`, `x2w_d3d12_texture_upload_probe` and +`x2w_d3d12_written_probe` read the bookkeeping the shim keeps; the retire probe returns +FALSE without the switch, like `x2w_d3d12_budget_snapshot`. `startup_resource_retire_off_*` runs the same steps without the switch. The hardware cases report 77 without a physical adapter, and the debug-layer cases report 77 where the debug layer is not installed. diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 6b40d70a2..879f71f8e 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -311,7 +311,17 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ view_ids()[hash] = record.id; ++views_distinct; } - if (std::uint32_t* slot = shadow_slot(dest_desktop)) *slot = record.id + 1; + if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { + const std::uint32_t prev = *slot_ptr; + *slot_ptr = record.id + 1; + if (prev != record.id + 1) { + if (slot == 18 && resource && materialized) retire_add_view_ref(reinterpret_cast(resource)); + if (prev && prev - 1 < view_records().size() && view_records()[prev - 1].slot == 18 && view_materialized()[prev - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[prev - 1].resource)); + } + } else if (slot == 18 && resource) { + retire_leave_class(reinterpret_cast(resource)); + } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; if (dest_title != dest_desktop && title_backed(dest_title, token_bytes) && @@ -329,8 +339,36 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, std::uint32_t* to = shadow_slot(dest_desktop, &dest_room); const std::uint32_t* from = shadow_slot(src_desktop, &src_room); if (to && count <= dest_room) { - if (from && count <= src_room) std::memmove(to, from, u64{count} * 4); - else std::memset(to, 0, u64{count} * 4); + if (from && count <= src_room) { + for (UINT i = 0; i < count; ++i) { + const std::uint32_t src_id = from[i]; + if (src_id && src_id - 1 < view_records().size() && + view_records()[src_id - 1].slot == 18 && view_materialized()[src_id - 1]) + retire_add_view_ref(reinterpret_cast(view_records()[src_id - 1].resource)); + } + for (UINT i = 0; i < count; ++i) { + const std::uint32_t old_id = to[i]; + if (old_id && old_id - 1 < view_records().size() && + view_records()[old_id - 1].slot == 18 && view_materialized()[old_id - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[old_id - 1].resource)); + } + std::memmove(to, from, u64{count} * 4); + } else { + for (UINT i = 0; i < count; ++i) { + const std::uint32_t old_id = to[i]; + if (old_id && old_id - 1 < view_records().size() && + view_records()[old_id - 1].slot == 18 && view_materialized()[old_id - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[old_id - 1].resource)); + } + std::memset(to, 0, u64{count} * 4); + } + } else if (from && count <= src_room) { + for (UINT i = 0; i < count; ++i) { + const std::uint32_t src_id = from[i]; + if (src_id && src_id - 1 < view_records().size() && + view_records()[src_id - 1].slot == 18 && view_materialized()[src_id - 1]) + retire_leave_class(reinterpret_cast(view_records()[src_id - 1].resource)); + } } ReleaseSRWLockExclusive(¬e_lock); const UINT stride = title_descriptor_stride(dest_title, increment); diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 94b639dae..0c18dcf3d 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2034,7 +2034,10 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } if (texture && !upload_texture(self, resource, texture)) texture = nullptr; - if (texture) require_state(self, texture, sampled_state(self, texture)); + if (texture) { + require_state(self, texture, sampled_state(self, texture)); + if (resource && !resource->own().tiled_address_srv) retire_hold(self, resource); + } const bool had_texture = texture != nullptr; bool mismatched = false; static LONG shown; diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index ce6698bb9..932983b5f 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -156,6 +156,11 @@ struct alignas(16) WrapperOwn { bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. bool retire_when_idle; // Resource: in the retire class (X2W_D3D12_RELEASE_RETIRED); cleared by any other use. Plain // accesses: a race needs the guest to use a resource across its own final Release. + bool retire_hold_missed; // Resource: retire_hold could not record a use (no desktop object or no room), so the + // drain must keep it for the process instead of dropping a list's desktop object. + volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. + bool retire_has_written_gen; // Whether written_textures()[title_memory].generation was snapshotted at Release. + u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup. bool list_ready; // CommandList (render mode): closed with recorded work, not yet submitted bool compute_pipeline; // PipelineState: a desktop compute pipeline u64 compute_trace_key; // Opt-in trace: selected slot 62 container hash @@ -788,15 +793,18 @@ bool release_retired_enabled() // The retire class of X2W_D3D12_RELEASE_RETIRED, decided once at creation from the desktop description: a committed // 2D texture with one sample, no render-target, depth-stencil or unordered-access use, in a default heap with no heap -// flags, that has no title memory (with the title's __XMemAllocationHooks__ export every slot 127 resource gets title -// memory, so none is in the class then). Every use reaches the shim through handlers that retire_hold covers or that -// clear the flag; see docs/startup-runtime.md#d3d12-resource-budget. +// flags. Slot 27 and non-hooked slot 127 have no title memory; slot 133 committed 2D textures with title memory are +// included (cleaned from resource_address_index, texture_uploads and written_textures on retirement), while slot 127 +// resources with __XMemAllocationHooks__ title memory remain excluded. Every use reaches the shim through handlers +// that retire_hold or shadow-slot SRV ref-counting cover, or that clear the flag; see +// docs/startup-runtime.md#d3d12-resource-budget. bool retire_class(const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, - const void* title_memory) + const void* title_memory, bool allow_title_memory = false) { return release_retired_enabled() && props.Type == D3D12_HEAP_TYPE_DEFAULT && heap_flags == D3D12_HEAP_FLAG_NONE && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && - (desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == D3D12_RESOURCE_FLAG_NONE && !title_memory; + (desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == D3D12_RESOURCE_FLAG_NONE && + (!title_memory || allow_title_memory); } template @@ -923,6 +931,10 @@ void retire_placement(Wrapper* w); void register_retire_queue(Wrapper* queue); void retire_resource(Wrapper* w); void retire_leave_class(const void* object); +void retire_add_view_ref(const void* object); +void retire_release_view_ref(const void* object); +void retire_drop_heap_views(Wrapper* heap); +void retire_note_title_release(Wrapper* w); void retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); void retire_discard_holds(Wrapper* list); @@ -936,9 +948,11 @@ ULONG __stdcall release(Wrapper* self) if (!refs) { if (self->own().budget) self->own().budget->end_use(); if (self->own().backing_budget) self->own().backing_budget->end_use(); + if (self->own().kind == descriptor_heap_kind) retire_drop_heap_views(self); if (self->own().kind == resource_kind && self->own().title_memory) { drop_mesh_lease_owner(self); retire_placement(self); + if (self->own().retire_when_idle) retire_note_title_release(self); } if (self->own().kind == list_kind && self->own().real) { discard_mesh_lease_recording(static_cast(self->own().real)); @@ -3869,13 +3883,17 @@ template __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) { Timed timed(time_view); - // A view keeps the resource's old lifetime, whether or not the view is created (X2W_D3D12_RELEASE_RETIRED). - if constexpr (N >= 18 && N <= 21) retire_leave_class(reinterpret_cast(a)); + // UAV, RTV and DSV views keep the resource's old lifetime; slot-18 SRVs stay in the retire class as long as + // their descriptor slots are tracked by shadow_slot and translated draws hold bound resources with retire_hold. + if constexpr (N >= 19 && N <= 21) retire_leave_class(reinterpret_cast(a)); if constexpr (N == 19) retire_leave_class(reinterpret_cast(b)); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); - if (!args[D]) return 0; + if (!args[D]) { + if constexpr (N == 18) retire_leave_class(reinterpret_cast(a)); + return 0; + } const auto record_view = [&](bool materialized) { const u64 raw[4] = {a, b, c, d}; const int described = N == 19 ? 2 : (N == 17 || N == 22) ? 0 : 1; @@ -3944,8 +3962,20 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) args[1] = reinterpret_cast(&null_rtv); } const u64 result = method_of(self->own().real, N)(self->own().real, args[0], args[1], args[2], args[3], 0, 0, 0, 0); - record_view(true); - if ((N == 20 || N == 21) && args[0]) note_view_target(args[D], reinterpret_cast(args[0]), N); + // A desktop view creation returns void, so the only failure it reports is a removed device. Only a created view + // may keep the resource: on failure the slot is recorded unmaterialized, which releases the slot's previous view + // reference and adds none. + const HRESULT removed = removal_device ? removal_device->GetDeviceRemovedReason() : S_OK; + const bool created = SUCCEEDED(removed); + record_view(created); + if (!created) { + static LONG failed; + if (first_calls(failed, 6)) + log("x2w-d3d12 Device::slot%d view not created: device removed, reason 0x%08lx", N, + static_cast(removed)); + } + if ((N == 20 || N == 21) && args[0] && created) + note_view_target(args[D], reinterpret_cast(args[0]), N); check_device("Device view", N); static LONG calls; if (first_calls(calls)) @@ -4200,6 +4230,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; note_resource(w, desc, 0); + w->own().retire_when_idle = retire_class(props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); *out = w; return S_OK; } @@ -4361,16 +4392,86 @@ void retire_leave_class(const void* object) if (Wrapper* w = as_wrapper(object)) w->own().retire_when_idle = false; } +void retire_add_view_ref(const void* object) +{ + if (!release_retired_enabled()) return; + if (Wrapper* w = as_wrapper(object); w && w->own().kind == resource_kind) + InterlockedIncrement(&w->own().retire_view_refs); +} + +void retire_release_view_ref(const void* object) +{ + if (!release_retired_enabled()) return; + if (Wrapper* w = as_wrapper(object); w && w->own().kind == resource_kind) + InterlockedDecrement(&w->own().retire_view_refs); +} + +void retire_drop_heap_views(Wrapper* heap) +{ + if (!release_retired_enabled() || !heap) return; + AcquireSRWLockExclusive(¬e_lock); + for (HeapInfo& h : heap_infos()) { + if (h.wrapper != reinterpret_cast(heap) || !h.shadow) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t id = h.shadow[i]; + if (!id) continue; + h.shadow[i] = 0; + if (id - 1 < view_records().size() && view_records()[id - 1].slot == 18 && view_materialized()[id - 1]) + retire_release_view_ref(reinterpret_cast(view_records()[id - 1].resource)); + } + } + ReleaseSRWLockExclusive(¬e_lock); +} + +bool retire_address_has_live_user(u64 address, const Wrapper* skip) +{ + bool other_live = false; + AcquireSRWLockShared(¬e_lock); + resource_address_index().for_each_reaching(address, 1, [&](const Wrapper* wrapper) { + if (wrapper == skip || reinterpret_cast(wrapper->own().title_memory) != address) return false; + if (InterlockedCompareExchange(const_cast(&wrapper->own().refs), 0, 0) > 0 || + InterlockedCompareExchange(const_cast(&wrapper->own().retire_view_refs), 0, 0) > 0) { + other_live = true; + return true; + } + return false; + }); + ReleaseSRWLockShared(¬e_lock); + if (other_live) return true; + std::lock_guard lock(tiled_srv_mutex); + return tiled_srv_addresses.count(address) != 0; +} + +void retire_note_title_release(Wrapper* w) +{ + const u64 address = reinterpret_cast(w->own().title_memory); + if (!address) return; + const bool shared_addr = retire_address_has_live_user(address, w); + const bool no_views = InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) == 0; + AcquireSRWLockExclusive(&written_lock); + if (const auto found = written_textures().find(address); found != written_textures().end()) { + if (!shared_addr && no_views) { + written_textures().erase(found); + } else { + w->own().retire_has_written_gen = true; + w->own().retire_written_gen = found->second.generation; + } + } + ReleaseSRWLockExclusive(&written_lock); +} + // After a copy, texture copy or resolve was forwarded to the desktop list: the list keeps a desktop reference to the // resource until its recording is dropped. Only wrappers are members of the class, so a raw desktop pointer is never // held. Assumption, not proven: the guest has no raw pointer to the desktop object of a class member. void retire_hold(Wrapper* list, Wrapper* resource) { if (!resource || !resource->own().retire_when_idle) return; - auto* real = static_cast(resource->own().real); bool held = false; + AcquireSRWLockExclusive(&retire_lock); + // own().real is cleared by drain_retired_resources under this lock, so the read and the AddRef happen under it + // (retire_lock is a leaf: nothing else is taken inside). + auto* real = static_cast(resource->own().real); if (real) { - AcquireSRWLockExclusive(&retire_lock); try { auto& held_by_list = retire_list_holds[list]; if (std::find(held_by_list.begin(), held_by_list.end(), real) != held_by_list.end()) { @@ -4384,10 +4485,14 @@ void retire_hold(Wrapper* list, Wrapper* resource) } } catch (const std::bad_alloc&) { } - ReleaseSRWLockExclusive(&retire_lock); } - // The guest still references the resource in this call, so it cannot be retired yet: leave the class instead. - if (!held) resource->own().retire_when_idle = false; + if (!held) { + // The use cannot be recorded: leave the class, and mark it so the drain keeps the desktop object for the + // process (as it keeps a submission it could not fence) rather than dropping one a list still names. + resource->own().retire_when_idle = false; + resource->own().retire_hold_missed = true; + } + ReleaseSRWLockExclusive(&retire_lock); } void retire_discard_holds(Wrapper* list) @@ -4490,15 +4595,35 @@ void drain_retired_resources() { if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; constexpr std::size_t batch = 256; - std::vector dropped; + struct RetiredDrop { + Wrapper* wrapper; + ID3D12Resource* resource; + }; + std::vector dropped; + std::vector> dropped_flights; try { dropped.reserve(batch); + dropped_flights.reserve(batch); } catch (const std::bad_alloc&) { return; } if (!TryAcquireSRWLockExclusive(&retire_lock)) return; for (std::size_t i = 0; i < retired_resources.size() && dropped.size() < batch;) { RetiredResource& item = retired_resources[i]; + Wrapper* w = item.wrapper; + if (w->own().retire_hold_missed) { + // retire_hold could not record a list's use of this resource: keep its desktop object for the process, + // like a submission that could not be fenced, and drop only the retire bookkeeping. + InterlockedIncrement64(&retire_kept); + if (i + 1 != retired_resources.size()) item = std::move(retired_resources.back()); + retired_resources.pop_back(); + InterlockedDecrement(&retire_pending); + continue; + } + if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + ++i; + continue; + } bool reached = item.targets.size() <= retire_queues.size(); for (std::size_t q = 0; q < item.targets.size() && reached; ++q) reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; @@ -4506,10 +4631,9 @@ void drain_retired_resources() ++i; continue; } - Wrapper* w = item.wrapper; // Claim the reference count so that a late AddRef cannot bring the wrapper back while its object goes. if (InterlockedCompareExchange(&w->own().refs, retired_refs, 0) == 0) { - dropped.push_back(static_cast(w->own().real)); + dropped.push_back({w, static_cast(w->own().real)}); w->own().real = nullptr; } else { InterlockedIncrement64(&retire_kept); // referenced again after its final Release @@ -4518,24 +4642,47 @@ void drain_retired_resources() retired_resources.pop_back(); InterlockedDecrement(&retire_pending); } - for (std::size_t i = 0; i < retire_flights.size() && dropped.size() < batch;) { + for (std::size_t i = 0; i < retire_flights.size() && dropped_flights.size() < batch;) { RetireFlight& flight = retire_flights[i]; if (retire_queues[flight.queue].fence->GetCompletedValue() < flight.value) { ++i; continue; } - // A flight holds at most a list's resources; it may overshoot the batch by that much. - dropped.insert(dropped.end(), flight.resources.begin(), flight.resources.end()); + dropped_flights.push_back(std::move(flight.resources)); if (i + 1 != retire_flights.size()) flight = std::move(retire_flights.back()); retire_flights.pop_back(); InterlockedDecrement(&retire_pending); } ReleaseSRWLockExclusive(&retire_lock); - for (ID3D12Resource* resource : dropped) { - resource->Release(); + for (const RetiredDrop& drop : dropped) { + if (drop.wrapper->own().title_memory) { + const u64 address = reinterpret_cast(drop.wrapper->own().title_memory); + { + x2w_startup::ExclusiveNoteLock guard(note_lock); + resource_address_index().erase(address, drop.wrapper); + } + if (drop.wrapper->own().retire_has_written_gen && !retire_address_has_live_user(address, drop.wrapper)) { + AcquireSRWLockExclusive(&written_lock); + if (const auto found = written_textures().find(address); + found != written_textures().end() && found->second.generation == drop.wrapper->own().retire_written_gen) + written_textures().erase(found); + ReleaseSRWLockExclusive(&written_lock); + } + } + AcquireSRWLockExclusive(&draw_lock); + texture_uploads().erase(drop.resource); + ReleaseSRWLockExclusive(&draw_lock); + drop.resource->Release(); const LONG64 total = InterlockedIncrement64(&retire_freed); if (total <= 8 || total % 1000 == 0) log("x2w-d3d12 retire: %lld desktop references dropped", total); } + for (const auto& resources : dropped_flights) { + for (ID3D12Resource* resource : resources) { + resource->Release(); + const LONG64 total = InterlockedIncrement64(&retire_freed); + if (total <= 8 || total % 1000 == 0) log("x2w-d3d12 retire: %lld desktop references dropped", total); + } + } } // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many @@ -4573,6 +4720,47 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } +// Fixture probes (startup_resource_retire_title) for state the retire bookkeeping maintains for one resource. They read +// the same maps the shim reads and never change them; the address index and the upload cache exist with and without +// the switch, so these answer in both modes. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_resource_index_probe(void* resource) +{ + Wrapper* w = as_wrapper(resource); + if (!w || w->own().kind != resource_kind) return FALSE; + const u64 base = reinterpret_cast(w->own().title_memory); + if (!base) return FALSE; + AcquireSRWLockShared(¬e_lock); + const bool indexed = resource_address_index().contains(base, static_cast(w)); + ReleaseSRWLockShared(¬e_lock); + return indexed ? TRUE : FALSE; +} + +// The desktop pointer is not dereferenced: the fixture keeps its own desktop reference to a retired resource. +extern "C" __declspec(dllexport) BOOL x2w_d3d12_texture_upload_probe(void* desktop_resource) +{ + if (!desktop_resource) return FALSE; + AcquireSRWLockExclusive(&draw_lock); + const bool cached = texture_uploads().count(static_cast(desktop_resource)) != 0; + ReleaseSRWLockExclusive(&draw_lock); + return cached ? TRUE : FALSE; +} + +extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, unsigned long long* generation, unsigned* bc7_width, + unsigned* desktop_rows) +{ + if (!address) return FALSE; + AcquireSRWLockShared(&written_lock); + const auto found = written_textures().find(reinterpret_cast(address)); + const bool present = found != written_textures().end(); + if (present) { + if (generation) *generation = found->second.generation; + if (bc7_width) *bc7_width = found->second.bc7_width; + if (desktop_rows) *desktop_rows = found->second.desktop_rows ? 1u : 0u; + } + ReleaseSRWLockShared(&written_lock); + return present ? TRUE : FALSE; +} + // The title exports __XMemAllocationHooks__ = {alloc(size, attributes), free(ptr, attributes), ...}. // Its alloc routine selects a hook chain by allocatorId (attribute bits 16-23). Around the creation // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index ff2441bf2..5ed62c724 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -83,12 +83,18 @@ bool sync_title_source(Wrapper* self, const CopyEndpoint& source) if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { // A target or UAV holds what the GPU wrote; its title memory is never uploaded. if (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return true; - const auto written = texture_uploads().find(source.resource); if (list_wrote(self, source.resource)) return true; - if (written != texture_uploads().end() && written->second.gpu_written) return true; - if (!upload_texture(self, source.wrapper, source.resource)) return false; - const auto found = texture_uploads().find(source.resource); - return found != texture_uploads().end() && found->second.staged; + AcquireSRWLockExclusive(&draw_lock); + const auto written = texture_uploads().find(source.resource); + bool ok = false; + if (written != texture_uploads().end() && written->second.gpu_written) { + ok = true; + } else if (upload_texture(self, source.wrapper, source.resource)) { + const auto found = texture_uploads().find(source.resource); + ok = found != texture_uploads().end() && found->second.staged; + } + ReleaseSRWLockExclusive(&draw_lock); + return ok; } const auto* info = resource_info(source.wrapper); return info && info->placement == Placement::aliased_buffer; diff --git a/src/startup_stubs/list_copy_texture.inl b/src/startup_stubs/list_copy_texture.inl index 57ffaaf7c..4f2ca279b 100644 --- a/src/startup_stubs/list_copy_texture.inl +++ b/src/startup_stubs/list_copy_texture.inl @@ -147,11 +147,21 @@ void __stdcall list_copy_texture(Wrapper* self, const D3D12_TEXTURE_COPY_LOCATIO } // Bring a texture's desktop copy up to date with its guest backing before the copy reads or partly overwrites it, // and record that upload so a later sample does not replace the copied texels. - // A resource of the retire class has no title memory, so there is nothing to upload and no cache entry to leave behind. - if (side_src.kind == x2w_list_copy_texture::Kind::subresource && !src_wrapper->own().retire_when_idle) + // A resource of the retire class that has no title memory has nothing to upload and leaves no texture_uploads() + // entry behind; every other resource uploads exactly as it did before the switch (switch off: nothing changes). + const auto needs_upload = [](const Wrapper* wrapper) { + return !wrapper->own().retire_when_idle || wrapper->own().title_memory; + }; + if (side_src.kind == x2w_list_copy_texture::Kind::subresource && needs_upload(src_wrapper)) { + AcquireSRWLockExclusive(&draw_lock); upload_texture(self, src_wrapper, real_src); - if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && !dst_wrapper->own().retire_when_idle) + ReleaseSRWLockExclusive(&draw_lock); + } + if (side_dst.kind == x2w_list_copy_texture::Kind::subresource && needs_upload(dst_wrapper)) { + AcquireSRWLockExclusive(&draw_lock); upload_texture(self, dst_wrapper, real_dst); + ReleaseSRWLockExclusive(&draw_lock); + } if (!src_fixed) require_state(self, real_src, D3D12_RESOURCE_STATE_COPY_SOURCE); if (!dst_fixed) require_state(self, real_dst, D3D12_RESOURCE_STATE_COPY_DEST); D3D12_TEXTURE_COPY_LOCATION to = *dst, from = *src; diff --git a/tests/startup_resource_retire.cpp b/tests/startup_resource_retire.cpp index 3eeb50f6f..2787867a0 100644 --- a/tests/startup_resource_retire.cpp +++ b/tests/startup_resource_retire.cpp @@ -675,7 +675,7 @@ bool classes(Context& c, bool on) struct Control { Res* resource; const char* fail; }; const Control controls[] = { - {&B, "a buffer was freed"}, {&G, "a render target was freed"}, {&T, "a texture with title memory was freed"}, + {&B, "a buffer was freed"}, {&G, "a render target was freed"}, {&V, "a resource with a view was freed"}, {&M, "a resource passed to MakeResident was freed"}, {&P, "the presented surface was freed"}}; for (const Control& control : controls) { @@ -685,8 +685,9 @@ bool classes(Context& c, bool on) } c.release(Z127); c.release(Z27); + c.release(T); if (!c.sync(c.direct) || !c.sync(c.other) || !c.sync(c.gated) || !c.sync(c.copy)) return false; - if (on) Z127.freed = Z27.freed = true; + if (on) Z127.freed = Z27.freed = T.freed = true; if (!c.settle("class released", "a resource of the class kept its desktop object")) return false; VirtualFree(title_memory, 0, MEM_RELEASE); return true; diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp new file mode 100644 index 000000000..756a9015f --- /dev/null +++ b/tests/startup_resource_retire_title.cpp @@ -0,0 +1,1082 @@ +// X2W_D3D12_RELEASE_RETIRED=1 (Slice 2, Refs #2379): slot 133 (CreatePlacedResourceX) committed 2D textures with +// title_memory retire once no recorded list, submission, release-time fence, or tracked slot-18 SRV descriptor slot +// still refers to them, and are cleaned from resource_address_index, texture_uploads and written_textures before +// their desktop ID3D12Resource is destroyed. +// +// startup_resource_retire_title [off] +// +// Cases: +// 1 slot 133 title_memory texture upload/copy (CopyTextureRegion + CopyResource): held behind closed list and +// gated second submission, read back after copy, then retired to baseline. +// 2 resource_address_index + slot 70 (existing_memory_texture) same-address reuse while T1 is pending behind a +// held fence, with X2W_RESOURCE_INDEX_CHECK=1 verifying live index consistency. +// 3 written_textures stale bc7_width cleanup on address reuse (BC7 retired -> RGBA8 at same address uploads +// fresh CPU texels). +// 4 descriptor & view reuse: view_slot<18> + CopyDescriptorsSimple + heap release + descriptor overwrite; +// stays retained while any tracked slot holds the SRV, retires once overwritten/freed and fences complete. +// 5 switch-off control: an ordinary committed texture (no slot 133, no title memory) copied as a subresource still +// records its upload, as before the switch (case runs with the switch off, which is what selects the control). +// 6 written_textures generation keeping: a live view keeps the older generation's entry, and a newer generation of +// the same address survives the older generation's retirement (case runs with the switch on, which is what +// retires resources). +// 7 draw path (review finding B1): a translated pixel shader samples a slot 133 title-memory texture through a +// descriptor table. The readback must hold the sampled texels and a clear sentinel corner, the draw must record +// a retire hold (so removing it fails here), and after the final Release and the descriptor overwrite the +// texture leaves the budget only when the closed draw recording is dropped (case runs with the switch on). +#include "startup_stubs/resource_budget.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +struct RetireProbe { + unsigned cache_entries; + unsigned list_states; + unsigned list_holds; +}; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_retire_probe(void*, void*, RetireProbe*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_resource_index_probe(void*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_texture_upload_probe(void*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_written_probe(void*, unsigned long long*, unsigned*, unsigned*); +extern "C" __declspec(dllimport) void x2w_d3d12_bc7_4k_s_written(void*, UINT, UINT); +extern "C" __declspec(dllimport) void x2w_d3d12_list_copy_texture_stats(LONG*, LONG*); + +namespace { +using namespace x2w_budget; + +constexpr UINT side = 64, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; + +template +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast((*reinterpret_cast(object))[slot])(object, args...); +} + +template +ComPtr desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast(hr)); + return SUCCEEDED(hr); +} + +std::uint8_t pattern_byte(int seed, UINT i) { return static_cast(i * 7 + seed * 13 + 1); } + +ComPtr pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Res { + ComPtr guest; + const char* name = ""; + Category category = texture; + UINT64 bytes = 0; + bool released = false; + bool freed = false; +}; + +struct GuestList { + ComPtr allocator, list; +}; + +struct GuestQueue { + ComPtr queue, done; + ComPtr done_real; + UINT64 value = 0; +}; + +struct MemorySrvInput { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + UINT64 address; +}; +static_assert(offsetof(MemorySrvInput, address) == 0x28); + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ID3D12InfoQueue* debug; + ComPtr own_queue; + ComPtr own_allocator; + ComPtr own_list; + ComPtr own_fence; + UINT64 own_value = 0; + HANDLE event = nullptr; + ComPtr upload, readback; + Snapshot base{}; + std::deque pool; + GuestQueue direct, gated; + GuestList drain_list; + D3D12_RESOURCE_DESC desc{}; + UINT64 texture_bytes = 0; + std::array iid_resource{__uuidof(ID3D12Resource)}; + + bool wait(ID3D12Fence* fence, UINT64 value) + { + if (fence->GetCompletedValue() >= value) return true; + if (FAILED(fence->SetEventOnCompletion(value, event))) return false; + return WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0; + } + bool own_run() + { + if (!require(own_list->Close(), "own list close")) return false; + ID3D12CommandList* lists[] = {own_list.Get()}; + own_queue->ExecuteCommandLists(1, lists); + if (!require(own_queue->Signal(own_fence.Get(), ++own_value), "own signal")) return false; + if (wait(own_fence.Get(), own_value)) return true; + std::puts("FAIL: own queue timed out"); + return false; + } + D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* buffer, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, + UINT width = side) const + { + D3D12_TEXTURE_COPY_LOCATION location{buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + location.PlacedFootprint.Footprint = {fmt, width, side, 1, pitch}; + return location; + } + bool make_queue(GuestQueue& q) + { + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + if (!require(invoke(guest, 8, &qd, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "fence")) + return false; + q.done_real = desktop_object(guest, device, q.done.Get()); + return q.done_real != nullptr; + } + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (wait(q.done_real.Get(), q.value)) return true; + std::puts("FAIL: guest queue timed out"); + return false; + } + bool make_list(GuestList& l) + { + const unsigned list_desc[] = {static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + return require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + l.allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, l.allocator.Get(), nullptr, + &__uuidof(ID3D12GraphicsCommandList), l.list.GetAddressOf()), "command list") && + require(invoke(l.list.Get(), 139, l.allocator.Get(), nullptr), "list reset"); + } + bool close(GuestList& l) { return require(invoke(l.list.Get(), 9), "list close"); } + HRESULT reset_list(GuestList& l) + { + ComPtr next; + if (!require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + next.GetAddressOf()), "allocator")) + return E_FAIL; + const HRESULT hr = invoke(l.list.Get(), 139, next.Get(), nullptr); + if (SUCCEEDED(hr)) l.allocator = next; + return hr; + } + void execute(GuestQueue& q, GuestList& l) + { + IUnknown* lists[] = {l.list.Get()}; + invoke(q.queue.Get(), 10, 1u, lists); + } + Res& make_committed(const char* name, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + d.Flags = flags; + Res& r = pool.emplace_back(); + r.name = name; + r.bytes = texture_bytes; + if (!require(invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid_resource[0], r.guest.GetAddressOf()), name)) + throw 4; + return r; + } + Res& make_slot133(const char* name, void* address, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, UINT width = side) + { + D3D12_RESOURCE_DESC d = desc; + d.Width = width; + d.Format = fmt; + Res& r = pool.emplace_back(); + r.name = name; + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + if (!require(invoke(guest, 133, address, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, &iid_resource[0], + r.guest.GetAddressOf()), name)) + throw 4; + return r; + } + bool fill_desktop(IUnknown* resource, int seed) + { + const auto real = desktop_object(guest, device, resource); + if (!real) return false; + void* mapped = nullptr; + const D3D12_RANGE none{}; + if (!require(upload->Map(0, &none, &mapped), "upload map")) return false; + auto* dst = static_cast(mapped); + for (UINT i = 0; i < image_bytes; ++i) dst[i] = pattern_byte(seed, i); + upload->Unmap(0, nullptr); + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) + return false; + own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COMMON}; + own_list->ResourceBarrier(1, &b); + return own_run(); + } + D3D12_TEXTURE_COPY_LOCATION footprint_tex(ID3D12Resource* tex) const + { + return {tex, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + } + bool holds(IUnknown* resource, int seed, const char* what, DXGI_FORMAT fmt = DXGI_FORMAT_R8G8B8A8_UNORM, + UINT width = side) + { + const auto real = desktop_object(guest, device, resource); + if (!real) return false; + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) + return false; + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyTextureRegion(&footprint(readback.Get(), fmt, width), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + own_list->ResourceBarrier(1, &b); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, image_bytes}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + const auto* src = static_cast(mapped); + const UINT row_bytes = fmt == DXGI_FORMAT_R8_UNORM ? width : width * 4; + UINT mismatches = 0; + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < row_bytes; ++x) { + const UINT i = y * pitch + x; + if (src[i] != pattern_byte(seed, i)) ++mismatches; + } + readback->Unmap(0, nullptr); + if (mismatches) { + std::printf("FAIL: %s readback had %u mismatched bytes\n", what, mismatches); + return false; + } + return true; + } + void release(Res& r) + { + r.guest.Reset(); + r.released = true; + } + void drain_once() + { + IUnknown* lists[] = {drain_list.list.Get()}; + invoke(direct.queue.Get(), 10, 1u, lists); + } + bool expect(const char* stage, const char* fail) const + { + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 live_b = base.live[texture].bytes, ret_b = base.retained[texture].bytes; + UINT64 live_n = base.live[texture].objects, ret_n = base.retained[texture].objects; + for (const Res& r : pool) { + if (r.category != texture) continue; + if (!r.released) { + live_b += r.bytes; + ++live_n; + } else if (!r.freed) { + ret_b += r.bytes; + ++ret_n; + } + } + const auto& got_live = now.live[texture]; + const auto& got_ret = now.retained[texture]; + if (got_live.bytes == live_b && got_live.objects == live_n && + got_ret.bytes == ret_b && got_ret.objects == ret_n) + return true; + std::printf("FAIL: %s\n stage '%s' live=%llu/%llu expected=%llu/%llu retained=%llu/%llu expected=%llu/%llu\n", + fail, stage, got_live.bytes, got_live.objects, live_b, live_n, + got_ret.bytes, got_ret.objects, ret_b, ret_n); + return false; + } + bool stays(const char* stage, const char* fail) + { + drain_once(); + return sync(direct) && expect(stage, fail); + } + bool settle(const char* stage, const char* fail) + { + for (int i = 0; i < settle_limit; ++i) { + drain_once(); + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 ret_n = base.retained[texture].objects; + for (const Res& r : pool) if (r.released && !r.freed) ++ret_n; + if (now.retained[texture].objects == ret_n) return expect(stage, fail); + } + return expect(stage, fail); + } +}; + +void fill_title_memory(void* address, int seed) +{ + auto* dst = static_cast(address); + for (UINT i = 0; i < image_bytes; ++i) dst[i] = pattern_byte(seed, i); +} + +// Case 7 (reviewer JB2WIN, finding B1): the fixture had no draw path, so retire_hold() in the translated draw and +// the view-token resolution that picks the sampled texture were untested. The case samples a slot 133 +// title-memory texture through a descriptor table with a host-built translated pipeline: the draw must bind the +// texture the token names, the closed recording must hold it (so its final Release cannot drop it from the budget +// before the recording is dropped), and the readback must hold the exact texel content throughout. +constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target +constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel +constexpr int draw_seed = 77; +constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM +constexpr char draw_revision[] = "x2w-startup-shader-14"; // d3d12_draw.inl cached_translation + +constexpr char draw_vertex_shader[] = R"( +struct Varying { float4 position : SV_Position; }; +Varying main(uint id : SV_VertexID) +{ + Varying result; + result.position = float4(id == 1 ? 3.0 : -1.0, id == 2 ? 3.0 : -1.0, 0.0, 1.0); + return result; +} +)"; + +// Samples the texture the title's descriptor table names at the pixel it covers, so an unresolved or wrongly +// resolved view token shows up as wrong texels rather than as a draw that silently binds nothing. +constexpr char draw_pixel_shader[] = R"( +Texture2D sampled : register(t0); +float4 main(float4 position : SV_Position) : SV_Target +{ + return sampled.Load(int3(uint2(position.xy), 0)); +} +)"; + +constexpr char draw_manifest[] = + "x2w-manifest 1\nud 1\nudsrc 0 rect\nsrv 0 tex2d table 0 0\nparams 0\ntargets 0\n"; + +std::uint64_t fnv_bytes(const void* data, std::size_t bytes, std::uint64_t hash = 1469598103934665603ull) +{ + const auto* p = static_cast(data); + for (std::size_t i = 0; i < bytes; ++i) hash = (hash ^ p[i]) * 1099511628211ull; + return hash; +} + +bool write_file(const std::wstring& path, const void* data, std::size_t bytes) +{ + HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + return complete; +} + +ComPtr compile_stage(const char* source, const char* entry, const char* profile) +{ + ComPtr code, errors; + const HRESULT hr = D3DCompile(source, std::strlen(source), nullptr, nullptr, nullptr, entry, profile, 0, 0, + code.GetAddressOf(), errors.GetAddressOf()); + if (FAILED(hr)) { + std::printf("FAIL: %s %s compile 0x%08lx%s%s\n", entry, profile, static_cast(hr), + errors ? ": " : "", errors ? static_cast(errors->GetBufferPointer()) : ""); + return nullptr; + } + return code; +} + +// Writes the source-built translation the shim looks up by the hash of the pipeline's two code blobs and its root +// signature (d3d12_draw.inl cached_translation), and creates the guest root signature and placeholder pipeline +// that name it. The shim loads the .vs/.ps bytecode and builds the desktop pipeline itself. +bool prepare_draw_translation(Context& c, ComPtr& root, ComPtr& pipeline) +{ + wchar_t temporary[MAX_PATH]{}; + if (!GetTempPathW(MAX_PATH, temporary)) return false; + const std::wstring directory = + std::wstring(temporary) + L"x2w-retire-title-" + std::to_wstring(GetCurrentProcessId()); + if (!CreateDirectoryW(directory.c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) return false; + if (!SetEnvironmentVariableW(L"X2W_SHADER_CACHE", directory.c_str())) return false; + + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameter{}; + parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameter.DescriptorTable = {1, &range}; + parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + const D3D12_ROOT_SIGNATURE_DESC descriptor{1, ¶meter, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, errors; + if (!require(D3D12SerializeRootSignature(&descriptor, D3D_ROOT_SIGNATURE_VERSION_1, blob.GetAddressOf(), + errors.GetAddressOf()), + "draw root serialize")) + return false; + if (!require(invoke(c.guest, 16, UINT{0}, blob->GetBufferPointer(), blob->GetBufferSize(), + &__uuidof(ID3D12RootSignature), root.GetAddressOf()), + "draw root signature")) + return false; + + const auto vertex = compile_stage(draw_vertex_shader, "main", "vs_5_1"); + const auto pixel = compile_stage(draw_pixel_shader, "main", "ps_5_1"); + if (!vertex || !pixel) return false; + // The opaque guest programs only identify the cache entry: the shim hashes these bytes with the root blob. + static std::uint32_t vertex_key[] = {0x7a1b0001, 0x2c3d4e5f}; + static std::uint32_t pixel_key[] = {0x7a1b0002, 0x5e4d3c2b}; + std::uint64_t key = fnv_bytes(draw_revision, sizeof(draw_revision) - 1); + key = fnv_bytes(vertex_key, sizeof(vertex_key), key); + key = fnv_bytes(pixel_key, sizeof(pixel_key), key); + key = fnv_bytes(blob->GetBufferPointer(), blob->GetBufferSize(), key); + wchar_t stem[64]{}; + swprintf(stem, 64, L"\\%016llx", static_cast(key)); + const std::wstring prefix = directory + stem; + if (!write_file(prefix + L".txt", draw_manifest, sizeof(draw_manifest) - 1) || + !write_file(prefix + L".vs.cso", vertex->GetBufferPointer(), vertex->GetBufferSize()) || + !write_file(prefix + L".ps.cso", pixel->GetBufferPointer(), pixel->GetBufferSize())) + return false; + + std::array description{}; + description[0] = reinterpret_cast(root.Get()); + description[5] = reinterpret_cast(vertex_key); + description[6] = sizeof(vertex_key); + description[9] = reinterpret_cast(pixel_key); + description[10] = sizeof(pixel_key); + return require(invoke(c.guest, 57, description.data(), &__uuidof(ID3D12PipelineState), pipeline.GetAddressOf()), + "draw pipeline"); +} + +// Reads a desktop target through the fixture's own desktop queue and readback buffer, as holds() does. +bool read_target(Context& c, ID3D12Resource* target, const D3D12_RESOURCE_DESC& desc, std::uint8_t* bytes, + UINT& row_pitch) +{ + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + c.device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + if (!total || total > image_bytes) { + std::puts("FAIL: target readback does not fit the fixture's readback buffer"); + return false; + } + if (!require(c.own_allocator->Reset(), "target allocator") || + !require(c.own_list->Reset(c.own_allocator.Get(), nullptr), "target list")) + return false; + D3D12_RESOURCE_BARRIER barrier{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + barrier.Transition = {target, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + c.own_list->ResourceBarrier(1, &barrier); + D3D12_TEXTURE_COPY_LOCATION to{c.readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + c.own_list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + c.own_list->ResourceBarrier(1, &barrier); + if (!c.own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, static_cast(total)}; + if (!require(c.readback->Map(0, &all, &mapped), "target readback map")) return false; + std::memcpy(bytes, mapped, static_cast(total)); + c.readback->Unmap(0, nullptr); + row_pitch = footprint.Footprint.RowPitch; + return true; +} + +std::uint32_t expected_target_pixel(UINT x, UINT y) +{ + if (x >= draw_covered || y >= draw_covered) return draw_clear_pixel; + std::uint32_t word = 0; + for (UINT byte = 0; byte < 4; ++byte) + word |= std::uint32_t{pattern_byte(draw_seed, y * pitch + x * 4 + byte)} << (8 * byte); + return word; +} + +bool check_target(const char* stage, const std::uint8_t* bytes, UINT row_pitch) +{ + for (UINT y = 0; y < draw_side; ++y) + for (UINT x = 0; x < draw_side; ++x) { + std::uint32_t got = 0; + std::memcpy(&got, bytes + y * row_pitch + x * 4, sizeof(got)); + const std::uint32_t want = expected_target_pixel(x, y); + if (got == want) continue; + std::printf("FAIL: %s: pixel (%u,%u) got %08lx want %08lx\n", stage, x, y, + static_cast(got), static_cast(want)); + return false; + } + return true; +} + +// 1: slot 133 title_memory texture upload & copy lifetime across closed list and gated submission. +bool case1_slot133_copy_and_upload(Context& c, bool on, void* title_mem) +{ + fill_title_memory(title_mem, 5); + Res& T1 = c.make_slot133("T1", title_mem); + auto t1_desktop = desktop_object(c.guest, c.device, T1.guest.Get()); + if (!t1_desktop) { + std::puts("FAIL: slot 133 texture has no desktop object"); + return false; + } + // The raw pointer only keys the upload cache after retirement: a COM reference here would keep the budget ticket + // of a retired desktop object alive (the fixture's expected retained count would then not drop). + ID3D12Resource* const t1_real = t1_desktop.Get(); + t1_desktop.Reset(); + Res& D1 = c.make_committed("D1"); + Res& D2 = c.make_committed("D2"); + if (!c.fill_desktop(D1.guest.Get(), 99) || !c.fill_desktop(D2.guest.Get(), 99)) return false; + GuestList L1, L2; + if (!c.make_list(L1) || !c.make_list(L2)) return false; + const D3D12_TEXTURE_COPY_LOCATION to1{static_cast(static_cast(D1.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION to2{static_cast(static_cast(D2.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(T1.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L1.list.Get(), 16, &to1, 0u, 0u, 0u, &from, static_cast(nullptr)); + invoke(L2.list.Get(), 17, D2.guest.Get(), T1.guest.Get()); + if (!c.close(L1) || !c.close(L2)) return false; + // texture_uploads()[T1->real] must be populated when T1 has title_memory. + RetireProbe probe = {}; + if (on && (!x2w_d3d12_retire_probe(T1.guest.Get(), L1.list.Get(), &probe) || probe.cache_entries == 0)) { + std::printf("FAIL: slot 133 CopyTextureRegion did not populate texture_uploads (cache_entries=%u)\n", probe.cache_entries); + return false; + } + c.release(T1); + if (!c.sync(c.direct) || !c.sync(c.gated)) return false; + if (!x2w_d3d12_texture_upload_probe(t1_real)) { + std::puts("FAIL: slot 133 CopyTextureRegion recorded no texture_uploads entry for T1"); + return false; + } + if (!c.stays("slot 133 released behind closed lists", "early release of slot 133 texture")) return false; + c.execute(c.direct, L1); + if (!c.sync(c.direct) || !c.holds(D1.guest.Get(), 5, "D1 CopyTextureRegion from slot 133")) return false; + if (!SUCCEEDED(c.reset_list(L1))) return false; + if (!c.stays("slot 133 still held by L2", "early release while L2 closed")) return false; + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate1") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait1")) + return false; + c.execute(c.gated, L2); + if (!SUCCEEDED(c.reset_list(L2))) return false; + if (!c.stays("slot 133 held by gated submission", "early release while gated submission in flight")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal1") || !c.sync(c.gated)) return false; + if (on) T1.freed = true; + if (!c.settle("slot 133 retired", "slot 133 texture kept after fences passed")) return false; + // The texture_uploads() entry the copy recorded leaves with the desktop object; without the switch nothing + // retires and the entry stays, as before the switch existed. + if ((x2w_d3d12_texture_upload_probe(t1_real) != FALSE) == on) { + std::printf("FAIL: texture_uploads entry for retired T1 is %s\n", on ? "still present" : "missing"); + return false; + } + return c.holds(D2.guest.Get(), 5, "D2 CopyResource from slot 133"); +} + +// 2: resource_address_index + slot 70 existing_memory_texture + same-address reuse while T1 is pending behind fence. +bool case2_same_address_and_slot70_reuse(Context& c, bool on, void* title_mem) +{ + fill_title_memory(title_mem, 11); + Res& T1 = c.make_slot133("T_addr1", title_mem, DXGI_FORMAT_R8_UNORM, pitch); + // The wrapper outlives its guest Release (the registry keeps it), so the raw pointer can be probed afterwards. + IUnknown* const t1_guest = T1.guest.Get(); + ComPtr gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate2") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait2")) + return false; + c.release(T1); + if (!c.stays("T_addr1 pending behind gate", "early release behind gate2")) return false; + // Reuse the exact same title_memory address while T1 is in retired_resources. + fill_title_memory(title_mem, 22); + Res& T2 = c.make_slot133("T_addr2", title_mem, DXGI_FORMAT_R8_UNORM, pitch); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}, 0, 0}; + ComPtr heap; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), "slot70 heap")) return false; + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const UINT64 h0 = invoke(heap.Get(), 9); + const UINT64 h1 = h0 + inc; + D3D12_RESOURCE_DESC r8_desc = c.desc; + r8_desc.Width = pitch; + r8_desc.Format = DXGI_FORMAT_R8_UNORM; + MemorySrvInput srv_in{}; + srv_in.address = reinterpret_cast(title_mem); + srv_in.view.Format = DXGI_FORMAT_R8_UNORM; + srv_in.view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv_in.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv_in.view.Texture2D.MipLevels = 1; + // Slot 70 exercises check_resource_address_index() (X2W_RESOURCE_INDEX_CHECK=1) and existing_memory_texture(). + invoke(c.guest, 70, &r8_desc, &srv_in, h0); + // Unblock T1: T1 retires cleanly, while T2 (held by slot 70 -> slot 18 SRV in heap[0]) remains live. + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal2") || !c.sync(c.gated)) return false; + if (on) T1.freed = true; + if (!c.settle("T_addr1 retired while T_addr2 live", "T_addr1 did not retire")) return false; + // Retirement drops T1's resource_address_index entry (the canonical record stays); without the switch T1 stays + // live, so its index entry stays too. T2's own entry must be there in both modes. + if (!x2w_d3d12_resource_index_probe(T2.guest.Get())) { + std::puts("FAIL: T_addr2 has no resource_address_index entry"); + return false; + } + if ((x2w_d3d12_resource_index_probe(t1_guest) != FALSE) == on) { + std::printf("FAIL: resource_address_index entry for retired T_addr1 is %s\n", on ? "still present" : "missing"); + return false; + } + // Verify T2 still uploads seed 22 properly after T1 retired. + const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& D = c.pool.emplace_back(); + D.name = "D_addr2"; + D.bytes = c.device->GetResourceAllocationInfo(0, 1, &r8_desc).SizeInBytes; + if (!require(invoke(c.guest, 127, &def_heap, D3D12_HEAP_FLAG_NONE, &r8_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + nullptr, 0u, nullptr, &c.iid_resource[0], D.guest.GetAddressOf()), "D_addr2")) + return false; + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(D.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(T2.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct) || + !c.holds(D.guest.Get(), 22, "T_addr2 after T_addr1 retired", DXGI_FORMAT_R8_UNORM, pitch)) + return false; + if (!SUCCEEDED(c.reset_list(L))) return false; + // Also exercise slot 70 once more after T1 retired, then release heap and T2. + invoke(c.guest, 70, &r8_desc, &srv_in, h1); + c.release(T2); + if (!c.stays("T_addr2 kept while slot70 SRV live", "T_addr2 freed while SRV slots live")) return false; + heap.Reset(); + if (on) T2.freed = true; + return c.settle("T_addr2 retired after heap released", "T_addr2 kept after heap released"); +} + +// 3: written_textures stale bc7_width cleanup on address reuse, and preservation of a newer generation. +bool case3_written_textures_cleanup(Context& c, bool on, void* title_mem, void* fallback_mem) +{ + x2w_d3d12_bc7_4k_s_written(title_mem, side, side); + Res& Tb = c.make_slot133("T_bc7", title_mem, DXGI_FORMAT_BC7_UNORM); + c.release(Tb); + if (!c.sync(c.direct) || !c.sync(c.gated)) return false; + if (on) Tb.freed = true; + if (!c.settle("T_bc7 retired", "T_bc7 kept")) return false; + + // When retire is on, reusing title_mem for plain RGBA8 (no XG call) must upload fresh texels instead of + // skipping on stale bc7_width; in off mode Tb stayed retained at title_mem so use fallback_mem. + void* rgba_mem = on ? title_mem : fallback_mem; + fill_title_memory(rgba_mem, 33); + Res& Tc = c.make_slot133("T_rgba_after_bc7", rgba_mem, DXGI_FORMAT_R8G8B8A8_UNORM); + Res& Dc = c.make_committed("D_rgba_after_bc7"); + if (!c.fill_desktop(Dc.guest.Get(), 99)) return false; + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(Dc.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(Tc.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct) || !c.holds(Dc.guest.Get(), 33, "RGBA8 reuse after BC7 retirement")) return false; + if (!SUCCEEDED(c.reset_list(L))) return false; + c.release(Tc); + if (on) Tc.freed = true; + return c.settle("T_rgba_after_bc7 retired", "T_rgba_after_bc7 kept"); +} + +// 4: descriptor & view reuse (slot 18 SRV + CopyDescriptorsSimple + heap release + descriptor overwrite). +bool case4_descriptor_and_view_reuse(Context& c, bool on, void* mem1, void* mem2) +{ + fill_title_memory(mem1, 44); + fill_title_memory(mem2, 55); + Res& Tv1 = c.make_slot133("Tv1", mem1); + Res& Tv2 = c.make_slot133("Tv2", mem2); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2}, 0, 0}; + ComPtr heap1, heap2; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap1.GetAddressOf()), "heap1") || + !require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap2.GetAddressOf()), "heap2")) + return false; + const UINT64 h1 = invoke(heap1.Get(), 9); + const UINT64 h2 = invoke(heap2.Get(), 9); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + invoke(c.guest, 18, Tv1.guest.Get(), &srv, h1); + invoke(c.guest, 24, 1u, h2, h1, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.release(Tv1); + if (!c.stays("Tv1 held by heap1 and heap2", "Tv1 freed while two SRV descriptors hold it")) return false; + heap1.Reset(); + if (!c.stays("Tv1 held by heap2 copy", "Tv1 freed while copied SRV in heap2 holds it")) return false; + // Overwrite heap2[0] with Tv2: Tv1's last tracked descriptor ref drops to 0 and Tv1 retires. + invoke(c.guest, 18, Tv2.guest.Get(), &srv, h2); + if (on) Tv1.freed = true; + if (!c.settle("Tv1 retired after descriptor overwrite", "Tv1 kept after all SRV descriptors overwritten")) return false; + c.release(Tv2); + if (!c.stays("Tv2 held by overwritten heap2[0]", "Tv2 freed while SRV descriptor holds it")) return false; + heap2.Reset(); + if (on) Tv2.freed = true; + return c.settle("Tv2 retired after heap2 released", "Tv2 kept after heap2 released"); +} + +// 5: switch-off control. An ordinary committed texture (slot 127, no title memory, not a slot 133 resource) copied as +// a subresource must still record its upload exactly as before the switch: upload_texture() is gated on the retire +// class, not on title memory. The observable is the per-desktop-object texture_uploads() entry the no-title-memory +// path records (a probe over the same map), plus the forwarded counter of the copy itself. +bool case5_ordinary_upload_switch_off(Context& c) +{ + Res& source = c.make_committed("U_src"); + Res& dest = c.make_committed("U_dst"); + const auto source_real = desktop_object(c.guest, c.device, source.guest.Get()); + const auto dest_real = desktop_object(c.guest, c.device, dest.guest.Get()); + if (!source_real || !dest_real) { + std::puts("FAIL: an ordinary committed texture has no desktop object"); + return false; + } + LONG forwarded_before = 0, refused_before = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded_before, &refused_before); + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_TEXTURE_COPY_LOCATION to{static_cast(static_cast(dest.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + const D3D12_TEXTURE_COPY_LOCATION from{static_cast(static_cast(source.guest.Get())), + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + invoke(L.list.Get(), 16, &to, 0u, 0u, 0u, &from, static_cast(nullptr)); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + LONG forwarded_after = 0, refused_after = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded_after, &refused_after); + if (forwarded_after != forwarded_before + 1 || refused_after != refused_before) { + std::printf("FAIL: ordinary texture copy forwarded %ld refused %ld, expected one more forwarded and none refused\n", + forwarded_after - forwarded_before, refused_after - refused_before); + return false; + } + const bool source_cached = x2w_d3d12_texture_upload_probe(source_real.Get()) != FALSE; + const bool dest_cached = x2w_d3d12_texture_upload_probe(dest_real.Get()) != FALSE; + if (!source_cached || !dest_cached) { + std::printf("FAIL: ordinary texture copy recorded no upload (source=%d destination=%d); " + "upload_texture is gated on title memory instead of the retire class\n", source_cached, dest_cached); + return false; + } + return true; +} + +// 6: A live slot-18 SRV keeps the current format metadata even after both same-address guest wrappers are released. +// The older wrapper's eventual retirement must also leave the newer generation intact. +bool case6_written_generation_preserved(Context& c, void* title_mem) +{ + x2w_d3d12_bc7_4k_s_written(title_mem, side, side); // generation 1 of this address + Res& Told = c.make_slot133("T_gen_old", title_mem); + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr heap; + if (!require(invoke(c.guest, 14, &heap_desc, &__uuidof(ID3D12DescriptorHeap), heap.GetAddressOf()), "generation heap")) + return false; + const UINT64 handle = invoke(heap.Get(), 9); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + invoke(c.guest, 18, Told.guest.Get(), &srv, handle); + c.release(Told); + // The live view keeps the entry: only its generation is snapshotted, the entry is not erased. + unsigned long long generation = 0; + unsigned bc7_width = 0; + if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 1 || + bc7_width != side) { + std::printf("FAIL: a live view did not keep written_textures entry (found=%d generation=%llu bc7_width=%u)\n", + x2w_d3d12_written_probe(title_mem, nullptr, nullptr, nullptr), generation, bc7_width); + return false; + } + // A newer generation of the same address while the older resource is still pending behind its view. + x2w_d3d12_bc7_4k_s_written(title_mem, side, side); + Res& Tnew = c.make_slot133("T_gen_new", title_mem); + c.release(Tnew); + if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 2 || bc7_width != side) { + std::puts("FAIL: releasing the newer wrapper erased metadata used by the older wrapper's live SRV"); + return false; + } + Tnew.freed = true; + if (!c.settle("newer wrapper retired with older SRV live", "newer wrapper kept or older SRV retired")) return false; + if (!x2w_d3d12_written_probe(title_mem, &generation, &bc7_width, nullptr) || generation != 2 || bc7_width != side) { + std::puts("FAIL: draining the newer wrapper erased metadata used by the older wrapper's live SRV"); + return false; + } + heap.Reset(); // drops the view reference: the older resource can retire now + Told.freed = true; + if (!c.settle("older generation retired", "older generation kept after its view was released")) return false; + unsigned long long kept_generation = 0; + unsigned kept_bc7_width = 0; + const BOOL found = x2w_d3d12_written_probe(title_mem, &kept_generation, &kept_bc7_width, nullptr); + if (!found || kept_generation != 2 || kept_bc7_width != side) { + std::printf("FAIL: retiring the older generation released the newer written generation " + "(found=%d generation=%llu bc7_width=%u)\n", found, kept_generation, kept_bc7_width); + return false; + } + return true; +} + +// 7 (B1): a translated draw samples a slot 133 title-memory texture through a descriptor table. The draw's view +// token must resolve to that texture (a broken resolution binds the wrong view and the readback disagrees), and +// the recording holds it so its final Release cannot drop it from the budget before the recording is dropped. +bool case7_draw_samples_slot133_texture(Context& c, void* title_mem) +{ + ComPtr root, pipeline; + if (!prepare_draw_translation(c, root, pipeline)) return false; + + fill_title_memory(title_mem, draw_seed); + // No COM reference to the desktop object here: it would keep the budget ticket of the retired texture alive. + Res& T = c.make_slot133("T_draw", title_mem); + + D3D12_RESOURCE_DESC target_desc = c.desc; + target_desc.Width = target_desc.Height = draw_side; + target_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + ComPtr target; + if (!require(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &target_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target)), + "draw target")) + return false; + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}, 0, 0}; + ComPtr rtv_heap; + if (!require(invoke(c.guest, 14, &rtv_heap_desc, &__uuidof(ID3D12DescriptorHeap), rtv_heap.GetAddressOf()), + "draw rtv heap")) + return false; + const UINT64 rtv = invoke(rtv_heap.Get(), 9); + invoke(c.guest, 20, target.Get(), static_cast(nullptr), rtv); + + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } view_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + ComPtr views; + if (!require(invoke(c.guest, 14, &view_heap_desc, &__uuidof(ID3D12DescriptorHeap), views.GetAddressOf()), + "draw view heap")) + return false; + const UINT64 view_cpu = invoke(views.Get(), 9); + const UINT64 view_gpu = invoke(views.Get(), 10); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + invoke(c.guest, 18, T.guest.Get(), &srv, view_cpu); + + GuestList L; + if (!c.make_list(L)) return false; + const D3D12_CPU_DESCRIPTOR_HANDLE target_view{static_cast(rtv)}; + const float clear[4] = {1.0f, 0.0f, 1.0f, 1.0f}; + const D3D12_VIEWPORT viewport{0, 0, static_cast(draw_side), static_cast(draw_side), 0, 1}; + const D3D12_RECT scissor{0, 0, draw_covered, draw_covered}; // the last row and column stay clear + invoke(L.list.Get(), 52, rtv, clear, 0u, static_cast(nullptr)); + invoke(L.list.Get(), 50, 1u, &target_view, FALSE, static_cast(nullptr)); + invoke(L.list.Get(), 25, pipeline.Get()); + invoke(L.list.Get(), 34, root.Get()); + IUnknown* heaps[] = {views.Get()}; + invoke(L.list.Get(), 32, 1u, heaps); + invoke(L.list.Get(), 36, 0u, view_gpu); + invoke(L.list.Get(), 20, static_cast(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST)); + invoke(L.list.Get(), 21, 1u, &viewport); + invoke(L.list.Get(), 22, 1u, &scissor); + invoke(L.list.Get(), 12, 3u, 1u, 0u, 0u); + if (!c.close(L)) return false; + c.execute(c.direct, L); + if (!c.sync(c.direct)) return false; + + std::array target_bytes{}; + UINT row_pitch = 0; + if (!read_target(c, target.Get(), target_desc, target_bytes.data(), row_pitch)) return false; + if (!check_target("slot 133 texture sampled by a translated draw", target_bytes.data(), row_pitch)) return false; + + // The draw path records the bind as a hold on the list, so the closed recording keeps the texture alive. The + // wrapper outlives its guest release, so the raw pointer still probes the list's holds afterwards. + IUnknown* const t_guest = T.guest.Get(); + + // Release the guest resource, then drop the descriptor that holds its slot 18 SRV reference by overwriting it + // with a view of the target. Only the draw's hold is left. + c.release(T); + D3D12_SHADER_RESOURCE_VIEW_DESC replaced = srv; + invoke(c.guest, 18, target.Get(), &replaced, view_cpu); + + // Draining while the closed list still names the texture keeps it retained, after its final Release too. + for (int i = 0; i < 8; ++i) { + c.drain_once(); + if (!c.sync(c.direct)) return false; + } + if (!c.expect("slot 133 texture held by the closed draw list", + "slot 133 texture left the budget before its draw recording was dropped")) + return false; + + RetireProbe held{}; + if (!x2w_d3d12_retire_probe(t_guest, L.list.Get(), &held) || held.list_holds == 0) { + std::printf("FAIL: translated draw recorded no retire hold on the slot 133 texture (list_holds=%u)\n", + held.list_holds); + return false; + } + + // The readback is still the sampled texel content after the release and the drains. + if (!read_target(c, target.Get(), target_desc, target_bytes.data(), row_pitch)) return false; + if (!check_target("readback after the guest release and drain", target_bytes.data(), row_pitch)) return false; + + // Dropping the recording releases the hold; only then may the texture leave the budget. + if (!SUCCEEDED(c.reset_list(L))) return false; + T.freed = true; + if (!c.settle("slot 133 draw hold dropped", "slot 133 texture kept after its draw recording was dropped")) + return false; + + if (!read_target(c, target.Get(), target_desc, target_bytes.data(), row_pitch)) return false; + return check_target("readback after the texture left the budget", target_bytes.data(), row_pitch); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off"))) + return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + char debug_env[2]{}; + const bool debug_on = GetEnvironmentVariableA("X2W_D3D12_DEBUG", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_on) { + ComPtr debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) return 77; + debug->EnableDebugLayer(); + } + ComPtr guest; + ComPtr device; + std::array parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + ComPtr debug; + if (debug_on && FAILED(device.As(&debug))) return 3; + if (debug) { + D3D12_MESSAGE_SEVERITY severities[] = { + D3D12_MESSAGE_SEVERITY_CORRUPTION, D3D12_MESSAGE_SEVERITY_ERROR, D3D12_MESSAGE_SEVERITY_WARNING}; + D3D12_INFO_QUEUE_FILTER filter{}; + filter.AllowList.NumSeverities = static_cast(std::size(severities)); + filter.AllowList.pSeverityList = severities; + if (FAILED(debug->AddStorageFilterEntries(&filter))) return 3; + debug->ClearStoredMessages(); + } + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + char switch_value[2]{}; + const bool switch_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", switch_value, sizeof(switch_value)) == 1 && + switch_value[0] == '1'; + const bool off_mode = argc == 3; + if (switch_on == off_mode) return 2; + const bool on = !off_mode; + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", off_mode ? "off" : "on"); + + constexpr SIZE_T page = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + auto* mem1 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + auto* mem2 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + auto* mem3 = VirtualAlloc(nullptr, page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!mem1 || !mem2 || !mem3) return 4; + + Context c{guest.Get(), device.Get(), debug.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.texture_bytes = device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.own_queue)), "own queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.own_allocator)), "own allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.own_allocator.Get(), nullptr, IID_PPV_ARGS(&c.own_list)), "own list") || + !require(c.own_list->Close(), "own list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.own_fence)), "own fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback")) + return 4; + if (!c.make_queue(c.direct) || !c.make_queue(c.gated) || !c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) return 4; + + if (!case1_slot133_copy_and_upload(c, on, mem1)) return 5; + std::puts("1 slot 133 copy and upload: held across closed list and gated submit, readback ok, retired"); + if (!case2_same_address_and_slot70_reuse(c, on, mem1)) return 5; + std::puts("2 same-address and slot 70 reuse: existing_memory_texture + resource_address_index ok"); + if (!case3_written_textures_cleanup(c, on, mem1, mem2)) return 5; + std::puts("3 written_textures cleanup: stale bc7_width cleared on address reuse"); + if (!case4_descriptor_and_view_reuse(c, on, mem1, mem2)) return 5; + std::puts("4 descriptor and view reuse: tracked slot-18 SRV holds and retires on overwrite/heap release"); + if (!on) { + if (!case5_ordinary_upload_switch_off(c)) return 5; + std::puts("5 switch-off ordinary texture copy: upload still recorded for a resource outside the retire class"); + } else { + if (!case6_written_generation_preserved(c, mem3)) return 5; + std::puts("6 written_textures generation: newer generation of an address kept by the older one's retirement"); + if (!case7_draw_samples_slot133_texture(c, mem1)) return 5; + std::puts("7 translated draw: slot 133 texture sampled through a descriptor table, held until the recording drained"); + } + } catch (int code) { + VirtualFree(mem1, 0, MEM_RELEASE); + VirtualFree(mem2, 0, MEM_RELEASE); + VirtualFree(mem3, 0, MEM_RELEASE); + return code; + } + VirtualFree(mem1, 0, MEM_RELEASE); + VirtualFree(mem2, 0, MEM_RELEASE); + VirtualFree(mem3, 0, MEM_RELEASE); + const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("debug_errors_or_warnings=%llu\n", errors); + if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(on ? "release-retired title checks passed" : "switch-off title checks passed"); + return 0; +} From 962dcf0d236df3c5cd6e0b6357f0a36352b053a7 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:47:35 +0100 Subject: [PATCH 122/232] startup: prove exec writes over every path of a compute execz block (#2509) A block that s_cbranch_execz skips per lane kept every exec write refused unless the block was straight-line. The check now runs a forward pass over the block: for each instruction the wave can reach from the branch it keeps the scalar words in which a skipped lane's bit is known clear on every path, branches and loops inside the block included, with the wave half each fact holds for. An exec write is accepted when it leaves exec among them. That accepts an if/else whose arms have their own s_cbranch_execz, the s_or_saveexec/s_xor switch, s_andn2_wrexec, loops, and masks built from a zero literal, when every restore reads a mask saved inside the block. A block entered by a branch from outside, a mask from before the block or from only some paths, the forms the pass does not follow and a copy of the other exec half stay refused. Case M runs an if/else block on a D3D12 device; a control that drops the switch to the else arm must mismatch. Refs #2274 Co-authored-by: Claude Fable 5.2 Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 2 +- docs/experiments.md | 46 ++++--- tests/startup_gfx2hlsl_compute_check.py | 154 +++++++++++++++++++++++- tools/startup/gfx2hlsl.py | 120 ++++++++++-------- 4 files changed, 258 insertions(+), 64 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c990663d7..2f4534c7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3433,7 +3433,7 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_compute_mbcnt_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) foreach(control IN ITEMS swapped-axes dropped-store b-offset c-unpredicated f-peer f-broadcast g-swapped-offsets g-overlap - j-scalar-dropped h-inner-unpredicated k-block-entered) + j-scalar-dropped h-inner-unpredicated k-block-entered m-else-unswitched) add_test(NAME startup_gfx2hlsl_compute_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py" control ${control} "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 40f37230f..a70d93bd5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14190,15 +14190,24 @@ join. When no lane is active, the wave skips the block too. The block is therefo when every SGPR, `vcc`, `m0` and SCC it may define is dead where it joins. A backward liveness pass over the program's instructions checks this. `m0` is always treated as live. -Exec writes inside the block are accepted when the block is straight-line (no branch in it and none into -it) and the write cannot set the exec bit of a lane whose bit is clear, because that lane's bit is clear on -entry. Accepted forms: -- `s_and_saveexec` and `v_cmpx`; -- `s_and` or `s_andn2` that keeps exec; -- `s_or`, `s_xor` or a move whose other source only ever holds a copy of exec made earlier in the same block. - -That covers a nested `if` without its own branch. The copies are tracked in program order, which is every path -only in a straight-line block. +Exec writes inside the block are accepted when they cannot set the exec bit of a lane whose bit was clear at +the branch. A forward pass over the block proves it. For each instruction the wave can reach from the branch, +the pass keeps the set of scalar words in which such a lane's bit is known clear, on every path through the +block, branches and loops inside it included (the largest sets that every path keeps, found by iteration). Each +fact names the half of the wave it holds for, so a copy of `exec_hi` proves nothing about `exec_lo`. The set +starts as exec alone. Only bitwise forms carry a fact: +- a copy of exec (`s_mov` from exec, or the mask a saveexec form saves) and a zero literal are clear; +- `s_and` is clear where either source is, `s_or` and `s_xor` where both are, `s_andn2` and `s_mov` where the + first source is; +- `s_and_saveexec`, `s_or_saveexec`, `s_xor_saveexec`, `s_andn2_saveexec` and `s_andn2_wrexec` are their + operation on exec and the source, and `v_cmpx` ANDs into exec; +- any other write, a compare result included, drops the facts of what it writes. + +An exec write must leave exec in the set. The lane's bit is then clear at every instruction the wave runs in +the block, so the wave changes nothing of that lane there, and its exec at the join is the model's. That +covers a nested `if`, an `if`/`else` whose arms have their own `s_cbranch_execz`, and a loop, when every +restore reads a mask saved inside the block. The proof starts at the branch, so it is not run for a block that +a branch from outside enters. Each instruction's reads and writes come from its printed operands, checked against the repository decoder's spelling: @@ -14221,9 +14230,10 @@ The block is still refused in these cases: - a definition that is live at the join, other than the lane mask above (or one of its conditions fails: zeroing with a value other than 0 or missing, a branch or a branch target between the zeroing and the branch, a write of M that is not from exec, a `vcc_hi` or 64-bit write, a whole-mask read after the join); -- any other exec write: exec set from a compare alone, restored from a mask saved before the block, or written - in a block with a branch or entered by one (a proven calculated `s_setpc_b64` jump counts), or restored through a 64-bit move, `s_or` or `s_xor` (the tracked copies name - registers, not which exec half they hold); +- any other exec write: exec set from a compare alone, restored from a mask saved before the block or on only + some of the paths, written by a form the pass does not follow (`s_orn2`, `s_nand`, `s_nor`, `s_xnor`, `s_not`, + the other saveexec and wrexec forms), written in a block that a branch from outside enters (a proven + calculated `s_setpc_b64` jump counts), or restored from a copy of the other exec half; - an effect outside scalar registers, such as a scalar store or atomic, a barrier, `s_endpgm` or `v_writelane`; - a branch out of the block; - a backward `s_cbranch_execz`. @@ -14270,6 +14280,9 @@ The runtime has no slot-67 path yet, so no translated compute program runs in th of the block's scalar statements must mismatch. - Case H nests an `s_and_saveexec`/`s_or` if inside such a block. Three lanes store two words, three more lanes store one word, and the rest store nothing. A control that drops the inner exec predicate must mismatch. +- Case M is case H with an `if`/`else` in the block. Each arm has its own `s_cbranch_execz`, `s_andn2_b32` of + the saved mask switches to the else arm and `s_mov_b32` restores it. Three lanes store the first word, three + more the second, and the rest store nothing. A control that drops the switch to the else arm must mismatch. - Case K enters such a block only in group 1; in the other three groups the whole wave skips it. A control that runs the block for the skipped waves must mismatch. @@ -14278,12 +14291,15 @@ for `cs_6_0`, and a plain D3D12 device dispatches it. The root signature is the a root UAV and the root constants), so the manifest's table lines and the descriptor fetch are not exercised on the GPU. All 320 words are compared, including the sentinels. Four controls must each mismatch: swapping the X and Y group IDs, dropping the store, dropping case B's immediate offset, and dropping case C's exec -predicate. Three more cover the execz cases: dropping a scalar statement in case J's block, dropping case H's -inner exec predicate, and running case K's block for the skipped waves. +predicate. Four more cover the execz cases: dropping a scalar statement in case J's block, dropping case H's +inner exec predicate, running case K's block for the skipped waves, and dropping case M's switch to the else arm. The pure-Python controls cover: - accepted and refused execz blocks: a dead definition is accepted; a live scalar definition, SCC consumed - after the join, a nested block and a backward branch are refused; + after the join and a backward branch are refused; +- exec writes in such a block: an `if`/`else` in both switch forms, a loop and a mask built from a zero literal + are accepted; a mask the loop body overwrites, a nonzero literal, an `s_or_saveexec` or `s_andn2_wrexec` source + from before the block, `s_orn2` and a copy of `exec_hi` are refused; - a modified descriptor word, an implicit-LOD sample and a misaligned immediate offset, all refused; - a store past the descriptor's range, which today translates with no range check. diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index b32acb0de..b88fe0d48 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -4,7 +4,7 @@ binary reassemble the fixture sources and compare them with the words below dispatch translate, compile with DXC cs_6_0, dispatch and compare every word - control + control the same dispatch with a mutated translation, which must mismatch The fixtures are source-built gfx1013 compute programs. The root signature puts two root constants (key, stride) @@ -28,6 +28,9 @@ the root constants that the active lanes store, and its scalars are dead where it joins; - case H is case J's shape with a nested if inside the skipped block (s_and_saveexec, restored with s_or of the saved mask): lanes tid.x < 3 store two words, lanes 3-5 one word, the rest none. +- case M is case H with an if/else in the skipped block: each arm has its own s_cbranch_execz, s_andn2_b32 of the + saved mask switches to the else arm and s_mov_b32 restores it. Lanes tid.x < 3 store the first word, lanes 3-5 + the second, the rest none. - case G reads two independently offset LDS dwords with the address in the first destination VGPR. - cases L-uint and L-unorm use the same formatted load with native descriptor stride and word 3 supplied by the harness. The descriptor selects unaligned UINT16 pairs or an UNORM8 field and permutes the outputs. @@ -235,6 +238,41 @@ def tidig(components): SOURCE_K = SOURCE_J.replace('v_cmp_gt_u32 vcc_lo, 3, v0\n', 'v_mov_b32 v6, s7\nv_cmp_eq_u32_e32 vcc_lo, 1, v6\n') WORDS_K = WORDS_J.replace(bytes.fromhex('8300887d'), bytes.fromhex('07020c7e' '810c847d')) +# Case M is case H with the nested if as an if/else. Each arm has its own s_cbranch_execz; the then arm stores the +# first word, s_andn2_b32 of the saved mask switches to the else arm, which stores the second, and s_mov_b32 +# restores the saved mask. +SOURCE_M = """\ +s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0x0 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s20, s7, 3 +v_add_nc_u32 v3, s20, v0 +v_lshlrev_b32 v4, 3, v3 +s_mov_b32 s21, exec_lo +v_cmp_gt_u32 vcc_lo, 6, v0 +s_mov_b32 exec_lo, vcc_lo +s_cbranch_execz 14 +s_mul_i32 s22, s7, s5 +s_add_u32 s22, s22, s4 +v_xor_b32 v5, s22, v3 +v_cmp_gt_u32 vcc_lo, 3, v0 +s_and_saveexec_b32 s0, vcc_lo +s_cbranch_execz 2 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_andn2_b32 exec_lo, s0, exec_lo +s_cbranch_execz 3 +v_not_b32 v6, v5 +buffer_store_dword v6, v4, s[16:19], 0 offen offset:4 +s_mov_b32 exec_lo, s0 +s_mov_b32 exec_lo, s21 +s_endpgm +""" +WORDS_M = bytes.fromhex( + '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '0783148f' '1400064a' '83060834' '7e0395be' '8600887d' + '6a03febe' '0e0088bf' '07051693' '16041680' '16060a3a' '8300887d' '6a3c80be' '020088bf' '001070e004050480' + '007e7e8a' '030088bf' '056f0c7e' '041070e004060480' '0003febe' '1503febe' '000081bf') + def saveexec_fixture(): # RDNA 2 ISA, SOP1: D takes old EXEC, then EXEC takes the bitwise result and SCC reports nonzero. # A single-thread group makes the lane bit the whole participating wave mask. @@ -366,6 +404,7 @@ def saveexec_fixture(): 'F': (SOURCE_F, WORDS_F, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), 'J': (SOURCE_J, WORDS_J, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'H': (SOURCE_H, WORDS_H, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), + 'M': (SOURCE_M, WORDS_M, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'K': (SOURCE_K, WORDS_K, USER7 | TGID_X | tidig(1), (8, 1, 1), (4, 1, 1)), 'G': (SOURCE_G, WORDS_G, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), **{name: (SOURCE_L, WORDS_L, USER7, (16, 1, 1), (1, 1, 1)) for name in L_WORD3}, @@ -543,6 +582,13 @@ def expected(name): out[2 * i] = value if tx < 6: # the skipped block out[2 * i + 1] = ~value & MASK + elif name == 'M': + i = gx * 8 + tx + value = i ^ ((KEY + gx * STRIDE) & MASK) + if tx < 3: # the then arm + out[2 * i] = value + elif tx < 6: # the else arm; lanes 6 and 7 skip the block + out[2 * i + 1] = ~value & MASK elif name == 'J': i = gx * 8 + tx if tx < 3: # the lanes the compare leaves active; the others skip the block @@ -985,6 +1031,111 @@ def check_controls(): refused('s_mov_b32 inside a block s_cbranch_execz skips per lane: exec write', lambda: translate( 'A', code=splice('s_getpc_b64 s[22:23]', 's_add_u32 s22, s22, 20', 's_addc_u32 s23, s23, 0', 's_setpc_b64 s[22:23]', *block)).hlsl_cs()) + # Exec writes in a block with branches. The proof follows, over every path from the branch, which masks keep + # the bit of a skipped lane clear; an exec write must leave exec among them. block() lists the refusals of a + # block of one-word instructions spliced between `enter` and `leave`. + words = { + 's_mov_b32 s0, exec_lo': '7e0380be', 's_mov_b32 exec_lo, s0': '0003febe', 's_mov_b32 s0, s21': '150380be', + 's_mov_b32 s0, 0': '800380be', 's_mov_b32 s0, 4': '840380be', 's_or_b32 s0, s0, exec_lo': '007e0088', + 's_andn2_b32 exec_lo, s0, exec_lo': '007e7e8a', 's_orn2_b32 exec_lo, s0, exec_lo': '007e7e8b', + 's_xor_b32 exec_lo, exec_lo, s0': '7e007e89', 's_and_b32 exec_lo, exec_lo, vcc_lo': '7e6a7e87', + 's_or_saveexec_b32 s0, s0': '003d80be', 's_andn2_wrexec_b32 s0, s0': '004780be', + 's_mov_b32 s22, exec_hi': '7f0396be', 's_or_b32 exec_lo, exec_lo, s22': '7e167e88', + 's_cbranch_execnz 65532': 'fcff89bf', 's_cbranch_scc1 65532': 'fcff85bf'} + SPLICE.update(words) + for line, word in words.items(): # the repository decoder prints each hand-assembled word as its line + (_, _, name, text), = G.decode(bytes.fromhex(word)) + assert text == line or name == line.split()[0] and name.startswith('s_cbranch'), (line, text) + + def block(*lines): + refusals = [] + SPLICE['s_cbranch_execz %d' % len(lines)] = '%02x0088bf' % len(lines) + G.ComputePipeline(splice(*enter, 's_cbranch_execz %d' % len(lines), *lines, *leave), root_blob(), CASES['A'][2], + (2, 3, 4), refusals=refusals) + return [reason for reason, _ in refusals] + + exec_write = '%s inside a block s_cbranch_execz skips per lane: exec write' + nested = ['v_cmp_gt_u32 vcc_lo, 3, v0', 's_and_saveexec_b32 s0, vcc_lo'] + # An if/else whose arms have their own s_cbranch_execz, switched with s_andn2 of the saved mask and restored + # with a move of it, and the same if/else switched with s_or_saveexec and s_xor: accepted. Case M runs the + # first on the GPU. + assert block(*nested, 's_cbranch_execz 1', 's_add_u32 s23, s7, 1', 's_andn2_b32 exec_lo, s0, exec_lo', + 's_cbranch_execz 1', 's_add_u32 s23, s7, 1', 's_mov_b32 exec_lo, s0') == [] + assert block(*nested, 's_or_saveexec_b32 s0, s0', 's_xor_b32 exec_lo, exec_lo, s0', + 's_or_b32 exec_lo, exec_lo, s0') == [] + # A loop that narrows exec until no lane is left, then restores the mask saved before it: accepted. + assert block('s_mov_b32 s0, exec_lo', 'v_mov_b32 v3, 0', 'v_add_nc_u32 v3, 1, v3', 'v_cmp_gt_u32 vcc_lo, 2, v3', + 's_and_b32 exec_lo, exec_lo, vcc_lo', 's_cbranch_execnz 65532', 's_mov_b32 exec_lo, s0') == [] + # A loop that restores exec from s0. With s0 left alone in the body it is accepted; when the body then + # overwrites s0 with the mask saved before the block, the back edge brings the restore, through the loop's + # first instruction, a mask that can set a skipped lane. + loop = ['s_mov_b32 s0, exec_lo', 's_add_u32 s23, s7, 1', 's_mov_b32 exec_lo, s0', 's_add_u32 s23, s7, 1', + 's_cbranch_scc1 65532'] + assert block(*loop) == [] + assert block(*loop[:3], 's_mov_b32 s0, s21', loop[4]) == [exec_write % 's_mov_b32'] + # A mask built from a zero literal and exec is clear for a skipped lane; one built from another literal is not. + assert block('s_mov_b32 s0, 0', 's_or_b32 s0, s0, exec_lo', 's_mov_b32 exec_lo, s0') == [] + assert block('s_mov_b32 s0, 4', 's_mov_b32 exec_lo, s0') == [exec_write % 's_mov_b32'] + # s_or_saveexec and s_andn2_wrexec keep exec clear only when their source is: a copy of exec saved in the block + # is accepted, s0 as it was before the block and a copy of the mask saved before the block are refused. + assert block('s_mov_b32 s0, exec_lo', 's_andn2_wrexec_b32 s0, s0') == [] + assert block('s_mov_b32 s0, s21', 's_andn2_wrexec_b32 s0, s0') == [exec_write % 's_andn2_wrexec_b32'] + assert block('s_or_saveexec_b32 s0, s0') == [exec_write % 's_or_saveexec_b32'] + # A form the proof does not follow (s_orn2 sets the lanes its second source leaves clear), and a copy of exec_hi + # ORed into exec_lo (the fact names the half of the wave it holds for): refused. + assert block('s_mov_b32 s0, exec_lo', 's_orn2_b32 exec_lo, s0, exec_lo') == [exec_write % 's_orn2_b32'] + assert exec_write % 's_or_b32' in block('s_mov_b32 s22, exec_hi', 's_or_b32 exec_lo, exec_lo, s22') + # The proof's step on its own: what a skipped lane's bit is known clear in, before and after one instruction. + start = {('exec', 0), ('exec_hi', 1)} + for facts, line, after in ( + (start, 's_and_saveexec_b64 s[2:3], vcc', start | {('s2', 0), ('s3', 1)}), + (start, 's_mov_b32 s2, exec_hi', start | {('s2', 1)}), + (start | {('s2', 0), ('s3', 0)}, 's_mov_b64 exec, s[2:3]', {('exec', 0), ('exec_hi', 0), ('s2', 0), ('s3', 0)}), + (start | {('s2', 0)}, 's_andn2_b32 exec_lo, s2, exec_lo', start | {('s2', 0)}), + (start | {('s2', 0)}, 's_andn2_b32 exec_lo, exec_lo, s2', start | {('s2', 0)}), + (start | {('s2', 0)}, 's_andn2_b32 exec_lo, s4, s2', {('exec_hi', 1), ('s2', 0)}), + (start | {('s2', 0)}, 's_add_u32 s2, s2, 1', start), + (start | {('s2', 0)}, 'v_cmp_gt_u32_e64 s2, 1, v0', start), + (start, 'v_cmpx_gt_u32_e32 1, v0', start)): + name = line.split()[0] + assert G.clear_after(name, line, G.scalar_effects(name, line)[2], facts) == after, line + # Case M's block: every statement of the lane that enters it, and the per-lane branches around both arms. + assert translate('M').hlsl_cs().endswith('''\ + if (pc == 1) { + s22 = s7 * ud1; + s22 = s22 + ud0; + if (exec & 1) v5 = s22 ^ v3; + vcc = (exec & ((0x00000003u > v0) ? 1u : 0u)); + s0 = exec; + exec = (exec & vcc) & 1; scc = exec != 0; + pc = ((exec & 1) == 0) ? 3 : 2; + } + if (pc == 2) { + a = (v4 + 0) & 0xfffffffcu; + if (exec & 1) u0.Store(a, v5); + pc = 3; + } + if (pc == 3) { + exec = (s0 & ~exec) & 1; + scc = exec != 0; + pc = ((exec & 1) == 0) ? 5 : 4; + } + if (pc == 4) { + if (exec & 1) v6 = ~v5; + a = (v4 + 4) & 0xfffffffcu; + if (exec & 1) u0.Store(a, v6); + pc = 5; + } + if (pc == 5) { + exec = (s0) & 1; + pc = 6; + } + if (pc == 6) { + exec = (s21) & 1; + pc = 0xffffu; + } +} +''') # The compiler's i1-phi lane mask: M is zeroed before the branch, set from exec in the block, and read per lane # after the join. For a lane the model skips, the wave's M bit is 0 either way (exec only narrows in the block), # which is the model's M. Accepted for vcc_lo and for an sN, with a move or an s_and in either operand order. @@ -1099,6 +1250,7 @@ def check_binary(llvm_mc): 'f-broadcast': ('F', 'lds[(v8 + 164u) >> 2]', 'lds[(v8 + 160u) >> 2]'), 'j-scalar-dropped': ('J', ' s22 = s7 * ud1;\n', ''), 'h-inner-unpredicated': ('H', 'if (exec & 1) u0.Store(a, v5);', 'u0.Store(a, v5);'), + 'm-else-unswitched': ('M', 'exec = (s0 & ~exec) & 1;', 'exec = (s0) & 1;'), # the then lanes run the else arm 'k-block-entered': ('K', 'pc = ((exec & 1) == 0) ? 2 : 1;', 'pc = 1; exec = 1;'), # skipped waves run it 'g-swapped-offsets': ('G', 'v6 = lds[(a + 20u) >> 2];\n v7 = lds[(a + 144u) >> 2];', 'v6 = lds[(a + 144u) >> 2];\n v7 = lds[(a + 20u) >> 2];'), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 826ed642b..2108bf301 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -515,40 +515,54 @@ def is_exec(regs): return regs in ({'exec'}, EXEC_KEYS) -def exec_stays_clear(name, asm, saved): - """True when an exec write cannot set the bit of a lane whose bit is clear: exec & x (s_and_saveexec, v_cmpx, - s_and or s_andn2 with exec as the kept operand), or exec | x, exec ^ x or a move of x where x is only ever a copy - of exec made inside the same skipped block (so x's bit is clear for that lane too).""" - base = re.sub(r'_e(32|64)$', '', name) - _, ops, _ = parse(asm) - if base.startswith(('s_and_saveexec', 'v_cmpx')): - return True - if not ops or not is_exec(scalar_tokens(ops[0])): - return False - srcs = [scalar_tokens(op) for op in ops[1:]] - # saved tracks register names, not which exec half was copied, so only a 32-bit restore is trusted - copies = lambda regs: bool(regs) and regs <= saved and base.endswith('32') - if base in ('s_and_b32', 's_and_b64'): - return any(is_exec(regs) for regs in srcs) - if base in ('s_andn2_b32', 's_andn2_b64'): - return bool(srcs) and is_exec(srcs[0]) - if base in ('s_or_b32', 's_or_b64', 's_xor_b32', 's_xor_b64') and len(srcs) == 2: - return all(is_exec(regs) or copies(regs) for regs in srcs) - if base in ('s_mov_b32', 's_mov_b64') and len(srcs) == 1: - return copies(srcs[0]) - return False - - -def exec_copies_after(name, asm, saved, may): - """The registers that hold only copies of exec made in the block, after this instruction.""" +def mask_words(tok, count): + """The scalar state keys holding a mask operand's words, low word first ('0' for a zero literal), or None when + the operand is not `count` whole words of scalar state.""" + if tok == '0': + return ['0'] * count + m = re.fullmatch(r's\[(\d+):(\d+)\]|s(\d+)|(vcc|exec)(_lo|_hi)?', tok) + if not m: + return None + if m.group(4): + words = {'_lo': [m.group(4)], '_hi': [m.group(4) + '_hi']}.get(m.group(5), [m.group(4), m.group(4) + '_hi']) + else: + words = ['s%d' % n for n in range(int(m.group(1) or m.group(3)), int(m.group(2) or m.group(3)) + 1)] + return words if len(words) == count else None + + +def clear_after(name, asm, may, clear): + """Forward step of the proof Stage.execz_refusals runs over a block that s_cbranch_execz skips. A fact (key, h) + says: for every lane of wave half h (0: lanes 0 to 31, 1: lanes 32 to 63) whose exec bit was clear at the branch, + that lane's bit of the scalar state word `key` is clear. Returns the facts after the instruction, given the + facts before it. + + Only bitwise forms carry a fact, per word: a zero literal holds it for both halves; D = A & B holds what either + source holds; A | B and A ^ B what both hold; A & ~B and a move what A holds. A saveexec or wrexec form is its + operation on exec plus the copy it saves, and v_cmpx ANDs its result into exec. Any other write, a compare + result included, drops the facts of what it may write.""" base = re.sub(r'_e(32|64)$', '', name) _, ops, _ = parse(asm) - dests = scalar_tokens(ops[0]) - EXEC_KEYS - {'scc'} if ops else set() - saved = saved - (may - EXEC_KEYS - {'scc'}) - if base.startswith('s_and_saveexec') or (base in ('s_mov_b32', 's_mov_b64') and len(ops) == 2 - and is_exec(scalar_tokens(ops[1]))): - saved |= dests - return saved + out = {fact for fact in clear if fact[0] not in may - EXEC_KEYS} + if base.startswith('v_cmpx'): + return out + halves = lambda word: {0, 1} if word == '0' else {h for key, h in clear if key == word} + m = re.fullmatch(r's_(mov|and|or|xor|andn2)(_saveexec|_wrexec)?_b(32|64)', base) + saving = m and m.group(2) + count = 2 if m and m.group(3) == '64' else 1 + words = [mask_words(op, count) for op in ops] if m and not (saving and m.group(1) == 'mov') else [None] + if None in words or len(words) != (2 if saving or m.group(1) == 'mov' else 3): + return {fact for fact in out if fact[0] not in may} + dest, srcs = words[0], words[1:] + if saving: # RDNA 2 ISA SOP1: the operation is S0 op EXEC, so andn2 is S0 & ~EXEC + srcs.append(['exec', 'exec_hi'][:count]) + combine = {'and': set.union, 'or': set.intersection, 'xor': set.intersection}.get(m.group(1), lambda a, *b: a) + value = [combine(*(halves(src[j]) for src in srcs)) for j in range(count)] + writes = list(zip(dest, value)) + if saving: # saveexec keeps the old exec in D; wrexec writes the result to both + writes = list(zip(('exec', 'exec_hi'), value)) + (writes if saving == '_wrexec' else + [(word, halves(old)) for word, old in zip(dest, srcs[-1])]) + out = {fact for fact in out if fact[0] not in dict(writes)} + return out | {(word, h) for word, held in writes for h in held} def scalar_effects(name, asm): @@ -1679,17 +1693,18 @@ def execz_refusals(self): model skips the block for an inactive lane. That lane can differ from the wave only by reading, after the join, scalar state the block defines (no lane active means the wave skipped the block too). The block is therefore accepted unchanged when every scalar register, mask and SCC it may define is dead where it joins, - and it has no effect outside scalar registers and no branch out of it. An exec write is accepted in a - straight-line block (no branch in it, none into it) when it cannot set the bit of a lane whose bit is clear - (exec_stays_clear): such a lane's bit is clear on entry, so the wave leaves it clear and its exec at the - join is the model's. A live definition, another exec write, a refused effect, a branch leaving the block - or a backward s_cbranch_execz is refused. - + and it has no effect outside scalar registers and no branch out of it. An exec write is accepted when it + cannot set the bit of a lane whose bit was clear at the branch: clear_after carries, over every path through + the block (its branches and loops included), which masks have that lane's bit clear, and the write must + leave exec among them. Such a lane's bit then stays clear at every instruction the wave runs in the block, + so the wave changes nothing of that lane there and its exec at the join is the model's. The proof starts at + the branch, so a block that a branch from outside enters keeps its exec writes refused. A live definition, + an unproven exec write, a refused effect, a branch leaving the block or a backward s_cbranch_execz is + refused. One live definition is accepted: the i1-phi lane mask of the compiler's if-conversion, a 32-bit M (vcc_lo or one sN) zeroed before the branch (`s_mov_b32 M, 0`) and set in the block from exec only (`s_mov_b32 M, exec_lo`, `s_and_b32 M, X, exec_lo` in either operand order). Every write of M in the block yields a value - whose bit is 0 for any lane whose exec bit is clear there: exec can only be narrowed in the block - (exec_stays_clear has accepted each exec write), and a copy of exec, or X & exec, has that bit clear. M is 0 + whose bit is 0 for any lane whose exec bit is clear there: the clear-mask proof keeps exec clear for that lane, and a copy of exec, or X & exec, has that bit clear. M is 0 at the branch on every path (nothing branches or lands between the zeroing and the branch). So for a lane the model skips, the wave's M has that lane's bit 0 whether the wave ran the block or not, which is the model's M (0); a lane that runs the block runs it in the model too. This holds only while M is read per @@ -1701,14 +1716,14 @@ def execz_refusals(self): index = {off: i for i, off in enumerate(offsets)} effects = [scalar_effects(name, asm) for _, _, name, asm in self.ins] succ = [] - targets = [] # every branch target, the proven calculated s_setpc_b64 ones included + jumps = [] # (instruction, target) of every branch, the proven calculated s_setpc_b64 ones included for i, (off, n, name, asm) in enumerate(self.ins): to = int(parse(asm)[1][0].split('_')[1], 16) if name.startswith(('s_cbranch', 's_branch')) else None if name == 's_setpc_b64': # a proven calculated jump reaches its target to = getattr(self, 'calculated_pc', {}).get(off) nxt = [i + 1] if i + 1 < len(self.ins) and name not in ('s_branch', 's_endpgm') else [] if to is not None: - targets.append(to) + jumps.append((i, to)) succ.append(nxt + ([index[to]] if to in index else [])) live_in = [set() for _ in self.ins] changed = True @@ -1729,9 +1744,20 @@ def execz_refusals(self): refused.setdefault(off, 's_cbranch_execz to a block before it') continue live = live_in[t] | {'m0'} # m0 is also read implicitly; treat it as live - saved = set() # registers whose every write in the block so far is a copy of exec - # The copies are tracked in program order, which is every path only in a straight-line block: no branch - # in it and no branch into it. Elsewhere an exec write is refused. + # Facts before each instruction the wave can reach from the branch: the largest sets every path keeps. + entry = frozenset({('exec', 0), ('exec_hi', 1)}) + before = {b + 1: entry} if b + 1 < t else {} + entered = any(index.get(target) in range(b + 1, t) for k, target in jumps if not b < k < t) + changed = not entered + while changed: + changed = False + for i in range(b + 1, t): + if i in before: + after = frozenset(clear_after(*self.ins[i][2:], effects[i][2], before[i])) | entry + for s in succ[i]: + if b < s < t and before.get(s, after) & after != before.get(s): + before[s], changed = before.get(s, after) & after, True + targets = [target for _, target in jumps] straight = not any(self.ins[k][2].startswith(('s_cbranch', 's_branch')) for k in range(b + 1, t)) and \ not any(index.get(target) in range(b + 1, t) for target in targets) cand = {k for i in range(b + 1, t) for k in (effects[i][2] - EXEC_KEYS) & live if re.fullmatch(r'vcc|s\d+', k)} @@ -1745,12 +1771,12 @@ def execz_refusals(self): elif inner.startswith(('s_cbranch', 's_branch')) and not ( b < index.get(int(parse(inner_asm)[1][0].split('_')[1], 16), -1) <= t): reason = 'branch out of the block' - elif may & EXEC_KEYS and not (straight and exec_stays_clear(inner, inner_asm, saved)): + elif may & EXEC_KEYS and (entered or i in before and + not entry <= clear_after(inner, inner_asm, may, before[i])): reason = 'exec write' elif (may - EXEC_KEYS - ok_masks) & live: reason = 'definition of %s, live where the block joins' % ', '.join( sorted((may - EXEC_KEYS - ok_masks) & live)) - saved = exec_copies_after(inner, inner_asm, saved, may) if reason: refused.setdefault(at, '%s inside a block s_cbranch_execz skips per lane: %s' % (inner, reason)) return refused From 3e3697f16383fc83ec896b2c1ef05189f3394223 Mon Sep 17 00:00:00 2001 From: ChazY11 Date: Thu, 26 Nov 2026 03:49:36 +0800 Subject: [PATCH 123/232] gfx2hlsl: refuse a scalar ALU source list shorter than the table template uses (#2515) Stage.scalar builds the expression with text.format(*values), where the SCA entry spells its sources as {0}, {1}, ... A short operand list leaves values too short and str.format raises IndexError, which the single-shader path records as "translator crash in : IndexError" rather than as a refusal naming the instruction (the class #2463 catalogues). The arity guards merged in #2469 fire earlier in lower() for their own subsets; this path reaches scalar() without passing one, so the short form of 36 two-source templates crashed. The guard asserts the count the template needs before formatting, which covers all of them in one place. python -B tests/startup_gfx2hlsl_scalar_table_arity_check.py scalar table arity checks: 0 failed The check covers the short form refused with the operand count it names, the complete form never refused for its operand count, and a negative control that disabling the guard brings the IndexError back for 35 of the 36 (s_bfm_b32 keeps its own arity message, so it refuses either way and is excluded by name rather than counted as a survivor). gfx2hlsl family after the change: 67 checks, 0 red. AI-assisted. Co-authored-by: ChazY11 <246129015+ChazY11@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + ...artup_gfx2hlsl_scalar_table_arity_check.py | 107 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 8 ++ 5 files changed, 120 insertions(+) create mode 100644 tests/startup_gfx2hlsl_scalar_table_arity_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index d858e7d68..d5ca03ed1 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -219,6 +219,7 @@ jobs: tests/startup_image_load_mip_check.py \ tests/startup_gfx2hlsl_operand_count_check.py \ tests/startup_gfx2hlsl_scalar_arity_check.py \ + tests/startup_gfx2hlsl_scalar_table_arity_check.py \ tests/startup_image_2d_array_check.py \ tests/startup_image_sample_a16_check.py \ tests/startup_image_load_d16_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 2c837487f..7c4722b39 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,6 +163,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_load_mip_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_operand_count_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_arity_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_table_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2f4534c7a..cee6cf077 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3000,6 +3000,9 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl refuses a scalar ALU operation whose operand list is too short. add_test(NAME startup_gfx2hlsl_scalar_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_arity_check.py") + # gfx2hlsl refuses a scalar ALU source list shorter than the template the scalar table spells (#2463). + add_test(NAME startup_gfx2hlsl_scalar_table_arity COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_table_arity_check.py") # gfx2hlsl lowers v_swap_b32 (VOP1): CPU evaluation of the translated text, refusals of every form llvm-mc rejects. add_test(NAME startup_gfx2hlsl_swap COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_swap_check.py") diff --git a/tests/startup_gfx2hlsl_scalar_table_arity_check.py b/tests/startup_gfx2hlsl_scalar_table_arity_check.py new file mode 100644 index 000000000..7a2d86ebc --- /dev/null +++ b/tests/startup_gfx2hlsl_scalar_table_arity_check.py @@ -0,0 +1,107 @@ +"""The scalar ALU table refuses a source list shorter than its template uses (#2463). + +`Stage.scalar` builds the expression with `text.format(*values)`, where the `SCA` entry spells its sources as +`{0}`, `{1}`, ... A short operand list leaves `values` too short and `str.format` raises IndexError, which the +single-shader path records as `translator crash in : IndexError` rather than as a refusal naming the +instruction. The guard asserts the count the template needs before formatting. + +AI-assisted. +""" + +import importlib.util +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SOURCE = HERE.parent / 'tools' / 'startup' / 'gfx2hlsl.py' + + +def load(text=None): + spec = importlib.util.spec_from_loader('gfx2hlsl_table', loader=None) + module = importlib.util.module_from_spec(spec) + module.__dict__['__file__'] = str(SOURCE) + exec(compile(text if text is not None else SOURCE.read_text(encoding='utf-8'), + str(SOURCE), 'exec'), module.__dict__) + return module + + +G = load() +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH %s' % detail)) + if not ok: + failures.append(label) + + +def probe_for(module): + """A Stage with no pipeline: enough state for one scalar instruction to be translated.""" + class Probe(module.Stage): + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + self.masks = set() + return Probe() + + +def needed_sources(module, op): + """How many sources the SCA template for op reads.""" + text, _ = module.SCA[op] + return max((int(i) for i in re.findall(r'\{(\d+)\}', text)), default=-1) + 1 + + +def refusal(module, op, sources): + """The Unsupported text for op with that many sources, 'ok', or the name of another exception.""" + line = '%s s1, %s' % (op, ', '.join('s%d' % (2 + i) for i in range(sources))) if sources else '%s s1' % op + try: + probe_for(module).one(op, line) + except module.Unsupported as error: + return str(error) + except Exception as error: # noqa: BLE001 the point is to see which exception a malformed form raises + return type(error).__name__ + return 'ok' + + +TWO_SOURCE = sorted(op for op in G.SCA if needed_sources(G, op) >= 2) +check('the SCA table has two-source templates', len(TWO_SOURCE) >= 30, len(TWO_SOURCE)) + +# The shape that crashed: one source fewer than the template uses. +crashing = [op for op in TWO_SOURCE if refusal(G, op, needed_sources(G, op) - 1) == 'IndexError'] +check('no two-source template crashes on a short source list', not crashing, repr(crashing[:6])) + +# Each refusal reads as a requirement: the count the instruction carries, not an internal index. +wrong = [] +for op in TWO_SOURCE: + count = needed_sources(G, op) + message = refusal(G, op, count - 1) + if not isinstance(message, str) or not message.endswith('expected %d' % (count + 1)): + wrong.append((op, message)) +check('every short form is refused with the operand count it needs', not wrong, repr(wrong[:4])) + +# The complete form is untouched by the guard: same verdict as the reference, which is translation or a +# later refusal, never the arity message. +changed = [] +for op in TWO_SOURCE: + count = needed_sources(G, op) + message = refusal(G, op, count) + if isinstance(message, str) and message.endswith('expected %d' % (count + 1)): + changed.append(op) +check('a complete form is never refused for its operand count', not changed, repr(changed[:4])) + +# Negative control: with the guard removed the short form raises IndexError again. One template keeps its own +# arity check (s_bfm_b32 spells "expected 3" in its body), so it refuses either way and is excluded here rather +# than counted as a survivor. +stripped = load(SOURCE.read_text(encoding='utf-8').replace(' if len(srcs) < needed:', + ' if False:')) +control = [op for op in TWO_SOURCE if refusal(stripped, op, needed_sources(stripped, op) - 1) == 'IndexError'] +check('control: without the guard the short form raises IndexError', len(control) >= len(TWO_SOURCE) - 1, + '%d of %d' % (len(control), len(TWO_SOURCE))) +kept = [op for op in TWO_SOURCE if op not in control] +check('the one template with its own arity check still refuses without the guard', + all(refusal(stripped, op, needed_sources(stripped, op) - 1).startswith(op) for op in kept), repr(kept)) + +print('scalar table arity checks: %d failed' % len(failures)) +sys.exit(1 if failures else 0) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 2108bf301..044913a36 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2870,6 +2870,14 @@ def src_sym(t): else: self.sym[d] = ('descnum',) return None + # The table templates name their sources as {0}, {1}, ...; a short operand list would make + # str.format raise IndexError, which the single-shader path records as a translator crash + # rather than a refusal. The arity guards above cover the table entries that spell a count, so + # this one covers the templates themselves: every placeholder the template uses must have a + # source, and a template may not read a source the instruction does not carry. + needed = max((int(i) for i in re.findall(r'\{(\d+)\}', text)), default=-1) + 1 + if len(srcs) < needed: + raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), needed + 1)) values = [self.u(t) for t in srcs] expr = text.format(*values) if shift_add: From a1d1db8b0ddcafb73757e5325b2ce2c04e46c61a Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:49:51 +0100 Subject: [PATCH 124/232] gfx2hlsl: accept fi:1 on the pixel-stage DPP16 quad forms under the whole-quad proof (#2483) * startup: accept fi:1 on the pixel-stage DPP16 quad forms under the whole-quad proof The quad swap, quad broadcast and pair broadcast lowerings of tools/startup/gfx2hlsl.py refused every DPP16 word with FI set. FI (bit 18 of the DPP dword; LLVM AMDGPU `fi`, Mesa ACO `fetch_inactive`) only chooses what a disabled source lane returns: its register instead of the bound_ctrl result. All three lowerings are taken only in a straight-line pixel stage whose EXEC is the entry mask after `s_wqm exec, exec`, so every lane of the quad is active, no source lane is disabled, and FI decides nothing, as for bound_ctrl. dpp() now drops `fi:1` before dispatching; the translation is the one without it. Without the proof (no s_wqm, EXEC changed, branches, vertex stage) the forms stay refused, as do `fi:0` as a spelling, row and wave controls, mirrors, DPP8 and partial masks. Tests: the three DPP checks build the fixtures with FI set, compare the translated text with the plain fixture, and keep fi:1 refused without the proof. Without the dpp() line each of the three checks fails with `..._dpp with fi:1`. Refs #2125, #2023 (item H), #1996 (item B). Co-Authored-By: Claude Fable 5.2 * tests: pin own lane minus quad lane 0 for v_subrev_f32_dpp with a broadcast The DPP source is SRC0 and v_subrev computes SRC1 - SRC0, so `v_subrev_f32_dpp vD, vS, vS quad_perm:[0,0,0,0]` is the lane's own word minus lane 0 (#1996 item B). The broadcast check now asserts the two emitted lines; with the operands exchanged in the table it fails. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 +-- tests/startup_gfx2hlsl_dpp_pair_check.py | 9 +++++- ...artup_gfx2hlsl_dpp_quad_broadcast_check.py | 16 ++++++++-- tests/startup_gfx2hlsl_dpp_quad_swap_check.py | 30 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 10 +++++-- 5 files changed, 60 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index a70d93bd5..fe25c904d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14108,7 +14108,7 @@ lane masks and the discard destination. Run `tools/startup/gfx2hlsl.py` lowers the gfx1013 binary16 interpolation pair `v_interp_p1ll_f16` / `v_interp_p2_f16` (#1996, item C). The attribute channel holds two binary16 values that the vertex stage exports with `compr`; half `h` of channel `c` is float channel `2 * c + h` of the parameter, and the pair becomes `(vD & 0xffff0000u) | f32tof16(i.paramN.)`, with the upper half of the destination kept. Only the plain form and `high` are lowered: `clamp`, an output modifier, a source modifier, a `p2` whose third source is not the matching `p1ll` result, and an attribute that the vertex stage does not export are refused. A vertex stage that packs the halves into a plain 32-bit export (no `compr`, e.g. with `v_cvt_pkrtz_f16_f32`) is lowered too, for all four channels: half `h` of channel `c` is `f16tof32(word_c >> 16 * h)`, carried by the extra interpolated outputs `hparamN_lo` and `hparamN_hi` that exist only when the pixel stage reads the attribute this way. An attribute exported both with `compr` and plain, and a read of a channel the plain export leaves `off`, are refused; the compr export still fills only `x` and `y`. `tests/startup_gfx2hlsl_interp_f16_check.py` evaluates the translated text on the CPU against a reference from the ISA layout and fails when the lowering is removed or the `high` bit is inverted; `binary ` reassembles the fixtures and `draw` is the desktop readback (tests `startup_gfx2hlsl_interp_f16_controls`, `_warp` and `_hardware`). The `op_sel` bits (word 0 bits 11 to 14, each refused on its own) and any read of the upper 16 bits of a `p2` destination stay refused because no source states them for gfx10. Either of two kinds of evidence would lift the refusals: a source that states the gfx10 behaviour of the high 16 bits of the `v_interp_p2_f16` destination and of `op_sel` (kept, cleared or written), or a hardware draw on RDNA that reads back both halves of a `p2` result for each `op_sel` value and compares them with the lowering. -The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands; vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks, `fi:1`, source modifiers and operations without a table entry are refused. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. +The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands; vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks, source modifiers and operations without a table entry are refused. `fi:1` (fetch inactive) is accepted under the same whole-quad proof, where no source lane is disabled, and gives the same translation. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writelane_b32 vN, sM, k` followed by `v_readlane_b32 sD, vN, k` with an inline constant lane `k` (0..31) becomes one scalar slot per (VGPR, lane), written and read back as plain assignments. Both instructions ignore EXEC and touch only lane `k`, so with a constant `k` and a VGPR that no other instruction names, no cross-lane read exists to model. Refused, each with a reason: a lane chosen by an SGPR, lanes outside 0..31, a VGPR that any other instruction also names (vector use or register range), a read of a slot nothing wrote, branches (write-before-read needs straight-line order), a lane mask, `m0` or modifier on the value, a destination that is not a plain SGPR, and vertex stages. A constant value reloads as a constant. `tests/startup_gfx2hlsl_sgpr_spill_check.py` builds a pixel program with four slots in three VGPRs, clobbers the source SGPRs, reloads them (one slot after a second write) and ORs each word into the packed screen position; it draws 16 x 16 pixels and compares every word with an integer reference computed from the slot rule. Four wrong lowerings (overwrite ignored, lane 31 read as lane 0, a second VGPR read as the first, no reload) must read a different image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sgpr_spill_' -V`. The Python controls and the `binary` assembler check run on Linux; the draws need DXC and `offscreen_check` on Windows. @@ -14894,7 +14894,7 @@ ctest --preset release --no-tests=error -R '^cpu_aot_vex_parity$' -V ### gfx1013 pixel DPP16 quad broadcast -The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted only in a straight-line pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. Without that proof the instruction is refused, as are swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `fi`, `bound_ctrl:0`, non-VGPR sources and vertex stages. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. +The pixel translator lowers `quad_perm:[k,k,k,k]` (k = 0 to 3) with full `row_mask` and `bank_mask` on `v_mov_b32` and the VOP1/VOP2 float, integer and integer-to-float forms to `QuadReadLaneAt(value, k)`. The four lanes of a pixel quad are one 2 x 2 block (lane = x & 1 | (y & 1) << 1). It is accepted only in a straight-line pixel stage that ran `s_wqm_b64 exec, exec` (or `s_wqm_b32 exec_lo, exec_lo`) with EXEC unchanged since: the entry EXEC can leave out lanes of a partly covered quad, and the guest would then read an inactive source lane while `QuadReadLaneAt` returns a helper lane's value. Without that proof the instruction is refused, as are swaps, pair broadcasts, row shifts, mirrors, DPP8, partial masks, `bound_ctrl:0`, non-VGPR sources and vertex stages. `fi:1` is accepted with the proof and changes nothing, since no source lane is disabled. A stage that holds a quad read compiles as `ps_6_0` with DXC (`X2W_DXC`, the Windows Kits `bin` folder or `PATH`), and its vertex stage as `vs_6_0`. Reproduce: `ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_dpp_quad_broadcast" -V`. The controls cover the translation, every refusal and the missing `s_wqm`; the WARP and hardware draws compare all 256 pixels of two fixtures with a CPU reference, with wrong-lane and own-lane translations as failing controls. This does not establish full-game startup. diff --git a/tests/startup_gfx2hlsl_dpp_pair_check.py b/tests/startup_gfx2hlsl_dpp_pair_check.py index d2ad88308..6470d7773 100644 --- a/tests/startup_gfx2hlsl_dpp_pair_check.py +++ b/tests/startup_gfx2hlsl_dpp_pair_check.py @@ -249,6 +249,11 @@ def controls(): accepted = 'v_mov_b32_dpp v2, v1 quad_perm:[1,1,3,3] row_mask:0xf bank_mask:0xf' check('accepted form translates', refused(accepted) is None, str(refused(accepted))) check('bound_ctrl does not change the lowering', refused(accepted + ' bound_ctrl:1') is None) + stages = [Probe(), Probe()] + stages[0].one('v_mov_b32_dpp', accepted + ' bound_ctrl:1 fi:1') + stages[1].one('v_mov_b32_dpp', accepted) + check('fi:1 does not change the lowering (no source lane of a whole quad is disabled)', + stages[0].lines == stages[1].lines and any('QuadReadLaneAt' in line for line in stages[0].lines)) check('quad swap also translates', refused(accepted.replace('[1,1,3,3]', '[1,0,3,2]')) is None) check('quad broadcast also translates', refused(accepted.replace('[1,1,3,3]', '[0,0,0,0]')) is None) for label, asm, kwargs in ( @@ -259,7 +264,9 @@ def controls(): ('a mirror control', 'v_mov_b32_dpp v2, v1 row_mirror row_mask:0xf bank_mask:0xf', {}), ('a partial row mask', accepted.replace('row_mask:0xf', 'row_mask:0x5'), {}), ('a partial bank mask', accepted.replace('bank_mask:0xf', 'bank_mask:0xe'), {}), - ('fi', accepted + ' fi:1', {}), + ('fi:1 with an entry mask not proven whole-quad', accepted + ' fi:1', {'wqm_exec': False}), + ('fi:1 with an unknown entry mask', accepted + ' fi:1', {'exec_known': False}), + ('fi:1 in a program with branches', accepted + ' fi:1', {'has_branches': True}), ('no control', 'v_mov_b32_dpp v2, v1 row_mask:0xf bank_mask:0xf', {}), ('a vertex stage', accepted, {'kind': 'vs'}), ('a program with branches', accepted, {'has_branches': True}), diff --git a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py index 052b0d4eb..db9e81b77 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_broadcast_check.py @@ -23,7 +23,7 @@ against the reference and match their own plain-Python image. Refused (the single-lane model cannot read a neighbour, or the quad may be partly off): swaps, pair broadcasts, row -shifts, mirrors, DPP8, a partial row_mask or bank_mask, fi, bound_ctrl:0, a scalar or constant source, a vertex +shifts, mirrors, DPP8, a partial row_mask or bank_mask, fi:1 without the whole-quad proof, bound_ctrl:0, a scalar or constant source, a vertex stage, a pixel stage after EXEC changed or with branches, and operations outside the VOP1/VOP2 tables. """ import re @@ -223,7 +223,6 @@ def controls(): 'partial row_mask': 'v_mov_b32_dpp v1, v0 quad_perm:[1,1,1,1] row_mask:0xe bank_mask:0xf', 'partial bank_mask': 'v_mov_b32_dpp v1, v0 quad_perm:[1,1,1,1] row_mask:0xf bank_mask:0x7', 'no masks': 'v_mov_b32_dpp v1, v0 quad_perm:[1,1,1,1]', - 'fi': sane + ' fi:1', 'bound_ctrl:0': sane + ' bound_ctrl:0', 'scalar source': 'v_mov_b32_dpp v1, s2 quad_perm:[1,1,1,1]' + DPP, 'constant source': 'v_mov_b32_dpp v1, 1.0 quad_perm:[1,1,1,1]' + DPP, @@ -240,6 +239,19 @@ def controls(): check('refused: s_wqm into another register', refused_in_stage(OTHER_WQM_WORDS)) check('refused: pixel stage with branches', refused(sane, branches=True)) check('control: the sane line itself translates', not refused(sane)) + # fi:1 only decides what a disabled source lane returns, and the whole quad is proven active. + with_fi = 'v_subrev_f32_dpp v1, v0, v0 quad_perm:[0,0,0,0]' + DPP + ' bound_ctrl:1 fi:1' + stages = [Probe(), Probe()] + stages[0].one('v_subrev_f32_dpp', with_fi) + stages[1].one('v_subrev_f32_dpp', with_fi[:-len(' fi:1')]) + check('fi:1 does not change the broadcast lowering', stages[0].lines == stages[1].lines) + # The DPP source is SRC0 and v_subrev computes SRC1 - SRC0 (#1996 item B): the lane's own word minus lane 0. + check('v_subrev_f32_dpp of a register with itself is own lane minus quad lane 0', + stages[0].lines == ['v256 = QuadReadLaneAt(v0, 0u);', 'v1 = U(F(v0) - F(v256));'], str(stages[0].lines)) + check('refused: fi:1 without s_wqm exec, exec', refused(with_fi, quad_exec=False)) + check('refused: fi:1 with EXEC no longer the entry mask', refused(with_fi, exec_known=False)) + check('refused: fi:1 in a pixel stage with branches', refused(with_fi, branches=True)) + check('refused: fi:1 in a vertex stage', refused(with_fi, kind='vs')) def check_binary(llvm_mc): diff --git a/tests/startup_gfx2hlsl_dpp_quad_swap_check.py b/tests/startup_gfx2hlsl_dpp_quad_swap_check.py index af9e7c091..a156b757c 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_swap_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_swap_check.py @@ -203,7 +203,9 @@ def controls(): ('partial bank_mask', base.replace('bank_mask:0xf', 'bank_mask:0x5'), {}), ('row_mirror', 'v_mov_b32_dpp v5, v0 row_mirror row_mask:0xf bank_mask:0xf', {}), ('DPP8', 'v_mov_b32_dpp v5, v0 dpp8:[1,0,3,2,5,4,7,6]', {}), - ('fi:1', base + ' fi:1', {}), + ('fi:0 spelling', base + ' fi:0', {}), + ('fi:1 with EXEC no longer the entry mask', base + ' fi:1', {'exec_known': False}), + ('fi:1 with entry EXEC not proven whole-quad', base + ' fi:1', {'wqm_exec': False}), ('negated source', 'v_add_f32_dpp v5, -v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf', {}), ('SGPR source', 'v_mov_b32_dpp v5, s0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf', {}), ('operation without a table entry', 'v_cvt_f64_f32_dpp v[5:6], v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf', {}), @@ -238,6 +240,32 @@ def controls(): except G.Unsupported as reason: check('refused: whole-quad proof dropped by a restored exec copy (%s)' % reason, 'whole-quad' in str(reason)) + # 4b'. fi:1 (fetch inactive, bit 18 of the DPP dword) decides what a disabled source lane returns. With the whole + # quad proven active there is none, so the translation is the one without it; without the proof it stays refused. + for name in NAMES: + plain = fixture(name)[1] + with_fi = bytearray(plain) + for off, _size, mnemonic, _asm in G.decode(plain): + if mnemonic.endswith('_dpp'): + with_fi[off + 6] |= 4 + decoded = [asm for _, _, mnemonic, asm in G.decode(bytes(with_fi)) if mnemonic.endswith('_dpp')] + check('%s fixture with FI set decodes to three fi:1 swaps' % name, + len(decoded) == 3 and all(asm.endswith(' fi:1') for asm in decoded), str(decoded)) + check('%s fixture with fi:1 translates to the text without it' % name, + pipeline(bytes(with_fi)).hlsl_ps() == pipeline(plain).hlsl_ps()) + try: + pipeline(bytes(with_fi)[len(WQM):]).hlsl_ps() + check('%s fixture with fi:1 and no s_wqm exec is refused' % name, False) + except G.Unsupported as reason: + check('%s fixture with fi:1 and no s_wqm exec is refused (%s)' % (name, reason), 'whole-quad' in str(reason)) + branched = Probe() + branched.has_branches = True + try: + branched.one('v_min_u32_dpp', dpp_text('v_min_u32_dpp', 'v5, v0, v0', (1, 0, 3, 2)) + ' fi:1') + check('refused: fi:1 in a shader with branches', False) + except G.Unsupported: + check('refused: fi:1 in a shader with branches', True) + # 4c. The min fixture keeps src1 in its own lane and its reference is neither the plain exchange nor a maximum. line = pipeline(fixture('min')[1]).hlsl_ps() check('v_min_u32_dpp lowers to min(exchanged src0, own src1)', diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 044913a36..da76aa969 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2370,7 +2370,7 @@ def dpp_pair(self, base, asm, ops, mods): lane keeps the one quad_perm names for its own position in the quad. That needs all four lanes of the quad to run the instruction in the same flow, as in a pixel shader with helper lanes: straight-line code and a whole-quad exec mask (proved by s_wqm exec, exec on the entry mask; a restored exact mask loses it). Every - other control (other permutations, row_*, wave_*, a partial row or bank mask, fi, a vertex stage) is refused by + other control (other permutations, row_*, wave_*, a partial row or bank mask, a vertex stage) is refused by name, since the single lane cannot read a neighbour.""" perms = [m for m in mods if m.startswith('quad_perm:')] rest = [m for m in mods if not m.startswith('quad_perm:')] @@ -2599,7 +2599,7 @@ def lower(self, base, asm, ops, mods): # Accepted only where the whole quad is proven active: a straight-line pixel stage that ran s_wqm exec, exec and # whose EXEC is still that mask (helper lanes are active, so no source lane is off). bound_ctrl then has # nothing to decide (the source lane is never disabled), so it is accepted and ignored. Everything else a DPP word can say stays refused: other controls (pair - # broadcasts, row shifts, mirrors, DPP8), a masked row or bank, fi, and a vertex stage. + # broadcasts, row shifts, mirrors, DPP8), a masked row or bank, and a vertex stage (dpp() drops fi:1 first). DPP_TEMP = 256 # hidden VGPR that holds the quad read; the hardware has v0..v255 only DPP_OUTPUT_MODS = ('clamp', 'mul:2', 'mul:4', 'div:2') @@ -2658,8 +2658,12 @@ def dpp_broadcast(self, base, ops, mods): # map onto the SM 6.0 quad intrinsics, which read the other lane of the 2x2 pixel quad and keep # helper lanes active. Only a pixel stage at entry EXEC qualifies, and only after `s_wqm exec, exec` # proved whole-quad EXEC: the hardware can return 0 or the old value for a source lane whose EXEC bit - # is off (an uncovered pixel of an edge quad), and the intrinsics have no such case. Other permutations, DPP8, row shifts and partial masks stay refused. + # is off (an uncovered pixel of an edge quad), and the intrinsics have no such case. Other permutations, fi:1 without that proof, DPP8, row shifts and partial masks stay refused. def dpp(self, base, ops, mods): + # fi:1 (fetch inactive, DPP16 dword bit 18; LLVM AMDGPU `fi`, Mesa ACO fetch_inactive) only decides what a + # disabled source lane returns. Every lowering below is taken only with the whole quad proven active, so no + # source lane is disabled and it decides nothing. + mods = [m for m in mods if m != 'fi:1'] if any(re.fullmatch(r'quad_perm:\[([0-3]),\1,\1,\1\]', mod) for mod in mods): return self.dpp_broadcast(base, ops, mods) perm = None From 66da8c4f9412925918eac2cf8bbf3ea8d2a75072 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Wed, 25 Nov 2026 21:52:13 +0200 Subject: [PATCH 125/232] tooling: retry incomplete slot 57 shader bytecode (#2521) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> --- docs/experiments.md | 5 ++++ tests/startup_gfx2hlsl_watch_check.py | 36 +++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 21 +++++++++++++--- 3 files changed, 59 insertions(+), 3 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index fe25c904d..6d9199ed8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9175,6 +9175,11 @@ The request fixture checks paired and mesh-only requests, duplicate publication, a mismatched root, a populated vertex slot, and an incomplete pixel span. +The pending scan checks the DXContainer header and file length for both +slot 57 bytecode artifacts. A missing or truncated artifact leaves the +request pending even if its manifest exists. In manifest-only mode the +manifest still completes the request. + Set `X2W_REFUSE_FIXED_MESH=1` to report unavailable fixed mesh pipelines at slot 57 creation. The descriptor must name a registered root, have an empty VS slot and have a readable 16-byte to 64-KiB MS span. The PS span must be diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index c756acea9..aacda35a9 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -115,6 +115,42 @@ def mesh57_fixture(ms, ps, expected, tamper=False): mesh57_fixture(mesh, vertex, 'slot 57 pixel stage has an incompatible export or termination') mesh57_fixture(mesh, pixel, 'slot 57 mesh request key mismatch', tamper=True) + +def mesh57_resume_controls(): + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + key = 0x57 + touch(d / 'req_0000000000000057.m57') + stem = d / f'{key:016x}' + touch(stem.with_suffix('.ms57.txt')) + ms, ps = (stem.with_suffix(suffix) for suffix in ('.ms57.cso', '.ps57.cso')) + # A container envelope is sufficient for an on-disk completeness check. + part = struct.pack('<4sI4s', b'DXIL', 4, b'test') + bytecode = struct.pack('<4s16sHHIII', b'DXBC', bytes(16), 1, 0, 36 + len(part), 1, 36) + part + prior = os.environ.pop('X2W_FXC', None) + try: + expect('slot 57 manifest alone is pending for bytecode', scan(d, False), [key]) + touch(ms, bytecode) + expect('slot 57 with only mesh bytecode is pending', scan(d, False), [key]) + touch(ps, bytecode) + expect('slot 57 with both complete containers is done', scan(d, False), []) + for stage in (ms, ps): + touch(stage, bytecode[:-1]) + expect(f'{stage.suffixes[0]} with truncated bytecode is pending', scan(d, True), [key]) + touch(stage, b'bad!' + bytecode[4:]) + expect(f'{stage.suffixes[0]} with a bad container header is pending', scan(d, False), [key]) + touch(stage, bytecode) + os.environ['X2W_FXC'] = '' + ps.unlink() + expect('slot 57 manifest-only mode finishes without pixel bytecode', scan(d, False), []) + finally: + os.environ.pop('X2W_FXC', None) + if prior is not None: + os.environ['X2W_FXC'] = prior + + +mesh57_resume_controls() + # Parallel --pending must give the same results as one worker. Sixteen RTV variants each name a # different missing base request, so each failure names its own base and a result reported against # the wrong key is visible. With four workers each batch holds one request. diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index da76aa969..a9ab9a7e2 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6238,6 +6238,19 @@ def has_bytecode(path): return False +def has_complete_mesh57_bytecode(path): + """Check the DXContainer header and length without reading the shader body.""" + try: + with open(path, 'rb') as shader: + header = shader.read(32) + if len(header) != 32 or header[:4] != b'DXBC': + return False + size, parts = struct.unpack_from('.vs.hlsl, .ps.hlsl and .txt (last), or .fail with the reason. @@ -6430,10 +6443,10 @@ def translate_mesh57(out_dir, key): bytecode = os.path.join(staging, stage + '.cso') r = subprocess.run([compiler, '-Gis', '-T', profile, '-E', 'main', '-Fo', bytecode, '%s.%s57.hlsl' % (name, stage)], capture_output=True, text=True) - if r.returncode or not has_bytecode(bytecode): + if r.returncode or not has_complete_mesh57_bytecode(bytecode): # DXC names the source path; keep only the diagnostic after it. lines = [re.sub(r'^.*?57\.hlsl(:\d+:\d+)?:\s*', '', line) for line in r.stderr.strip().splitlines()] - raise Unsupported('dxc %s: %s' % (stage, (lines[0] if lines else 'no bytecode produced')[:500])) + raise Unsupported('dxc %s: %s' % (stage, (lines[0] if lines else 'missing or incomplete bytecode')[:500])) for stage, _, _ in sources: os.replace(os.path.join(staging, stage + '.cso'), '%s.%s57.cso' % (name, stage)) temporary = '%s.ms57.txt.%d.tmp' % (name, os.getpid()) @@ -6784,8 +6797,10 @@ def pending_keys(out_dir, skip_failed): result = os.path.join(out_dir, '%016x' % key) mesh = m.group(2) == 'm57' stages = ('.cs.cso',) if m.group(2) == 'c67' else ('.ms57.cso', '.ps57.cso') if mesh else ('.vs.cso', '.ps.cso') + ready_bytecode = has_complete_mesh57_bytecode if mesh else has_bytecode + manifest = result + ('.ms57.txt' if mesh else '.txt') # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if os.path.isfile(result + ('.ms57.txt' if mesh else '.txt')) and (manifest_only or all(has_bytecode(result + s) for s in stages)): + if os.path.isfile(manifest) and (manifest_only or all(ready_bytecode(result + s) for s in stages)): continue fail = os.path.join(out_dir, '%016x.fail' % key) # A repeated pass retries a failure only once its request is rewritten. From c133432a5e9907813b34ad8fb07b79caea6f9f20 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Wed, 25 Nov 2026 21:56:11 +0200 Subject: [PATCH 126/232] gpu: cover hardware and disabled slot 86 writer traces (#2513) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 11 ++++++++--- CMakePresets.json | 2 +- docs/experiments.md | 5 +++++ tests/startup_indirect_mesh_cache_check.py | 22 +++++++++++++++++++++- 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cee6cf077..595e145af 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1548,12 +1548,17 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh86_srv_proof_check.py" "${DXC_EXECUTABLE}" "${CMAKE_CURRENT_BINARY_DIR}") set_tests_properties(startup_mesh86_srv_proof PROPERTIES TIMEOUT 60) - add_test(NAME startup_indirect_mesh_lease_warp_dual-trace COMMAND "${INTAKE_PYTHON}" -B + add_test(NAME startup_indirect_mesh_lease_warp_dual-trace-disabled COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" warp - "$" dual-trace) - set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + "$" dual-trace-disabled) + set_tests_properties(startup_indirect_mesh_lease_warp_dual-trace-disabled PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_indirect_mesh_lease_${backend}_dual-trace COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" + "${DXC_EXECUTABLE}" "$" ${backend} + "$" dual-trace) + set_tests_properties(startup_indirect_mesh_lease_${backend}_dual-trace PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_indirect_mesh_cache_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$" ${backend}) diff --git a/CMakePresets.json b/CMakePresets.json index d3cdebc55..ffb951925 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 6d9199ed8..0dd1e0389 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9132,6 +9132,11 @@ the writer. `order` records a cross-queue wait, a shared wait, same-queue ordering or an omitted wait in a control. A `recorded` call reaches a desktop command list. A `forwarded` submission reaches the desktop queue. +The paired trace fixture runs on WARP and hardware. An additional WARP +control leaves the selector unset, supplies a nondecimal suffix, and supplies +a value that would truncate to the ordered call's ordinal. Each control must +pass the paired pixel readback without emitting any trace rows. + The recent-copy rows search the last 1,024 submitted copy destinations recorded by the XMem lease tracker. These cover forwarded slot 15 and slot 17 copies into eligible copied placements. A placement overlap is a candidate diff --git a/tests/startup_indirect_mesh_cache_check.py b/tests/startup_indirect_mesh_cache_check.py index d83349a79..5daf66915 100644 --- a/tests/startup_indirect_mesh_cache_check.py +++ b/tests/startup_indirect_mesh_cache_check.py @@ -70,6 +70,24 @@ def trace_paired_submission(cmd, environment): return 0 +def check_trace_disabled(cmd, environment): + # Both invalid values would select call 3 if the parser accepted a prefix or truncated to UINT. + for selector in (None, '3x', '4294967299'): + traced = dict(environment) + if selector is None: + traced.pop('X2W_MESH86_WRITER_TRACE', None) + else: + traced['X2W_MESH86_WRITER_TRACE'] = selector + result = subprocess.run(cmd, env=traced, stderr=subprocess.PIPE, encoding='utf-8', errors='replace') + sys.stderr.write(result.stderr) + if result.returncode: + return result.returncode + trace = [line for line in result.stderr.splitlines() if line.startswith('x2w-mesh86-trace ')] + assert not trace, f'trace selector {selector!r} emitted unexpected rows: {trace!r}' + print(f'trace selector {selector!r}: paired readback passed without trace rows') + return 0 + + def run(dxc, fixture, backend, work, depth_only, lease_xmem=None, mode=None, depth_pixel=None): for suffix, stage in (('ms', 13), ('ps', 0)): (work / f'source.{suffix}.dxbc').write_bytes(source_envelope(stage)) @@ -92,7 +110,7 @@ def run(dxc, fixture, backend, work, depth_only, lease_xmem=None, mode=None, dep environment['X2W_MESH86_FIXTURE_LOOSE_ROOT'] = '1' elif mode == 'skip-wait': environment['X2W_TEST_MESH_XMEM_SKIP_WAIT'] = '1' - elif mode in ('dual', 'dual-skip-srv', 'dual-skip-argument', 'dual-init-only', 'dual-trace'): + elif mode in ('dual', 'dual-skip-srv', 'dual-skip-argument', 'dual-init-only', 'dual-trace', 'dual-trace-disabled'): environment.update(X2W_MESH86_FIXTURE_DUAL='1', X2W_MESH_INDIRECT_XMEM='1') if mode == 'dual-skip-srv': environment['X2W_TEST_MESH_XMEM_SKIP_SRV_WAIT'] = '1' @@ -134,6 +152,8 @@ def run(dxc, fixture, backend, work, depth_only, lease_xmem=None, mode=None, dep environment['X2W_MESH86_FIXTURE_READY'] = '1' if mode == 'dual-trace': return trace_paired_submission(cmd, environment) + if mode == 'dual-trace-disabled': + return check_trace_disabled(cmd, environment) if lease_xmem or depth_only: return subprocess.run(cmd, env=environment).returncode From 5c823e39da53eaccd94762057b5e0ba3971a4056 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 21:58:29 +0200 Subject: [PATCH 127/232] runtime: add main(argv), atomic --output writes, and directory/error guards in xmem_attribute_scan with CLI suite (#2429) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/xmem_attribute_scan_cli_check.py | 411 +++++++++++++++++++++++++ tools/xmem_attribute_scan.py | 275 +++++++++-------- 3 files changed, 566 insertions(+), 122 deletions(-) create mode 100644 tests/xmem_attribute_scan_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 595e145af..54c873938 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5639,6 +5639,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME xmem_attribute_scan COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/xmem_attribute_scan_check.py" "$" "$") + add_test(NAME xmem_attribute_scan_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/xmem_attribute_scan_cli_check.py") # VEX.128 16-bit packed-integer leaf functions, an arithmetic-shift control, and their C++. foreach(variant IN ITEMS original altered) diff --git a/tests/xmem_attribute_scan_cli_check.py b/tests/xmem_attribute_scan_cli_check.py new file mode 100644 index 000000000..a4b2f97b9 --- /dev/null +++ b/tests/xmem_attribute_scan_cli_check.py @@ -0,0 +1,411 @@ +"""CLI, atomic output, directory/collision, and mutation control suite for tools/xmem_attribute_scan.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +import pefile + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "xmem_attribute_scan.py" +sys.path.insert(0, str(ROOT / "tools")) + +import xmem_attribute_scan as scanner # noqa: E402 + + +BINK_WORD = 0x05E50000 +PHYSICAL_NULL_WORD = 0xE0000000 + + +def _build_synthetic_x64_pe( + *, + word: int = BINK_WORD, + resolved: bool = True, + machine: int = 0x8664, +) -> bytes: + """Build a minimal synthetic x64 PE32+ image importing XMemAlloc from xmem.dll.""" + file_alignment = 0x200 + section_alignment = 0x1000 + headers_size = 0x200 + text_rva = 0x1000 + text_raw = 0x200 + rdata_rva = 0x2000 + rdata_raw = 0x400 + + # .rdata layout at rdata_rva (0x2000): + # +0x00..0x28: 2x IMAGE_IMPORT_DESCRIPTOR (20B each, second is zero terminator) + # +0x28..0x38: ILT (2x 8B) + # +0x38..0x48: IAT (2x 8B) + # +0x48..0x58: b"xmem.dll\0" padded + # +0x58..0x68: IMAGE_IMPORT_BY_NAME (Hint=0, b"XMemAlloc\0") + # +0x68..0x78: RUNTIME_FUNCTION (12B) when resolved=True + # +0x78..0x7c: UNWIND_INFO (4B) + ilt_rva = rdata_rva + 0x28 + iat_rva = rdata_rva + 0x38 + dll_name_rva = rdata_rva + 0x48 + by_name_rva = rdata_rva + 0x58 + pdata_rva = rdata_rva + 0x68 + unwind_rva = rdata_rva + 0x78 + + if resolved: + # mov edx, word (5B) + call [rip+disp32] (6B) + ret (1B) = 12B inside .pdata function. + call_next_rva = text_rva + 5 + 6 + disp = iat_rva - call_next_rva + code = struct.pack(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = scanner.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class XmemAttributeScanCliPositiveTests(unittest.TestCase): + def _assert_report_schema(self, payload: dict, *, image_name: str, expected_sites: int) -> None: + self.assertEqual( + set(payload), + {"format", "image", "imports", "unmatched_xmem_ordinals", "thunks", "sites", "summary", "stats"}, + ) + self.assertEqual(payload["format"], scanner.FORMAT) + self.assertEqual(payload["image"], image_name) + self.assertEqual(payload["imports"], [{"import": "XMemAlloc", "kind": "import"}]) + self.assertEqual(len(payload["sites"]), expected_sites) + self.assertEqual( + set(payload["summary"]), + {"sites", "by_source", "words", "null_words", "sites_not_fully_constant"}, + ) + self.assertEqual(set(payload["stats"]), {"pdata_functions", "instructions_decoded", "passes", "seconds"}) + + def test_stdout_and_atomic_nested_output_json_schema_and_exit_codes(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + clean_pe = root / "clean.exe" + null_pe = root / "null_word.exe" + unresolved_pe = root / "unresolved.exe" + clean_pe.write_bytes(_build_synthetic_x64_pe(word=BINK_WORD, resolved=True)) + null_pe.write_bytes(_build_synthetic_x64_pe(word=PHYSICAL_NULL_WORD, resolved=True)) + unresolved_pe.write_bytes(_build_synthetic_x64_pe(resolved=False)) + + # 1) Stdout JSON mode (exit 0) + both --fail-on-* flags stay 0 on clean image. + for extra in ([], ["--fail-on-null", "--fail-on-unresolved"]): + code, out, err = _run_main([str(clean_pe), *extra]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertIn("clean.exe: 1 sites", err) + report = json.loads(out) + self._assert_report_schema(report, image_name="clean.exe", expected_sites=1) + self.assertEqual(report["summary"]["null_words"], []) + self.assertEqual(report["summary"]["sites_not_fully_constant"], []) + self.assertEqual(report["stats"]["pdata_functions"], 1) + + # 2) Nested --output uses TemporaryDirectory(dir=...) + os.replace() atomically, leaves zero temp dirs. + nested_out = root / "nested" / "reports" / "scan.json" + self.assertFalse(nested_out.parent.exists()) + replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with mock.patch.object(scanner.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(clean_pe), "--output", str(nested_out)]) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(len(replaces), 1) + self.assertEqual([p.name for p in nested_out.parent.iterdir()], ["scan.json"]) + self._assert_report_schema( + json.loads(nested_out.read_text(encoding="utf-8")), + image_name="clean.exe", + expected_sites=1, + ) + + # 3) Gate exit 1 separation: --fail-on-null and --fail-on-unresolved strictly return 1 (not 0 or 2). + for img, flag, expected_code in ( + (null_pe, "--fail-on-null", 1), + (null_pe, "--fail-on-unresolved", 0), + (unresolved_pe, "--fail-on-unresolved", 1), + (unresolved_pe, "--fail-on-null", 0), + ): + with self.subTest(image=img.name, flag=flag): + proc = _run_subprocess(str(img), flag) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self._assert_report_schema( + json.loads(proc.stdout), + image_name=img.name, + expected_sites=1, + ) + + def test_main_forwards_default_sys_argv_and_script_entrypoint(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + pe_path = root / "entry.exe" + out_path = root / "entry.json" + pe_path.write_bytes(_build_synthetic_x64_pe()) + cli_argv = [str(TOOL), str(pe_path), "--output", str(out_path)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self._assert_report_schema(json.loads(out_path.read_text(encoding="utf-8")), + image_name="entry.exe", expected_sites=1) + + out_path.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self._assert_report_schema(json.loads(out_path.read_text(encoding="utf-8")), + image_name="entry.exe", expected_sites=1) + + +class XmemAttributeScanCliNegativeAndMutationTests(unittest.TestCase): + def _assert_exit_2( + self, + argv: list[str], + *, + expected_type: str, + expected_fragment: str, + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(f"{expected_type}: ", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(f"{expected_type}: ", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_missing_directory_and_corrupt_pe_exit_2_without_traceback(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.exe" + self._assert_exit_2([str(missing)], expected_type="FileNotFoundError", expected_fragment=missing.name) + + image_dir = root / "dir.exe" + image_dir.mkdir() + with mock.patch.object(scanner, "scan") as scan_mock: + self._assert_exit_2( + [str(image_dir)], + expected_type="ValueError", + expected_fragment="directory", + check_subprocess=False, + ) + scan_mock.assert_not_called() + proc = _run_subprocess(str(image_dir)) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("ValueError: ", proc.stderr) + self.assertIn("directory", proc.stderr) + + corrupt = root / "corrupt.exe" + corrupt.write_bytes(b"NOT_A_PE_HEADER" * 16) + self._assert_exit_2([str(corrupt)], expected_type="PEFormatError", expected_fragment="corrupt.exe") + + x86_pe = root / "x86.exe" + x86_pe.write_bytes(_build_synthetic_x64_pe(machine=0x014C)) + self._assert_exit_2([str(x86_pe)], expected_type="ValueError", expected_fragment="Expected an x64 image") + + def test_output_directory_rejected_upfront_before_scanning(self) -> None: + # Kills removal of args.output.is_dir() guard (and checks scan is never called). + with TemporaryDirectory() as tmp: + root = Path(tmp) + pe_path = root / "image.exe" + pe_path.write_bytes(_build_synthetic_x64_pe()) + out_dir = root / "existing_out_dir" + out_dir.mkdir() + + argv = [str(pe_path), "--output", str(out_dir)] + with mock.patch.object(scanner, "scan") as scan_mock: + self._assert_exit_2( + argv, + expected_type="ValueError", + expected_fragment="existing directory", + check_subprocess=False, + ) + scan_mock.assert_not_called() + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("ValueError: ", proc.stderr) + self.assertIn("existing directory", proc.stderr) + + def test_output_collision_via_resolve_and_samefile_rejected_upfront(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + + # 1) Non-existent image + alias --output path colliding via resolve() (kills resolve() mutation). + ghost_img = root / "missing.exe" + alias_out = root / "sub" / ".." / "missing.exe" + with mock.patch.object(scanner, "scan") as scan_mock: + self._assert_exit_2( + [str(ghost_img), "--output", str(alias_out)], + expected_type="ValueError", + expected_fragment="collides with image", + ) + scan_mock.assert_not_called() + + # 2) Existing image + hardlink alias where resolve() differs (kills samefile() mutation). + real_img = root / "real.exe" + hardlink_out = sub / "hardlink.exe" + pe_bytes = _build_synthetic_x64_pe() + real_img.write_bytes(pe_bytes) + os.link(real_img, hardlink_out) + self.assertNotEqual(real_img.resolve(), hardlink_out.resolve()) + self.assertTrue(real_img.samefile(hardlink_out)) + + with mock.patch.object(scanner, "scan") as scan_mock: + self._assert_exit_2( + [str(real_img), "--output", str(hardlink_out)], + expected_type="ValueError", + expected_fragment="collides with image", + ) + scan_mock.assert_not_called() + self.assertEqual(real_img.read_bytes(), pe_bytes) + + def test_os_replace_failure_exits_2_and_leaves_zero_temp_dirs_or_partial_files(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + pe_path = root / "image.exe" + pe_path.write_bytes(_build_synthetic_x64_pe()) + out_dir = root / "out" + out_path = out_dir / "report.json" + + # 1) os.replace fails on fresh output -> exit 2, zero output files, zero temp dirs. + def failing_replace(src, dst): + self.assertTrue(Path(src).is_file()) + raise OSError("simulated replace failure") + + with mock.patch.object(scanner.os, "replace", side_effect=failing_replace): + self._assert_exit_2( + [str(pe_path), "--output", str(out_path)], + expected_type="OSError", + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(list(out_dir.iterdir()), []) + + # 2) os.replace fails when replacing existing output -> prior file stays intact, zero temp dirs. + out_path.write_text("prior-report\n", encoding="utf-8") + with mock.patch.object(scanner.os, "replace", side_effect=failing_replace): + self._assert_exit_2( + [str(pe_path), "--output", str(out_path)], + expected_type="OSError", + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(out_path.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual([p.name for p in out_dir.iterdir()], ["report.json"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/xmem_attribute_scan.py b/tools/xmem_attribute_scan.py index eb4373101..1be01b6e8 100644 --- a/tools/xmem_attribute_scan.py +++ b/tools/xmem_attribute_scan.py @@ -46,9 +46,11 @@ import argparse import bisect import json +import os import re import struct import sys +import tempfile import time from collections import Counter from pathlib import Path @@ -138,44 +140,48 @@ def __init__(self, lo, hi, kind, data, start): class Image: def __init__(self, path): self.pe = pefile.PE(str(path), fast_load=True) - d = pefile.DIRECTORY_ENTRY - self.pe.parse_data_directories(directories=[ - d["IMAGE_DIRECTORY_ENTRY_IMPORT"], d["IMAGE_DIRECTORY_ENTRY_EXPORT"], - d["IMAGE_DIRECTORY_ENTRY_EXCEPTION"], d["IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT"]]) - if self.pe.FILE_HEADER.Machine != pefile.MACHINE_TYPE["IMAGE_FILE_MACHINE_AMD64"]: - raise ValueError("Expected an x64 image") - self.base = self.pe.OPTIONAL_HEADER.ImageBase - self.info = InstructionInfoFactory() - self.slots = {} # IAT slot RVA -> (name, "import" or "delay") - self.ordinals = [] # xmem.dll imports by ordinal, which have no name to match - for desc in getattr(self.pe, "DIRECTORY_ENTRY_IMPORT", []): - self._add_imports(desc, "import") - for desc in getattr(self.pe, "DIRECTORY_ENTRY_DELAY_IMPORT", []): - self._add_imports(desc, "delay") - self.sections = [(s.VirtualAddress, s.VirtualAddress + max(s.Misc_VirtualSize, s.SizeOfRawData), - s.Characteristics) for s in self.pe.sections] - self.code = [] - for s in self.pe.sections: - if s.Characteristics & SCN_EXECUTE: - data = s.get_data() - if s.Misc_VirtualSize: - data = data[:s.Misc_VirtualSize] - self.code.append((s.VirtualAddress, data)) - self.functions = [] # (begin, end, chained) - for entry in getattr(self.pe, "DIRECTORY_ENTRY_EXCEPTION", []): - unwind = self.pe.get_data(entry.struct.UnwindData, 1) - chained = bool(unwind and (unwind[0] >> 3) & UNW_FLAG_CHAININFO) - self.functions.append((entry.struct.BeginAddress, entry.struct.EndAddress, chained)) - self.functions.sort() - self.begins = [f[0] for f in self.functions] - self.exports = {sym.address for sym in - getattr(getattr(self.pe, "DIRECTORY_ENTRY_EXPORT", None), "symbols", []) if sym.address} - # Function entries: exports, unchained .pdata starts, and (added while streaming) call targets. - self.entries = set(self.exports) | {b for b, _, chained in self.functions if not chained} - self.thunks = self._find_thunks() - self.regions = {} - self.decoded = 0 - self.passes = 0 + try: + d = pefile.DIRECTORY_ENTRY + self.pe.parse_data_directories(directories=[ + d["IMAGE_DIRECTORY_ENTRY_IMPORT"], d["IMAGE_DIRECTORY_ENTRY_EXPORT"], + d["IMAGE_DIRECTORY_ENTRY_EXCEPTION"], d["IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT"]]) + if self.pe.FILE_HEADER.Machine != pefile.MACHINE_TYPE["IMAGE_FILE_MACHINE_AMD64"]: + raise ValueError("Expected an x64 image") + self.base = self.pe.OPTIONAL_HEADER.ImageBase + self.info = InstructionInfoFactory() + self.slots = {} # IAT slot RVA -> (name, "import" or "delay") + self.ordinals = [] # xmem.dll imports by ordinal, which have no name to match + for desc in getattr(self.pe, "DIRECTORY_ENTRY_IMPORT", []): + self._add_imports(desc, "import") + for desc in getattr(self.pe, "DIRECTORY_ENTRY_DELAY_IMPORT", []): + self._add_imports(desc, "delay") + self.sections = [(s.VirtualAddress, s.VirtualAddress + max(s.Misc_VirtualSize, s.SizeOfRawData), + s.Characteristics) for s in self.pe.sections] + self.code = [] + for s in self.pe.sections: + if s.Characteristics & SCN_EXECUTE: + data = s.get_data() + if s.Misc_VirtualSize: + data = data[:s.Misc_VirtualSize] + self.code.append((s.VirtualAddress, data)) + self.functions = [] # (begin, end, chained) + for entry in getattr(self.pe, "DIRECTORY_ENTRY_EXCEPTION", []): + unwind = self.pe.get_data(entry.struct.UnwindData, 1) + chained = bool(unwind and (unwind[0] >> 3) & UNW_FLAG_CHAININFO) + self.functions.append((entry.struct.BeginAddress, entry.struct.EndAddress, chained)) + self.functions.sort() + self.begins = [f[0] for f in self.functions] + self.exports = {sym.address for sym in + getattr(getattr(self.pe, "DIRECTORY_ENTRY_EXPORT", None), "symbols", []) if sym.address} + # Function entries: exports, unchained .pdata starts, and (added while streaming) call targets. + self.entries = set(self.exports) | {b for b, _, chained in self.functions if not chained} + self.thunks = self._find_thunks() + self.regions = {} + self.decoded = 0 + self.passes = 0 + except Exception: + self.pe.close() + raise def _add_imports(self, desc, kind): name = desc.dll.decode(errors="replace").lower() @@ -505,85 +511,103 @@ def constants(result): def scan(path): started = time.perf_counter() image = Image(path) - work = Scan(image) - found = [] - loads = [] - for instruction in image.stream() if image.slots else (): - op = instruction.mnemonic - if op == M.CALL and instruction.op0_kind == K.NEAR_BRANCH64: - image.entries.add(instruction.near_branch_target) - if op in (M.CALL, M.JMP): - if instruction.is_ip_rel_memory_operand and instruction.ip_rel_memory_address in image.slots \ - and instruction.ip not in image.thunks: - found.append((instruction.ip, image.slots[instruction.ip_rel_memory_address], "slot")) - elif instruction.op0_kind == K.NEAR_BRANCH64 and instruction.near_branch_target in image.thunks: - found.append((instruction.ip, image.thunks[instruction.near_branch_target], "thunk")) - elif op == M.MOV and instruction.op0_kind == K.REGISTER and instruction.is_ip_rel_memory_operand \ - and instruction.ip_rel_memory_address in image.slots: - loads.append((instruction.ip, image.slots[instruction.ip_rel_memory_address])) - # Calls through a register loaded from a slot, before the register changes. - for ip, target in loads: - region = image.region(ip) - n = region.index.get(ip) - if n is None: - continue - register = full(region.ins[n].op0_register) - for instruction in region.ins[n + 1:]: - if instruction.mnemonic in (M.CALL, M.JMP) and instruction.op0_kind == K.REGISTER \ - and full(instruction.op0_register) == register: - found.append((instruction.ip, target, "register")) - break - if instruction.flow_control in STOPS or image.writes(instruction, register): - break - sites = [] - for ip, (name, kind), route in sorted(found): - region = image.region(ip) - n = region.index.get(ip) - attributes = work.resolve(region, n) if n is not None else { - "source": "unknown", "detail": "site not on an instruction boundary of its region"} - transfer = "jmp" if n is not None and region.ins[n].mnemonic == M.JMP else "call" - sites.append({"site": hex(ip), "import": name, "import_kind": kind, "route": route, "transfer": transfer, - "region": f"{region.kind} {hex(region.lo)}", "attributes": attributes}) - # Writer and caller passes; resolving callers can add data queries of their own. - while work.run_queries(): + try: + work = Scan(image) + found = [] + loads = [] + for instruction in image.stream() if image.slots else (): + op = instruction.mnemonic + if op == M.CALL and instruction.op0_kind == K.NEAR_BRANCH64: + image.entries.add(instruction.near_branch_target) + if op in (M.CALL, M.JMP): + if instruction.is_ip_rel_memory_operand and instruction.ip_rel_memory_address in image.slots \ + and instruction.ip not in image.thunks: + found.append((instruction.ip, image.slots[instruction.ip_rel_memory_address], "slot")) + elif instruction.op0_kind == K.NEAR_BRANCH64 and instruction.near_branch_target in image.thunks: + found.append((instruction.ip, image.thunks[instruction.near_branch_target], "thunk")) + elif op == M.MOV and instruction.op0_kind == K.REGISTER and instruction.is_ip_rel_memory_operand \ + and instruction.ip_rel_memory_address in image.slots: + loads.append((instruction.ip, image.slots[instruction.ip_rel_memory_address])) + # Calls through a register loaded from a slot, before the register changes. + for ip, target in loads: + region = image.region(ip) + n = region.index.get(ip) + if n is None: + continue + register = full(region.ins[n].op0_register) + for instruction in region.ins[n + 1:]: + if instruction.mnemonic in (M.CALL, M.JMP) and instruction.op0_kind == K.REGISTER \ + and full(instruction.op0_register) == register: + found.append((instruction.ip, target, "register")) + break + if instruction.flow_control in STOPS or image.writes(instruction, register): + break + sites = [] + for ip, (name, kind), route in sorted(found): + region = image.region(ip) + n = region.index.get(ip) + attributes = work.resolve(region, n) if n is not None else { + "source": "unknown", "detail": "site not on an instruction boundary of its region"} + transfer = "jmp" if n is not None and region.ins[n].mnemonic == M.JMP else "call" + sites.append({"site": hex(ip), "import": name, "import_kind": kind, "route": route, "transfer": transfer, + "region": f"{region.kind} {hex(region.lo)}", "attributes": attributes}) + # Writer and caller passes; resolving callers can add data queries of their own. + while work.run_queries(): + for site in sites: + work.finish(site["attributes"]) + words = {} + by_source = Counter() + unresolved = [] for site in sites: - work.finish(site["attributes"]) - words = {} - by_source = Counter() - unresolved = [] - for site in sites: - annotate(site["attributes"]) - by_source[site["attributes"]["source"]] += 1 - site_words, complete = constants(site["attributes"]) - if not complete: - unresolved.append(site["site"]) - for word in site_words: - entry = words.setdefault(word, {"word_hex": f"0x{word:x}", "desktop": desktop(word), - "fields": decode(word), "sites": []}) - if site["site"] not in entry["sites"]: - entry["sites"].append(site["site"]) - word_list = [words[w] for w in sorted(words)] - return { - "format": FORMAT, - "image": Path(path).name, - "imports": [{"import": n, "kind": k} for n, k in sorted(set(image.slots.values()))], - "unmatched_xmem_ordinals": image.ordinals, - "thunks": [{"thunk": hex(ip), "import": name, "exported": ip in image.exports} - for ip, (name, _) in sorted(image.thunks.items())], - "sites": sites, - "summary": { - "sites": len(sites), - "by_source": dict(sorted(by_source.items())), - "words": word_list, - "null_words": [w["word_hex"] for w in word_list if w["desktop"].startswith("null")], - "sites_not_fully_constant": unresolved, - }, - "stats": {"pdata_functions": len(image.functions), "instructions_decoded": image.decoded, - "passes": image.passes, "seconds": round(time.perf_counter() - started, 3)}, - } + annotate(site["attributes"]) + by_source[site["attributes"]["source"]] += 1 + site_words, complete = constants(site["attributes"]) + if not complete: + unresolved.append(site["site"]) + for word in site_words: + entry = words.setdefault(word, {"word_hex": f"0x{word:x}", "desktop": desktop(word), + "fields": decode(word), "sites": []}) + if site["site"] not in entry["sites"]: + entry["sites"].append(site["site"]) + word_list = [words[w] for w in sorted(words)] + return { + "format": FORMAT, + "image": Path(path).name, + "imports": [{"import": n, "kind": k} for n, k in sorted(set(image.slots.values()))], + "unmatched_xmem_ordinals": image.ordinals, + "thunks": [{"thunk": hex(ip), "import": name, "exported": ip in image.exports} + for ip, (name, _) in sorted(image.thunks.items())], + "sites": sites, + "summary": { + "sites": len(sites), + "by_source": dict(sorted(by_source.items())), + "words": word_list, + "null_words": [w["word_hex"] for w in word_list if w["desktop"].startswith("null")], + "sites_not_fully_constant": unresolved, + }, + "stats": {"pdata_functions": len(image.functions), "instructions_decoded": image.decoded, + "passes": image.passes, "seconds": round(time.perf_counter() - started, 3)}, + } + finally: + image.pe.close() + + +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + +def _atomic_write_text(destination: Path, payload: str) -> None: + """Stage JSON output in a sibling temp dir and atomically replace destination.""" + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=destination.parent) as staging_dir: + staged = Path(staging_dir) / destination.name + staged.write_text(payload, encoding="utf-8") + os.replace(staged, destination) -def main(): + +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("image", type=Path) parser.add_argument("--output", type=Path) @@ -591,17 +615,24 @@ def main(): help="exit 1 when a constant word would make era_heap return null") parser.add_argument("--fail-on-unresolved", action="store_true", help="exit 1 when a site has a path that does not end in a constant") - args = parser.parse_args() + args = parser.parse_args(argv) try: + if args.output is not None: + if args.output.exists() and args.output.is_dir(): + raise ValueError(f"Output path is an existing directory: {args.output}") + if _same_path(args.image, args.output): + raise ValueError(f"Output path collides with image: {args.output}") + if args.image.is_dir(): + raise ValueError(f"Image path is a directory: {args.image}") report = scan(args.image) + text = json.dumps(report, indent=2) + if args.output is not None: + _atomic_write_text(args.output, text + "\n") + else: + print(text) except (OSError, ValueError, pefile.PEFormatError) as exc: # Status 1 is reserved for the --fail-on-* gates. - parser.exit(2, f"{args.image}: {exc}\n") - text = json.dumps(report, indent=2) - if args.output: - args.output.write_text(text + "\n", encoding="utf-8") - else: - print(text) + parser.exit(2, f"{type(exc).__name__}: {args.image}: {exc}\n") summary = report["summary"] print(f"{report['image']}: {summary['sites']} sites, {len(summary['words'])} distinct words, " f"{len(summary['null_words'])} null, {len(summary['sites_not_fully_constant'])} not fully constant, " @@ -615,4 +646,4 @@ def main(): if __name__ == "__main__": - sys.exit(main()) + raise SystemExit(main()) From 0e8b8d387f722b6650a81fd29b191503fb406295 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:59:08 -0700 Subject: [PATCH 128/232] d3d12: enable Resource GetDesc at slot 10 (#2473) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 10 ++ src/startup_stubs/d3d12_xs_device.cpp | 12 ++- tests/startup_resource_desc.cpp | 150 ++++++++++++++++++++++++++ 3 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 tests/startup_resource_desc.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 54c873938..23a9bbe33 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1501,6 +1501,16 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +# Resource slot 10: GetDesc on console resource wrappers. +add_executable(startup_resource_desc tests/startup_resource_desc.cpp) +target_compile_features(startup_resource_desc PRIVATE cxx_std_17) +target_link_libraries(startup_resource_desc PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_resource_desc_${backend} COMMAND startup_resource_desc ${backend}) + set_tests_properties(startup_resource_desc_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() + add_executable(startup_nv12_draw tests/startup_nv12_draw.cpp tests/desktop_gpu.cpp) target_compile_features(startup_nv12_draw PRIVATE cxx_std_17) target_include_directories(startup_nv12_draw PRIVATE src) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 932983b5f..fb0db80ee 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3733,7 +3733,15 @@ void* __stdcall resource_get_desc(void* a, void* b) { void* result = nullptr; Wrapper* self = receiver(a, b, &result, "Resource::GetDesc(no receiver)"); + if (!self || !self->own().real || !result) return result; *static_cast(result) = static_cast(self->own().real)->GetDesc(); + static LONG logged; + if (first_calls(logged, 4)) { + const auto& d = *static_cast(result); + log("x2w-d3d12 Resource::GetDesc res=%p dim=%d fmt=%d size=%llux%ux%u mips=%u layout=0x%x flags=0x%x", + static_cast(self), d.Dimension, d.Format, static_cast(d.Width), + d.Height, d.DepthOrArraySize, d.MipLevels, d.Layout, d.Flags); + } return result; } @@ -5626,10 +5634,10 @@ void build_tables() // Resource: Map, Unmap, GetDesc, GetGPUVirtualAddress, Write/ReadFromSubresource, GetHeapProperties. tables[resource_kind][8] = reinterpret_cast(&resource_map); tables[resource_kind][9] = reinterpret_cast(&resource_unmap); + tables[resource_kind][10] = reinterpret_cast(&resource_get_desc); tables[resource_kind][11] = reinterpret_cast(&resource_gpu_address); - // Desktop Resource 10 (GetDesc), 12-14, Heap 8 and DescriptorHeap 8 (GetDesc, struct returns) are + // Desktop Resource 12-14, Heap 8 and DescriptorHeap 8 (GetDesc, struct returns) are // not installed until a call site confirms them: the queue's slot 18 showed what a wrong one does. - (void)&resource_get_desc; (void)&heap_get_desc; (void)&descriptor_heap_get_desc; tables[descriptor_heap_kind][9] = reinterpret_cast(&descriptor_heap_cpu_start); diff --git a/tests/startup_resource_desc.cpp b/tests/startup_resource_desc.cpp new file mode 100644 index 000000000..5c1150abd --- /dev/null +++ b/tests/startup_resource_desc.cpp @@ -0,0 +1,150 @@ +// Resource GetDesc (desktop slot 10) on console resource wrappers. +// +// startup_resource_desc (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe creates committed buffer and texture resources +// and queries their descriptions through ID3D12Resource::GetDesc() (slot 10). +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0, Word g = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f, g); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +std::atomic debug_error_count{0}; +void WINAPI on_message(D3D12_MESSAGE_CATEGORY, D3D12_MESSAGE_SEVERITY severity, D3D12_MESSAGE_ID, LPCSTR text, void*) +{ + if (severity > D3D12_MESSAGE_SEVERITY_ERROR) return; + if (++debug_error_count <= 12) std::printf("debug layer: %.300s\n", text); +} + +struct Probe { + ComPtr desktop; + DWORD cookie = 0; + ComPtr queue1; + bool watch() + { + return SUCCEEDED(desktop.As(&queue1)) && + SUCCEEDED(queue1->RegisterMessageCallback(on_message, D3D12_MESSAGE_CALLBACK_FLAG_NONE, nullptr, &cookie)); + } +}; +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + Probe probe; + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe.desktop)))) return 4; + + if (!probe.watch()) std::printf("no debug layer message callback: validation not counted\n"); + + // 1. Create committed buffer (64 KiB) through the startup device wrapper (slot 27). + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC buffer_desc{ + D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE + }; + void* buffer_res = nullptr; + if (!ok(invoke(device, 27, arg(&heap), D3D12_HEAP_FLAG_NONE, arg(&buffer_desc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&buffer_res)))) + return 5; + + // 2. Create committed texture (128x64 RGBA8) through the startup device wrapper (slot 27). + const D3D12_RESOURCE_DESC tex_desc{ + D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 128, 64, 1, 1, + DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET + }; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + void* tex_res = nullptr; + if (!ok(invoke(device, 27, arg(&heap), D3D12_HEAP_FLAG_NONE, arg(&tex_desc), + D3D12_RESOURCE_STATE_COMMON, arg(&rtv_clear), arg(&__uuidof(ID3D12Resource)), arg(&tex_res)))) + return 6; + + // 3. Query buffer description via ID3D12Resource::GetDesc() virtual call. + auto* cl_buf = static_cast(buffer_res); + const D3D12_RESOURCE_DESC got_buf = cl_buf->GetDesc(); + std::printf("1 buffer desc: dim=%d width=%llu height=%u mips=%u fmt=%d layout=0x%x\n", + got_buf.Dimension, static_cast(got_buf.Width), + got_buf.Height, got_buf.MipLevels, got_buf.Format, got_buf.Layout); + if (got_buf.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || got_buf.Width != 65536 || + got_buf.Height != 1 || got_buf.DepthOrArraySize != 1 || got_buf.MipLevels != 1 || + got_buf.Format != DXGI_FORMAT_UNKNOWN || got_buf.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) + return 10; + + // 4. Query texture description via ID3D12Resource::GetDesc() virtual call. + auto* cl_tex = static_cast(tex_res); + const D3D12_RESOURCE_DESC got_tex = cl_tex->GetDesc(); + std::printf("2 texture desc: dim=%d width=%llu height=%u mips=%u fmt=%d flags=0x%x\n", + got_tex.Dimension, static_cast(got_tex.Width), + got_tex.Height, got_tex.MipLevels, got_tex.Format, got_tex.Flags); + if (got_tex.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || got_tex.Width != 128 || + got_tex.Height != 64 || got_tex.DepthOrArraySize != 1 || got_tex.MipLevels != 1 || + got_tex.Format != DXGI_FORMAT_R8G8B8A8_UNORM || got_tex.Flags != D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) + return 11; + + // 5. Query through function pointer with swapped arguments to verify `receiver` handles both ABI orders. + using GetDescSlot = void* (WINAPI*)(void*, void*); + auto get_desc_fn = reinterpret_cast((*static_cast(tex_res))[10]); + D3D12_RESOURCE_DESC swapped{}; + void* ret = get_desc_fn(&swapped, tex_res); + if (ret != &swapped || swapped.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || swapped.Width != 128 || + swapped.Height != 64) + return 12; + + // 6. Negative control: call with null destination pointer returns null without crashing. + void* null_call = get_desc_fn(tex_res, nullptr); + if (null_call != nullptr) return 13; + + // 7. Verify device health and debug layer + const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); + const unsigned long long errors = debug_error_count.load(); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} From 122e86016f0fa930215df2a73f09bc47397d96fd Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 20:59:35 +0100 Subject: [PATCH 129/232] gfx2hlsl: read a joined mask ANDed with exec at an execz branch target (#2466) * startup: read a joined mask ANDed with exec at an execz branch target A lane mask written on the fall-through of a forward s_cbranch_execz and combined with exec by the instruction at the branch target was refused with `numeric use of sN holding joined at a branch target` when the skipping edge still brought a descriptor word or a pointer in that register. On the skipping edge the lane's exec bit is 0, so bit 0 of `S & exec` is 0 and of `S | ~exec` is 1 whatever S holds. `s_and_b64 D, S, exec` (either order) and `s_orn2_b64 D, S, exec` now read S there, in vertex and pixel stages, when every branch into the target is a forward s_cbranch_execz and the fall-through wrote S as a plain run-time number. Every other read of a joined register stays refused: another branch kind or a second edge into the target, an instruction after the target, other operations, a constant on the fall-through, compute stages. Co-Authored-By: Claude Fable 5.2 * tests: evaluate the emitted exec-join statements and pin exec as the destination Co-Authored-By: Claude Fable 5.2 * gfx2hlsl: pin the forward-only, fall-through and compute conditions of the execz join read Review mutations of exec_join survived: the compute exclusion, the fall-through requirement and the forward-only requirement. Add a control for each (a backward s_cbranch_execz, a target with only skipping edges, a compute stage with and without its execz pre-pass). The joined-marker conjuncts were redundant with the plain-variable read and are removed. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 6 + tests/startup_gfx2hlsl_join_symbols_check.py | 139 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 34 ++++- 3 files changed, 178 insertions(+), 1 deletion(-) diff --git a/docs/experiments.md b/docs/experiments.md index 0dd1e0389..6a206cc2d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15050,6 +15050,12 @@ that names one value (a pointer only if no add touched it), is read at run time read before its next write when a path brings a symbol with no run-time value or no definition at all. `startup_gfx2hlsl_join_symbols_check.py` pins the cases; the `join_symbols_folded_*` tests run the old OUTSIDE statement and must give 3, not 11. Controls are pure Python plus a pixel dispatch on WARP and hardware; `binary` reassembles the fixture words with LLVM 15. +One read of such a register is accepted in vertex and pixel stages: `s_and_b64 D, S, exec` (either order) or +`s_orn2_b64 D, S, exec` as the instruction at a target that only forward `s_cbranch_execz` branches and a +fall-through enter, when the fall-through wrote S as a plain run-time number. On a skipping edge the lane's exec bit +is 0, so bit 0 of the result is 0 (1 for `s_orn2_b64`) whatever S holds. This relies on the one-lane model, in which +a lane whose exec bit is 0 takes the branch; it is pure Python only, not run on a GPU, and its words are built from +the field layouts rather than assembled. ## Startup translator: a short operand list is refused, never a translator crash diff --git a/tests/startup_gfx2hlsl_join_symbols_check.py b/tests/startup_gfx2hlsl_join_symbols_check.py index 9a21b0857..8d72a634d 100644 --- a/tests/startup_gfx2hlsl_join_symbols_check.py +++ b/tests/startup_gfx2hlsl_join_symbols_check.py @@ -29,6 +29,13 @@ - CALC: s23 = 1, a proven s_setpc_b64 skips s23 = 2 and lands on the read (a calculated jump is a branch; 1). - LOOP_RFL, JOIN_RFL: v_readfirstlane_b32 of a loop counter, and of a register written on one path of a join (both refused as unproven, never recomputed with a folded constant). +- exec_join(): a lane mask written on the fall-through of a forward s_cbranch_execz and ANDed with exec by the + instruction at the branch target, while the skipping edge still brings a descriptor word. On the skipping edge + the lane's exec bit is 0, so bit 0 of `S & exec` is 0 (and of `S | ~exec` is 1) whatever S holds: these two + forms read the joined register. That a lane whose exec bit is 0 behaves as if it took the branch is the + translator's one-lane model, not something this check proves. The words are built here from the SOP2, SOPP and + VOP3 field layouts and checked against the decoder's text; they are not in SOURCES, so `binary` does not + assemble them. """ import struct import subprocess @@ -249,6 +256,137 @@ def check_controls(): 'on every path are kept; straight-line code still folds') +def sop2(op, dst, src0, src1): + return struct.pack(': IndexError` in the census instead of a @@ -2882,7 +2911,10 @@ def src_sym(t): needed = max((int(i) for i in re.findall(r'\{(\d+)\}', text)), default=-1) + 1 if len(srcs) < needed: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), needed + 1)) - values = [self.u(t) for t in srcs] + absorbed = self.exec_absorbed_source(base, srcs) + if absorbed is not None: + self.used_s.add(reg_range(srcs[absorbed])[1]) + values = [t if i == absorbed else self.u(t) for i, t in enumerate(srcs)] expr = text.format(*values) if shift_add: # carry = bits shifted out of S0, or a wrap of the 32-bit sum; read before the destination is written From be9ad0cb31800cbcd61ace720e7b963bb42162ca Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:00:37 +0100 Subject: [PATCH 130/232] tests: read back s_pack_ll/lh/hh and s_absdiff_i32 on D3D12 WARP and hardware (#2523) Review request on #2512: compile the HLSL that gfx2hlsl emits for each op into one cs_6_0 shader with DXC and run it through offscreen_check --raw-uav-dump. The sources are loaded from the UAV fill pattern and XORed, so DXC cannot fold them; D and, for s_absdiff_i32, SCC are stored and compared with the integer references. Cases: absdiff (0x80000000, 1) and its reverse, (0x7fffffff, 0x80000000) and its reverse, equal sources, 0 and 0xffffffff; packs with the <<16 and 0xffff0000 edges, both orders. The operand region must come back unchanged. Registered as startup_gfx2hlsl_pack_absdiff_dispatch_warp and _hardware (skip 77). AI-assisted. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 6 ++ tests/startup_gfx2hlsl_pack_absdiff_check.py | 88 +++++++++++++++++++- 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 23a9bbe33..0c1965680 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3127,6 +3127,12 @@ if(EXISTS "${INTAKE_PYTHON}") # s_pack_ll_b32_b16, s_pack_lh_b32_b16 and s_absdiff_i32 against an integer reference (#1723). add_test(NAME startup_gfx2hlsl_pack_absdiff COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_absdiff_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_pack_absdiff_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_absdiff_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_pack_absdiff_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with # DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with. find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") diff --git a/tests/startup_gfx2hlsl_pack_absdiff_check.py b/tests/startup_gfx2hlsl_pack_absdiff_check.py index 15a4fd0bd..f3d944b0a 100644 --- a/tests/startup_gfx2hlsl_pack_absdiff_check.py +++ b/tests/startup_gfx2hlsl_pack_absdiff_check.py @@ -10,8 +10,13 @@ s_absdiff_i32: D = |wrap32(S0 - S1)| (INT_MIN stays INT_MIN); SCC = (D != 0) Lane-mask operands of the pack forms and s_absdiff_i32 are refused (the per-lane projection has no whole word to read). + +dispatch also checks translated HLSL by D3D12 UAV readback. """ +import struct +import subprocess import sys +import tempfile from pathlib import Path HERE = Path(__file__).resolve().parent @@ -32,6 +37,82 @@ def signed(x): 's_absdiff_i32': (lambda a, b: abs(signed((a - b) & MASK)) & MASK, True), } +ABSDIFF_CASES = ( + (0x80000000, 1), (1, 0x80000000), + (0x7fffffff, 0x80000000), (0x80000000, 0x7fffffff), + (5, 5), (0, 0), (0xffffffff, 0), (3, 10), +) +PACK_CASES = ( + (0xffffffff, 0xffffffff), (0x0000ffff, 0x0000ffff), + (0xffff0000, 0xffff0000), (0x00010000, 0x0000ffff), + (0x12345678, 0x9abcdef0), (0, 0xffffffff), +) +PACK_CASES += tuple((b, a) for a, b in PACK_CASES if a != b) + + +def dispatch(dxc, runner, adapter, name, cases, updates_scc, directory): + _, stage = C.translate(C.code(name, (3, 1, 2, None))) + # The runner fills the source words. XOR at load time to recover the inputs. + fill = tuple(((i + 1) * 0x9e3779b1 & MASK) | 1 for i in range(2 * len(cases))) + result_width = 1 + int(updates_scc) + lines = ['RWByteAddressBuffer data : register(u0);', '[numthreads(1, 1, 1)]', 'void main() {'] + for i, (a, b) in enumerate(cases): + src_word = 2 * i + dst_byte = 4 * (len(fill) + result_width * i) + lines.extend(( + ' {', + f' uint s1 = data.Load({4 * src_word}) ^ {fill[src_word] ^ a:#010x}u;', + f' uint s2 = data.Load({4 * (src_word + 1)}) ^ {fill[src_word + 1] ^ b:#010x}u;', + ' uint s3;', + ' bool scc = true;', + )) + lines.extend(' ' + line for line in stage.lines) + lines.append(f' data.Store({dst_byte}, s3);') + if updates_scc: + lines.append(f' data.Store({dst_byte + 4}, uint(scc));') + lines.append(' }') + lines.append('}') + + src, cso, output = (directory / (name + suffix) for suffix in ('.hlsl', '.cso', '.bin')) + src.write_text('\n'.join(lines) + '\n', encoding='ascii') + compile_result = subprocess.run([dxc, '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], + stderr=subprocess.PIPE, text=True) + if compile_result.returncode or compile_result.stderr: + raise AssertionError(compile_result.stderr or f'DXC exited with {compile_result.returncode}') + word_count = len(fill) + result_width * len(cases) + # The raw UAV dump takes a size in whole 16-byte rows; the padding words are not read back. + dump_words = (word_count + 3) // 4 * 4 + run = subprocess.run([runner, adapter, '--raw-uav-dump', str(cso), '1', str(4 * dump_words), str(output)], + capture_output=True, text=True) + print(run.stdout, end='') + if run.returncode == 77: + sys.exit(77) + if run.returncode or run.stderr: + raise AssertionError(run.stderr or f'raw UAV dump exited with {run.returncode}') + actual = struct.unpack(f'<{dump_words}I', output.read_bytes()) + assert actual[:len(fill)] == fill, f'{name}: operand region changed' + return actual[len(fill):word_count] + + +def check_dispatch(dxc, runner, adapter): + runner = str(Path(runner).resolve()) + out = HERE.parent / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + for name, (reference, updates_scc) in REFERENCES.items(): + cases = ABSDIFF_CASES if name == 's_absdiff_i32' else PACK_CASES + actual = dispatch(dxc, runner, adapter, name, cases, updates_scc, Path(tmp)) + width = 1 + int(updates_scc) + for i, (a, b) in enumerate(cases): + result = reference(a, b) + want = (result, int(result != 0)) if updates_scc else (result,) + got = actual[i * width:(i + 1) * width] + label = f'{name} {a:#010x}, {b:#010x}' + detail = f'got {tuple(map(hex, got))}, want {tuple(map(hex, want))}' + C.check(f'{label}: {detail}', got == want) + if C.failures: + sys.exit(1) + def main(): for name, (reference, scc) in REFERENCES.items(): @@ -64,4 +145,9 @@ def main(): if __name__ == '__main__': - main() + if len(sys.argv) == 1: + main() + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) + else: + sys.exit(__doc__) From 258e8bfe5db0465b2adc52f9b3ec4065f0c496df Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:01:15 +0100 Subject: [PATCH 131/232] gfx2hlsl: keep a scalar constant across a branch target when its write dominates (#2460) * startup: lower scalar complements whose sources are all lane masks s_nand_b32, s_nor_b32 and s_xnor_b32 were refused whenever an operand was a lane mask. Bit i of ~(S0 op S1) depends only on bit i of each source, so with every source a lane mask (vcc_lo, exec_lo or an SGPR holding a compare mask) and an SGPR destination the lane's bit of the result is exact. SCC is (the whole complemented word != 0), which the bits of the other lanes decide. It is not emitted: the write is recorded as an SCC effect that is not modelled, and the existing stale-SCC scan refuses a program that can read it before the next SCC write, through joins and back edges. The mask mark follows program order. At a branch target a marked SGPR stays proven only if its last write dominates the target and no block on a path from that write to the target writes it again; a complement on any other marked SGPR is refused until the register is written again. A mask mixed with a plain word or a constant, and a vcc_lo, exec_lo or m0 destination, stay refused. Co-Authored-By: Claude Fable 5.2 * startup: keep a scalar constant across a branch target when its write dominates At a branch target the translator drops every scalar constant whose register is in the target's joined set. That set also holds the writes of every earlier block that is off the dominator chain, so a register used inside an earlier conditional block and then set to a constant on every path lost the constant at each later join. A constant sampler built from s_movk_i32, s_bfm_b32 and s_mov_b64 then reached the image instruction as four plain words and was refused as a descriptor operand without a symbol. The constant is now dropped only when it is not proven by its own write: the block of the register's last write must dominate the target and no block on a path from that write to the target may write the register again (the rule the lane-mask complement uses for mask marks, now shared as Stage.unjoined). A later arm or a loop body that writes the register still drops it. Co-Authored-By: Claude Fable 5.2 * gfx2hlsl: drop the unreachable target guard in Stage.unjoined Both callers pass the offset of an instruction in self.ins, and the flow index is built from the same list, so the target is always in index. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .../startup_gfx2hlsl_loop_constants_check.py | 40 ++++++++++++++++++- .../startup_gfx2hlsl_sop2_complement_check.py | 6 +-- tools/startup/gfx2hlsl.py | 28 +++++++------ 3 files changed, 56 insertions(+), 18 deletions(-) diff --git a/tests/startup_gfx2hlsl_loop_constants_check.py b/tests/startup_gfx2hlsl_loop_constants_check.py index 353307417..b652996b9 100644 --- a/tests/startup_gfx2hlsl_loop_constants_check.py +++ b/tests/startup_gfx2hlsl_loop_constants_check.py @@ -11,8 +11,14 @@ A constant that no other path writes stays folded (control). Folding the counter froze it at 1, so the exit test fired only for a trip count of 1 and every other loop ran until the dispatcher guard (65,536 iterations). -Mutations (each must turn the battery red): constants kept at every join (the behavior before this check), and -the loop body range left out (only forward branches handled). +"No other path writes the register" is judged from the constant's own write: the constant stays known at a branch +target when the block of that write dominates the target and no block on a path from the write to the target writes +the register again. A write in an earlier arm, before the constant was set, does not count (a register reused for a +constant sampler word after an earlier conditional block used it for something else). A later arm or a loop body +that writes it still drops it. + +Mutation (must turn the battery red): constants kept at every join (the behavior before this check). Leaving the +loop body range out of join_writes alone does not: the joined set and the dominance rule see the loop body too. """ import os import sys @@ -67,6 +73,36 @@ def run(*instructions): 's_endpgm'), ['s8 = 0x00000003u + 0x00000001u;', 's14 = s14 + 0x00000001u;'], ['s8 = s7 + 0x00000001u;']), + # An earlier arm writes s7, then every path sets it to 3; the second conditional block does not write it. + ('constant set after an earlier arm wrote the register', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_cmp_eq_u32 s2, 1', + 's_cbranch_scc1 label_001c', 's_mov_b32 s9, 1', 's_add_u32 s8, s7, 1', 's_endpgm'), + ['s8 = 0x00000003u + 0x00000001u;'], + ['s8 = s7 + 0x00000001u;']), + # The same program with the second arm writing s7: two values reach the join. + ('constant set after an earlier arm, later arm writes it', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_cmp_eq_u32 s2, 1', + 's_cbranch_scc1 label_001c', 's_mov_b32 s7, 9', 's_add_u32 s8, s7, 1', 's_endpgm'), + ['s8 = s7 + 0x00000001u;'], + ['s8 = 0x00000003u + 0x00000001u;', 's8 = 0x00000009u + 0x00000001u;']), + # The constant is set in an arm only: its write does not dominate the join, whatever the arm before it did. + ('constant set in an arm after an earlier arm wrote the register', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_cmp_eq_u32 s2, 1', + 's_cbranch_scc1 label_0018', 's_mov_b32 s7, 3', 's_add_u32 s8, s7, 1', 's_endpgm'), + ['s8 = s7 + 0x00000001u;'], + ['s8 = 0x00000003u + 0x00000001u;', 's8 = 0x00000005u + 0x00000001u;']), + # An earlier arm writes s7, every path sets it to 3, and a loop reads it: kept when the body leaves it alone, + # dropped when the body writes it after the read. + ('constant set after an earlier arm, read in a loop', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_add_u32 s8, s7, 1', + 's_cmp_eq_u32 s8, s2', 's_cbranch_scc0 label_0010', 's_endpgm'), + ['s8 = 0x00000003u + 0x00000001u;'], + ['s8 = s7 + 0x00000001u;']), + ('constant set after an earlier arm, written in the loop', + ('s_cmp_eq_u32 s2, 0', 's_cbranch_scc1 label_000c', 's_mov_b32 s7, 5', 's_mov_b32 s7, 3', 's_add_u32 s8, s7, 1', + 's_mov_b32 s7, 4', 's_cmp_eq_u32 s8, s2', 's_cbranch_scc0 label_0010', 's_endpgm'), + ['s8 = s7 + 0x00000001u;'], + ['s8 = 0x00000003u + 0x00000001u;', 's8 = 0x00000004u + 0x00000001u;']), ] for label, program, wanted, unwanted in CASES: diff --git a/tests/startup_gfx2hlsl_sop2_complement_check.py b/tests/startup_gfx2hlsl_sop2_complement_check.py index 6c1b7de02..6a4394bb9 100644 --- a/tests/startup_gfx2hlsl_sop2_complement_check.py +++ b/tests/startup_gfx2hlsl_sop2_complement_check.py @@ -339,12 +339,12 @@ def lane_mask_controls(): check('an overwritten mask is a plain word: refused', got == 's_nand_b32 on a lane mask', got) # 5. Mutations: each rule disabled accepts a program refused above. - saved = G.Stage.unjoined_masks - G.Stage.unjoined_masks = lambda self, target, last_write: set() + saved = G.Stage.unjoined + G.Stage.unjoined = lambda self, target, last_write, regs: set() try: got = [text_refusal(*skip, 's_nand_b32 s6, s5, s4', 's_endpgm'), text_refusal(*loop)] finally: - G.Stage.unjoined_masks = saved + G.Stage.unjoined = saved check('mutation without the join rule accepts both programs', all(t.startswith('accepted') for t in got), str(got)) saved = G.Stage.descriptor_scc_reads G.Stage.descriptor_scc_reads = lambda self, branches, effects: iter(()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index d31e9e4ad..dcfdf2ab1 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1972,13 +1972,12 @@ def joined_registers(self, with_cfg=False): self.flow = (index, block_of, succ, dom, writes, {}) return joined, forward_splits, div_targets - def unjoined_masks(self, target, last_write): - """Marked SGPRs whose mark is not proven at a branch target. self.masks follows program order, so a mark - holds on every path into the target only if the block of the register's last write dominates the target and - no block on a path from that write to the target writes the register again.""" + def unjoined(self, target, last_write, regs): + """The registers of regs whose program-order state is not proven at a branch target. A lane-mask mark or a + constant follows program order, so it holds on every path into the target only if the block of the register's + last write dominates the target and no block on a path from that write to the target writes the register + again.""" index, block_of, succ, dom, writes, reached = self.flow - if target not in index: - return set(self.masks) def after(block): # blocks reached from block over at least one edge if block not in reached: seen, todo = set(), list(succ[block]) @@ -1992,7 +1991,7 @@ def after(block): # blocks reached from block over at least one edge t = block_of[index[target]] into = {b for b in range(len(succ)) if t in after(b)} out = set() - for reg in self.masks: + for reg in regs: w = block_of[index[last_write[reg]]] if reg in last_write else 0 if w not in dom[t] or any(reg in writes[b] for b in (after(w) & into) - {w}): out.add(reg) @@ -2054,7 +2053,7 @@ def translate(self): self.exec_known = init_exec_known self.wqm_exec = init_wqm_exec self.masks = set(init_masks) - self.join_masks = set() # marked SGPRs whose mark is not proven on every path (unjoined_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 self.attrs = dict(init_attrs) self.used_s, self.used_v = set(init_used_s), set(init_used_v) @@ -2139,7 +2138,7 @@ def translate(self): reg for reg in here if falls and off in execz_targets and reg in arriving[0][1] and arriving[0][0][reg] is None}) clobber = here if off in joined else every_sgpr - self.join_masks |= self.unjoined_masks(off, last_write) + self.join_masks |= self.unjoined(off, last_write, self.masks) fwd_clobber = forward_splits.get(off, clobber) blocked = force_unproven | force_at.get(off, set()) kept_u = { @@ -2152,9 +2151,12 @@ def translate(self): # A constant is only known here if no other path into the join writes the register: a loop counter # set before the loop and incremented in it reaches the loop head with a new value on every pass. # set_s also assigns constants at run time, so the register reads its real value once it is dropped. - for reg in join_writes.get(off, ()) | (clobber & every_sgpr): - if (self.sym.get(reg) or ('',))[0] == 'const': - del self.sym[reg] + # clobber also holds the writes of every earlier block off the dominator chain; a constant written + # after those, by a block every path runs, with no later write on any path, is still known. + consts = {reg for reg in join_writes.get(off, set()) | (clobber & every_sgpr) + if (self.sym.get(reg) or ('',))[0] == 'const'} + for reg in self.unjoined(off, last_write, consts): + del self.sym[reg] self.defined_uniform_s = set(kept_u) | { k for k, v in self.sym.items() if isinstance(k, int) and v and ( @@ -2178,7 +2180,7 @@ def translate(self): falls = name not in ('s_branch', 's_setpc_b64', 's_endpgm') dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests - last_write.update(dict.fromkeys(dests, off)) + last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) try: if off in refused: raise Unsupported(refused[off]) From 1ff74487068cac2feef645fcfb55e7a9984401b8 Mon Sep 17 00:00:00 2001 From: KelboLive <168463230+KelboLive@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:02:49 -0500 Subject: [PATCH 132/232] name stale fixture DLL on missing export (#2501) * PR #1922: name stale fixture DLL on missing export * tests: name missing x87 exports in both fixture entry paths --------- Co-authored-by: Kelbo Co-authored-by: Royoo <3230853833@qq.com> --- tests/cpu/x87_add.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/tests/cpu/x87_add.py b/tests/cpu/x87_add.py index 134dfcbf0..8a82207bb 100644 --- a/tests/cpu/x87_add.py +++ b/tests/cpu/x87_add.py @@ -369,19 +369,17 @@ def __init__(self, harness_path, path): self.call.argtypes, self.call.restype = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p], ctypes.c_uint64 self.seeded = self.harness.x87_seeded self.seeded.argtypes, self.seeded.restype = [ctypes.c_void_p] * 4, ctypes.c_uint64 - self.lib = ctypes.CDLL(str(Path(path).resolve())) self.path = Path(path).resolve() + self.lib = ctypes.CDLL(str(self.path)) def export(self, name): - """The fixture export `name`, or a message that names the stale DLL.""" + """The fixture export `name`, or a diagnostic naming the DLL.""" try: return getattr(self.lib, name) except AttributeError: - # A partial build leaves the variants at their previous revision, so the newest - # export can be missing from one of them. Say which file and what to rebuild. raise AssertionError( - f"{self.path.name} has no export {name!r}: this fixture DLL predates the export. " - f"Rebuild the target that produces {self.path.name} before running this check." + f"{self.path.name} has no export {name!r}. " + "Rebuild the fixture target and verify that it exports this symbol." ) from None def _buffers(self, data): @@ -410,7 +408,7 @@ def with_live_value(self, harness, name, data): m80_bytes(SEED_VALUE)[:10] + b"\0" * 6 + SEED_CONTROL.to_bytes(2, "little") + b"\0" * 62) io = (ctypes.c_uint64 * 2)(ctypes.addressof(source) + GUARD, ctypes.addressof(target) + GUARD) state = self.seeded(ctypes.cast(getattr(self.harness, harness), ctypes.c_void_p).value, - ctypes.cast(getattr(self.lib, name), ctypes.c_void_p).value, + ctypes.cast(self.export(name), ctypes.c_void_p).value, ctypes.addressof(io), ctypes.addressof(probe)) return self._output(name, data, guard, source, target), state, bytes(probe[32:42]), bytes(probe[48:76]) From a678260495806728f30e5838c575a1e7083de320 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:03:54 +0100 Subject: [PATCH 133/232] startup: give formatted buffer loads the word 3 of title-created typed views; add xyzw (#2418) Builds on the descriptor-word-3 lowering of buffer_load_format_x/xy/xyz. A typed buffer view the title creates through the runtime leaves no hardware descriptor, so the draw passed word 3 as 0 and the loads read zeros. The draw now builds FORMAT from the view's DXGI format (the fourteen formats the translation's switch decodes) and DST_SEL from its component mapping (src/startup_stubs/buffer_format_word3.h). A translated formatted load without a resolved word 3 refuses the draw instead of reading zeros: no descriptor or typed view, an unreadable entry, an undecoded view format or hardware FORMAT, an invalid mapping or reserved DST_SEL, or a buffer past the 16 MiB copy. Each refusal is logged with its reason and counted in the render totals. buffer_load_format_xyzw uses the same switch with four registers. Tests: the DXGI table against the translation's codes (pure Python, with a wrong-code control), the word builder and its refusals (with a mapping-ignored control), three xyzw device cases in the vertex-fetch readback, and a translated pixel stage reading eight title-created views bit for bit into an R32G32B32A32_FLOAT target. Co-authored-by: Claude Fable 5.2 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 14 ++ docs/experiments.md | 31 +++- src/startup_stubs/buffer_format_word3.h | 72 ++++++++++ src/startup_stubs/d3d12_draw.inl | 34 ++++- src/startup_stubs/d3d12_xs_device.cpp | 5 +- tests/startup_address_srv.cpp | 35 +++++ tests/startup_buffer_address_check.py | 19 ++- tests/startup_buffer_format_word3_check.cpp | 97 +++++++++++++ ...startup_buffer_format_word3_table_check.py | 55 ++++++++ tests/startup_formatted_view_draw_check.py | 132 ++++++++++++++++++ tests/startup_stream_consumer.cpp | 3 +- tests/startup_stream_draw.cpp | 3 + tests/startup_vertex_fetch_formats_check.py | 32 +++-- tools/startup/gfx2hlsl.py | 12 +- 16 files changed, 515 insertions(+), 31 deletions(-) create mode 100644 src/startup_stubs/buffer_format_word3.h create mode 100644 tests/startup_buffer_format_word3_check.cpp create mode 100644 tests/startup_buffer_format_word3_table_check.py create mode 100644 tests/startup_formatted_view_draw_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index d5ca03ed1..d62cf5f7a 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -287,6 +287,7 @@ jobs: tests/startup_gfx2hlsl_scalar_brev_fold_check.py \ tests/startup_inline_sampler_check.py \ tests/startup_buffer_address_check.py \ + tests/startup_buffer_format_word3_table_check.py \ tests/startup_smem_address_check.py \ tests/startup_stream_fetch_check.py \ tests/startup_stream_interface_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 7c4722b39..138a3ee0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -206,6 +206,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_root_check.py ./out/pe-env/bin/python -B tests/startup_inline_sampler_check.py ./out/pe-env/bin/python -B tests/startup_buffer_address_check.py +./out/pe-env/bin/python -B tests/startup_buffer_format_word3_table_check.py ./out/pe-env/bin/python -B tests/startup_smem_address_check.py ./out/pe-env/bin/python -B tests/startup_stream_fetch_check.py ./out/pe-env/bin/python -B tests/startup_stream_interface_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 0c1965680..cb3be24bf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1877,6 +1877,13 @@ add_executable(startup_memory_srv_buffer_check tests/startup_memory_srv_buffer_c target_include_directories(startup_memory_srv_buffer_check PRIVATE src) target_compile_features(startup_memory_srv_buffer_check PRIVATE cxx_std_17) add_test(NAME startup_memory_srv_buffer COMMAND startup_memory_srv_buffer_check) +# Descriptor word 3 for formatted buffer loads (src/startup_stubs/buffer_format_word3.h); the mutated run must fail. +add_executable(startup_buffer_format_word3_check tests/startup_buffer_format_word3_check.cpp) +target_include_directories(startup_buffer_format_word3_check PRIVATE src) +target_compile_features(startup_buffer_format_word3_check PRIVATE cxx_std_17) +add_test(NAME startup_buffer_format_word3 COMMAND startup_buffer_format_word3_check) +add_test(NAME startup_buffer_format_word3_mapping_control COMMAND startup_buffer_format_word3_check --mutate mapping) +set_tests_properties(startup_buffer_format_word3_mapping_control PROPERTIES WILL_FAIL TRUE) foreach(mutation IN ITEMS height exact-fit first-32) add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) @@ -3112,6 +3119,9 @@ if(EXISTS "${INTAKE_PYTHON}") # A typed buffer load of BUF_FMT_16_16_16_16_FLOAT reads four halves from one 8-byte element (#1695). add_test(NAME startup_gfx2hlsl_tbuffer_16f COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_tbuffer_16f_check.py") + # The draw's DXGI -> FORMAT table for typed views read by buffer_load_format_* matches the translation's switch. + add_test(NAME startup_buffer_format_word3_table COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_buffer_format_word3_table_check.py") # 32-bit scalar complement logic: s_nand_b32, s_nor_b32 and s_xnor_b32 against an integer reference (#1919). add_test(NAME startup_gfx2hlsl_sop2_complement COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sop2_complement_check.py") @@ -3677,6 +3687,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_requests_check.py" "$" "${backend}") set_tests_properties(startup_indirect_requests_${backend} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_formatted_view_draw_${backend} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_formatted_view_draw_check.py" + "$" "${backend}" "${STARTUP_FXC}") + set_tests_properties(startup_formatted_view_draw_${backend} PROPERTIES TIMEOUT 240 SKIP_RETURN_CODE 77) add_test(NAME startup_packed_target_draw_${backend} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_packed_target_draw_check.py" "$" "${DXC_EXECUTABLE}" "${backend}") diff --git a/docs/experiments.md b/docs/experiments.md index 6a206cc2d..467948493 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -377,11 +377,40 @@ ctest --preset dev --no-tests=error -R '^startup_vertex_fetch_formats_(controls| `BUF_FMT_16_16_SNORM` (format 24, DXGI `R16G16_SNORM` 37) sign-extends each half, divides by 32767 and clamps to -1.0, so -32768 and -32767 both give -1.0 (the Direct3D and Vulkan SNORM rule, as in LLVM 15 and Mesa `ac_formats`). The device run compares `round(v * 32767)` against the same byte decode, with a wrong reference that reads the halves unsigned and a mutated translation that does the same. The pattern the harness writes to t0 holds no 0x8000, so `startup_vertex_fetch_formats_controls` also evaluates the emitted expressions on 0x8000, 0x8001, 0x7fff, 0x0000, 0xffff and 0x4000 in each half, and four wrong forms (unsigned read, no clamp, divisor 32768, one half for both) must fail that check. The D3D12 draw has not been run on Linux. -`buffer_load_format_x`, `_xy` and `_xyz` (MUBUF) use FORMAT (word 3 bits 12 to 18) and DST_SEL (bits 0 to 11) from the buffer descriptor. The draw snapshots the hardware table descriptor and provides word 3 as `udsrc descword3 `. It refuses missing hardware descriptor metadata, unsupported FORMAT codes and unresolved buffer ranges before submitting the draw. The shader decodes using the same expressions as the tbuffer path. Selectors 4 to 7 choose x, y, z and w, while selectors 0 and 1 choose constants 0 and 1. For a load after a branch, the vertex or pixel shader must load all four descriptor words in the same basic block as the use. The root table pointer must reach the load or its local pointer copy without any intervening write along the control-flow predecessors. It refuses rewritten descriptor words and the four-component `buffer_load_format_xyzw` form. `startup_vertex_fetch_formats_*` covers twelve formats, component swizzles, integer 1 and mutations that must differ on readback. `startup_mubuf_descriptor_*` draws with the real binding path on WARP and hardware. Missing metadata, unsupported FORMAT and unresolved backing leave the target blue, while valid zero and one draw black and red. +`buffer_load_format_x`, `_xy`, `_xyz` and `_xyzw` (MUBUF) use FORMAT (word 3 bits 12 to 18) and DST_SEL (bits 0 to 11) from the buffer descriptor. The draw snapshots the hardware table descriptor and provides word 3 as `udsrc descword3 `. It refuses missing hardware descriptor metadata, unsupported FORMAT codes and unresolved buffer ranges before submitting the draw. The shader decodes using the same expressions as the tbuffer path. Selectors 4 to 7 choose x, y, z and w, while selectors 0 and 1 choose constants 0 and 1. For a load after a branch, the vertex or pixel shader must load all four descriptor words in the same basic block as the use. The root table pointer must reach the load or its local pointer copy without any intervening write along the control-flow predecessors. It refuses rewritten descriptor words. `startup_vertex_fetch_formats_*` covers twelve formats, component swizzles, integer 1 and mutations that must differ on readback, plus three `buffer_load_format_xyzw` device cases (identity, a two-channel format whose z and w are the defaults 0 and 1, and the word (w, 1, 0, x)), each of which must also fail through the xyz translation of the same load. `startup_mubuf_descriptor_*` draws with the real binding path on WARP and hardware. Missing metadata, unsupported FORMAT and unresolved backing leave the target blue, while valid zero and one draw black and red. `BUF_FMT_8_8_8_8_UINT` (gfx10 format 60, DXGI `R8G8B8A8_UINT` 30) reads four unsigned bytes into X, Y, Z and W in increasing address order. With stride 5 and byte offset 3, the 16-vertex fixture visits all four dword alignments. On WARP, all 64 component words matched the byte reference. Swapping channels in the reference or normalizing the green byte in the generated shader each triggered a mismatch. `BUF_FMT_16_16_UINT` (gfx10 format 27; LLVM 15 `BUF_DATA_FORMAT_16_16` with `BUF_NUM_FORMAT_UINT`) reads two unsigned 16-bit fields into X and Y, the low half first, with Z = 0 and W = 1. With stride 6 and byte offset 2, the fixture's elements sit at two dword alignments, so half of them cross a dword. On WARP and on an AMD Radeon RX 9070 XT (driver 32.0.32015.7029, Windows 10.0.26300.9974, debug layer enabled), all 64 component words matched the byte reference. The wrong references and three mutated translations each triggered a mismatch: a normalized low half, the high half read from the low half, and a missing W read as 1.0. +A typed buffer view that the title creates through the runtime (`CreateShaderResourceView`, `BUFFER`, no flags, no structure stride) leaves no hardware descriptor in the table. For this case the draw builds word 3 the way the console driver builds it from the view, using `view_word3()` in `src/startup_stubs/buffer_format_word3.h`: + +- FORMAT is the code of the DXGI format whose typed read gives the same components. The 14 formats in the switch are covered: `R8_UNORM` 1, `R8_UINT` 5, `R8G8_UNORM` 14, `R32_FLOAT` 22, `R16G16_UNORM` 23, `R16G16_SNORM` 24, `R16G16_UINT` 27, `R16G16_FLOAT` 29, `R8G8B8A8_UNORM` 56, `R8G8B8A8_UINT` 60, `R32G32_FLOAT` 64, `R16G16B16A16_FLOAT` 71, `R32G32B32_FLOAT` 74 and `R32G32B32A32_FLOAT` 77. The codes are the LLVM 15 `llvm-mc -mcpu=gfx1013` encodings of the tbuffer `format:` operand. +- DST_SEL comes from `Shader4ComponentMapping`: a channel becomes 4 to 7, a forced 0 becomes 0 and a forced 1 becomes 1. + +The draw is refused, not read as zeros, whenever a translated formatted load has no resolved word 3: + +- no hardware descriptor or typed view behind the entry (a raw or structured view, a texture, an unknown token); +- an unreadable descriptor entry; +- a view format or hardware FORMAT the switch has no case for; +- an invalid component mapping or a reserved DST_SEL (2, 3); +- a buffer larger than the 16 MiB copy. + +Each refusal logs `srv : formatted buffer refused ( )` for the first 6 occurrences and counts as `formatted-load draws refused` in the `x2w-render totals` line. Because the shader reads the raw copy at `vindex * stride`, the alignment of the upload ring does not constrain 12-byte formats. + +`startup_buffer_format_word3_table` checks that the DXGI table equals `DESC_FORMAT_CODES`, agrees with `FETCH_DXGI` and with `formatted_buffer_supported()`; a header that gives `R32G32B32A32_FLOAT` code 74 must fail it. `startup_buffer_format_word3` checks words and refusal reasons, and its `mapping` control, which ignores the view mapping, must fail. `startup_formatted_view_draw_{warp,hardware}` draws one source-built pixel stage through the stand-in: `buffer_load_format_xyzw` with `idxen` of element 1 into an `R32G32B32A32_FLOAT` target, compared as four 32-bit words with distinct sentinels per channel. One translation serves every view: + +- `R32G32B32A32_FLOAT` and `R16G16B16A16_FLOAT`; +- `R16G16_FLOAT`, whose z and w must be the defaults 0 and 1.0; +- `R16G16_SNORM` with -32768 and 0, which gives -1.0 and 0; +- `R32G32B32A32_FLOAT` mapped (w, 0, x, 1); +- `R8G8B8A8_UNORM` mapped (z, 1, 0, w). + +An `R32_UINT` view and a raw view must refuse the draw with their reasons, logged once, and leave the clear value. A translation whose W selector reads the Z field must fail. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_(buffer_format_word3|formatted_view_draw_(warp|hardware)|vertex_fetch_formats_)' -V +``` + ### Combined `idxen` + `offen`, scalar `soffset` and MUBUF/MTBUF modifier checks In RDNA 2 MUBUF (`buffer_load_dword*`) and MTBUF (`tbuffer_load_format_*`) instructions, `idxen` and `offen` can be enabled at the same time: `vaddr` is then a two-VGPR pair `v[n:n+1]` holding `(vindex, voffset)`, and the effective byte address is `vindex * stride + voffset + soffset + inst_offset`. `Stage.buffer_address()` in `tools/startup/gfx2hlsl.py` previously used an `if 'idxen' in mods / elif 'offen' in mods` branch, which read `v[n]` as the index and silently dropped `v[n+1]`. It also ignored `tfe`, raised `IndexError` on `lds` (whose disassembly omits `vdata`), and raised `ValueError` when `soffset` named an SGPR or non-integer operand instead of an integer literal. diff --git a/src/startup_stubs/buffer_format_word3.h b/src/startup_stubs/buffer_format_word3.h new file mode 100644 index 000000000..771ec1dd8 --- /dev/null +++ b/src/startup_stubs/buffer_format_word3.h @@ -0,0 +1,72 @@ +// Descriptor word 3 (FORMAT bits 12..18, DST_SEL bits 0..11) for translated buffer_load_format_* loads. +// A hardware buffer descriptor carries the word itself. For a typed buffer view the title created through the +// runtime, the console driver builds it from the view's DXGI format and component mapping; this header does the +// same for the formats the translation decodes. Pure functions, checked by tests/startup_buffer_format_word3_check.cpp. +#pragma once + +#include + +#include "startup_stubs/formatted_buffer.h" + +#include + +namespace x2w_startup { + +// FORMAT codes of tools/startup/gfx2hlsl.py DESC_FORMAT_CODES (gfx10 unified formats, as LLVM 15 encodes the +// tbuffer format: operand) for the DXGI format whose typed read gives the same components; 0 for any other +// format. tests/startup_buffer_format_word3_table_check.py keeps both tables equal. +inline std::uint32_t buffer_format_code(DXGI_FORMAT format) +{ + switch (format) { + case DXGI_FORMAT_R8_UNORM: return 1; + case DXGI_FORMAT_R8_UINT: return 5; + case DXGI_FORMAT_R8G8_UNORM: return 14; + case DXGI_FORMAT_R32_FLOAT: return 22; + case DXGI_FORMAT_R16G16_UNORM: return 23; + case DXGI_FORMAT_R16G16_SNORM: return 24; + case DXGI_FORMAT_R16G16_UINT: return 27; + case DXGI_FORMAT_R16G16_FLOAT: return 29; + case DXGI_FORMAT_R8G8B8A8_UNORM: return 56; + case DXGI_FORMAT_R8G8B8A8_UINT: return 60; + case DXGI_FORMAT_R32G32_FLOAT: return 64; + case DXGI_FORMAT_R16G16B16A16_FLOAT: return 71; + case DXGI_FORMAT_R32G32B32_FLOAT: return 74; + case DXGI_FORMAT_R32G32B32A32_FLOAT: return 77; + default: return 0; + } +} + +// Word 3 for a typed buffer view: DST_SEL 4..7 for channels x..w, 0 and 1 for the forced constants. Returns +// nullptr and sets `word`, or the reason no word can be given (the draw is then refused, not read as zeros). +inline const char* view_word3(const D3D12_SHADER_RESOURCE_VIEW_DESC& view, std::uint32_t& word) +{ + word = 0; + if (view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER || view.Buffer.Flags != D3D12_BUFFER_SRV_FLAG_NONE || + view.Buffer.StructureByteStride != 0) + return "not a typed buffer view"; + const std::uint32_t code = buffer_format_code(view.Format); + if (!code) return "view format has no decoded buffer FORMAT"; + const UINT mapping = view.Shader4ComponentMapping; + if ((mapping >> 12) != 1) return "invalid component mapping"; + std::uint32_t selects = 0; + for (int c = 0; c < 4; ++c) { + const UINT source = (mapping >> (3 * c)) & 7; + if (source > 5) return "invalid component mapping"; + selects |= (source < 4 ? 4 + source : source - 4) << (3 * c); // FORCE_VALUE_0 is 4, FORCE_VALUE_1 is 5 + } + word = code << 12 | selects; + return nullptr; +} + +// A DST_SEL the title wrote in a hardware descriptor: nullptr unless one selector is reserved (2 or 3). The FORMAT is +// checked by formatted_buffer_supported() in formatted_buffer.h. +inline const char* descriptor_word3_refusal(std::uint32_t word) +{ + for (int c = 0; c < 4; ++c) { + const std::uint32_t select = (word >> (3 * c)) & 7; + if (select == 2 || select == 3) return "descriptor DST_SEL reserved value"; + } + return nullptr; +} + +} // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 0c18dcf3d..14a2aff0c 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -79,6 +79,7 @@ SRWLOCK draw_lock = SRWLOCK_INIT; std::unordered_map& translation_by_pipeline() { static std::unordered_map m; return m; } std::unordered_map& translation_by_key() { static std::unordered_map m; return m; } LONG translated_draws, untranslated_draws, translation_ready, translation_missing, null_bindings; +LONG formatted_draws_refused; // draws whose formatted buffer load had no resolved descriptor word 3 (also untranslated) LONG null_by_cause[x2w_local::null_cause_count]; // null_bindings split by cause; the parts add up to it void count_null_binding(x2w_local::NullCause cause) @@ -1819,6 +1820,7 @@ struct FormattedBufferDescriptor { bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedBufferDescriptor (&descriptors)[32]) { const auto refuse = [&](int slot, const char* reason, std::uint32_t detail = 0) { + InterlockedIncrement(&formatted_draws_refused); static LONG refused; if (first_calls(refused, 6)) log("x2w-draw %016llx srv %d: formatted buffer refused (%s %u)", tr.key, slot, reason, detail); @@ -1837,11 +1839,25 @@ bool formatted_buffers_ready(const Translation& tr, const Pass& pass, FormattedB if (!entry || !x2w_local::readable(reinterpret_cast(entry), sizeof(descriptor.words))) return refuse(ud.a, "missing hardware descriptor"); std::memcpy(descriptor.words, reinterpret_cast(entry), sizeof(descriptor.words)); - if (descriptor.words[0] == view_token_magic) - return refuse(ud.a, "missing hardware descriptor"); + if (descriptor.words[0] == view_token_magic) { + // A typed buffer view the title created: the driver builds word 3 from its format and component mapping. + ViewRecord record{}; + AcquireSRWLockShared(¬e_lock); + const bool known = descriptor.words[1] < view_records().size(); + if (known) record = view_records()[descriptor.words[1]]; + ReleaseSRWLockShared(¬e_lock); + if (!known || record.slot != 18 || record.desc_bytes < 40) + return refuse(ud.a, "missing hardware descriptor"); + D3D12_SHADER_RESOURCE_VIEW_DESC view; + std::memcpy(&view, record.desc, 40); + if (const char* reason = x2w_startup::view_word3(view, descriptor.words[3])) return refuse(ud.a, reason); + descriptor.entry = entry; + continue; + } const auto format = x2w_startup::formatted_buffer_code(descriptor.words[3]); if (!x2w_startup::formatted_buffer_supported(format)) return refuse(ud.a, "unsupported FORMAT", format); + if (const char* reason = x2w_startup::descriptor_word3_refusal(descriptor.words[3])) return refuse(ud.a, reason); descriptor.entry = entry; } return true; @@ -2142,7 +2158,18 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI strides[i] = (words[1] >> 16) & 0x3fff; bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; } - if (bytes > (16u << 20)) bytes = 16u << 20; + if (bytes > (16u << 20)) { + bytes = 16u << 20; + // Formatted loads past the copy would read zeros on the desktop; refuse the draw instead. + if (formatted.entry) { + InterlockedIncrement(&formatted_draws_refused); + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-draw %016llx srv %u: formatted buffer refused (buffer larger than the 16 MiB draw copy)", tr->key, i); + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + } // A buffer binding that ends up without a readable range counts as a null binding with its cause. const auto count_buffer = [&](bool bound) { x2w_local::BindingFacts buffer_facts; @@ -2182,6 +2209,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // slot the title leaves empty here; why is not known yet. static const bool identity_for_null = x2w_local::env_on("X2W_DRAW_NULL_IDENTITY"); if (!have && formatted.entry) { + InterlockedIncrement(&formatted_draws_refused); static LONG refused; if (first_calls(refused, 6)) log("x2w-draw %016llx srv %u: formatted buffer refused (unresolved buffer)", tr->key, i); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index fb0db80ee..0c2a5caae 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -43,6 +43,7 @@ #include "startup_stubs/memory_srv_census.h" #include "startup_stubs/memory_srv_as.h" #include "startup_stubs/per_reason_refusal_census.h" +#include "startup_stubs/buffer_format_word3.h" #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" #include "startup_stubs/list_copy.h" @@ -5389,11 +5390,11 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (render_mode() && frame % 300 == 0) log("x2w-render totals: resets %ld (failed %ld), closes %ld, clears %ld, target binds %ld (unresolved %ld), executes %ld, draws %ld (skipped %ld), " "translated draws %ld (not drawn %ld), pipelines translated %ld / missing %ld, null bindings %ld (entry %ld, buffer %ld, token %ld, wrapper %ld, dimension %ld), " - "textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " + "formatted-load draws refused %ld, textures uploaded %ld (%ld KiB, unreadable %ld), heap-indexed roots deferred %ld (real draws refused: view heap %ld, " "sampler heap %ld, both heaps %ld, state %ld), pipelines first looked up by ExecuteIndirect %ld, compute requests published %ld (already present %ld, failed %ld, pointer-like blob qwords %ld)", render_resets, render_reset_failures, render_closes, render_clears, render_target_binds, render_target_unresolved, render_executes, render_draws, render_draws_skipped, translated_draws, untranslated_draws, translation_ready, translation_missing, null_total, - null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], textures_uploaded, + null_causes[0], null_causes[1], null_causes[2], null_causes[3], null_causes[4], formatted_draws_refused, textures_uploaded, texture_bytes_uploaded, textures_unreadable, heap_roots_deferred, heap_root_refusals[static_cast(x2w_startup::RealRootDecision::view_heap_missing)], heap_root_refusals[static_cast(x2w_startup::RealRootDecision::sampler_heap_missing)], diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index d2ab481a6..2e02f53ce 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -415,6 +415,41 @@ void release_placed_vertices(bool done) } } +// X2W_TEST_FORMATTED_VIEW=:::<64 hex bytes>: one typed (or raw) buffer view +// the title creates over a placed buffer holding those bytes, at table entry 0, then one draw. The translated pixel +// shader in tests/startup_formatted_view_draw_check.py reads element 1 through buffer_load_format_xyzw. +int draw_formatted_view(void* guest, void* list) +{ + char spec[256]{}; + if (!GetEnvironmentVariableA("X2W_TEST_FORMATTED_VIEW", spec, sizeof(spec))) return 48; + unsigned format = 0, mapping = 0, raw = 0; + char hex[129]{}; + if (std::sscanf(spec, "%u:%x:%u:%128s", &format, &mapping, &raw, hex) != 4 || std::strlen(hex) != 128) return 48; + static std::array backing{}; + auto* const bytes = reinterpret_cast((ptr(backing.data()) + 0xffff) & ~Word{0xffff}); + for (unsigned i = 0; i < 64; ++i) { + unsigned value = 0; + if (std::sscanf(hex + 2 * i, "%2x", &value) != 1) return 48; + bytes[i] = static_cast(value); + } + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 256; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* placed = nullptr; + if (FAILED(static_cast(invoke(guest, 133, ptr(bytes), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + Word cpu = 0; + if (!bind_view_table(guest, list, cpu)) return 42; + D3D12_SHADER_RESOURCE_VIEW_DESC view{static_cast(format), D3D12_SRV_DIMENSION_BUFFER, mapping}; + view.Buffer.NumElements = 4; + view.Buffer.Flags = raw ? D3D12_BUFFER_SRV_FLAG_RAW : D3D12_BUFFER_SRV_FLAG_NONE; + invoke(guest, 18, ptr(placed), ptr(&view), cpu); + invoke(list, 12, 3, 1); + return 0; +} + int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) { static std::array raw_buf0{}; diff --git a/tests/startup_buffer_address_check.py b/tests/startup_buffer_address_check.py index fcd13238c..6e2ba647e 100644 --- a/tests/startup_buffer_address_check.py +++ b/tests/startup_buffer_address_check.py @@ -18,6 +18,7 @@ """ import os from pathlib import Path +import re import struct import subprocess import sys @@ -219,16 +220,14 @@ def request(load): mnemonic = 'buffer_load_format_' + suffix assert G.decode(load) == [(0, 8, mnemonic, f'{mnemonic} {dest}, off, s[32:35], 0')] result, name = request(load) - if op < 3: - # x, xy and xyz take FORMAT and DST_SEL from descriptor word 3 at draw time. - assert result == 'ok', result - assert 'switch ((ud' in name.with_suffix('.vs.hlsl').read_text() - continue - reason = name.with_suffix('.fail').read_text().strip() - assert reason == f'{mnemonic} requires descriptor FORMAT and DST_SEL', reason - assert result == f'unsupported: {reason}', result - assert classify_shader_reason(reason) == 'buffer_* instruction', reason - assert set(folder.glob(name.name + '.*')) == {name.with_suffix('.fail')} + # All four forms take FORMAT and DST_SEL from descriptor word 3 at draw time, one register per component. + assert result == 'ok', result + source = name.with_suffix('.vs.hlsl').read_text() + assert 'switch ((ud' in source + written = {int(n) for n in re.findall(r'^\s*v(\d+) = ', source, re.M)} & set(range(6, 10)) + assert written == set(range(6, 7 + op)), (mnemonic, written) + # The old refusal text is still classified for caches written by earlier translators. + assert classify_shader_reason('buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL') == 'buffer_* instruction' def controls(): diff --git a/tests/startup_buffer_format_word3_check.cpp b/tests/startup_buffer_format_word3_check.cpp new file mode 100644 index 000000000..8df22b7b4 --- /dev/null +++ b/tests/startup_buffer_format_word3_check.cpp @@ -0,0 +1,97 @@ +// Checks src/startup_stubs/buffer_format_word3.h without a device: the descriptor word 3 built from a title's typed +// buffer view, and the refusals for views and hardware words the translation cannot decode. +// --mutate mapping: expect the identity DST_SEL whatever the view's mapping (a negative control: must fail). +#include "startup_stubs/buffer_format_word3.h" + +#include +#include + +namespace { +int failures; + +void check(const char* name, bool condition) +{ + if (condition) return; + ++failures; + std::printf("FAIL %s\n", name); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC typed(DXGI_FORMAT format, UINT mapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC v{}; + v.Format = format; + v.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + v.Shader4ComponentMapping = mapping; + v.Buffer.NumElements = 4; + return v; +} + +void refused(const char* name, const char* got, const char* expected) +{ + if (got && std::strcmp(got, expected) == 0) return; + ++failures; + std::printf("FAIL %s: \"%s\", expected \"%s\"\n", name, got ? got : "(accepted)", expected); +} +} // namespace + +int main(int argc, char** argv) +{ + const bool ignore_mapping = argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "mapping") == 0; + if (argc != 1 && !ignore_mapping) { + std::printf("usage: startup_buffer_format_word3_check [--mutate mapping]\n"); + return 2; + } + constexpr std::uint32_t identity = 4 | 5 << 3 | 6 << 6 | 7 << 9; + std::uint32_t word = 0; + check("float4 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R32G32B32A32_FLOAT), word) && + word == (77u << 12 | identity)); + check("half2 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R16G16_FLOAT), word) && word == (29u << 12 | identity)); + check("snorm2 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R16G16_SNORM), word) && word == (24u << 12 | identity)); + check("uint8 identity", !x2w_startup::view_word3(typed(DXGI_FORMAT_R8_UINT), word) && word == (5u << 12 | identity)); + // Mapping (w, 0, x, 1): DST_SEL 7, 0, 4, 1. + const UINT swizzle = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(3, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, 0, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1); + const std::uint32_t swizzled = ignore_mapping ? identity : (7u | 0u << 3 | 4u << 6 | 1u << 9); + check("float4 swizzled", !x2w_startup::view_word3(typed(DXGI_FORMAT_R32G32B32A32_FLOAT, swizzle), word) && + word == (77u << 12 | swizzled)); + + // Every decoded DXGI format gives a code the translation decodes; a few others give none. + const DXGI_FORMAT decoded[] = {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R8G8B8A8_UINT}; + for (DXGI_FORMAT f : decoded) { + const std::uint32_t code = x2w_startup::buffer_format_code(f); + if (!code || !x2w_startup::formatted_buffer_supported(code)) { + ++failures; + std::printf("FAIL DXGI format %d: code %u\n", static_cast(f), code); + } + } + + refused("integer 32-bit view", x2w_startup::view_word3(typed(DXGI_FORMAT_R32_UINT), word), "view format has no decoded buffer FORMAT"); + check("refused view leaves word 0", word == 0); + refused("16-bit UNORM 4-channel view", x2w_startup::view_word3(typed(DXGI_FORMAT_R16G16B16A16_UNORM), word), + "view format has no decoded buffer FORMAT"); + refused("sRGB view", x2w_startup::view_word3(typed(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB), word), "view format has no decoded buffer FORMAT"); + auto raw = typed(DXGI_FORMAT_R32_TYPELESS); + raw.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + refused("raw view", x2w_startup::view_word3(raw, word), "not a typed buffer view"); + auto structured = typed(DXGI_FORMAT_UNKNOWN); + structured.Buffer.StructureByteStride = 16; + refused("structured view", x2w_startup::view_word3(structured, word), "not a typed buffer view"); + refused("texture view", x2w_startup::view_word3(D3D12_SHADER_RESOURCE_VIEW_DESC{}, word), "not a typed buffer view"); + refused("selector 6", x2w_startup::view_word3(typed(DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(6, 1, 2, 3)), word), + "invalid component mapping"); + refused("bit 12 missing", x2w_startup::view_word3(typed(DXGI_FORMAT_R32G32B32A32_FLOAT, 0x688), word), "invalid component mapping"); + + check("hardware word decoded", !x2w_startup::descriptor_word3_refusal(77u << 12 | identity)); + check("hardware constants decoded", !x2w_startup::descriptor_word3_refusal(56u << 12 | 1u | 0u << 3 | 4u << 6 | 7u << 9)); + check("hardware format codes", !x2w_startup::formatted_buffer_supported(0) && !x2w_startup::formatted_buffer_supported(2) && + x2w_startup::formatted_buffer_supported(77)); + refused("hardware DST_SEL 3", x2w_startup::descriptor_word3_refusal(77u << 12 | 3u | 5u << 3 | 6u << 6 | 7u << 9), + "descriptor DST_SEL reserved value"); + + if (failures) return 1; + std::printf("startup_buffer_format_word3: all checks passed\n"); + return 0; +} diff --git a/tests/startup_buffer_format_word3_table_check.py b/tests/startup_buffer_format_word3_table_check.py new file mode 100644 index 000000000..c89621218 --- /dev/null +++ b/tests/startup_buffer_format_word3_table_check.py @@ -0,0 +1,55 @@ +"""The stand-in's DXGI -> FORMAT table (src/startup_stubs/buffer_format_word3.h) against tools/startup/gfx2hlsl.py. + +A typed buffer view the title created has no hardware descriptor, so the draw builds word 3 for the translated +buffer_load_format_* switch from the view's DXGI format. Each mapped format must name a FORMAT code the switch +decodes (DESC_FORMAT_CODES), agree with the vertex-fetch table FETCH_DXGI where that has the format, and the +decoded-code list must equal the switch's cases, so a code is never accepted that would read zeros. +""" +from pathlib import Path +import re +import sys + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +import gfx2hlsl # noqa: E402 + +# Public DXGI_FORMAT values (dxgiformat.h) for the names the header uses. +DXGI = {'R32G32B32A32_FLOAT': 2, 'R32G32B32_FLOAT': 6, 'R16G16B16A16_FLOAT': 10, 'R32G32_FLOAT': 16, + 'R8G8B8A8_UNORM': 28, 'R16G16_FLOAT': 34, 'R16G16_UNORM': 35, 'R16G16_UINT': 36, 'R16G16_SNORM': 37, 'R8G8B8A8_UINT': 30, 'R32_FLOAT': 41, + 'R8G8_UNORM': 49, 'R8_UNORM': 61, 'R8_UINT': 62} +# The buffer format each DXGI format reads as: FETCH_DXGI, plus the three formats it does not list. +EXPECTED = {**{dxgi: name for dxgi, (name, _) in gfx2hlsl.FETCH_DXGI.items()}, + 10: 'BUF_FMT_16_16_16_16_FLOAT', 62: 'BUF_FMT_8_UINT', 36: 'BUF_FMT_16_16_UINT'} + + +def main(header=ROOT / 'src' / 'startup_stubs' / 'buffer_format_word3.h'): + text = header.read_text() + code_fn = text[text.index('buffer_format_code('):text.index('view_word3(')] + mapped = {DXGI[n]: int(c) for n, c in re.findall(r'case DXGI_FORMAT_(\w+): return (\d+);', code_fn)} + supported = (ROOT / 'src' / 'startup_stubs' / 'formatted_buffer.h').read_text() + decoded_fn = supported[supported.index('formatted_buffer_supported('):] + decoded = {int(c) for c in re.findall(r'case (\d+):', decoded_fn)} + codes = gfx2hlsl.DESC_FORMAT_CODES + assert decoded == set(codes.values()), sorted(decoded ^ set(codes.values())) + assert set(mapped) == set(EXPECTED), sorted(set(mapped) ^ set(EXPECTED)) + for dxgi, code in mapped.items(): + assert code == codes[EXPECTED[dxgi]], (dxgi, code, EXPECTED[dxgi]) + assert set(EXPECTED.values()) == set(codes), 'every decoded format has a DXGI view format' + return len(mapped) + + +if __name__ == '__main__': + # Negative control: a header that maps R32G32B32A32_FLOAT to 74 (the three-channel code) must fail. + original = (ROOT / 'src' / 'startup_stubs' / 'buffer_format_word3.h').read_text() + import tempfile + with tempfile.TemporaryDirectory() as temp: + wrong = Path(temp) / 'buffer_format_word3.h' + wrong.write_text(original.replace('case DXGI_FORMAT_R32G32B32A32_FLOAT: return 77;', + 'case DXGI_FORMAT_R32G32B32A32_FLOAT: return 74;')) + try: + main(wrong) + except AssertionError: + pass + else: + raise SystemExit('a wrong FORMAT code for R32G32B32A32_FLOAT passed') + print('buffer format word 3 table: %d DXGI formats match the translation' % main()) diff --git a/tests/startup_formatted_view_draw_check.py b/tests/startup_formatted_view_draw_check.py new file mode 100644 index 000000000..cbe3a2d3d --- /dev/null +++ b/tests/startup_formatted_view_draw_check.py @@ -0,0 +1,132 @@ +"""Read typed buffer views the title created through a translated buffer_load_format_xyzw, bit for bit. + +usage: startup_formatted_view_draw_check.py + +A source-built gfx1013 pixel stage loads its descriptor from table entry 0, reads element 1 with +buffer_load_format_xyzw (idxen) and exports the four registers to an R32G32B32A32_FLOAT target. The view behind the +entry is made by tests/startup_address_srv.cpp (draw_formatted_view) through the title-side CreateShaderResourceView, +so the draw has no hardware descriptor word 3: it builds FORMAT and DST_SEL from the view's DXGI format and component +mapping (src/startup_stubs/buffer_format_word3.h). One translation serves every case; each draw is compared as four +32-bit words. Views the translation cannot decode refuse the draw with one logged reason, and the +target keeps its clear value. A translation whose W selector reads the Z field must fail. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +from startup_stream_check import container, gfx2hlsl +from startup_stream_draw_check import vertex, vop1 + +PIXEL = container(0, [ + 0xf4080304, 0xfa000000, # s_load_dwordx4 s[12:15], s[8:9], 0x0 + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + vop1(1, 4, 129), # v_mov_b32 v4, 1 + 0xe00c2000, 0x80030004, # buffer_load_format_xyzw v[0:3], v4, s[12:15], 0 idxen + 0xbf8c3f70, # s_waitcnt vmcnt(0) + 0xf800180f, 0x03020100, # exp mrt0 v0, v1, v2, v3 done vm + 0xbf810000]) # s_endpgm +TARGET = 2 # DXGI_FORMAT_R32G32B32A32_FLOAT +IDENTITY = 0x1688 +F = lambda x: struct.unpack(' drawn;' not in log and refusals == [expected], (label, refusals) + assert words == CLEAR, (label, [hex(w) for w in words]) + else: + assert '-> drawn;' in log and not refusals, (label, refusals, log[-2000:]) + assert words == expected, (label, [hex(w) for w in words], [hex(w) for w in expected]) + print('%s: %s' % (label, 'refused and logged' if isinstance(expected, str) else 'bit-exact')) + + # Negative control: the same translation with the W selector read from the Z field must fail the first case. + variant = next(p for p in manifests if 'rtv1' in p.read_text()) + hlsl = variant.with_suffix('.ps.hlsl') + source = hlsl.read_text() + selector = re.search(r'\(\((ud\d+) >> 9\) & 7u\)', source) + assert selector, 'no W selector in the translation' + hlsl.write_text(source.replace(selector.group(0), '((%s >> 6) & 7u)' % selector.group(1))) + subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', variant.with_suffix('.ps.cso'), hlsl], + check=True, capture_output=True) + words, _ = draw(CASES[0]) + assert words != CASES[0][5] and words[3] == CASES[0][5][2], [hex(w) for w in words] + print('control: a W selector read from the Z field fails (w = z)') + print('%s: %d typed-view cases through the translated buffer_load_format_xyzw' % (backend, len(CASES))) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) != 4: + raise SystemExit(__doc__) + if not Path(sys.argv[3]).is_file(): + print('fxc unavailable') + sys.exit(77) + with tempfile.TemporaryDirectory() as temp: + sys.exit(check(Path(temp), *sys.argv[1:])) diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index d3f5d5fac..e7dcab0a2 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -260,7 +260,8 @@ int main(int argc, char** argv) void* pso = nullptr; const bool hardware = draw && std::strcmp(argv[4], "hardware") == 0; const bool textured = bc7.blocks != nullptr || GetEnvironmentVariableW(L"X2W_TEST_D16_SRV", nullptr, 0) != 0 || - GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0; + GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_BUFFER", nullptr, 0) != 0 || + GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0) != 0; if (const int rc = prepare_stream_pipeline(argv[1], argv[2], argv[3], hardware, textured, adapter, device, pso)) return rc; // slot67 [case]: WARP device and root only, then slot-67 creations. diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index b6b703b6b..34a837861 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -332,6 +332,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_SINGLE_ELEMENT", nullptr, 0)) { extern int draw_single_element_srvs(void*, void*); if (const int result = draw_single_element_srvs(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_FORMATTED_VIEW", nullptr, 0)) { + extern int draw_formatted_view(void*, void*); + if (const int result = draw_formatted_view(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_BUFFER_SRV", nullptr, 0)) { extern int draw_address_buffer_srvs(ID3D12Device*, void*, void*); if (const int result = draw_address_buffer_srvs(desktop.Get(), guest, list)) return result; diff --git a/tests/startup_vertex_fetch_formats_check.py b/tests/startup_vertex_fetch_formats_check.py index 20f6d8823..187fa7b56 100644 --- a/tests/startup_vertex_fetch_formats_check.py +++ b/tests/startup_vertex_fetch_formats_check.py @@ -244,6 +244,12 @@ def mutate_case(source, code, old, new): ('DST_SEL constant 1 as 0', 'one = U(1.0)', 'one = 0u'), ) # Integer 1 for the constant of an integer format, and the switch cases themselves, are mutated per format below. +# buffer_load_format_xyzw device cases: (label, format, DST_SEL x, y, z, w). The fourth register is never 0 here. +XYZW_CASES = ( + ('xyzw', 'BUF_FMT_32_32_32_32_FLOAT', (4, 5, 6, 7)), + ('xyzw with missing z and w', 'BUF_FMT_16_16_FLOAT', (4, 5, 6, 7)), + ('xyzw read as w, 1, 0, x', 'BUF_FMT_32_32_32_32_FLOAT', (7, 1, 0, 4)), +) def mubuf_cases(): @@ -331,7 +337,10 @@ def table_matches(table): swapped[victim] = 'BUF_FMT_INVALID' assert not table_matches(swapped), 'format mutation not caught' assert not table_matches({**MTBUF_FORMATS, 1: 'BUF_FMT_8_UNORM'}), 'code 1 must stay the omitted default' - for op, count in ((0, 1), (1, 2), (2, 3)): + for label, name, selects in XYZW_CASES: + words = mubuf_expected(name, 4, selects) + assert all(words[v * 4 + 3] for v in range(16)), label # an xyz translation leaves this register 0 + for op, count in ((0, 1), (1, 2), (2, 3), (3, 4)): source = pipeline_mubuf(4, op).hlsl_vs() assert source.count('case ') == len(FORMATS), op # An unvalidated FORMAT yields the NaN sentinel in every component, never silent zeros. @@ -339,13 +348,6 @@ def table_matches(table): assert 'default: break' not in source, op written = {int(n) for n in re.findall(r'^\s*v(\d+) = ', source, re.M) if int(n) >= 4} assert written == set(range(4, 4 + count)), (op, written) - try: - gfx2hlsl.Pipeline(struct.pack('<7I', 0xf4080404, 0xfa000000, 0xe00c2000, 0x80040400, 0xf80008cf, 0x07060504, 0xbf810000), - struct.pack('<3I', 0xf800180f, 0, 0xbf810000), root_blob(flags=0)) - except gfx2hlsl.Unsupported: - pass - else: - raise AssertionError('buffer_load_format_xyzw must stay refused') # A shader that rewrites descriptor word 3 (s_mov_b32 s19, 0x50fac) after the load must not be translated # with the table word: the formatted load is refused. try: @@ -540,6 +542,20 @@ def check(directory, compiler, consumer, adapter): print('%s: descriptor-path mutation %r fails' % (name, label)) print('%s: %d buffer_load_format descriptor cases, wrong descriptor words and %d mutations fail' % (adapter, mubuf_runs, len(MUTATIONS) + len(DESC_MUTATIONS))) + # buffer_load_format_xyzw: the fourth register holds what DST_SEL w routes there, and the xyz translation of the + # same load (fourth register left 0) must fail each reference. + for label, name, selects in XYZW_CASES: + word3, words = descriptor_word3(name, selects), mubuf_expected(name, 4, selects) + translated = pipeline_mubuf(FORMATS[name][2], 3) + result = run(directory, compiler, consumer, adapter, name, translated.hlsl_vs(), words, translated, word3) + if result.returncode: + raise RuntimeError('descriptor %s: %s%s' % (label, result.stdout, result.stderr)) + print('descriptor %s: %s' % (label, [l for l in result.stdout.splitlines() if 'mismatches=' in l][0])) + xyz = pipeline_mubuf(FORMATS[name][2], 2) + bad = run(directory, compiler, consumer, adapter, name, xyz.hlsl_vs(), words, xyz, word3) + if bad.returncode != 1 or 'Compute readback differs' not in bad.stderr: + raise AssertionError('descriptor %s: the xyz form passed the xyzw reference\n%s' % (label, bad.stderr)) + print('descriptor %s: the xyz form fails' % label) return 0 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index dcfdf2ab1..34f5a14a3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3801,13 +3801,15 @@ def formatted_descriptor_from_block(self, reg, first): return False def mubuf_format(self, ops, mods, count): - """Lower a formatted MUBUF read using FORMAT and DST_SEL from descriptor word 3. + """buffer_load_format_x/xy/xyz/xyzw: FORMAT and DST_SEL come from word 3 of the descriptor, known at draw time. The caller supplies that word as an entry constant. Each supported format becomes one case of a switch on the FORMAT field that decodes the four components as the tbuffer path does; DST_SEL then picks, for - each destination register, a component or the constant 0 or 1. For compute, the caller must validate - the native descriptor and reachable byte addresses, and bind the SRV and entry constants from that - same descriptor snapshot. The switch default is a diagnostic for an unsupported format. + each destination register, a component or the constant 0 or 1. The draw builds the word from a hardware + descriptor or from the title's typed buffer view (src/startup_stubs/buffer_format_word3.h) and refuses the + draw when it has none or the FORMAT has no case here, so the default arm is not reached from a draw. + For compute, the caller must validate the native descriptor and reachable byte addresses, and bind the + SRV and entry constants from that same descriptor snapshot. """ buf, address = self.buffer_address(ops, mods) dst = reg_range(ops[0]) @@ -3851,8 +3853,6 @@ def op_buffer_load_format_xyz(self, ops, mods): self.mubuf_format(ops, mods, 3) def op_buffer_load_format_xyzw(self, ops, mods): - if self.kind != 'cs': - raise Unsupported('buffer_load_format_xyzw requires descriptor FORMAT and DST_SEL') self.mubuf_format(ops, mods, 4) def op_tbuffer_load_format_x(self, ops, mods): From d6830702fd5e2cc09962692ca88837c7f4168ac6 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:06:14 +0200 Subject: [PATCH 134/232] pe: add main(argv) and JSON/schema/IO error guards in dependency_paths with CLI suite (#2436) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/dependency_paths_cli_check.py | 280 ++++++++++++++++++++++++++++ tools/dependency_paths.py | 34 +++- 3 files changed, 306 insertions(+), 10 deletions(-) create mode 100644 tests/dependency_paths_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cb3be24bf..c1c11e495 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9703,6 +9703,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/layout_chunks_check.py") add_test(NAME dependency_paths_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dependency_paths_check.py") + add_test(NAME pe_dependency_paths_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/dependency_paths_cli_check.py") add_test(NAME pe_package_import_closure COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_package_preflight_check.py") add_test(NAME pe_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/dependency_paths_cli_check.py b/tests/dependency_paths_cli_check.py new file mode 100644 index 000000000..6dd0bc0c1 --- /dev/null +++ b/tests/dependency_paths_cli_check.py @@ -0,0 +1,280 @@ +"""CLI, schema-validation, encoding, and mutation control suite for tools/dependency_paths.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "dependency_paths.py" +sys.path.insert(0, str(ROOT / "tools")) + +import dependency_paths # noqa: E402 + + +def _synthetic_inventory() -> dict: + return { + "images": { + "app/game.exe": {"sha256": "a" * 64, "exports": []}, + "app/helper.dll": { + "sha256": "b" * 64, + "exports": [{"name": "HelperInit"}], + }, + }, + "imports": [ + { + "image": "app/game.exe", + "kind": "normal", + "dll": "helper.dll", + "symbol": "HelperInit", + "bundle_exports_in": ["app/helper.dll"], + "desktop_export": "export_not_found", + } + ], + } + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = dependency_paths.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[bytes]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + env=env, + timeout=30, + ) + + +class DependencyPathsCliPositiveTests(unittest.TestCase): + def _assert_document_schema(self, doc: dict, expected_sha256: str, expected_entries: list[str]) -> None: + self.assertEqual(set(doc), {"inventory_sha256", "entries"}) + self.assertEqual(doc["inventory_sha256"], expected_sha256) + self.assertEqual(sorted(doc["entries"]), sorted(expected_entries)) + for name in expected_entries: + entry = doc["entries"][name] + self.assertEqual( + set(entry), + {"entry", "reachable", "findings", "dynamic_lookup_imports", "unlinked_in_this_graph", "scope"}, + ) + self.assertEqual(entry["entry"], name) + + def test_single_entry_and_all_entries_return_zero_with_exact_json_schema(self) -> None: + payload = json.dumps(_synthetic_inventory()).encode("utf-8") + expected_sha = hashlib.sha256(payload).hexdigest() + + with TemporaryDirectory() as tmp: + inv_path = Path(tmp) / "inventory.json" + inv_path.write_bytes(payload) + + # 1) All entries mode (omitted entry arg) + code, out, err = _run_main([str(inv_path)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + all_doc = json.loads(out) + self._assert_document_schema(all_doc, expected_sha, ["app/game.exe", "app/helper.dll"]) + self.assertEqual( + sorted(all_doc["entries"]["app/game.exe"]["reachable"]), + ["app/game.exe", "app/helper.dll"], + ) + self.assertEqual(all_doc["entries"]["app/game.exe"]["findings"], []) + + # 2) Single entry mode + code, out, err = _run_main([str(inv_path), "app/game.exe"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + one_doc = json.loads(out) + self._assert_document_schema(one_doc, expected_sha, ["app/game.exe"]) + + proc = _run_subprocess(str(inv_path), "app/helper.dll") + self.assertEqual(proc.returncode, 0, proc.stderr.decode(errors="replace")) + self.assertEqual(proc.stderr, b"") + sub_doc = json.loads(proc.stdout) + self._assert_document_schema(sub_doc, expected_sha, ["app/helper.dll"]) + self.assertEqual(sub_doc["entries"]["app/helper.dll"]["unlinked_in_this_graph"], ["app/game.exe"]) + + def test_non_ascii_survives_cp1252_stdout_and_sys_argv_entrypoint(self) -> None: + non_ascii_name = "pkg/\u03a9mega_\u2603.dll" + inv = { + "images": {non_ascii_name: {"sha256": "0" * 64, "exports": []}}, + "imports": [], + } + payload = json.dumps(inv, ensure_ascii=False).encode("utf-8") + expected_sha = hashlib.sha256(payload).hexdigest() + + env = dict(os.environ, PYTHONIOENCODING="cp1252") + env.pop("PYTHONUTF8", None) + + with TemporaryDirectory() as tmp: + inv_path = Path(tmp) / "non_ascii.json" + inv_path.write_bytes(payload) + + proc = _run_subprocess(str(inv_path), non_ascii_name, env=env) + self.assertEqual(proc.returncode, 0, proc.stderr.decode(errors="replace")) + self.assertEqual(proc.stderr, b"") + doc = json.loads(proc.stdout) + self._assert_document_schema(doc, expected_sha, [non_ascii_name]) + + # Forward sys.argv when argv=None and verify __main__ raises SystemExit(0). + cli_argv = [str(TOOL), str(inv_path)] + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self._assert_document_schema(json.loads(out), expected_sha, [non_ascii_name]) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self._assert_document_schema(json.loads(stdout.getvalue()), expected_sha, [non_ascii_name]) + + +class DependencyPathsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_exit( + self, + argv: list[str], + *, + expected_code: int, + expected_fragments: tuple[str, ...], + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code) + self.assertEqual(proc.stdout, b"") + stderr = proc.stderr.decode(errors="replace") + self.assertNotIn("Traceback", stderr) + for fragment in expected_fragments: + self.assertIn(fragment, stderr) + + def test_missing_and_directory_inventory_rejected_cleanly(self) -> None: + # Kills removal of OSError guard and removal of args.inventory.is_dir() guard. + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.json" + self._assert_clean_exit( + [str(missing)], + expected_code=1, + expected_fragments=(str(missing),), + ) + + inv_dir = root / "inv_dir" + inv_dir.mkdir() + with mock.patch.object(dependency_paths, "trace") as trace_mock: + self._assert_clean_exit( + [str(inv_dir)], + expected_code=1, + expected_fragments=(str(inv_dir), "Inventory path is a directory"), + ) + trace_mock.assert_not_called() + + def test_invalid_utf8_and_invalid_json_rejected_cleanly(self) -> None: + # Kills removal of UnicodeDecodeError / ValueError guards. + with TemporaryDirectory() as tmp: + root = Path(tmp) + bad_utf8 = root / "bad_utf8.json" + bad_utf8.write_bytes(b"\xff\xfe\x80\x81") + self._assert_clean_exit( + [str(bad_utf8)], + expected_code=1, + expected_fragments=(str(bad_utf8),), + ) + + bad_json = root / "bad_json.json" + bad_json.write_bytes(b"{not valid json") + self._assert_clean_exit( + [str(bad_json)], + expected_code=1, + expected_fragments=(str(bad_json),), + ) + + def test_schema_guards_kill_mutations_on_root_images_and_imports(self) -> None: + # Each case uses values that would succeed or raise AttributeError if the corresponding guard were removed. + schema_cases = ( + ("root_list", json.dumps(["images", "imports"]), "root must be an object"), + ("root_int", json.dumps(42), "root must be an object"), + ("missing_images", json.dumps({"imports": []}), "'images' object"), + ("images_empty_list", json.dumps({"images": [], "imports": []}), "'images' object"), + ("missing_imports", json.dumps({"images": {}}), "'imports' list"), + ("imports_empty_dict", json.dumps({"images": {"a.exe": {"sha256": "0" * 64, "exports": []}}, + "imports": {}}), "'imports' list"), + ) + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, content, fragment in schema_cases: + with self.subTest(label=label): + inv_path = root / f"{label}.json" + inv_path.write_text(content, encoding="utf-8") + self._assert_clean_exit( + [str(inv_path)], + expected_code=1, + expected_fragments=(str(inv_path), fragment), + ) + + def test_trace_keyerror_and_typeerror_and_missing_entry_arg(self) -> None: + # Kills removal of KeyError/TypeError from except tuple and entry presence/is-not-None guards. + with TemporaryDirectory() as tmp: + root = Path(tmp) + + missing_sha = root / "missing_sha.json" + missing_sha.write_text(json.dumps({"images": {"a.exe": {"exports": []}}, "imports": []}), encoding="utf-8") + self._assert_clean_exit( + [str(missing_sha)], + expected_code=1, + expected_fragments=(str(missing_sha), "sha256"), + ) + + bad_image_type = root / "bad_image_type.json" + bad_image_type.write_text(json.dumps({"images": {"a.exe": None}, "imports": []}), encoding="utf-8") + self._assert_clean_exit( + [str(bad_image_type)], + expected_code=1, + expected_fragments=(str(bad_image_type),), + ) + + valid = root / "valid.json" + valid.write_text(json.dumps(_synthetic_inventory()), encoding="utf-8") + for missing_entry in ("missing.exe", ""): + with self.subTest(entry=missing_entry): + self._assert_clean_exit( + [str(valid), missing_entry], + expected_code=2, + expected_fragments=("Entry does not appear in this inventory",), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/dependency_paths.py b/tools/dependency_paths.py index b5e7dbba8..cdd61b99c 100644 --- a/tools/dependency_paths.py +++ b/tools/dependency_paths.py @@ -127,20 +127,34 @@ def trace(report, entry): "Dynamic targets and actual execution order require independent evidence.") -def main(): +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("inventory", type=Path) parser.add_argument("entry", nargs="?", help="Relative PE path, or omit to assess every entry independently") - args = parser.parse_args() - data = args.inventory.read_bytes() - inventory = json.loads(data) - if args.entry and args.entry not in inventory["images"]: - parser.error("Entry does not appear in this inventory") - entries = [args.entry] if args.entry else sorted(inventory["images"]) - document = dict(inventory_sha256=hashlib.sha256(data).hexdigest(), - entries={name: trace(inventory, name) for name in entries}) + args = parser.parse_args(argv) + try: + if args.inventory.is_dir(): + raise ValueError(f"Inventory path is a directory: {args.inventory}") + data = args.inventory.read_bytes() + inventory = json.loads(data) + if not isinstance(inventory, dict): + raise ValueError("Inventory JSON root must be an object") + images = inventory.get("images") + if not isinstance(images, dict): + raise ValueError("Inventory JSON must contain an 'images' object") + imports = inventory.get("imports") + if not isinstance(imports, list): + raise ValueError("Inventory JSON must contain an 'imports' list") + if args.entry is not None and args.entry not in images: + parser.error("Entry does not appear in this inventory") + entries = [args.entry] if args.entry is not None else sorted(images) + document = dict(inventory_sha256=hashlib.sha256(data).hexdigest(), + entries={name: trace(inventory, name) for name in entries}) + except (OSError, UnicodeDecodeError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"{args.inventory}: {exc}\n") print(json.dumps(document, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 2b883ea655ae80fe7492b7783a7d1055f9ae8615 Mon Sep 17 00:00:00 2001 From: RonLogic Date: Wed, 25 Nov 2026 22:08:21 +0200 Subject: [PATCH 135/232] gpu: verify slot 57 request publication through desktop readback (#2522) Co-authored-by: RonLogic <307541314+RonLogic@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 4 ++ docs/experiments.md | 6 +++ tests/startup_indirect_draw_indexed.cpp | 51 ++++++++++++++++++------- tests/startup_mesh57_skeleton_check.py | 48 +++++++++++++++++++++-- 4 files changed, 91 insertions(+), 18 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c1c11e495..59d7ca244 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8549,6 +8549,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_mesh57_skeleton_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_skeleton_exchange_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" exchange "${DXC_EXECUTABLE}" + "$" ${adapter} "$") + set_tests_properties(startup_mesh57_skeleton_exchange_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME mesh_cbv_order_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_cbv_order_check.py" "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 467948493..1e2a7ff98 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9209,6 +9209,12 @@ The request fixture checks paired and mesh-only requests, duplicate publication, a mismatched root, a populated vertex slot, and an incomplete pixel span. +The `startup_mesh57_skeleton_exchange_` tests pass the same source-built +shader pair through the guest request publisher. The offline reader checks +the published bytes and key, compiles the recorded pair with its serialized +root, and compares all 1,024 desktop readback pixels with the CPU reference. +The one-pixel negative control uses that same published pair. + The pending scan checks the DXContainer header and file length for both slot 57 bytecode artifacts. A missing or truncated artifact leaves the request pending even if its manifest exists. In manifest-only mode the diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 3d62fb0af..a8d4dbb05 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -1785,24 +1785,47 @@ int main(int argc, char** argv) try return ok ? 0 : 1; } if (mesh && GetEnvironmentVariableA("X2W_MESH_REQUEST_FIXTURE", nullptr, 0)) { - const auto cache = std::filesystem::current_path() / ("slot57-mesh-" + std::to_string(GetCurrentProcessId())); + wchar_t exchange[MAX_PATH]{}; + const DWORD exchange_size = GetEnvironmentVariableW(L"X2W_TEST_MESH57_EXCHANGE", exchange, MAX_PATH); + if (exchange_size >= MAX_PATH) return 1; + const auto cache = exchange_size ? std::filesystem::path(exchange) / "requests" : + std::filesystem::current_path() / ("slot57-mesh-" + std::to_string(GetCurrentProcessId())); std::filesystem::create_directory(cache); check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "set mesh fixture cache"); + const D3D12_DESCRIPTOR_RANGE srv{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND}; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &srv}; + const D3D12_ROOT_SIGNATURE_DESC source_root{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto& desc = exchange_size ? source_root : graphics_desc; ComPtr root_blob; - const auto root = create_root(guest.Get(), graphics_desc, &root_blob); - const auto different_root = create_root(guest.Get(), graphics_desc); + const auto root = create_root(guest.Get(), desc, &root_blob); + const auto different_root = create_root(guest.Get(), desc); // Distinct, source-owned bounded spans. The request publisher must preserve their stage roles and lengths. - const std::array ms{0xbfa00003, 0xbf900009, 0xbf810000, 0}; - const std::array ps{0xbfa00003, 0xbf810000}; + const std::array default_ms{0xbfa00003, 0xbf900009, 0xbf810000, 0}; + const std::array default_ps{0xbfa00003, 0xbf810000}; + const auto read_stage = [&](const wchar_t* name) { + std::ifstream file(std::filesystem::path(exchange) / name, std::ios::binary); + return std::vector(std::istreambuf_iterator(file), {}); + }; + const auto source_ms = exchange_size ? read_stage(L"ms.bin") : std::vector{}; + const auto source_ps = exchange_size ? read_stage(L"ps.bin") : std::vector{}; + if (exchange_size && (source_ms.empty() || source_ps.empty())) return 1; + const void* ms = exchange_size ? static_cast(source_ms.data()) : default_ms.data(); + const void* ps = exchange_size ? static_cast(source_ps.data()) : default_ps.data(); + const auto ms_size = exchange_size ? source_ms.size() : sizeof(default_ms); + const auto ps_size = exchange_size ? source_ps.size() : sizeof(default_ps); const auto make_pso = [&](bool with_pixel, bool with_vertex, bool incomplete_pixel) { std::array fields{}; fields[0] = reinterpret_cast(root.Get()); - fields[5] = with_pixel ? reinterpret_cast(ps.data()) : 0; - fields[6] = with_pixel && !incomplete_pixel ? sizeof(ps) : 0; - fields[9] = with_vertex ? reinterpret_cast(ps.data()) : 0; - fields[10] = with_vertex ? sizeof(ps) : 0; - fields[13] = reinterpret_cast(ms.data()); - fields[14] = sizeof(ms); + fields[5] = with_pixel ? reinterpret_cast(ps) : 0; + fields[6] = with_pixel && !incomplete_pixel ? ps_size : 0; + fields[9] = with_vertex ? reinterpret_cast(ps) : 0; + fields[10] = with_vertex ? ps_size : 0; + fields[13] = reinterpret_cast(ms); + fields[14] = ms_size; using Create = HRESULT (WINAPI*)(IUnknown*, const void*, REFIID, void**); ComPtr pso; check(slot(guest.Get(), 57)(guest.Get(), fields.data(), __uuidof(ID3D12PipelineState), @@ -1841,13 +1864,13 @@ int main(int argc, char** argv) try auto path = file.path(); if (path.extension() != ".m57") continue; ++requests; - if (!matches(path, ms.data(), sizeof(ms)) || + if (!matches(path, ms, ms_size) || !matches(path.replace_extension(".root"), root_blob->GetBufferPointer(), root_blob->GetBufferSize())) return 1; - if (matches(path.replace_extension(".ps57"), ps.data(), sizeof(ps))) ++with_ps; + if (matches(path.replace_extension(".ps57"), ps, ps_size)) ++with_ps; else if (!matches(path, nullptr, 0)) return 1; } if (requests != 2 || with_ps != 1 || files != 6) return 1; - std::filesystem::remove_all(cache); + if (!exchange_size) std::filesystem::remove_all(cache); std::puts("slot 57 MS+PS and MS-only requests preserved stages and the matching root"); return 0; } diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 4ffaac3ba..04c032521 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -3,6 +3,7 @@ usage: startup_mesh57_skeleton_check.py startup_mesh57_skeleton_check.py binary startup_mesh57_skeleton_check.py draw + startup_mesh57_skeleton_check.py exchange The fixture (tests/startup_mesh57_skeleton.s, source-built) holds the accepted shape: lane 0 of wave 0 stores a word and both waves pass a barrier; later the same lane stores the primitive and vertex counts, both waves pass @@ -14,6 +15,7 @@ refused with its own message. `binary` compares the embedded words with llvm-mc. `draw` compiles the request path's output (ms_6_5, ps_6_0), draws it and compares the read-back target with a CPU rasteriser written here; a reference with one wrong pixel must fail. +The exchange mode uses the runtime-published request and the same pixel comparison. """ import os from pathlib import Path @@ -232,17 +234,51 @@ def rasterise(points, colours, indices, verts, prims): return image -def draw(dxc, renderer, adapter): +def publish_request(directory, publisher, adapter): + ms, ps = code(MESH), code(PIXEL) + (directory / 'ms.bin').write_bytes(ms) + (directory / 'ps.bin').write_bytes(ps) + env = dict(os.environ, X2W_MESH_REQUEST_FIXTURE='1', X2W_TEST_MESH57_EXCHANGE=str(directory)) + result = subprocess.run([publisher, adapter, 'mesh'], env=env, capture_output=True, text=True) + print(result.stdout, end='') + if result.returncode: + if result.returncode != 77: + print(result.stderr, end='') + return result.returncode, None + cache = directory / 'requests' + pair = [path for path in cache.glob('req_*.ps57') if path.stat().st_size] + expect('one published mesh and pixel request', len(pair), 1) + if len(pair) != 1: + return 1, None + root_blob = pair[0].with_suffix('.root').read_bytes() + key = G.mesh57_key(ms, ps, root_blob) + expect('published key matches the offline reader', pair[0].stem, f'req_{key:016x}') + expect('published mesh matches the fixture', pair[0].with_suffix('.m57').read_bytes(), ms) + expect('published pixel matches the fixture', pair[0].read_bytes(), ps) + if FAILED: + return 1, None + return 0, (cache, key, root_blob) + + +def draw(dxc, renderer, adapter, publisher=None): os.environ['X2W_DXC'] = dxc os.environ.pop('X2W_FXC', None) points, colours, indices = geometry() with tempfile.TemporaryDirectory() as tmp: - key, result = request(tmp, MESH) + if publisher: + status, published = publish_request(Path(tmp), publisher, adapter) + if status: + return status + cache, key, root_blob = published + result = G.translate_request(str(cache), key) + else: + cache, root_blob = Path(tmp), root() + key, result = request(tmp, MESH) expect('the fixture translates and compiles', result, 'ok') if result != 'ok': return 0 - name = str(Path(tmp) / ('%016x' % key)) - uds = G.MeshPipeline(code(MESH), code(PIXEL), root()).uds + name = str(cache / ('%016x' % key)) + uds = G.MeshPipeline(code(MESH), code(PIXEL), root_blob).uds # (vertex count, primitive count, thread of vertex slot 0, flags of the first primitive words): all, fewer # primitives, fewer vertices (indices clamp), no vertex; every thread, with the triangles on vertices # 112..123 (wave 1, lanes 48..59), each named by eight primitives and the other 96 primitives on vertex 0 @@ -250,6 +286,8 @@ def draw(dxc, renderer, adapter): # Each case is one process and one device, which takes seconds on a hardware adapter. cases = ((12, 4, 0, ()), (12, 1, 0, ()), (7, 4, 0, ()), (0, 4, 0, ()), (128, 128, 112, (1 << 31, 1 << 9 | 1 << 19 | 1 << 29))) + if publisher: + cases = cases[:1] for case in cases: verts, prims, first, flags = case named = [tuple(first + i for i in triangle) for triangle in indices] @@ -291,6 +329,8 @@ def main(argv): binary(argv[2]) elif argv[1:2] == ['draw'] and len(argv) == 5: status = draw(*argv[2:]) + elif argv[1:2] == ['exchange'] and len(argv) == 6: + status = draw(*argv[2:]) elif len(argv) == 1: controls() else: From 4a5058283029cad1a159ed2469f0288ed7033a9c Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 04:11:33 +0800 Subject: [PATCH 136/232] shader: preserve the direction of dynamic SCC1 mesh branches (#2442) AI-assisted with Codex + GPT-6.2 Astra (xhigh). Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 3 +++ tests/mesh_join_descriptor_check.py | 18 ++++++++++++------ tools/mesh_entry_aot.py | 11 +++++++---- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 1e2a7ff98..6b9b1a1d0 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3577,6 +3577,9 @@ register defined in one arm only, and scalar ALU on the joined registers. `tests/mesh_join_descriptor_check.py` checks the lowering and these refusals in pure Python and, with ` `, draws both arms and the null arm on D3D12 against the mesh export trace and a pixel reference. +Reversing the two descriptor arms and changing `s_cbranch_scc0` to +`s_cbranch_scc1` preserves the image. One input selects vertex depth 1.625 +and clips the entire triangle; the other table would give a visible depth of 0.5. The Linux run covers only the Python part; the D3D12 draw runs on Windows. ```sh diff --git a/tests/mesh_join_descriptor_check.py b/tests/mesh_join_descriptor_check.py index 4b4643de3..bea2e2a0f 100644 --- a/tests/mesh_join_descriptor_check.py +++ b/tests/mesh_join_descriptor_check.py @@ -20,19 +20,19 @@ POINT, MATRIX = "0x60", "0x80" -def program(arm_true, arm_false, selector="s_cmp_eq_u32 s14, 0"): +def program(fallthrough, taken, selector="s_cmp_eq_u32 s14, 0", *, branch="s_cbranch_scc0"): """Splice a uniform if/else that defines the descriptor s[36:39].""" - first = arm_true + ["s_branch %d" % len(arm_false)] + first = fallthrough + ["s_branch %d" % len(taken)] return ( PROGRAM[:7] # descriptor tables, wait, geometry word s15 + [ "s_buffer_load_dword s14, s[16:19], null", "s_waitcnt lgkmcnt(0)", selector, - "s_cbranch_scc0 %d" % len(first), + f"{branch} {len(first)}", ] + first - + arm_false + + taken + [ "s_buffer_load_dword s30, s[36:39], 0x4", "s_buffer_load_dword s31, s[20:23], 0xc", @@ -49,6 +49,7 @@ def table(offset): NULL = [f"s_mov_b32 s{i}, 0" for i in range(36, 40)] PER_MATERIAL = program(table(POINT), table(MATRIX)) NULL_ARM = program(table(POINT), NULL) +PER_MATERIAL_SCC1 = program(table(MATRIX), table(POINT), branch="s_cbranch_scc1") def build(lines, **kw): @@ -69,11 +70,15 @@ def checks(): source = build(PER_MATERIAL) expect = "(asuint(pointData[0].x) == 0u) ? pointData[0].y : matrixData[0].y" assert expect in source, source + assert build(PER_MATERIAL_SCC1) == source + assert build(program(NULL, table(POINT), branch="s_cbranch_scc1")) == build(NULL_ARM) assert "(asuint(pointData[0].x) == 0u) ? pointData[0].y : 0.0f" in build(NULL_ARM) # LLVM 15 prints a branch to itself (SIMM16 = -1) as 65535. split = PER_MATERIAL.copy() split[split.index("s_cbranch_scc0 3")] = "s_cbranch_scc0 65535" refused(split, "Expected a forward mesh branch") + refused(program(table(POINT) + ["s_mov_b64 exec, 1"], table(MATRIX), branch="s_cbranch_scc1"), + "changed EXEC, VCC or M0") arm = PER_MATERIAL.copy() latch = arm.index("s_branch 2") @@ -139,16 +144,17 @@ def cases(null_arm): def triangle(z): return [(x, y, z, w) for x, y, _, w in TRIANGLE] - # selector 0.0 takes the fall-through arm (point table); 1.0 the other arm. + # Selector 0.0 chooses the point table in either branch encoding. other = 0.0 if null_arm else 0.25 return [ (constants(0.0, 0.125, 0.25, 0.375), triangle(0.5), True), (constants(1.0, 0.125, 0.25, 0.375), triangle(other + 0.375), True), + (constants(1.0, 0.125, 1.25, 0.375), triangle(0.375 if null_arm else 1.625), null_arm), ] def check(dxc, renderer, adapter): - for lines, null_arm in ((PER_MATERIAL, False), (NULL_ARM, True)): + for lines, null_arm in ((PER_MATERIAL, False), (NULL_ARM, True), (PER_MATERIAL_SCC1, False)): with tempfile.TemporaryDirectory() as directory: result = draw(dxc, renderer, adapter, Path(directory), build(lines), cases(null_arm)) if result == 77: diff --git a/tools/mesh_entry_aot.py b/tools/mesh_entry_aot.py index bf314bf2b..74217daaf 100644 --- a/tools/mesh_entry_aot.py +++ b/tools/mesh_entry_aot.py @@ -307,7 +307,7 @@ def selected_words(self, desc, first, count): ) return [f"({cond.expr} ? {t} : {f})" for t, f in zip(*arms)] - def join_arms(self, decoded, expressions, jumps, pc, offset, target_offset, cond): + def join_arms(self, decoded, expressions, jumps, pc, target_offset, cond, *, branch_on_true): """Run both arms of a uniform branch on a constant predicate and merge them. Only scalar ALU and loads may appear inside an arm; the arms write no @@ -338,6 +338,9 @@ def join_arms(self, decoded, expressions, jumps, pc, offset, target_offset, cond if (self.exec, self.vcc, self.m0) != before: raise ValueError("A descriptor join arm changed EXEC, VCC or M0") outcomes.append((self.s, self.pending, self.pending_v)) + # Outcomes are in fall-through, taken order. Select needs true, false. + if branch_on_true: + outcomes.reverse() (true_s, true_p, true_v), (false_s, false_p, false_v) = outcomes self.pending_v = true_v | false_v if true_s.keys() != false_s.keys(): @@ -761,10 +764,10 @@ def exec_range(self, decoded, expressions, jumps, pc, stop, arm=False): self.ds_writes_pending = False if "vmcnt" in tail: self.pending_v.clear() - elif op == "s_cbranch_scc0" and isinstance(self.scc, Dyn): + elif op in ("s_cbranch_scc0", "s_cbranch_scc1") and isinstance(self.scc, Dyn): pc = self.join_arms( - decoded, expressions, jumps, pc, offset, - branch_target(offset, tail), self.scc, + decoded, expressions, jumps, pc, branch_target(offset, tail), + self.scc, branch_on_true=op == "s_cbranch_scc1", ) elif op == "s_branch" or op.startswith("s_cbranch_"): if ( From 53a7d10e674e724c934027f024fc91e6598decee Mon Sep 17 00:00:00 2001 From: dnn <55638248+denn0x@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:12:38 +0000 Subject: [PATCH 137/232] startup: decode a PA_SU_SC_MODE_CNTL value to D3D12 cull, winding and fill (#2480) src/startup_stubs/rasterizer_state_decode.h turns a PA_SU_SC_MODE_CNTL register value into the CullMode, FrontCounterClockwise and FillMode of a D3D12_RASTERIZER_DESC (#1999, item B). Field positions follow the amdgpu gc_10_3_0_sh_mask.h header and Mesa's gfx10.json. It decodes the value only. Where a slot 57 pipeline keeps the word is not part of this change and stays open until independently established. FACE 0 is counter-clockwise front (radeonsi writes S_028814_FACE(!front_ccw)); the caller's flip_winding inverts it, since the convention is not established against the D3D12 viewport. Refused with a reason: both faces culled, point, unknown or mixed polygon types, a reserved POLY_MODE, any polygon offset enable, last-vertex provoking and disabled perspective correction. Pure and unused by draws. Test: tests/startup_rasterizer_decode_check.cpp (device-free) covers each cull mode with both FACE values and both flip settings, wireframe and solid dual polygon mode, unread fields, and the 10 refused forms. Its face, cull and fill controls each read one field wrongly and must fail (WILL_FAIL). --- CMakeLists.txt | 10 ++ docs/startup-runtime.md | 10 ++ src/startup_stubs/rasterizer_state_decode.h | 89 ++++++++++++++++ tests/startup_rasterizer_decode_check.cpp | 111 ++++++++++++++++++++ 4 files changed, 220 insertions(+) create mode 100644 src/startup_stubs/rasterizer_state_decode.h create mode 100644 tests/startup_rasterizer_decode_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 59d7ca244..8fb309aea 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2019,6 +2019,16 @@ set_tests_properties(startup_pipeline_state_offset_control PROPERTIES WILL_FAIL # Mesh-pipeline layout (+0x004 == 6, fields 0x54 later): a mesh block read at the vertex offsets must fail. add_test(NAME startup_pipeline_state_mesh_shift_control COMMAND startup_pipeline_state_check --mutate mesh-shift) set_tests_properties(startup_pipeline_state_mesh_shift_control PROPERTIES WILL_FAIL TRUE) +# PA_SU_SC_MODE_CNTL value -> D3D12 cull, winding and fill (src/startup_stubs/rasterizer_state_decode.h, #1999 B). +# Device-free; each control reads one field wrongly and must fail. +add_executable(startup_rasterizer_decode_check tests/startup_rasterizer_decode_check.cpp) +target_include_directories(startup_rasterizer_decode_check PRIVATE src) +target_compile_features(startup_rasterizer_decode_check PRIVATE cxx_std_17) +add_test(NAME startup_rasterizer_decode COMMAND startup_rasterizer_decode_check) +foreach(mutation IN ITEMS face cull fill) + add_test(NAME startup_rasterizer_decode_${mutation}_control COMMAND startup_rasterizer_decode_check --mutate ${mutation}) + set_tests_properties(startup_rasterizer_decode_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # X2W_DEPTH_STATE (src/startup_stubs/depth_state_apply.h): off takes nothing from the block, on takes a decodable one. add_executable(startup_depth_state_check tests/startup_depth_state_check.cpp) target_include_directories(startup_depth_state_check PRIVATE src) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index fe910c39b..2debb4afd 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2342,6 +2342,16 @@ These are measured on one executable; treat them as hypotheses for others. (`ctest --preset dev --no-tests=error -R "^startup_(depth_state|slot57_depth)" -V`). Not covered: raster bias, depth bounds, back-face-only state, the title's own `OMSetStencilRef` order, clears (#1806), and any pipeline layout other than the measured one. +- Rasterizer state (#1999, item B) has a decoder for the register value only: + `src/startup_stubs/rasterizer_state_decode.h` turns a `PA_SU_SC_MODE_CNTL` value into the cull mode, + front-face winding and fill mode of a `D3D12_RASTERIZER_DESC`, with the field positions of the amdgpu + `gc_10_3_0_sh_mask.h` header and Mesa's `gfx10.json`. Where a slot 57 pipeline keeps that word is not + part of it and is left open until independently established. It refuses both faces culled, point or + mixed polygon modes, polygon offset, last-vertex provoking and disabled perspective correction. The + caller's `flip_winding` inverts the FACE convention, which is not established against the D3D12 + viewport. A device-free check covers each cull mode, winding and fill form and the refusals; its + `_face_control`, `_cull_control` and `_fill_control` runs read one field wrongly and must fail + (`ctest --preset dev --no-tests=error -R "^startup_rasterizer_decode" -V`). Not used by draws yet. - Audio produces no output from the console audio path. A separate desktop render sink exists (see "Audio output"); nothing connects the console path to it yet. diff --git a/src/startup_stubs/rasterizer_state_decode.h b/src/startup_stubs/rasterizer_state_decode.h new file mode 100644 index 000000000..27d1395a4 --- /dev/null +++ b/src/startup_stubs/rasterizer_state_decode.h @@ -0,0 +1,89 @@ +// Experimental (#1999, item B): the cull, front-face and fill state in a PA_SU_SC_MODE_CNTL register +// value, as a D3D12 rasterizer description. +// +// This header decodes the register value only. Where a guest pipeline keeps that word is not part of it: +// the caller supplies the value once its location is independently established. +// +// Field positions follow the amdgpu register header gc_10_3_0_sh_mask.h (Linux +// drivers/gpu/drm/amd/include/asic_reg/gc, MIT) and Mesa's src/amd/registers/gfx10.json, PA_SU_SC_MODE_CNTL: +// CULL_FRONT [0], CULL_BACK [1], FACE [2], POLY_MODE [4:3] (0 disabled, 1 dual), +// POLYMODE_FRONT_PTYPE [7:5] and POLYMODE_BACK_PTYPE [10:8] (0 points, 1 lines, 2 triangles), +// POLY_OFFSET_FRONT_ENABLE [11], POLY_OFFSET_BACK_ENABLE [12], POLY_OFFSET_PARA_ENABLE [13], +// PROVOKING_VTX_LAST [19], PERSP_CORR_DIS [20]. +// FACE 0 selects counter-clockwise front faces (radeonsi writes S_028814_FACE(!front_ccw)). Whether the +// guest's window coordinates and the D3D12 viewport agree on that winding is not established here, so the +// caller passes flip_winding to invert it. +// +// Refused with a reason, so the caller can keep the state it had: both faces culled (D3D12 has no such +// cull mode), a polygon mode that draws points or differs between front and back faces, a reserved +// POLY_MODE value, any polygon offset enable (the offset words are not decoded here), the last vertex +// as provoking vertex (D3D12 uses the first), and disabled perspective correction (a D3D12 pipeline has +// no such switch). The other fields (VTX_WINDOW_OFFSET_ENABLE, MULTI_PRIM_IB_ENA, the gradient and quad +// decomposition bits, KEEP_TOGETHER_ENABLE) are not read. +// A pure function, not used by the draw path yet. +#pragma once + +#include + +#include + +namespace x2w_rasterizer_state { + +constexpr std::uint32_t field(std::uint32_t v, unsigned lo, unsigned hi) { return (v >> lo) & ((1u << (hi - lo + 1)) - 1); } + +struct Raster { + bool ok = false; + const char* reason = nullptr; + D3D12_RASTERIZER_DESC desc{}; +}; + +inline Raster decode_mode_cntl(std::uint32_t mode, bool flip_winding) +{ + Raster out; + D3D12_RASTERIZER_DESC& r = out.desc; + const std::uint32_t poly_mode = field(mode, 3, 4); + if (poly_mode > 1) { + out.reason = "reserved POLY_MODE value"; + return out; + } + r.FillMode = D3D12_FILL_MODE_SOLID; + if (poly_mode == 1) { + const std::uint32_t front = field(mode, 5, 7), back = field(mode, 8, 10); + if (front != back || (front != 1 && front != 2)) { + out.reason = "polygon mode with points, an unknown type, or different front and back types"; + return out; + } + r.FillMode = front == 1 ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID; + } + const bool cull_front = field(mode, 0, 0) != 0, cull_back = field(mode, 1, 1) != 0; + if (cull_front && cull_back) { + out.reason = "both faces culled"; + return out; + } + if (field(mode, 11, 13)) { + out.reason = "polygon offset enabled (offset words not decoded)"; + return out; + } + if (field(mode, 19, 19)) { + out.reason = "last vertex as provoking vertex"; + return out; + } + if (field(mode, 20, 20)) { + out.reason = "perspective correction disabled"; + return out; + } + r.CullMode = cull_front ? D3D12_CULL_MODE_FRONT : cull_back ? D3D12_CULL_MODE_BACK : D3D12_CULL_MODE_NONE; + r.FrontCounterClockwise = (field(mode, 2, 2) == 0) != flip_winding; + r.DepthBias = 0; + r.DepthBiasClamp = 0.0f; + r.SlopeScaledDepthBias = 0.0f; + r.DepthClipEnable = TRUE; + r.MultisampleEnable = FALSE; + r.AntialiasedLineEnable = FALSE; + r.ForcedSampleCount = 0; + r.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; + out.ok = true; + return out; +} + +} // namespace x2w_rasterizer_state diff --git a/tests/startup_rasterizer_decode_check.cpp b/tests/startup_rasterizer_decode_check.cpp new file mode 100644 index 000000000..17d8afd98 --- /dev/null +++ b/tests/startup_rasterizer_decode_check.cpp @@ -0,0 +1,111 @@ +// Device-free check of src/startup_stubs/rasterizer_state_decode.h (#1999, item B): synthetic +// PA_SU_SC_MODE_CNTL values built from the Mesa gfx10 field layout, decoded to D3D12 cull, winding and fill +// state, plus every refused form. +// +// startup_rasterizer_decode_check [--mutate face|cull|fill] +// A mutation changes the expectations the way a wrong field reading would (FACE read inverted, CULL_FRONT +// and CULL_BACK swapped, the polygon types swapped); the check must then fail (CTest WILL_FAIL controls). +#include "startup_stubs/rasterizer_state_decode.h" + +#include +#include + +namespace { + +using namespace x2w_rasterizer_state; + +int failures = 0; +bool mutate_face = false, mutate_cull = false, mutate_fill = false; + +constexpr std::uint32_t CULL_FRONT = 1u << 0, CULL_BACK = 1u << 1, FACE_CW = 1u << 2, POLY_DUAL = 1u << 3; +constexpr std::uint32_t front_type(std::uint32_t t) { return t << 5; } +constexpr std::uint32_t back_type(std::uint32_t t) { return t << 8; } +constexpr std::uint32_t PTYPE_POINTS = 0, PTYPE_LINES = 1, PTYPE_TRIANGLES = 2; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +void accepted(const char* label, std::uint32_t mode, bool flip, D3D12_CULL_MODE cull, bool front_ccw, D3D12_FILL_MODE fill) +{ + if (mutate_cull && cull != D3D12_CULL_MODE_NONE) + cull = cull == D3D12_CULL_MODE_FRONT ? D3D12_CULL_MODE_BACK : D3D12_CULL_MODE_FRONT; + if (mutate_face) + front_ccw = !front_ccw; + if (mutate_fill && (mode & POLY_DUAL)) + fill = fill == D3D12_FILL_MODE_SOLID ? D3D12_FILL_MODE_WIREFRAME : D3D12_FILL_MODE_SOLID; + const Raster r = decode_mode_cntl(mode, flip); + char what[160]; + std::snprintf(what, sizeof what, "%s (mode %#x flip %d): ok=%d reason=%s cull=%d ccw=%d fill=%d", label, mode, flip, + r.ok, r.reason ? r.reason : "-", r.desc.CullMode, r.desc.FrontCounterClockwise, r.desc.FillMode); + expect(r.ok && r.desc.CullMode == cull && (r.desc.FrontCounterClockwise != FALSE) == front_ccw && + r.desc.FillMode == fill && r.desc.DepthClipEnable && r.desc.DepthBias == 0 && + r.desc.SlopeScaledDepthBias == 0.0f && !r.desc.MultisampleEnable && + r.desc.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF, + what); +} + +void refused(const char* label, std::uint32_t mode, const char* reason) +{ + const Raster r = decode_mode_cntl(mode, false); + char what[160]; + std::snprintf(what, sizeof what, "%s (mode %#x) refused with \"%s\", got ok=%d reason=%s", label, mode, reason, r.ok, + r.reason ? r.reason : "-"); + expect(!r.ok && r.reason && std::strstr(r.reason, reason), what); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc > 2 && std::strcmp(argv[1], "--mutate") == 0) { + mutate_face = std::strcmp(argv[2], "face") == 0; + mutate_cull = std::strcmp(argv[2], "cull") == 0; + mutate_fill = std::strcmp(argv[2], "fill") == 0; + } + if (argc > 1 && !mutate_face && !mutate_cull && !mutate_fill) { + std::printf("usage: startup_rasterizer_decode_check [--mutate face|cull|fill]\n"); + return 2; + } + // Cull mode x winding, with the caller's flip both ways. + for (int flip = 0; flip < 2; ++flip) { + const std::uint32_t faces[] = {0u, FACE_CW}; + for (std::uint32_t face : faces) { + const bool ccw = (face == 0) != (flip != 0); + accepted("no cull", face, flip != 0, D3D12_CULL_MODE_NONE, ccw, D3D12_FILL_MODE_SOLID); + accepted("cull front", face | CULL_FRONT, flip != 0, D3D12_CULL_MODE_FRONT, ccw, D3D12_FILL_MODE_SOLID); + accepted("cull back", face | CULL_BACK, flip != 0, D3D12_CULL_MODE_BACK, ccw, D3D12_FILL_MODE_SOLID); + } + } + // Dual polygon mode with the same type on both faces; the types are ignored while POLY_MODE is 0. + accepted("lines", POLY_DUAL | front_type(PTYPE_LINES) | back_type(PTYPE_LINES), false, D3D12_CULL_MODE_NONE, true, + D3D12_FILL_MODE_WIREFRAME); + accepted("triangles", POLY_DUAL | front_type(PTYPE_TRIANGLES) | back_type(PTYPE_TRIANGLES) | CULL_BACK, false, + D3D12_CULL_MODE_BACK, true, D3D12_FILL_MODE_SOLID); + accepted("types without POLY_MODE", front_type(PTYPE_POINTS) | back_type(PTYPE_LINES), false, D3D12_CULL_MODE_NONE, true, + D3D12_FILL_MODE_SOLID); + // Fields this decoder does not read leave the result alone (MULTI_PRIM_IB_ENA [21], KEEP_TOGETHER_ENABLE [24]). + accepted("unread fields", CULL_BACK | 1u << 21 | 1u << 24, false, D3D12_CULL_MODE_BACK, true, D3D12_FILL_MODE_SOLID); + // Refused forms. + refused("both faces culled", CULL_FRONT | CULL_BACK, "both faces culled"); + refused("points", POLY_DUAL | front_type(PTYPE_POINTS) | back_type(PTYPE_POINTS), "polygon mode"); + refused("front and back differ", POLY_DUAL | front_type(PTYPE_LINES) | back_type(PTYPE_TRIANGLES), "polygon mode"); + refused("unknown polygon type", POLY_DUAL | front_type(3) | back_type(3), "polygon mode"); + refused("reserved POLY_MODE", 2u << 3, "reserved POLY_MODE"); + refused("front offset", 1u << 11, "polygon offset"); + refused("back offset", 1u << 12, "polygon offset"); + refused("para offset", 1u << 13, "polygon offset"); + refused("last provoking vertex", 1u << 19, "provoking vertex"); + refused("no perspective correction", 1u << 20, "perspective correction"); + if (failures) { + std::printf("startup_rasterizer_decode: %d failures\n", failures); + return 1; + } + std::printf("startup_rasterizer_decode: PASS (cull none/front/back x FACE x flip, wireframe and solid dual polygon " + "mode, unread fields ignored, 10 refused forms)\n"); + return 0; +} From 577f72e88234b1ec6b14e6f06b6b87de5abdaf7d Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:12:52 +0100 Subject: [PATCH 138/232] mesh: accept the whole-register scratch-base setup in the bounded lowerers (#2508) Two s_setreg_imm32_b32 writes to HW_REG_FLAT_SCR_LO/HI were the first refusal for 4,274 of 4,458 programs in the mesh loop census (#1998). Lower a whole-register immediate write to either half to nothing, with the immediate spelling compute_store_aot accepts. The wave model only checks the instructions it executes, so run_group scans the whole decoded program first and refuses it when it holds an accepted write and any scratch_*, flat_* or s_getreg_* instruction (none of which the mesh lowerers lower), on any path. Field writes, the s_setreg_b32 form, non-immediate sources and other hardware registers stay refused. Tests: mesh_entry_check.py flat-scratch (new CPU mode, registered as mesh_entry_flat_scratch_cpu) checks output equivalence and refuses each reader on a skipped arm, with a control that the same arm lowers unchanged without the writes; mesh_dynamic_aot_check.py repeats it for the run-time lowerer; mesh_loop_census_check.py now expects the setup fixture to reach its latch in both census runs. Part of #1998. AI-assisted. --- AGENTS.md | 1 + CMakeLists.txt | 2 ++ docs/experiments.md | 43 +++++++++++++++++++++++++++++--- tests/mesh_dynamic_aot_check.py | 11 +++++++++ tests/mesh_entry_check.py | 44 ++++++++++++++++++++++++++++++++- tests/mesh_loop_census_check.py | 11 ++++----- tools/mesh_entry_aot.py | 24 ++++++++++++++++++ 7 files changed, 126 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 138a3ee0d..98f718a83 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -221,6 +221,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_ngg_slice_check.py ./out/pe-env/bin/python -B tests/mesh_clip_cull_check.py ./out/pe-env/bin/python -B tests/mesh_dynamic_aot_check.py +./out/pe-env/bin/python -B tests/mesh_entry_check.py flat-scratch ./out/pe-env/bin/python -B tests/mesh_heap_sampler_check.py ./out/pe-env/bin/python -B tests/mesh_lane_spill_check.py ./out/pe-env/bin/python -B tests/mesh_join_descriptor_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8fb309aea..7dd23d905 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8525,6 +8525,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/mesh_lane_spill_check.py") add_test(NAME mesh_entry_skipped_scalar_cpu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_entry_check.py" skipped) + add_test(NAME mesh_entry_flat_scratch_cpu COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_entry_check.py" flat-scratch) add_test(NAME mesh_scc_any_lane_cpu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_scc_any_lane_check.py") add_test(NAME mesh_loop_census COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 6b9b1a1d0..ad84f206f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4008,9 +4008,12 @@ the pattern does not match is reported as `other`, with nothing claimed. It then runs both bounded lowerers once per program and places the first refusal: at a latch, in a loop body, before the first loop or after one. The -run is repeated with the two flat-scratch setup writes replaced by `s_nop`, -because the lowerers refuse `s_setreg_imm32_b32` and that refusal otherwise -hides what follows. LLVM 15 prints a negative branch offset unsigned +run is repeated with the two flat-scratch setup writes replaced by `s_nop`. +The lowerers refused `s_setreg_imm32_b32` when the census was added, which hid +what follows; they now accept the setup (next section), so for a program with +no scratch-base reader both runs place the first refusal the same way. A +program with the setup and a reader is refused before execution in the first +run, which the census reports as "after execution". LLVM 15 prints a negative branch offset unsigned (`s_branch 65535`); the census reads it signed. The SCC-writer filter excludes scalar instructions by mnemonic prefix, so a later `s_mul_*` or `s_cselect_*` variant that writes SCC would be skipped. @@ -4028,6 +4031,40 @@ barrier placed before the header instead of in the body is a second control. 14 mutants each move one loop across one category boundary. The fixtures carry a loop and nothing else; they are not complete mesh programs. +### Scratch-base setup in the bounded mesh lowerers + +In the loop census input, the two `s_setreg_imm32_b32` writes to +`HW_REG_FLAT_SCR_LO` and `HW_REG_FLAT_SCR_HI` were the first refusal for 4,274 +of 4,458 programs (issue #1998). `tools/mesh_entry_aot.py` now lowers a +whole-register immediate write to either half to nothing, with the immediate +spelling `tools/compute_store_aot.py` accepts. `tools/mesh_dynamic_aot.py` +shares the wave model and gets the same rule. + +Only `scratch_*` and `flat_*` memory instructions and `s_getreg_b32` of these +registers read the scratch base. The wave model does not track the written +value and only checks the instructions it executes, so `run_group` scans the +whole decoded program first: if it holds an accepted write and any +`scratch_*`, `flat_*` or `s_getreg_*` instruction (the mesh lowerers lower no +`s_getreg_*` for any register), on any path, the program is refused. A field write +(`hwreg(HW_REG_FLAT_SCR_LO, 0, 16)`), the `s_setreg_b32` SGPR form, a +non-immediate source and every other hardware register stay refused. + +`tests/mesh_entry_check.py flat-scratch` checks that the program with the +two writes prefixed lowers to the same text as without them. It also refuses +a `scratch_load_dword`, a `flat_load_dword` and an `s_getreg_b32` of +`HW_REG_FLAT_SCR_LO`, each on a branch arm that no wave executes and that +lowers unchanged without the writes, and the four refused write forms. +`tests/mesh_dynamic_aot_check.py` repeats the equivalence and the skipped +scratch load, with the same control, for the run-time lowerer. +`tests/mesh_loop_census_check.py` now expects the setup fixture to reach its +latch in both census runs. + +```sh +python3 -B tests/mesh_entry_check.py flat-scratch +python3 -B tests/mesh_dynamic_aot_check.py +python3 -B tests/mesh_loop_census_check.py +``` + ## Amplification and mesh pipeline forms `tests/mesh_amplified_check.py` builds an amplification shader (`as_6_5`) and a diff --git a/tests/mesh_dynamic_aot_check.py b/tests/mesh_dynamic_aot_check.py index 105c2a3bc..3e7090071 100644 --- a/tests/mesh_dynamic_aot_check.py +++ b/tests/mesh_dynamic_aot_check.py @@ -182,6 +182,17 @@ def check(): check_exec_restore(decoded) hlsl = lower(decoded, 2, MESH_LIMITS) + writes = [ + (0, "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO), 0x1234"), + (8, "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_HI), 0"), + ] + assert lower(writes + [(pc + 16, line) for pc, line in decoded], 2, MESH_LIMITS) == hlsl + dead_arm = [(0, "s_branch 2"), (4, "scratch_load_dword v4, v1, off")] + # Without the writes the skipped scratch load is never checked; with them it refuses the program. + assert lower(dead_arm + [(pc + 12, line) for pc, line in decoded], 2, MESH_LIMITS) == hlsl + dead_scratch = writes + [(pc + 16, line) for pc, line in dead_arm] + expect_refusal(dead_scratch + [(pc + 28, line) for pc, line in decoded], 2, + "may be observed by scratch_load_dword") assert hlsl.count("SetMeshOutputCounts(") == 1 assert "ByteAddressBuffer geometryData : register(t0);" in hlsl assert "geometryData.Load(0)" in hlsl and "geometryData.Load(4)" in hlsl diff --git a/tests/mesh_entry_check.py b/tests/mesh_entry_check.py index c5f48eb12..c4ef7bdef 100644 --- a/tests/mesh_entry_check.py +++ b/tests/mesh_entry_check.py @@ -126,6 +126,42 @@ def enumerate_pcs(program): return [(i * 4, line) for i, line in enumerate(program)] +def flat_scratch_checks(decoded, expected): + writes = [ + (0, "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO), 0x1234"), + (8, "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_HI), 0"), + ] + + def lower_prefixed(prefix, size): + return lower(prefix + [(pc + size, line) for pc, line in decoded], [0x1003], (3, 1)) + + assert lower_prefixed(writes, 16) == expected + # The branch skips an eight-byte scratch instruction on every wave. + skipped = [(0, "s_branch 2"), (4, "scratch_load_dword v4, v1, off")] + assert lower_prefixed(skipped, 12) == expected + # Each observer sits on a skipped arm, so only the whole-program check can refuse it; without the + # writes the same arms lower to the expected text. + flat = [(16, "s_branch 2"), (20, "flat_load_dword v4, v[2:3]")] + getreg = [(16, "s_branch 1"), (20, "s_getreg_b32 s48, hwreg(HW_REG_FLAT_SCR_LO)")] + assert lower_prefixed([(pc - 16, line) for pc, line in flat], 12) == expected + assert lower_prefixed([(pc - 16, line) for pc, line in getreg], 8) == expected + for prefix, size, refused in ( + (writes + [(pc + 16, line) for pc, line in skipped], 28, "may be observed by scratch_load_dword"), + (writes + flat, 28, "may be observed by flat_load_dword"), + (writes + getreg, 24, "may be observed by s_getreg_b32"), + ([(0, "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO, 0, 16), 0")], 8, "s_setreg_imm32_b32"), + ([(0, "s_setreg_b32 hwreg(HW_REG_FLAT_SCR_LO), s3")], 4, "s_setreg_b32"), + ([(0, "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0")], 8, "s_setreg_imm32_b32"), + ([(0, "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO), s3")], 8, "s_setreg_imm32_b32"), + ): + try: + lower_prefixed(prefix, size) + except ValueError as error: + assert refused in str(error), error + else: + raise AssertionError(f"Accepted unsupported mesh instruction {refused}") + + def source(): # Branches only span scalar instructions of known 4-byte length. decoded = enumerate_pcs(PROGRAM) @@ -150,7 +186,9 @@ def source(): except (KeyError, ValueError): continue raise AssertionError("Invalid mesh path accepted") - return lower(decoded, [0x1003], (3, 1)) + expected = lower(decoded, [0x1003], (3, 1)) + flat_scratch_checks(decoded, expected) + return expected ALU_PROGRAM = PROGRAM.copy() @@ -1026,6 +1064,10 @@ def exec_restore_negative_draws(dxc, renderer, adapter, tmp): if sys.argv[1] == "skipped": skipped_cpu() sys.exit(0) + if sys.argv[1] == "flat-scratch": + source() + print("Scratch-base writes lowered to nothing and every observer was refused") + sys.exit(0) if sys.argv[1] == "draw-skipped": args = sys.argv[2:] sys.exit( diff --git a/tests/mesh_loop_census_check.py b/tests/mesh_loop_census_check.py index 2253c332e..401500ff9 100644 --- a/tests/mesh_loop_census_check.py +++ b/tests/mesh_loop_census_check.py @@ -22,7 +22,6 @@ LIMITS = (4, 2) BACK_EDGE = "Expected a forward mesh branch" -SETREG = "Unsupported scalar instruction s_setreg_imm32_b32" # Shape columns: barrier in body, LDS access in body, body writes EXEC, latch tests EXEC, loop-carried scalar, trip. COUNTED = (False, False, False, False, True, "constant pattern") SCALAR_OTHER = (False, False, False, False, True, "other") @@ -168,12 +167,12 @@ def check_lowerers(): for tier in census.TIERS: assert refusal(counters, lowerer, tier) == ( {("at a latch", "with loops"): 1}, {(BACK_EDGE, "with loops"): 1}), (lowerer, tier) - # The scratch setup stops the program before its loop; with the two writes skipped the latch is reached. + # The lowerers accept the whole-register scratch-base setup, so the program reaches its latch as it + # does with the two writes skipped. counters = census.census([(program("flat-scratch setup"), LIMITS)]) - assert refusal(counters, lowerer, as_decoded) == ( - {("before the first loop", "with loops"): 1}, {(SETREG, "with loops"): 1}), lowerer - assert refusal(counters, lowerer, skipped) == ( - {("at a latch", "with loops"): 1}, {(BACK_EDGE, "with loops"): 1}), lowerer + for tier in (as_decoded, skipped): + assert refusal(counters, lowerer, tier) == ( + {("at a latch", "with loops"): 1}, {(BACK_EDGE, "with loops"): 1}), (lowerer, tier) # An unsupported latch is counted by name at its own instruction. latch = [(pc, text.replace("s_cbranch_scc1", "s_cbranch_execnz")) for pc, text in program("counted")] counters = census.census([(latch, LIMITS)]) diff --git a/tools/mesh_entry_aot.py b/tools/mesh_entry_aot.py index 74217daaf..d53d0365f 100644 --- a/tools/mesh_entry_aot.py +++ b/tools/mesh_entry_aot.py @@ -24,6 +24,18 @@ LANE_SPILL_OPS = {"v_writelane_b32", "v_readlane_b32"} VGPR_OPERAND = re.compile(r"\bv(?:(\d+)\b|\[(\d+):(\d+)\])") LDS_BYTES = 1 << 16 +FLAT_SCRATCH_WRITE = re.compile(r"s_setreg_imm32_b32 hwreg\(HW_REG_FLAT_SCR_(?:LO|HI)\), (.+)") +# The immediate spellings compute_store_aot accepts for the same write (a copy of its pattern). +IMM32_LITERAL = re.compile( + r"-?(?:0x[0-9a-fA-F]+|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|nan|inf(?:inity)?)", + re.IGNORECASE, +) + + +def flat_scratch_write(line): + """A whole-register immediate write of either half of the scratch base.""" + match = FLAT_SCRATCH_WRITE.fullmatch(line) + return match is not None and IMM32_LITERAL.fullmatch(match[1]) is not None def branch_target(offset, operand): @@ -727,6 +739,8 @@ def exec_range(self, decoded, expressions, jumps, pc, stop, arm=False): offset, line = decoded[pc] pc += 1 op, _, tail = line.partition(" ") + if flat_scratch_write(line): + continue args = tail.split(", ") if op in LANE_SPILL_OPS: self.lane_spill(op, args) @@ -917,6 +931,16 @@ def run_group(waves, decoded, expressions): Each wave runs to its next barrier before any wave goes on. Stores become visible to every wave only when all of them have reached the barrier. """ + # Whole-register immediate writes of the scratch base lower to nothing when + # nothing can read either half: scratch_* and flat_* memory forms and + # s_getreg_* (which these lowerers do not lower for any register). Check every + # instruction, including skipped arms, since the wave model does not track the + # written value and only checks the instructions it executes. + if any(flat_scratch_write(line) for _, line in decoded): + for _, line in decoded: + op = line.partition(" ")[0] + if op.startswith(("scratch_", "flat_", "s_getreg_")): + raise ValueError(f"Mesh scratch-base write may be observed by {op}") lds = {} for wave in waves: wave.lds = lds From 3ef8f24fbbb1d5bb573e7eb68de2157863f8dfac Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:13:10 +0100 Subject: [PATCH 139/232] startup: s_load with a constant register offset reaches the heap descriptor (continues #2066, Part of #1723) (#2517) * startup: s_load with a constant register offset reaches the heap descriptor (#1723) Fold only in shaders without branches, sign-extend s_movk_i32, and document the accepted form. * startup: drop the s_movk_i32 sign extension that main already applies 8e0ef148 sign-extends the SOPK i32 immediates through sopk_imm before this branch, so a 0x8000..0xffff value can no longer reach it. The startup_gfx2hlsl_sload_const_offset checks for the sign-extended value and the refused negative offset still pass on main's path. AI-assisted. * startup: refuse tagged constants as SMEM offsets and cover the edges const_soffset now takes only an untagged ('const', value) symbol, so the ('const', 0, 'unassigned') default-sampler placeholder is not folded to offset 0. New checks: s_mov_b32 0x8000 stays 0x8000, a constant plus an offset: modifier above 0xfffff is refused, the placeholder is refused, and a sampler-heap register offset is not folded. List startup_gfx2hlsl_sload_const_offset_check.py in AGENTS.md and the Linux CI Python list next to startup_gfx2hlsl_smem_offset_check.py, and drop the OS from the docs' evidence line. AI-assisted. --------- Co-authored-by: tedin7 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 3 + ...artup_gfx2hlsl_sload_const_offset_check.py | 83 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 22 +++++ 6 files changed, 113 insertions(+) create mode 100644 tests/startup_gfx2hlsl_sload_const_offset_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index d62cf5f7a..1aad82663 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -239,6 +239,7 @@ jobs: tests/startup_gfx2hlsl_watch_check.py \ tests/startup_translator_check.py \ tests/startup_gfx2hlsl_smem_offset_check.py \ + tests/startup_gfx2hlsl_sload_const_offset_check.py \ tests/startup_archive_requests_check.py \ tests/startup_gfx2hlsl_refusals_check.py \ tests/startup_compute_request_offline_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 98f718a83..da7d4c281 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,6 +178,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_watch_check.py ./out/pe-env/bin/python -B tests/startup_translator_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_smem_offset_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sload_const_offset_check.py ./out/pe-env/bin/python -B tests/startup_archive_requests_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_refusals_check.py ./out/pe-env/bin/python -B tests/startup_compute_request_offline_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dd23d905..c2df5bcd5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3833,6 +3833,9 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_join_symbols_folded_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 PASS_REGULAR_EXPRESSION "control OUTSIDE: 3 in all four channels") endforeach() + # Startup shader translator: s_load with a register offset holding a known constant reaches the heap descriptor (#1723). + add_test(NAME startup_gfx2hlsl_sload_const_offset COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_const_offset_check.py") # Startup shader translator: uniform sources of v_readfirstlane_b32 in straight-line code and entry blocks (#1723). add_test(NAME startup_gfx2hlsl_readfirstlane_uniform COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index ad84f206f..6a8e5d416 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14554,10 +14554,13 @@ python -B tools/startup/gfx2hlsl.py --refusals out/startup/shader_cache | a literal (`0x4`, `16`) | byte offset into the buffer, `rN.Load(0x00000004u + 4 * i)` | byte offset from the pointer | | `off` | the literal 0 | the literal 0 | | `m0` | register byte offset, `rN.Load(m0 + 4 * i)` | refused (`s_load with a register offset through ...`), except for the run-time sampler heap index | +| `s0`..`s105` holding a constant (`s_mov_b32`/`s_movk_i32` before the load) | not changed | that constant as a literal byte offset, plus any `offset:` modifier; the total is 0..0xfffff | | anything else (`null`, `OFF`, `offset`, ...) | refused (`operand '...'`) | refused | `off` names no offset at all, so it is translated exactly as the literal 0: the same emitted HLSL, the same descriptor offset for a table load, and the same fixed-word marking of an `s_buffer_load` result. Before this change, `s_buffer_load_dword s0, s[4:7], off` was refused with `operand 'off'`, and the `s_load` form with the misleading register-offset message. `tests/startup_gfx2hlsl_smem_offset_check.py` drives each load handler on a scalar symbol state with no machine code. It compares the `off` form of `s_buffer_load_dword`, `_dwordx2` and `_dwordx4`, of `s_load_dword` and `_dwordx2` from a root buffer and of `s_load_dwordx8` from a descriptor table with the literal 0, keeps the literal and `m0` behaviour above, and requires five other operand spellings to be refused by both kinds of load. With the `off` handling removed in-process, both `off` forms must be refused again. Test: `startup_gfx2hlsl_smem_offset`. Not covered here: whether the full set of locally refused shaders now translates, which needs local inputs. +**Constant register offsets for `s_load_dword*`.** An SGPR that holds a known constant (`s_movk_i32 s9, 0x40` before the load) is translated as the literal offset, which reaches descriptors in a bindless heap. Limits: the proof is used only in shaders without branches, because symbols are not merged at control-flow joins; `s_movk_i32` sign-extends its 16-bit immediate, so `0x8000` and above become negative and stay refused; the run-time sampler heap index is unchanged; an SGPR with an unknown value, `m0`, and a total above 0xfffff stay refused. Measured on CPU only (translation checks); D3D12 and GPU behavior are not measured. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sload_const_offset$' -V` or `python3 -B tests/startup_gfx2hlsl_sload_const_offset_check.py`. [Part of #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) + ### Scalar writes to and symbolic tracking of `m0` `Stage.scalar()` in [`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) previously returned `None` whenever `dname == 'm0'`, dropping every scalar ALU write (and its `SCC` update) to `m0` even though `Stage.u('m0')` and `Stage.op_s_buffer_load_dword()` read `m0` as a runtime `uint` variable. In addition, `scalar_select()`, `op_s_bfm_b32()`, `op_s_and_saveexec_b64()` and `op_s_andn2_wrexec_b64()` subscripted `reg_range(ops[0])` directly, raising `TypeError` on `m0`, and 64-bit scalar operations (`*_b64`, where `decode_s_reg64(124)` prints `m0`) silently vanished or raised `TypeError`. diff --git a/tests/startup_gfx2hlsl_sload_const_offset_check.py b/tests/startup_gfx2hlsl_sload_const_offset_check.py new file mode 100644 index 000000000..23fe611b3 --- /dev/null +++ b/tests/startup_gfx2hlsl_sload_const_offset_check.py @@ -0,0 +1,83 @@ +"""Check s_load with a register offset that holds a known constant (#1723). + +usage: startup_gfx2hlsl_sload_const_offset_check.py + +A title loads a descriptor from the resource heap with the byte offset in a scalar register that an earlier +s_movk filled. The translator must read that register as the literal offset (plus any offset: modifier), so +the result equals the literal form. An unknown register, m0, and the sampler heap keep their old handling. +""" +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH ' + detail}") + if not condition: + failures.append(label) + + +class Pipe: + sampler_heap = False + + def resource(self, key, kind): + return 'r0' + + +def run(symbols, op, operands, mods=(), branches=False): + s = G.Stage.__new__(G.Stage) + s.pipe, s.sym, s.lines = Pipe(), dict(symbols), [] + s.used_s, s.used_v, s.uniform_v, s.exec_known = set(), set(), set(), True + s.has_branches, s.masks = branches, set() + try: + if hasattr(s, 'op_' + op): + getattr(s, 'op_' + op)(operands.split(', '), list(mods)) + else: + s.one(op, '%s %s' % (op, operands)) + except G.Unsupported as error: + return str(error) + return s.sym + + +HEAP = {4: ('ptr', ('resheap',)), 9: ('const', 0x40), 10: ('ud', 0)} +want = [('desc', ('resheap',), 0x40, i) for i in range(8)] + +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9') +check('constant register offset reaches the heap descriptor', + isinstance(got, dict) and [got[16 + i] for i in range(8)] == want, repr(got)) +literal = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], 0x40') +check('same as the literal offset', isinstance(got, dict) and isinstance(literal, dict) + and [got[16 + i] for i in range(8)] == [literal[16 + i] for i in range(8)]) +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9', ['offset:0x20']) +check('offset: modifier adds to the register', isinstance(got, dict) and got[16] == ('desc', ('resheap',), 0x60, 0), repr(got)) +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s10') +check('unknown register still refused', got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], m0') +check('m0 still refused', got == "s_load with a register offset through ('resheap',)", repr(got)) + +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9', branches=True) +check('constant offset in a shader with branches is refused', got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run({}, 's_movk_i32', 's9, 0x8000') +check('s_movk_i32 sign-extends its 16-bit immediate', isinstance(got, dict) and got[9] == ('const', 0xffff8000), repr(got)) +got = run({4: ('ptr', ('resheap',)), 9: ('const', 0xffff8000)}, 's_load_dwordx8', 's[16:23], s[4:5], s9') +check('a negative movk offset is refused', got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run({}, 's_movk_i32', 's9, 0x7fff') +check('positive movk immediate unchanged', isinstance(got, dict) and got[9] == ('const', 0x7fff), repr(got)) +got = run({}, 's_mov_b32', 's9, 0x8000') +check('s_mov_b32 0x8000 is not sign-extended', isinstance(got, dict) and got[9] == ('const', 0x8000), repr(got)) + +got = run(HEAP, 's_load_dwordx8', 's[16:23], s[4:5], s9', ['offset:0xfffe0']) +check('a constant plus modifier above 0xfffff is refused', got == 'SMEM register offset 0x100020', repr(got)) +got = run({4: ('ptr', ('resheap',)), 9: ('const', 0, 'unassigned')}, 's_load_dwordx8', 's[16:23], s[4:5], s9') +check('the unassigned placeholder is not a constant offset', + got == "s_load with a register offset through ('resheap',)", repr(got)) +got = run({4: ('ptr', ('smpheap',)), 9: ('const', 0x40)}, 's_load_dwordx8', 's[16:23], s[4:5], s9') +check('a sampler heap register offset keeps its old handling', not (isinstance(got, dict) and got.get(16, (None,))[0] == 'desc' + and got[16][2] == 0x40), repr(got)) + +print('s_load constant offset checks: %d failed' % len(failures)) +sys.exit(1 if failures else 0) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 34f5a14a3..7b5e76021 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3194,6 +3194,20 @@ def smem_soffset(self, tok, record_use=True): self.used_s = saved raise Unsupported('operand %r' % tok) + def const_soffset(self, tok): + """The constant held by an SMEM offset register s0..s105, or None (m0 and unknown values).""" + r = reg_range(tok) + # Symbols are not merged at control-flow joins, so a constant proves the runtime value only without branches. + if getattr(self, 'has_branches', True): + return None + if r and r[0] == 's' and r[1] == r[2] and r[1] <= 105: + # A tagged constant (the ('const', 0, 'unassigned') default-sampler placeholder) is not a run-time value. + sym = self.sym.get(r[1]) + value = self.is_const(r[1]) if sym and len(sym) == 2 else None + if value is not None and 0 <= value <= 0xfffff: + return value + return None + def op_s_load_dwordx4(self, ops, mods, count=4): imm = smem_mods(mods) if len(ops) != 3: @@ -3211,6 +3225,14 @@ def op_s_load_dwordx4(self, ops, mods, count=4): raise Unsupported('s_load through s%d holding %s' % (base[1], p)) # 'off' names no offset operand at all, so the byte offset is zero, as for the literal 0. token = smem_offset(ops[2]) + known = self.const_soffset(token) if p[1] != ('smpheap',) else None + if known is not None: + # A register offset that holds a known constant (s_movk before the load) is that literal byte + # offset; the modifier adds to it. This reaches descriptors in a bindless heap (#1723). + total = known + (imm or 0) + if total > 0xfffff: + raise Unsupported('SMEM register offset %#x' % total) + token, imm = str(total), None if re.fullmatch(r'-?(?:0[xX][0-9a-fA-F]+|\d+)', token): off = int(token, 0) if off < 0 or off > 0xfffff: From 42d690a792e2d192fd11b81d2e795d264807ac2b Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 04:13:24 +0800 Subject: [PATCH 140/232] tests: run explicit shader and reference pairs on one pixel device (#2525) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- CMakeLists.txt | 4 ++ docs/experiments.md | 7 ++++ tests/offscreen_check.cpp | 23 ++++++++--- tests/pixel_batch_pairs_check.py | 67 ++++++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 5 deletions(-) create mode 100644 tests/pixel_batch_pairs_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index c2df5bcd5..7ed68f969 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9239,6 +9239,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} ${control}) set_tests_properties(pixel_batch_${control}_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) endforeach() + add_test(NAME pixel_batch_pairs_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_batch_pairs_check.py" "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_batch_pairs_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME pixel_aot_u32_from_f32_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_uint_conversion_check.py" "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 6a8e5d416..a79ec1c21 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7413,6 +7413,13 @@ following valid draw must pass. The fixture checks each status in order and checks the process exit code. This leaves four device creations for the predicate groups in place of 21, without changing the number of DXC calls. +`offscreen_check --check-pixel-pairs [ ...]` +runs different compiled pixel shaders on one D3D12 device. Each pair reports +its own indexed status and names both files on stderr. A mismatch or error +sets the process exit code to 1. The remaining pairs still report a status. +Run `ctest --preset dev --no-tests=error -R '^pixel_batch_pairs_(hardware|warp)$' -V` +to compare two shaders with isolated draws and exercise mismatch and missing-file controls. + The 32-bit integer, 16-bit integer and SDWA predicate draws use the same runner, one batch per compiled group, with the same references. The signed-against-unsigned control of the first `i32` e32 group and the diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 57f64c8cf..8b8a9f675 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -430,6 +430,11 @@ bool validate_check_pixel_args(int, char** argv) return format == "rgba" || format == "bgra"; } +bool validate_pixel_pairs_args(int argc, char**) +{ + return (argc - 3) % 2 == 0; +} + bool validate_mesh_entry_args(int argc, char** argv) { if (argc == 6) return true; @@ -457,14 +462,18 @@ bool validate_compute_mesh_texture_fallback_args(int argc, char** argv) template OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_draw) { + const bool pairs = std::string_view(ctx.argv[2]) == "--check-pixel-pairs"; + const int stride = pairs ? 2 : 1; bool failed = false; - for (int i = 4; i < ctx.argc; ++i) { + for (int i = 4, index = 0; i < ctx.argc; i += stride, ++index) { + const char* shader = ctx.argv[pairs ? i - 1 : 3]; const char* status = "pass"; - std::fprintf(stderr, "case=%d path=%s\n", i - 4, ctx.argv[i]); + std::fprintf(stderr, "case=%d path=%s\n", index, ctx.argv[i]); + if (pairs) std::fprintf(stderr, "shader=%s\n", shader); try { check(ctx.device->GetDeviceRemovedReason(), "Pixel batch device"); - check_translated_pixel(ctx.device, ctx.argv[3], false, ctx.argv[i]); - after_draw(i - 4); + check_translated_pixel(ctx.device, shader, false, ctx.argv[i]); + after_draw(index); } catch (const PixelMismatch& e) { std::fprintf(stderr, "%s\n", e.what()); status = "mismatch"; @@ -475,7 +484,7 @@ OperationResult run_pixel_batch(const OperationContext& ctx, AfterDraw after_dra if (report_debug_errors(ctx.messages) || FAILED(ctx.device->GetDeviceRemovedReason())) status = "error"; if (ctx.messages) ctx.messages->ClearStoredMessages(); - std::printf("case=%d status=%s\n", i - 4, status); + std::printf("case=%d status=%s\n", index, status); failed |= std::string_view(status) != "pass"; } return failed ? OperationResult{OutcomeKind::fail, nullptr} : OperationResult{OutcomeKind::pass, nullptr}; @@ -1561,6 +1570,7 @@ constexpr CapabilityGate kGateSm66MinLod{ // remain inside the handlers and report OutcomeKind::skip. const OperationSpec kOperations[] = { {"--check-pixel-batch", 5, kUnboundedArgc, nullptr, kNoGate, run_check_pixel_batch}, + {"--check-pixel-pairs", 5, kUnboundedArgc, validate_pixel_pairs_args, kNoGate, run_check_pixel_batch}, {"--pixel-batch-debug-control", 7, 7, nullptr, kNoGate, run_pixel_batch_debug_control}, {"--pixel-batch-removal-control", 7, 7, nullptr, kNoGate, run_pixel_batch_removal_control}, {"--compute-root", 3, 3, nullptr, kNoGate, run_compute_root}, @@ -1923,6 +1933,9 @@ int run_self_test() return 1; if (!check_cli({"offscreen_check", "warp", "--spirv-ballot", "a.dxil"}, CliAction::usage_error, "Unknown GPU operation or invalid arguments: --spirv-ballot")) return 1; + if (!check_cli({"offscreen_check", "warp", "--check-pixel-pairs", "a.cso", "a.case", "b.cso"}, + CliAction::usage_error, "Unknown GPU operation or invalid arguments: --check-pixel-pairs")) + return 1; if (!check_cli({"offscreen_check", "warp", "--check-pixel", "a.cso", "invalid"}, CliAction::usage_error, "Unknown GPU operation or invalid arguments: --check-pixel")) return 1; if (!check_cli({"offscreen_check", "warp", "--mesh-entry", "a", "b", "c", "invalid"}, CliAction::usage_error, diff --git a/tests/pixel_batch_pairs_check.py b/tests/pixel_batch_pairs_check.py new file mode 100644 index 000000000..cfc56f7e8 --- /dev/null +++ b/tests/pixel_batch_pairs_check.py @@ -0,0 +1,67 @@ +"""Compare a sequence of two pixel shaders on one device with isolated draws.""" +from pathlib import Path +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory + + +def verify(dxc, renderer, adapter, directory): + shaders = [] + cases = [] + for label, expression, output in (("rg", "color", (0.25, 0.75, 0.5, 1.0)), + ("gr", "color.grba", (0.75, 0.25, 0.5, 1.0))): + source = directory / f"{label}.hlsl" + source.write_text("cbuffer Params : register(b0) { float4 color; };\n" + f"float4 main() : SV_Target {{ return {expression}; }}\n", encoding="ascii") + shader = directory / f"{label}.dxil" + subprocess.run([dxc, "-T", "ps_6_0", "-E", "main", "-Fo", shader, source], check=True) + shaders.append(shader) + case = directory / f"{label}.case" + constants = struct.pack("<4f", 0.25, 0.75, 0.5, 1.0).ljust(256, b"\0") + case.write_bytes(constants + struct.pack("<4f", *output) * 64) + cases.append(case) + + def run(*args): + return subprocess.run([renderer, adapter, *args], capture_output=True, text=True) + + a, b = shaders + rg, gr = cases + sequence = [(a, rg), (b, rg), (b, gr), (a, rg)] + baseline = [] + for shader, case in sequence: + single = run("--check-pixel-case", shader, case) + if single.returncode == 77 and adapter == "hardware": + print(single.stdout + single.stderr) + return 77 + if single.returncode == 0: + baseline.append("pass") + elif single.returncode == 1 and "pixel_mismatch" in single.stderr: + baseline.append("mismatch") + else: + raise AssertionError(single.stdout + single.stderr) + assert baseline == ["pass", "mismatch", "pass", "pass"], baseline + + def check(pairs, statuses, code): + batch = run("--check-pixel-pairs", *(path for pair in pairs for path in pair)) + lines = [line for line in batch.stdout.splitlines() if line.startswith("case=")] + expected = [f"case={i} status={status}" for i, status in enumerate(statuses)] + if batch.returncode != code or lines != expected: + raise AssertionError(batch.stdout + batch.stderr) + return batch + + mixed = check(sequence, baseline, 1) + diagnostics = mixed.stderr.split("case=") + assert len(diagnostics) == len(sequence) + 1, mixed.stderr + for i, ((shader, case), section) in enumerate(zip(sequence, diagnostics[1:])): + assert section.startswith(f"{i} path={case}\nshader={shader}\n"), section + assert ("pixel_mismatch" in section) == (baseline[i] == "mismatch"), section + check([(a, rg), (b, gr)], ["pass", "pass"], 0) + check([(a, rg), (directory / "absent.dxil", rg), (b, gr)], ["pass", "error", "pass"], 1) + print("Two shaders matched the four isolated results. The missing shader failed only its own case.") + return 0 + + +if __name__ == "__main__": + with TemporaryDirectory() as folder: + sys.exit(verify(*sys.argv[1:], Path(folder))) From 5123cc6d0cd9c7730d39e9d989f38dc060a987d1 Mon Sep 17 00:00:00 2001 From: KomaGuy Date: Wed, 25 Nov 2026 23:13:40 +0300 Subject: [PATCH 141/232] pixel_aot: lower binary16 SDWA arith, round, ldexp, and cvt forms (#2519) Co-authored-by: KomaGuy <265821007+KomaGuy@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 18 ++ tests/form_coverage_check.py | 40 ++++ tests/pixel_aot_check.py | 357 ++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 311 ++++++++++++++++++++++++++++++ 5 files changed, 722 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7ed68f969..34c78eb0b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9137,6 +9137,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_dpp_f16_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_dpp_f16_${adapter}.txt") + add_test(NAME pixel_aot_sdwa_f16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-sdwa-f16 "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sdwa_f16_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_f16_${adapter}.txt") add_test(NAME pixel_aot_dpp_extra_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-dpp-extra "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index a79ec1c21..3132b2d25 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15193,3 +15193,21 @@ Building on #2443 (Slice 1), `X2W_D3D12_RELEASE_RETIRED=1` extends desktop objec ```powershell ctest --preset dev --no-tests=error -R '^startup_resource_(retire|budget)' -V ``` + +## Binary16 SDWA arithmetic, rounding, scaling and conversions in pixel_aot + +[The pixel shader translator](../tools/pixel_aot.py) adds 14 contracted binary16 `SDWA` forms (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): + +- VOP2 arithmetic (4): `v_add_f16_sdwa`, `v_sub_f16_sdwa`, `v_subrev_f16_sdwa`, `v_mul_f16_sdwa` +- VOP2 scaling (1): `v_ldexp_f16_sdwa` +- VOP1 rounding (4): `v_floor_f16_sdwa`, `v_ceil_f16_sdwa`, `v_trunc_f16_sdwa`, `v_rndne_f16_sdwa` +- VOP1 conversions (5): `v_cvt_f16_f32_sdwa`, `v_cvt_f16_i16_sdwa`, `v_cvt_f16_u16_sdwa`, `v_cvt_i16_f16_sdwa`, `v_cvt_u16_f16_sdwa` + +All 14 require explicit `half_denorm="preserve"` and refuse `HALF_RTZ` (via `HW_REG_MODE`). Binary16 float sources accept VGPRs or SGPRs with `WORD_0`, `WORD_1`, or `DWORD` selection and optional bit-15 `abs`/`neg` modifiers (`half16` sources allow `WORD_0` only), under the static finite-proof contract; `v_cvt_f16_f32_sdwa` requires `src0_sel:DWORD` with optional bit-31 `abs`/`neg` modifiers. Integer sources (`v_ldexp_f16_sdwa` `src1`, `v_cvt_f16_{i16,u16}_sdwa` `src0`) accept `BYTE_0..3`, `WORD_0..1`, or `DWORD` with optional `sext()` and refuse float modifiers (`low16` sources allow `WORD_0`/`BYTE_0`/`BYTE_1` only; `u16` requires a static proof `< 65520`; `ldexp` requires a static exponent in `[-64, 64]`). Destination placement keeps the low-16-only contract (`("half16", alu)` / `("low16", alu)`) for `dst_sel:DWORD`, defines all 32 bits with `known_ssa_bits` tracking for `dst_sel:WORD_0` / `WORD_1` under `UNUSED_PAD` or `UNUSED_PRESERVE`, and refuses `UNUSED_SEXT`, `BYTE_*` destinations, `clamp`, and `omod`. + +```powershell +python3 tests/pixel_aot_check.py +ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_f16_warp|pixel_aot_sdwa_f16_hardware|pixel_aot_binary)$' -V +``` + +Linux controls, `form_coverage_check.check_sdwa_f16_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index a902aa14a..9ecb93f87 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -1495,6 +1495,45 @@ def check_dpp_f16_cvt_fmac_ldexp_forms(): pixel.ACCEPTED.update(saved) +def check_sdwa_f16_forms(): + """The 14 contracted binary16 SDWA forms count as covered once the translator accepts their + fixtures; unlowered binary16 SDWA neighbours stay uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for body in (*pixel.SDWA_F16_PROGRAMS.values(), pixel.SDWA_F16_CVT_F32_BODY): + pixel.translate_f16(pixel.uncompressed_export(body)) + ops = ( + "v_add_f16_sdwa", "v_sub_f16_sdwa", "v_subrev_f16_sdwa", "v_mul_f16_sdwa", + "v_ldexp_f16_sdwa", "v_floor_f16_sdwa", "v_ceil_f16_sdwa", "v_trunc_f16_sdwa", + "v_rndne_f16_sdwa", "v_cvt_f16_f32_sdwa", "v_cvt_f16_i16_sdwa", "v_cvt_f16_u16_sdwa", + "v_cvt_i16_f16_sdwa", "v_cvt_u16_f16_sdwa", + ) + forms = {("SDWA", op) for op in ops} + assert len(forms) == 14 + neighbours = { + ("SDWA", "v_min_f16_sdwa"), ("SDWA", "v_max_f16_sdwa"), + ("SDWA", "v_fract_f16_sdwa"), ("SDWA", "v_rcp_f16_sdwa"), + ("SDWA", "v_cvt_norm_i16_f16_sdwa"), ("SDWA", "v_cvt_norm_u16_f16_sdwa"), + ("SDWA", "v_cvt_pkrtz_f16_f32_sdwa"), ("SDWA", "v_frexp_mant_f16_sdwa"), + ("SDWA", "v_frexp_exp_i16_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not (neighbours & covered), (name, sorted(neighbours & covered)) + # Control: removing one opcode removes its SDWA form from the count. + stripped = pixel.ACCEPTED - {"v_ldexp_f16_sdwa"} + assert ("SDWA", "v_ldexp_f16_sdwa") not in fc.gfx_forms(stripped, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + if __name__ == "__main__": check_denominators() check_example() @@ -1517,6 +1556,7 @@ def check_dpp_f16_cvt_fmac_ldexp_forms(): check_f16_to_int16_forms() check_dpp_f16_arith_round_forms() check_dpp_f16_cvt_fmac_ldexp_forms() + check_sdwa_f16_forms() check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index c7f8a45ba..43f65bd72 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -10767,6 +10767,341 @@ def check_dpp_f16_draw(directory, compiler, renderer, backend): return 0 +# SDWA binary16 fixtures covering 14 SDWA forms across arithmetic (add/sub/subrev/mul), rounding +# (floor/ceil/trunc/rndne), exponent scaling (ldexp), int16<->f16 conversions, and f32->f16 conversion. +# Exercises WORD_0/WORD_1/DWORD/BYTE_* selections, float abs/neg and integer sext() modifiers, +# dst_sel:DWORD (low-16-only half16/low16 contract), WORD_0/WORD_1 UNUSED_PAD and UNUSED_PRESERVE +# packing, subnormals under -denorm ftz, and ties-to-even rounding. +SDWA_F16_PROGRAMS = { + "arith": [ + "v_mov_b32_e32 v20, 0x3e003c00", # WORD_0=1.0, WORD_1=1.5 + "v_mov_b32_e32 v21, 0xc0000001", # WORD_0=2^-24 (subnormal), WORD_1=-2.0 + "s_mov_b32 s60, 0x4200bc00", # WORD_0=-1.0, WORD_1=3.0 + "s_mov_b32 s61, 0x3c030002", # WORD_0=2*2^-24 (subnormal), WORD_1=1+3*2^-10 + # ch0: 1.5 + (-2.0) = -0.5 (0xb800), dst_sel:DWORD keeps low-16-only half16 contract. + "v_add_f16_sdwa v24, v20, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_1", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + # ch1: 2*2^-24 - (-2^-24) = 3*2^-24 (0x0003, subnormal preserved under -denorm ftz). + "v_sub_f16_sdwa v13, s61, -v21 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", + # ch2: subrev(-3.0, 1.0) = 1.0 - (-3.0) = 4.0 (0x4400) placed into WORD_1 with UNUSED_PAD. + "v_subrev_f16_sdwa v14, -s60, v20 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD", + # ch3: pack (-|-2.0|)*(-1.0) = 2.0 (0x4000) into WORD_0, then in-place 2.0 + (1+3*2^-10) = 0x4202 + # (ties-to-even) into WORD_1 with UNUSED_PRESERVE -> 0x42024000. + "v_mul_f16_sdwa v15, -|v21|, s60 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0", + "v_add_f16_sdwa v15, v15, s61 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_1", + ], + "round_ldexp": [ + "v_mov_b32_e32 v20, 0xbe003e00", # WORD_0=1.5, WORD_1=-1.5 + "v_mov_b32_e32 v21, 0x4100c100", # WORD_0=-2.5, WORD_1=2.5 + "s_mov_b32 s60, 0x00fe0003", # BYTE_0=3, BYTE_2=0xfe (sext=-2) + "v_mov_b32_e32 v22, 0x00020400", # WORD_0=2^-14 (smallest normal), WORD_1=2 + # ch0: floor(-1.5) = -2.0 (0xc000) in WORD_0, ceil(-1.5) = -1.0 (0xbc00) in WORD_1 -> 0xbc00c000. + "v_floor_f16_sdwa v12, v20 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_ceil_f16_sdwa v12, -v20 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + # ch1: trunc(-2.5) = -2.0 (0xc000) in WORD_0, rndne(2.5) = 2.0 (0x4000, ties-to-even) in WORD_1 -> 0x4000c000. + "v_trunc_f16_sdwa v13, v21 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rndne_f16_sdwa v13, v21 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + # ch2: |-1.5| * 2^3 = 12.0 (0x4a00), dst_sel:DWORD keeps low-16-only half16 contract. + "v_ldexp_f16_sdwa v24, |v20|, s60 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:BYTE_0", + "v_mov_b32_sdwa v14, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + # ch3: 2^-14 * 2^-2 = 2^-16 (0x0100 subnormal via sext BYTE_2) in WORD_0, -1.5 * 2^2 = -6.0 (0xc600) in WORD_1. + "v_ldexp_f16_sdwa v15, v22, sext(s60) dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:BYTE_2", + "v_ldexp_f16_sdwa v15, -v20, v22 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_1", + ], + "cvt_int16": [ + "v_mov_b32_e32 v20, 0xffef0007", # WORD_0=7, WORD_1=65519 (max finite u16) + "v_mov_b32_e32 v21, 0xc3804380", # WORD_0=3.75, WORD_1=-3.75 + "s_mov_b32 s60, 0xfbff7bff", # WORD_0=65504.0, WORD_1=-65504.0 + # ch0: runtime s44=0x0080ff80 -> sext(BYTE_0)=-128 (0xd800) in WORD_0, zero-ext BYTE_0=+128 (0x5800) in WORD_1. + "v_cvt_f16_i16_sdwa v12, sext(s44) dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:BYTE_0", + "v_cvt_f16_i16_sdwa v12, s44 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0", + # ch1: u16(65519) -> 65504.0 (0x7bff) in WORD_0, u16(7) -> 7.0 (0x4700) in WORD_1 -> 0x47007bff. + "v_cvt_f16_u16_sdwa v13, v20 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_f16_u16_sdwa v13, v20 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0", + # ch2: trunc(-3.75) = -3 (0xfffd) via dst_sel:DWORD (low16), trunc(3.75) = 3 (0x0003) in WORD_1 -> 0x0003fffd. + "v_cvt_i16_f16_sdwa v24, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_mov_b32_sdwa v14, v24 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_i16_f16_sdwa v14, v21 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + # ch3: trunc(|-65504.0|) = 65504 (0xffe0) in WORD_0, trunc(|-3.75|) = 3 (0x0003) in WORD_1 -> 0x0003ffe0. + "v_cvt_u16_f16_sdwa v15, |s60| dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_u16_f16_sdwa v15, |v21| dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + ], +} +SDWA_F16_CONSTANTS = { + "arith": (0, 0, 0, 0), + "round_ldexp": (0, 0, 0, 0), + "cvt_int16": (0x0080ff80, 0, 0, 0), +} +SDWA_F16_EXPECTED = { + "arith": (0x0000b800, 0x00000003, 0x44000000, 0x42024000), + "round_ldexp": (0xbc00c000, 0x4000c000, 0x00004a00, 0xc6000100), + "cvt_int16": (0x5800d800, 0x47007bff, 0x0003fffd, 0x0003ffe0), +} +SDWA_F16_MUTATIONS = { + "arith": ( + ("v_add_f16_sdwa v24, v20, v21", "v_sub_f16_sdwa v24, v20, v21"), + ("v_sub_f16_sdwa v13, s61, -v21", "v_sub_f16_sdwa v13, s61, v21"), + ("v_subrev_f16_sdwa v14, -s60, v20", "v_sub_f16_sdwa v14, -s60, v20"), + ("v_add_f16_sdwa v15, v15, s61 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_add_f16_sdwa v15, v15, s61 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), + "round_ldexp": ( + ("v_floor_f16_sdwa v12, v20", "v_ceil_f16_sdwa v12, v20"), + ("v_trunc_f16_sdwa v13, v21", "v_floor_f16_sdwa v13, v21"), + ("v_rndne_f16_sdwa v13, v21", "v_ceil_f16_sdwa v13, v21"), + ("v_ldexp_f16_sdwa v24, |v20|, s60", "v_ldexp_f16_sdwa v24, v20, s60"), + ("src1_sel:BYTE_2", "src1_sel:BYTE_0"), + ), + "cvt_int16": ( + ("v_cvt_f16_i16_sdwa v12, sext(s44)", "v_cvt_f16_i16_sdwa v12, s44"), + ("v_cvt_f16_u16_sdwa v13, v20 dst_sel:WORD_0", "v_cvt_f16_i16_sdwa v13, v20 dst_sel:WORD_0"), + ("v_cvt_i16_f16_sdwa v24, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_i16_f16_sdwa v24, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"), + ("v_cvt_u16_f16_sdwa v15, |v21| dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_cvt_u16_f16_sdwa v15, |v21| dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), +} +SDWA_F16_CVT_F32_BODY = [ + "v_mov_b32_e32 v20, s46", + "v_mov_b32_e32 v15, 0x0000beef", + "v_cvt_f16_f32_sdwa v24, s44 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_mov_b32_sdwa v12, v24 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_f16_f32_sdwa v13, -s45 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_cvt_f16_f32_sdwa v14, |v20| dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_cvt_f16_f32_sdwa v15, -|s47| dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", +] + + +def check_sdwa_f16_controls(): + """Positive and negative controls for all 14 contracted binary16 SDWA forms.""" + sdwa1 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + sdwa2 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0" + for name, body in SDWA_F16_PROGRAMS.items(): + prog = uncompressed_export(body) + hlsl = translate_f16(prog) + for old, new in SDWA_F16_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + assert translate_f16(mutated) != hlsl, (name, old, new) + cvt_f32_prog = uncompressed_export(SDWA_F16_CVT_F32_BODY) + cvt_f32_hlsl = translate_f16(cvt_f32_prog) + assert "narrow16(" in cvt_f32_hlsl + # Positive chaining controls: low16 -> v_cvt_f16_i16_sdwa (WORD_0/BYTE_0/BYTE_1), + # half16 -> v_add_f16_sdwa / v_cvt_u16_f16_sdwa (WORD_0), abs(reg) spelling accepted. + for body in ( + ["v_mov_b32_e32 v20, 0x3e003c00", + f"v_cvt_i16_f16_sdwa v24, v20 {sdwa1}WORD_0", + f"v_cvt_f16_i16_sdwa v25, sext(v24) {sdwa1}BYTE_1", + f"v_mov_b32_sdwa v12, v25 {sdwa1}WORD_0"], + ["v_mov_b32_e32 v20, 0x0005", + f"v_cvt_f16_u16_sdwa v24, v20 {sdwa1}WORD_0", + f"v_cvt_u16_f16_sdwa v25, abs(v24) {sdwa1}WORD_0", + f"v_mov_b32_sdwa v12, v25 {sdwa1}WORD_0"], + ["v_mov_b32_e32 v20, 0x3c00", + f"v_add_f16_sdwa v24, abs(v20), v20 {sdwa2}", + f"v_floor_f16_sdwa v25, v24 {sdwa1}WORD_0", + f"v_mov_b32_sdwa v12, v25 {sdwa1}WORD_0"], + ): + translate_f16(uncompressed_export(body)) + # Explicit entry denormal mode and HW_REG_MODE binary16 rounding controls across all families. + proven_pair = ["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 0x4000"] + for prog, op in ( + (uncompressed_export([*proven_pair, f"v_add_f16_sdwa v24, v20, v21 {sdwa2}", + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_0"]), "v_add_f16_sdwa"), + (uncompressed_export(["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2", + f"v_ldexp_f16_sdwa v24, v20, v21 {sdwa2}", + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_0"]), "v_ldexp_f16_sdwa"), + (uncompressed_export([*proven_pair, f"v_floor_f16_sdwa v24, v20 {sdwa1}WORD_0", + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_0"]), "v_floor_f16_sdwa"), + (cvt_f32_prog, "v_cvt_f16_f32_sdwa"), + (uncompressed_export([f"v_cvt_f16_i16_sdwa v24, s44 {sdwa1}WORD_0", + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_0"]), "v_cvt_f16_i16_sdwa"), + (uncompressed_export([*proven_pair, f"v_cvt_i16_f16_sdwa v24, v20 {sdwa1}WORD_0", + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_0"]), "v_cvt_i16_f16_sdwa"), + ): + expect_value_error(translate_int, prog, "binary16 denormal mode unknown at entry") + expect_value_error(translate_f16, [HALF_RTZ, *prog], f"under round toward zero: {op}") + assert translate_f16([HALF_RTZ, HALF_RNE, *prog]) == translate_f16(["s_nop 0", "s_nop 0", *prog]) + # Refusals: low-16-only dst_sel:DWORD contract, UNUSED_SEXT, BYTE_* dst_sel, UNUSED_PRESERVE on + # untracked/half16/low16 dst, finite proof, overflow, out-of-range, illegal source modifiers, clamp/omod, + # non-DWORD src0_sel on v_cvt_f16_f32_sdwa, and unlowered SDWA neighbours. + for prefix, bad, message in ( + # dst_sel:DWORD keeps low-16-only half16/low16 tags; WORD_1 and whole-word reads reject. + ([*proven_pair, f"v_add_f16_sdwa v24, v20, v21 {sdwa2}"], + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_1", "Reads the undefined high half of a 16-bit result"), + ([*proven_pair, f"v_add_f16_sdwa v24, v20, v21 {sdwa2}"], + f"v_floor_f16_sdwa v25, v24 {sdwa1}WORD_1", "Reads the undefined high half of a 16-bit result"), + ([*proven_pair, f"v_add_f16_sdwa v24, v20, v21 {sdwa2}"], + "v_mov_b32_e32 v12, v24", "Expected a numeric register"), + ([f"v_cvt_f16_f32_sdwa v24, s44 {sdwa1}DWORD"], + f"v_mov_b32_sdwa v12, v24 {sdwa1}WORD_1", "Reads the undefined high half of a 16-bit result"), + ([*proven_pair, f"v_cvt_i16_f16_sdwa v24, v20 {sdwa1}WORD_0"], + f"v_cvt_f16_i16_sdwa v25, v24 {sdwa1}WORD_1", "Reads the undefined high half of a 16-bit result"), + ([*proven_pair, f"v_cvt_i16_f16_sdwa v24, v20 {sdwa1}WORD_0"], + "v_cvt_f32_f16_e32 v12, v24", "Expected a numeric register"), + # Destination placement refusals. + (proven_pair, "v_add_f16_sdwa v24, v20, v21 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_0", + "UNUSED_SEXT is not lowered"), + (proven_pair, "v_floor_f16_sdwa v24, v20 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:WORD_0", + "UNUSED_SEXT is not lowered"), + (proven_pair, "v_add_f16_sdwa v24, v20, v21 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", + "Unsupported 16-bit SDWA destination selection: BYTE_0"), + (proven_pair, "v_add_f16_sdwa v24, v20, v21 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0", + "UNUSED_PRESERVE needs a tracked numeric destination"), + ([*proven_pair, f"v_add_f16_sdwa v24, v20, v21 {sdwa2}"], + "v_floor_f16_sdwa v24, v20 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "Reads the undefined high half of a 16-bit result"), + ([*proven_pair, f"v_cvt_i16_f16_sdwa v24, v20 {sdwa1}WORD_0"], + "v_cvt_i16_f16_sdwa v24, v20 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "Reads the undefined high half of a 16-bit result"), + # Source selection and modifier refusals. + ([], f"v_cvt_f16_f32_sdwa v24, s44 {sdwa1}WORD_0", "v_cvt_f16_f32_sdwa requires src0_sel:DWORD, got WORD_0"), + ([], f"v_cvt_f16_f32_sdwa v24, sext(s44) {sdwa1}DWORD", "Unsupported binary16 SDWA source modifier: sext(s44)"), + (proven_pair, f"v_add_f16_sdwa v24, v20, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:WORD_0", + "Unsupported binary16 SDWA source selection: BYTE_0"), + (proven_pair, f"v_add_f16_sdwa v24, sext(v20), v21 {sdwa2}", + "Unsupported binary16 SDWA source modifier: sext(v20)"), + (proven_pair, f"v_floor_f16_sdwa v24, sext(v20) {sdwa1}WORD_0", + "Unsupported binary16 SDWA source modifier: sext(v20)"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], f"v_ldexp_f16_sdwa v24, v20, -v21 {sdwa2}", + "Source modifiers are not allowed on -v21"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], f"v_ldexp_f16_sdwa v24, v20, |v21| {sdwa2}", + "Source modifiers are not allowed on |v21|"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 2"], f"v_ldexp_f16_sdwa v24, v20, abs(v21) {sdwa2}", + "Source modifiers are not allowed on abs(v21)"), + (["v_mov_b32_e32 v20, 1"], f"v_cvt_f16_i16_sdwa v24, -v20 {sdwa1}WORD_0", + "Source modifiers are not allowed on -v20"), + (["v_mov_b32_e32 v20, 1"], f"v_cvt_f16_u16_sdwa v24, |v20| {sdwa1}WORD_0", + "Source modifiers are not allowed on |v20|"), + (["v_mov_b32_e32 v20, 1"], f"v_cvt_f16_u16_sdwa v24, abs(v20) {sdwa1}WORD_0", + "Source modifiers are not allowed on abs(v20)"), + ([*proven_pair, f"v_add_f16_sdwa v24, v20, v21 {sdwa2}"], f"v_cvt_f16_i16_sdwa v25, v24 {sdwa1}WORD_0", + "Expected a numeric register"), + # Finite proof, overflow, and range refusals (checked on the selected field). + ([], f"v_add_f16_sdwa v24, s44, s44 {sdwa2}", "binary16 operand lacks a finite proof: s44"), + ([], f"v_floor_f16_sdwa v24, s44 {sdwa1}WORD_0", "binary16 operand lacks a finite proof: s44"), + (["v_mov_b32_e32 v20, 0x7c003c00"], f"v_floor_f16_sdwa v24, v20 {sdwa1}WORD_1", "binary16 operand is not finite: v20"), + (["v_mov_b32_e32 v20, 0x7bff0000"], + "v_add_f16_sdwa v24, v20, v20 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_1", + "binary16 result overflows: v_add_f16_sdwa"), + (["v_mov_b32_e32 v20, 0x3c00"], f"v_ldexp_f16_sdwa v24, v20, s44 {sdwa2}", + "binary16 ldexp exponent lacks a proof: s44"), + (["v_mov_b32_e32 v20, 0x3c00", "v_mov_b32_e32 v21, 0x00410000"], + "v_ldexp_f16_sdwa v24, v20, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_1", + "binary16 ldexp exponent out of range: 65"), + (["v_mov_b32_e32 v20, 0x7bff", "v_mov_b32_e32 v21, 1"], f"v_ldexp_f16_sdwa v24, v20, v21 {sdwa2}", + "binary16 result overflows: v_ldexp_f16_sdwa"), + ([], f"v_cvt_f16_u16_sdwa v24, s44 {sdwa1}WORD_0", "binary16 conversion source lacks a range proof: s44"), + (["v_mov_b32_e32 v20, 0xfff00000"], f"v_cvt_f16_u16_sdwa v24, v20 {sdwa1}WORD_1", + "binary16 result overflows: v_cvt_f16_u16_sdwa"), + (["v_mov_b32_e32 v20, 0x000000ff"], f"v_cvt_f16_u16_sdwa v24, sext(v20) {sdwa1}BYTE_0", + "binary16 result overflows: v_cvt_f16_u16_sdwa"), + (["v_mov_b32_e32 v20, 0xbc000000"], f"v_cvt_u16_f16_sdwa v24, v20 {sdwa1}WORD_1", + "binary16 value out of range: v_cvt_u16_f16_sdwa"), + (["v_mov_b32_e32 v20, 0x78000000"], f"v_cvt_i16_f16_sdwa v24, v20 {sdwa1}WORD_1", + "binary16 value out of range: v_cvt_i16_f16_sdwa"), + # clamp / omod, bad dst register, and unlowered SDWA neighbours. + (proven_pair, f"v_add_f16_sdwa v24, v20, v21 clamp {sdwa2}", "Unsupported binary16 SDWA operands"), + (proven_pair, f"v_floor_f16_sdwa v24, v20 mul:2 {sdwa1}WORD_0", "Unsupported binary16 SDWA operands"), + (proven_pair, f"v_cvt_f16_f32_sdwa v24, v20 clamp {sdwa1}DWORD", "Unsupported binary16 SDWA operands"), + (proven_pair, f"v_add_f16_sdwa v256, v20, v21 {sdwa2}", "Invalid binary16 SDWA operation"), + (proven_pair, f"v_min_f16_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), + (proven_pair, f"v_max_f16_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), + (proven_pair, f"v_fract_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_rcp_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_cvt_norm_i16_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_cvt_pkrtz_f16_f32_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), + ): + expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) + # Scheduling: pending scalar load, outstanding sample, and non-entry EXEC mask must refuse. + base = uncompressed_export([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + expect_value_error(translate_f16, base[:load + 1] + [f"v_cvt_f16_f32_sdwa v24, s44 {sdwa1}DWORD"] + base[load + 1:], + "Constant read before load completion") + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(translate_f16, base[:sample + 1] + [f"v_cvt_f16_f32_sdwa v12, s44 {sdwa1}DWORD"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(translate_f16, base[:sample + 1] + [f"v_cvt_f16_f32_sdwa v24, v12 {sdwa1}DWORD"] + base[sample + 1:], + "Sample used before vmcnt wait") + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(translate_f16, base[:masked] + [f"v_cvt_f16_f32_sdwa v24, s44 {sdwa1}DWORD"] + base[masked:], + "Invalid binary16 SDWA operation") + + +def check_sdwa_f16_draw(directory, compiler, renderer, backend): + check_sdwa_f16_controls() + # 1. Arithmetic, rounding, ldexp, and int16<->f16 SDWA draws, verified in both default denorm mode + # and binary32 -denorm ftz, plus numerically distinct op/selector/modifier/preserve mutations. + for name, body in SDWA_F16_PROGRAMS.items(): + prog = uncompressed_export(body) + expected = SDWA_F16_EXPECTED[name] + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *SDWA_F16_CONSTANTS[name]) + src_path = directory / f"sdwa_f16_{name}.hlsl" + cso_path = directory / f"sdwa_f16_{name}.cso" + pass_case = directory / f"sdwa_f16_{name}_pass.case" + pass_case.write_bytes(bytes(constants) + struct.pack("<4I", *expected) * 64 + b"\x01") + src_path.write_text(translate_f16(prog), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + # Binary32 -denorm ftz must preserve binary16 subnormals. + compile_shader(compiler, src_path, cso_path, mode="ftz") + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + for old, new in SDWA_F16_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + src_path.write_text(translate_f16(mutated), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cso_path, [pass_case]) + print(f"sdwa_f16 {name} mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"sdwa_f16 {name} mutation {old!r} -> {new!r} escaped detection") + + # 2. v_cvt_f16_f32_sdwa bit-exact draws: RNE vs RTZ, ties-to-even, subnormals under -denorm ftz, + # max finite/overflow, signed zeros, infinities, qNaNs, and WORD_1 UNUSED_PRESERVE packing. + cvt_prog = uncompressed_export(SDWA_F16_CVT_F32_BODY) + cvt_src = directory / "sdwa_f16_cvt_f32.hlsl" + cvt_cso = directory / "sdwa_f16_cvt_f32.cso" + cvt_src.write_text(translate_f16(cvt_prog), encoding="ascii") + compile_shader(compiler, cvt_src, cvt_cso) + input_rows = ( + (0x3f801000, 0x3f803000, 0xbf801001, 0x3f803000), + (0x33000000, 0x33000001, 0xb8000000, 0x38800000), + (0x477fe000, 0x477ff000, 0x80000000, 0x00000000), + (0x7f800000, 0xff800000, 0xffc02000, 0x7fc02000), + ) + cases = [] + for index, (w0, w1, w2, w3) in enumerate(input_rows): + expected = ( + dpp_f16_narrow16_ref(w0), + dpp_f16_narrow16_ref(w1 ^ 0x80000000), + dpp_f16_narrow16_ref(w2 & 0x7fffffff) << 16, + (dpp_f16_narrow16_ref((w3 & 0x7fffffff) ^ 0x80000000) << 16) | 0xbeef, + ) + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, w0, w1, w2, w3) + case_path = directory / f"sdwa_f16_cvt_f32_{index}.case" + case_path.write_bytes(bytes(constants) + struct.pack("<4I", *expected) * 64 + b"\x01") + cases.append((case_path, "pass")) + run_pixel_batch(renderer, backend, cvt_cso, cases) + compile_shader(compiler, cvt_src, cvt_cso, mode="ftz") + run_pixel_batch(renderer, backend, cvt_cso, cases) + for old, new in ( + ("v_cvt_f16_f32_sdwa v13, -s45", "v_cvt_f16_f32_sdwa v13, s45"), + ("v_cvt_f16_f32_sdwa v14, |v20|", "v_cvt_f16_f32_sdwa v14, v20"), + ("dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", "dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ): + mutated = [line.replace(old, new) for line in cvt_prog] + assert mutated != cvt_prog, old + cvt_src.write_text(translate_f16(mutated), encoding="ascii") + compile_shader(compiler, cvt_src, cvt_cso) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cvt_cso, [cases[0][0]]) + print(f"sdwa_f16 cvt_f32 mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"sdwa_f16 cvt_f32 mutation {old!r} -> {new!r} escaped detection") + return 0 + + # Quad-local DPP16 and DPP8 integer/bitwise/shift/bit-scan/saturate fixture covering 24 VOP1/VOP2 DPP forms. # Derives integer quad lane ID {0, 1, 2, 3} from interpolated uv.x/uv.y (v8/v9), verifies quad # swizzles across lanes, folds all 23 ops into a 32-bit accumulator, and exports all 4 bytes as @@ -15289,7 +15624,7 @@ def refuse(line, message, translator=translate_f16): # Forms the lowering does not accept fall through to the generic refusal, and so do the neighbouring binary16 ops. for line in ("v_add_f16_e64 v24, v18, v19 clamp", "v_mul_f16_e64 v24, v18, v19 mul:2", "v_mul_f16_e64 v24, v18, v19 div:2", "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_min_f16_dpp v24, v18, v19 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_add_f16_sdwa v24, v18, v19 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", + "v_min_f16_sdwa v24, v18, v19 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_min_f16_e64 v24, v18, v19", "v_max_f16_e32 v24, v18, v19"): refuse(line, "Unsupported instruction") @@ -15688,7 +16023,7 @@ def refuse(line, message, *lines): translate_f16(program("v_mov_b32_e32 v24, 0x3c00", f"v_{op}_f16_e32 v24, {operands}")) for form in (f"v_{op}_f16_e64 v24, v18, v19", f"v_{op}_f16_e64 v24, v18, v19 clamp", f"v_{op}_f16_e64 v24, v18, v19 mul:2", f"v_{op}_f16_e64 v24, v18, v19 op_sel:[0,1]", f"v_{op}_f16_e32 v24, v18, v19 clamp", - f"v_{op}_f16_sdwa v24, v18, v19 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", + "v_fmac_f16_sdwa v24, v18, v19 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", f"v_{op}_f16 v24, v18", f"v_{op}_f16 v24, v18, v19, v19"): refuse(form, "Unsupported instruction") # Operand kinds of src0: VGPR, SGPR, every inline constant, 0 and 16-bit literals; a copy of a proven constant and @@ -16118,7 +16453,7 @@ def refuse(line, message, translator=translate_f16): "v_rndne_f16_e64 v24, v18 div:2", "v_rndne_f16_e64 v24, v18 mul:4", "v_floor_f16_e64 v24, v18 op_sel:[0,1]", "v_floor_f16_e64 v24, -v18 clamp", "v_floor_f16_e32 v24, v18 clamp", "v_fract_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_floor_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_fract_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_fract_f16_e32 v24, v18", "v_rcp_f16_e32 v24, v18", "v_sqrt_f16_e64 v24, v18", "v_fract_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") @@ -16542,8 +16877,8 @@ def refuse(line, message, translator=translate_f16): for line in ("v_cvt_f16_i16_e64 v24, v18 clamp", "v_cvt_f16_u16_e64 v24, v18 clamp", "v_cvt_f16_i16_e64 v24, v18 mul:2", "v_cvt_f16_u16_e64 v24, v18 div:2", "v_cvt_f16_i16_e64 v24, v18 op_sel:[0,1]", "v_cvt_f16_i16_e64 v24, -v18 clamp", "v_cvt_f16_i16_e32 v24, v18 clamp", "v_cvt_f16_u16_e32 v24, 1 clamp", - "v_cvt_f16_i16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_cvt_f16_u16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_i16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_u16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_f16_i16 v24, v18, v19", "v_cvt_f16_i16 v24", "v_cvt_norm_i16_f16_e32 v24, v18", "v_cvt_norm_u16_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): @@ -16905,8 +17240,8 @@ def refuse(line, message, translator=translate_f16): for line in ("v_cvt_i16_f16_e64 v24, v18 clamp", "v_cvt_u16_f16_e64 v24, v18 clamp", "v_cvt_i16_f16_e64 v24, v18 mul:2", "v_cvt_u16_f16_e64 v24, v18 div:2", "v_cvt_i16_f16_e64 v24, v18 mul:4", "v_cvt_i16_f16_e64 v24, v18 op_sel:[0,1]", "v_cvt_i16_f16_e64 v24, -v18 clamp", "v_cvt_i16_f16_e32 v24, v18 clamp", "v_cvt_u16_f16_e32 v24, 1.0 clamp", - "v_cvt_i16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_cvt_u16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_i16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_cvt_norm_u16_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", "v_cvt_i16_f16 v24, v18, v19", "v_cvt_u16_f16 v24", "v_cvt_norm_i16_f16_e32 v24, v18", "v_cvt_norm_u16_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") @@ -19002,6 +19337,7 @@ def _check_controls_inline(directory): "check_unbound_operand_diagnostics", "check_dpp_cvt_refusals", "check_dpp_f16_contract_controls", + "check_sdwa_f16_controls", "check_smem_pointer_controls", "check_masked_controls", "check_masked_mov_close_controls", @@ -19651,6 +19987,8 @@ def check_binary(directory, assembler, objcopy, library): fixtures.extend((uncompressed_export(body), translate_f16) for body in DPP_F16_ARITH_ROUND_PROGRAMS.values()) fixtures.extend((uncompressed_export(body), translate_f16) for body in DPP_F16_CVT_FMAC_LDEXP_PROGRAMS.values()) fixtures.append((uncompressed_export(DPP_F16_CVT_I16_LANES), translate_f16)) + fixtures.extend((uncompressed_export(body), translate_f16) for body in SDWA_F16_PROGRAMS.values()) + fixtures.append((uncompressed_export(SDWA_F16_CVT_F32_BODY), translate_f16)) fixtures.extend((bit_program(op), translate) for op in BIT_OPERATIONS) fixtures.extend((program, function) for _, program, function, _ in e64_spelling_programs()) fixtures.append((vop1_nop_program(), translate)) @@ -26397,7 +26735,7 @@ def main(): "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", - "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-dpp-extra", "draw-pk-fmac"): + "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, "draw-dpp-cvt": check_dpp_cvt_draw, @@ -26459,7 +26797,8 @@ def main(): "draw-sopk-hwreg": check_sopk_hwreg_draw, "draw-sopp-round-mode": check_sopp_round_mode_draw, "draw-smem-pointers": check_smem_pointer_draw, - "draw-dpp-f16": check_dpp_f16_draw}[mode] + "draw-dpp-f16": check_dpp_f16_draw, + "draw-sdwa-f16": check_sdwa_f16_draw}[mode] return draw(directory, *args) except subprocess.CalledProcessError as error: if error.returncode == 77 and str(error.cmd[0]) == str(args[1]): diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 44b59a0f7..652dee1b8 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -2988,6 +2988,152 @@ def sdwa_cmp_bits(token, sel, sext, scalar, vector, pending, sample_dest, *, f16 rf"(v\d+), {SDWA_INT_SOURCE}(?:, {SDWA_INT_SOURCE})? dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" r" dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" r"(?: src1_sel:(BYTE_[0-3]|WORD_[01]|DWORD))?") +SDWA_F16_SRC = re.compile(r"(-?)(?:abs\(([vs]\d+)\)|\|([vs]\d+)\||([vs]\d+))") +SDWA_F16_UNARY_OPERANDS = re.compile( + r"(v\d+), ([^,\s]+) dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" + r" dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD)") +SDWA_F16_BINARY_OPERANDS = re.compile( + r"(v\d+), ([^,\s]+), ([^,\s]+) dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" + r" dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" + r" src1_sel:(BYTE_[0-3]|WORD_[01]|DWORD)") + + +def half16_sdwa_source(token, sel, scalar, vector, pending, sample_dest, known_ssa_bits, known_half): + """Parse one float register source of a binary16 SDWA op under the static finite-proof contract. + + Accepts a VGPR or SGPR with optional bit-15 abs/neg modifiers and WORD_0, WORD_1 or DWORD selection + (refusing BYTE_* and sext()). A ("half16", name) source only permits WORD_0 so the undefined high + half is never read. Returns (hlsl_u16_expr, proven_u16_bits). + """ + if sel not in ("WORD_0", "WORD_1", "DWORD"): + raise ValueError(f"Unsupported binary16 SDWA source selection: {sel}") + if token.startswith("sext("): + raise ValueError(f"Unsupported binary16 SDWA source modifier: {token}") + m = SDWA_F16_SRC.fullmatch(token) + if not m: + raise ValueError(f"Unsupported binary16 SDWA operand: {token}") + neg, abs_fn, abs_bars, plain = m.groups() + reg = abs_fn or abs_bars or plain + use_abs = bool(abs_fn or abs_bars) + idx = int(reg[1:]) + if not 0 <= idx <= (255 if reg[0] == "v" else 105): + raise ValueError(f"Register out of range: {reg}") + if reg in pending: + raise ValueError("Constant read before load completion") + if reg in sample_dest: + raise ValueError("Sample used before vmcnt wait") + if reg[0] == "s": + value = scalar.get(reg) + if not isinstance(value, int): + raise ValueError(f"binary16 operand lacks a finite proof: {reg}") + full_bits, word = value & 0xffffffff, f"{value & 0xffffffff}u" + else: + value = vector.get(reg) + if isinstance(value, str) and value in known_ssa_bits: + full_bits, word = known_ssa_bits[value] & 0xffffffff, f"asuint({value})" + elif (name := half16_name(reg, vector)) is not None: + if sel != "WORD_0": + raise ValueError("Reads the undefined high half of a 16-bit result") + if name not in known_half: + raise ValueError(f"binary16 operand lacks a finite proof: {reg}") + full_bits, word = known_half[name] & 0xffff, f"asuint({name})" + else: + raise ValueError(f"binary16 operand lacks a finite proof: {reg}") + bits = (full_bits >> 16) & 0xffff if sel == "WORD_1" else full_bits & 0xffff + if (bits >> 10) & 0x1f == 0x1f: + raise ValueError(f"binary16 operand is not finite: {reg}") + hlsl_bits = f"((({word}) >> 16u) & 0xffffu)" if sel == "WORD_1" else f"(({word}) & 0xffffu)" + if use_abs: + bits &= 0x7fff + hlsl_bits = f"({hlsl_bits} & 0x7fffu)" + if neg: + bits ^= 0x8000 + hlsl_bits = f"({hlsl_bits} ^ 0x8000u)" + return hlsl_bits, bits + + +def int16_sdwa_source(token, sel, scalar, vector, pending, sample_dest, known_ssa_bits): + """Parse one integer register source of a binary16 SDWA op (optional sext(), no float modifiers). + + Accepts a VGPR or SGPR with BYTE_0..3, WORD_0..1 or DWORD selection. A ("low16", name) source is + restricted to WORD_0, BYTE_0 or BYTE_1; a ("half16", name) source is rejected. Returns + (hlsl_selected_u32_expr, known_low16_or_None). + """ + if token.startswith(("-", "|", "abs(")): + raise ValueError(f"Source modifiers are not allowed on {token}") + m = re.fullmatch(SDWA_INT_SOURCE, token) + if not m or bool(m.group(1)) != bool(m.group(3)): + raise ValueError(f"Unsupported SDWA integer operand: {token}") + is_sext, reg = bool(m.group(1)), m.group(2) + idx = int(reg[1:]) + if not 0 <= idx <= (255 if reg[0] == "v" else 105): + raise ValueError(f"Register out of range: {reg}") + if reg in pending: + raise ValueError("Constant read before load completion") + if reg in sample_dest: + raise ValueError("Sample used before vmcnt wait") + if reg[0] == "s": + value = scalar.get(reg) + if isinstance(value, int): + full_bits, word = value & 0xffffffff, f"{value & 0xffffffff}u" + else: + word = int_operand(reg, scalar, vector, pending, sample_dest, signed=False) + full_bits = None + elif (low_name := low16_name(reg, vector)) is not None: + if sel not in ("WORD_0", "BYTE_0", "BYTE_1"): + raise ValueError("Reads the undefined high half of a 16-bit result") + word, full_bits = f"asuint({low_name})", None + elif half16_name(reg, vector) is not None: + raise ValueError("Expected a numeric register") + else: + if reg not in vector: + raise ValueError(f"Untracked 16-bit source: {reg}") + word = int_operand(reg, scalar, vector, pending, sample_dest, signed=False) + value = vector[reg] + full_bits = known_ssa_bits[value] & 0xffffffff if isinstance(value, str) and value in known_ssa_bits else None + hlsl_word = sdwa_source(word, sel, is_sext) + if full_bits is None: + return hlsl_word, None + offset, width = SDWA_SEL[sel] + raw_field = (full_bits >> offset) & ((1 << width) - 1) + if is_sext and width < 32 and (raw_field >> (width - 1)) & 1: + selected = (raw_field | (~((1 << width) - 1) & 0xffffffff)) & 0xffffffff + else: + selected = raw_field + return hlsl_word, selected & 0xffff + + +def emit_sdwa_f16_dest(lines, i, dst, result_u16_expr, dst_sel, unused, vector, known_ssa_bits, known_half, + *, tag, known_result=None): + """Emit the SDWA destination placement for a 16-bit binary16 or int16 result. + + dst_sel:DWORD keeps the low-16-only contract (("half16", alu) or ("low16", alu)) because bits 31:16 + are unspecified. dst_sel:WORD_0 and WORD_1 with UNUSED_PAD or UNUSED_PRESERVE define all 32 bits, + updating known_ssa_bits whenever the full 32-bit result is statically known. + """ + if dst_sel not in ("DWORD", "WORD_0", "WORD_1"): + raise ValueError(f"Unsupported 16-bit SDWA destination selection: {dst_sel}") + if unused == "UNUSED_SEXT": + raise ValueError("UNUSED_SEXT is not lowered") + if dst_sel == "DWORD": + lines.append(f" precise float alu{i} = asfloat({result_u16_expr});") + vector[dst] = (tag, f"alu{i}") + if tag == "half16" and known_result is not None: + known_half[f"alu{i}"] = known_result & 0xffff + return + old = vector.get(dst) if unused == "UNUSED_PRESERVE" else None + if isinstance(old, tuple) and old[0] in ("low16", "half16"): + raise ValueError("Reads the undefined high half of a 16-bit result") + dest_expr = sdwa_dest(result_u16_expr, dst_sel, unused, old) + lines.append(f" precise float alu{i} = asfloat({dest_expr});") + vector[dst] = f"alu{i}" + if known_result is not None: + shift = 16 if dst_sel == "WORD_1" else 0 + if unused == "UNUSED_PAD": + known_ssa_bits[f"alu{i}"] = (known_result & 0xffff) << shift + elif old in known_ssa_bits: + keep = 0x0000ffff if dst_sel == "WORD_1" else 0xffff0000 + known_ssa_bits[f"alu{i}"] = (known_ssa_bits[old] & keep) | ((known_result & 0xffff) << shift) class VectorRegisters(dict): @@ -5184,6 +5330,171 @@ def sample_coord(reg): result = sdwa_dest(f"({template.format(*args)})", dst_sel, unused, vector.get(dst)) vector[dst] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({result});") + elif m := match(r"v_cvt_f16_f32_sdwa (.+)"): + # SDWA binary32-to-binary16 conversion under the declared entry profile (half_denorm="preserve" + # and HW_REG_MODE RNE). Takes a whole-dword register source (so f32 denormal mode never touches + # a zero-extended sub-dword) with optional bit-31 abs/neg modifiers. + rest = m.group(1) + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_cvt_f16_f32_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + if sel0 != "DWORD": + raise ValueError(f"v_cvt_f16_f32_sdwa requires src0_sel:DWORD, got {sel0}") + if src0.startswith("sext("): + raise ValueError(f"Unsupported binary16 SDWA source modifier: {src0}") + sm = SDWA_F16_SRC.fullmatch(src0) + if not sm: + raise ValueError(f"Unsupported binary16 SDWA operand: {src0}") + neg, abs_fn, abs_bars, plain = sm.groups() + reg = abs_fn or abs_bars or plain + if not 0 <= int(reg[1:]) <= (255 if reg[0] == "v" else 105): + raise ValueError(f"Register out of range: {reg}") + val = fp_operand(reg, scalar, vector, pending, sample_dest) + bits = f"asuint({val})" + if abs_fn or abs_bars: + bits = f"({bits} & 0x7fffffffu)" + if neg: + bits = f"({bits} ^ 0x80000000u)" + emit_sdwa_f16_dest(lines, i, dst, f"narrow16(asfloat({bits}))", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16") + elif m := match(rf"v_({'|'.join(VOP2_F16)})_f16_sdwa (.+)"): + # SDWA binary16 VOP2 arithmetic under the static finite-proof contract (#839). Both sources + # select WORD_0, WORD_1 or DWORD with optional bit-15 abs/neg modifiers. + name, rest = m.groups() + parsed = SDWA_F16_BINARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_{name}_f16_sdwa {rest}") + dst, src0, src1, dst_sel, unused, sel0, sel1 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + s1_bits, b1 = half16_sdwa_source( + src1, sel1, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_vop2_result(name, b0, b1) + if result is None: + raise ValueError(f"binary16 result overflows: v_{name}_f16_sdwa") + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" uint hf{i}_1 = {s1_bits};") + expression = VOP2_F16[name].format(f"widen16(hf{i}_0)", f"widen16(hf{i}_1)") + lines.append(f" precise float hs{i} = {expression};") + emit_sdwa_f16_dest(lines, i, dst, f"narrow16(hs{i})", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(r"v_ldexp_f16_sdwa (.+)"): + # SDWA binary16 exponent scaling (D = S0 * 2^S1): float src0 with optional abs/neg and + # WORD_0/WORD_1/DWORD selection; integer src1 with optional sext() and any SDWA selection, + # statically proven within [-LDEXP_F16_EXPONENT_LIMIT, LDEXP_F16_EXPONENT_LIMIT]. + rest = m.group(1) + parsed = SDWA_F16_BINARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_ldexp_f16_sdwa {rest}") + dst, src0, src1, dst_sel, unused, sel0, sel1 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + _, known = int16_sdwa_source(src1, sel1, scalar, vector, pending, sample_dest, known_ssa_bits) + if known is None: + raise ValueError(f"binary16 ldexp exponent lacks a proof: {src1}") + exponent = known - 0x10000 if known & 0x8000 else known + if abs(exponent) > LDEXP_F16_EXPONENT_LIMIT: + raise ValueError(f"binary16 ldexp exponent out of range: {exponent}") + result = f16_ldexp_result(b0, exponent) + if result is None: + raise ValueError("binary16 result overflows: v_ldexp_f16_sdwa") + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = widen16(hf{i}_0) * asfloat({(127 + exponent) << 23}u);") + emit_sdwa_f16_dest(lines, i, dst, f"narrow16(hs{i})", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(rf"v_({'|'.join(VOP1_F16_ROUND)})_f16_sdwa (.+)"): + # SDWA binary16 VOP1 rounding under the static finite-proof contract (#839). + name, rest = m.groups() + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_{name}_f16_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_round_result(name, b0) + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = {VOP1_F16_ROUND[name].format(f'widen16(hf{i}_0)')};") + emit_sdwa_f16_dest(lines, i, dst, f"narrow16(hs{i})", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(r"v_cvt_f16_(i16|u16)_sdwa (.+)"): + # SDWA 16-bit integer to binary16 conversion (round to nearest even): integer src0 with + # optional sext() and any SDWA selection. Runtime i16 is always finite; u16 requires a + # static proof < 65520 after selection/sign-extension. + kind, rest = m.groups() + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_cvt_f16_{kind}_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + signed = kind == "i16" + selected_word, known = int16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits) + result = None + if known is not None: + result = f16_cvt_int_result(signed, known) + if result is None: + raise ValueError(f"binary16 result overflows: v_cvt_f16_{kind}_sdwa") + elif not signed: + raise ValueError(f"binary16 conversion source lacks a range proof: {src0}") + word = f"(asint(({selected_word}) << 16) >> 16)" if signed else f"(({selected_word}) & 0xffffu)" + lines.append(f" {'int' if signed else 'uint'} cv{i}_0 = {word};") + lines.append(f" precise float hs{i} = float(cv{i}_0);") + emit_sdwa_f16_dest(lines, i, dst, f"narrow16(hs{i})", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(r"v_cvt_(i16|u16)_f16_sdwa (.+)"): + # SDWA binary16 to 16-bit integer conversion (truncation toward zero): statically proven + # finite float src0 whose truncated integer lies in range. + kind, rest = m.groups() + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_cvt_{kind}_f16_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_to_int_result(kind == "i16", b0) + if result is None: + raise ValueError(f"binary16 value out of range: v_cvt_{kind}_f16_sdwa") + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = widen16(hf{i}_0);") + lines.append(f" int cv{i}_0 = int(trunc(hs{i}));") + emit_sdwa_f16_dest(lines, i, dst, f"(asuint(cv{i}_0) & 0xffffu)", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="low16", known_result=result) elif m := match(r"v_(lshlrev_b64|lshrrev_b64|ashrrev_i64)(?:_e64)? (v\[\d+:\d+\]), ([^,\s]+), ([^,\s]+)"): # VOP3 64-bit shifts (issue #928): D = S1 << S0[5:0], S1 >> S0[5:0], or signext(S1) >> S0[5:0] # (AMD RDNA 2 ISA §12.12, opcodes 767-769). The 64-bit value is two 32-bit words. Both source words From ae5d482a722461a2c89dc2919bed43930ae39f14 Mon Sep 17 00:00:00 2001 From: Yann Bucaille <83926195+Ybucaille@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:15:11 +0100 Subject: [PATCH 142/232] shader: lower v_cvt_pk_u8_f32 for any binary32 source in gfx2hlsl (#2467) * shader: lower v_cvt_pk_u8_f32 for any binary32 source in gfx2hlsl flt32_to_uint8 is undefined in the RDNA ISA guides, so the startup translator only accepted +0.0 or an integer in 1..255. It was measured on two RDNA 2 parts (RX 6900 XT gfx1030 and a gfx1036 iGPU, Windows, ROCm 7.2): round to nearest even, saturate to 0..255, NaN and negatives to 0, with no difference under s_denorm_mode 0. Round toward zero in MODE makes it truncate, so s_setreg_imm32_b32 that puts a non-zero rounding mode in MODE[1:0] is now refused instead of ignored. The byte_float_v proof and the pk_u8_s0_contract fixture switch only existed for the restricted domain and are removed. Refs #2023 (item K), follows #2101 * tests: pin the MODE write offset, width and hwreg refusal for cvt_pk_u8 Three mutations of the s_setreg_imm32_b32 MODE handling reported on #2467 survived: dropping the offset shift, defaulting the width to 1 and skipping the non-hwreg refusal. Add accepted and refused forms that kill each one, and note that the offset < 2 bound is a shortcut. * Advance the startup shader cache revision to 15 The v_cvt_pk_u8_f32 lowering changes the HLSL emitted for forms that main already accepted (constant and proven-register S0, MODE writes), so a cache built under revision 14 would keep the old clamp lowering and the earlier refusals. Draw and compute revisions move together. * Guard v_cvt_pk_u8_f32 with an integer compare on the raw bits DXC compiles the float guard to fcmp fast ogt, so the NaN result relied on the driver honouring the ordered compare. (bits - 1u) < 0x7f800000u is true exactly from the smallest positive subnormal to +inf, so fast-math cannot fold it. The test evaluator now fails with a clear message when the lowering text no longer matches. The docs name both devices that matched (gfx1030, gfx1036) and the two open assumptions: IEEE mode and the initial rounding mode from PGM_RSRC1.FLOAT_MODE. * Decode float-printed immediates in s_setreg_imm32_b32 MODE writes disasm prints some inline constants as floats (1.0, 0.5). They were refused as writing MODE[1:0] even when bits 1:0 are clear. They now read as their binary32 bits, and an immediate that cannot be decoded is refused with its own reason. Refusal stays the safe direction. * Add the v_cvt_pk_u8_f32 hardware probe and its stored output The measurement behind the lowering could not be rerun: the probe lived outside the repository and the raw words were not attached. Add the probe as tools/rdna_cvt_pk_u8.py (builds its kernels with clang, runs through HIP, writes a compact TSV and compares it with the stored one) and store the output in tests/data/rdna_cvt_pk_u8_measured.tsv. The gfx1030 and gfx1036 runs gave identical rows, so one set is kept. The check now validates every stored row without a GPU: nearest-even for the default word, truncation for the rtz word, with negative controls from the other models. The docstring points at the in-repo probe. --- docs/experiments.md | 4 +- docs/startup-runtime.md | 4 +- src/startup_stubs/d3d12_draw.inl | 4 +- tests/data/rdna_cvt_pk_u8_measured.tsv | 5439 +++++++++++++++++ .../startup_compute_request_offline_check.py | 4 +- tests/startup_gfx2hlsl_buffer_store_check.py | 4 +- tests/startup_gfx2hlsl_cvt_pk_u8_check.py | 401 +- tests/startup_indirect_draw_indexed.cpp | 2 +- tests/startup_resource_retire_title.cpp | 2 +- tools/rdna_cvt_pk_u8.py | 615 ++ tools/startup/gfx2hlsl.py | 87 +- 11 files changed, 6436 insertions(+), 130 deletions(-) create mode 100644 tests/data/rdna_cvt_pk_u8_measured.tsv create mode 100644 tools/rdna_cvt_pk_u8.py diff --git a/docs/experiments.md b/docs/experiments.md index 3132b2d25..f5c8cb13a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6356,7 +6356,9 @@ The source-built gfx1013 fixture `VADD_NC_I32` in `tests/compute_store_check.py` `v_cvt_pk_u8_f32 vD, s0, s1, s2` (VOP3A opcode 350, #1546) lowers to an inline expression on known words. The RDNA 1.0 and RDNA 2 ISA guides give `D = (S2 & ~(0xff << 8 * S1[1:0])) | ((flt32_to_uint8(S0) & 0xff) << 8 * S1[1:0])`. The byte select and the merge are fully specified. `flt32_to_uint8` is not defined: the guides give no rounding mode, no bounds and no result for NaN or negative inputs, and AMD's machine-readable ISA description only says that the float becomes an unsigned 8-bit integer. The translation is claimed only where every reading agrees: an S0 that is +0.0 or an integer in [1, 255]. Truncation, every rounding mode and any clamp give the same byte there. A constant S0 outside that set is refused. -A register S0 is accepted by ordinary translation only when it is proven in the set: written by `v_cvt_f32_ubyte0..3` without modifier, in straight-line code under the entry exec mask, with no write since. Any other register is refused (`source vN is not proven to be +0.0 or an integer in 1..255`) unless the caller selects the `pk_u8_s0_contract` keyword of `Pipeline`, which states that every such S0 holds +0.0 or an integer in 1..255 and is recorded in the pipeline notes. The fixture draws select it, because their S0 words come from flat parameters; the request path never does. The HLSL is `(S2 & ~(0xffu << ((S1 & 3u) << 3u))) | ((uint(asfloat(S0)) & 0xffu) << ((S1 & 3u) << 3u))`. +The startup translator (`tools/startup/gfx2hlsl.py`, `tests/startup_gfx2hlsl_cvt_pk_u8_check.py`) no longer restricts S0: `flt32_to_uint8` was measured on RDNA 2 hardware, two RDNA 2 devices, an RX 6900 XT (gfx1030) and an integrated GPU (gfx1036), both Windows, ROCm 7.2, Adrenalin 26.11.2, with kernels built by clang that run the instruction on about 270 binary32 inputs (zeros, integers, every tie k + 0.5 and its neighbours one ulp away, x * 255.0 values, negatives, above 255, infinities, NaN payloads, subnormals) under the 8 byte selects, S2 holding a sentinel word: 5,432 words on each device, and the two devices gave the same words. At the default MODE the result is the nearest integer, ties to even, saturated to [0, 255]; NaN, negative values (-0.5 included), -0.0 and -infinity give 0; +infinity gives 255. The model matches all 5432 rows; truncation, rounding half away from zero and an 8-bit wrap of the integer conversion do not (1512, 40 and 1632 mismatches). With `s_round_mode 0xf` (round toward zero) the same rows match truncation with saturation and NaN to 0 (and not the nearest-even model), so the conversion follows the binary32 rounding of MODE; `s_denorm_mode 0` gave the default results. These are desktop RDNA 2 GPUs, not the console GPU: the console's own result is not measured, and other architectures are not covered. Two assumptions are open. The probe ran as compute with the HSA launch defaults (IEEE mode on), while pixel shaders usually run with IEEE mode off. The initial rounding mode comes from `PGM_RSRC1.FLOAT_MODE`, which the translator does not decode: only explicit `s_setreg_imm32_b32` writes are checked. The HLSL is `(S2 & ~(0xffu << ((S1 & 3u) << 3u))) | (((((S0 - 1u) < 0x7f800000u) ? uint(round(min(asfloat(S0), 255.0))) : 0u) & 0xffu) << ((S1 & 3u) << 3u))`, with S0 the raw word of a register or a literal. The guard is an integer test, true exactly from the smallest positive subnormal to +infinity and false for both zeros, every negative and every NaN, so those take 0 without relying on how `min` and `max` treat a NaN operand and without a float compare that fast-math could fold; above zero `min` saturates (infinity included) and the HLSL `round` is DXIL `Round_ne` (ties to even). A register or a constant S0 is lowered alike; there is no proof set and no `pk_u8_s0_contract` keyword any more. Because the lowering assumes MODE[1:0] = 0, `s_setreg_imm32_b32` is refused when its immediate puts a non-zero value in MODE bits 1:0 (`hwreg(HW_REG_MODE, 0, n)` or an offset below 2, including a whole-register write), and accepted when it writes 0 there; writes to MODE[3:2], the scratch base and the other targets stay accepted, and `s_round_mode`, `s_denorm_mode` and `s_setreg_b32` were already unsupported. `tools/compute_store_aot.py` is unchanged and keeps the restricted S0 set described above. + +The measurement is reproducible by anyone with an RDNA 2 adapter. The probe is `tools/rdna_cvt_pk_u8.py` (Python 3 standard library only; `clang` from ROCm 7.x or the HIP SDK, found on `PATH`, `HIP_PATH`, `ROCM_PATH` or passed with `--clang`; the HIP runtime of the driver). It compiles three device-only HIP kernels whose only hand-written part is one `asm volatile` block, `v_cvt_pk_u8_f32 vD, vIn, vSel, vS2` with S2 = 0xa5c3e17b, and runs them through HIP on 5,432 (input, select) rows: the default MODE, `s_round_mode 0xf` (`rtz`) and `s_denorm_mode 0` (`flush`). Rerun with `python3 tools/rdna_cvt_pk_u8.py` (Windows: `py -3 tools/rdna_cvt_pk_u8.py`; `--device N` picks the adapter, `--arch gfx10xx` overrides the target; a consumer gfx103x that ROCm does not list may need `HSA_OVERRIDE_GFX_VERSION=10.3.0` with `--arch gfx1030`). It prints the per-variant verdict against four models (nearest even, truncation, half away from zero, truncation wrapped to 8 bits), writes `out/rdna_cvt_pk_u8.tsv` and says whether its rows equal the stored ones; `--self-test` and `--help` need no GPU. The stored result is `tests/data/rdna_cvt_pk_u8_measured.tsv` (about 300 KB, one tab separated row per line: label, input word, select word, then the `default`, `rtz` and `flush` words). It holds one set of rows because the two devices gave identical rows, which was verified word by word before the file was written: gfx1030 (Radeon RX 6900 XT, Windows, Adrenalin 26.11.2, ROCm 7.2) and gfx1036 (integrated GPU, Windows, ROCm 7.2, driver version not reported). `tests/startup_gfx2hlsl_cvt_pk_u8_check.py` checks every stored row without a GPU: `default` equals the nearest-even model, `rtz` equals truncation with saturation, `flush` equals `default`, and the truncation, half-away and 8-bit-wrap models must disagree with stored rows. S0 is a VGPR, an SGPR that holds a known word, a literal, the integer zero or an inline float constant. S1 and S2 are any known word. A constant S0 outside the agreed set is refused with `Unverified ALU operand`: `0.5`, `1/(2*pi)`, 1.5, negative values, -0.0, 256.0, infinity, NaN, a nonzero inline integer (a denormal bit pattern) and a word wider than 32 bits. A word read from memory is not known statically, so a caller that binds one must keep it inside the set. The input modifiers `-`, `|...|` and `-|...|`, `clamp`, `mul:2`, the `_e64` spelling and a register range are not lowered; each stops at the instruction. Unknown, pending, descriptor and saved-exec sources and a destination past v255 are refused, as for the integer subset. A result is data only and is refused as an address or a lane-guard operand. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2debb4afd..a89434bd9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -204,8 +204,10 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-14`. Older translations evaluate `s_brev_b32` of a +The shader cache revision is `x2w-startup-shader-15`. Older translations evaluate `s_brev_b32` of a constant at run time instead of folding it into a known word, which changes the emitted HLSL. +Revisions before 15 lower `v_cvt_pk_u8_f32` with a float clamp and accept `s_setreg_imm32_b32` writes of the +rounding mode. Revisions before 12 can overwrite the source mask when a save-EXEC instruction uses the same source and destination register. Earlier revisions can also carry a stale scalar symbol across a join, read a stale SCC after diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 14a2aff0c..57cef5130 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -244,7 +244,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-14"; + constexpr char revision[] = "x2w-startup-shader-15"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -364,7 +364,7 @@ void publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-14cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-15cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/data/rdna_cvt_pk_u8_measured.tsv b/tests/data/rdna_cvt_pk_u8_measured.tsv new file mode 100644 index 000000000..95dedf83c --- /dev/null +++ b/tests/data/rdna_cvt_pk_u8_measured.tsv @@ -0,0 +1,5439 @@ +# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py +# sentinel (S2) a5c3e17b +# device gfx1030 (Radeon RX 6900 XT, Windows, Adrenalin 26.11.2, ROCm 7.2) +# device gfx1036 (integrated GPU, Windows, ROCm 7.2, driver not reported) +# both devices produced identical rows; the rows below are that common result +# columns (tab separated, words in hex): label in sel default rtz flush +# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0 ++0 00000000 00000000 a5c3e100 a5c3e100 a5c3e100 ++0 00000000 00000001 a5c3007b a5c3007b a5c3007b ++0 00000000 00000002 a500e17b a500e17b a500e17b ++0 00000000 00000003 00c3e17b 00c3e17b 00c3e17b ++0 00000000 fffffffd a5c3007b a5c3007b a5c3007b ++0 00000000 fffffffc a5c3e100 a5c3e100 a5c3e100 ++0 00000000 80000002 a500e17b a500e17b a500e17b ++0 00000000 00000103 00c3e17b 00c3e17b 00c3e17b +-0 80000000 00000000 a5c3e100 a5c3e100 a5c3e100 +-0 80000000 00000001 a5c3007b a5c3007b a5c3007b +-0 80000000 00000002 a500e17b a500e17b a500e17b +-0 80000000 00000003 00c3e17b 00c3e17b 00c3e17b +-0 80000000 fffffffd a5c3007b a5c3007b a5c3007b +-0 80000000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-0 80000000 80000002 a500e17b a500e17b a500e17b +-0 80000000 00000103 00c3e17b 00c3e17b 00c3e17b +1 3f800000 00000000 a5c3e101 a5c3e101 a5c3e101 +1 3f800000 00000001 a5c3017b a5c3017b a5c3017b +1 3f800000 00000002 a501e17b a501e17b a501e17b +1 3f800000 00000003 01c3e17b 01c3e17b 01c3e17b +1 3f800000 fffffffd a5c3017b a5c3017b a5c3017b +1 3f800000 fffffffc a5c3e101 a5c3e101 a5c3e101 +1 3f800000 80000002 a501e17b a501e17b a501e17b +1 3f800000 00000103 01c3e17b 01c3e17b 01c3e17b +2 40000000 00000000 a5c3e102 a5c3e102 a5c3e102 +2 40000000 00000001 a5c3027b a5c3027b a5c3027b +2 40000000 00000002 a502e17b a502e17b a502e17b +2 40000000 00000003 02c3e17b 02c3e17b 02c3e17b +2 40000000 fffffffd a5c3027b a5c3027b a5c3027b +2 40000000 fffffffc a5c3e102 a5c3e102 a5c3e102 +2 40000000 80000002 a502e17b a502e17b a502e17b +2 40000000 00000103 02c3e17b 02c3e17b 02c3e17b +3 40400000 00000000 a5c3e103 a5c3e103 a5c3e103 +3 40400000 00000001 a5c3037b a5c3037b a5c3037b +3 40400000 00000002 a503e17b a503e17b a503e17b +3 40400000 00000003 03c3e17b 03c3e17b 03c3e17b +3 40400000 fffffffd a5c3037b a5c3037b a5c3037b +3 40400000 fffffffc a5c3e103 a5c3e103 a5c3e103 +3 40400000 80000002 a503e17b a503e17b a503e17b +3 40400000 00000103 03c3e17b 03c3e17b 03c3e17b +4 40800000 00000000 a5c3e104 a5c3e104 a5c3e104 +4 40800000 00000001 a5c3047b a5c3047b a5c3047b +4 40800000 00000002 a504e17b a504e17b a504e17b +4 40800000 00000003 04c3e17b 04c3e17b 04c3e17b +4 40800000 fffffffd a5c3047b a5c3047b a5c3047b +4 40800000 fffffffc a5c3e104 a5c3e104 a5c3e104 +4 40800000 80000002 a504e17b a504e17b a504e17b +4 40800000 00000103 04c3e17b 04c3e17b 04c3e17b +5 40a00000 00000000 a5c3e105 a5c3e105 a5c3e105 +5 40a00000 00000001 a5c3057b a5c3057b a5c3057b +5 40a00000 00000002 a505e17b a505e17b a505e17b +5 40a00000 00000003 05c3e17b 05c3e17b 05c3e17b +5 40a00000 fffffffd a5c3057b a5c3057b a5c3057b +5 40a00000 fffffffc a5c3e105 a5c3e105 a5c3e105 +5 40a00000 80000002 a505e17b a505e17b a505e17b +5 40a00000 00000103 05c3e17b 05c3e17b 05c3e17b +6 40c00000 00000000 a5c3e106 a5c3e106 a5c3e106 +6 40c00000 00000001 a5c3067b a5c3067b a5c3067b +6 40c00000 00000002 a506e17b a506e17b a506e17b +6 40c00000 00000003 06c3e17b 06c3e17b 06c3e17b +6 40c00000 fffffffd a5c3067b a5c3067b a5c3067b +6 40c00000 fffffffc a5c3e106 a5c3e106 a5c3e106 +6 40c00000 80000002 a506e17b a506e17b a506e17b +6 40c00000 00000103 06c3e17b 06c3e17b 06c3e17b +7 40e00000 00000000 a5c3e107 a5c3e107 a5c3e107 +7 40e00000 00000001 a5c3077b a5c3077b a5c3077b +7 40e00000 00000002 a507e17b a507e17b a507e17b +7 40e00000 00000003 07c3e17b 07c3e17b 07c3e17b +7 40e00000 fffffffd a5c3077b a5c3077b a5c3077b +7 40e00000 fffffffc a5c3e107 a5c3e107 a5c3e107 +7 40e00000 80000002 a507e17b a507e17b a507e17b +7 40e00000 00000103 07c3e17b 07c3e17b 07c3e17b +8 41000000 00000000 a5c3e108 a5c3e108 a5c3e108 +8 41000000 00000001 a5c3087b a5c3087b a5c3087b +8 41000000 00000002 a508e17b a508e17b a508e17b +8 41000000 00000003 08c3e17b 08c3e17b 08c3e17b +8 41000000 fffffffd a5c3087b a5c3087b a5c3087b +8 41000000 fffffffc a5c3e108 a5c3e108 a5c3e108 +8 41000000 80000002 a508e17b a508e17b a508e17b +8 41000000 00000103 08c3e17b 08c3e17b 08c3e17b +9 41100000 00000000 a5c3e109 a5c3e109 a5c3e109 +9 41100000 00000001 a5c3097b a5c3097b a5c3097b +9 41100000 00000002 a509e17b a509e17b a509e17b +9 41100000 00000003 09c3e17b 09c3e17b 09c3e17b +9 41100000 fffffffd a5c3097b a5c3097b a5c3097b +9 41100000 fffffffc a5c3e109 a5c3e109 a5c3e109 +9 41100000 80000002 a509e17b a509e17b a509e17b +9 41100000 00000103 09c3e17b 09c3e17b 09c3e17b +10 41200000 00000000 a5c3e10a a5c3e10a a5c3e10a +10 41200000 00000001 a5c30a7b a5c30a7b a5c30a7b +10 41200000 00000002 a50ae17b a50ae17b a50ae17b +10 41200000 00000003 0ac3e17b 0ac3e17b 0ac3e17b +10 41200000 fffffffd a5c30a7b a5c30a7b a5c30a7b +10 41200000 fffffffc a5c3e10a a5c3e10a a5c3e10a +10 41200000 80000002 a50ae17b a50ae17b a50ae17b +10 41200000 00000103 0ac3e17b 0ac3e17b 0ac3e17b +11 41300000 00000000 a5c3e10b a5c3e10b a5c3e10b +11 41300000 00000001 a5c30b7b a5c30b7b a5c30b7b +11 41300000 00000002 a50be17b a50be17b a50be17b +11 41300000 00000003 0bc3e17b 0bc3e17b 0bc3e17b +11 41300000 fffffffd a5c30b7b a5c30b7b a5c30b7b +11 41300000 fffffffc a5c3e10b a5c3e10b a5c3e10b +11 41300000 80000002 a50be17b a50be17b a50be17b +11 41300000 00000103 0bc3e17b 0bc3e17b 0bc3e17b +12 41400000 00000000 a5c3e10c a5c3e10c a5c3e10c +12 41400000 00000001 a5c30c7b a5c30c7b a5c30c7b +12 41400000 00000002 a50ce17b a50ce17b a50ce17b +12 41400000 00000003 0cc3e17b 0cc3e17b 0cc3e17b +12 41400000 fffffffd a5c30c7b a5c30c7b a5c30c7b +12 41400000 fffffffc a5c3e10c a5c3e10c a5c3e10c +12 41400000 80000002 a50ce17b a50ce17b a50ce17b +12 41400000 00000103 0cc3e17b 0cc3e17b 0cc3e17b +13 41500000 00000000 a5c3e10d a5c3e10d a5c3e10d +13 41500000 00000001 a5c30d7b a5c30d7b a5c30d7b +13 41500000 00000002 a50de17b a50de17b a50de17b +13 41500000 00000003 0dc3e17b 0dc3e17b 0dc3e17b +13 41500000 fffffffd a5c30d7b a5c30d7b a5c30d7b +13 41500000 fffffffc a5c3e10d a5c3e10d a5c3e10d +13 41500000 80000002 a50de17b a50de17b a50de17b +13 41500000 00000103 0dc3e17b 0dc3e17b 0dc3e17b +14 41600000 00000000 a5c3e10e a5c3e10e a5c3e10e +14 41600000 00000001 a5c30e7b a5c30e7b a5c30e7b +14 41600000 00000002 a50ee17b a50ee17b a50ee17b +14 41600000 00000003 0ec3e17b 0ec3e17b 0ec3e17b +14 41600000 fffffffd a5c30e7b a5c30e7b a5c30e7b +14 41600000 fffffffc a5c3e10e a5c3e10e a5c3e10e +14 41600000 80000002 a50ee17b a50ee17b a50ee17b +14 41600000 00000103 0ec3e17b 0ec3e17b 0ec3e17b +15 41700000 00000000 a5c3e10f a5c3e10f a5c3e10f +15 41700000 00000001 a5c30f7b a5c30f7b a5c30f7b +15 41700000 00000002 a50fe17b a50fe17b a50fe17b +15 41700000 00000003 0fc3e17b 0fc3e17b 0fc3e17b +15 41700000 fffffffd a5c30f7b a5c30f7b a5c30f7b +15 41700000 fffffffc a5c3e10f a5c3e10f a5c3e10f +15 41700000 80000002 a50fe17b a50fe17b a50fe17b +15 41700000 00000103 0fc3e17b 0fc3e17b 0fc3e17b +16 41800000 00000000 a5c3e110 a5c3e110 a5c3e110 +16 41800000 00000001 a5c3107b a5c3107b a5c3107b +16 41800000 00000002 a510e17b a510e17b a510e17b +16 41800000 00000003 10c3e17b 10c3e17b 10c3e17b +16 41800000 fffffffd a5c3107b a5c3107b a5c3107b +16 41800000 fffffffc a5c3e110 a5c3e110 a5c3e110 +16 41800000 80000002 a510e17b a510e17b a510e17b +16 41800000 00000103 10c3e17b 10c3e17b 10c3e17b +31 41f80000 00000000 a5c3e11f a5c3e11f a5c3e11f +31 41f80000 00000001 a5c31f7b a5c31f7b a5c31f7b +31 41f80000 00000002 a51fe17b a51fe17b a51fe17b +31 41f80000 00000003 1fc3e17b 1fc3e17b 1fc3e17b +31 41f80000 fffffffd a5c31f7b a5c31f7b a5c31f7b +31 41f80000 fffffffc a5c3e11f a5c3e11f a5c3e11f +31 41f80000 80000002 a51fe17b a51fe17b a51fe17b +31 41f80000 00000103 1fc3e17b 1fc3e17b 1fc3e17b +32 42000000 00000000 a5c3e120 a5c3e120 a5c3e120 +32 42000000 00000001 a5c3207b a5c3207b a5c3207b +32 42000000 00000002 a520e17b a520e17b a520e17b +32 42000000 00000003 20c3e17b 20c3e17b 20c3e17b +32 42000000 fffffffd a5c3207b a5c3207b a5c3207b +32 42000000 fffffffc a5c3e120 a5c3e120 a5c3e120 +32 42000000 80000002 a520e17b a520e17b a520e17b +32 42000000 00000103 20c3e17b 20c3e17b 20c3e17b +63 427c0000 00000000 a5c3e13f a5c3e13f a5c3e13f +63 427c0000 00000001 a5c33f7b a5c33f7b a5c33f7b +63 427c0000 00000002 a53fe17b a53fe17b a53fe17b +63 427c0000 00000003 3fc3e17b 3fc3e17b 3fc3e17b +63 427c0000 fffffffd a5c33f7b a5c33f7b a5c33f7b +63 427c0000 fffffffc a5c3e13f a5c3e13f a5c3e13f +63 427c0000 80000002 a53fe17b a53fe17b a53fe17b +63 427c0000 00000103 3fc3e17b 3fc3e17b 3fc3e17b +64 42800000 00000000 a5c3e140 a5c3e140 a5c3e140 +64 42800000 00000001 a5c3407b a5c3407b a5c3407b +64 42800000 00000002 a540e17b a540e17b a540e17b +64 42800000 00000003 40c3e17b 40c3e17b 40c3e17b +64 42800000 fffffffd a5c3407b a5c3407b a5c3407b +64 42800000 fffffffc a5c3e140 a5c3e140 a5c3e140 +64 42800000 80000002 a540e17b a540e17b a540e17b +64 42800000 00000103 40c3e17b 40c3e17b 40c3e17b +100 42c80000 00000000 a5c3e164 a5c3e164 a5c3e164 +100 42c80000 00000001 a5c3647b a5c3647b a5c3647b +100 42c80000 00000002 a564e17b a564e17b a564e17b +100 42c80000 00000003 64c3e17b 64c3e17b 64c3e17b +100 42c80000 fffffffd a5c3647b a5c3647b a5c3647b +100 42c80000 fffffffc a5c3e164 a5c3e164 a5c3e164 +100 42c80000 80000002 a564e17b a564e17b a564e17b +100 42c80000 00000103 64c3e17b 64c3e17b 64c3e17b +127 42fe0000 00000000 a5c3e17f a5c3e17f a5c3e17f +127 42fe0000 00000001 a5c37f7b a5c37f7b a5c37f7b +127 42fe0000 00000002 a57fe17b a57fe17b a57fe17b +127 42fe0000 00000003 7fc3e17b 7fc3e17b 7fc3e17b +127 42fe0000 fffffffd a5c37f7b a5c37f7b a5c37f7b +127 42fe0000 fffffffc a5c3e17f a5c3e17f a5c3e17f +127 42fe0000 80000002 a57fe17b a57fe17b a57fe17b +127 42fe0000 00000103 7fc3e17b 7fc3e17b 7fc3e17b +128 43000000 00000000 a5c3e180 a5c3e180 a5c3e180 +128 43000000 00000001 a5c3807b a5c3807b a5c3807b +128 43000000 00000002 a580e17b a580e17b a580e17b +128 43000000 00000003 80c3e17b 80c3e17b 80c3e17b +128 43000000 fffffffd a5c3807b a5c3807b a5c3807b +128 43000000 fffffffc a5c3e180 a5c3e180 a5c3e180 +128 43000000 80000002 a580e17b a580e17b a580e17b +128 43000000 00000103 80c3e17b 80c3e17b 80c3e17b +129 43010000 00000000 a5c3e181 a5c3e181 a5c3e181 +129 43010000 00000001 a5c3817b a5c3817b a5c3817b +129 43010000 00000002 a581e17b a581e17b a581e17b +129 43010000 00000003 81c3e17b 81c3e17b 81c3e17b +129 43010000 fffffffd a5c3817b a5c3817b a5c3817b +129 43010000 fffffffc a5c3e181 a5c3e181 a5c3e181 +129 43010000 80000002 a581e17b a581e17b a581e17b +129 43010000 00000103 81c3e17b 81c3e17b 81c3e17b +200 43480000 00000000 a5c3e1c8 a5c3e1c8 a5c3e1c8 +200 43480000 00000001 a5c3c87b a5c3c87b a5c3c87b +200 43480000 00000002 a5c8e17b a5c8e17b a5c8e17b +200 43480000 00000003 c8c3e17b c8c3e17b c8c3e17b +200 43480000 fffffffd a5c3c87b a5c3c87b a5c3c87b +200 43480000 fffffffc a5c3e1c8 a5c3e1c8 a5c3e1c8 +200 43480000 80000002 a5c8e17b a5c8e17b a5c8e17b +200 43480000 00000103 c8c3e17b c8c3e17b c8c3e17b +253 437d0000 00000000 a5c3e1fd a5c3e1fd a5c3e1fd +253 437d0000 00000001 a5c3fd7b a5c3fd7b a5c3fd7b +253 437d0000 00000002 a5fde17b a5fde17b a5fde17b +253 437d0000 00000003 fdc3e17b fdc3e17b fdc3e17b +253 437d0000 fffffffd a5c3fd7b a5c3fd7b a5c3fd7b +253 437d0000 fffffffc a5c3e1fd a5c3e1fd a5c3e1fd +253 437d0000 80000002 a5fde17b a5fde17b a5fde17b +253 437d0000 00000103 fdc3e17b fdc3e17b fdc3e17b +254 437e0000 00000000 a5c3e1fe a5c3e1fe a5c3e1fe +254 437e0000 00000001 a5c3fe7b a5c3fe7b a5c3fe7b +254 437e0000 00000002 a5fee17b a5fee17b a5fee17b +254 437e0000 00000003 fec3e17b fec3e17b fec3e17b +254 437e0000 fffffffd a5c3fe7b a5c3fe7b a5c3fe7b +254 437e0000 fffffffc a5c3e1fe a5c3e1fe a5c3e1fe +254 437e0000 80000002 a5fee17b a5fee17b a5fee17b +254 437e0000 00000103 fec3e17b fec3e17b fec3e17b +255 437f0000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +255 437f0000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +255 437f0000 00000002 a5ffe17b a5ffe17b a5ffe17b +255 437f0000 00000003 ffc3e17b ffc3e17b ffc3e17b +255 437f0000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +255 437f0000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +255 437f0000 80000002 a5ffe17b a5ffe17b a5ffe17b +255 437f0000 00000103 ffc3e17b ffc3e17b ffc3e17b +0.5 3f000000 00000000 a5c3e100 a5c3e100 a5c3e100 +0.5 3f000000 00000001 a5c3007b a5c3007b a5c3007b +0.5 3f000000 00000002 a500e17b a500e17b a500e17b +0.5 3f000000 00000003 00c3e17b 00c3e17b 00c3e17b +0.5 3f000000 fffffffd a5c3007b a5c3007b a5c3007b +0.5 3f000000 fffffffc a5c3e100 a5c3e100 a5c3e100 +0.5 3f000000 80000002 a500e17b a500e17b a500e17b +0.5 3f000000 00000103 00c3e17b 00c3e17b 00c3e17b +0.5-ulp 3effffff 00000000 a5c3e100 a5c3e100 a5c3e100 +0.5-ulp 3effffff 00000001 a5c3007b a5c3007b a5c3007b +0.5-ulp 3effffff 00000002 a500e17b a500e17b a500e17b +0.5-ulp 3effffff 00000003 00c3e17b 00c3e17b 00c3e17b +0.5-ulp 3effffff fffffffd a5c3007b a5c3007b a5c3007b +0.5-ulp 3effffff fffffffc a5c3e100 a5c3e100 a5c3e100 +0.5-ulp 3effffff 80000002 a500e17b a500e17b a500e17b +0.5-ulp 3effffff 00000103 00c3e17b 00c3e17b 00c3e17b +0.5+ulp 3f000001 00000000 a5c3e101 a5c3e100 a5c3e101 +0.5+ulp 3f000001 00000001 a5c3017b a5c3007b a5c3017b +0.5+ulp 3f000001 00000002 a501e17b a500e17b a501e17b +0.5+ulp 3f000001 00000003 01c3e17b 00c3e17b 01c3e17b +0.5+ulp 3f000001 fffffffd a5c3017b a5c3007b a5c3017b +0.5+ulp 3f000001 fffffffc a5c3e101 a5c3e100 a5c3e101 +0.5+ulp 3f000001 80000002 a501e17b a500e17b a501e17b +0.5+ulp 3f000001 00000103 01c3e17b 00c3e17b 01c3e17b +1.5 3fc00000 00000000 a5c3e102 a5c3e101 a5c3e102 +1.5 3fc00000 00000001 a5c3027b a5c3017b a5c3027b +1.5 3fc00000 00000002 a502e17b a501e17b a502e17b +1.5 3fc00000 00000003 02c3e17b 01c3e17b 02c3e17b +1.5 3fc00000 fffffffd a5c3027b a5c3017b a5c3027b +1.5 3fc00000 fffffffc a5c3e102 a5c3e101 a5c3e102 +1.5 3fc00000 80000002 a502e17b a501e17b a502e17b +1.5 3fc00000 00000103 02c3e17b 01c3e17b 02c3e17b +1.5-ulp 3fbfffff 00000000 a5c3e101 a5c3e101 a5c3e101 +1.5-ulp 3fbfffff 00000001 a5c3017b a5c3017b a5c3017b +1.5-ulp 3fbfffff 00000002 a501e17b a501e17b a501e17b +1.5-ulp 3fbfffff 00000003 01c3e17b 01c3e17b 01c3e17b +1.5-ulp 3fbfffff fffffffd a5c3017b a5c3017b a5c3017b +1.5-ulp 3fbfffff fffffffc a5c3e101 a5c3e101 a5c3e101 +1.5-ulp 3fbfffff 80000002 a501e17b a501e17b a501e17b +1.5-ulp 3fbfffff 00000103 01c3e17b 01c3e17b 01c3e17b +1.5+ulp 3fc00001 00000000 a5c3e102 a5c3e101 a5c3e102 +1.5+ulp 3fc00001 00000001 a5c3027b a5c3017b a5c3027b +1.5+ulp 3fc00001 00000002 a502e17b a501e17b a502e17b +1.5+ulp 3fc00001 00000003 02c3e17b 01c3e17b 02c3e17b +1.5+ulp 3fc00001 fffffffd a5c3027b a5c3017b a5c3027b +1.5+ulp 3fc00001 fffffffc a5c3e102 a5c3e101 a5c3e102 +1.5+ulp 3fc00001 80000002 a502e17b a501e17b a502e17b +1.5+ulp 3fc00001 00000103 02c3e17b 01c3e17b 02c3e17b +2.5 40200000 00000000 a5c3e102 a5c3e102 a5c3e102 +2.5 40200000 00000001 a5c3027b a5c3027b a5c3027b +2.5 40200000 00000002 a502e17b a502e17b a502e17b +2.5 40200000 00000003 02c3e17b 02c3e17b 02c3e17b +2.5 40200000 fffffffd a5c3027b a5c3027b a5c3027b +2.5 40200000 fffffffc a5c3e102 a5c3e102 a5c3e102 +2.5 40200000 80000002 a502e17b a502e17b a502e17b +2.5 40200000 00000103 02c3e17b 02c3e17b 02c3e17b +2.5-ulp 401fffff 00000000 a5c3e102 a5c3e102 a5c3e102 +2.5-ulp 401fffff 00000001 a5c3027b a5c3027b a5c3027b +2.5-ulp 401fffff 00000002 a502e17b a502e17b a502e17b +2.5-ulp 401fffff 00000003 02c3e17b 02c3e17b 02c3e17b +2.5-ulp 401fffff fffffffd a5c3027b a5c3027b a5c3027b +2.5-ulp 401fffff fffffffc a5c3e102 a5c3e102 a5c3e102 +2.5-ulp 401fffff 80000002 a502e17b a502e17b a502e17b +2.5-ulp 401fffff 00000103 02c3e17b 02c3e17b 02c3e17b +2.5+ulp 40200001 00000000 a5c3e103 a5c3e102 a5c3e103 +2.5+ulp 40200001 00000001 a5c3037b a5c3027b a5c3037b +2.5+ulp 40200001 00000002 a503e17b a502e17b a503e17b +2.5+ulp 40200001 00000003 03c3e17b 02c3e17b 03c3e17b +2.5+ulp 40200001 fffffffd a5c3037b a5c3027b a5c3037b +2.5+ulp 40200001 fffffffc a5c3e103 a5c3e102 a5c3e103 +2.5+ulp 40200001 80000002 a503e17b a502e17b a503e17b +2.5+ulp 40200001 00000103 03c3e17b 02c3e17b 03c3e17b +3.5 40600000 00000000 a5c3e104 a5c3e103 a5c3e104 +3.5 40600000 00000001 a5c3047b a5c3037b a5c3047b +3.5 40600000 00000002 a504e17b a503e17b a504e17b +3.5 40600000 00000003 04c3e17b 03c3e17b 04c3e17b +3.5 40600000 fffffffd a5c3047b a5c3037b a5c3047b +3.5 40600000 fffffffc a5c3e104 a5c3e103 a5c3e104 +3.5 40600000 80000002 a504e17b a503e17b a504e17b +3.5 40600000 00000103 04c3e17b 03c3e17b 04c3e17b +3.5-ulp 405fffff 00000000 a5c3e103 a5c3e103 a5c3e103 +3.5-ulp 405fffff 00000001 a5c3037b a5c3037b a5c3037b +3.5-ulp 405fffff 00000002 a503e17b a503e17b a503e17b +3.5-ulp 405fffff 00000003 03c3e17b 03c3e17b 03c3e17b +3.5-ulp 405fffff fffffffd a5c3037b a5c3037b a5c3037b +3.5-ulp 405fffff fffffffc a5c3e103 a5c3e103 a5c3e103 +3.5-ulp 405fffff 80000002 a503e17b a503e17b a503e17b +3.5-ulp 405fffff 00000103 03c3e17b 03c3e17b 03c3e17b +3.5+ulp 40600001 00000000 a5c3e104 a5c3e103 a5c3e104 +3.5+ulp 40600001 00000001 a5c3047b a5c3037b a5c3047b +3.5+ulp 40600001 00000002 a504e17b a503e17b a504e17b +3.5+ulp 40600001 00000003 04c3e17b 03c3e17b 04c3e17b +3.5+ulp 40600001 fffffffd a5c3047b a5c3037b a5c3047b +3.5+ulp 40600001 fffffffc a5c3e104 a5c3e103 a5c3e104 +3.5+ulp 40600001 80000002 a504e17b a503e17b a504e17b +3.5+ulp 40600001 00000103 04c3e17b 03c3e17b 04c3e17b +127.5 42ff0000 00000000 a5c3e180 a5c3e17f a5c3e180 +127.5 42ff0000 00000001 a5c3807b a5c37f7b a5c3807b +127.5 42ff0000 00000002 a580e17b a57fe17b a580e17b +127.5 42ff0000 00000003 80c3e17b 7fc3e17b 80c3e17b +127.5 42ff0000 fffffffd a5c3807b a5c37f7b a5c3807b +127.5 42ff0000 fffffffc a5c3e180 a5c3e17f a5c3e180 +127.5 42ff0000 80000002 a580e17b a57fe17b a580e17b +127.5 42ff0000 00000103 80c3e17b 7fc3e17b 80c3e17b +127.5-ulp 42feffff 00000000 a5c3e17f a5c3e17f a5c3e17f +127.5-ulp 42feffff 00000001 a5c37f7b a5c37f7b a5c37f7b +127.5-ulp 42feffff 00000002 a57fe17b a57fe17b a57fe17b +127.5-ulp 42feffff 00000003 7fc3e17b 7fc3e17b 7fc3e17b +127.5-ulp 42feffff fffffffd a5c37f7b a5c37f7b a5c37f7b +127.5-ulp 42feffff fffffffc a5c3e17f a5c3e17f a5c3e17f +127.5-ulp 42feffff 80000002 a57fe17b a57fe17b a57fe17b +127.5-ulp 42feffff 00000103 7fc3e17b 7fc3e17b 7fc3e17b +127.5+ulp 42ff0001 00000000 a5c3e180 a5c3e17f a5c3e180 +127.5+ulp 42ff0001 00000001 a5c3807b a5c37f7b a5c3807b +127.5+ulp 42ff0001 00000002 a580e17b a57fe17b a580e17b +127.5+ulp 42ff0001 00000003 80c3e17b 7fc3e17b 80c3e17b +127.5+ulp 42ff0001 fffffffd a5c3807b a5c37f7b a5c3807b +127.5+ulp 42ff0001 fffffffc a5c3e180 a5c3e17f a5c3e180 +127.5+ulp 42ff0001 80000002 a580e17b a57fe17b a580e17b +127.5+ulp 42ff0001 00000103 80c3e17b 7fc3e17b 80c3e17b +254.5 437e8000 00000000 a5c3e1fe a5c3e1fe a5c3e1fe +254.5 437e8000 00000001 a5c3fe7b a5c3fe7b a5c3fe7b +254.5 437e8000 00000002 a5fee17b a5fee17b a5fee17b +254.5 437e8000 00000003 fec3e17b fec3e17b fec3e17b +254.5 437e8000 fffffffd a5c3fe7b a5c3fe7b a5c3fe7b +254.5 437e8000 fffffffc a5c3e1fe a5c3e1fe a5c3e1fe +254.5 437e8000 80000002 a5fee17b a5fee17b a5fee17b +254.5 437e8000 00000103 fec3e17b fec3e17b fec3e17b +254.5-ulp 437e7fff 00000000 a5c3e1fe a5c3e1fe a5c3e1fe +254.5-ulp 437e7fff 00000001 a5c3fe7b a5c3fe7b a5c3fe7b +254.5-ulp 437e7fff 00000002 a5fee17b a5fee17b a5fee17b +254.5-ulp 437e7fff 00000003 fec3e17b fec3e17b fec3e17b +254.5-ulp 437e7fff fffffffd a5c3fe7b a5c3fe7b a5c3fe7b +254.5-ulp 437e7fff fffffffc a5c3e1fe a5c3e1fe a5c3e1fe +254.5-ulp 437e7fff 80000002 a5fee17b a5fee17b a5fee17b +254.5-ulp 437e7fff 00000103 fec3e17b fec3e17b fec3e17b +254.5+ulp 437e8001 00000000 a5c3e1ff a5c3e1fe a5c3e1ff +254.5+ulp 437e8001 00000001 a5c3ff7b a5c3fe7b a5c3ff7b +254.5+ulp 437e8001 00000002 a5ffe17b a5fee17b a5ffe17b +254.5+ulp 437e8001 00000003 ffc3e17b fec3e17b ffc3e17b +254.5+ulp 437e8001 fffffffd a5c3ff7b a5c3fe7b a5c3ff7b +254.5+ulp 437e8001 fffffffc a5c3e1ff a5c3e1fe a5c3e1ff +254.5+ulp 437e8001 80000002 a5ffe17b a5fee17b a5ffe17b +254.5+ulp 437e8001 00000103 ffc3e17b fec3e17b ffc3e17b +255.5 437f8000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +255.5 437f8000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +255.5 437f8000 00000002 a5ffe17b a5ffe17b a5ffe17b +255.5 437f8000 00000003 ffc3e17b ffc3e17b ffc3e17b +255.5 437f8000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +255.5 437f8000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +255.5 437f8000 80000002 a5ffe17b a5ffe17b a5ffe17b +255.5 437f8000 00000103 ffc3e17b ffc3e17b ffc3e17b +255.5-ulp 437f7fff 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +255.5-ulp 437f7fff 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +255.5-ulp 437f7fff 00000002 a5ffe17b a5ffe17b a5ffe17b +255.5-ulp 437f7fff 00000003 ffc3e17b ffc3e17b ffc3e17b +255.5-ulp 437f7fff fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +255.5-ulp 437f7fff fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +255.5-ulp 437f7fff 80000002 a5ffe17b a5ffe17b a5ffe17b +255.5-ulp 437f7fff 00000103 ffc3e17b ffc3e17b ffc3e17b +255.5+ulp 437f8001 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +255.5+ulp 437f8001 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +255.5+ulp 437f8001 00000002 a5ffe17b a5ffe17b a5ffe17b +255.5+ulp 437f8001 00000003 ffc3e17b ffc3e17b ffc3e17b +255.5+ulp 437f8001 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +255.5+ulp 437f8001 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +255.5+ulp 437f8001 80000002 a5ffe17b a5ffe17b a5ffe17b +255.5+ulp 437f8001 00000103 ffc3e17b ffc3e17b ffc3e17b +0.25 3e800000 00000000 a5c3e100 a5c3e100 a5c3e100 +0.25 3e800000 00000001 a5c3007b a5c3007b a5c3007b +0.25 3e800000 00000002 a500e17b a500e17b a500e17b +0.25 3e800000 00000003 00c3e17b 00c3e17b 00c3e17b +0.25 3e800000 fffffffd a5c3007b a5c3007b a5c3007b +0.25 3e800000 fffffffc a5c3e100 a5c3e100 a5c3e100 +0.25 3e800000 80000002 a500e17b a500e17b a500e17b +0.25 3e800000 00000103 00c3e17b 00c3e17b 00c3e17b +0.75 3f400000 00000000 a5c3e101 a5c3e100 a5c3e101 +0.75 3f400000 00000001 a5c3017b a5c3007b a5c3017b +0.75 3f400000 00000002 a501e17b a500e17b a501e17b +0.75 3f400000 00000003 01c3e17b 00c3e17b 01c3e17b +0.75 3f400000 fffffffd a5c3017b a5c3007b a5c3017b +0.75 3f400000 fffffffc a5c3e101 a5c3e100 a5c3e101 +0.75 3f400000 80000002 a501e17b a500e17b a501e17b +0.75 3f400000 00000103 01c3e17b 00c3e17b 01c3e17b +1.25 3fa00000 00000000 a5c3e101 a5c3e101 a5c3e101 +1.25 3fa00000 00000001 a5c3017b a5c3017b a5c3017b +1.25 3fa00000 00000002 a501e17b a501e17b a501e17b +1.25 3fa00000 00000003 01c3e17b 01c3e17b 01c3e17b +1.25 3fa00000 fffffffd a5c3017b a5c3017b a5c3017b +1.25 3fa00000 fffffffc a5c3e101 a5c3e101 a5c3e101 +1.25 3fa00000 80000002 a501e17b a501e17b a501e17b +1.25 3fa00000 00000103 01c3e17b 01c3e17b 01c3e17b +1.75 3fe00000 00000000 a5c3e102 a5c3e101 a5c3e102 +1.75 3fe00000 00000001 a5c3027b a5c3017b a5c3027b +1.75 3fe00000 00000002 a502e17b a501e17b a502e17b +1.75 3fe00000 00000003 02c3e17b 01c3e17b 02c3e17b +1.75 3fe00000 fffffffd a5c3027b a5c3017b a5c3027b +1.75 3fe00000 fffffffc a5c3e102 a5c3e101 a5c3e102 +1.75 3fe00000 80000002 a502e17b a501e17b a502e17b +1.75 3fe00000 00000103 02c3e17b 01c3e17b 02c3e17b +2.25 40100000 00000000 a5c3e102 a5c3e102 a5c3e102 +2.25 40100000 00000001 a5c3027b a5c3027b a5c3027b +2.25 40100000 00000002 a502e17b a502e17b a502e17b +2.25 40100000 00000003 02c3e17b 02c3e17b 02c3e17b +2.25 40100000 fffffffd a5c3027b a5c3027b a5c3027b +2.25 40100000 fffffffc a5c3e102 a5c3e102 a5c3e102 +2.25 40100000 80000002 a502e17b a502e17b a502e17b +2.25 40100000 00000103 02c3e17b 02c3e17b 02c3e17b +2.75 40300000 00000000 a5c3e103 a5c3e102 a5c3e103 +2.75 40300000 00000001 a5c3037b a5c3027b a5c3037b +2.75 40300000 00000002 a503e17b a502e17b a503e17b +2.75 40300000 00000003 03c3e17b 02c3e17b 03c3e17b +2.75 40300000 fffffffd a5c3037b a5c3027b a5c3037b +2.75 40300000 fffffffc a5c3e103 a5c3e102 a5c3e103 +2.75 40300000 80000002 a503e17b a502e17b a503e17b +2.75 40300000 00000103 03c3e17b 02c3e17b 03c3e17b +100.25 42c88000 00000000 a5c3e164 a5c3e164 a5c3e164 +100.25 42c88000 00000001 a5c3647b a5c3647b a5c3647b +100.25 42c88000 00000002 a564e17b a564e17b a564e17b +100.25 42c88000 00000003 64c3e17b 64c3e17b 64c3e17b +100.25 42c88000 fffffffd a5c3647b a5c3647b a5c3647b +100.25 42c88000 fffffffc a5c3e164 a5c3e164 a5c3e164 +100.25 42c88000 80000002 a564e17b a564e17b a564e17b +100.25 42c88000 00000103 64c3e17b 64c3e17b 64c3e17b +100.75 42c98000 00000000 a5c3e165 a5c3e164 a5c3e165 +100.75 42c98000 00000001 a5c3657b a5c3647b a5c3657b +100.75 42c98000 00000002 a565e17b a564e17b a565e17b +100.75 42c98000 00000003 65c3e17b 64c3e17b 65c3e17b +100.75 42c98000 fffffffd a5c3657b a5c3647b a5c3657b +100.75 42c98000 fffffffc a5c3e165 a5c3e164 a5c3e165 +100.75 42c98000 80000002 a565e17b a564e17b a565e17b +100.75 42c98000 00000103 65c3e17b 64c3e17b 65c3e17b +254.25 437e4000 00000000 a5c3e1fe a5c3e1fe a5c3e1fe +254.25 437e4000 00000001 a5c3fe7b a5c3fe7b a5c3fe7b +254.25 437e4000 00000002 a5fee17b a5fee17b a5fee17b +254.25 437e4000 00000003 fec3e17b fec3e17b fec3e17b +254.25 437e4000 fffffffd a5c3fe7b a5c3fe7b a5c3fe7b +254.25 437e4000 fffffffc a5c3e1fe a5c3e1fe a5c3e1fe +254.25 437e4000 80000002 a5fee17b a5fee17b a5fee17b +254.25 437e4000 00000103 fec3e17b fec3e17b fec3e17b +254.75 437ec000 00000000 a5c3e1ff a5c3e1fe a5c3e1ff +254.75 437ec000 00000001 a5c3ff7b a5c3fe7b a5c3ff7b +254.75 437ec000 00000002 a5ffe17b a5fee17b a5ffe17b +254.75 437ec000 00000003 ffc3e17b fec3e17b ffc3e17b +254.75 437ec000 fffffffd a5c3ff7b a5c3fe7b a5c3ff7b +254.75 437ec000 fffffffc a5c3e1ff a5c3e1fe a5c3e1ff +254.75 437ec000 80000002 a5ffe17b a5fee17b a5ffe17b +254.75 437ec000 00000103 ffc3e17b fec3e17b ffc3e17b +0.1 3dcccccd 00000000 a5c3e100 a5c3e100 a5c3e100 +0.1 3dcccccd 00000001 a5c3007b a5c3007b a5c3007b +0.1 3dcccccd 00000002 a500e17b a500e17b a500e17b +0.1 3dcccccd 00000003 00c3e17b 00c3e17b 00c3e17b +0.1 3dcccccd fffffffd a5c3007b a5c3007b a5c3007b +0.1 3dcccccd fffffffc a5c3e100 a5c3e100 a5c3e100 +0.1 3dcccccd 80000002 a500e17b a500e17b a500e17b +0.1 3dcccccd 00000103 00c3e17b 00c3e17b 00c3e17b +0.9 3f666666 00000000 a5c3e101 a5c3e100 a5c3e101 +0.9 3f666666 00000001 a5c3017b a5c3007b a5c3017b +0.9 3f666666 00000002 a501e17b a500e17b a501e17b +0.9 3f666666 00000003 01c3e17b 00c3e17b 01c3e17b +0.9 3f666666 fffffffd a5c3017b a5c3007b a5c3017b +0.9 3f666666 fffffffc a5c3e101 a5c3e100 a5c3e101 +0.9 3f666666 80000002 a501e17b a500e17b a501e17b +0.9 3f666666 00000103 01c3e17b 00c3e17b 01c3e17b +0.4999999 3efffffd 00000000 a5c3e100 a5c3e100 a5c3e100 +0.4999999 3efffffd 00000001 a5c3007b a5c3007b a5c3007b +0.4999999 3efffffd 00000002 a500e17b a500e17b a500e17b +0.4999999 3efffffd 00000003 00c3e17b 00c3e17b 00c3e17b +0.4999999 3efffffd fffffffd a5c3007b a5c3007b a5c3007b +0.4999999 3efffffd fffffffc a5c3e100 a5c3e100 a5c3e100 +0.4999999 3efffffd 80000002 a500e17b a500e17b a500e17b +0.4999999 3efffffd 00000103 00c3e17b 00c3e17b 00c3e17b +0.5000001 3f000002 00000000 a5c3e101 a5c3e100 a5c3e101 +0.5000001 3f000002 00000001 a5c3017b a5c3007b a5c3017b +0.5000001 3f000002 00000002 a501e17b a500e17b a501e17b +0.5000001 3f000002 00000003 01c3e17b 00c3e17b 01c3e17b +0.5000001 3f000002 fffffffd a5c3017b a5c3007b a5c3017b +0.5000001 3f000002 fffffffc a5c3e101 a5c3e100 a5c3e101 +0.5000001 3f000002 80000002 a501e17b a500e17b a501e17b +0.5000001 3f000002 00000103 01c3e17b 00c3e17b 01c3e17b +-0.1 bdcccccd 00000000 a5c3e100 a5c3e100 a5c3e100 +-0.1 bdcccccd 00000001 a5c3007b a5c3007b a5c3007b +-0.1 bdcccccd 00000002 a500e17b a500e17b a500e17b +-0.1 bdcccccd 00000003 00c3e17b 00c3e17b 00c3e17b +-0.1 bdcccccd fffffffd a5c3007b a5c3007b a5c3007b +-0.1 bdcccccd fffffffc a5c3e100 a5c3e100 a5c3e100 +-0.1 bdcccccd 80000002 a500e17b a500e17b a500e17b +-0.1 bdcccccd 00000103 00c3e17b 00c3e17b 00c3e17b +-0.4 becccccd 00000000 a5c3e100 a5c3e100 a5c3e100 +-0.4 becccccd 00000001 a5c3007b a5c3007b a5c3007b +-0.4 becccccd 00000002 a500e17b a500e17b a500e17b +-0.4 becccccd 00000003 00c3e17b 00c3e17b 00c3e17b +-0.4 becccccd fffffffd a5c3007b a5c3007b a5c3007b +-0.4 becccccd fffffffc a5c3e100 a5c3e100 a5c3e100 +-0.4 becccccd 80000002 a500e17b a500e17b a500e17b +-0.4 becccccd 00000103 00c3e17b 00c3e17b 00c3e17b +-0.5 bf000000 00000000 a5c3e100 a5c3e100 a5c3e100 +-0.5 bf000000 00000001 a5c3007b a5c3007b a5c3007b +-0.5 bf000000 00000002 a500e17b a500e17b a500e17b +-0.5 bf000000 00000003 00c3e17b 00c3e17b 00c3e17b +-0.5 bf000000 fffffffd a5c3007b a5c3007b a5c3007b +-0.5 bf000000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-0.5 bf000000 80000002 a500e17b a500e17b a500e17b +-0.5 bf000000 00000103 00c3e17b 00c3e17b 00c3e17b +-0.6 bf19999a 00000000 a5c3e100 a5c3e100 a5c3e100 +-0.6 bf19999a 00000001 a5c3007b a5c3007b a5c3007b +-0.6 bf19999a 00000002 a500e17b a500e17b a500e17b +-0.6 bf19999a 00000003 00c3e17b 00c3e17b 00c3e17b +-0.6 bf19999a fffffffd a5c3007b a5c3007b a5c3007b +-0.6 bf19999a fffffffc a5c3e100 a5c3e100 a5c3e100 +-0.6 bf19999a 80000002 a500e17b a500e17b a500e17b +-0.6 bf19999a 00000103 00c3e17b 00c3e17b 00c3e17b +-1 bf800000 00000000 a5c3e100 a5c3e100 a5c3e100 +-1 bf800000 00000001 a5c3007b a5c3007b a5c3007b +-1 bf800000 00000002 a500e17b a500e17b a500e17b +-1 bf800000 00000003 00c3e17b 00c3e17b 00c3e17b +-1 bf800000 fffffffd a5c3007b a5c3007b a5c3007b +-1 bf800000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-1 bf800000 80000002 a500e17b a500e17b a500e17b +-1 bf800000 00000103 00c3e17b 00c3e17b 00c3e17b +-1.5 bfc00000 00000000 a5c3e100 a5c3e100 a5c3e100 +-1.5 bfc00000 00000001 a5c3007b a5c3007b a5c3007b +-1.5 bfc00000 00000002 a500e17b a500e17b a500e17b +-1.5 bfc00000 00000003 00c3e17b 00c3e17b 00c3e17b +-1.5 bfc00000 fffffffd a5c3007b a5c3007b a5c3007b +-1.5 bfc00000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-1.5 bfc00000 80000002 a500e17b a500e17b a500e17b +-1.5 bfc00000 00000103 00c3e17b 00c3e17b 00c3e17b +-2 c0000000 00000000 a5c3e100 a5c3e100 a5c3e100 +-2 c0000000 00000001 a5c3007b a5c3007b a5c3007b +-2 c0000000 00000002 a500e17b a500e17b a500e17b +-2 c0000000 00000003 00c3e17b 00c3e17b 00c3e17b +-2 c0000000 fffffffd a5c3007b a5c3007b a5c3007b +-2 c0000000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-2 c0000000 80000002 a500e17b a500e17b a500e17b +-2 c0000000 00000103 00c3e17b 00c3e17b 00c3e17b +-255 c37f0000 00000000 a5c3e100 a5c3e100 a5c3e100 +-255 c37f0000 00000001 a5c3007b a5c3007b a5c3007b +-255 c37f0000 00000002 a500e17b a500e17b a500e17b +-255 c37f0000 00000003 00c3e17b 00c3e17b 00c3e17b +-255 c37f0000 fffffffd a5c3007b a5c3007b a5c3007b +-255 c37f0000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-255 c37f0000 80000002 a500e17b a500e17b a500e17b +-255 c37f0000 00000103 00c3e17b 00c3e17b 00c3e17b +-256 c3800000 00000000 a5c3e100 a5c3e100 a5c3e100 +-256 c3800000 00000001 a5c3007b a5c3007b a5c3007b +-256 c3800000 00000002 a500e17b a500e17b a500e17b +-256 c3800000 00000003 00c3e17b 00c3e17b 00c3e17b +-256 c3800000 fffffffd a5c3007b a5c3007b a5c3007b +-256 c3800000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-256 c3800000 80000002 a500e17b a500e17b a500e17b +-256 c3800000 00000103 00c3e17b 00c3e17b 00c3e17b +-0.5-ulp bf000001 00000000 a5c3e100 a5c3e100 a5c3e100 +-0.5-ulp bf000001 00000001 a5c3007b a5c3007b a5c3007b +-0.5-ulp bf000001 00000002 a500e17b a500e17b a500e17b +-0.5-ulp bf000001 00000003 00c3e17b 00c3e17b 00c3e17b +-0.5-ulp bf000001 fffffffd a5c3007b a5c3007b a5c3007b +-0.5-ulp bf000001 fffffffc a5c3e100 a5c3e100 a5c3e100 +-0.5-ulp bf000001 80000002 a500e17b a500e17b a500e17b +-0.5-ulp bf000001 00000103 00c3e17b 00c3e17b 00c3e17b +-0.5+ulp beffffff 00000000 a5c3e100 a5c3e100 a5c3e100 +-0.5+ulp beffffff 00000001 a5c3007b a5c3007b a5c3007b +-0.5+ulp beffffff 00000002 a500e17b a500e17b a500e17b +-0.5+ulp beffffff 00000003 00c3e17b 00c3e17b 00c3e17b +-0.5+ulp beffffff fffffffd a5c3007b a5c3007b a5c3007b +-0.5+ulp beffffff fffffffc a5c3e100 a5c3e100 a5c3e100 +-0.5+ulp beffffff 80000002 a500e17b a500e17b a500e17b +-0.5+ulp beffffff 00000103 00c3e17b 00c3e17b 00c3e17b +255.4 437f6666 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +255.4 437f6666 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +255.4 437f6666 00000002 a5ffe17b a5ffe17b a5ffe17b +255.4 437f6666 00000003 ffc3e17b ffc3e17b ffc3e17b +255.4 437f6666 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +255.4 437f6666 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +255.4 437f6666 80000002 a5ffe17b a5ffe17b a5ffe17b +255.4 437f6666 00000103 ffc3e17b ffc3e17b ffc3e17b +255.9 437fe666 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +255.9 437fe666 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +255.9 437fe666 00000002 a5ffe17b a5ffe17b a5ffe17b +255.9 437fe666 00000003 ffc3e17b ffc3e17b ffc3e17b +255.9 437fe666 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +255.9 437fe666 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +255.9 437fe666 80000002 a5ffe17b a5ffe17b a5ffe17b +255.9 437fe666 00000103 ffc3e17b ffc3e17b ffc3e17b +256 43800000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +256 43800000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +256 43800000 00000002 a5ffe17b a5ffe17b a5ffe17b +256 43800000 00000003 ffc3e17b ffc3e17b ffc3e17b +256 43800000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +256 43800000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +256 43800000 80000002 a5ffe17b a5ffe17b a5ffe17b +256 43800000 00000103 ffc3e17b ffc3e17b ffc3e17b +256.5 43804000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +256.5 43804000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +256.5 43804000 00000002 a5ffe17b a5ffe17b a5ffe17b +256.5 43804000 00000003 ffc3e17b ffc3e17b ffc3e17b +256.5 43804000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +256.5 43804000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +256.5 43804000 80000002 a5ffe17b a5ffe17b a5ffe17b +256.5 43804000 00000103 ffc3e17b ffc3e17b ffc3e17b +257 43808000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +257 43808000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +257 43808000 00000002 a5ffe17b a5ffe17b a5ffe17b +257 43808000 00000003 ffc3e17b ffc3e17b ffc3e17b +257 43808000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +257 43808000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +257 43808000 80000002 a5ffe17b a5ffe17b a5ffe17b +257 43808000 00000103 ffc3e17b ffc3e17b ffc3e17b +511 43ff8000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +511 43ff8000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +511 43ff8000 00000002 a5ffe17b a5ffe17b a5ffe17b +511 43ff8000 00000003 ffc3e17b ffc3e17b ffc3e17b +511 43ff8000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +511 43ff8000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +511 43ff8000 80000002 a5ffe17b a5ffe17b a5ffe17b +511 43ff8000 00000103 ffc3e17b ffc3e17b ffc3e17b +512 44000000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +512 44000000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +512 44000000 00000002 a5ffe17b a5ffe17b a5ffe17b +512 44000000 00000003 ffc3e17b ffc3e17b ffc3e17b +512 44000000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +512 44000000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +512 44000000 80000002 a5ffe17b a5ffe17b a5ffe17b +512 44000000 00000103 ffc3e17b ffc3e17b ffc3e17b +1000 447a0000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +1000 447a0000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +1000 447a0000 00000002 a5ffe17b a5ffe17b a5ffe17b +1000 447a0000 00000003 ffc3e17b ffc3e17b ffc3e17b +1000 447a0000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +1000 447a0000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +1000 447a0000 80000002 a5ffe17b a5ffe17b a5ffe17b +1000 447a0000 00000103 ffc3e17b ffc3e17b ffc3e17b +65535 477fff00 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +65535 477fff00 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +65535 477fff00 00000002 a5ffe17b a5ffe17b a5ffe17b +65535 477fff00 00000003 ffc3e17b ffc3e17b ffc3e17b +65535 477fff00 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +65535 477fff00 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +65535 477fff00 80000002 a5ffe17b a5ffe17b a5ffe17b +65535 477fff00 00000103 ffc3e17b ffc3e17b ffc3e17b +65536 47800000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +65536 47800000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +65536 47800000 00000002 a5ffe17b a5ffe17b a5ffe17b +65536 47800000 00000003 ffc3e17b ffc3e17b ffc3e17b +65536 47800000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +65536 47800000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +65536 47800000 80000002 a5ffe17b a5ffe17b a5ffe17b +65536 47800000 00000103 ffc3e17b ffc3e17b ffc3e17b +1.67772e+07 4b800000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +1.67772e+07 4b800000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +1.67772e+07 4b800000 00000002 a5ffe17b a5ffe17b a5ffe17b +1.67772e+07 4b800000 00000003 ffc3e17b ffc3e17b ffc3e17b +1.67772e+07 4b800000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +1.67772e+07 4b800000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +1.67772e+07 4b800000 80000002 a5ffe17b a5ffe17b a5ffe17b +1.67772e+07 4b800000 00000103 ffc3e17b ffc3e17b ffc3e17b +4.29497e+09 4f800000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +4.29497e+09 4f800000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +4.29497e+09 4f800000 00000002 a5ffe17b a5ffe17b a5ffe17b +4.29497e+09 4f800000 00000003 ffc3e17b ffc3e17b ffc3e17b +4.29497e+09 4f800000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +4.29497e+09 4f800000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +4.29497e+09 4f800000 80000002 a5ffe17b a5ffe17b a5ffe17b +4.29497e+09 4f800000 00000103 ffc3e17b ffc3e17b ffc3e17b +1e+10 501502f9 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +1e+10 501502f9 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +1e+10 501502f9 00000002 a5ffe17b a5ffe17b a5ffe17b +1e+10 501502f9 00000003 ffc3e17b ffc3e17b ffc3e17b +1e+10 501502f9 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +1e+10 501502f9 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +1e+10 501502f9 80000002 a5ffe17b a5ffe17b a5ffe17b +1e+10 501502f9 00000103 ffc3e17b ffc3e17b ffc3e17b ++inf 7f800000 00000000 a5c3e1ff a5c3e1ff a5c3e1ff ++inf 7f800000 00000001 a5c3ff7b a5c3ff7b a5c3ff7b ++inf 7f800000 00000002 a5ffe17b a5ffe17b a5ffe17b ++inf 7f800000 00000003 ffc3e17b ffc3e17b ffc3e17b ++inf 7f800000 fffffffd a5c3ff7b a5c3ff7b a5c3ff7b ++inf 7f800000 fffffffc a5c3e1ff a5c3e1ff a5c3e1ff ++inf 7f800000 80000002 a5ffe17b a5ffe17b a5ffe17b ++inf 7f800000 00000103 ffc3e17b ffc3e17b ffc3e17b +-inf ff800000 00000000 a5c3e100 a5c3e100 a5c3e100 +-inf ff800000 00000001 a5c3007b a5c3007b a5c3007b +-inf ff800000 00000002 a500e17b a500e17b a500e17b +-inf ff800000 00000003 00c3e17b 00c3e17b 00c3e17b +-inf ff800000 fffffffd a5c3007b a5c3007b a5c3007b +-inf ff800000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-inf ff800000 80000002 a500e17b a500e17b a500e17b +-inf ff800000 00000103 00c3e17b 00c3e17b 00c3e17b +qNaN 7fc00000 00000000 a5c3e100 a5c3e100 a5c3e100 +qNaN 7fc00000 00000001 a5c3007b a5c3007b a5c3007b +qNaN 7fc00000 00000002 a500e17b a500e17b a500e17b +qNaN 7fc00000 00000003 00c3e17b 00c3e17b 00c3e17b +qNaN 7fc00000 fffffffd a5c3007b a5c3007b a5c3007b +qNaN 7fc00000 fffffffc a5c3e100 a5c3e100 a5c3e100 +qNaN 7fc00000 80000002 a500e17b a500e17b a500e17b +qNaN 7fc00000 00000103 00c3e17b 00c3e17b 00c3e17b +-qNaN ffc00000 00000000 a5c3e100 a5c3e100 a5c3e100 +-qNaN ffc00000 00000001 a5c3007b a5c3007b a5c3007b +-qNaN ffc00000 00000002 a500e17b a500e17b a500e17b +-qNaN ffc00000 00000003 00c3e17b 00c3e17b 00c3e17b +-qNaN ffc00000 fffffffd a5c3007b a5c3007b a5c3007b +-qNaN ffc00000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-qNaN ffc00000 80000002 a500e17b a500e17b a500e17b +-qNaN ffc00000 00000103 00c3e17b 00c3e17b 00c3e17b +sNaN 7fa00000 00000000 a5c3e100 a5c3e100 a5c3e100 +sNaN 7fa00000 00000001 a5c3007b a5c3007b a5c3007b +sNaN 7fa00000 00000002 a500e17b a500e17b a500e17b +sNaN 7fa00000 00000003 00c3e17b 00c3e17b 00c3e17b +sNaN 7fa00000 fffffffd a5c3007b a5c3007b a5c3007b +sNaN 7fa00000 fffffffc a5c3e100 a5c3e100 a5c3e100 +sNaN 7fa00000 80000002 a500e17b a500e17b a500e17b +sNaN 7fa00000 00000103 00c3e17b 00c3e17b 00c3e17b +-sNaN ffa00000 00000000 a5c3e100 a5c3e100 a5c3e100 +-sNaN ffa00000 00000001 a5c3007b a5c3007b a5c3007b +-sNaN ffa00000 00000002 a500e17b a500e17b a500e17b +-sNaN ffa00000 00000003 00c3e17b 00c3e17b 00c3e17b +-sNaN ffa00000 fffffffd a5c3007b a5c3007b a5c3007b +-sNaN ffa00000 fffffffc a5c3e100 a5c3e100 a5c3e100 +-sNaN ffa00000 80000002 a500e17b a500e17b a500e17b +-sNaN ffa00000 00000103 00c3e17b 00c3e17b 00c3e17b +qNaN+payload 7fc00001 00000000 a5c3e100 a5c3e100 a5c3e100 +qNaN+payload 7fc00001 00000001 a5c3007b a5c3007b a5c3007b +qNaN+payload 7fc00001 00000002 a500e17b a500e17b a500e17b +qNaN+payload 7fc00001 00000003 00c3e17b 00c3e17b 00c3e17b +qNaN+payload 7fc00001 fffffffd a5c3007b a5c3007b a5c3007b +qNaN+payload 7fc00001 fffffffc a5c3e100 a5c3e100 a5c3e100 +qNaN+payload 7fc00001 80000002 a500e17b a500e17b a500e17b +qNaN+payload 7fc00001 00000103 00c3e17b 00c3e17b 00c3e17b +sNaN+1 7f800001 00000000 a5c3e100 a5c3e100 a5c3e100 +sNaN+1 7f800001 00000001 a5c3007b a5c3007b a5c3007b +sNaN+1 7f800001 00000002 a500e17b a500e17b a500e17b +sNaN+1 7f800001 00000003 00c3e17b 00c3e17b 00c3e17b +sNaN+1 7f800001 fffffffd a5c3007b a5c3007b a5c3007b +sNaN+1 7f800001 fffffffc a5c3e100 a5c3e100 a5c3e100 +sNaN+1 7f800001 80000002 a500e17b a500e17b a500e17b +sNaN+1 7f800001 00000103 00c3e17b 00c3e17b 00c3e17b +NaN-all-ones 7fffffff 00000000 a5c3e100 a5c3e100 a5c3e100 +NaN-all-ones 7fffffff 00000001 a5c3007b a5c3007b a5c3007b +NaN-all-ones 7fffffff 00000002 a500e17b a500e17b a500e17b +NaN-all-ones 7fffffff 00000003 00c3e17b 00c3e17b 00c3e17b +NaN-all-ones 7fffffff fffffffd a5c3007b a5c3007b a5c3007b +NaN-all-ones 7fffffff fffffffc a5c3e100 a5c3e100 a5c3e100 +NaN-all-ones 7fffffff 80000002 a500e17b a500e17b a500e17b +NaN-all-ones 7fffffff 00000103 00c3e17b 00c3e17b 00c3e17b +-NaN-all-ones ffffffff 00000000 a5c3e100 a5c3e100 a5c3e100 +-NaN-all-ones ffffffff 00000001 a5c3007b a5c3007b a5c3007b +-NaN-all-ones ffffffff 00000002 a500e17b a500e17b a500e17b +-NaN-all-ones ffffffff 00000003 00c3e17b 00c3e17b 00c3e17b +-NaN-all-ones ffffffff fffffffd a5c3007b a5c3007b a5c3007b +-NaN-all-ones ffffffff fffffffc a5c3e100 a5c3e100 a5c3e100 +-NaN-all-ones ffffffff 80000002 a500e17b a500e17b a500e17b +-NaN-all-ones ffffffff 00000103 00c3e17b 00c3e17b 00c3e17b +qNaN-low-payload-ff 7fc000ff 00000000 a5c3e100 a5c3e100 a5c3e100 +qNaN-low-payload-ff 7fc000ff 00000001 a5c3007b a5c3007b a5c3007b +qNaN-low-payload-ff 7fc000ff 00000002 a500e17b a500e17b a500e17b +qNaN-low-payload-ff 7fc000ff 00000003 00c3e17b 00c3e17b 00c3e17b +qNaN-low-payload-ff 7fc000ff fffffffd a5c3007b a5c3007b a5c3007b +qNaN-low-payload-ff 7fc000ff fffffffc a5c3e100 a5c3e100 a5c3e100 +qNaN-low-payload-ff 7fc000ff 80000002 a500e17b a500e17b a500e17b +qNaN-low-payload-ff 7fc000ff 00000103 00c3e17b 00c3e17b 00c3e17b +min-subnormal 00000001 00000000 a5c3e100 a5c3e100 a5c3e100 +min-subnormal 00000001 00000001 a5c3007b a5c3007b a5c3007b +min-subnormal 00000001 00000002 a500e17b a500e17b a500e17b +min-subnormal 00000001 00000003 00c3e17b 00c3e17b 00c3e17b +min-subnormal 00000001 fffffffd a5c3007b a5c3007b a5c3007b +min-subnormal 00000001 fffffffc a5c3e100 a5c3e100 a5c3e100 +min-subnormal 00000001 80000002 a500e17b a500e17b a500e17b +min-subnormal 00000001 00000103 00c3e17b 00c3e17b 00c3e17b +-min-subnormal 80000001 00000000 a5c3e100 a5c3e100 a5c3e100 +-min-subnormal 80000001 00000001 a5c3007b a5c3007b a5c3007b +-min-subnormal 80000001 00000002 a500e17b a500e17b a500e17b +-min-subnormal 80000001 00000003 00c3e17b 00c3e17b 00c3e17b +-min-subnormal 80000001 fffffffd a5c3007b a5c3007b a5c3007b +-min-subnormal 80000001 fffffffc a5c3e100 a5c3e100 a5c3e100 +-min-subnormal 80000001 80000002 a500e17b a500e17b a500e17b +-min-subnormal 80000001 00000103 00c3e17b 00c3e17b 00c3e17b +max-subnormal 007fffff 00000000 a5c3e100 a5c3e100 a5c3e100 +max-subnormal 007fffff 00000001 a5c3007b a5c3007b a5c3007b +max-subnormal 007fffff 00000002 a500e17b a500e17b a500e17b +max-subnormal 007fffff 00000003 00c3e17b 00c3e17b 00c3e17b +max-subnormal 007fffff fffffffd a5c3007b a5c3007b a5c3007b +max-subnormal 007fffff fffffffc a5c3e100 a5c3e100 a5c3e100 +max-subnormal 007fffff 80000002 a500e17b a500e17b a500e17b +max-subnormal 007fffff 00000103 00c3e17b 00c3e17b 00c3e17b +min-normal 00800000 00000000 a5c3e100 a5c3e100 a5c3e100 +min-normal 00800000 00000001 a5c3007b a5c3007b a5c3007b +min-normal 00800000 00000002 a500e17b a500e17b a500e17b +min-normal 00800000 00000003 00c3e17b 00c3e17b 00c3e17b +min-normal 00800000 fffffffd a5c3007b a5c3007b a5c3007b +min-normal 00800000 fffffffc a5c3e100 a5c3e100 a5c3e100 +min-normal 00800000 80000002 a500e17b a500e17b a500e17b +min-normal 00800000 00000103 00c3e17b 00c3e17b 00c3e17b +max-float 7f7fffff 00000000 a5c3e1ff a5c3e1ff a5c3e1ff +max-float 7f7fffff 00000001 a5c3ff7b a5c3ff7b a5c3ff7b +max-float 7f7fffff 00000002 a5ffe17b a5ffe17b a5ffe17b +max-float 7f7fffff 00000003 ffc3e17b ffc3e17b ffc3e17b +max-float 7f7fffff fffffffd a5c3ff7b a5c3ff7b a5c3ff7b +max-float 7f7fffff fffffffc a5c3e1ff a5c3e1ff a5c3e1ff +max-float 7f7fffff 80000002 a5ffe17b a5ffe17b a5ffe17b +max-float 7f7fffff 00000103 ffc3e17b ffc3e17b ffc3e17b +-max-float ff7fffff 00000000 a5c3e100 a5c3e100 a5c3e100 +-max-float ff7fffff 00000001 a5c3007b a5c3007b a5c3007b +-max-float ff7fffff 00000002 a500e17b a500e17b a500e17b +-max-float ff7fffff 00000003 00c3e17b 00c3e17b 00c3e17b +-max-float ff7fffff fffffffd a5c3007b a5c3007b a5c3007b +-max-float ff7fffff fffffffc a5c3e100 a5c3e100 a5c3e100 +-max-float ff7fffff 80000002 a500e17b a500e17b a500e17b +-max-float ff7fffff 00000103 00c3e17b 00c3e17b 00c3e17b +(17/255)*255 41880000 00000000 a5c3e111 a5c3e111 a5c3e111 +(17/255)*255 41880000 00000001 a5c3117b a5c3117b a5c3117b +(17/255)*255 41880000 00000002 a511e17b a511e17b a511e17b +(17/255)*255 41880000 00000003 11c3e17b 11c3e17b 11c3e17b +(17/255)*255 41880000 fffffffd a5c3117b a5c3117b a5c3117b +(17/255)*255 41880000 fffffffc a5c3e111 a5c3e111 a5c3e111 +(17/255)*255 41880000 80000002 a511e17b a511e17b a511e17b +(17/255)*255 41880000 00000103 11c3e17b 11c3e17b 11c3e17b +(18/255)*255 41900000 00000000 a5c3e112 a5c3e112 a5c3e112 +(18/255)*255 41900000 00000001 a5c3127b a5c3127b a5c3127b +(18/255)*255 41900000 00000002 a512e17b a512e17b a512e17b +(18/255)*255 41900000 00000003 12c3e17b 12c3e17b 12c3e17b +(18/255)*255 41900000 fffffffd a5c3127b a5c3127b a5c3127b +(18/255)*255 41900000 fffffffc a5c3e112 a5c3e112 a5c3e112 +(18/255)*255 41900000 80000002 a512e17b a512e17b a512e17b +(18/255)*255 41900000 00000103 12c3e17b 12c3e17b 12c3e17b +(19/255)*255 41980000 00000000 a5c3e113 a5c3e113 a5c3e113 +(19/255)*255 41980000 00000001 a5c3137b a5c3137b a5c3137b +(19/255)*255 41980000 00000002 a513e17b a513e17b a513e17b +(19/255)*255 41980000 00000003 13c3e17b 13c3e17b 13c3e17b +(19/255)*255 41980000 fffffffd a5c3137b a5c3137b a5c3137b +(19/255)*255 41980000 fffffffc a5c3e113 a5c3e113 a5c3e113 +(19/255)*255 41980000 80000002 a513e17b a513e17b a513e17b +(19/255)*255 41980000 00000103 13c3e17b 13c3e17b 13c3e17b +(20/255)*255 41a00000 00000000 a5c3e114 a5c3e114 a5c3e114 +(20/255)*255 41a00000 00000001 a5c3147b a5c3147b a5c3147b +(20/255)*255 41a00000 00000002 a514e17b a514e17b a514e17b +(20/255)*255 41a00000 00000003 14c3e17b 14c3e17b 14c3e17b +(20/255)*255 41a00000 fffffffd a5c3147b a5c3147b a5c3147b +(20/255)*255 41a00000 fffffffc a5c3e114 a5c3e114 a5c3e114 +(20/255)*255 41a00000 80000002 a514e17b a514e17b a514e17b +(20/255)*255 41a00000 00000103 14c3e17b 14c3e17b 14c3e17b +(21/255)*255 41a80000 00000000 a5c3e115 a5c3e115 a5c3e115 +(21/255)*255 41a80000 00000001 a5c3157b a5c3157b a5c3157b +(21/255)*255 41a80000 00000002 a515e17b a515e17b a515e17b +(21/255)*255 41a80000 00000003 15c3e17b 15c3e17b 15c3e17b +(21/255)*255 41a80000 fffffffd a5c3157b a5c3157b a5c3157b +(21/255)*255 41a80000 fffffffc a5c3e115 a5c3e115 a5c3e115 +(21/255)*255 41a80000 80000002 a515e17b a515e17b a515e17b +(21/255)*255 41a80000 00000103 15c3e17b 15c3e17b 15c3e17b +(22/255)*255 41b00000 00000000 a5c3e116 a5c3e116 a5c3e116 +(22/255)*255 41b00000 00000001 a5c3167b a5c3167b a5c3167b +(22/255)*255 41b00000 00000002 a516e17b a516e17b a516e17b +(22/255)*255 41b00000 00000003 16c3e17b 16c3e17b 16c3e17b +(22/255)*255 41b00000 fffffffd a5c3167b a5c3167b a5c3167b +(22/255)*255 41b00000 fffffffc a5c3e116 a5c3e116 a5c3e116 +(22/255)*255 41b00000 80000002 a516e17b a516e17b a516e17b +(22/255)*255 41b00000 00000103 16c3e17b 16c3e17b 16c3e17b +(23/255)*255 41b80000 00000000 a5c3e117 a5c3e117 a5c3e117 +(23/255)*255 41b80000 00000001 a5c3177b a5c3177b a5c3177b +(23/255)*255 41b80000 00000002 a517e17b a517e17b a517e17b +(23/255)*255 41b80000 00000003 17c3e17b 17c3e17b 17c3e17b +(23/255)*255 41b80000 fffffffd a5c3177b a5c3177b a5c3177b +(23/255)*255 41b80000 fffffffc a5c3e117 a5c3e117 a5c3e117 +(23/255)*255 41b80000 80000002 a517e17b a517e17b a517e17b +(23/255)*255 41b80000 00000103 17c3e17b 17c3e17b 17c3e17b +(24/255)*255 41c00000 00000000 a5c3e118 a5c3e118 a5c3e118 +(24/255)*255 41c00000 00000001 a5c3187b a5c3187b a5c3187b +(24/255)*255 41c00000 00000002 a518e17b a518e17b a518e17b +(24/255)*255 41c00000 00000003 18c3e17b 18c3e17b 18c3e17b +(24/255)*255 41c00000 fffffffd a5c3187b a5c3187b a5c3187b +(24/255)*255 41c00000 fffffffc a5c3e118 a5c3e118 a5c3e118 +(24/255)*255 41c00000 80000002 a518e17b a518e17b a518e17b +(24/255)*255 41c00000 00000103 18c3e17b 18c3e17b 18c3e17b +(25/255)*255 41c80000 00000000 a5c3e119 a5c3e119 a5c3e119 +(25/255)*255 41c80000 00000001 a5c3197b a5c3197b a5c3197b +(25/255)*255 41c80000 00000002 a519e17b a519e17b a519e17b +(25/255)*255 41c80000 00000003 19c3e17b 19c3e17b 19c3e17b +(25/255)*255 41c80000 fffffffd a5c3197b a5c3197b a5c3197b +(25/255)*255 41c80000 fffffffc a5c3e119 a5c3e119 a5c3e119 +(25/255)*255 41c80000 80000002 a519e17b a519e17b a519e17b +(25/255)*255 41c80000 00000103 19c3e17b 19c3e17b 19c3e17b +(26/255)*255 41d00000 00000000 a5c3e11a a5c3e11a a5c3e11a +(26/255)*255 41d00000 00000001 a5c31a7b a5c31a7b a5c31a7b +(26/255)*255 41d00000 00000002 a51ae17b a51ae17b a51ae17b +(26/255)*255 41d00000 00000003 1ac3e17b 1ac3e17b 1ac3e17b +(26/255)*255 41d00000 fffffffd a5c31a7b a5c31a7b a5c31a7b +(26/255)*255 41d00000 fffffffc a5c3e11a a5c3e11a a5c3e11a +(26/255)*255 41d00000 80000002 a51ae17b a51ae17b a51ae17b +(26/255)*255 41d00000 00000103 1ac3e17b 1ac3e17b 1ac3e17b +(27/255)*255 41d80000 00000000 a5c3e11b a5c3e11b a5c3e11b +(27/255)*255 41d80000 00000001 a5c31b7b a5c31b7b a5c31b7b +(27/255)*255 41d80000 00000002 a51be17b a51be17b a51be17b +(27/255)*255 41d80000 00000003 1bc3e17b 1bc3e17b 1bc3e17b +(27/255)*255 41d80000 fffffffd a5c31b7b a5c31b7b a5c31b7b +(27/255)*255 41d80000 fffffffc a5c3e11b a5c3e11b a5c3e11b +(27/255)*255 41d80000 80000002 a51be17b a51be17b a51be17b +(27/255)*255 41d80000 00000103 1bc3e17b 1bc3e17b 1bc3e17b +(28/255)*255 41e00000 00000000 a5c3e11c a5c3e11c a5c3e11c +(28/255)*255 41e00000 00000001 a5c31c7b a5c31c7b a5c31c7b +(28/255)*255 41e00000 00000002 a51ce17b a51ce17b a51ce17b +(28/255)*255 41e00000 00000003 1cc3e17b 1cc3e17b 1cc3e17b +(28/255)*255 41e00000 fffffffd a5c31c7b a5c31c7b a5c31c7b +(28/255)*255 41e00000 fffffffc a5c3e11c a5c3e11c a5c3e11c +(28/255)*255 41e00000 80000002 a51ce17b a51ce17b a51ce17b +(28/255)*255 41e00000 00000103 1cc3e17b 1cc3e17b 1cc3e17b +(29/255)*255 41e80000 00000000 a5c3e11d a5c3e11d a5c3e11d +(29/255)*255 41e80000 00000001 a5c31d7b a5c31d7b a5c31d7b +(29/255)*255 41e80000 00000002 a51de17b a51de17b a51de17b +(29/255)*255 41e80000 00000003 1dc3e17b 1dc3e17b 1dc3e17b +(29/255)*255 41e80000 fffffffd a5c31d7b a5c31d7b a5c31d7b +(29/255)*255 41e80000 fffffffc a5c3e11d a5c3e11d a5c3e11d +(29/255)*255 41e80000 80000002 a51de17b a51de17b a51de17b +(29/255)*255 41e80000 00000103 1dc3e17b 1dc3e17b 1dc3e17b +(30/255)*255 41f00000 00000000 a5c3e11e a5c3e11e a5c3e11e +(30/255)*255 41f00000 00000001 a5c31e7b a5c31e7b a5c31e7b +(30/255)*255 41f00000 00000002 a51ee17b a51ee17b a51ee17b +(30/255)*255 41f00000 00000003 1ec3e17b 1ec3e17b 1ec3e17b +(30/255)*255 41f00000 fffffffd a5c31e7b a5c31e7b a5c31e7b +(30/255)*255 41f00000 fffffffc a5c3e11e a5c3e11e a5c3e11e +(30/255)*255 41f00000 80000002 a51ee17b a51ee17b a51ee17b +(30/255)*255 41f00000 00000103 1ec3e17b 1ec3e17b 1ec3e17b +(33/255)*255 42040000 00000000 a5c3e121 a5c3e121 a5c3e121 +(33/255)*255 42040000 00000001 a5c3217b a5c3217b a5c3217b +(33/255)*255 42040000 00000002 a521e17b a521e17b a521e17b +(33/255)*255 42040000 00000003 21c3e17b 21c3e17b 21c3e17b +(33/255)*255 42040000 fffffffd a5c3217b a5c3217b a5c3217b +(33/255)*255 42040000 fffffffc a5c3e121 a5c3e121 a5c3e121 +(33/255)*255 42040000 80000002 a521e17b a521e17b a521e17b +(33/255)*255 42040000 00000103 21c3e17b 21c3e17b 21c3e17b +(34/255)*255 42080000 00000000 a5c3e122 a5c3e122 a5c3e122 +(34/255)*255 42080000 00000001 a5c3227b a5c3227b a5c3227b +(34/255)*255 42080000 00000002 a522e17b a522e17b a522e17b +(34/255)*255 42080000 00000003 22c3e17b 22c3e17b 22c3e17b +(34/255)*255 42080000 fffffffd a5c3227b a5c3227b a5c3227b +(34/255)*255 42080000 fffffffc a5c3e122 a5c3e122 a5c3e122 +(34/255)*255 42080000 80000002 a522e17b a522e17b a522e17b +(34/255)*255 42080000 00000103 22c3e17b 22c3e17b 22c3e17b +(35/255)*255 420c0000 00000000 a5c3e123 a5c3e123 a5c3e123 +(35/255)*255 420c0000 00000001 a5c3237b a5c3237b a5c3237b +(35/255)*255 420c0000 00000002 a523e17b a523e17b a523e17b +(35/255)*255 420c0000 00000003 23c3e17b 23c3e17b 23c3e17b +(35/255)*255 420c0000 fffffffd a5c3237b a5c3237b a5c3237b +(35/255)*255 420c0000 fffffffc a5c3e123 a5c3e123 a5c3e123 +(35/255)*255 420c0000 80000002 a523e17b a523e17b a523e17b +(35/255)*255 420c0000 00000103 23c3e17b 23c3e17b 23c3e17b +(36/255)*255 42100000 00000000 a5c3e124 a5c3e124 a5c3e124 +(36/255)*255 42100000 00000001 a5c3247b a5c3247b a5c3247b +(36/255)*255 42100000 00000002 a524e17b a524e17b a524e17b +(36/255)*255 42100000 00000003 24c3e17b 24c3e17b 24c3e17b +(36/255)*255 42100000 fffffffd a5c3247b a5c3247b a5c3247b +(36/255)*255 42100000 fffffffc a5c3e124 a5c3e124 a5c3e124 +(36/255)*255 42100000 80000002 a524e17b a524e17b a524e17b +(36/255)*255 42100000 00000103 24c3e17b 24c3e17b 24c3e17b +(37/255)*255 42140000 00000000 a5c3e125 a5c3e125 a5c3e125 +(37/255)*255 42140000 00000001 a5c3257b a5c3257b a5c3257b +(37/255)*255 42140000 00000002 a525e17b a525e17b a525e17b +(37/255)*255 42140000 00000003 25c3e17b 25c3e17b 25c3e17b +(37/255)*255 42140000 fffffffd a5c3257b a5c3257b a5c3257b +(37/255)*255 42140000 fffffffc a5c3e125 a5c3e125 a5c3e125 +(37/255)*255 42140000 80000002 a525e17b a525e17b a525e17b +(37/255)*255 42140000 00000103 25c3e17b 25c3e17b 25c3e17b +(38/255)*255 42180000 00000000 a5c3e126 a5c3e126 a5c3e126 +(38/255)*255 42180000 00000001 a5c3267b a5c3267b a5c3267b +(38/255)*255 42180000 00000002 a526e17b a526e17b a526e17b +(38/255)*255 42180000 00000003 26c3e17b 26c3e17b 26c3e17b +(38/255)*255 42180000 fffffffd a5c3267b a5c3267b a5c3267b +(38/255)*255 42180000 fffffffc a5c3e126 a5c3e126 a5c3e126 +(38/255)*255 42180000 80000002 a526e17b a526e17b a526e17b +(38/255)*255 42180000 00000103 26c3e17b 26c3e17b 26c3e17b +(39/255)*255 421c0000 00000000 a5c3e127 a5c3e127 a5c3e127 +(39/255)*255 421c0000 00000001 a5c3277b a5c3277b a5c3277b +(39/255)*255 421c0000 00000002 a527e17b a527e17b a527e17b +(39/255)*255 421c0000 00000003 27c3e17b 27c3e17b 27c3e17b +(39/255)*255 421c0000 fffffffd a5c3277b a5c3277b a5c3277b +(39/255)*255 421c0000 fffffffc a5c3e127 a5c3e127 a5c3e127 +(39/255)*255 421c0000 80000002 a527e17b a527e17b a527e17b +(39/255)*255 421c0000 00000103 27c3e17b 27c3e17b 27c3e17b +(40/255)*255 42200000 00000000 a5c3e128 a5c3e128 a5c3e128 +(40/255)*255 42200000 00000001 a5c3287b a5c3287b a5c3287b +(40/255)*255 42200000 00000002 a528e17b a528e17b a528e17b +(40/255)*255 42200000 00000003 28c3e17b 28c3e17b 28c3e17b +(40/255)*255 42200000 fffffffd a5c3287b a5c3287b a5c3287b +(40/255)*255 42200000 fffffffc a5c3e128 a5c3e128 a5c3e128 +(40/255)*255 42200000 80000002 a528e17b a528e17b a528e17b +(40/255)*255 42200000 00000103 28c3e17b 28c3e17b 28c3e17b +(41/255)*255 42240000 00000000 a5c3e129 a5c3e129 a5c3e129 +(41/255)*255 42240000 00000001 a5c3297b a5c3297b a5c3297b +(41/255)*255 42240000 00000002 a529e17b a529e17b a529e17b +(41/255)*255 42240000 00000003 29c3e17b 29c3e17b 29c3e17b +(41/255)*255 42240000 fffffffd a5c3297b a5c3297b a5c3297b +(41/255)*255 42240000 fffffffc a5c3e129 a5c3e129 a5c3e129 +(41/255)*255 42240000 80000002 a529e17b a529e17b a529e17b +(41/255)*255 42240000 00000103 29c3e17b 29c3e17b 29c3e17b +(42/255)*255 42280000 00000000 a5c3e12a a5c3e12a a5c3e12a +(42/255)*255 42280000 00000001 a5c32a7b a5c32a7b a5c32a7b +(42/255)*255 42280000 00000002 a52ae17b a52ae17b a52ae17b +(42/255)*255 42280000 00000003 2ac3e17b 2ac3e17b 2ac3e17b +(42/255)*255 42280000 fffffffd a5c32a7b a5c32a7b a5c32a7b +(42/255)*255 42280000 fffffffc a5c3e12a a5c3e12a a5c3e12a +(42/255)*255 42280000 80000002 a52ae17b a52ae17b a52ae17b +(42/255)*255 42280000 00000103 2ac3e17b 2ac3e17b 2ac3e17b +(43/255)*255 422c0000 00000000 a5c3e12b a5c3e12b a5c3e12b +(43/255)*255 422c0000 00000001 a5c32b7b a5c32b7b a5c32b7b +(43/255)*255 422c0000 00000002 a52be17b a52be17b a52be17b +(43/255)*255 422c0000 00000003 2bc3e17b 2bc3e17b 2bc3e17b +(43/255)*255 422c0000 fffffffd a5c32b7b a5c32b7b a5c32b7b +(43/255)*255 422c0000 fffffffc a5c3e12b a5c3e12b a5c3e12b +(43/255)*255 422c0000 80000002 a52be17b a52be17b a52be17b +(43/255)*255 422c0000 00000103 2bc3e17b 2bc3e17b 2bc3e17b +(44/255)*255 42300000 00000000 a5c3e12c a5c3e12c a5c3e12c +(44/255)*255 42300000 00000001 a5c32c7b a5c32c7b a5c32c7b +(44/255)*255 42300000 00000002 a52ce17b a52ce17b a52ce17b +(44/255)*255 42300000 00000003 2cc3e17b 2cc3e17b 2cc3e17b +(44/255)*255 42300000 fffffffd a5c32c7b a5c32c7b a5c32c7b +(44/255)*255 42300000 fffffffc a5c3e12c a5c3e12c a5c3e12c +(44/255)*255 42300000 80000002 a52ce17b a52ce17b a52ce17b +(44/255)*255 42300000 00000103 2cc3e17b 2cc3e17b 2cc3e17b +(45/255)*255 42340000 00000000 a5c3e12d a5c3e12d a5c3e12d +(45/255)*255 42340000 00000001 a5c32d7b a5c32d7b a5c32d7b +(45/255)*255 42340000 00000002 a52de17b a52de17b a52de17b +(45/255)*255 42340000 00000003 2dc3e17b 2dc3e17b 2dc3e17b +(45/255)*255 42340000 fffffffd a5c32d7b a5c32d7b a5c32d7b +(45/255)*255 42340000 fffffffc a5c3e12d a5c3e12d a5c3e12d +(45/255)*255 42340000 80000002 a52de17b a52de17b a52de17b +(45/255)*255 42340000 00000103 2dc3e17b 2dc3e17b 2dc3e17b +(46/255)*255 42380000 00000000 a5c3e12e a5c3e12e a5c3e12e +(46/255)*255 42380000 00000001 a5c32e7b a5c32e7b a5c32e7b +(46/255)*255 42380000 00000002 a52ee17b a52ee17b a52ee17b +(46/255)*255 42380000 00000003 2ec3e17b 2ec3e17b 2ec3e17b +(46/255)*255 42380000 fffffffd a5c32e7b a5c32e7b a5c32e7b +(46/255)*255 42380000 fffffffc a5c3e12e a5c3e12e a5c3e12e +(46/255)*255 42380000 80000002 a52ee17b a52ee17b a52ee17b +(46/255)*255 42380000 00000103 2ec3e17b 2ec3e17b 2ec3e17b +(47/255)*255 423c0000 00000000 a5c3e12f a5c3e12f a5c3e12f +(47/255)*255 423c0000 00000001 a5c32f7b a5c32f7b a5c32f7b +(47/255)*255 423c0000 00000002 a52fe17b a52fe17b a52fe17b +(47/255)*255 423c0000 00000003 2fc3e17b 2fc3e17b 2fc3e17b +(47/255)*255 423c0000 fffffffd a5c32f7b a5c32f7b a5c32f7b +(47/255)*255 423c0000 fffffffc a5c3e12f a5c3e12f a5c3e12f +(47/255)*255 423c0000 80000002 a52fe17b a52fe17b a52fe17b +(47/255)*255 423c0000 00000103 2fc3e17b 2fc3e17b 2fc3e17b +(48/255)*255 42400000 00000000 a5c3e130 a5c3e130 a5c3e130 +(48/255)*255 42400000 00000001 a5c3307b a5c3307b a5c3307b +(48/255)*255 42400000 00000002 a530e17b a530e17b a530e17b +(48/255)*255 42400000 00000003 30c3e17b 30c3e17b 30c3e17b +(48/255)*255 42400000 fffffffd a5c3307b a5c3307b a5c3307b +(48/255)*255 42400000 fffffffc a5c3e130 a5c3e130 a5c3e130 +(48/255)*255 42400000 80000002 a530e17b a530e17b a530e17b +(48/255)*255 42400000 00000103 30c3e17b 30c3e17b 30c3e17b +(49/255)*255 42440000 00000000 a5c3e131 a5c3e131 a5c3e131 +(49/255)*255 42440000 00000001 a5c3317b a5c3317b a5c3317b +(49/255)*255 42440000 00000002 a531e17b a531e17b a531e17b +(49/255)*255 42440000 00000003 31c3e17b 31c3e17b 31c3e17b +(49/255)*255 42440000 fffffffd a5c3317b a5c3317b a5c3317b +(49/255)*255 42440000 fffffffc a5c3e131 a5c3e131 a5c3e131 +(49/255)*255 42440000 80000002 a531e17b a531e17b a531e17b +(49/255)*255 42440000 00000103 31c3e17b 31c3e17b 31c3e17b +(50/255)*255 42480000 00000000 a5c3e132 a5c3e132 a5c3e132 +(50/255)*255 42480000 00000001 a5c3327b a5c3327b a5c3327b +(50/255)*255 42480000 00000002 a532e17b a532e17b a532e17b +(50/255)*255 42480000 00000003 32c3e17b 32c3e17b 32c3e17b +(50/255)*255 42480000 fffffffd a5c3327b a5c3327b a5c3327b +(50/255)*255 42480000 fffffffc a5c3e132 a5c3e132 a5c3e132 +(50/255)*255 42480000 80000002 a532e17b a532e17b a532e17b +(50/255)*255 42480000 00000103 32c3e17b 32c3e17b 32c3e17b +(51/255)*255 424c0000 00000000 a5c3e133 a5c3e133 a5c3e133 +(51/255)*255 424c0000 00000001 a5c3337b a5c3337b a5c3337b +(51/255)*255 424c0000 00000002 a533e17b a533e17b a533e17b +(51/255)*255 424c0000 00000003 33c3e17b 33c3e17b 33c3e17b +(51/255)*255 424c0000 fffffffd a5c3337b a5c3337b a5c3337b +(51/255)*255 424c0000 fffffffc a5c3e133 a5c3e133 a5c3e133 +(51/255)*255 424c0000 80000002 a533e17b a533e17b a533e17b +(51/255)*255 424c0000 00000103 33c3e17b 33c3e17b 33c3e17b +(52/255)*255 42500000 00000000 a5c3e134 a5c3e134 a5c3e134 +(52/255)*255 42500000 00000001 a5c3347b a5c3347b a5c3347b +(52/255)*255 42500000 00000002 a534e17b a534e17b a534e17b +(52/255)*255 42500000 00000003 34c3e17b 34c3e17b 34c3e17b +(52/255)*255 42500000 fffffffd a5c3347b a5c3347b a5c3347b +(52/255)*255 42500000 fffffffc a5c3e134 a5c3e134 a5c3e134 +(52/255)*255 42500000 80000002 a534e17b a534e17b a534e17b +(52/255)*255 42500000 00000103 34c3e17b 34c3e17b 34c3e17b +(53/255)*255 42540000 00000000 a5c3e135 a5c3e135 a5c3e135 +(53/255)*255 42540000 00000001 a5c3357b a5c3357b a5c3357b +(53/255)*255 42540000 00000002 a535e17b a535e17b a535e17b +(53/255)*255 42540000 00000003 35c3e17b 35c3e17b 35c3e17b +(53/255)*255 42540000 fffffffd a5c3357b a5c3357b a5c3357b +(53/255)*255 42540000 fffffffc a5c3e135 a5c3e135 a5c3e135 +(53/255)*255 42540000 80000002 a535e17b a535e17b a535e17b +(53/255)*255 42540000 00000103 35c3e17b 35c3e17b 35c3e17b +(54/255)*255 42580000 00000000 a5c3e136 a5c3e136 a5c3e136 +(54/255)*255 42580000 00000001 a5c3367b a5c3367b a5c3367b +(54/255)*255 42580000 00000002 a536e17b a536e17b a536e17b +(54/255)*255 42580000 00000003 36c3e17b 36c3e17b 36c3e17b +(54/255)*255 42580000 fffffffd a5c3367b a5c3367b a5c3367b +(54/255)*255 42580000 fffffffc a5c3e136 a5c3e136 a5c3e136 +(54/255)*255 42580000 80000002 a536e17b a536e17b a536e17b +(54/255)*255 42580000 00000103 36c3e17b 36c3e17b 36c3e17b +(55/255)*255 425c0000 00000000 a5c3e137 a5c3e137 a5c3e137 +(55/255)*255 425c0000 00000001 a5c3377b a5c3377b a5c3377b +(55/255)*255 425c0000 00000002 a537e17b a537e17b a537e17b +(55/255)*255 425c0000 00000003 37c3e17b 37c3e17b 37c3e17b +(55/255)*255 425c0000 fffffffd a5c3377b a5c3377b a5c3377b +(55/255)*255 425c0000 fffffffc a5c3e137 a5c3e137 a5c3e137 +(55/255)*255 425c0000 80000002 a537e17b a537e17b a537e17b +(55/255)*255 425c0000 00000103 37c3e17b 37c3e17b 37c3e17b +(56/255)*255 42600000 00000000 a5c3e138 a5c3e138 a5c3e138 +(56/255)*255 42600000 00000001 a5c3387b a5c3387b a5c3387b +(56/255)*255 42600000 00000002 a538e17b a538e17b a538e17b +(56/255)*255 42600000 00000003 38c3e17b 38c3e17b 38c3e17b +(56/255)*255 42600000 fffffffd a5c3387b a5c3387b a5c3387b +(56/255)*255 42600000 fffffffc a5c3e138 a5c3e138 a5c3e138 +(56/255)*255 42600000 80000002 a538e17b a538e17b a538e17b +(56/255)*255 42600000 00000103 38c3e17b 38c3e17b 38c3e17b +(57/255)*255 42640000 00000000 a5c3e139 a5c3e139 a5c3e139 +(57/255)*255 42640000 00000001 a5c3397b a5c3397b a5c3397b +(57/255)*255 42640000 00000002 a539e17b a539e17b a539e17b +(57/255)*255 42640000 00000003 39c3e17b 39c3e17b 39c3e17b +(57/255)*255 42640000 fffffffd a5c3397b a5c3397b a5c3397b +(57/255)*255 42640000 fffffffc a5c3e139 a5c3e139 a5c3e139 +(57/255)*255 42640000 80000002 a539e17b a539e17b a539e17b +(57/255)*255 42640000 00000103 39c3e17b 39c3e17b 39c3e17b +(58/255)*255 42680000 00000000 a5c3e13a a5c3e13a a5c3e13a +(58/255)*255 42680000 00000001 a5c33a7b a5c33a7b a5c33a7b +(58/255)*255 42680000 00000002 a53ae17b a53ae17b a53ae17b +(58/255)*255 42680000 00000003 3ac3e17b 3ac3e17b 3ac3e17b +(58/255)*255 42680000 fffffffd a5c33a7b a5c33a7b a5c33a7b +(58/255)*255 42680000 fffffffc a5c3e13a a5c3e13a a5c3e13a +(58/255)*255 42680000 80000002 a53ae17b a53ae17b a53ae17b +(58/255)*255 42680000 00000103 3ac3e17b 3ac3e17b 3ac3e17b +(59/255)*255 426c0000 00000000 a5c3e13b a5c3e13b a5c3e13b +(59/255)*255 426c0000 00000001 a5c33b7b a5c33b7b a5c33b7b +(59/255)*255 426c0000 00000002 a53be17b a53be17b a53be17b +(59/255)*255 426c0000 00000003 3bc3e17b 3bc3e17b 3bc3e17b +(59/255)*255 426c0000 fffffffd a5c33b7b a5c33b7b a5c33b7b +(59/255)*255 426c0000 fffffffc a5c3e13b a5c3e13b a5c3e13b +(59/255)*255 426c0000 80000002 a53be17b a53be17b a53be17b +(59/255)*255 426c0000 00000103 3bc3e17b 3bc3e17b 3bc3e17b +(60/255)*255 42700000 00000000 a5c3e13c a5c3e13c a5c3e13c +(60/255)*255 42700000 00000001 a5c33c7b a5c33c7b a5c33c7b +(60/255)*255 42700000 00000002 a53ce17b a53ce17b a53ce17b +(60/255)*255 42700000 00000003 3cc3e17b 3cc3e17b 3cc3e17b +(60/255)*255 42700000 fffffffd a5c33c7b a5c33c7b a5c33c7b +(60/255)*255 42700000 fffffffc a5c3e13c a5c3e13c a5c3e13c +(60/255)*255 42700000 80000002 a53ce17b a53ce17b a53ce17b +(60/255)*255 42700000 00000103 3cc3e17b 3cc3e17b 3cc3e17b +(61/255)*255 42740000 00000000 a5c3e13d a5c3e13d a5c3e13d +(61/255)*255 42740000 00000001 a5c33d7b a5c33d7b a5c33d7b +(61/255)*255 42740000 00000002 a53de17b a53de17b a53de17b +(61/255)*255 42740000 00000003 3dc3e17b 3dc3e17b 3dc3e17b +(61/255)*255 42740000 fffffffd a5c33d7b a5c33d7b a5c33d7b +(61/255)*255 42740000 fffffffc a5c3e13d a5c3e13d a5c3e13d +(61/255)*255 42740000 80000002 a53de17b a53de17b a53de17b +(61/255)*255 42740000 00000103 3dc3e17b 3dc3e17b 3dc3e17b +(62/255)*255 42780000 00000000 a5c3e13e a5c3e13e a5c3e13e +(62/255)*255 42780000 00000001 a5c33e7b a5c33e7b a5c33e7b +(62/255)*255 42780000 00000002 a53ee17b a53ee17b a53ee17b +(62/255)*255 42780000 00000003 3ec3e17b 3ec3e17b 3ec3e17b +(62/255)*255 42780000 fffffffd a5c33e7b a5c33e7b a5c33e7b +(62/255)*255 42780000 fffffffc a5c3e13e a5c3e13e a5c3e13e +(62/255)*255 42780000 80000002 a53ee17b a53ee17b a53ee17b +(62/255)*255 42780000 00000103 3ec3e17b 3ec3e17b 3ec3e17b +(65/255)*255 42820000 00000000 a5c3e141 a5c3e141 a5c3e141 +(65/255)*255 42820000 00000001 a5c3417b a5c3417b a5c3417b +(65/255)*255 42820000 00000002 a541e17b a541e17b a541e17b +(65/255)*255 42820000 00000003 41c3e17b 41c3e17b 41c3e17b +(65/255)*255 42820000 fffffffd a5c3417b a5c3417b a5c3417b +(65/255)*255 42820000 fffffffc a5c3e141 a5c3e141 a5c3e141 +(65/255)*255 42820000 80000002 a541e17b a541e17b a541e17b +(65/255)*255 42820000 00000103 41c3e17b 41c3e17b 41c3e17b +(66/255)*255 42840000 00000000 a5c3e142 a5c3e142 a5c3e142 +(66/255)*255 42840000 00000001 a5c3427b a5c3427b a5c3427b +(66/255)*255 42840000 00000002 a542e17b a542e17b a542e17b +(66/255)*255 42840000 00000003 42c3e17b 42c3e17b 42c3e17b +(66/255)*255 42840000 fffffffd a5c3427b a5c3427b a5c3427b +(66/255)*255 42840000 fffffffc a5c3e142 a5c3e142 a5c3e142 +(66/255)*255 42840000 80000002 a542e17b a542e17b a542e17b +(66/255)*255 42840000 00000103 42c3e17b 42c3e17b 42c3e17b +(67/255)*255 42860000 00000000 a5c3e143 a5c3e143 a5c3e143 +(67/255)*255 42860000 00000001 a5c3437b a5c3437b a5c3437b +(67/255)*255 42860000 00000002 a543e17b a543e17b a543e17b +(67/255)*255 42860000 00000003 43c3e17b 43c3e17b 43c3e17b +(67/255)*255 42860000 fffffffd a5c3437b a5c3437b a5c3437b +(67/255)*255 42860000 fffffffc a5c3e143 a5c3e143 a5c3e143 +(67/255)*255 42860000 80000002 a543e17b a543e17b a543e17b +(67/255)*255 42860000 00000103 43c3e17b 43c3e17b 43c3e17b +(68/255)*255 42880000 00000000 a5c3e144 a5c3e144 a5c3e144 +(68/255)*255 42880000 00000001 a5c3447b a5c3447b a5c3447b +(68/255)*255 42880000 00000002 a544e17b a544e17b a544e17b +(68/255)*255 42880000 00000003 44c3e17b 44c3e17b 44c3e17b +(68/255)*255 42880000 fffffffd a5c3447b a5c3447b a5c3447b +(68/255)*255 42880000 fffffffc a5c3e144 a5c3e144 a5c3e144 +(68/255)*255 42880000 80000002 a544e17b a544e17b a544e17b +(68/255)*255 42880000 00000103 44c3e17b 44c3e17b 44c3e17b +(69/255)*255 428a0000 00000000 a5c3e145 a5c3e145 a5c3e145 +(69/255)*255 428a0000 00000001 a5c3457b a5c3457b a5c3457b +(69/255)*255 428a0000 00000002 a545e17b a545e17b a545e17b +(69/255)*255 428a0000 00000003 45c3e17b 45c3e17b 45c3e17b +(69/255)*255 428a0000 fffffffd a5c3457b a5c3457b a5c3457b +(69/255)*255 428a0000 fffffffc a5c3e145 a5c3e145 a5c3e145 +(69/255)*255 428a0000 80000002 a545e17b a545e17b a545e17b +(69/255)*255 428a0000 00000103 45c3e17b 45c3e17b 45c3e17b +(70/255)*255 428c0000 00000000 a5c3e146 a5c3e146 a5c3e146 +(70/255)*255 428c0000 00000001 a5c3467b a5c3467b a5c3467b +(70/255)*255 428c0000 00000002 a546e17b a546e17b a546e17b +(70/255)*255 428c0000 00000003 46c3e17b 46c3e17b 46c3e17b +(70/255)*255 428c0000 fffffffd a5c3467b a5c3467b a5c3467b +(70/255)*255 428c0000 fffffffc a5c3e146 a5c3e146 a5c3e146 +(70/255)*255 428c0000 80000002 a546e17b a546e17b a546e17b +(70/255)*255 428c0000 00000103 46c3e17b 46c3e17b 46c3e17b +(71/255)*255 428e0000 00000000 a5c3e147 a5c3e147 a5c3e147 +(71/255)*255 428e0000 00000001 a5c3477b a5c3477b a5c3477b +(71/255)*255 428e0000 00000002 a547e17b a547e17b a547e17b +(71/255)*255 428e0000 00000003 47c3e17b 47c3e17b 47c3e17b +(71/255)*255 428e0000 fffffffd a5c3477b a5c3477b a5c3477b +(71/255)*255 428e0000 fffffffc a5c3e147 a5c3e147 a5c3e147 +(71/255)*255 428e0000 80000002 a547e17b a547e17b a547e17b +(71/255)*255 428e0000 00000103 47c3e17b 47c3e17b 47c3e17b +(72/255)*255 42900000 00000000 a5c3e148 a5c3e148 a5c3e148 +(72/255)*255 42900000 00000001 a5c3487b a5c3487b a5c3487b +(72/255)*255 42900000 00000002 a548e17b a548e17b a548e17b +(72/255)*255 42900000 00000003 48c3e17b 48c3e17b 48c3e17b +(72/255)*255 42900000 fffffffd a5c3487b a5c3487b a5c3487b +(72/255)*255 42900000 fffffffc a5c3e148 a5c3e148 a5c3e148 +(72/255)*255 42900000 80000002 a548e17b a548e17b a548e17b +(72/255)*255 42900000 00000103 48c3e17b 48c3e17b 48c3e17b +(73/255)*255 42920000 00000000 a5c3e149 a5c3e149 a5c3e149 +(73/255)*255 42920000 00000001 a5c3497b a5c3497b a5c3497b +(73/255)*255 42920000 00000002 a549e17b a549e17b a549e17b +(73/255)*255 42920000 00000003 49c3e17b 49c3e17b 49c3e17b +(73/255)*255 42920000 fffffffd a5c3497b a5c3497b a5c3497b +(73/255)*255 42920000 fffffffc a5c3e149 a5c3e149 a5c3e149 +(73/255)*255 42920000 80000002 a549e17b a549e17b a549e17b +(73/255)*255 42920000 00000103 49c3e17b 49c3e17b 49c3e17b +(74/255)*255 42940000 00000000 a5c3e14a a5c3e14a a5c3e14a +(74/255)*255 42940000 00000001 a5c34a7b a5c34a7b a5c34a7b +(74/255)*255 42940000 00000002 a54ae17b a54ae17b a54ae17b +(74/255)*255 42940000 00000003 4ac3e17b 4ac3e17b 4ac3e17b +(74/255)*255 42940000 fffffffd a5c34a7b a5c34a7b a5c34a7b +(74/255)*255 42940000 fffffffc a5c3e14a a5c3e14a a5c3e14a +(74/255)*255 42940000 80000002 a54ae17b a54ae17b a54ae17b +(74/255)*255 42940000 00000103 4ac3e17b 4ac3e17b 4ac3e17b +(75/255)*255 42960000 00000000 a5c3e14b a5c3e14b a5c3e14b +(75/255)*255 42960000 00000001 a5c34b7b a5c34b7b a5c34b7b +(75/255)*255 42960000 00000002 a54be17b a54be17b a54be17b +(75/255)*255 42960000 00000003 4bc3e17b 4bc3e17b 4bc3e17b +(75/255)*255 42960000 fffffffd a5c34b7b a5c34b7b a5c34b7b +(75/255)*255 42960000 fffffffc a5c3e14b a5c3e14b a5c3e14b +(75/255)*255 42960000 80000002 a54be17b a54be17b a54be17b +(75/255)*255 42960000 00000103 4bc3e17b 4bc3e17b 4bc3e17b +(76/255)*255 42980000 00000000 a5c3e14c a5c3e14c a5c3e14c +(76/255)*255 42980000 00000001 a5c34c7b a5c34c7b a5c34c7b +(76/255)*255 42980000 00000002 a54ce17b a54ce17b a54ce17b +(76/255)*255 42980000 00000003 4cc3e17b 4cc3e17b 4cc3e17b +(76/255)*255 42980000 fffffffd a5c34c7b a5c34c7b a5c34c7b +(76/255)*255 42980000 fffffffc a5c3e14c a5c3e14c a5c3e14c +(76/255)*255 42980000 80000002 a54ce17b a54ce17b a54ce17b +(76/255)*255 42980000 00000103 4cc3e17b 4cc3e17b 4cc3e17b +(77/255)*255 429a0000 00000000 a5c3e14d a5c3e14d a5c3e14d +(77/255)*255 429a0000 00000001 a5c34d7b a5c34d7b a5c34d7b +(77/255)*255 429a0000 00000002 a54de17b a54de17b a54de17b +(77/255)*255 429a0000 00000003 4dc3e17b 4dc3e17b 4dc3e17b +(77/255)*255 429a0000 fffffffd a5c34d7b a5c34d7b a5c34d7b +(77/255)*255 429a0000 fffffffc a5c3e14d a5c3e14d a5c3e14d +(77/255)*255 429a0000 80000002 a54de17b a54de17b a54de17b +(77/255)*255 429a0000 00000103 4dc3e17b 4dc3e17b 4dc3e17b +(78/255)*255 429c0000 00000000 a5c3e14e a5c3e14e a5c3e14e +(78/255)*255 429c0000 00000001 a5c34e7b a5c34e7b a5c34e7b +(78/255)*255 429c0000 00000002 a54ee17b a54ee17b a54ee17b +(78/255)*255 429c0000 00000003 4ec3e17b 4ec3e17b 4ec3e17b +(78/255)*255 429c0000 fffffffd a5c34e7b a5c34e7b a5c34e7b +(78/255)*255 429c0000 fffffffc a5c3e14e a5c3e14e a5c3e14e +(78/255)*255 429c0000 80000002 a54ee17b a54ee17b a54ee17b +(78/255)*255 429c0000 00000103 4ec3e17b 4ec3e17b 4ec3e17b +(79/255)*255 429e0000 00000000 a5c3e14f a5c3e14f a5c3e14f +(79/255)*255 429e0000 00000001 a5c34f7b a5c34f7b a5c34f7b +(79/255)*255 429e0000 00000002 a54fe17b a54fe17b a54fe17b +(79/255)*255 429e0000 00000003 4fc3e17b 4fc3e17b 4fc3e17b +(79/255)*255 429e0000 fffffffd a5c34f7b a5c34f7b a5c34f7b +(79/255)*255 429e0000 fffffffc a5c3e14f a5c3e14f a5c3e14f +(79/255)*255 429e0000 80000002 a54fe17b a54fe17b a54fe17b +(79/255)*255 429e0000 00000103 4fc3e17b 4fc3e17b 4fc3e17b +(80/255)*255 42a00000 00000000 a5c3e150 a5c3e150 a5c3e150 +(80/255)*255 42a00000 00000001 a5c3507b a5c3507b a5c3507b +(80/255)*255 42a00000 00000002 a550e17b a550e17b a550e17b +(80/255)*255 42a00000 00000003 50c3e17b 50c3e17b 50c3e17b +(80/255)*255 42a00000 fffffffd a5c3507b a5c3507b a5c3507b +(80/255)*255 42a00000 fffffffc a5c3e150 a5c3e150 a5c3e150 +(80/255)*255 42a00000 80000002 a550e17b a550e17b a550e17b +(80/255)*255 42a00000 00000103 50c3e17b 50c3e17b 50c3e17b +(81/255)*255 42a20000 00000000 a5c3e151 a5c3e151 a5c3e151 +(81/255)*255 42a20000 00000001 a5c3517b a5c3517b a5c3517b +(81/255)*255 42a20000 00000002 a551e17b a551e17b a551e17b +(81/255)*255 42a20000 00000003 51c3e17b 51c3e17b 51c3e17b +(81/255)*255 42a20000 fffffffd a5c3517b a5c3517b a5c3517b +(81/255)*255 42a20000 fffffffc a5c3e151 a5c3e151 a5c3e151 +(81/255)*255 42a20000 80000002 a551e17b a551e17b a551e17b +(81/255)*255 42a20000 00000103 51c3e17b 51c3e17b 51c3e17b +(82/255)*255 42a40000 00000000 a5c3e152 a5c3e152 a5c3e152 +(82/255)*255 42a40000 00000001 a5c3527b a5c3527b a5c3527b +(82/255)*255 42a40000 00000002 a552e17b a552e17b a552e17b +(82/255)*255 42a40000 00000003 52c3e17b 52c3e17b 52c3e17b +(82/255)*255 42a40000 fffffffd a5c3527b a5c3527b a5c3527b +(82/255)*255 42a40000 fffffffc a5c3e152 a5c3e152 a5c3e152 +(82/255)*255 42a40000 80000002 a552e17b a552e17b a552e17b +(82/255)*255 42a40000 00000103 52c3e17b 52c3e17b 52c3e17b +(83/255)*255 42a60000 00000000 a5c3e153 a5c3e153 a5c3e153 +(83/255)*255 42a60000 00000001 a5c3537b a5c3537b a5c3537b +(83/255)*255 42a60000 00000002 a553e17b a553e17b a553e17b +(83/255)*255 42a60000 00000003 53c3e17b 53c3e17b 53c3e17b +(83/255)*255 42a60000 fffffffd a5c3537b a5c3537b a5c3537b +(83/255)*255 42a60000 fffffffc a5c3e153 a5c3e153 a5c3e153 +(83/255)*255 42a60000 80000002 a553e17b a553e17b a553e17b +(83/255)*255 42a60000 00000103 53c3e17b 53c3e17b 53c3e17b +(84/255)*255 42a80000 00000000 a5c3e154 a5c3e154 a5c3e154 +(84/255)*255 42a80000 00000001 a5c3547b a5c3547b a5c3547b +(84/255)*255 42a80000 00000002 a554e17b a554e17b a554e17b +(84/255)*255 42a80000 00000003 54c3e17b 54c3e17b 54c3e17b +(84/255)*255 42a80000 fffffffd a5c3547b a5c3547b a5c3547b +(84/255)*255 42a80000 fffffffc a5c3e154 a5c3e154 a5c3e154 +(84/255)*255 42a80000 80000002 a554e17b a554e17b a554e17b +(84/255)*255 42a80000 00000103 54c3e17b 54c3e17b 54c3e17b +(85/255)*255 42aa0000 00000000 a5c3e155 a5c3e155 a5c3e155 +(85/255)*255 42aa0000 00000001 a5c3557b a5c3557b a5c3557b +(85/255)*255 42aa0000 00000002 a555e17b a555e17b a555e17b +(85/255)*255 42aa0000 00000003 55c3e17b 55c3e17b 55c3e17b +(85/255)*255 42aa0000 fffffffd a5c3557b a5c3557b a5c3557b +(85/255)*255 42aa0000 fffffffc a5c3e155 a5c3e155 a5c3e155 +(85/255)*255 42aa0000 80000002 a555e17b a555e17b a555e17b +(85/255)*255 42aa0000 00000103 55c3e17b 55c3e17b 55c3e17b +(86/255)*255 42ac0000 00000000 a5c3e156 a5c3e156 a5c3e156 +(86/255)*255 42ac0000 00000001 a5c3567b a5c3567b a5c3567b +(86/255)*255 42ac0000 00000002 a556e17b a556e17b a556e17b +(86/255)*255 42ac0000 00000003 56c3e17b 56c3e17b 56c3e17b +(86/255)*255 42ac0000 fffffffd a5c3567b a5c3567b a5c3567b +(86/255)*255 42ac0000 fffffffc a5c3e156 a5c3e156 a5c3e156 +(86/255)*255 42ac0000 80000002 a556e17b a556e17b a556e17b +(86/255)*255 42ac0000 00000103 56c3e17b 56c3e17b 56c3e17b +(87/255)*255 42ae0000 00000000 a5c3e157 a5c3e157 a5c3e157 +(87/255)*255 42ae0000 00000001 a5c3577b a5c3577b a5c3577b +(87/255)*255 42ae0000 00000002 a557e17b a557e17b a557e17b +(87/255)*255 42ae0000 00000003 57c3e17b 57c3e17b 57c3e17b +(87/255)*255 42ae0000 fffffffd a5c3577b a5c3577b a5c3577b +(87/255)*255 42ae0000 fffffffc a5c3e157 a5c3e157 a5c3e157 +(87/255)*255 42ae0000 80000002 a557e17b a557e17b a557e17b +(87/255)*255 42ae0000 00000103 57c3e17b 57c3e17b 57c3e17b +(88/255)*255 42b00000 00000000 a5c3e158 a5c3e158 a5c3e158 +(88/255)*255 42b00000 00000001 a5c3587b a5c3587b a5c3587b +(88/255)*255 42b00000 00000002 a558e17b a558e17b a558e17b +(88/255)*255 42b00000 00000003 58c3e17b 58c3e17b 58c3e17b +(88/255)*255 42b00000 fffffffd a5c3587b a5c3587b a5c3587b +(88/255)*255 42b00000 fffffffc a5c3e158 a5c3e158 a5c3e158 +(88/255)*255 42b00000 80000002 a558e17b a558e17b a558e17b +(88/255)*255 42b00000 00000103 58c3e17b 58c3e17b 58c3e17b +(89/255)*255 42b20000 00000000 a5c3e159 a5c3e159 a5c3e159 +(89/255)*255 42b20000 00000001 a5c3597b a5c3597b a5c3597b +(89/255)*255 42b20000 00000002 a559e17b a559e17b a559e17b +(89/255)*255 42b20000 00000003 59c3e17b 59c3e17b 59c3e17b +(89/255)*255 42b20000 fffffffd a5c3597b a5c3597b a5c3597b +(89/255)*255 42b20000 fffffffc a5c3e159 a5c3e159 a5c3e159 +(89/255)*255 42b20000 80000002 a559e17b a559e17b a559e17b +(89/255)*255 42b20000 00000103 59c3e17b 59c3e17b 59c3e17b +(90/255)*255 42b40000 00000000 a5c3e15a a5c3e15a a5c3e15a +(90/255)*255 42b40000 00000001 a5c35a7b a5c35a7b a5c35a7b +(90/255)*255 42b40000 00000002 a55ae17b a55ae17b a55ae17b +(90/255)*255 42b40000 00000003 5ac3e17b 5ac3e17b 5ac3e17b +(90/255)*255 42b40000 fffffffd a5c35a7b a5c35a7b a5c35a7b +(90/255)*255 42b40000 fffffffc a5c3e15a a5c3e15a a5c3e15a +(90/255)*255 42b40000 80000002 a55ae17b a55ae17b a55ae17b +(90/255)*255 42b40000 00000103 5ac3e17b 5ac3e17b 5ac3e17b +(91/255)*255 42b60000 00000000 a5c3e15b a5c3e15b a5c3e15b +(91/255)*255 42b60000 00000001 a5c35b7b a5c35b7b a5c35b7b +(91/255)*255 42b60000 00000002 a55be17b a55be17b a55be17b +(91/255)*255 42b60000 00000003 5bc3e17b 5bc3e17b 5bc3e17b +(91/255)*255 42b60000 fffffffd a5c35b7b a5c35b7b a5c35b7b +(91/255)*255 42b60000 fffffffc a5c3e15b a5c3e15b a5c3e15b +(91/255)*255 42b60000 80000002 a55be17b a55be17b a55be17b +(91/255)*255 42b60000 00000103 5bc3e17b 5bc3e17b 5bc3e17b +(92/255)*255 42b80000 00000000 a5c3e15c a5c3e15c a5c3e15c +(92/255)*255 42b80000 00000001 a5c35c7b a5c35c7b a5c35c7b +(92/255)*255 42b80000 00000002 a55ce17b a55ce17b a55ce17b +(92/255)*255 42b80000 00000003 5cc3e17b 5cc3e17b 5cc3e17b +(92/255)*255 42b80000 fffffffd a5c35c7b a5c35c7b a5c35c7b +(92/255)*255 42b80000 fffffffc a5c3e15c a5c3e15c a5c3e15c +(92/255)*255 42b80000 80000002 a55ce17b a55ce17b a55ce17b +(92/255)*255 42b80000 00000103 5cc3e17b 5cc3e17b 5cc3e17b +(93/255)*255 42ba0000 00000000 a5c3e15d a5c3e15d a5c3e15d +(93/255)*255 42ba0000 00000001 a5c35d7b a5c35d7b a5c35d7b +(93/255)*255 42ba0000 00000002 a55de17b a55de17b a55de17b +(93/255)*255 42ba0000 00000003 5dc3e17b 5dc3e17b 5dc3e17b +(93/255)*255 42ba0000 fffffffd a5c35d7b a5c35d7b a5c35d7b +(93/255)*255 42ba0000 fffffffc a5c3e15d a5c3e15d a5c3e15d +(93/255)*255 42ba0000 80000002 a55de17b a55de17b a55de17b +(93/255)*255 42ba0000 00000103 5dc3e17b 5dc3e17b 5dc3e17b +(94/255)*255 42bc0000 00000000 a5c3e15e a5c3e15e a5c3e15e +(94/255)*255 42bc0000 00000001 a5c35e7b a5c35e7b a5c35e7b +(94/255)*255 42bc0000 00000002 a55ee17b a55ee17b a55ee17b +(94/255)*255 42bc0000 00000003 5ec3e17b 5ec3e17b 5ec3e17b +(94/255)*255 42bc0000 fffffffd a5c35e7b a5c35e7b a5c35e7b +(94/255)*255 42bc0000 fffffffc a5c3e15e a5c3e15e a5c3e15e +(94/255)*255 42bc0000 80000002 a55ee17b a55ee17b a55ee17b +(94/255)*255 42bc0000 00000103 5ec3e17b 5ec3e17b 5ec3e17b +(95/255)*255 42be0000 00000000 a5c3e15f a5c3e15f a5c3e15f +(95/255)*255 42be0000 00000001 a5c35f7b a5c35f7b a5c35f7b +(95/255)*255 42be0000 00000002 a55fe17b a55fe17b a55fe17b +(95/255)*255 42be0000 00000003 5fc3e17b 5fc3e17b 5fc3e17b +(95/255)*255 42be0000 fffffffd a5c35f7b a5c35f7b a5c35f7b +(95/255)*255 42be0000 fffffffc a5c3e15f a5c3e15f a5c3e15f +(95/255)*255 42be0000 80000002 a55fe17b a55fe17b a55fe17b +(95/255)*255 42be0000 00000103 5fc3e17b 5fc3e17b 5fc3e17b +(96/255)*255 42c00000 00000000 a5c3e160 a5c3e160 a5c3e160 +(96/255)*255 42c00000 00000001 a5c3607b a5c3607b a5c3607b +(96/255)*255 42c00000 00000002 a560e17b a560e17b a560e17b +(96/255)*255 42c00000 00000003 60c3e17b 60c3e17b 60c3e17b +(96/255)*255 42c00000 fffffffd a5c3607b a5c3607b a5c3607b +(96/255)*255 42c00000 fffffffc a5c3e160 a5c3e160 a5c3e160 +(96/255)*255 42c00000 80000002 a560e17b a560e17b a560e17b +(96/255)*255 42c00000 00000103 60c3e17b 60c3e17b 60c3e17b +(97/255)*255 42c20000 00000000 a5c3e161 a5c3e161 a5c3e161 +(97/255)*255 42c20000 00000001 a5c3617b a5c3617b a5c3617b +(97/255)*255 42c20000 00000002 a561e17b a561e17b a561e17b +(97/255)*255 42c20000 00000003 61c3e17b 61c3e17b 61c3e17b +(97/255)*255 42c20000 fffffffd a5c3617b a5c3617b a5c3617b +(97/255)*255 42c20000 fffffffc a5c3e161 a5c3e161 a5c3e161 +(97/255)*255 42c20000 80000002 a561e17b a561e17b a561e17b +(97/255)*255 42c20000 00000103 61c3e17b 61c3e17b 61c3e17b +(98/255)*255 42c40000 00000000 a5c3e162 a5c3e162 a5c3e162 +(98/255)*255 42c40000 00000001 a5c3627b a5c3627b a5c3627b +(98/255)*255 42c40000 00000002 a562e17b a562e17b a562e17b +(98/255)*255 42c40000 00000003 62c3e17b 62c3e17b 62c3e17b +(98/255)*255 42c40000 fffffffd a5c3627b a5c3627b a5c3627b +(98/255)*255 42c40000 fffffffc a5c3e162 a5c3e162 a5c3e162 +(98/255)*255 42c40000 80000002 a562e17b a562e17b a562e17b +(98/255)*255 42c40000 00000103 62c3e17b 62c3e17b 62c3e17b +(99/255)*255 42c60000 00000000 a5c3e163 a5c3e163 a5c3e163 +(99/255)*255 42c60000 00000001 a5c3637b a5c3637b a5c3637b +(99/255)*255 42c60000 00000002 a563e17b a563e17b a563e17b +(99/255)*255 42c60000 00000003 63c3e17b 63c3e17b 63c3e17b +(99/255)*255 42c60000 fffffffd a5c3637b a5c3637b a5c3637b +(99/255)*255 42c60000 fffffffc a5c3e163 a5c3e163 a5c3e163 +(99/255)*255 42c60000 80000002 a563e17b a563e17b a563e17b +(99/255)*255 42c60000 00000103 63c3e17b 63c3e17b 63c3e17b +(101/255)*255 42ca0000 00000000 a5c3e165 a5c3e165 a5c3e165 +(101/255)*255 42ca0000 00000001 a5c3657b a5c3657b a5c3657b +(101/255)*255 42ca0000 00000002 a565e17b a565e17b a565e17b +(101/255)*255 42ca0000 00000003 65c3e17b 65c3e17b 65c3e17b +(101/255)*255 42ca0000 fffffffd a5c3657b a5c3657b a5c3657b +(101/255)*255 42ca0000 fffffffc a5c3e165 a5c3e165 a5c3e165 +(101/255)*255 42ca0000 80000002 a565e17b a565e17b a565e17b +(101/255)*255 42ca0000 00000103 65c3e17b 65c3e17b 65c3e17b +(102/255)*255 42cc0000 00000000 a5c3e166 a5c3e166 a5c3e166 +(102/255)*255 42cc0000 00000001 a5c3667b a5c3667b a5c3667b +(102/255)*255 42cc0000 00000002 a566e17b a566e17b a566e17b +(102/255)*255 42cc0000 00000003 66c3e17b 66c3e17b 66c3e17b +(102/255)*255 42cc0000 fffffffd a5c3667b a5c3667b a5c3667b +(102/255)*255 42cc0000 fffffffc a5c3e166 a5c3e166 a5c3e166 +(102/255)*255 42cc0000 80000002 a566e17b a566e17b a566e17b +(102/255)*255 42cc0000 00000103 66c3e17b 66c3e17b 66c3e17b +(103/255)*255 42ce0000 00000000 a5c3e167 a5c3e167 a5c3e167 +(103/255)*255 42ce0000 00000001 a5c3677b a5c3677b a5c3677b +(103/255)*255 42ce0000 00000002 a567e17b a567e17b a567e17b +(103/255)*255 42ce0000 00000003 67c3e17b 67c3e17b 67c3e17b +(103/255)*255 42ce0000 fffffffd a5c3677b a5c3677b a5c3677b +(103/255)*255 42ce0000 fffffffc a5c3e167 a5c3e167 a5c3e167 +(103/255)*255 42ce0000 80000002 a567e17b a567e17b a567e17b +(103/255)*255 42ce0000 00000103 67c3e17b 67c3e17b 67c3e17b +(104/255)*255 42d00000 00000000 a5c3e168 a5c3e168 a5c3e168 +(104/255)*255 42d00000 00000001 a5c3687b a5c3687b a5c3687b +(104/255)*255 42d00000 00000002 a568e17b a568e17b a568e17b +(104/255)*255 42d00000 00000003 68c3e17b 68c3e17b 68c3e17b +(104/255)*255 42d00000 fffffffd a5c3687b a5c3687b a5c3687b +(104/255)*255 42d00000 fffffffc a5c3e168 a5c3e168 a5c3e168 +(104/255)*255 42d00000 80000002 a568e17b a568e17b a568e17b +(104/255)*255 42d00000 00000103 68c3e17b 68c3e17b 68c3e17b +(105/255)*255 42d20000 00000000 a5c3e169 a5c3e169 a5c3e169 +(105/255)*255 42d20000 00000001 a5c3697b a5c3697b a5c3697b +(105/255)*255 42d20000 00000002 a569e17b a569e17b a569e17b +(105/255)*255 42d20000 00000003 69c3e17b 69c3e17b 69c3e17b +(105/255)*255 42d20000 fffffffd a5c3697b a5c3697b a5c3697b +(105/255)*255 42d20000 fffffffc a5c3e169 a5c3e169 a5c3e169 +(105/255)*255 42d20000 80000002 a569e17b a569e17b a569e17b +(105/255)*255 42d20000 00000103 69c3e17b 69c3e17b 69c3e17b +(106/255)*255 42d40000 00000000 a5c3e16a a5c3e16a a5c3e16a +(106/255)*255 42d40000 00000001 a5c36a7b a5c36a7b a5c36a7b +(106/255)*255 42d40000 00000002 a56ae17b a56ae17b a56ae17b +(106/255)*255 42d40000 00000003 6ac3e17b 6ac3e17b 6ac3e17b +(106/255)*255 42d40000 fffffffd a5c36a7b a5c36a7b a5c36a7b +(106/255)*255 42d40000 fffffffc a5c3e16a a5c3e16a a5c3e16a +(106/255)*255 42d40000 80000002 a56ae17b a56ae17b a56ae17b +(106/255)*255 42d40000 00000103 6ac3e17b 6ac3e17b 6ac3e17b +(107/255)*255 42d60000 00000000 a5c3e16b a5c3e16b a5c3e16b +(107/255)*255 42d60000 00000001 a5c36b7b a5c36b7b a5c36b7b +(107/255)*255 42d60000 00000002 a56be17b a56be17b a56be17b +(107/255)*255 42d60000 00000003 6bc3e17b 6bc3e17b 6bc3e17b +(107/255)*255 42d60000 fffffffd a5c36b7b a5c36b7b a5c36b7b +(107/255)*255 42d60000 fffffffc a5c3e16b a5c3e16b a5c3e16b +(107/255)*255 42d60000 80000002 a56be17b a56be17b a56be17b +(107/255)*255 42d60000 00000103 6bc3e17b 6bc3e17b 6bc3e17b +(108/255)*255 42d80000 00000000 a5c3e16c a5c3e16c a5c3e16c +(108/255)*255 42d80000 00000001 a5c36c7b a5c36c7b a5c36c7b +(108/255)*255 42d80000 00000002 a56ce17b a56ce17b a56ce17b +(108/255)*255 42d80000 00000003 6cc3e17b 6cc3e17b 6cc3e17b +(108/255)*255 42d80000 fffffffd a5c36c7b a5c36c7b a5c36c7b +(108/255)*255 42d80000 fffffffc a5c3e16c a5c3e16c a5c3e16c +(108/255)*255 42d80000 80000002 a56ce17b a56ce17b a56ce17b +(108/255)*255 42d80000 00000103 6cc3e17b 6cc3e17b 6cc3e17b +(109/255)*255 42da0000 00000000 a5c3e16d a5c3e16d a5c3e16d +(109/255)*255 42da0000 00000001 a5c36d7b a5c36d7b a5c36d7b +(109/255)*255 42da0000 00000002 a56de17b a56de17b a56de17b +(109/255)*255 42da0000 00000003 6dc3e17b 6dc3e17b 6dc3e17b +(109/255)*255 42da0000 fffffffd a5c36d7b a5c36d7b a5c36d7b +(109/255)*255 42da0000 fffffffc a5c3e16d a5c3e16d a5c3e16d +(109/255)*255 42da0000 80000002 a56de17b a56de17b a56de17b +(109/255)*255 42da0000 00000103 6dc3e17b 6dc3e17b 6dc3e17b +(110/255)*255 42dc0000 00000000 a5c3e16e a5c3e16e a5c3e16e +(110/255)*255 42dc0000 00000001 a5c36e7b a5c36e7b a5c36e7b +(110/255)*255 42dc0000 00000002 a56ee17b a56ee17b a56ee17b +(110/255)*255 42dc0000 00000003 6ec3e17b 6ec3e17b 6ec3e17b +(110/255)*255 42dc0000 fffffffd a5c36e7b a5c36e7b a5c36e7b +(110/255)*255 42dc0000 fffffffc a5c3e16e a5c3e16e a5c3e16e +(110/255)*255 42dc0000 80000002 a56ee17b a56ee17b a56ee17b +(110/255)*255 42dc0000 00000103 6ec3e17b 6ec3e17b 6ec3e17b +(111/255)*255 42de0000 00000000 a5c3e16f a5c3e16f a5c3e16f +(111/255)*255 42de0000 00000001 a5c36f7b a5c36f7b a5c36f7b +(111/255)*255 42de0000 00000002 a56fe17b a56fe17b a56fe17b +(111/255)*255 42de0000 00000003 6fc3e17b 6fc3e17b 6fc3e17b +(111/255)*255 42de0000 fffffffd a5c36f7b a5c36f7b a5c36f7b +(111/255)*255 42de0000 fffffffc a5c3e16f a5c3e16f a5c3e16f +(111/255)*255 42de0000 80000002 a56fe17b a56fe17b a56fe17b +(111/255)*255 42de0000 00000103 6fc3e17b 6fc3e17b 6fc3e17b +(112/255)*255 42e00000 00000000 a5c3e170 a5c3e170 a5c3e170 +(112/255)*255 42e00000 00000001 a5c3707b a5c3707b a5c3707b +(112/255)*255 42e00000 00000002 a570e17b a570e17b a570e17b +(112/255)*255 42e00000 00000003 70c3e17b 70c3e17b 70c3e17b +(112/255)*255 42e00000 fffffffd a5c3707b a5c3707b a5c3707b +(112/255)*255 42e00000 fffffffc a5c3e170 a5c3e170 a5c3e170 +(112/255)*255 42e00000 80000002 a570e17b a570e17b a570e17b +(112/255)*255 42e00000 00000103 70c3e17b 70c3e17b 70c3e17b +(113/255)*255 42e20000 00000000 a5c3e171 a5c3e171 a5c3e171 +(113/255)*255 42e20000 00000001 a5c3717b a5c3717b a5c3717b +(113/255)*255 42e20000 00000002 a571e17b a571e17b a571e17b +(113/255)*255 42e20000 00000003 71c3e17b 71c3e17b 71c3e17b +(113/255)*255 42e20000 fffffffd a5c3717b a5c3717b a5c3717b +(113/255)*255 42e20000 fffffffc a5c3e171 a5c3e171 a5c3e171 +(113/255)*255 42e20000 80000002 a571e17b a571e17b a571e17b +(113/255)*255 42e20000 00000103 71c3e17b 71c3e17b 71c3e17b +(114/255)*255 42e40000 00000000 a5c3e172 a5c3e172 a5c3e172 +(114/255)*255 42e40000 00000001 a5c3727b a5c3727b a5c3727b +(114/255)*255 42e40000 00000002 a572e17b a572e17b a572e17b +(114/255)*255 42e40000 00000003 72c3e17b 72c3e17b 72c3e17b +(114/255)*255 42e40000 fffffffd a5c3727b a5c3727b a5c3727b +(114/255)*255 42e40000 fffffffc a5c3e172 a5c3e172 a5c3e172 +(114/255)*255 42e40000 80000002 a572e17b a572e17b a572e17b +(114/255)*255 42e40000 00000103 72c3e17b 72c3e17b 72c3e17b +(115/255)*255 42e60000 00000000 a5c3e173 a5c3e173 a5c3e173 +(115/255)*255 42e60000 00000001 a5c3737b a5c3737b a5c3737b +(115/255)*255 42e60000 00000002 a573e17b a573e17b a573e17b +(115/255)*255 42e60000 00000003 73c3e17b 73c3e17b 73c3e17b +(115/255)*255 42e60000 fffffffd a5c3737b a5c3737b a5c3737b +(115/255)*255 42e60000 fffffffc a5c3e173 a5c3e173 a5c3e173 +(115/255)*255 42e60000 80000002 a573e17b a573e17b a573e17b +(115/255)*255 42e60000 00000103 73c3e17b 73c3e17b 73c3e17b +(116/255)*255 42e80000 00000000 a5c3e174 a5c3e174 a5c3e174 +(116/255)*255 42e80000 00000001 a5c3747b a5c3747b a5c3747b +(116/255)*255 42e80000 00000002 a574e17b a574e17b a574e17b +(116/255)*255 42e80000 00000003 74c3e17b 74c3e17b 74c3e17b +(116/255)*255 42e80000 fffffffd a5c3747b a5c3747b a5c3747b +(116/255)*255 42e80000 fffffffc a5c3e174 a5c3e174 a5c3e174 +(116/255)*255 42e80000 80000002 a574e17b a574e17b a574e17b +(116/255)*255 42e80000 00000103 74c3e17b 74c3e17b 74c3e17b +(117/255)*255 42ea0000 00000000 a5c3e175 a5c3e175 a5c3e175 +(117/255)*255 42ea0000 00000001 a5c3757b a5c3757b a5c3757b +(117/255)*255 42ea0000 00000002 a575e17b a575e17b a575e17b +(117/255)*255 42ea0000 00000003 75c3e17b 75c3e17b 75c3e17b +(117/255)*255 42ea0000 fffffffd a5c3757b a5c3757b a5c3757b +(117/255)*255 42ea0000 fffffffc a5c3e175 a5c3e175 a5c3e175 +(117/255)*255 42ea0000 80000002 a575e17b a575e17b a575e17b +(117/255)*255 42ea0000 00000103 75c3e17b 75c3e17b 75c3e17b +(118/255)*255 42ec0000 00000000 a5c3e176 a5c3e176 a5c3e176 +(118/255)*255 42ec0000 00000001 a5c3767b a5c3767b a5c3767b +(118/255)*255 42ec0000 00000002 a576e17b a576e17b a576e17b +(118/255)*255 42ec0000 00000003 76c3e17b 76c3e17b 76c3e17b +(118/255)*255 42ec0000 fffffffd a5c3767b a5c3767b a5c3767b +(118/255)*255 42ec0000 fffffffc a5c3e176 a5c3e176 a5c3e176 +(118/255)*255 42ec0000 80000002 a576e17b a576e17b a576e17b +(118/255)*255 42ec0000 00000103 76c3e17b 76c3e17b 76c3e17b +(119/255)*255 42ee0000 00000000 a5c3e177 a5c3e177 a5c3e177 +(119/255)*255 42ee0000 00000001 a5c3777b a5c3777b a5c3777b +(119/255)*255 42ee0000 00000002 a577e17b a577e17b a577e17b +(119/255)*255 42ee0000 00000003 77c3e17b 77c3e17b 77c3e17b +(119/255)*255 42ee0000 fffffffd a5c3777b a5c3777b a5c3777b +(119/255)*255 42ee0000 fffffffc a5c3e177 a5c3e177 a5c3e177 +(119/255)*255 42ee0000 80000002 a577e17b a577e17b a577e17b +(119/255)*255 42ee0000 00000103 77c3e17b 77c3e17b 77c3e17b +(120/255)*255 42f00000 00000000 a5c3e178 a5c3e178 a5c3e178 +(120/255)*255 42f00000 00000001 a5c3787b a5c3787b a5c3787b +(120/255)*255 42f00000 00000002 a578e17b a578e17b a578e17b +(120/255)*255 42f00000 00000003 78c3e17b 78c3e17b 78c3e17b +(120/255)*255 42f00000 fffffffd a5c3787b a5c3787b a5c3787b +(120/255)*255 42f00000 fffffffc a5c3e178 a5c3e178 a5c3e178 +(120/255)*255 42f00000 80000002 a578e17b a578e17b a578e17b +(120/255)*255 42f00000 00000103 78c3e17b 78c3e17b 78c3e17b +(121/255)*255 42f20000 00000000 a5c3e179 a5c3e179 a5c3e179 +(121/255)*255 42f20000 00000001 a5c3797b a5c3797b a5c3797b +(121/255)*255 42f20000 00000002 a579e17b a579e17b a579e17b +(121/255)*255 42f20000 00000003 79c3e17b 79c3e17b 79c3e17b +(121/255)*255 42f20000 fffffffd a5c3797b a5c3797b a5c3797b +(121/255)*255 42f20000 fffffffc a5c3e179 a5c3e179 a5c3e179 +(121/255)*255 42f20000 80000002 a579e17b a579e17b a579e17b +(121/255)*255 42f20000 00000103 79c3e17b 79c3e17b 79c3e17b +(122/255)*255 42f40000 00000000 a5c3e17a a5c3e17a a5c3e17a +(122/255)*255 42f40000 00000001 a5c37a7b a5c37a7b a5c37a7b +(122/255)*255 42f40000 00000002 a57ae17b a57ae17b a57ae17b +(122/255)*255 42f40000 00000003 7ac3e17b 7ac3e17b 7ac3e17b +(122/255)*255 42f40000 fffffffd a5c37a7b a5c37a7b a5c37a7b +(122/255)*255 42f40000 fffffffc a5c3e17a a5c3e17a a5c3e17a +(122/255)*255 42f40000 80000002 a57ae17b a57ae17b a57ae17b +(122/255)*255 42f40000 00000103 7ac3e17b 7ac3e17b 7ac3e17b +(123/255)*255 42f60000 00000000 a5c3e17b a5c3e17b a5c3e17b +(123/255)*255 42f60000 00000001 a5c37b7b a5c37b7b a5c37b7b +(123/255)*255 42f60000 00000002 a57be17b a57be17b a57be17b +(123/255)*255 42f60000 00000003 7bc3e17b 7bc3e17b 7bc3e17b +(123/255)*255 42f60000 fffffffd a5c37b7b a5c37b7b a5c37b7b +(123/255)*255 42f60000 fffffffc a5c3e17b a5c3e17b a5c3e17b +(123/255)*255 42f60000 80000002 a57be17b a57be17b a57be17b +(123/255)*255 42f60000 00000103 7bc3e17b 7bc3e17b 7bc3e17b +(124/255)*255 42f80000 00000000 a5c3e17c a5c3e17c a5c3e17c +(124/255)*255 42f80000 00000001 a5c37c7b a5c37c7b a5c37c7b +(124/255)*255 42f80000 00000002 a57ce17b a57ce17b a57ce17b +(124/255)*255 42f80000 00000003 7cc3e17b 7cc3e17b 7cc3e17b +(124/255)*255 42f80000 fffffffd a5c37c7b a5c37c7b a5c37c7b +(124/255)*255 42f80000 fffffffc a5c3e17c a5c3e17c a5c3e17c +(124/255)*255 42f80000 80000002 a57ce17b a57ce17b a57ce17b +(124/255)*255 42f80000 00000103 7cc3e17b 7cc3e17b 7cc3e17b +(125/255)*255 42fa0000 00000000 a5c3e17d a5c3e17d a5c3e17d +(125/255)*255 42fa0000 00000001 a5c37d7b a5c37d7b a5c37d7b +(125/255)*255 42fa0000 00000002 a57de17b a57de17b a57de17b +(125/255)*255 42fa0000 00000003 7dc3e17b 7dc3e17b 7dc3e17b +(125/255)*255 42fa0000 fffffffd a5c37d7b a5c37d7b a5c37d7b +(125/255)*255 42fa0000 fffffffc a5c3e17d a5c3e17d a5c3e17d +(125/255)*255 42fa0000 80000002 a57de17b a57de17b a57de17b +(125/255)*255 42fa0000 00000103 7dc3e17b 7dc3e17b 7dc3e17b +(126/255)*255 42fc0000 00000000 a5c3e17e a5c3e17e a5c3e17e +(126/255)*255 42fc0000 00000001 a5c37e7b a5c37e7b a5c37e7b +(126/255)*255 42fc0000 00000002 a57ee17b a57ee17b a57ee17b +(126/255)*255 42fc0000 00000003 7ec3e17b 7ec3e17b 7ec3e17b +(126/255)*255 42fc0000 fffffffd a5c37e7b a5c37e7b a5c37e7b +(126/255)*255 42fc0000 fffffffc a5c3e17e a5c3e17e a5c3e17e +(126/255)*255 42fc0000 80000002 a57ee17b a57ee17b a57ee17b +(126/255)*255 42fc0000 00000103 7ec3e17b 7ec3e17b 7ec3e17b +(130/255)*255 43020000 00000000 a5c3e182 a5c3e182 a5c3e182 +(130/255)*255 43020000 00000001 a5c3827b a5c3827b a5c3827b +(130/255)*255 43020000 00000002 a582e17b a582e17b a582e17b +(130/255)*255 43020000 00000003 82c3e17b 82c3e17b 82c3e17b +(130/255)*255 43020000 fffffffd a5c3827b a5c3827b a5c3827b +(130/255)*255 43020000 fffffffc a5c3e182 a5c3e182 a5c3e182 +(130/255)*255 43020000 80000002 a582e17b a582e17b a582e17b +(130/255)*255 43020000 00000103 82c3e17b 82c3e17b 82c3e17b +(131/255)*255 43030000 00000000 a5c3e183 a5c3e183 a5c3e183 +(131/255)*255 43030000 00000001 a5c3837b a5c3837b a5c3837b +(131/255)*255 43030000 00000002 a583e17b a583e17b a583e17b +(131/255)*255 43030000 00000003 83c3e17b 83c3e17b 83c3e17b +(131/255)*255 43030000 fffffffd a5c3837b a5c3837b a5c3837b +(131/255)*255 43030000 fffffffc a5c3e183 a5c3e183 a5c3e183 +(131/255)*255 43030000 80000002 a583e17b a583e17b a583e17b +(131/255)*255 43030000 00000103 83c3e17b 83c3e17b 83c3e17b +(132/255)*255 43040000 00000000 a5c3e184 a5c3e184 a5c3e184 +(132/255)*255 43040000 00000001 a5c3847b a5c3847b a5c3847b +(132/255)*255 43040000 00000002 a584e17b a584e17b a584e17b +(132/255)*255 43040000 00000003 84c3e17b 84c3e17b 84c3e17b +(132/255)*255 43040000 fffffffd a5c3847b a5c3847b a5c3847b +(132/255)*255 43040000 fffffffc a5c3e184 a5c3e184 a5c3e184 +(132/255)*255 43040000 80000002 a584e17b a584e17b a584e17b +(132/255)*255 43040000 00000103 84c3e17b 84c3e17b 84c3e17b +(133/255)*255 43050000 00000000 a5c3e185 a5c3e185 a5c3e185 +(133/255)*255 43050000 00000001 a5c3857b a5c3857b a5c3857b +(133/255)*255 43050000 00000002 a585e17b a585e17b a585e17b +(133/255)*255 43050000 00000003 85c3e17b 85c3e17b 85c3e17b +(133/255)*255 43050000 fffffffd a5c3857b a5c3857b a5c3857b +(133/255)*255 43050000 fffffffc a5c3e185 a5c3e185 a5c3e185 +(133/255)*255 43050000 80000002 a585e17b a585e17b a585e17b +(133/255)*255 43050000 00000103 85c3e17b 85c3e17b 85c3e17b +(134/255)*255 43060000 00000000 a5c3e186 a5c3e186 a5c3e186 +(134/255)*255 43060000 00000001 a5c3867b a5c3867b a5c3867b +(134/255)*255 43060000 00000002 a586e17b a586e17b a586e17b +(134/255)*255 43060000 00000003 86c3e17b 86c3e17b 86c3e17b +(134/255)*255 43060000 fffffffd a5c3867b a5c3867b a5c3867b +(134/255)*255 43060000 fffffffc a5c3e186 a5c3e186 a5c3e186 +(134/255)*255 43060000 80000002 a586e17b a586e17b a586e17b +(134/255)*255 43060000 00000103 86c3e17b 86c3e17b 86c3e17b +(135/255)*255 43070000 00000000 a5c3e187 a5c3e187 a5c3e187 +(135/255)*255 43070000 00000001 a5c3877b a5c3877b a5c3877b +(135/255)*255 43070000 00000002 a587e17b a587e17b a587e17b +(135/255)*255 43070000 00000003 87c3e17b 87c3e17b 87c3e17b +(135/255)*255 43070000 fffffffd a5c3877b a5c3877b a5c3877b +(135/255)*255 43070000 fffffffc a5c3e187 a5c3e187 a5c3e187 +(135/255)*255 43070000 80000002 a587e17b a587e17b a587e17b +(135/255)*255 43070000 00000103 87c3e17b 87c3e17b 87c3e17b +(136/255)*255 43080000 00000000 a5c3e188 a5c3e188 a5c3e188 +(136/255)*255 43080000 00000001 a5c3887b a5c3887b a5c3887b +(136/255)*255 43080000 00000002 a588e17b a588e17b a588e17b +(136/255)*255 43080000 00000003 88c3e17b 88c3e17b 88c3e17b +(136/255)*255 43080000 fffffffd a5c3887b a5c3887b a5c3887b +(136/255)*255 43080000 fffffffc a5c3e188 a5c3e188 a5c3e188 +(136/255)*255 43080000 80000002 a588e17b a588e17b a588e17b +(136/255)*255 43080000 00000103 88c3e17b 88c3e17b 88c3e17b +(137/255)*255 43090000 00000000 a5c3e189 a5c3e189 a5c3e189 +(137/255)*255 43090000 00000001 a5c3897b a5c3897b a5c3897b +(137/255)*255 43090000 00000002 a589e17b a589e17b a589e17b +(137/255)*255 43090000 00000003 89c3e17b 89c3e17b 89c3e17b +(137/255)*255 43090000 fffffffd a5c3897b a5c3897b a5c3897b +(137/255)*255 43090000 fffffffc a5c3e189 a5c3e189 a5c3e189 +(137/255)*255 43090000 80000002 a589e17b a589e17b a589e17b +(137/255)*255 43090000 00000103 89c3e17b 89c3e17b 89c3e17b +(138/255)*255 430a0000 00000000 a5c3e18a a5c3e18a a5c3e18a +(138/255)*255 430a0000 00000001 a5c38a7b a5c38a7b a5c38a7b +(138/255)*255 430a0000 00000002 a58ae17b a58ae17b a58ae17b +(138/255)*255 430a0000 00000003 8ac3e17b 8ac3e17b 8ac3e17b +(138/255)*255 430a0000 fffffffd a5c38a7b a5c38a7b a5c38a7b +(138/255)*255 430a0000 fffffffc a5c3e18a a5c3e18a a5c3e18a +(138/255)*255 430a0000 80000002 a58ae17b a58ae17b a58ae17b +(138/255)*255 430a0000 00000103 8ac3e17b 8ac3e17b 8ac3e17b +(139/255)*255 430b0000 00000000 a5c3e18b a5c3e18b a5c3e18b +(139/255)*255 430b0000 00000001 a5c38b7b a5c38b7b a5c38b7b +(139/255)*255 430b0000 00000002 a58be17b a58be17b a58be17b +(139/255)*255 430b0000 00000003 8bc3e17b 8bc3e17b 8bc3e17b +(139/255)*255 430b0000 fffffffd a5c38b7b a5c38b7b a5c38b7b +(139/255)*255 430b0000 fffffffc a5c3e18b a5c3e18b a5c3e18b +(139/255)*255 430b0000 80000002 a58be17b a58be17b a58be17b +(139/255)*255 430b0000 00000103 8bc3e17b 8bc3e17b 8bc3e17b +(140/255)*255 430c0000 00000000 a5c3e18c a5c3e18c a5c3e18c +(140/255)*255 430c0000 00000001 a5c38c7b a5c38c7b a5c38c7b +(140/255)*255 430c0000 00000002 a58ce17b a58ce17b a58ce17b +(140/255)*255 430c0000 00000003 8cc3e17b 8cc3e17b 8cc3e17b +(140/255)*255 430c0000 fffffffd a5c38c7b a5c38c7b a5c38c7b +(140/255)*255 430c0000 fffffffc a5c3e18c a5c3e18c a5c3e18c +(140/255)*255 430c0000 80000002 a58ce17b a58ce17b a58ce17b +(140/255)*255 430c0000 00000103 8cc3e17b 8cc3e17b 8cc3e17b +(141/255)*255 430d0000 00000000 a5c3e18d a5c3e18d a5c3e18d +(141/255)*255 430d0000 00000001 a5c38d7b a5c38d7b a5c38d7b +(141/255)*255 430d0000 00000002 a58de17b a58de17b a58de17b +(141/255)*255 430d0000 00000003 8dc3e17b 8dc3e17b 8dc3e17b +(141/255)*255 430d0000 fffffffd a5c38d7b a5c38d7b a5c38d7b +(141/255)*255 430d0000 fffffffc a5c3e18d a5c3e18d a5c3e18d +(141/255)*255 430d0000 80000002 a58de17b a58de17b a58de17b +(141/255)*255 430d0000 00000103 8dc3e17b 8dc3e17b 8dc3e17b +(142/255)*255 430e0000 00000000 a5c3e18e a5c3e18e a5c3e18e +(142/255)*255 430e0000 00000001 a5c38e7b a5c38e7b a5c38e7b +(142/255)*255 430e0000 00000002 a58ee17b a58ee17b a58ee17b +(142/255)*255 430e0000 00000003 8ec3e17b 8ec3e17b 8ec3e17b +(142/255)*255 430e0000 fffffffd a5c38e7b a5c38e7b a5c38e7b +(142/255)*255 430e0000 fffffffc a5c3e18e a5c3e18e a5c3e18e +(142/255)*255 430e0000 80000002 a58ee17b a58ee17b a58ee17b +(142/255)*255 430e0000 00000103 8ec3e17b 8ec3e17b 8ec3e17b +(143/255)*255 430f0000 00000000 a5c3e18f a5c3e18f a5c3e18f +(143/255)*255 430f0000 00000001 a5c38f7b a5c38f7b a5c38f7b +(143/255)*255 430f0000 00000002 a58fe17b a58fe17b a58fe17b +(143/255)*255 430f0000 00000003 8fc3e17b 8fc3e17b 8fc3e17b +(143/255)*255 430f0000 fffffffd a5c38f7b a5c38f7b a5c38f7b +(143/255)*255 430f0000 fffffffc a5c3e18f a5c3e18f a5c3e18f +(143/255)*255 430f0000 80000002 a58fe17b a58fe17b a58fe17b +(143/255)*255 430f0000 00000103 8fc3e17b 8fc3e17b 8fc3e17b +(144/255)*255 43100000 00000000 a5c3e190 a5c3e190 a5c3e190 +(144/255)*255 43100000 00000001 a5c3907b a5c3907b a5c3907b +(144/255)*255 43100000 00000002 a590e17b a590e17b a590e17b +(144/255)*255 43100000 00000003 90c3e17b 90c3e17b 90c3e17b +(144/255)*255 43100000 fffffffd a5c3907b a5c3907b a5c3907b +(144/255)*255 43100000 fffffffc a5c3e190 a5c3e190 a5c3e190 +(144/255)*255 43100000 80000002 a590e17b a590e17b a590e17b +(144/255)*255 43100000 00000103 90c3e17b 90c3e17b 90c3e17b +(145/255)*255 43110000 00000000 a5c3e191 a5c3e191 a5c3e191 +(145/255)*255 43110000 00000001 a5c3917b a5c3917b a5c3917b +(145/255)*255 43110000 00000002 a591e17b a591e17b a591e17b +(145/255)*255 43110000 00000003 91c3e17b 91c3e17b 91c3e17b +(145/255)*255 43110000 fffffffd a5c3917b a5c3917b a5c3917b +(145/255)*255 43110000 fffffffc a5c3e191 a5c3e191 a5c3e191 +(145/255)*255 43110000 80000002 a591e17b a591e17b a591e17b +(145/255)*255 43110000 00000103 91c3e17b 91c3e17b 91c3e17b +(146/255)*255 43120000 00000000 a5c3e192 a5c3e192 a5c3e192 +(146/255)*255 43120000 00000001 a5c3927b a5c3927b a5c3927b +(146/255)*255 43120000 00000002 a592e17b a592e17b a592e17b +(146/255)*255 43120000 00000003 92c3e17b 92c3e17b 92c3e17b +(146/255)*255 43120000 fffffffd a5c3927b a5c3927b a5c3927b +(146/255)*255 43120000 fffffffc a5c3e192 a5c3e192 a5c3e192 +(146/255)*255 43120000 80000002 a592e17b a592e17b a592e17b +(146/255)*255 43120000 00000103 92c3e17b 92c3e17b 92c3e17b +(147/255)*255 43130000 00000000 a5c3e193 a5c3e193 a5c3e193 +(147/255)*255 43130000 00000001 a5c3937b a5c3937b a5c3937b +(147/255)*255 43130000 00000002 a593e17b a593e17b a593e17b +(147/255)*255 43130000 00000003 93c3e17b 93c3e17b 93c3e17b +(147/255)*255 43130000 fffffffd a5c3937b a5c3937b a5c3937b +(147/255)*255 43130000 fffffffc a5c3e193 a5c3e193 a5c3e193 +(147/255)*255 43130000 80000002 a593e17b a593e17b a593e17b +(147/255)*255 43130000 00000103 93c3e17b 93c3e17b 93c3e17b +(148/255)*255 43140000 00000000 a5c3e194 a5c3e194 a5c3e194 +(148/255)*255 43140000 00000001 a5c3947b a5c3947b a5c3947b +(148/255)*255 43140000 00000002 a594e17b a594e17b a594e17b +(148/255)*255 43140000 00000003 94c3e17b 94c3e17b 94c3e17b +(148/255)*255 43140000 fffffffd a5c3947b a5c3947b a5c3947b +(148/255)*255 43140000 fffffffc a5c3e194 a5c3e194 a5c3e194 +(148/255)*255 43140000 80000002 a594e17b a594e17b a594e17b +(148/255)*255 43140000 00000103 94c3e17b 94c3e17b 94c3e17b +(149/255)*255 43150000 00000000 a5c3e195 a5c3e195 a5c3e195 +(149/255)*255 43150000 00000001 a5c3957b a5c3957b a5c3957b +(149/255)*255 43150000 00000002 a595e17b a595e17b a595e17b +(149/255)*255 43150000 00000003 95c3e17b 95c3e17b 95c3e17b +(149/255)*255 43150000 fffffffd a5c3957b a5c3957b a5c3957b +(149/255)*255 43150000 fffffffc a5c3e195 a5c3e195 a5c3e195 +(149/255)*255 43150000 80000002 a595e17b a595e17b a595e17b +(149/255)*255 43150000 00000103 95c3e17b 95c3e17b 95c3e17b +(150/255)*255 43160000 00000000 a5c3e196 a5c3e196 a5c3e196 +(150/255)*255 43160000 00000001 a5c3967b a5c3967b a5c3967b +(150/255)*255 43160000 00000002 a596e17b a596e17b a596e17b +(150/255)*255 43160000 00000003 96c3e17b 96c3e17b 96c3e17b +(150/255)*255 43160000 fffffffd a5c3967b a5c3967b a5c3967b +(150/255)*255 43160000 fffffffc a5c3e196 a5c3e196 a5c3e196 +(150/255)*255 43160000 80000002 a596e17b a596e17b a596e17b +(150/255)*255 43160000 00000103 96c3e17b 96c3e17b 96c3e17b +(151/255)*255 43170000 00000000 a5c3e197 a5c3e197 a5c3e197 +(151/255)*255 43170000 00000001 a5c3977b a5c3977b a5c3977b +(151/255)*255 43170000 00000002 a597e17b a597e17b a597e17b +(151/255)*255 43170000 00000003 97c3e17b 97c3e17b 97c3e17b +(151/255)*255 43170000 fffffffd a5c3977b a5c3977b a5c3977b +(151/255)*255 43170000 fffffffc a5c3e197 a5c3e197 a5c3e197 +(151/255)*255 43170000 80000002 a597e17b a597e17b a597e17b +(151/255)*255 43170000 00000103 97c3e17b 97c3e17b 97c3e17b +(152/255)*255 43180000 00000000 a5c3e198 a5c3e198 a5c3e198 +(152/255)*255 43180000 00000001 a5c3987b a5c3987b a5c3987b +(152/255)*255 43180000 00000002 a598e17b a598e17b a598e17b +(152/255)*255 43180000 00000003 98c3e17b 98c3e17b 98c3e17b +(152/255)*255 43180000 fffffffd a5c3987b a5c3987b a5c3987b +(152/255)*255 43180000 fffffffc a5c3e198 a5c3e198 a5c3e198 +(152/255)*255 43180000 80000002 a598e17b a598e17b a598e17b +(152/255)*255 43180000 00000103 98c3e17b 98c3e17b 98c3e17b +(153/255)*255 43190000 00000000 a5c3e199 a5c3e199 a5c3e199 +(153/255)*255 43190000 00000001 a5c3997b a5c3997b a5c3997b +(153/255)*255 43190000 00000002 a599e17b a599e17b a599e17b +(153/255)*255 43190000 00000003 99c3e17b 99c3e17b 99c3e17b +(153/255)*255 43190000 fffffffd a5c3997b a5c3997b a5c3997b +(153/255)*255 43190000 fffffffc a5c3e199 a5c3e199 a5c3e199 +(153/255)*255 43190000 80000002 a599e17b a599e17b a599e17b +(153/255)*255 43190000 00000103 99c3e17b 99c3e17b 99c3e17b +(154/255)*255 431a0000 00000000 a5c3e19a a5c3e19a a5c3e19a +(154/255)*255 431a0000 00000001 a5c39a7b a5c39a7b a5c39a7b +(154/255)*255 431a0000 00000002 a59ae17b a59ae17b a59ae17b +(154/255)*255 431a0000 00000003 9ac3e17b 9ac3e17b 9ac3e17b +(154/255)*255 431a0000 fffffffd a5c39a7b a5c39a7b a5c39a7b +(154/255)*255 431a0000 fffffffc a5c3e19a a5c3e19a a5c3e19a +(154/255)*255 431a0000 80000002 a59ae17b a59ae17b a59ae17b +(154/255)*255 431a0000 00000103 9ac3e17b 9ac3e17b 9ac3e17b +(155/255)*255 431b0000 00000000 a5c3e19b a5c3e19b a5c3e19b +(155/255)*255 431b0000 00000001 a5c39b7b a5c39b7b a5c39b7b +(155/255)*255 431b0000 00000002 a59be17b a59be17b a59be17b +(155/255)*255 431b0000 00000003 9bc3e17b 9bc3e17b 9bc3e17b +(155/255)*255 431b0000 fffffffd a5c39b7b a5c39b7b a5c39b7b +(155/255)*255 431b0000 fffffffc a5c3e19b a5c3e19b a5c3e19b +(155/255)*255 431b0000 80000002 a59be17b a59be17b a59be17b +(155/255)*255 431b0000 00000103 9bc3e17b 9bc3e17b 9bc3e17b +(156/255)*255 431c0000 00000000 a5c3e19c a5c3e19c a5c3e19c +(156/255)*255 431c0000 00000001 a5c39c7b a5c39c7b a5c39c7b +(156/255)*255 431c0000 00000002 a59ce17b a59ce17b a59ce17b +(156/255)*255 431c0000 00000003 9cc3e17b 9cc3e17b 9cc3e17b +(156/255)*255 431c0000 fffffffd a5c39c7b a5c39c7b a5c39c7b +(156/255)*255 431c0000 fffffffc a5c3e19c a5c3e19c a5c3e19c +(156/255)*255 431c0000 80000002 a59ce17b a59ce17b a59ce17b +(156/255)*255 431c0000 00000103 9cc3e17b 9cc3e17b 9cc3e17b +(157/255)*255 431d0000 00000000 a5c3e19d a5c3e19d a5c3e19d +(157/255)*255 431d0000 00000001 a5c39d7b a5c39d7b a5c39d7b +(157/255)*255 431d0000 00000002 a59de17b a59de17b a59de17b +(157/255)*255 431d0000 00000003 9dc3e17b 9dc3e17b 9dc3e17b +(157/255)*255 431d0000 fffffffd a5c39d7b a5c39d7b a5c39d7b +(157/255)*255 431d0000 fffffffc a5c3e19d a5c3e19d a5c3e19d +(157/255)*255 431d0000 80000002 a59de17b a59de17b a59de17b +(157/255)*255 431d0000 00000103 9dc3e17b 9dc3e17b 9dc3e17b +(158/255)*255 431e0000 00000000 a5c3e19e a5c3e19e a5c3e19e +(158/255)*255 431e0000 00000001 a5c39e7b a5c39e7b a5c39e7b +(158/255)*255 431e0000 00000002 a59ee17b a59ee17b a59ee17b +(158/255)*255 431e0000 00000003 9ec3e17b 9ec3e17b 9ec3e17b +(158/255)*255 431e0000 fffffffd a5c39e7b a5c39e7b a5c39e7b +(158/255)*255 431e0000 fffffffc a5c3e19e a5c3e19e a5c3e19e +(158/255)*255 431e0000 80000002 a59ee17b a59ee17b a59ee17b +(158/255)*255 431e0000 00000103 9ec3e17b 9ec3e17b 9ec3e17b +(159/255)*255 431f0000 00000000 a5c3e19f a5c3e19f a5c3e19f +(159/255)*255 431f0000 00000001 a5c39f7b a5c39f7b a5c39f7b +(159/255)*255 431f0000 00000002 a59fe17b a59fe17b a59fe17b +(159/255)*255 431f0000 00000003 9fc3e17b 9fc3e17b 9fc3e17b +(159/255)*255 431f0000 fffffffd a5c39f7b a5c39f7b a5c39f7b +(159/255)*255 431f0000 fffffffc a5c3e19f a5c3e19f a5c3e19f +(159/255)*255 431f0000 80000002 a59fe17b a59fe17b a59fe17b +(159/255)*255 431f0000 00000103 9fc3e17b 9fc3e17b 9fc3e17b +(160/255)*255 43200000 00000000 a5c3e1a0 a5c3e1a0 a5c3e1a0 +(160/255)*255 43200000 00000001 a5c3a07b a5c3a07b a5c3a07b +(160/255)*255 43200000 00000002 a5a0e17b a5a0e17b a5a0e17b +(160/255)*255 43200000 00000003 a0c3e17b a0c3e17b a0c3e17b +(160/255)*255 43200000 fffffffd a5c3a07b a5c3a07b a5c3a07b +(160/255)*255 43200000 fffffffc a5c3e1a0 a5c3e1a0 a5c3e1a0 +(160/255)*255 43200000 80000002 a5a0e17b a5a0e17b a5a0e17b +(160/255)*255 43200000 00000103 a0c3e17b a0c3e17b a0c3e17b +(161/255)*255 43210000 00000000 a5c3e1a1 a5c3e1a1 a5c3e1a1 +(161/255)*255 43210000 00000001 a5c3a17b a5c3a17b a5c3a17b +(161/255)*255 43210000 00000002 a5a1e17b a5a1e17b a5a1e17b +(161/255)*255 43210000 00000003 a1c3e17b a1c3e17b a1c3e17b +(161/255)*255 43210000 fffffffd a5c3a17b a5c3a17b a5c3a17b +(161/255)*255 43210000 fffffffc a5c3e1a1 a5c3e1a1 a5c3e1a1 +(161/255)*255 43210000 80000002 a5a1e17b a5a1e17b a5a1e17b +(161/255)*255 43210000 00000103 a1c3e17b a1c3e17b a1c3e17b +(162/255)*255 43220000 00000000 a5c3e1a2 a5c3e1a2 a5c3e1a2 +(162/255)*255 43220000 00000001 a5c3a27b a5c3a27b a5c3a27b +(162/255)*255 43220000 00000002 a5a2e17b a5a2e17b a5a2e17b +(162/255)*255 43220000 00000003 a2c3e17b a2c3e17b a2c3e17b +(162/255)*255 43220000 fffffffd a5c3a27b a5c3a27b a5c3a27b +(162/255)*255 43220000 fffffffc a5c3e1a2 a5c3e1a2 a5c3e1a2 +(162/255)*255 43220000 80000002 a5a2e17b a5a2e17b a5a2e17b +(162/255)*255 43220000 00000103 a2c3e17b a2c3e17b a2c3e17b +(163/255)*255 43230000 00000000 a5c3e1a3 a5c3e1a3 a5c3e1a3 +(163/255)*255 43230000 00000001 a5c3a37b a5c3a37b a5c3a37b +(163/255)*255 43230000 00000002 a5a3e17b a5a3e17b a5a3e17b +(163/255)*255 43230000 00000003 a3c3e17b a3c3e17b a3c3e17b +(163/255)*255 43230000 fffffffd a5c3a37b a5c3a37b a5c3a37b +(163/255)*255 43230000 fffffffc a5c3e1a3 a5c3e1a3 a5c3e1a3 +(163/255)*255 43230000 80000002 a5a3e17b a5a3e17b a5a3e17b +(163/255)*255 43230000 00000103 a3c3e17b a3c3e17b a3c3e17b +(164/255)*255 43240000 00000000 a5c3e1a4 a5c3e1a4 a5c3e1a4 +(164/255)*255 43240000 00000001 a5c3a47b a5c3a47b a5c3a47b +(164/255)*255 43240000 00000002 a5a4e17b a5a4e17b a5a4e17b +(164/255)*255 43240000 00000003 a4c3e17b a4c3e17b a4c3e17b +(164/255)*255 43240000 fffffffd a5c3a47b a5c3a47b a5c3a47b +(164/255)*255 43240000 fffffffc a5c3e1a4 a5c3e1a4 a5c3e1a4 +(164/255)*255 43240000 80000002 a5a4e17b a5a4e17b a5a4e17b +(164/255)*255 43240000 00000103 a4c3e17b a4c3e17b a4c3e17b +(165/255)*255 43250000 00000000 a5c3e1a5 a5c3e1a5 a5c3e1a5 +(165/255)*255 43250000 00000001 a5c3a57b a5c3a57b a5c3a57b +(165/255)*255 43250000 00000002 a5a5e17b a5a5e17b a5a5e17b +(165/255)*255 43250000 00000003 a5c3e17b a5c3e17b a5c3e17b +(165/255)*255 43250000 fffffffd a5c3a57b a5c3a57b a5c3a57b +(165/255)*255 43250000 fffffffc a5c3e1a5 a5c3e1a5 a5c3e1a5 +(165/255)*255 43250000 80000002 a5a5e17b a5a5e17b a5a5e17b +(165/255)*255 43250000 00000103 a5c3e17b a5c3e17b a5c3e17b +(166/255)*255 43260000 00000000 a5c3e1a6 a5c3e1a6 a5c3e1a6 +(166/255)*255 43260000 00000001 a5c3a67b a5c3a67b a5c3a67b +(166/255)*255 43260000 00000002 a5a6e17b a5a6e17b a5a6e17b +(166/255)*255 43260000 00000003 a6c3e17b a6c3e17b a6c3e17b +(166/255)*255 43260000 fffffffd a5c3a67b a5c3a67b a5c3a67b +(166/255)*255 43260000 fffffffc a5c3e1a6 a5c3e1a6 a5c3e1a6 +(166/255)*255 43260000 80000002 a5a6e17b a5a6e17b a5a6e17b +(166/255)*255 43260000 00000103 a6c3e17b a6c3e17b a6c3e17b +(167/255)*255 43270000 00000000 a5c3e1a7 a5c3e1a7 a5c3e1a7 +(167/255)*255 43270000 00000001 a5c3a77b a5c3a77b a5c3a77b +(167/255)*255 43270000 00000002 a5a7e17b a5a7e17b a5a7e17b +(167/255)*255 43270000 00000003 a7c3e17b a7c3e17b a7c3e17b +(167/255)*255 43270000 fffffffd a5c3a77b a5c3a77b a5c3a77b +(167/255)*255 43270000 fffffffc a5c3e1a7 a5c3e1a7 a5c3e1a7 +(167/255)*255 43270000 80000002 a5a7e17b a5a7e17b a5a7e17b +(167/255)*255 43270000 00000103 a7c3e17b a7c3e17b a7c3e17b +(168/255)*255 43280000 00000000 a5c3e1a8 a5c3e1a8 a5c3e1a8 +(168/255)*255 43280000 00000001 a5c3a87b a5c3a87b a5c3a87b +(168/255)*255 43280000 00000002 a5a8e17b a5a8e17b a5a8e17b +(168/255)*255 43280000 00000003 a8c3e17b a8c3e17b a8c3e17b +(168/255)*255 43280000 fffffffd a5c3a87b a5c3a87b a5c3a87b +(168/255)*255 43280000 fffffffc a5c3e1a8 a5c3e1a8 a5c3e1a8 +(168/255)*255 43280000 80000002 a5a8e17b a5a8e17b a5a8e17b +(168/255)*255 43280000 00000103 a8c3e17b a8c3e17b a8c3e17b +(169/255)*255 43290000 00000000 a5c3e1a9 a5c3e1a9 a5c3e1a9 +(169/255)*255 43290000 00000001 a5c3a97b a5c3a97b a5c3a97b +(169/255)*255 43290000 00000002 a5a9e17b a5a9e17b a5a9e17b +(169/255)*255 43290000 00000003 a9c3e17b a9c3e17b a9c3e17b +(169/255)*255 43290000 fffffffd a5c3a97b a5c3a97b a5c3a97b +(169/255)*255 43290000 fffffffc a5c3e1a9 a5c3e1a9 a5c3e1a9 +(169/255)*255 43290000 80000002 a5a9e17b a5a9e17b a5a9e17b +(169/255)*255 43290000 00000103 a9c3e17b a9c3e17b a9c3e17b +(170/255)*255 432a0000 00000000 a5c3e1aa a5c3e1aa a5c3e1aa +(170/255)*255 432a0000 00000001 a5c3aa7b a5c3aa7b a5c3aa7b +(170/255)*255 432a0000 00000002 a5aae17b a5aae17b a5aae17b +(170/255)*255 432a0000 00000003 aac3e17b aac3e17b aac3e17b +(170/255)*255 432a0000 fffffffd a5c3aa7b a5c3aa7b a5c3aa7b +(170/255)*255 432a0000 fffffffc a5c3e1aa a5c3e1aa a5c3e1aa +(170/255)*255 432a0000 80000002 a5aae17b a5aae17b a5aae17b +(170/255)*255 432a0000 00000103 aac3e17b aac3e17b aac3e17b +(171/255)*255 432b0000 00000000 a5c3e1ab a5c3e1ab a5c3e1ab +(171/255)*255 432b0000 00000001 a5c3ab7b a5c3ab7b a5c3ab7b +(171/255)*255 432b0000 00000002 a5abe17b a5abe17b a5abe17b +(171/255)*255 432b0000 00000003 abc3e17b abc3e17b abc3e17b +(171/255)*255 432b0000 fffffffd a5c3ab7b a5c3ab7b a5c3ab7b +(171/255)*255 432b0000 fffffffc a5c3e1ab a5c3e1ab a5c3e1ab +(171/255)*255 432b0000 80000002 a5abe17b a5abe17b a5abe17b +(171/255)*255 432b0000 00000103 abc3e17b abc3e17b abc3e17b +(172/255)*255 432c0000 00000000 a5c3e1ac a5c3e1ac a5c3e1ac +(172/255)*255 432c0000 00000001 a5c3ac7b a5c3ac7b a5c3ac7b +(172/255)*255 432c0000 00000002 a5ace17b a5ace17b a5ace17b +(172/255)*255 432c0000 00000003 acc3e17b acc3e17b acc3e17b +(172/255)*255 432c0000 fffffffd a5c3ac7b a5c3ac7b a5c3ac7b +(172/255)*255 432c0000 fffffffc a5c3e1ac a5c3e1ac a5c3e1ac +(172/255)*255 432c0000 80000002 a5ace17b a5ace17b a5ace17b +(172/255)*255 432c0000 00000103 acc3e17b acc3e17b acc3e17b +(173/255)*255 432d0000 00000000 a5c3e1ad a5c3e1ad a5c3e1ad +(173/255)*255 432d0000 00000001 a5c3ad7b a5c3ad7b a5c3ad7b +(173/255)*255 432d0000 00000002 a5ade17b a5ade17b a5ade17b +(173/255)*255 432d0000 00000003 adc3e17b adc3e17b adc3e17b +(173/255)*255 432d0000 fffffffd a5c3ad7b a5c3ad7b a5c3ad7b +(173/255)*255 432d0000 fffffffc a5c3e1ad a5c3e1ad a5c3e1ad +(173/255)*255 432d0000 80000002 a5ade17b a5ade17b a5ade17b +(173/255)*255 432d0000 00000103 adc3e17b adc3e17b adc3e17b +(174/255)*255 432e0000 00000000 a5c3e1ae a5c3e1ae a5c3e1ae +(174/255)*255 432e0000 00000001 a5c3ae7b a5c3ae7b a5c3ae7b +(174/255)*255 432e0000 00000002 a5aee17b a5aee17b a5aee17b +(174/255)*255 432e0000 00000003 aec3e17b aec3e17b aec3e17b +(174/255)*255 432e0000 fffffffd a5c3ae7b a5c3ae7b a5c3ae7b +(174/255)*255 432e0000 fffffffc a5c3e1ae a5c3e1ae a5c3e1ae +(174/255)*255 432e0000 80000002 a5aee17b a5aee17b a5aee17b +(174/255)*255 432e0000 00000103 aec3e17b aec3e17b aec3e17b +(175/255)*255 432f0000 00000000 a5c3e1af a5c3e1af a5c3e1af +(175/255)*255 432f0000 00000001 a5c3af7b a5c3af7b a5c3af7b +(175/255)*255 432f0000 00000002 a5afe17b a5afe17b a5afe17b +(175/255)*255 432f0000 00000003 afc3e17b afc3e17b afc3e17b +(175/255)*255 432f0000 fffffffd a5c3af7b a5c3af7b a5c3af7b +(175/255)*255 432f0000 fffffffc a5c3e1af a5c3e1af a5c3e1af +(175/255)*255 432f0000 80000002 a5afe17b a5afe17b a5afe17b +(175/255)*255 432f0000 00000103 afc3e17b afc3e17b afc3e17b +(176/255)*255 43300000 00000000 a5c3e1b0 a5c3e1b0 a5c3e1b0 +(176/255)*255 43300000 00000001 a5c3b07b a5c3b07b a5c3b07b +(176/255)*255 43300000 00000002 a5b0e17b a5b0e17b a5b0e17b +(176/255)*255 43300000 00000003 b0c3e17b b0c3e17b b0c3e17b +(176/255)*255 43300000 fffffffd a5c3b07b a5c3b07b a5c3b07b +(176/255)*255 43300000 fffffffc a5c3e1b0 a5c3e1b0 a5c3e1b0 +(176/255)*255 43300000 80000002 a5b0e17b a5b0e17b a5b0e17b +(176/255)*255 43300000 00000103 b0c3e17b b0c3e17b b0c3e17b +(177/255)*255 43310000 00000000 a5c3e1b1 a5c3e1b1 a5c3e1b1 +(177/255)*255 43310000 00000001 a5c3b17b a5c3b17b a5c3b17b +(177/255)*255 43310000 00000002 a5b1e17b a5b1e17b a5b1e17b +(177/255)*255 43310000 00000003 b1c3e17b b1c3e17b b1c3e17b +(177/255)*255 43310000 fffffffd a5c3b17b a5c3b17b a5c3b17b +(177/255)*255 43310000 fffffffc a5c3e1b1 a5c3e1b1 a5c3e1b1 +(177/255)*255 43310000 80000002 a5b1e17b a5b1e17b a5b1e17b +(177/255)*255 43310000 00000103 b1c3e17b b1c3e17b b1c3e17b +(178/255)*255 43320000 00000000 a5c3e1b2 a5c3e1b2 a5c3e1b2 +(178/255)*255 43320000 00000001 a5c3b27b a5c3b27b a5c3b27b +(178/255)*255 43320000 00000002 a5b2e17b a5b2e17b a5b2e17b +(178/255)*255 43320000 00000003 b2c3e17b b2c3e17b b2c3e17b +(178/255)*255 43320000 fffffffd a5c3b27b a5c3b27b a5c3b27b +(178/255)*255 43320000 fffffffc a5c3e1b2 a5c3e1b2 a5c3e1b2 +(178/255)*255 43320000 80000002 a5b2e17b a5b2e17b a5b2e17b +(178/255)*255 43320000 00000103 b2c3e17b b2c3e17b b2c3e17b +(179/255)*255 43330000 00000000 a5c3e1b3 a5c3e1b3 a5c3e1b3 +(179/255)*255 43330000 00000001 a5c3b37b a5c3b37b a5c3b37b +(179/255)*255 43330000 00000002 a5b3e17b a5b3e17b a5b3e17b +(179/255)*255 43330000 00000003 b3c3e17b b3c3e17b b3c3e17b +(179/255)*255 43330000 fffffffd a5c3b37b a5c3b37b a5c3b37b +(179/255)*255 43330000 fffffffc a5c3e1b3 a5c3e1b3 a5c3e1b3 +(179/255)*255 43330000 80000002 a5b3e17b a5b3e17b a5b3e17b +(179/255)*255 43330000 00000103 b3c3e17b b3c3e17b b3c3e17b +(180/255)*255 43340000 00000000 a5c3e1b4 a5c3e1b4 a5c3e1b4 +(180/255)*255 43340000 00000001 a5c3b47b a5c3b47b a5c3b47b +(180/255)*255 43340000 00000002 a5b4e17b a5b4e17b a5b4e17b +(180/255)*255 43340000 00000003 b4c3e17b b4c3e17b b4c3e17b +(180/255)*255 43340000 fffffffd a5c3b47b a5c3b47b a5c3b47b +(180/255)*255 43340000 fffffffc a5c3e1b4 a5c3e1b4 a5c3e1b4 +(180/255)*255 43340000 80000002 a5b4e17b a5b4e17b a5b4e17b +(180/255)*255 43340000 00000103 b4c3e17b b4c3e17b b4c3e17b +(181/255)*255 43350000 00000000 a5c3e1b5 a5c3e1b5 a5c3e1b5 +(181/255)*255 43350000 00000001 a5c3b57b a5c3b57b a5c3b57b +(181/255)*255 43350000 00000002 a5b5e17b a5b5e17b a5b5e17b +(181/255)*255 43350000 00000003 b5c3e17b b5c3e17b b5c3e17b +(181/255)*255 43350000 fffffffd a5c3b57b a5c3b57b a5c3b57b +(181/255)*255 43350000 fffffffc a5c3e1b5 a5c3e1b5 a5c3e1b5 +(181/255)*255 43350000 80000002 a5b5e17b a5b5e17b a5b5e17b +(181/255)*255 43350000 00000103 b5c3e17b b5c3e17b b5c3e17b +(182/255)*255 43360000 00000000 a5c3e1b6 a5c3e1b6 a5c3e1b6 +(182/255)*255 43360000 00000001 a5c3b67b a5c3b67b a5c3b67b +(182/255)*255 43360000 00000002 a5b6e17b a5b6e17b a5b6e17b +(182/255)*255 43360000 00000003 b6c3e17b b6c3e17b b6c3e17b +(182/255)*255 43360000 fffffffd a5c3b67b a5c3b67b a5c3b67b +(182/255)*255 43360000 fffffffc a5c3e1b6 a5c3e1b6 a5c3e1b6 +(182/255)*255 43360000 80000002 a5b6e17b a5b6e17b a5b6e17b +(182/255)*255 43360000 00000103 b6c3e17b b6c3e17b b6c3e17b +(183/255)*255 43370000 00000000 a5c3e1b7 a5c3e1b7 a5c3e1b7 +(183/255)*255 43370000 00000001 a5c3b77b a5c3b77b a5c3b77b +(183/255)*255 43370000 00000002 a5b7e17b a5b7e17b a5b7e17b +(183/255)*255 43370000 00000003 b7c3e17b b7c3e17b b7c3e17b +(183/255)*255 43370000 fffffffd a5c3b77b a5c3b77b a5c3b77b +(183/255)*255 43370000 fffffffc a5c3e1b7 a5c3e1b7 a5c3e1b7 +(183/255)*255 43370000 80000002 a5b7e17b a5b7e17b a5b7e17b +(183/255)*255 43370000 00000103 b7c3e17b b7c3e17b b7c3e17b +(184/255)*255 43380000 00000000 a5c3e1b8 a5c3e1b8 a5c3e1b8 +(184/255)*255 43380000 00000001 a5c3b87b a5c3b87b a5c3b87b +(184/255)*255 43380000 00000002 a5b8e17b a5b8e17b a5b8e17b +(184/255)*255 43380000 00000003 b8c3e17b b8c3e17b b8c3e17b +(184/255)*255 43380000 fffffffd a5c3b87b a5c3b87b a5c3b87b +(184/255)*255 43380000 fffffffc a5c3e1b8 a5c3e1b8 a5c3e1b8 +(184/255)*255 43380000 80000002 a5b8e17b a5b8e17b a5b8e17b +(184/255)*255 43380000 00000103 b8c3e17b b8c3e17b b8c3e17b +(185/255)*255 43390000 00000000 a5c3e1b9 a5c3e1b9 a5c3e1b9 +(185/255)*255 43390000 00000001 a5c3b97b a5c3b97b a5c3b97b +(185/255)*255 43390000 00000002 a5b9e17b a5b9e17b a5b9e17b +(185/255)*255 43390000 00000003 b9c3e17b b9c3e17b b9c3e17b +(185/255)*255 43390000 fffffffd a5c3b97b a5c3b97b a5c3b97b +(185/255)*255 43390000 fffffffc a5c3e1b9 a5c3e1b9 a5c3e1b9 +(185/255)*255 43390000 80000002 a5b9e17b a5b9e17b a5b9e17b +(185/255)*255 43390000 00000103 b9c3e17b b9c3e17b b9c3e17b +(186/255)*255 433a0000 00000000 a5c3e1ba a5c3e1ba a5c3e1ba +(186/255)*255 433a0000 00000001 a5c3ba7b a5c3ba7b a5c3ba7b +(186/255)*255 433a0000 00000002 a5bae17b a5bae17b a5bae17b +(186/255)*255 433a0000 00000003 bac3e17b bac3e17b bac3e17b +(186/255)*255 433a0000 fffffffd a5c3ba7b a5c3ba7b a5c3ba7b +(186/255)*255 433a0000 fffffffc a5c3e1ba a5c3e1ba a5c3e1ba +(186/255)*255 433a0000 80000002 a5bae17b a5bae17b a5bae17b +(186/255)*255 433a0000 00000103 bac3e17b bac3e17b bac3e17b +(187/255)*255 433b0000 00000000 a5c3e1bb a5c3e1bb a5c3e1bb +(187/255)*255 433b0000 00000001 a5c3bb7b a5c3bb7b a5c3bb7b +(187/255)*255 433b0000 00000002 a5bbe17b a5bbe17b a5bbe17b +(187/255)*255 433b0000 00000003 bbc3e17b bbc3e17b bbc3e17b +(187/255)*255 433b0000 fffffffd a5c3bb7b a5c3bb7b a5c3bb7b +(187/255)*255 433b0000 fffffffc a5c3e1bb a5c3e1bb a5c3e1bb +(187/255)*255 433b0000 80000002 a5bbe17b a5bbe17b a5bbe17b +(187/255)*255 433b0000 00000103 bbc3e17b bbc3e17b bbc3e17b +(188/255)*255 433c0000 00000000 a5c3e1bc a5c3e1bc a5c3e1bc +(188/255)*255 433c0000 00000001 a5c3bc7b a5c3bc7b a5c3bc7b +(188/255)*255 433c0000 00000002 a5bce17b a5bce17b a5bce17b +(188/255)*255 433c0000 00000003 bcc3e17b bcc3e17b bcc3e17b +(188/255)*255 433c0000 fffffffd a5c3bc7b a5c3bc7b a5c3bc7b +(188/255)*255 433c0000 fffffffc a5c3e1bc a5c3e1bc a5c3e1bc +(188/255)*255 433c0000 80000002 a5bce17b a5bce17b a5bce17b +(188/255)*255 433c0000 00000103 bcc3e17b bcc3e17b bcc3e17b +(189/255)*255 433d0000 00000000 a5c3e1bd a5c3e1bd a5c3e1bd +(189/255)*255 433d0000 00000001 a5c3bd7b a5c3bd7b a5c3bd7b +(189/255)*255 433d0000 00000002 a5bde17b a5bde17b a5bde17b +(189/255)*255 433d0000 00000003 bdc3e17b bdc3e17b bdc3e17b +(189/255)*255 433d0000 fffffffd a5c3bd7b a5c3bd7b a5c3bd7b +(189/255)*255 433d0000 fffffffc a5c3e1bd a5c3e1bd a5c3e1bd +(189/255)*255 433d0000 80000002 a5bde17b a5bde17b a5bde17b +(189/255)*255 433d0000 00000103 bdc3e17b bdc3e17b bdc3e17b +(190/255)*255 433e0000 00000000 a5c3e1be a5c3e1be a5c3e1be +(190/255)*255 433e0000 00000001 a5c3be7b a5c3be7b a5c3be7b +(190/255)*255 433e0000 00000002 a5bee17b a5bee17b a5bee17b +(190/255)*255 433e0000 00000003 bec3e17b bec3e17b bec3e17b +(190/255)*255 433e0000 fffffffd a5c3be7b a5c3be7b a5c3be7b +(190/255)*255 433e0000 fffffffc a5c3e1be a5c3e1be a5c3e1be +(190/255)*255 433e0000 80000002 a5bee17b a5bee17b a5bee17b +(190/255)*255 433e0000 00000103 bec3e17b bec3e17b bec3e17b +(191/255)*255 433f0000 00000000 a5c3e1bf a5c3e1bf a5c3e1bf +(191/255)*255 433f0000 00000001 a5c3bf7b a5c3bf7b a5c3bf7b +(191/255)*255 433f0000 00000002 a5bfe17b a5bfe17b a5bfe17b +(191/255)*255 433f0000 00000003 bfc3e17b bfc3e17b bfc3e17b +(191/255)*255 433f0000 fffffffd a5c3bf7b a5c3bf7b a5c3bf7b +(191/255)*255 433f0000 fffffffc a5c3e1bf a5c3e1bf a5c3e1bf +(191/255)*255 433f0000 80000002 a5bfe17b a5bfe17b a5bfe17b +(191/255)*255 433f0000 00000103 bfc3e17b bfc3e17b bfc3e17b +(192/255)*255 43400000 00000000 a5c3e1c0 a5c3e1c0 a5c3e1c0 +(192/255)*255 43400000 00000001 a5c3c07b a5c3c07b a5c3c07b +(192/255)*255 43400000 00000002 a5c0e17b a5c0e17b a5c0e17b +(192/255)*255 43400000 00000003 c0c3e17b c0c3e17b c0c3e17b +(192/255)*255 43400000 fffffffd a5c3c07b a5c3c07b a5c3c07b +(192/255)*255 43400000 fffffffc a5c3e1c0 a5c3e1c0 a5c3e1c0 +(192/255)*255 43400000 80000002 a5c0e17b a5c0e17b a5c0e17b +(192/255)*255 43400000 00000103 c0c3e17b c0c3e17b c0c3e17b +(193/255)*255 43410000 00000000 a5c3e1c1 a5c3e1c1 a5c3e1c1 +(193/255)*255 43410000 00000001 a5c3c17b a5c3c17b a5c3c17b +(193/255)*255 43410000 00000002 a5c1e17b a5c1e17b a5c1e17b +(193/255)*255 43410000 00000003 c1c3e17b c1c3e17b c1c3e17b +(193/255)*255 43410000 fffffffd a5c3c17b a5c3c17b a5c3c17b +(193/255)*255 43410000 fffffffc a5c3e1c1 a5c3e1c1 a5c3e1c1 +(193/255)*255 43410000 80000002 a5c1e17b a5c1e17b a5c1e17b +(193/255)*255 43410000 00000103 c1c3e17b c1c3e17b c1c3e17b +(194/255)*255 43420000 00000000 a5c3e1c2 a5c3e1c2 a5c3e1c2 +(194/255)*255 43420000 00000001 a5c3c27b a5c3c27b a5c3c27b +(194/255)*255 43420000 00000002 a5c2e17b a5c2e17b a5c2e17b +(194/255)*255 43420000 00000003 c2c3e17b c2c3e17b c2c3e17b +(194/255)*255 43420000 fffffffd a5c3c27b a5c3c27b a5c3c27b +(194/255)*255 43420000 fffffffc a5c3e1c2 a5c3e1c2 a5c3e1c2 +(194/255)*255 43420000 80000002 a5c2e17b a5c2e17b a5c2e17b +(194/255)*255 43420000 00000103 c2c3e17b c2c3e17b c2c3e17b +(195/255)*255 43430000 00000000 a5c3e1c3 a5c3e1c3 a5c3e1c3 +(195/255)*255 43430000 00000001 a5c3c37b a5c3c37b a5c3c37b +(195/255)*255 43430000 00000002 a5c3e17b a5c3e17b a5c3e17b +(195/255)*255 43430000 00000003 c3c3e17b c3c3e17b c3c3e17b +(195/255)*255 43430000 fffffffd a5c3c37b a5c3c37b a5c3c37b +(195/255)*255 43430000 fffffffc a5c3e1c3 a5c3e1c3 a5c3e1c3 +(195/255)*255 43430000 80000002 a5c3e17b a5c3e17b a5c3e17b +(195/255)*255 43430000 00000103 c3c3e17b c3c3e17b c3c3e17b +(196/255)*255 43440000 00000000 a5c3e1c4 a5c3e1c4 a5c3e1c4 +(196/255)*255 43440000 00000001 a5c3c47b a5c3c47b a5c3c47b +(196/255)*255 43440000 00000002 a5c4e17b a5c4e17b a5c4e17b +(196/255)*255 43440000 00000003 c4c3e17b c4c3e17b c4c3e17b +(196/255)*255 43440000 fffffffd a5c3c47b a5c3c47b a5c3c47b +(196/255)*255 43440000 fffffffc a5c3e1c4 a5c3e1c4 a5c3e1c4 +(196/255)*255 43440000 80000002 a5c4e17b a5c4e17b a5c4e17b +(196/255)*255 43440000 00000103 c4c3e17b c4c3e17b c4c3e17b +(197/255)*255 43450000 00000000 a5c3e1c5 a5c3e1c5 a5c3e1c5 +(197/255)*255 43450000 00000001 a5c3c57b a5c3c57b a5c3c57b +(197/255)*255 43450000 00000002 a5c5e17b a5c5e17b a5c5e17b +(197/255)*255 43450000 00000003 c5c3e17b c5c3e17b c5c3e17b +(197/255)*255 43450000 fffffffd a5c3c57b a5c3c57b a5c3c57b +(197/255)*255 43450000 fffffffc a5c3e1c5 a5c3e1c5 a5c3e1c5 +(197/255)*255 43450000 80000002 a5c5e17b a5c5e17b a5c5e17b +(197/255)*255 43450000 00000103 c5c3e17b c5c3e17b c5c3e17b +(198/255)*255 43460000 00000000 a5c3e1c6 a5c3e1c6 a5c3e1c6 +(198/255)*255 43460000 00000001 a5c3c67b a5c3c67b a5c3c67b +(198/255)*255 43460000 00000002 a5c6e17b a5c6e17b a5c6e17b +(198/255)*255 43460000 00000003 c6c3e17b c6c3e17b c6c3e17b +(198/255)*255 43460000 fffffffd a5c3c67b a5c3c67b a5c3c67b +(198/255)*255 43460000 fffffffc a5c3e1c6 a5c3e1c6 a5c3e1c6 +(198/255)*255 43460000 80000002 a5c6e17b a5c6e17b a5c6e17b +(198/255)*255 43460000 00000103 c6c3e17b c6c3e17b c6c3e17b +(199/255)*255 43470000 00000000 a5c3e1c7 a5c3e1c7 a5c3e1c7 +(199/255)*255 43470000 00000001 a5c3c77b a5c3c77b a5c3c77b +(199/255)*255 43470000 00000002 a5c7e17b a5c7e17b a5c7e17b +(199/255)*255 43470000 00000003 c7c3e17b c7c3e17b c7c3e17b +(199/255)*255 43470000 fffffffd a5c3c77b a5c3c77b a5c3c77b +(199/255)*255 43470000 fffffffc a5c3e1c7 a5c3e1c7 a5c3e1c7 +(199/255)*255 43470000 80000002 a5c7e17b a5c7e17b a5c7e17b +(199/255)*255 43470000 00000103 c7c3e17b c7c3e17b c7c3e17b +(201/255)*255 43490000 00000000 a5c3e1c9 a5c3e1c9 a5c3e1c9 +(201/255)*255 43490000 00000001 a5c3c97b a5c3c97b a5c3c97b +(201/255)*255 43490000 00000002 a5c9e17b a5c9e17b a5c9e17b +(201/255)*255 43490000 00000003 c9c3e17b c9c3e17b c9c3e17b +(201/255)*255 43490000 fffffffd a5c3c97b a5c3c97b a5c3c97b +(201/255)*255 43490000 fffffffc a5c3e1c9 a5c3e1c9 a5c3e1c9 +(201/255)*255 43490000 80000002 a5c9e17b a5c9e17b a5c9e17b +(201/255)*255 43490000 00000103 c9c3e17b c9c3e17b c9c3e17b +(202/255)*255 434a0000 00000000 a5c3e1ca a5c3e1ca a5c3e1ca +(202/255)*255 434a0000 00000001 a5c3ca7b a5c3ca7b a5c3ca7b +(202/255)*255 434a0000 00000002 a5cae17b a5cae17b a5cae17b +(202/255)*255 434a0000 00000003 cac3e17b cac3e17b cac3e17b +(202/255)*255 434a0000 fffffffd a5c3ca7b a5c3ca7b a5c3ca7b +(202/255)*255 434a0000 fffffffc a5c3e1ca a5c3e1ca a5c3e1ca +(202/255)*255 434a0000 80000002 a5cae17b a5cae17b a5cae17b +(202/255)*255 434a0000 00000103 cac3e17b cac3e17b cac3e17b +(203/255)*255 434b0000 00000000 a5c3e1cb a5c3e1cb a5c3e1cb +(203/255)*255 434b0000 00000001 a5c3cb7b a5c3cb7b a5c3cb7b +(203/255)*255 434b0000 00000002 a5cbe17b a5cbe17b a5cbe17b +(203/255)*255 434b0000 00000003 cbc3e17b cbc3e17b cbc3e17b +(203/255)*255 434b0000 fffffffd a5c3cb7b a5c3cb7b a5c3cb7b +(203/255)*255 434b0000 fffffffc a5c3e1cb a5c3e1cb a5c3e1cb +(203/255)*255 434b0000 80000002 a5cbe17b a5cbe17b a5cbe17b +(203/255)*255 434b0000 00000103 cbc3e17b cbc3e17b cbc3e17b +(204/255)*255 434c0000 00000000 a5c3e1cc a5c3e1cc a5c3e1cc +(204/255)*255 434c0000 00000001 a5c3cc7b a5c3cc7b a5c3cc7b +(204/255)*255 434c0000 00000002 a5cce17b a5cce17b a5cce17b +(204/255)*255 434c0000 00000003 ccc3e17b ccc3e17b ccc3e17b +(204/255)*255 434c0000 fffffffd a5c3cc7b a5c3cc7b a5c3cc7b +(204/255)*255 434c0000 fffffffc a5c3e1cc a5c3e1cc a5c3e1cc +(204/255)*255 434c0000 80000002 a5cce17b a5cce17b a5cce17b +(204/255)*255 434c0000 00000103 ccc3e17b ccc3e17b ccc3e17b +(205/255)*255 434d0000 00000000 a5c3e1cd a5c3e1cd a5c3e1cd +(205/255)*255 434d0000 00000001 a5c3cd7b a5c3cd7b a5c3cd7b +(205/255)*255 434d0000 00000002 a5cde17b a5cde17b a5cde17b +(205/255)*255 434d0000 00000003 cdc3e17b cdc3e17b cdc3e17b +(205/255)*255 434d0000 fffffffd a5c3cd7b a5c3cd7b a5c3cd7b +(205/255)*255 434d0000 fffffffc a5c3e1cd a5c3e1cd a5c3e1cd +(205/255)*255 434d0000 80000002 a5cde17b a5cde17b a5cde17b +(205/255)*255 434d0000 00000103 cdc3e17b cdc3e17b cdc3e17b +(206/255)*255 434e0000 00000000 a5c3e1ce a5c3e1ce a5c3e1ce +(206/255)*255 434e0000 00000001 a5c3ce7b a5c3ce7b a5c3ce7b +(206/255)*255 434e0000 00000002 a5cee17b a5cee17b a5cee17b +(206/255)*255 434e0000 00000003 cec3e17b cec3e17b cec3e17b +(206/255)*255 434e0000 fffffffd a5c3ce7b a5c3ce7b a5c3ce7b +(206/255)*255 434e0000 fffffffc a5c3e1ce a5c3e1ce a5c3e1ce +(206/255)*255 434e0000 80000002 a5cee17b a5cee17b a5cee17b +(206/255)*255 434e0000 00000103 cec3e17b cec3e17b cec3e17b +(207/255)*255 434f0000 00000000 a5c3e1cf a5c3e1cf a5c3e1cf +(207/255)*255 434f0000 00000001 a5c3cf7b a5c3cf7b a5c3cf7b +(207/255)*255 434f0000 00000002 a5cfe17b a5cfe17b a5cfe17b +(207/255)*255 434f0000 00000003 cfc3e17b cfc3e17b cfc3e17b +(207/255)*255 434f0000 fffffffd a5c3cf7b a5c3cf7b a5c3cf7b +(207/255)*255 434f0000 fffffffc a5c3e1cf a5c3e1cf a5c3e1cf +(207/255)*255 434f0000 80000002 a5cfe17b a5cfe17b a5cfe17b +(207/255)*255 434f0000 00000103 cfc3e17b cfc3e17b cfc3e17b +(208/255)*255 43500000 00000000 a5c3e1d0 a5c3e1d0 a5c3e1d0 +(208/255)*255 43500000 00000001 a5c3d07b a5c3d07b a5c3d07b +(208/255)*255 43500000 00000002 a5d0e17b a5d0e17b a5d0e17b +(208/255)*255 43500000 00000003 d0c3e17b d0c3e17b d0c3e17b +(208/255)*255 43500000 fffffffd a5c3d07b a5c3d07b a5c3d07b +(208/255)*255 43500000 fffffffc a5c3e1d0 a5c3e1d0 a5c3e1d0 +(208/255)*255 43500000 80000002 a5d0e17b a5d0e17b a5d0e17b +(208/255)*255 43500000 00000103 d0c3e17b d0c3e17b d0c3e17b +(209/255)*255 43510000 00000000 a5c3e1d1 a5c3e1d1 a5c3e1d1 +(209/255)*255 43510000 00000001 a5c3d17b a5c3d17b a5c3d17b +(209/255)*255 43510000 00000002 a5d1e17b a5d1e17b a5d1e17b +(209/255)*255 43510000 00000003 d1c3e17b d1c3e17b d1c3e17b +(209/255)*255 43510000 fffffffd a5c3d17b a5c3d17b a5c3d17b +(209/255)*255 43510000 fffffffc a5c3e1d1 a5c3e1d1 a5c3e1d1 +(209/255)*255 43510000 80000002 a5d1e17b a5d1e17b a5d1e17b +(209/255)*255 43510000 00000103 d1c3e17b d1c3e17b d1c3e17b +(210/255)*255 43520000 00000000 a5c3e1d2 a5c3e1d2 a5c3e1d2 +(210/255)*255 43520000 00000001 a5c3d27b a5c3d27b a5c3d27b +(210/255)*255 43520000 00000002 a5d2e17b a5d2e17b a5d2e17b +(210/255)*255 43520000 00000003 d2c3e17b d2c3e17b d2c3e17b +(210/255)*255 43520000 fffffffd a5c3d27b a5c3d27b a5c3d27b +(210/255)*255 43520000 fffffffc a5c3e1d2 a5c3e1d2 a5c3e1d2 +(210/255)*255 43520000 80000002 a5d2e17b a5d2e17b a5d2e17b +(210/255)*255 43520000 00000103 d2c3e17b d2c3e17b d2c3e17b +(211/255)*255 43530000 00000000 a5c3e1d3 a5c3e1d3 a5c3e1d3 +(211/255)*255 43530000 00000001 a5c3d37b a5c3d37b a5c3d37b +(211/255)*255 43530000 00000002 a5d3e17b a5d3e17b a5d3e17b +(211/255)*255 43530000 00000003 d3c3e17b d3c3e17b d3c3e17b +(211/255)*255 43530000 fffffffd a5c3d37b a5c3d37b a5c3d37b +(211/255)*255 43530000 fffffffc a5c3e1d3 a5c3e1d3 a5c3e1d3 +(211/255)*255 43530000 80000002 a5d3e17b a5d3e17b a5d3e17b +(211/255)*255 43530000 00000103 d3c3e17b d3c3e17b d3c3e17b +(212/255)*255 43540000 00000000 a5c3e1d4 a5c3e1d4 a5c3e1d4 +(212/255)*255 43540000 00000001 a5c3d47b a5c3d47b a5c3d47b +(212/255)*255 43540000 00000002 a5d4e17b a5d4e17b a5d4e17b +(212/255)*255 43540000 00000003 d4c3e17b d4c3e17b d4c3e17b +(212/255)*255 43540000 fffffffd a5c3d47b a5c3d47b a5c3d47b +(212/255)*255 43540000 fffffffc a5c3e1d4 a5c3e1d4 a5c3e1d4 +(212/255)*255 43540000 80000002 a5d4e17b a5d4e17b a5d4e17b +(212/255)*255 43540000 00000103 d4c3e17b d4c3e17b d4c3e17b +(213/255)*255 43550000 00000000 a5c3e1d5 a5c3e1d5 a5c3e1d5 +(213/255)*255 43550000 00000001 a5c3d57b a5c3d57b a5c3d57b +(213/255)*255 43550000 00000002 a5d5e17b a5d5e17b a5d5e17b +(213/255)*255 43550000 00000003 d5c3e17b d5c3e17b d5c3e17b +(213/255)*255 43550000 fffffffd a5c3d57b a5c3d57b a5c3d57b +(213/255)*255 43550000 fffffffc a5c3e1d5 a5c3e1d5 a5c3e1d5 +(213/255)*255 43550000 80000002 a5d5e17b a5d5e17b a5d5e17b +(213/255)*255 43550000 00000103 d5c3e17b d5c3e17b d5c3e17b +(214/255)*255 43560000 00000000 a5c3e1d6 a5c3e1d6 a5c3e1d6 +(214/255)*255 43560000 00000001 a5c3d67b a5c3d67b a5c3d67b +(214/255)*255 43560000 00000002 a5d6e17b a5d6e17b a5d6e17b +(214/255)*255 43560000 00000003 d6c3e17b d6c3e17b d6c3e17b +(214/255)*255 43560000 fffffffd a5c3d67b a5c3d67b a5c3d67b +(214/255)*255 43560000 fffffffc a5c3e1d6 a5c3e1d6 a5c3e1d6 +(214/255)*255 43560000 80000002 a5d6e17b a5d6e17b a5d6e17b +(214/255)*255 43560000 00000103 d6c3e17b d6c3e17b d6c3e17b +(215/255)*255 43570000 00000000 a5c3e1d7 a5c3e1d7 a5c3e1d7 +(215/255)*255 43570000 00000001 a5c3d77b a5c3d77b a5c3d77b +(215/255)*255 43570000 00000002 a5d7e17b a5d7e17b a5d7e17b +(215/255)*255 43570000 00000003 d7c3e17b d7c3e17b d7c3e17b +(215/255)*255 43570000 fffffffd a5c3d77b a5c3d77b a5c3d77b +(215/255)*255 43570000 fffffffc a5c3e1d7 a5c3e1d7 a5c3e1d7 +(215/255)*255 43570000 80000002 a5d7e17b a5d7e17b a5d7e17b +(215/255)*255 43570000 00000103 d7c3e17b d7c3e17b d7c3e17b +(216/255)*255 43580000 00000000 a5c3e1d8 a5c3e1d8 a5c3e1d8 +(216/255)*255 43580000 00000001 a5c3d87b a5c3d87b a5c3d87b +(216/255)*255 43580000 00000002 a5d8e17b a5d8e17b a5d8e17b +(216/255)*255 43580000 00000003 d8c3e17b d8c3e17b d8c3e17b +(216/255)*255 43580000 fffffffd a5c3d87b a5c3d87b a5c3d87b +(216/255)*255 43580000 fffffffc a5c3e1d8 a5c3e1d8 a5c3e1d8 +(216/255)*255 43580000 80000002 a5d8e17b a5d8e17b a5d8e17b +(216/255)*255 43580000 00000103 d8c3e17b d8c3e17b d8c3e17b +(217/255)*255 43590000 00000000 a5c3e1d9 a5c3e1d9 a5c3e1d9 +(217/255)*255 43590000 00000001 a5c3d97b a5c3d97b a5c3d97b +(217/255)*255 43590000 00000002 a5d9e17b a5d9e17b a5d9e17b +(217/255)*255 43590000 00000003 d9c3e17b d9c3e17b d9c3e17b +(217/255)*255 43590000 fffffffd a5c3d97b a5c3d97b a5c3d97b +(217/255)*255 43590000 fffffffc a5c3e1d9 a5c3e1d9 a5c3e1d9 +(217/255)*255 43590000 80000002 a5d9e17b a5d9e17b a5d9e17b +(217/255)*255 43590000 00000103 d9c3e17b d9c3e17b d9c3e17b +(218/255)*255 435a0000 00000000 a5c3e1da a5c3e1da a5c3e1da +(218/255)*255 435a0000 00000001 a5c3da7b a5c3da7b a5c3da7b +(218/255)*255 435a0000 00000002 a5dae17b a5dae17b a5dae17b +(218/255)*255 435a0000 00000003 dac3e17b dac3e17b dac3e17b +(218/255)*255 435a0000 fffffffd a5c3da7b a5c3da7b a5c3da7b +(218/255)*255 435a0000 fffffffc a5c3e1da a5c3e1da a5c3e1da +(218/255)*255 435a0000 80000002 a5dae17b a5dae17b a5dae17b +(218/255)*255 435a0000 00000103 dac3e17b dac3e17b dac3e17b +(219/255)*255 435b0000 00000000 a5c3e1db a5c3e1db a5c3e1db +(219/255)*255 435b0000 00000001 a5c3db7b a5c3db7b a5c3db7b +(219/255)*255 435b0000 00000002 a5dbe17b a5dbe17b a5dbe17b +(219/255)*255 435b0000 00000003 dbc3e17b dbc3e17b dbc3e17b +(219/255)*255 435b0000 fffffffd a5c3db7b a5c3db7b a5c3db7b +(219/255)*255 435b0000 fffffffc a5c3e1db a5c3e1db a5c3e1db +(219/255)*255 435b0000 80000002 a5dbe17b a5dbe17b a5dbe17b +(219/255)*255 435b0000 00000103 dbc3e17b dbc3e17b dbc3e17b +(220/255)*255 435c0000 00000000 a5c3e1dc a5c3e1dc a5c3e1dc +(220/255)*255 435c0000 00000001 a5c3dc7b a5c3dc7b a5c3dc7b +(220/255)*255 435c0000 00000002 a5dce17b a5dce17b a5dce17b +(220/255)*255 435c0000 00000003 dcc3e17b dcc3e17b dcc3e17b +(220/255)*255 435c0000 fffffffd a5c3dc7b a5c3dc7b a5c3dc7b +(220/255)*255 435c0000 fffffffc a5c3e1dc a5c3e1dc a5c3e1dc +(220/255)*255 435c0000 80000002 a5dce17b a5dce17b a5dce17b +(220/255)*255 435c0000 00000103 dcc3e17b dcc3e17b dcc3e17b +(221/255)*255 435d0000 00000000 a5c3e1dd a5c3e1dd a5c3e1dd +(221/255)*255 435d0000 00000001 a5c3dd7b a5c3dd7b a5c3dd7b +(221/255)*255 435d0000 00000002 a5dde17b a5dde17b a5dde17b +(221/255)*255 435d0000 00000003 ddc3e17b ddc3e17b ddc3e17b +(221/255)*255 435d0000 fffffffd a5c3dd7b a5c3dd7b a5c3dd7b +(221/255)*255 435d0000 fffffffc a5c3e1dd a5c3e1dd a5c3e1dd +(221/255)*255 435d0000 80000002 a5dde17b a5dde17b a5dde17b +(221/255)*255 435d0000 00000103 ddc3e17b ddc3e17b ddc3e17b +(222/255)*255 435e0000 00000000 a5c3e1de a5c3e1de a5c3e1de +(222/255)*255 435e0000 00000001 a5c3de7b a5c3de7b a5c3de7b +(222/255)*255 435e0000 00000002 a5dee17b a5dee17b a5dee17b +(222/255)*255 435e0000 00000003 dec3e17b dec3e17b dec3e17b +(222/255)*255 435e0000 fffffffd a5c3de7b a5c3de7b a5c3de7b +(222/255)*255 435e0000 fffffffc a5c3e1de a5c3e1de a5c3e1de +(222/255)*255 435e0000 80000002 a5dee17b a5dee17b a5dee17b +(222/255)*255 435e0000 00000103 dec3e17b dec3e17b dec3e17b +(223/255)*255 435f0000 00000000 a5c3e1df a5c3e1df a5c3e1df +(223/255)*255 435f0000 00000001 a5c3df7b a5c3df7b a5c3df7b +(223/255)*255 435f0000 00000002 a5dfe17b a5dfe17b a5dfe17b +(223/255)*255 435f0000 00000003 dfc3e17b dfc3e17b dfc3e17b +(223/255)*255 435f0000 fffffffd a5c3df7b a5c3df7b a5c3df7b +(223/255)*255 435f0000 fffffffc a5c3e1df a5c3e1df a5c3e1df +(223/255)*255 435f0000 80000002 a5dfe17b a5dfe17b a5dfe17b +(223/255)*255 435f0000 00000103 dfc3e17b dfc3e17b dfc3e17b +(224/255)*255 43600000 00000000 a5c3e1e0 a5c3e1e0 a5c3e1e0 +(224/255)*255 43600000 00000001 a5c3e07b a5c3e07b a5c3e07b +(224/255)*255 43600000 00000002 a5e0e17b a5e0e17b a5e0e17b +(224/255)*255 43600000 00000003 e0c3e17b e0c3e17b e0c3e17b +(224/255)*255 43600000 fffffffd a5c3e07b a5c3e07b a5c3e07b +(224/255)*255 43600000 fffffffc a5c3e1e0 a5c3e1e0 a5c3e1e0 +(224/255)*255 43600000 80000002 a5e0e17b a5e0e17b a5e0e17b +(224/255)*255 43600000 00000103 e0c3e17b e0c3e17b e0c3e17b +(225/255)*255 43610000 00000000 a5c3e1e1 a5c3e1e1 a5c3e1e1 +(225/255)*255 43610000 00000001 a5c3e17b a5c3e17b a5c3e17b +(225/255)*255 43610000 00000002 a5e1e17b a5e1e17b a5e1e17b +(225/255)*255 43610000 00000003 e1c3e17b e1c3e17b e1c3e17b +(225/255)*255 43610000 fffffffd a5c3e17b a5c3e17b a5c3e17b +(225/255)*255 43610000 fffffffc a5c3e1e1 a5c3e1e1 a5c3e1e1 +(225/255)*255 43610000 80000002 a5e1e17b a5e1e17b a5e1e17b +(225/255)*255 43610000 00000103 e1c3e17b e1c3e17b e1c3e17b +(226/255)*255 43620000 00000000 a5c3e1e2 a5c3e1e2 a5c3e1e2 +(226/255)*255 43620000 00000001 a5c3e27b a5c3e27b a5c3e27b +(226/255)*255 43620000 00000002 a5e2e17b a5e2e17b a5e2e17b +(226/255)*255 43620000 00000003 e2c3e17b e2c3e17b e2c3e17b +(226/255)*255 43620000 fffffffd a5c3e27b a5c3e27b a5c3e27b +(226/255)*255 43620000 fffffffc a5c3e1e2 a5c3e1e2 a5c3e1e2 +(226/255)*255 43620000 80000002 a5e2e17b a5e2e17b a5e2e17b +(226/255)*255 43620000 00000103 e2c3e17b e2c3e17b e2c3e17b +(227/255)*255 43630000 00000000 a5c3e1e3 a5c3e1e3 a5c3e1e3 +(227/255)*255 43630000 00000001 a5c3e37b a5c3e37b a5c3e37b +(227/255)*255 43630000 00000002 a5e3e17b a5e3e17b a5e3e17b +(227/255)*255 43630000 00000003 e3c3e17b e3c3e17b e3c3e17b +(227/255)*255 43630000 fffffffd a5c3e37b a5c3e37b a5c3e37b +(227/255)*255 43630000 fffffffc a5c3e1e3 a5c3e1e3 a5c3e1e3 +(227/255)*255 43630000 80000002 a5e3e17b a5e3e17b a5e3e17b +(227/255)*255 43630000 00000103 e3c3e17b e3c3e17b e3c3e17b +(228/255)*255 43640000 00000000 a5c3e1e4 a5c3e1e4 a5c3e1e4 +(228/255)*255 43640000 00000001 a5c3e47b a5c3e47b a5c3e47b +(228/255)*255 43640000 00000002 a5e4e17b a5e4e17b a5e4e17b +(228/255)*255 43640000 00000003 e4c3e17b e4c3e17b e4c3e17b +(228/255)*255 43640000 fffffffd a5c3e47b a5c3e47b a5c3e47b +(228/255)*255 43640000 fffffffc a5c3e1e4 a5c3e1e4 a5c3e1e4 +(228/255)*255 43640000 80000002 a5e4e17b a5e4e17b a5e4e17b +(228/255)*255 43640000 00000103 e4c3e17b e4c3e17b e4c3e17b +(229/255)*255 43650000 00000000 a5c3e1e5 a5c3e1e5 a5c3e1e5 +(229/255)*255 43650000 00000001 a5c3e57b a5c3e57b a5c3e57b +(229/255)*255 43650000 00000002 a5e5e17b a5e5e17b a5e5e17b +(229/255)*255 43650000 00000003 e5c3e17b e5c3e17b e5c3e17b +(229/255)*255 43650000 fffffffd a5c3e57b a5c3e57b a5c3e57b +(229/255)*255 43650000 fffffffc a5c3e1e5 a5c3e1e5 a5c3e1e5 +(229/255)*255 43650000 80000002 a5e5e17b a5e5e17b a5e5e17b +(229/255)*255 43650000 00000103 e5c3e17b e5c3e17b e5c3e17b +(230/255)*255 43660000 00000000 a5c3e1e6 a5c3e1e6 a5c3e1e6 +(230/255)*255 43660000 00000001 a5c3e67b a5c3e67b a5c3e67b +(230/255)*255 43660000 00000002 a5e6e17b a5e6e17b a5e6e17b +(230/255)*255 43660000 00000003 e6c3e17b e6c3e17b e6c3e17b +(230/255)*255 43660000 fffffffd a5c3e67b a5c3e67b a5c3e67b +(230/255)*255 43660000 fffffffc a5c3e1e6 a5c3e1e6 a5c3e1e6 +(230/255)*255 43660000 80000002 a5e6e17b a5e6e17b a5e6e17b +(230/255)*255 43660000 00000103 e6c3e17b e6c3e17b e6c3e17b +(231/255)*255 43670000 00000000 a5c3e1e7 a5c3e1e7 a5c3e1e7 +(231/255)*255 43670000 00000001 a5c3e77b a5c3e77b a5c3e77b +(231/255)*255 43670000 00000002 a5e7e17b a5e7e17b a5e7e17b +(231/255)*255 43670000 00000003 e7c3e17b e7c3e17b e7c3e17b +(231/255)*255 43670000 fffffffd a5c3e77b a5c3e77b a5c3e77b +(231/255)*255 43670000 fffffffc a5c3e1e7 a5c3e1e7 a5c3e1e7 +(231/255)*255 43670000 80000002 a5e7e17b a5e7e17b a5e7e17b +(231/255)*255 43670000 00000103 e7c3e17b e7c3e17b e7c3e17b +(232/255)*255 43680000 00000000 a5c3e1e8 a5c3e1e8 a5c3e1e8 +(232/255)*255 43680000 00000001 a5c3e87b a5c3e87b a5c3e87b +(232/255)*255 43680000 00000002 a5e8e17b a5e8e17b a5e8e17b +(232/255)*255 43680000 00000003 e8c3e17b e8c3e17b e8c3e17b +(232/255)*255 43680000 fffffffd a5c3e87b a5c3e87b a5c3e87b +(232/255)*255 43680000 fffffffc a5c3e1e8 a5c3e1e8 a5c3e1e8 +(232/255)*255 43680000 80000002 a5e8e17b a5e8e17b a5e8e17b +(232/255)*255 43680000 00000103 e8c3e17b e8c3e17b e8c3e17b +(233/255)*255 43690000 00000000 a5c3e1e9 a5c3e1e9 a5c3e1e9 +(233/255)*255 43690000 00000001 a5c3e97b a5c3e97b a5c3e97b +(233/255)*255 43690000 00000002 a5e9e17b a5e9e17b a5e9e17b +(233/255)*255 43690000 00000003 e9c3e17b e9c3e17b e9c3e17b +(233/255)*255 43690000 fffffffd a5c3e97b a5c3e97b a5c3e97b +(233/255)*255 43690000 fffffffc a5c3e1e9 a5c3e1e9 a5c3e1e9 +(233/255)*255 43690000 80000002 a5e9e17b a5e9e17b a5e9e17b +(233/255)*255 43690000 00000103 e9c3e17b e9c3e17b e9c3e17b +(234/255)*255 436a0000 00000000 a5c3e1ea a5c3e1ea a5c3e1ea +(234/255)*255 436a0000 00000001 a5c3ea7b a5c3ea7b a5c3ea7b +(234/255)*255 436a0000 00000002 a5eae17b a5eae17b a5eae17b +(234/255)*255 436a0000 00000003 eac3e17b eac3e17b eac3e17b +(234/255)*255 436a0000 fffffffd a5c3ea7b a5c3ea7b a5c3ea7b +(234/255)*255 436a0000 fffffffc a5c3e1ea a5c3e1ea a5c3e1ea +(234/255)*255 436a0000 80000002 a5eae17b a5eae17b a5eae17b +(234/255)*255 436a0000 00000103 eac3e17b eac3e17b eac3e17b +(235/255)*255 436b0000 00000000 a5c3e1eb a5c3e1eb a5c3e1eb +(235/255)*255 436b0000 00000001 a5c3eb7b a5c3eb7b a5c3eb7b +(235/255)*255 436b0000 00000002 a5ebe17b a5ebe17b a5ebe17b +(235/255)*255 436b0000 00000003 ebc3e17b ebc3e17b ebc3e17b +(235/255)*255 436b0000 fffffffd a5c3eb7b a5c3eb7b a5c3eb7b +(235/255)*255 436b0000 fffffffc a5c3e1eb a5c3e1eb a5c3e1eb +(235/255)*255 436b0000 80000002 a5ebe17b a5ebe17b a5ebe17b +(235/255)*255 436b0000 00000103 ebc3e17b ebc3e17b ebc3e17b +(236/255)*255 436c0000 00000000 a5c3e1ec a5c3e1ec a5c3e1ec +(236/255)*255 436c0000 00000001 a5c3ec7b a5c3ec7b a5c3ec7b +(236/255)*255 436c0000 00000002 a5ece17b a5ece17b a5ece17b +(236/255)*255 436c0000 00000003 ecc3e17b ecc3e17b ecc3e17b +(236/255)*255 436c0000 fffffffd a5c3ec7b a5c3ec7b a5c3ec7b +(236/255)*255 436c0000 fffffffc a5c3e1ec a5c3e1ec a5c3e1ec +(236/255)*255 436c0000 80000002 a5ece17b a5ece17b a5ece17b +(236/255)*255 436c0000 00000103 ecc3e17b ecc3e17b ecc3e17b +(237/255)*255 436d0000 00000000 a5c3e1ed a5c3e1ed a5c3e1ed +(237/255)*255 436d0000 00000001 a5c3ed7b a5c3ed7b a5c3ed7b +(237/255)*255 436d0000 00000002 a5ede17b a5ede17b a5ede17b +(237/255)*255 436d0000 00000003 edc3e17b edc3e17b edc3e17b +(237/255)*255 436d0000 fffffffd a5c3ed7b a5c3ed7b a5c3ed7b +(237/255)*255 436d0000 fffffffc a5c3e1ed a5c3e1ed a5c3e1ed +(237/255)*255 436d0000 80000002 a5ede17b a5ede17b a5ede17b +(237/255)*255 436d0000 00000103 edc3e17b edc3e17b edc3e17b +(238/255)*255 436e0000 00000000 a5c3e1ee a5c3e1ee a5c3e1ee +(238/255)*255 436e0000 00000001 a5c3ee7b a5c3ee7b a5c3ee7b +(238/255)*255 436e0000 00000002 a5eee17b a5eee17b a5eee17b +(238/255)*255 436e0000 00000003 eec3e17b eec3e17b eec3e17b +(238/255)*255 436e0000 fffffffd a5c3ee7b a5c3ee7b a5c3ee7b +(238/255)*255 436e0000 fffffffc a5c3e1ee a5c3e1ee a5c3e1ee +(238/255)*255 436e0000 80000002 a5eee17b a5eee17b a5eee17b +(238/255)*255 436e0000 00000103 eec3e17b eec3e17b eec3e17b +(239/255)*255 436f0000 00000000 a5c3e1ef a5c3e1ef a5c3e1ef +(239/255)*255 436f0000 00000001 a5c3ef7b a5c3ef7b a5c3ef7b +(239/255)*255 436f0000 00000002 a5efe17b a5efe17b a5efe17b +(239/255)*255 436f0000 00000003 efc3e17b efc3e17b efc3e17b +(239/255)*255 436f0000 fffffffd a5c3ef7b a5c3ef7b a5c3ef7b +(239/255)*255 436f0000 fffffffc a5c3e1ef a5c3e1ef a5c3e1ef +(239/255)*255 436f0000 80000002 a5efe17b a5efe17b a5efe17b +(239/255)*255 436f0000 00000103 efc3e17b efc3e17b efc3e17b +(240/255)*255 43700000 00000000 a5c3e1f0 a5c3e1f0 a5c3e1f0 +(240/255)*255 43700000 00000001 a5c3f07b a5c3f07b a5c3f07b +(240/255)*255 43700000 00000002 a5f0e17b a5f0e17b a5f0e17b +(240/255)*255 43700000 00000003 f0c3e17b f0c3e17b f0c3e17b +(240/255)*255 43700000 fffffffd a5c3f07b a5c3f07b a5c3f07b +(240/255)*255 43700000 fffffffc a5c3e1f0 a5c3e1f0 a5c3e1f0 +(240/255)*255 43700000 80000002 a5f0e17b a5f0e17b a5f0e17b +(240/255)*255 43700000 00000103 f0c3e17b f0c3e17b f0c3e17b +(241/255)*255 43710000 00000000 a5c3e1f1 a5c3e1f1 a5c3e1f1 +(241/255)*255 43710000 00000001 a5c3f17b a5c3f17b a5c3f17b +(241/255)*255 43710000 00000002 a5f1e17b a5f1e17b a5f1e17b +(241/255)*255 43710000 00000003 f1c3e17b f1c3e17b f1c3e17b +(241/255)*255 43710000 fffffffd a5c3f17b a5c3f17b a5c3f17b +(241/255)*255 43710000 fffffffc a5c3e1f1 a5c3e1f1 a5c3e1f1 +(241/255)*255 43710000 80000002 a5f1e17b a5f1e17b a5f1e17b +(241/255)*255 43710000 00000103 f1c3e17b f1c3e17b f1c3e17b +(242/255)*255 43720000 00000000 a5c3e1f2 a5c3e1f2 a5c3e1f2 +(242/255)*255 43720000 00000001 a5c3f27b a5c3f27b a5c3f27b +(242/255)*255 43720000 00000002 a5f2e17b a5f2e17b a5f2e17b +(242/255)*255 43720000 00000003 f2c3e17b f2c3e17b f2c3e17b +(242/255)*255 43720000 fffffffd a5c3f27b a5c3f27b a5c3f27b +(242/255)*255 43720000 fffffffc a5c3e1f2 a5c3e1f2 a5c3e1f2 +(242/255)*255 43720000 80000002 a5f2e17b a5f2e17b a5f2e17b +(242/255)*255 43720000 00000103 f2c3e17b f2c3e17b f2c3e17b +(243/255)*255 43730000 00000000 a5c3e1f3 a5c3e1f3 a5c3e1f3 +(243/255)*255 43730000 00000001 a5c3f37b a5c3f37b a5c3f37b +(243/255)*255 43730000 00000002 a5f3e17b a5f3e17b a5f3e17b +(243/255)*255 43730000 00000003 f3c3e17b f3c3e17b f3c3e17b +(243/255)*255 43730000 fffffffd a5c3f37b a5c3f37b a5c3f37b +(243/255)*255 43730000 fffffffc a5c3e1f3 a5c3e1f3 a5c3e1f3 +(243/255)*255 43730000 80000002 a5f3e17b a5f3e17b a5f3e17b +(243/255)*255 43730000 00000103 f3c3e17b f3c3e17b f3c3e17b +(244/255)*255 43740000 00000000 a5c3e1f4 a5c3e1f4 a5c3e1f4 +(244/255)*255 43740000 00000001 a5c3f47b a5c3f47b a5c3f47b +(244/255)*255 43740000 00000002 a5f4e17b a5f4e17b a5f4e17b +(244/255)*255 43740000 00000003 f4c3e17b f4c3e17b f4c3e17b +(244/255)*255 43740000 fffffffd a5c3f47b a5c3f47b a5c3f47b +(244/255)*255 43740000 fffffffc a5c3e1f4 a5c3e1f4 a5c3e1f4 +(244/255)*255 43740000 80000002 a5f4e17b a5f4e17b a5f4e17b +(244/255)*255 43740000 00000103 f4c3e17b f4c3e17b f4c3e17b +(245/255)*255 43750000 00000000 a5c3e1f5 a5c3e1f5 a5c3e1f5 +(245/255)*255 43750000 00000001 a5c3f57b a5c3f57b a5c3f57b +(245/255)*255 43750000 00000002 a5f5e17b a5f5e17b a5f5e17b +(245/255)*255 43750000 00000003 f5c3e17b f5c3e17b f5c3e17b +(245/255)*255 43750000 fffffffd a5c3f57b a5c3f57b a5c3f57b +(245/255)*255 43750000 fffffffc a5c3e1f5 a5c3e1f5 a5c3e1f5 +(245/255)*255 43750000 80000002 a5f5e17b a5f5e17b a5f5e17b +(245/255)*255 43750000 00000103 f5c3e17b f5c3e17b f5c3e17b +(246/255)*255 43760000 00000000 a5c3e1f6 a5c3e1f6 a5c3e1f6 +(246/255)*255 43760000 00000001 a5c3f67b a5c3f67b a5c3f67b +(246/255)*255 43760000 00000002 a5f6e17b a5f6e17b a5f6e17b +(246/255)*255 43760000 00000003 f6c3e17b f6c3e17b f6c3e17b +(246/255)*255 43760000 fffffffd a5c3f67b a5c3f67b a5c3f67b +(246/255)*255 43760000 fffffffc a5c3e1f6 a5c3e1f6 a5c3e1f6 +(246/255)*255 43760000 80000002 a5f6e17b a5f6e17b a5f6e17b +(246/255)*255 43760000 00000103 f6c3e17b f6c3e17b f6c3e17b +(247/255)*255 43770000 00000000 a5c3e1f7 a5c3e1f7 a5c3e1f7 +(247/255)*255 43770000 00000001 a5c3f77b a5c3f77b a5c3f77b +(247/255)*255 43770000 00000002 a5f7e17b a5f7e17b a5f7e17b +(247/255)*255 43770000 00000003 f7c3e17b f7c3e17b f7c3e17b +(247/255)*255 43770000 fffffffd a5c3f77b a5c3f77b a5c3f77b +(247/255)*255 43770000 fffffffc a5c3e1f7 a5c3e1f7 a5c3e1f7 +(247/255)*255 43770000 80000002 a5f7e17b a5f7e17b a5f7e17b +(247/255)*255 43770000 00000103 f7c3e17b f7c3e17b f7c3e17b +(248/255)*255 43780000 00000000 a5c3e1f8 a5c3e1f8 a5c3e1f8 +(248/255)*255 43780000 00000001 a5c3f87b a5c3f87b a5c3f87b +(248/255)*255 43780000 00000002 a5f8e17b a5f8e17b a5f8e17b +(248/255)*255 43780000 00000003 f8c3e17b f8c3e17b f8c3e17b +(248/255)*255 43780000 fffffffd a5c3f87b a5c3f87b a5c3f87b +(248/255)*255 43780000 fffffffc a5c3e1f8 a5c3e1f8 a5c3e1f8 +(248/255)*255 43780000 80000002 a5f8e17b a5f8e17b a5f8e17b +(248/255)*255 43780000 00000103 f8c3e17b f8c3e17b f8c3e17b +(249/255)*255 43790000 00000000 a5c3e1f9 a5c3e1f9 a5c3e1f9 +(249/255)*255 43790000 00000001 a5c3f97b a5c3f97b a5c3f97b +(249/255)*255 43790000 00000002 a5f9e17b a5f9e17b a5f9e17b +(249/255)*255 43790000 00000003 f9c3e17b f9c3e17b f9c3e17b +(249/255)*255 43790000 fffffffd a5c3f97b a5c3f97b a5c3f97b +(249/255)*255 43790000 fffffffc a5c3e1f9 a5c3e1f9 a5c3e1f9 +(249/255)*255 43790000 80000002 a5f9e17b a5f9e17b a5f9e17b +(249/255)*255 43790000 00000103 f9c3e17b f9c3e17b f9c3e17b +(250/255)*255 437a0000 00000000 a5c3e1fa a5c3e1fa a5c3e1fa +(250/255)*255 437a0000 00000001 a5c3fa7b a5c3fa7b a5c3fa7b +(250/255)*255 437a0000 00000002 a5fae17b a5fae17b a5fae17b +(250/255)*255 437a0000 00000003 fac3e17b fac3e17b fac3e17b +(250/255)*255 437a0000 fffffffd a5c3fa7b a5c3fa7b a5c3fa7b +(250/255)*255 437a0000 fffffffc a5c3e1fa a5c3e1fa a5c3e1fa +(250/255)*255 437a0000 80000002 a5fae17b a5fae17b a5fae17b +(250/255)*255 437a0000 00000103 fac3e17b fac3e17b fac3e17b +(251/255)*255 437b0000 00000000 a5c3e1fb a5c3e1fb a5c3e1fb +(251/255)*255 437b0000 00000001 a5c3fb7b a5c3fb7b a5c3fb7b +(251/255)*255 437b0000 00000002 a5fbe17b a5fbe17b a5fbe17b +(251/255)*255 437b0000 00000003 fbc3e17b fbc3e17b fbc3e17b +(251/255)*255 437b0000 fffffffd a5c3fb7b a5c3fb7b a5c3fb7b +(251/255)*255 437b0000 fffffffc a5c3e1fb a5c3e1fb a5c3e1fb +(251/255)*255 437b0000 80000002 a5fbe17b a5fbe17b a5fbe17b +(251/255)*255 437b0000 00000103 fbc3e17b fbc3e17b fbc3e17b +(252/255)*255 437c0000 00000000 a5c3e1fc a5c3e1fc a5c3e1fc +(252/255)*255 437c0000 00000001 a5c3fc7b a5c3fc7b a5c3fc7b +(252/255)*255 437c0000 00000002 a5fce17b a5fce17b a5fce17b +(252/255)*255 437c0000 00000003 fcc3e17b fcc3e17b fcc3e17b +(252/255)*255 437c0000 fffffffd a5c3fc7b a5c3fc7b a5c3fc7b +(252/255)*255 437c0000 fffffffc a5c3e1fc a5c3e1fc a5c3e1fc +(252/255)*255 437c0000 80000002 a5fce17b a5fce17b a5fce17b +(252/255)*255 437c0000 00000103 fcc3e17b fcc3e17b fcc3e17b +(1/256)*255 3f7f0000 00000000 a5c3e101 a5c3e100 a5c3e101 +(1/256)*255 3f7f0000 00000001 a5c3017b a5c3007b a5c3017b +(1/256)*255 3f7f0000 00000002 a501e17b a500e17b a501e17b +(1/256)*255 3f7f0000 00000003 01c3e17b 00c3e17b 01c3e17b +(1/256)*255 3f7f0000 fffffffd a5c3017b a5c3007b a5c3017b +(1/256)*255 3f7f0000 fffffffc a5c3e101 a5c3e100 a5c3e101 +(1/256)*255 3f7f0000 80000002 a501e17b a500e17b a501e17b +(1/256)*255 3f7f0000 00000103 01c3e17b 00c3e17b 01c3e17b +(2/256)*255 3fff0000 00000000 a5c3e102 a5c3e101 a5c3e102 +(2/256)*255 3fff0000 00000001 a5c3027b a5c3017b a5c3027b +(2/256)*255 3fff0000 00000002 a502e17b a501e17b a502e17b +(2/256)*255 3fff0000 00000003 02c3e17b 01c3e17b 02c3e17b +(2/256)*255 3fff0000 fffffffd a5c3027b a5c3017b a5c3027b +(2/256)*255 3fff0000 fffffffc a5c3e102 a5c3e101 a5c3e102 +(2/256)*255 3fff0000 80000002 a502e17b a501e17b a502e17b +(2/256)*255 3fff0000 00000103 02c3e17b 01c3e17b 02c3e17b +(3/256)*255 403f4000 00000000 a5c3e103 a5c3e102 a5c3e103 +(3/256)*255 403f4000 00000001 a5c3037b a5c3027b a5c3037b +(3/256)*255 403f4000 00000002 a503e17b a502e17b a503e17b +(3/256)*255 403f4000 00000003 03c3e17b 02c3e17b 03c3e17b +(3/256)*255 403f4000 fffffffd a5c3037b a5c3027b a5c3037b +(3/256)*255 403f4000 fffffffc a5c3e103 a5c3e102 a5c3e103 +(3/256)*255 403f4000 80000002 a503e17b a502e17b a503e17b +(3/256)*255 403f4000 00000103 03c3e17b 02c3e17b 03c3e17b +(4/256)*255 407f0000 00000000 a5c3e104 a5c3e103 a5c3e104 +(4/256)*255 407f0000 00000001 a5c3047b a5c3037b a5c3047b +(4/256)*255 407f0000 00000002 a504e17b a503e17b a504e17b +(4/256)*255 407f0000 00000003 04c3e17b 03c3e17b 04c3e17b +(4/256)*255 407f0000 fffffffd a5c3047b a5c3037b a5c3047b +(4/256)*255 407f0000 fffffffc a5c3e104 a5c3e103 a5c3e104 +(4/256)*255 407f0000 80000002 a504e17b a503e17b a504e17b +(4/256)*255 407f0000 00000103 04c3e17b 03c3e17b 04c3e17b +(5/256)*255 409f6000 00000000 a5c3e105 a5c3e104 a5c3e105 +(5/256)*255 409f6000 00000001 a5c3057b a5c3047b a5c3057b +(5/256)*255 409f6000 00000002 a505e17b a504e17b a505e17b +(5/256)*255 409f6000 00000003 05c3e17b 04c3e17b 05c3e17b +(5/256)*255 409f6000 fffffffd a5c3057b a5c3047b a5c3057b +(5/256)*255 409f6000 fffffffc a5c3e105 a5c3e104 a5c3e105 +(5/256)*255 409f6000 80000002 a505e17b a504e17b a505e17b +(5/256)*255 409f6000 00000103 05c3e17b 04c3e17b 05c3e17b +(6/256)*255 40bf4000 00000000 a5c3e106 a5c3e105 a5c3e106 +(6/256)*255 40bf4000 00000001 a5c3067b a5c3057b a5c3067b +(6/256)*255 40bf4000 00000002 a506e17b a505e17b a506e17b +(6/256)*255 40bf4000 00000003 06c3e17b 05c3e17b 06c3e17b +(6/256)*255 40bf4000 fffffffd a5c3067b a5c3057b a5c3067b +(6/256)*255 40bf4000 fffffffc a5c3e106 a5c3e105 a5c3e106 +(6/256)*255 40bf4000 80000002 a506e17b a505e17b a506e17b +(6/256)*255 40bf4000 00000103 06c3e17b 05c3e17b 06c3e17b +(7/256)*255 40df2000 00000000 a5c3e107 a5c3e106 a5c3e107 +(7/256)*255 40df2000 00000001 a5c3077b a5c3067b a5c3077b +(7/256)*255 40df2000 00000002 a507e17b a506e17b a507e17b +(7/256)*255 40df2000 00000003 07c3e17b 06c3e17b 07c3e17b +(7/256)*255 40df2000 fffffffd a5c3077b a5c3067b a5c3077b +(7/256)*255 40df2000 fffffffc a5c3e107 a5c3e106 a5c3e107 +(7/256)*255 40df2000 80000002 a507e17b a506e17b a507e17b +(7/256)*255 40df2000 00000103 07c3e17b 06c3e17b 07c3e17b +(8/256)*255 40ff0000 00000000 a5c3e108 a5c3e107 a5c3e108 +(8/256)*255 40ff0000 00000001 a5c3087b a5c3077b a5c3087b +(8/256)*255 40ff0000 00000002 a508e17b a507e17b a508e17b +(8/256)*255 40ff0000 00000003 08c3e17b 07c3e17b 08c3e17b +(8/256)*255 40ff0000 fffffffd a5c3087b a5c3077b a5c3087b +(8/256)*255 40ff0000 fffffffc a5c3e108 a5c3e107 a5c3e108 +(8/256)*255 40ff0000 80000002 a508e17b a507e17b a508e17b +(8/256)*255 40ff0000 00000103 08c3e17b 07c3e17b 08c3e17b +(9/256)*255 410f7000 00000000 a5c3e109 a5c3e108 a5c3e109 +(9/256)*255 410f7000 00000001 a5c3097b a5c3087b a5c3097b +(9/256)*255 410f7000 00000002 a509e17b a508e17b a509e17b +(9/256)*255 410f7000 00000003 09c3e17b 08c3e17b 09c3e17b +(9/256)*255 410f7000 fffffffd a5c3097b a5c3087b a5c3097b +(9/256)*255 410f7000 fffffffc a5c3e109 a5c3e108 a5c3e109 +(9/256)*255 410f7000 80000002 a509e17b a508e17b a509e17b +(9/256)*255 410f7000 00000103 09c3e17b 08c3e17b 09c3e17b +(10/256)*255 411f6000 00000000 a5c3e10a a5c3e109 a5c3e10a +(10/256)*255 411f6000 00000001 a5c30a7b a5c3097b a5c30a7b +(10/256)*255 411f6000 00000002 a50ae17b a509e17b a50ae17b +(10/256)*255 411f6000 00000003 0ac3e17b 09c3e17b 0ac3e17b +(10/256)*255 411f6000 fffffffd a5c30a7b a5c3097b a5c30a7b +(10/256)*255 411f6000 fffffffc a5c3e10a a5c3e109 a5c3e10a +(10/256)*255 411f6000 80000002 a50ae17b a509e17b a50ae17b +(10/256)*255 411f6000 00000103 0ac3e17b 09c3e17b 0ac3e17b +(11/256)*255 412f5000 00000000 a5c3e10b a5c3e10a a5c3e10b +(11/256)*255 412f5000 00000001 a5c30b7b a5c30a7b a5c30b7b +(11/256)*255 412f5000 00000002 a50be17b a50ae17b a50be17b +(11/256)*255 412f5000 00000003 0bc3e17b 0ac3e17b 0bc3e17b +(11/256)*255 412f5000 fffffffd a5c30b7b a5c30a7b a5c30b7b +(11/256)*255 412f5000 fffffffc a5c3e10b a5c3e10a a5c3e10b +(11/256)*255 412f5000 80000002 a50be17b a50ae17b a50be17b +(11/256)*255 412f5000 00000103 0bc3e17b 0ac3e17b 0bc3e17b +(12/256)*255 413f4000 00000000 a5c3e10c a5c3e10b a5c3e10c +(12/256)*255 413f4000 00000001 a5c30c7b a5c30b7b a5c30c7b +(12/256)*255 413f4000 00000002 a50ce17b a50be17b a50ce17b +(12/256)*255 413f4000 00000003 0cc3e17b 0bc3e17b 0cc3e17b +(12/256)*255 413f4000 fffffffd a5c30c7b a5c30b7b a5c30c7b +(12/256)*255 413f4000 fffffffc a5c3e10c a5c3e10b a5c3e10c +(12/256)*255 413f4000 80000002 a50ce17b a50be17b a50ce17b +(12/256)*255 413f4000 00000103 0cc3e17b 0bc3e17b 0cc3e17b +(13/256)*255 414f3000 00000000 a5c3e10d a5c3e10c a5c3e10d +(13/256)*255 414f3000 00000001 a5c30d7b a5c30c7b a5c30d7b +(13/256)*255 414f3000 00000002 a50de17b a50ce17b a50de17b +(13/256)*255 414f3000 00000003 0dc3e17b 0cc3e17b 0dc3e17b +(13/256)*255 414f3000 fffffffd a5c30d7b a5c30c7b a5c30d7b +(13/256)*255 414f3000 fffffffc a5c3e10d a5c3e10c a5c3e10d +(13/256)*255 414f3000 80000002 a50de17b a50ce17b a50de17b +(13/256)*255 414f3000 00000103 0dc3e17b 0cc3e17b 0dc3e17b +(14/256)*255 415f2000 00000000 a5c3e10e a5c3e10d a5c3e10e +(14/256)*255 415f2000 00000001 a5c30e7b a5c30d7b a5c30e7b +(14/256)*255 415f2000 00000002 a50ee17b a50de17b a50ee17b +(14/256)*255 415f2000 00000003 0ec3e17b 0dc3e17b 0ec3e17b +(14/256)*255 415f2000 fffffffd a5c30e7b a5c30d7b a5c30e7b +(14/256)*255 415f2000 fffffffc a5c3e10e a5c3e10d a5c3e10e +(14/256)*255 415f2000 80000002 a50ee17b a50de17b a50ee17b +(14/256)*255 415f2000 00000103 0ec3e17b 0dc3e17b 0ec3e17b +(15/256)*255 416f1000 00000000 a5c3e10f a5c3e10e a5c3e10f +(15/256)*255 416f1000 00000001 a5c30f7b a5c30e7b a5c30f7b +(15/256)*255 416f1000 00000002 a50fe17b a50ee17b a50fe17b +(15/256)*255 416f1000 00000003 0fc3e17b 0ec3e17b 0fc3e17b +(15/256)*255 416f1000 fffffffd a5c30f7b a5c30e7b a5c30f7b +(15/256)*255 416f1000 fffffffc a5c3e10f a5c3e10e a5c3e10f +(15/256)*255 416f1000 80000002 a50fe17b a50ee17b a50fe17b +(15/256)*255 416f1000 00000103 0fc3e17b 0ec3e17b 0fc3e17b +(16/256)*255 417f0000 00000000 a5c3e110 a5c3e10f a5c3e110 +(16/256)*255 417f0000 00000001 a5c3107b a5c30f7b a5c3107b +(16/256)*255 417f0000 00000002 a510e17b a50fe17b a510e17b +(16/256)*255 417f0000 00000003 10c3e17b 0fc3e17b 10c3e17b +(16/256)*255 417f0000 fffffffd a5c3107b a5c30f7b a5c3107b +(16/256)*255 417f0000 fffffffc a5c3e110 a5c3e10f a5c3e110 +(16/256)*255 417f0000 80000002 a510e17b a50fe17b a510e17b +(16/256)*255 417f0000 00000103 10c3e17b 0fc3e17b 10c3e17b +(17/256)*255 41877800 00000000 a5c3e111 a5c3e110 a5c3e111 +(17/256)*255 41877800 00000001 a5c3117b a5c3107b a5c3117b +(17/256)*255 41877800 00000002 a511e17b a510e17b a511e17b +(17/256)*255 41877800 00000003 11c3e17b 10c3e17b 11c3e17b +(17/256)*255 41877800 fffffffd a5c3117b a5c3107b a5c3117b +(17/256)*255 41877800 fffffffc a5c3e111 a5c3e110 a5c3e111 +(17/256)*255 41877800 80000002 a511e17b a510e17b a511e17b +(17/256)*255 41877800 00000103 11c3e17b 10c3e17b 11c3e17b +(18/256)*255 418f7000 00000000 a5c3e112 a5c3e111 a5c3e112 +(18/256)*255 418f7000 00000001 a5c3127b a5c3117b a5c3127b +(18/256)*255 418f7000 00000002 a512e17b a511e17b a512e17b +(18/256)*255 418f7000 00000003 12c3e17b 11c3e17b 12c3e17b +(18/256)*255 418f7000 fffffffd a5c3127b a5c3117b a5c3127b +(18/256)*255 418f7000 fffffffc a5c3e112 a5c3e111 a5c3e112 +(18/256)*255 418f7000 80000002 a512e17b a511e17b a512e17b +(18/256)*255 418f7000 00000103 12c3e17b 11c3e17b 12c3e17b +(19/256)*255 41976800 00000000 a5c3e113 a5c3e112 a5c3e113 +(19/256)*255 41976800 00000001 a5c3137b a5c3127b a5c3137b +(19/256)*255 41976800 00000002 a513e17b a512e17b a513e17b +(19/256)*255 41976800 00000003 13c3e17b 12c3e17b 13c3e17b +(19/256)*255 41976800 fffffffd a5c3137b a5c3127b a5c3137b +(19/256)*255 41976800 fffffffc a5c3e113 a5c3e112 a5c3e113 +(19/256)*255 41976800 80000002 a513e17b a512e17b a513e17b +(19/256)*255 41976800 00000103 13c3e17b 12c3e17b 13c3e17b +(20/256)*255 419f6000 00000000 a5c3e114 a5c3e113 a5c3e114 +(20/256)*255 419f6000 00000001 a5c3147b a5c3137b a5c3147b +(20/256)*255 419f6000 00000002 a514e17b a513e17b a514e17b +(20/256)*255 419f6000 00000003 14c3e17b 13c3e17b 14c3e17b +(20/256)*255 419f6000 fffffffd a5c3147b a5c3137b a5c3147b +(20/256)*255 419f6000 fffffffc a5c3e114 a5c3e113 a5c3e114 +(20/256)*255 419f6000 80000002 a514e17b a513e17b a514e17b +(20/256)*255 419f6000 00000103 14c3e17b 13c3e17b 14c3e17b +(21/256)*255 41a75800 00000000 a5c3e115 a5c3e114 a5c3e115 +(21/256)*255 41a75800 00000001 a5c3157b a5c3147b a5c3157b +(21/256)*255 41a75800 00000002 a515e17b a514e17b a515e17b +(21/256)*255 41a75800 00000003 15c3e17b 14c3e17b 15c3e17b +(21/256)*255 41a75800 fffffffd a5c3157b a5c3147b a5c3157b +(21/256)*255 41a75800 fffffffc a5c3e115 a5c3e114 a5c3e115 +(21/256)*255 41a75800 80000002 a515e17b a514e17b a515e17b +(21/256)*255 41a75800 00000103 15c3e17b 14c3e17b 15c3e17b +(22/256)*255 41af5000 00000000 a5c3e116 a5c3e115 a5c3e116 +(22/256)*255 41af5000 00000001 a5c3167b a5c3157b a5c3167b +(22/256)*255 41af5000 00000002 a516e17b a515e17b a516e17b +(22/256)*255 41af5000 00000003 16c3e17b 15c3e17b 16c3e17b +(22/256)*255 41af5000 fffffffd a5c3167b a5c3157b a5c3167b +(22/256)*255 41af5000 fffffffc a5c3e116 a5c3e115 a5c3e116 +(22/256)*255 41af5000 80000002 a516e17b a515e17b a516e17b +(22/256)*255 41af5000 00000103 16c3e17b 15c3e17b 16c3e17b +(23/256)*255 41b74800 00000000 a5c3e117 a5c3e116 a5c3e117 +(23/256)*255 41b74800 00000001 a5c3177b a5c3167b a5c3177b +(23/256)*255 41b74800 00000002 a517e17b a516e17b a517e17b +(23/256)*255 41b74800 00000003 17c3e17b 16c3e17b 17c3e17b +(23/256)*255 41b74800 fffffffd a5c3177b a5c3167b a5c3177b +(23/256)*255 41b74800 fffffffc a5c3e117 a5c3e116 a5c3e117 +(23/256)*255 41b74800 80000002 a517e17b a516e17b a517e17b +(23/256)*255 41b74800 00000103 17c3e17b 16c3e17b 17c3e17b +(24/256)*255 41bf4000 00000000 a5c3e118 a5c3e117 a5c3e118 +(24/256)*255 41bf4000 00000001 a5c3187b a5c3177b a5c3187b +(24/256)*255 41bf4000 00000002 a518e17b a517e17b a518e17b +(24/256)*255 41bf4000 00000003 18c3e17b 17c3e17b 18c3e17b +(24/256)*255 41bf4000 fffffffd a5c3187b a5c3177b a5c3187b +(24/256)*255 41bf4000 fffffffc a5c3e118 a5c3e117 a5c3e118 +(24/256)*255 41bf4000 80000002 a518e17b a517e17b a518e17b +(24/256)*255 41bf4000 00000103 18c3e17b 17c3e17b 18c3e17b +(25/256)*255 41c73800 00000000 a5c3e119 a5c3e118 a5c3e119 +(25/256)*255 41c73800 00000001 a5c3197b a5c3187b a5c3197b +(25/256)*255 41c73800 00000002 a519e17b a518e17b a519e17b +(25/256)*255 41c73800 00000003 19c3e17b 18c3e17b 19c3e17b +(25/256)*255 41c73800 fffffffd a5c3197b a5c3187b a5c3197b +(25/256)*255 41c73800 fffffffc a5c3e119 a5c3e118 a5c3e119 +(25/256)*255 41c73800 80000002 a519e17b a518e17b a519e17b +(25/256)*255 41c73800 00000103 19c3e17b 18c3e17b 19c3e17b +(26/256)*255 41cf3000 00000000 a5c3e11a a5c3e119 a5c3e11a +(26/256)*255 41cf3000 00000001 a5c31a7b a5c3197b a5c31a7b +(26/256)*255 41cf3000 00000002 a51ae17b a519e17b a51ae17b +(26/256)*255 41cf3000 00000003 1ac3e17b 19c3e17b 1ac3e17b +(26/256)*255 41cf3000 fffffffd a5c31a7b a5c3197b a5c31a7b +(26/256)*255 41cf3000 fffffffc a5c3e11a a5c3e119 a5c3e11a +(26/256)*255 41cf3000 80000002 a51ae17b a519e17b a51ae17b +(26/256)*255 41cf3000 00000103 1ac3e17b 19c3e17b 1ac3e17b +(27/256)*255 41d72800 00000000 a5c3e11b a5c3e11a a5c3e11b +(27/256)*255 41d72800 00000001 a5c31b7b a5c31a7b a5c31b7b +(27/256)*255 41d72800 00000002 a51be17b a51ae17b a51be17b +(27/256)*255 41d72800 00000003 1bc3e17b 1ac3e17b 1bc3e17b +(27/256)*255 41d72800 fffffffd a5c31b7b a5c31a7b a5c31b7b +(27/256)*255 41d72800 fffffffc a5c3e11b a5c3e11a a5c3e11b +(27/256)*255 41d72800 80000002 a51be17b a51ae17b a51be17b +(27/256)*255 41d72800 00000103 1bc3e17b 1ac3e17b 1bc3e17b +(28/256)*255 41df2000 00000000 a5c3e11c a5c3e11b a5c3e11c +(28/256)*255 41df2000 00000001 a5c31c7b a5c31b7b a5c31c7b +(28/256)*255 41df2000 00000002 a51ce17b a51be17b a51ce17b +(28/256)*255 41df2000 00000003 1cc3e17b 1bc3e17b 1cc3e17b +(28/256)*255 41df2000 fffffffd a5c31c7b a5c31b7b a5c31c7b +(28/256)*255 41df2000 fffffffc a5c3e11c a5c3e11b a5c3e11c +(28/256)*255 41df2000 80000002 a51ce17b a51be17b a51ce17b +(28/256)*255 41df2000 00000103 1cc3e17b 1bc3e17b 1cc3e17b +(29/256)*255 41e71800 00000000 a5c3e11d a5c3e11c a5c3e11d +(29/256)*255 41e71800 00000001 a5c31d7b a5c31c7b a5c31d7b +(29/256)*255 41e71800 00000002 a51de17b a51ce17b a51de17b +(29/256)*255 41e71800 00000003 1dc3e17b 1cc3e17b 1dc3e17b +(29/256)*255 41e71800 fffffffd a5c31d7b a5c31c7b a5c31d7b +(29/256)*255 41e71800 fffffffc a5c3e11d a5c3e11c a5c3e11d +(29/256)*255 41e71800 80000002 a51de17b a51ce17b a51de17b +(29/256)*255 41e71800 00000103 1dc3e17b 1cc3e17b 1dc3e17b +(30/256)*255 41ef1000 00000000 a5c3e11e a5c3e11d a5c3e11e +(30/256)*255 41ef1000 00000001 a5c31e7b a5c31d7b a5c31e7b +(30/256)*255 41ef1000 00000002 a51ee17b a51de17b a51ee17b +(30/256)*255 41ef1000 00000003 1ec3e17b 1dc3e17b 1ec3e17b +(30/256)*255 41ef1000 fffffffd a5c31e7b a5c31d7b a5c31e7b +(30/256)*255 41ef1000 fffffffc a5c3e11e a5c3e11d a5c3e11e +(30/256)*255 41ef1000 80000002 a51ee17b a51de17b a51ee17b +(30/256)*255 41ef1000 00000103 1ec3e17b 1dc3e17b 1ec3e17b +(31/256)*255 41f70800 00000000 a5c3e11f a5c3e11e a5c3e11f +(31/256)*255 41f70800 00000001 a5c31f7b a5c31e7b a5c31f7b +(31/256)*255 41f70800 00000002 a51fe17b a51ee17b a51fe17b +(31/256)*255 41f70800 00000003 1fc3e17b 1ec3e17b 1fc3e17b +(31/256)*255 41f70800 fffffffd a5c31f7b a5c31e7b a5c31f7b +(31/256)*255 41f70800 fffffffc a5c3e11f a5c3e11e a5c3e11f +(31/256)*255 41f70800 80000002 a51fe17b a51ee17b a51fe17b +(31/256)*255 41f70800 00000103 1fc3e17b 1ec3e17b 1fc3e17b +(32/256)*255 41ff0000 00000000 a5c3e120 a5c3e11f a5c3e120 +(32/256)*255 41ff0000 00000001 a5c3207b a5c31f7b a5c3207b +(32/256)*255 41ff0000 00000002 a520e17b a51fe17b a520e17b +(32/256)*255 41ff0000 00000003 20c3e17b 1fc3e17b 20c3e17b +(32/256)*255 41ff0000 fffffffd a5c3207b a5c31f7b a5c3207b +(32/256)*255 41ff0000 fffffffc a5c3e120 a5c3e11f a5c3e120 +(32/256)*255 41ff0000 80000002 a520e17b a51fe17b a520e17b +(32/256)*255 41ff0000 00000103 20c3e17b 1fc3e17b 20c3e17b +(33/256)*255 42037c00 00000000 a5c3e121 a5c3e120 a5c3e121 +(33/256)*255 42037c00 00000001 a5c3217b a5c3207b a5c3217b +(33/256)*255 42037c00 00000002 a521e17b a520e17b a521e17b +(33/256)*255 42037c00 00000003 21c3e17b 20c3e17b 21c3e17b +(33/256)*255 42037c00 fffffffd a5c3217b a5c3207b a5c3217b +(33/256)*255 42037c00 fffffffc a5c3e121 a5c3e120 a5c3e121 +(33/256)*255 42037c00 80000002 a521e17b a520e17b a521e17b +(33/256)*255 42037c00 00000103 21c3e17b 20c3e17b 21c3e17b +(34/256)*255 42077800 00000000 a5c3e122 a5c3e121 a5c3e122 +(34/256)*255 42077800 00000001 a5c3227b a5c3217b a5c3227b +(34/256)*255 42077800 00000002 a522e17b a521e17b a522e17b +(34/256)*255 42077800 00000003 22c3e17b 21c3e17b 22c3e17b +(34/256)*255 42077800 fffffffd a5c3227b a5c3217b a5c3227b +(34/256)*255 42077800 fffffffc a5c3e122 a5c3e121 a5c3e122 +(34/256)*255 42077800 80000002 a522e17b a521e17b a522e17b +(34/256)*255 42077800 00000103 22c3e17b 21c3e17b 22c3e17b +(35/256)*255 420b7400 00000000 a5c3e123 a5c3e122 a5c3e123 +(35/256)*255 420b7400 00000001 a5c3237b a5c3227b a5c3237b +(35/256)*255 420b7400 00000002 a523e17b a522e17b a523e17b +(35/256)*255 420b7400 00000003 23c3e17b 22c3e17b 23c3e17b +(35/256)*255 420b7400 fffffffd a5c3237b a5c3227b a5c3237b +(35/256)*255 420b7400 fffffffc a5c3e123 a5c3e122 a5c3e123 +(35/256)*255 420b7400 80000002 a523e17b a522e17b a523e17b +(35/256)*255 420b7400 00000103 23c3e17b 22c3e17b 23c3e17b +(36/256)*255 420f7000 00000000 a5c3e124 a5c3e123 a5c3e124 +(36/256)*255 420f7000 00000001 a5c3247b a5c3237b a5c3247b +(36/256)*255 420f7000 00000002 a524e17b a523e17b a524e17b +(36/256)*255 420f7000 00000003 24c3e17b 23c3e17b 24c3e17b +(36/256)*255 420f7000 fffffffd a5c3247b a5c3237b a5c3247b +(36/256)*255 420f7000 fffffffc a5c3e124 a5c3e123 a5c3e124 +(36/256)*255 420f7000 80000002 a524e17b a523e17b a524e17b +(36/256)*255 420f7000 00000103 24c3e17b 23c3e17b 24c3e17b +(37/256)*255 42136c00 00000000 a5c3e125 a5c3e124 a5c3e125 +(37/256)*255 42136c00 00000001 a5c3257b a5c3247b a5c3257b +(37/256)*255 42136c00 00000002 a525e17b a524e17b a525e17b +(37/256)*255 42136c00 00000003 25c3e17b 24c3e17b 25c3e17b +(37/256)*255 42136c00 fffffffd a5c3257b a5c3247b a5c3257b +(37/256)*255 42136c00 fffffffc a5c3e125 a5c3e124 a5c3e125 +(37/256)*255 42136c00 80000002 a525e17b a524e17b a525e17b +(37/256)*255 42136c00 00000103 25c3e17b 24c3e17b 25c3e17b +(38/256)*255 42176800 00000000 a5c3e126 a5c3e125 a5c3e126 +(38/256)*255 42176800 00000001 a5c3267b a5c3257b a5c3267b +(38/256)*255 42176800 00000002 a526e17b a525e17b a526e17b +(38/256)*255 42176800 00000003 26c3e17b 25c3e17b 26c3e17b +(38/256)*255 42176800 fffffffd a5c3267b a5c3257b a5c3267b +(38/256)*255 42176800 fffffffc a5c3e126 a5c3e125 a5c3e126 +(38/256)*255 42176800 80000002 a526e17b a525e17b a526e17b +(38/256)*255 42176800 00000103 26c3e17b 25c3e17b 26c3e17b +(39/256)*255 421b6400 00000000 a5c3e127 a5c3e126 a5c3e127 +(39/256)*255 421b6400 00000001 a5c3277b a5c3267b a5c3277b +(39/256)*255 421b6400 00000002 a527e17b a526e17b a527e17b +(39/256)*255 421b6400 00000003 27c3e17b 26c3e17b 27c3e17b +(39/256)*255 421b6400 fffffffd a5c3277b a5c3267b a5c3277b +(39/256)*255 421b6400 fffffffc a5c3e127 a5c3e126 a5c3e127 +(39/256)*255 421b6400 80000002 a527e17b a526e17b a527e17b +(39/256)*255 421b6400 00000103 27c3e17b 26c3e17b 27c3e17b +(40/256)*255 421f6000 00000000 a5c3e128 a5c3e127 a5c3e128 +(40/256)*255 421f6000 00000001 a5c3287b a5c3277b a5c3287b +(40/256)*255 421f6000 00000002 a528e17b a527e17b a528e17b +(40/256)*255 421f6000 00000003 28c3e17b 27c3e17b 28c3e17b +(40/256)*255 421f6000 fffffffd a5c3287b a5c3277b a5c3287b +(40/256)*255 421f6000 fffffffc a5c3e128 a5c3e127 a5c3e128 +(40/256)*255 421f6000 80000002 a528e17b a527e17b a528e17b +(40/256)*255 421f6000 00000103 28c3e17b 27c3e17b 28c3e17b +(41/256)*255 42235c00 00000000 a5c3e129 a5c3e128 a5c3e129 +(41/256)*255 42235c00 00000001 a5c3297b a5c3287b a5c3297b +(41/256)*255 42235c00 00000002 a529e17b a528e17b a529e17b +(41/256)*255 42235c00 00000003 29c3e17b 28c3e17b 29c3e17b +(41/256)*255 42235c00 fffffffd a5c3297b a5c3287b a5c3297b +(41/256)*255 42235c00 fffffffc a5c3e129 a5c3e128 a5c3e129 +(41/256)*255 42235c00 80000002 a529e17b a528e17b a529e17b +(41/256)*255 42235c00 00000103 29c3e17b 28c3e17b 29c3e17b +(42/256)*255 42275800 00000000 a5c3e12a a5c3e129 a5c3e12a +(42/256)*255 42275800 00000001 a5c32a7b a5c3297b a5c32a7b +(42/256)*255 42275800 00000002 a52ae17b a529e17b a52ae17b +(42/256)*255 42275800 00000003 2ac3e17b 29c3e17b 2ac3e17b +(42/256)*255 42275800 fffffffd a5c32a7b a5c3297b a5c32a7b +(42/256)*255 42275800 fffffffc a5c3e12a a5c3e129 a5c3e12a +(42/256)*255 42275800 80000002 a52ae17b a529e17b a52ae17b +(42/256)*255 42275800 00000103 2ac3e17b 29c3e17b 2ac3e17b +(43/256)*255 422b5400 00000000 a5c3e12b a5c3e12a a5c3e12b +(43/256)*255 422b5400 00000001 a5c32b7b a5c32a7b a5c32b7b +(43/256)*255 422b5400 00000002 a52be17b a52ae17b a52be17b +(43/256)*255 422b5400 00000003 2bc3e17b 2ac3e17b 2bc3e17b +(43/256)*255 422b5400 fffffffd a5c32b7b a5c32a7b a5c32b7b +(43/256)*255 422b5400 fffffffc a5c3e12b a5c3e12a a5c3e12b +(43/256)*255 422b5400 80000002 a52be17b a52ae17b a52be17b +(43/256)*255 422b5400 00000103 2bc3e17b 2ac3e17b 2bc3e17b +(44/256)*255 422f5000 00000000 a5c3e12c a5c3e12b a5c3e12c +(44/256)*255 422f5000 00000001 a5c32c7b a5c32b7b a5c32c7b +(44/256)*255 422f5000 00000002 a52ce17b a52be17b a52ce17b +(44/256)*255 422f5000 00000003 2cc3e17b 2bc3e17b 2cc3e17b +(44/256)*255 422f5000 fffffffd a5c32c7b a5c32b7b a5c32c7b +(44/256)*255 422f5000 fffffffc a5c3e12c a5c3e12b a5c3e12c +(44/256)*255 422f5000 80000002 a52ce17b a52be17b a52ce17b +(44/256)*255 422f5000 00000103 2cc3e17b 2bc3e17b 2cc3e17b +(45/256)*255 42334c00 00000000 a5c3e12d a5c3e12c a5c3e12d +(45/256)*255 42334c00 00000001 a5c32d7b a5c32c7b a5c32d7b +(45/256)*255 42334c00 00000002 a52de17b a52ce17b a52de17b +(45/256)*255 42334c00 00000003 2dc3e17b 2cc3e17b 2dc3e17b +(45/256)*255 42334c00 fffffffd a5c32d7b a5c32c7b a5c32d7b +(45/256)*255 42334c00 fffffffc a5c3e12d a5c3e12c a5c3e12d +(45/256)*255 42334c00 80000002 a52de17b a52ce17b a52de17b +(45/256)*255 42334c00 00000103 2dc3e17b 2cc3e17b 2dc3e17b +(46/256)*255 42374800 00000000 a5c3e12e a5c3e12d a5c3e12e +(46/256)*255 42374800 00000001 a5c32e7b a5c32d7b a5c32e7b +(46/256)*255 42374800 00000002 a52ee17b a52de17b a52ee17b +(46/256)*255 42374800 00000003 2ec3e17b 2dc3e17b 2ec3e17b +(46/256)*255 42374800 fffffffd a5c32e7b a5c32d7b a5c32e7b +(46/256)*255 42374800 fffffffc a5c3e12e a5c3e12d a5c3e12e +(46/256)*255 42374800 80000002 a52ee17b a52de17b a52ee17b +(46/256)*255 42374800 00000103 2ec3e17b 2dc3e17b 2ec3e17b +(47/256)*255 423b4400 00000000 a5c3e12f a5c3e12e a5c3e12f +(47/256)*255 423b4400 00000001 a5c32f7b a5c32e7b a5c32f7b +(47/256)*255 423b4400 00000002 a52fe17b a52ee17b a52fe17b +(47/256)*255 423b4400 00000003 2fc3e17b 2ec3e17b 2fc3e17b +(47/256)*255 423b4400 fffffffd a5c32f7b a5c32e7b a5c32f7b +(47/256)*255 423b4400 fffffffc a5c3e12f a5c3e12e a5c3e12f +(47/256)*255 423b4400 80000002 a52fe17b a52ee17b a52fe17b +(47/256)*255 423b4400 00000103 2fc3e17b 2ec3e17b 2fc3e17b +(48/256)*255 423f4000 00000000 a5c3e130 a5c3e12f a5c3e130 +(48/256)*255 423f4000 00000001 a5c3307b a5c32f7b a5c3307b +(48/256)*255 423f4000 00000002 a530e17b a52fe17b a530e17b +(48/256)*255 423f4000 00000003 30c3e17b 2fc3e17b 30c3e17b +(48/256)*255 423f4000 fffffffd a5c3307b a5c32f7b a5c3307b +(48/256)*255 423f4000 fffffffc a5c3e130 a5c3e12f a5c3e130 +(48/256)*255 423f4000 80000002 a530e17b a52fe17b a530e17b +(48/256)*255 423f4000 00000103 30c3e17b 2fc3e17b 30c3e17b +(49/256)*255 42433c00 00000000 a5c3e131 a5c3e130 a5c3e131 +(49/256)*255 42433c00 00000001 a5c3317b a5c3307b a5c3317b +(49/256)*255 42433c00 00000002 a531e17b a530e17b a531e17b +(49/256)*255 42433c00 00000003 31c3e17b 30c3e17b 31c3e17b +(49/256)*255 42433c00 fffffffd a5c3317b a5c3307b a5c3317b +(49/256)*255 42433c00 fffffffc a5c3e131 a5c3e130 a5c3e131 +(49/256)*255 42433c00 80000002 a531e17b a530e17b a531e17b +(49/256)*255 42433c00 00000103 31c3e17b 30c3e17b 31c3e17b +(50/256)*255 42473800 00000000 a5c3e132 a5c3e131 a5c3e132 +(50/256)*255 42473800 00000001 a5c3327b a5c3317b a5c3327b +(50/256)*255 42473800 00000002 a532e17b a531e17b a532e17b +(50/256)*255 42473800 00000003 32c3e17b 31c3e17b 32c3e17b +(50/256)*255 42473800 fffffffd a5c3327b a5c3317b a5c3327b +(50/256)*255 42473800 fffffffc a5c3e132 a5c3e131 a5c3e132 +(50/256)*255 42473800 80000002 a532e17b a531e17b a532e17b +(50/256)*255 42473800 00000103 32c3e17b 31c3e17b 32c3e17b +(51/256)*255 424b3400 00000000 a5c3e133 a5c3e132 a5c3e133 +(51/256)*255 424b3400 00000001 a5c3337b a5c3327b a5c3337b +(51/256)*255 424b3400 00000002 a533e17b a532e17b a533e17b +(51/256)*255 424b3400 00000003 33c3e17b 32c3e17b 33c3e17b +(51/256)*255 424b3400 fffffffd a5c3337b a5c3327b a5c3337b +(51/256)*255 424b3400 fffffffc a5c3e133 a5c3e132 a5c3e133 +(51/256)*255 424b3400 80000002 a533e17b a532e17b a533e17b +(51/256)*255 424b3400 00000103 33c3e17b 32c3e17b 33c3e17b +(52/256)*255 424f3000 00000000 a5c3e134 a5c3e133 a5c3e134 +(52/256)*255 424f3000 00000001 a5c3347b a5c3337b a5c3347b +(52/256)*255 424f3000 00000002 a534e17b a533e17b a534e17b +(52/256)*255 424f3000 00000003 34c3e17b 33c3e17b 34c3e17b +(52/256)*255 424f3000 fffffffd a5c3347b a5c3337b a5c3347b +(52/256)*255 424f3000 fffffffc a5c3e134 a5c3e133 a5c3e134 +(52/256)*255 424f3000 80000002 a534e17b a533e17b a534e17b +(52/256)*255 424f3000 00000103 34c3e17b 33c3e17b 34c3e17b +(53/256)*255 42532c00 00000000 a5c3e135 a5c3e134 a5c3e135 +(53/256)*255 42532c00 00000001 a5c3357b a5c3347b a5c3357b +(53/256)*255 42532c00 00000002 a535e17b a534e17b a535e17b +(53/256)*255 42532c00 00000003 35c3e17b 34c3e17b 35c3e17b +(53/256)*255 42532c00 fffffffd a5c3357b a5c3347b a5c3357b +(53/256)*255 42532c00 fffffffc a5c3e135 a5c3e134 a5c3e135 +(53/256)*255 42532c00 80000002 a535e17b a534e17b a535e17b +(53/256)*255 42532c00 00000103 35c3e17b 34c3e17b 35c3e17b +(54/256)*255 42572800 00000000 a5c3e136 a5c3e135 a5c3e136 +(54/256)*255 42572800 00000001 a5c3367b a5c3357b a5c3367b +(54/256)*255 42572800 00000002 a536e17b a535e17b a536e17b +(54/256)*255 42572800 00000003 36c3e17b 35c3e17b 36c3e17b +(54/256)*255 42572800 fffffffd a5c3367b a5c3357b a5c3367b +(54/256)*255 42572800 fffffffc a5c3e136 a5c3e135 a5c3e136 +(54/256)*255 42572800 80000002 a536e17b a535e17b a536e17b +(54/256)*255 42572800 00000103 36c3e17b 35c3e17b 36c3e17b +(55/256)*255 425b2400 00000000 a5c3e137 a5c3e136 a5c3e137 +(55/256)*255 425b2400 00000001 a5c3377b a5c3367b a5c3377b +(55/256)*255 425b2400 00000002 a537e17b a536e17b a537e17b +(55/256)*255 425b2400 00000003 37c3e17b 36c3e17b 37c3e17b +(55/256)*255 425b2400 fffffffd a5c3377b a5c3367b a5c3377b +(55/256)*255 425b2400 fffffffc a5c3e137 a5c3e136 a5c3e137 +(55/256)*255 425b2400 80000002 a537e17b a536e17b a537e17b +(55/256)*255 425b2400 00000103 37c3e17b 36c3e17b 37c3e17b +(56/256)*255 425f2000 00000000 a5c3e138 a5c3e137 a5c3e138 +(56/256)*255 425f2000 00000001 a5c3387b a5c3377b a5c3387b +(56/256)*255 425f2000 00000002 a538e17b a537e17b a538e17b +(56/256)*255 425f2000 00000003 38c3e17b 37c3e17b 38c3e17b +(56/256)*255 425f2000 fffffffd a5c3387b a5c3377b a5c3387b +(56/256)*255 425f2000 fffffffc a5c3e138 a5c3e137 a5c3e138 +(56/256)*255 425f2000 80000002 a538e17b a537e17b a538e17b +(56/256)*255 425f2000 00000103 38c3e17b 37c3e17b 38c3e17b +(57/256)*255 42631c00 00000000 a5c3e139 a5c3e138 a5c3e139 +(57/256)*255 42631c00 00000001 a5c3397b a5c3387b a5c3397b +(57/256)*255 42631c00 00000002 a539e17b a538e17b a539e17b +(57/256)*255 42631c00 00000003 39c3e17b 38c3e17b 39c3e17b +(57/256)*255 42631c00 fffffffd a5c3397b a5c3387b a5c3397b +(57/256)*255 42631c00 fffffffc a5c3e139 a5c3e138 a5c3e139 +(57/256)*255 42631c00 80000002 a539e17b a538e17b a539e17b +(57/256)*255 42631c00 00000103 39c3e17b 38c3e17b 39c3e17b +(58/256)*255 42671800 00000000 a5c3e13a a5c3e139 a5c3e13a +(58/256)*255 42671800 00000001 a5c33a7b a5c3397b a5c33a7b +(58/256)*255 42671800 00000002 a53ae17b a539e17b a53ae17b +(58/256)*255 42671800 00000003 3ac3e17b 39c3e17b 3ac3e17b +(58/256)*255 42671800 fffffffd a5c33a7b a5c3397b a5c33a7b +(58/256)*255 42671800 fffffffc a5c3e13a a5c3e139 a5c3e13a +(58/256)*255 42671800 80000002 a53ae17b a539e17b a53ae17b +(58/256)*255 42671800 00000103 3ac3e17b 39c3e17b 3ac3e17b +(59/256)*255 426b1400 00000000 a5c3e13b a5c3e13a a5c3e13b +(59/256)*255 426b1400 00000001 a5c33b7b a5c33a7b a5c33b7b +(59/256)*255 426b1400 00000002 a53be17b a53ae17b a53be17b +(59/256)*255 426b1400 00000003 3bc3e17b 3ac3e17b 3bc3e17b +(59/256)*255 426b1400 fffffffd a5c33b7b a5c33a7b a5c33b7b +(59/256)*255 426b1400 fffffffc a5c3e13b a5c3e13a a5c3e13b +(59/256)*255 426b1400 80000002 a53be17b a53ae17b a53be17b +(59/256)*255 426b1400 00000103 3bc3e17b 3ac3e17b 3bc3e17b +(60/256)*255 426f1000 00000000 a5c3e13c a5c3e13b a5c3e13c +(60/256)*255 426f1000 00000001 a5c33c7b a5c33b7b a5c33c7b +(60/256)*255 426f1000 00000002 a53ce17b a53be17b a53ce17b +(60/256)*255 426f1000 00000003 3cc3e17b 3bc3e17b 3cc3e17b +(60/256)*255 426f1000 fffffffd a5c33c7b a5c33b7b a5c33c7b +(60/256)*255 426f1000 fffffffc a5c3e13c a5c3e13b a5c3e13c +(60/256)*255 426f1000 80000002 a53ce17b a53be17b a53ce17b +(60/256)*255 426f1000 00000103 3cc3e17b 3bc3e17b 3cc3e17b +(61/256)*255 42730c00 00000000 a5c3e13d a5c3e13c a5c3e13d +(61/256)*255 42730c00 00000001 a5c33d7b a5c33c7b a5c33d7b +(61/256)*255 42730c00 00000002 a53de17b a53ce17b a53de17b +(61/256)*255 42730c00 00000003 3dc3e17b 3cc3e17b 3dc3e17b +(61/256)*255 42730c00 fffffffd a5c33d7b a5c33c7b a5c33d7b +(61/256)*255 42730c00 fffffffc a5c3e13d a5c3e13c a5c3e13d +(61/256)*255 42730c00 80000002 a53de17b a53ce17b a53de17b +(61/256)*255 42730c00 00000103 3dc3e17b 3cc3e17b 3dc3e17b +(62/256)*255 42770800 00000000 a5c3e13e a5c3e13d a5c3e13e +(62/256)*255 42770800 00000001 a5c33e7b a5c33d7b a5c33e7b +(62/256)*255 42770800 00000002 a53ee17b a53de17b a53ee17b +(62/256)*255 42770800 00000003 3ec3e17b 3dc3e17b 3ec3e17b +(62/256)*255 42770800 fffffffd a5c33e7b a5c33d7b a5c33e7b +(62/256)*255 42770800 fffffffc a5c3e13e a5c3e13d a5c3e13e +(62/256)*255 42770800 80000002 a53ee17b a53de17b a53ee17b +(62/256)*255 42770800 00000103 3ec3e17b 3dc3e17b 3ec3e17b +(63/256)*255 427b0400 00000000 a5c3e13f a5c3e13e a5c3e13f +(63/256)*255 427b0400 00000001 a5c33f7b a5c33e7b a5c33f7b +(63/256)*255 427b0400 00000002 a53fe17b a53ee17b a53fe17b +(63/256)*255 427b0400 00000003 3fc3e17b 3ec3e17b 3fc3e17b +(63/256)*255 427b0400 fffffffd a5c33f7b a5c33e7b a5c33f7b +(63/256)*255 427b0400 fffffffc a5c3e13f a5c3e13e a5c3e13f +(63/256)*255 427b0400 80000002 a53fe17b a53ee17b a53fe17b +(63/256)*255 427b0400 00000103 3fc3e17b 3ec3e17b 3fc3e17b +(64/256)*255 427f0000 00000000 a5c3e140 a5c3e13f a5c3e140 +(64/256)*255 427f0000 00000001 a5c3407b a5c33f7b a5c3407b +(64/256)*255 427f0000 00000002 a540e17b a53fe17b a540e17b +(64/256)*255 427f0000 00000003 40c3e17b 3fc3e17b 40c3e17b +(64/256)*255 427f0000 fffffffd a5c3407b a5c33f7b a5c3407b +(64/256)*255 427f0000 fffffffc a5c3e140 a5c3e13f a5c3e140 +(64/256)*255 427f0000 80000002 a540e17b a53fe17b a540e17b +(64/256)*255 427f0000 00000103 40c3e17b 3fc3e17b 40c3e17b +(65/256)*255 42817e00 00000000 a5c3e141 a5c3e140 a5c3e141 +(65/256)*255 42817e00 00000001 a5c3417b a5c3407b a5c3417b +(65/256)*255 42817e00 00000002 a541e17b a540e17b a541e17b +(65/256)*255 42817e00 00000003 41c3e17b 40c3e17b 41c3e17b +(65/256)*255 42817e00 fffffffd a5c3417b a5c3407b a5c3417b +(65/256)*255 42817e00 fffffffc a5c3e141 a5c3e140 a5c3e141 +(65/256)*255 42817e00 80000002 a541e17b a540e17b a541e17b +(65/256)*255 42817e00 00000103 41c3e17b 40c3e17b 41c3e17b +(66/256)*255 42837c00 00000000 a5c3e142 a5c3e141 a5c3e142 +(66/256)*255 42837c00 00000001 a5c3427b a5c3417b a5c3427b +(66/256)*255 42837c00 00000002 a542e17b a541e17b a542e17b +(66/256)*255 42837c00 00000003 42c3e17b 41c3e17b 42c3e17b +(66/256)*255 42837c00 fffffffd a5c3427b a5c3417b a5c3427b +(66/256)*255 42837c00 fffffffc a5c3e142 a5c3e141 a5c3e142 +(66/256)*255 42837c00 80000002 a542e17b a541e17b a542e17b +(66/256)*255 42837c00 00000103 42c3e17b 41c3e17b 42c3e17b +(67/256)*255 42857a00 00000000 a5c3e143 a5c3e142 a5c3e143 +(67/256)*255 42857a00 00000001 a5c3437b a5c3427b a5c3437b +(67/256)*255 42857a00 00000002 a543e17b a542e17b a543e17b +(67/256)*255 42857a00 00000003 43c3e17b 42c3e17b 43c3e17b +(67/256)*255 42857a00 fffffffd a5c3437b a5c3427b a5c3437b +(67/256)*255 42857a00 fffffffc a5c3e143 a5c3e142 a5c3e143 +(67/256)*255 42857a00 80000002 a543e17b a542e17b a543e17b +(67/256)*255 42857a00 00000103 43c3e17b 42c3e17b 43c3e17b +(68/256)*255 42877800 00000000 a5c3e144 a5c3e143 a5c3e144 +(68/256)*255 42877800 00000001 a5c3447b a5c3437b a5c3447b +(68/256)*255 42877800 00000002 a544e17b a543e17b a544e17b +(68/256)*255 42877800 00000003 44c3e17b 43c3e17b 44c3e17b +(68/256)*255 42877800 fffffffd a5c3447b a5c3437b a5c3447b +(68/256)*255 42877800 fffffffc a5c3e144 a5c3e143 a5c3e144 +(68/256)*255 42877800 80000002 a544e17b a543e17b a544e17b +(68/256)*255 42877800 00000103 44c3e17b 43c3e17b 44c3e17b +(69/256)*255 42897600 00000000 a5c3e145 a5c3e144 a5c3e145 +(69/256)*255 42897600 00000001 a5c3457b a5c3447b a5c3457b +(69/256)*255 42897600 00000002 a545e17b a544e17b a545e17b +(69/256)*255 42897600 00000003 45c3e17b 44c3e17b 45c3e17b +(69/256)*255 42897600 fffffffd a5c3457b a5c3447b a5c3457b +(69/256)*255 42897600 fffffffc a5c3e145 a5c3e144 a5c3e145 +(69/256)*255 42897600 80000002 a545e17b a544e17b a545e17b +(69/256)*255 42897600 00000103 45c3e17b 44c3e17b 45c3e17b +(70/256)*255 428b7400 00000000 a5c3e146 a5c3e145 a5c3e146 +(70/256)*255 428b7400 00000001 a5c3467b a5c3457b a5c3467b +(70/256)*255 428b7400 00000002 a546e17b a545e17b a546e17b +(70/256)*255 428b7400 00000003 46c3e17b 45c3e17b 46c3e17b +(70/256)*255 428b7400 fffffffd a5c3467b a5c3457b a5c3467b +(70/256)*255 428b7400 fffffffc a5c3e146 a5c3e145 a5c3e146 +(70/256)*255 428b7400 80000002 a546e17b a545e17b a546e17b +(70/256)*255 428b7400 00000103 46c3e17b 45c3e17b 46c3e17b +(71/256)*255 428d7200 00000000 a5c3e147 a5c3e146 a5c3e147 +(71/256)*255 428d7200 00000001 a5c3477b a5c3467b a5c3477b +(71/256)*255 428d7200 00000002 a547e17b a546e17b a547e17b +(71/256)*255 428d7200 00000003 47c3e17b 46c3e17b 47c3e17b +(71/256)*255 428d7200 fffffffd a5c3477b a5c3467b a5c3477b +(71/256)*255 428d7200 fffffffc a5c3e147 a5c3e146 a5c3e147 +(71/256)*255 428d7200 80000002 a547e17b a546e17b a547e17b +(71/256)*255 428d7200 00000103 47c3e17b 46c3e17b 47c3e17b +(72/256)*255 428f7000 00000000 a5c3e148 a5c3e147 a5c3e148 +(72/256)*255 428f7000 00000001 a5c3487b a5c3477b a5c3487b +(72/256)*255 428f7000 00000002 a548e17b a547e17b a548e17b +(72/256)*255 428f7000 00000003 48c3e17b 47c3e17b 48c3e17b +(72/256)*255 428f7000 fffffffd a5c3487b a5c3477b a5c3487b +(72/256)*255 428f7000 fffffffc a5c3e148 a5c3e147 a5c3e148 +(72/256)*255 428f7000 80000002 a548e17b a547e17b a548e17b +(72/256)*255 428f7000 00000103 48c3e17b 47c3e17b 48c3e17b +(73/256)*255 42916e00 00000000 a5c3e149 a5c3e148 a5c3e149 +(73/256)*255 42916e00 00000001 a5c3497b a5c3487b a5c3497b +(73/256)*255 42916e00 00000002 a549e17b a548e17b a549e17b +(73/256)*255 42916e00 00000003 49c3e17b 48c3e17b 49c3e17b +(73/256)*255 42916e00 fffffffd a5c3497b a5c3487b a5c3497b +(73/256)*255 42916e00 fffffffc a5c3e149 a5c3e148 a5c3e149 +(73/256)*255 42916e00 80000002 a549e17b a548e17b a549e17b +(73/256)*255 42916e00 00000103 49c3e17b 48c3e17b 49c3e17b +(74/256)*255 42936c00 00000000 a5c3e14a a5c3e149 a5c3e14a +(74/256)*255 42936c00 00000001 a5c34a7b a5c3497b a5c34a7b +(74/256)*255 42936c00 00000002 a54ae17b a549e17b a54ae17b +(74/256)*255 42936c00 00000003 4ac3e17b 49c3e17b 4ac3e17b +(74/256)*255 42936c00 fffffffd a5c34a7b a5c3497b a5c34a7b +(74/256)*255 42936c00 fffffffc a5c3e14a a5c3e149 a5c3e14a +(74/256)*255 42936c00 80000002 a54ae17b a549e17b a54ae17b +(74/256)*255 42936c00 00000103 4ac3e17b 49c3e17b 4ac3e17b +(75/256)*255 42956a00 00000000 a5c3e14b a5c3e14a a5c3e14b +(75/256)*255 42956a00 00000001 a5c34b7b a5c34a7b a5c34b7b +(75/256)*255 42956a00 00000002 a54be17b a54ae17b a54be17b +(75/256)*255 42956a00 00000003 4bc3e17b 4ac3e17b 4bc3e17b +(75/256)*255 42956a00 fffffffd a5c34b7b a5c34a7b a5c34b7b +(75/256)*255 42956a00 fffffffc a5c3e14b a5c3e14a a5c3e14b +(75/256)*255 42956a00 80000002 a54be17b a54ae17b a54be17b +(75/256)*255 42956a00 00000103 4bc3e17b 4ac3e17b 4bc3e17b +(76/256)*255 42976800 00000000 a5c3e14c a5c3e14b a5c3e14c +(76/256)*255 42976800 00000001 a5c34c7b a5c34b7b a5c34c7b +(76/256)*255 42976800 00000002 a54ce17b a54be17b a54ce17b +(76/256)*255 42976800 00000003 4cc3e17b 4bc3e17b 4cc3e17b +(76/256)*255 42976800 fffffffd a5c34c7b a5c34b7b a5c34c7b +(76/256)*255 42976800 fffffffc a5c3e14c a5c3e14b a5c3e14c +(76/256)*255 42976800 80000002 a54ce17b a54be17b a54ce17b +(76/256)*255 42976800 00000103 4cc3e17b 4bc3e17b 4cc3e17b +(77/256)*255 42996600 00000000 a5c3e14d a5c3e14c a5c3e14d +(77/256)*255 42996600 00000001 a5c34d7b a5c34c7b a5c34d7b +(77/256)*255 42996600 00000002 a54de17b a54ce17b a54de17b +(77/256)*255 42996600 00000003 4dc3e17b 4cc3e17b 4dc3e17b +(77/256)*255 42996600 fffffffd a5c34d7b a5c34c7b a5c34d7b +(77/256)*255 42996600 fffffffc a5c3e14d a5c3e14c a5c3e14d +(77/256)*255 42996600 80000002 a54de17b a54ce17b a54de17b +(77/256)*255 42996600 00000103 4dc3e17b 4cc3e17b 4dc3e17b +(78/256)*255 429b6400 00000000 a5c3e14e a5c3e14d a5c3e14e +(78/256)*255 429b6400 00000001 a5c34e7b a5c34d7b a5c34e7b +(78/256)*255 429b6400 00000002 a54ee17b a54de17b a54ee17b +(78/256)*255 429b6400 00000003 4ec3e17b 4dc3e17b 4ec3e17b +(78/256)*255 429b6400 fffffffd a5c34e7b a5c34d7b a5c34e7b +(78/256)*255 429b6400 fffffffc a5c3e14e a5c3e14d a5c3e14e +(78/256)*255 429b6400 80000002 a54ee17b a54de17b a54ee17b +(78/256)*255 429b6400 00000103 4ec3e17b 4dc3e17b 4ec3e17b +(79/256)*255 429d6200 00000000 a5c3e14f a5c3e14e a5c3e14f +(79/256)*255 429d6200 00000001 a5c34f7b a5c34e7b a5c34f7b +(79/256)*255 429d6200 00000002 a54fe17b a54ee17b a54fe17b +(79/256)*255 429d6200 00000003 4fc3e17b 4ec3e17b 4fc3e17b +(79/256)*255 429d6200 fffffffd a5c34f7b a5c34e7b a5c34f7b +(79/256)*255 429d6200 fffffffc a5c3e14f a5c3e14e a5c3e14f +(79/256)*255 429d6200 80000002 a54fe17b a54ee17b a54fe17b +(79/256)*255 429d6200 00000103 4fc3e17b 4ec3e17b 4fc3e17b +(80/256)*255 429f6000 00000000 a5c3e150 a5c3e14f a5c3e150 +(80/256)*255 429f6000 00000001 a5c3507b a5c34f7b a5c3507b +(80/256)*255 429f6000 00000002 a550e17b a54fe17b a550e17b +(80/256)*255 429f6000 00000003 50c3e17b 4fc3e17b 50c3e17b +(80/256)*255 429f6000 fffffffd a5c3507b a5c34f7b a5c3507b +(80/256)*255 429f6000 fffffffc a5c3e150 a5c3e14f a5c3e150 +(80/256)*255 429f6000 80000002 a550e17b a54fe17b a550e17b +(80/256)*255 429f6000 00000103 50c3e17b 4fc3e17b 50c3e17b +(81/256)*255 42a15e00 00000000 a5c3e151 a5c3e150 a5c3e151 +(81/256)*255 42a15e00 00000001 a5c3517b a5c3507b a5c3517b +(81/256)*255 42a15e00 00000002 a551e17b a550e17b a551e17b +(81/256)*255 42a15e00 00000003 51c3e17b 50c3e17b 51c3e17b +(81/256)*255 42a15e00 fffffffd a5c3517b a5c3507b a5c3517b +(81/256)*255 42a15e00 fffffffc a5c3e151 a5c3e150 a5c3e151 +(81/256)*255 42a15e00 80000002 a551e17b a550e17b a551e17b +(81/256)*255 42a15e00 00000103 51c3e17b 50c3e17b 51c3e17b +(82/256)*255 42a35c00 00000000 a5c3e152 a5c3e151 a5c3e152 +(82/256)*255 42a35c00 00000001 a5c3527b a5c3517b a5c3527b +(82/256)*255 42a35c00 00000002 a552e17b a551e17b a552e17b +(82/256)*255 42a35c00 00000003 52c3e17b 51c3e17b 52c3e17b +(82/256)*255 42a35c00 fffffffd a5c3527b a5c3517b a5c3527b +(82/256)*255 42a35c00 fffffffc a5c3e152 a5c3e151 a5c3e152 +(82/256)*255 42a35c00 80000002 a552e17b a551e17b a552e17b +(82/256)*255 42a35c00 00000103 52c3e17b 51c3e17b 52c3e17b +(83/256)*255 42a55a00 00000000 a5c3e153 a5c3e152 a5c3e153 +(83/256)*255 42a55a00 00000001 a5c3537b a5c3527b a5c3537b +(83/256)*255 42a55a00 00000002 a553e17b a552e17b a553e17b +(83/256)*255 42a55a00 00000003 53c3e17b 52c3e17b 53c3e17b +(83/256)*255 42a55a00 fffffffd a5c3537b a5c3527b a5c3537b +(83/256)*255 42a55a00 fffffffc a5c3e153 a5c3e152 a5c3e153 +(83/256)*255 42a55a00 80000002 a553e17b a552e17b a553e17b +(83/256)*255 42a55a00 00000103 53c3e17b 52c3e17b 53c3e17b +(84/256)*255 42a75800 00000000 a5c3e154 a5c3e153 a5c3e154 +(84/256)*255 42a75800 00000001 a5c3547b a5c3537b a5c3547b +(84/256)*255 42a75800 00000002 a554e17b a553e17b a554e17b +(84/256)*255 42a75800 00000003 54c3e17b 53c3e17b 54c3e17b +(84/256)*255 42a75800 fffffffd a5c3547b a5c3537b a5c3547b +(84/256)*255 42a75800 fffffffc a5c3e154 a5c3e153 a5c3e154 +(84/256)*255 42a75800 80000002 a554e17b a553e17b a554e17b +(84/256)*255 42a75800 00000103 54c3e17b 53c3e17b 54c3e17b +(85/256)*255 42a95600 00000000 a5c3e155 a5c3e154 a5c3e155 +(85/256)*255 42a95600 00000001 a5c3557b a5c3547b a5c3557b +(85/256)*255 42a95600 00000002 a555e17b a554e17b a555e17b +(85/256)*255 42a95600 00000003 55c3e17b 54c3e17b 55c3e17b +(85/256)*255 42a95600 fffffffd a5c3557b a5c3547b a5c3557b +(85/256)*255 42a95600 fffffffc a5c3e155 a5c3e154 a5c3e155 +(85/256)*255 42a95600 80000002 a555e17b a554e17b a555e17b +(85/256)*255 42a95600 00000103 55c3e17b 54c3e17b 55c3e17b +(86/256)*255 42ab5400 00000000 a5c3e156 a5c3e155 a5c3e156 +(86/256)*255 42ab5400 00000001 a5c3567b a5c3557b a5c3567b +(86/256)*255 42ab5400 00000002 a556e17b a555e17b a556e17b +(86/256)*255 42ab5400 00000003 56c3e17b 55c3e17b 56c3e17b +(86/256)*255 42ab5400 fffffffd a5c3567b a5c3557b a5c3567b +(86/256)*255 42ab5400 fffffffc a5c3e156 a5c3e155 a5c3e156 +(86/256)*255 42ab5400 80000002 a556e17b a555e17b a556e17b +(86/256)*255 42ab5400 00000103 56c3e17b 55c3e17b 56c3e17b +(87/256)*255 42ad5200 00000000 a5c3e157 a5c3e156 a5c3e157 +(87/256)*255 42ad5200 00000001 a5c3577b a5c3567b a5c3577b +(87/256)*255 42ad5200 00000002 a557e17b a556e17b a557e17b +(87/256)*255 42ad5200 00000003 57c3e17b 56c3e17b 57c3e17b +(87/256)*255 42ad5200 fffffffd a5c3577b a5c3567b a5c3577b +(87/256)*255 42ad5200 fffffffc a5c3e157 a5c3e156 a5c3e157 +(87/256)*255 42ad5200 80000002 a557e17b a556e17b a557e17b +(87/256)*255 42ad5200 00000103 57c3e17b 56c3e17b 57c3e17b +(88/256)*255 42af5000 00000000 a5c3e158 a5c3e157 a5c3e158 +(88/256)*255 42af5000 00000001 a5c3587b a5c3577b a5c3587b +(88/256)*255 42af5000 00000002 a558e17b a557e17b a558e17b +(88/256)*255 42af5000 00000003 58c3e17b 57c3e17b 58c3e17b +(88/256)*255 42af5000 fffffffd a5c3587b a5c3577b a5c3587b +(88/256)*255 42af5000 fffffffc a5c3e158 a5c3e157 a5c3e158 +(88/256)*255 42af5000 80000002 a558e17b a557e17b a558e17b +(88/256)*255 42af5000 00000103 58c3e17b 57c3e17b 58c3e17b +(89/256)*255 42b14e00 00000000 a5c3e159 a5c3e158 a5c3e159 +(89/256)*255 42b14e00 00000001 a5c3597b a5c3587b a5c3597b +(89/256)*255 42b14e00 00000002 a559e17b a558e17b a559e17b +(89/256)*255 42b14e00 00000003 59c3e17b 58c3e17b 59c3e17b +(89/256)*255 42b14e00 fffffffd a5c3597b a5c3587b a5c3597b +(89/256)*255 42b14e00 fffffffc a5c3e159 a5c3e158 a5c3e159 +(89/256)*255 42b14e00 80000002 a559e17b a558e17b a559e17b +(89/256)*255 42b14e00 00000103 59c3e17b 58c3e17b 59c3e17b +(90/256)*255 42b34c00 00000000 a5c3e15a a5c3e159 a5c3e15a +(90/256)*255 42b34c00 00000001 a5c35a7b a5c3597b a5c35a7b +(90/256)*255 42b34c00 00000002 a55ae17b a559e17b a55ae17b +(90/256)*255 42b34c00 00000003 5ac3e17b 59c3e17b 5ac3e17b +(90/256)*255 42b34c00 fffffffd a5c35a7b a5c3597b a5c35a7b +(90/256)*255 42b34c00 fffffffc a5c3e15a a5c3e159 a5c3e15a +(90/256)*255 42b34c00 80000002 a55ae17b a559e17b a55ae17b +(90/256)*255 42b34c00 00000103 5ac3e17b 59c3e17b 5ac3e17b +(91/256)*255 42b54a00 00000000 a5c3e15b a5c3e15a a5c3e15b +(91/256)*255 42b54a00 00000001 a5c35b7b a5c35a7b a5c35b7b +(91/256)*255 42b54a00 00000002 a55be17b a55ae17b a55be17b +(91/256)*255 42b54a00 00000003 5bc3e17b 5ac3e17b 5bc3e17b +(91/256)*255 42b54a00 fffffffd a5c35b7b a5c35a7b a5c35b7b +(91/256)*255 42b54a00 fffffffc a5c3e15b a5c3e15a a5c3e15b +(91/256)*255 42b54a00 80000002 a55be17b a55ae17b a55be17b +(91/256)*255 42b54a00 00000103 5bc3e17b 5ac3e17b 5bc3e17b +(92/256)*255 42b74800 00000000 a5c3e15c a5c3e15b a5c3e15c +(92/256)*255 42b74800 00000001 a5c35c7b a5c35b7b a5c35c7b +(92/256)*255 42b74800 00000002 a55ce17b a55be17b a55ce17b +(92/256)*255 42b74800 00000003 5cc3e17b 5bc3e17b 5cc3e17b +(92/256)*255 42b74800 fffffffd a5c35c7b a5c35b7b a5c35c7b +(92/256)*255 42b74800 fffffffc a5c3e15c a5c3e15b a5c3e15c +(92/256)*255 42b74800 80000002 a55ce17b a55be17b a55ce17b +(92/256)*255 42b74800 00000103 5cc3e17b 5bc3e17b 5cc3e17b +(93/256)*255 42b94600 00000000 a5c3e15d a5c3e15c a5c3e15d +(93/256)*255 42b94600 00000001 a5c35d7b a5c35c7b a5c35d7b +(93/256)*255 42b94600 00000002 a55de17b a55ce17b a55de17b +(93/256)*255 42b94600 00000003 5dc3e17b 5cc3e17b 5dc3e17b +(93/256)*255 42b94600 fffffffd a5c35d7b a5c35c7b a5c35d7b +(93/256)*255 42b94600 fffffffc a5c3e15d a5c3e15c a5c3e15d +(93/256)*255 42b94600 80000002 a55de17b a55ce17b a55de17b +(93/256)*255 42b94600 00000103 5dc3e17b 5cc3e17b 5dc3e17b +(94/256)*255 42bb4400 00000000 a5c3e15e a5c3e15d a5c3e15e +(94/256)*255 42bb4400 00000001 a5c35e7b a5c35d7b a5c35e7b +(94/256)*255 42bb4400 00000002 a55ee17b a55de17b a55ee17b +(94/256)*255 42bb4400 00000003 5ec3e17b 5dc3e17b 5ec3e17b +(94/256)*255 42bb4400 fffffffd a5c35e7b a5c35d7b a5c35e7b +(94/256)*255 42bb4400 fffffffc a5c3e15e a5c3e15d a5c3e15e +(94/256)*255 42bb4400 80000002 a55ee17b a55de17b a55ee17b +(94/256)*255 42bb4400 00000103 5ec3e17b 5dc3e17b 5ec3e17b +(95/256)*255 42bd4200 00000000 a5c3e15f a5c3e15e a5c3e15f +(95/256)*255 42bd4200 00000001 a5c35f7b a5c35e7b a5c35f7b +(95/256)*255 42bd4200 00000002 a55fe17b a55ee17b a55fe17b +(95/256)*255 42bd4200 00000003 5fc3e17b 5ec3e17b 5fc3e17b +(95/256)*255 42bd4200 fffffffd a5c35f7b a5c35e7b a5c35f7b +(95/256)*255 42bd4200 fffffffc a5c3e15f a5c3e15e a5c3e15f +(95/256)*255 42bd4200 80000002 a55fe17b a55ee17b a55fe17b +(95/256)*255 42bd4200 00000103 5fc3e17b 5ec3e17b 5fc3e17b +(96/256)*255 42bf4000 00000000 a5c3e160 a5c3e15f a5c3e160 +(96/256)*255 42bf4000 00000001 a5c3607b a5c35f7b a5c3607b +(96/256)*255 42bf4000 00000002 a560e17b a55fe17b a560e17b +(96/256)*255 42bf4000 00000003 60c3e17b 5fc3e17b 60c3e17b +(96/256)*255 42bf4000 fffffffd a5c3607b a5c35f7b a5c3607b +(96/256)*255 42bf4000 fffffffc a5c3e160 a5c3e15f a5c3e160 +(96/256)*255 42bf4000 80000002 a560e17b a55fe17b a560e17b +(96/256)*255 42bf4000 00000103 60c3e17b 5fc3e17b 60c3e17b +(97/256)*255 42c13e00 00000000 a5c3e161 a5c3e160 a5c3e161 +(97/256)*255 42c13e00 00000001 a5c3617b a5c3607b a5c3617b +(97/256)*255 42c13e00 00000002 a561e17b a560e17b a561e17b +(97/256)*255 42c13e00 00000003 61c3e17b 60c3e17b 61c3e17b +(97/256)*255 42c13e00 fffffffd a5c3617b a5c3607b a5c3617b +(97/256)*255 42c13e00 fffffffc a5c3e161 a5c3e160 a5c3e161 +(97/256)*255 42c13e00 80000002 a561e17b a560e17b a561e17b +(97/256)*255 42c13e00 00000103 61c3e17b 60c3e17b 61c3e17b +(98/256)*255 42c33c00 00000000 a5c3e162 a5c3e161 a5c3e162 +(98/256)*255 42c33c00 00000001 a5c3627b a5c3617b a5c3627b +(98/256)*255 42c33c00 00000002 a562e17b a561e17b a562e17b +(98/256)*255 42c33c00 00000003 62c3e17b 61c3e17b 62c3e17b +(98/256)*255 42c33c00 fffffffd a5c3627b a5c3617b a5c3627b +(98/256)*255 42c33c00 fffffffc a5c3e162 a5c3e161 a5c3e162 +(98/256)*255 42c33c00 80000002 a562e17b a561e17b a562e17b +(98/256)*255 42c33c00 00000103 62c3e17b 61c3e17b 62c3e17b +(99/256)*255 42c53a00 00000000 a5c3e163 a5c3e162 a5c3e163 +(99/256)*255 42c53a00 00000001 a5c3637b a5c3627b a5c3637b +(99/256)*255 42c53a00 00000002 a563e17b a562e17b a563e17b +(99/256)*255 42c53a00 00000003 63c3e17b 62c3e17b 63c3e17b +(99/256)*255 42c53a00 fffffffd a5c3637b a5c3627b a5c3637b +(99/256)*255 42c53a00 fffffffc a5c3e163 a5c3e162 a5c3e163 +(99/256)*255 42c53a00 80000002 a563e17b a562e17b a563e17b +(99/256)*255 42c53a00 00000103 63c3e17b 62c3e17b 63c3e17b +(100/256)*255 42c73800 00000000 a5c3e164 a5c3e163 a5c3e164 +(100/256)*255 42c73800 00000001 a5c3647b a5c3637b a5c3647b +(100/256)*255 42c73800 00000002 a564e17b a563e17b a564e17b +(100/256)*255 42c73800 00000003 64c3e17b 63c3e17b 64c3e17b +(100/256)*255 42c73800 fffffffd a5c3647b a5c3637b a5c3647b +(100/256)*255 42c73800 fffffffc a5c3e164 a5c3e163 a5c3e164 +(100/256)*255 42c73800 80000002 a564e17b a563e17b a564e17b +(100/256)*255 42c73800 00000103 64c3e17b 63c3e17b 64c3e17b +(101/256)*255 42c93600 00000000 a5c3e165 a5c3e164 a5c3e165 +(101/256)*255 42c93600 00000001 a5c3657b a5c3647b a5c3657b +(101/256)*255 42c93600 00000002 a565e17b a564e17b a565e17b +(101/256)*255 42c93600 00000003 65c3e17b 64c3e17b 65c3e17b +(101/256)*255 42c93600 fffffffd a5c3657b a5c3647b a5c3657b +(101/256)*255 42c93600 fffffffc a5c3e165 a5c3e164 a5c3e165 +(101/256)*255 42c93600 80000002 a565e17b a564e17b a565e17b +(101/256)*255 42c93600 00000103 65c3e17b 64c3e17b 65c3e17b +(102/256)*255 42cb3400 00000000 a5c3e166 a5c3e165 a5c3e166 +(102/256)*255 42cb3400 00000001 a5c3667b a5c3657b a5c3667b +(102/256)*255 42cb3400 00000002 a566e17b a565e17b a566e17b +(102/256)*255 42cb3400 00000003 66c3e17b 65c3e17b 66c3e17b +(102/256)*255 42cb3400 fffffffd a5c3667b a5c3657b a5c3667b +(102/256)*255 42cb3400 fffffffc a5c3e166 a5c3e165 a5c3e166 +(102/256)*255 42cb3400 80000002 a566e17b a565e17b a566e17b +(102/256)*255 42cb3400 00000103 66c3e17b 65c3e17b 66c3e17b +(103/256)*255 42cd3200 00000000 a5c3e167 a5c3e166 a5c3e167 +(103/256)*255 42cd3200 00000001 a5c3677b a5c3667b a5c3677b +(103/256)*255 42cd3200 00000002 a567e17b a566e17b a567e17b +(103/256)*255 42cd3200 00000003 67c3e17b 66c3e17b 67c3e17b +(103/256)*255 42cd3200 fffffffd a5c3677b a5c3667b a5c3677b +(103/256)*255 42cd3200 fffffffc a5c3e167 a5c3e166 a5c3e167 +(103/256)*255 42cd3200 80000002 a567e17b a566e17b a567e17b +(103/256)*255 42cd3200 00000103 67c3e17b 66c3e17b 67c3e17b +(104/256)*255 42cf3000 00000000 a5c3e168 a5c3e167 a5c3e168 +(104/256)*255 42cf3000 00000001 a5c3687b a5c3677b a5c3687b +(104/256)*255 42cf3000 00000002 a568e17b a567e17b a568e17b +(104/256)*255 42cf3000 00000003 68c3e17b 67c3e17b 68c3e17b +(104/256)*255 42cf3000 fffffffd a5c3687b a5c3677b a5c3687b +(104/256)*255 42cf3000 fffffffc a5c3e168 a5c3e167 a5c3e168 +(104/256)*255 42cf3000 80000002 a568e17b a567e17b a568e17b +(104/256)*255 42cf3000 00000103 68c3e17b 67c3e17b 68c3e17b +(105/256)*255 42d12e00 00000000 a5c3e169 a5c3e168 a5c3e169 +(105/256)*255 42d12e00 00000001 a5c3697b a5c3687b a5c3697b +(105/256)*255 42d12e00 00000002 a569e17b a568e17b a569e17b +(105/256)*255 42d12e00 00000003 69c3e17b 68c3e17b 69c3e17b +(105/256)*255 42d12e00 fffffffd a5c3697b a5c3687b a5c3697b +(105/256)*255 42d12e00 fffffffc a5c3e169 a5c3e168 a5c3e169 +(105/256)*255 42d12e00 80000002 a569e17b a568e17b a569e17b +(105/256)*255 42d12e00 00000103 69c3e17b 68c3e17b 69c3e17b +(106/256)*255 42d32c00 00000000 a5c3e16a a5c3e169 a5c3e16a +(106/256)*255 42d32c00 00000001 a5c36a7b a5c3697b a5c36a7b +(106/256)*255 42d32c00 00000002 a56ae17b a569e17b a56ae17b +(106/256)*255 42d32c00 00000003 6ac3e17b 69c3e17b 6ac3e17b +(106/256)*255 42d32c00 fffffffd a5c36a7b a5c3697b a5c36a7b +(106/256)*255 42d32c00 fffffffc a5c3e16a a5c3e169 a5c3e16a +(106/256)*255 42d32c00 80000002 a56ae17b a569e17b a56ae17b +(106/256)*255 42d32c00 00000103 6ac3e17b 69c3e17b 6ac3e17b +(107/256)*255 42d52a00 00000000 a5c3e16b a5c3e16a a5c3e16b +(107/256)*255 42d52a00 00000001 a5c36b7b a5c36a7b a5c36b7b +(107/256)*255 42d52a00 00000002 a56be17b a56ae17b a56be17b +(107/256)*255 42d52a00 00000003 6bc3e17b 6ac3e17b 6bc3e17b +(107/256)*255 42d52a00 fffffffd a5c36b7b a5c36a7b a5c36b7b +(107/256)*255 42d52a00 fffffffc a5c3e16b a5c3e16a a5c3e16b +(107/256)*255 42d52a00 80000002 a56be17b a56ae17b a56be17b +(107/256)*255 42d52a00 00000103 6bc3e17b 6ac3e17b 6bc3e17b +(108/256)*255 42d72800 00000000 a5c3e16c a5c3e16b a5c3e16c +(108/256)*255 42d72800 00000001 a5c36c7b a5c36b7b a5c36c7b +(108/256)*255 42d72800 00000002 a56ce17b a56be17b a56ce17b +(108/256)*255 42d72800 00000003 6cc3e17b 6bc3e17b 6cc3e17b +(108/256)*255 42d72800 fffffffd a5c36c7b a5c36b7b a5c36c7b +(108/256)*255 42d72800 fffffffc a5c3e16c a5c3e16b a5c3e16c +(108/256)*255 42d72800 80000002 a56ce17b a56be17b a56ce17b +(108/256)*255 42d72800 00000103 6cc3e17b 6bc3e17b 6cc3e17b +(109/256)*255 42d92600 00000000 a5c3e16d a5c3e16c a5c3e16d +(109/256)*255 42d92600 00000001 a5c36d7b a5c36c7b a5c36d7b +(109/256)*255 42d92600 00000002 a56de17b a56ce17b a56de17b +(109/256)*255 42d92600 00000003 6dc3e17b 6cc3e17b 6dc3e17b +(109/256)*255 42d92600 fffffffd a5c36d7b a5c36c7b a5c36d7b +(109/256)*255 42d92600 fffffffc a5c3e16d a5c3e16c a5c3e16d +(109/256)*255 42d92600 80000002 a56de17b a56ce17b a56de17b +(109/256)*255 42d92600 00000103 6dc3e17b 6cc3e17b 6dc3e17b +(110/256)*255 42db2400 00000000 a5c3e16e a5c3e16d a5c3e16e +(110/256)*255 42db2400 00000001 a5c36e7b a5c36d7b a5c36e7b +(110/256)*255 42db2400 00000002 a56ee17b a56de17b a56ee17b +(110/256)*255 42db2400 00000003 6ec3e17b 6dc3e17b 6ec3e17b +(110/256)*255 42db2400 fffffffd a5c36e7b a5c36d7b a5c36e7b +(110/256)*255 42db2400 fffffffc a5c3e16e a5c3e16d a5c3e16e +(110/256)*255 42db2400 80000002 a56ee17b a56de17b a56ee17b +(110/256)*255 42db2400 00000103 6ec3e17b 6dc3e17b 6ec3e17b +(111/256)*255 42dd2200 00000000 a5c3e16f a5c3e16e a5c3e16f +(111/256)*255 42dd2200 00000001 a5c36f7b a5c36e7b a5c36f7b +(111/256)*255 42dd2200 00000002 a56fe17b a56ee17b a56fe17b +(111/256)*255 42dd2200 00000003 6fc3e17b 6ec3e17b 6fc3e17b +(111/256)*255 42dd2200 fffffffd a5c36f7b a5c36e7b a5c36f7b +(111/256)*255 42dd2200 fffffffc a5c3e16f a5c3e16e a5c3e16f +(111/256)*255 42dd2200 80000002 a56fe17b a56ee17b a56fe17b +(111/256)*255 42dd2200 00000103 6fc3e17b 6ec3e17b 6fc3e17b +(112/256)*255 42df2000 00000000 a5c3e170 a5c3e16f a5c3e170 +(112/256)*255 42df2000 00000001 a5c3707b a5c36f7b a5c3707b +(112/256)*255 42df2000 00000002 a570e17b a56fe17b a570e17b +(112/256)*255 42df2000 00000003 70c3e17b 6fc3e17b 70c3e17b +(112/256)*255 42df2000 fffffffd a5c3707b a5c36f7b a5c3707b +(112/256)*255 42df2000 fffffffc a5c3e170 a5c3e16f a5c3e170 +(112/256)*255 42df2000 80000002 a570e17b a56fe17b a570e17b +(112/256)*255 42df2000 00000103 70c3e17b 6fc3e17b 70c3e17b +(113/256)*255 42e11e00 00000000 a5c3e171 a5c3e170 a5c3e171 +(113/256)*255 42e11e00 00000001 a5c3717b a5c3707b a5c3717b +(113/256)*255 42e11e00 00000002 a571e17b a570e17b a571e17b +(113/256)*255 42e11e00 00000003 71c3e17b 70c3e17b 71c3e17b +(113/256)*255 42e11e00 fffffffd a5c3717b a5c3707b a5c3717b +(113/256)*255 42e11e00 fffffffc a5c3e171 a5c3e170 a5c3e171 +(113/256)*255 42e11e00 80000002 a571e17b a570e17b a571e17b +(113/256)*255 42e11e00 00000103 71c3e17b 70c3e17b 71c3e17b +(114/256)*255 42e31c00 00000000 a5c3e172 a5c3e171 a5c3e172 +(114/256)*255 42e31c00 00000001 a5c3727b a5c3717b a5c3727b +(114/256)*255 42e31c00 00000002 a572e17b a571e17b a572e17b +(114/256)*255 42e31c00 00000003 72c3e17b 71c3e17b 72c3e17b +(114/256)*255 42e31c00 fffffffd a5c3727b a5c3717b a5c3727b +(114/256)*255 42e31c00 fffffffc a5c3e172 a5c3e171 a5c3e172 +(114/256)*255 42e31c00 80000002 a572e17b a571e17b a572e17b +(114/256)*255 42e31c00 00000103 72c3e17b 71c3e17b 72c3e17b +(115/256)*255 42e51a00 00000000 a5c3e173 a5c3e172 a5c3e173 +(115/256)*255 42e51a00 00000001 a5c3737b a5c3727b a5c3737b +(115/256)*255 42e51a00 00000002 a573e17b a572e17b a573e17b +(115/256)*255 42e51a00 00000003 73c3e17b 72c3e17b 73c3e17b +(115/256)*255 42e51a00 fffffffd a5c3737b a5c3727b a5c3737b +(115/256)*255 42e51a00 fffffffc a5c3e173 a5c3e172 a5c3e173 +(115/256)*255 42e51a00 80000002 a573e17b a572e17b a573e17b +(115/256)*255 42e51a00 00000103 73c3e17b 72c3e17b 73c3e17b +(116/256)*255 42e71800 00000000 a5c3e174 a5c3e173 a5c3e174 +(116/256)*255 42e71800 00000001 a5c3747b a5c3737b a5c3747b +(116/256)*255 42e71800 00000002 a574e17b a573e17b a574e17b +(116/256)*255 42e71800 00000003 74c3e17b 73c3e17b 74c3e17b +(116/256)*255 42e71800 fffffffd a5c3747b a5c3737b a5c3747b +(116/256)*255 42e71800 fffffffc a5c3e174 a5c3e173 a5c3e174 +(116/256)*255 42e71800 80000002 a574e17b a573e17b a574e17b +(116/256)*255 42e71800 00000103 74c3e17b 73c3e17b 74c3e17b +(117/256)*255 42e91600 00000000 a5c3e175 a5c3e174 a5c3e175 +(117/256)*255 42e91600 00000001 a5c3757b a5c3747b a5c3757b +(117/256)*255 42e91600 00000002 a575e17b a574e17b a575e17b +(117/256)*255 42e91600 00000003 75c3e17b 74c3e17b 75c3e17b +(117/256)*255 42e91600 fffffffd a5c3757b a5c3747b a5c3757b +(117/256)*255 42e91600 fffffffc a5c3e175 a5c3e174 a5c3e175 +(117/256)*255 42e91600 80000002 a575e17b a574e17b a575e17b +(117/256)*255 42e91600 00000103 75c3e17b 74c3e17b 75c3e17b +(118/256)*255 42eb1400 00000000 a5c3e176 a5c3e175 a5c3e176 +(118/256)*255 42eb1400 00000001 a5c3767b a5c3757b a5c3767b +(118/256)*255 42eb1400 00000002 a576e17b a575e17b a576e17b +(118/256)*255 42eb1400 00000003 76c3e17b 75c3e17b 76c3e17b +(118/256)*255 42eb1400 fffffffd a5c3767b a5c3757b a5c3767b +(118/256)*255 42eb1400 fffffffc a5c3e176 a5c3e175 a5c3e176 +(118/256)*255 42eb1400 80000002 a576e17b a575e17b a576e17b +(118/256)*255 42eb1400 00000103 76c3e17b 75c3e17b 76c3e17b +(119/256)*255 42ed1200 00000000 a5c3e177 a5c3e176 a5c3e177 +(119/256)*255 42ed1200 00000001 a5c3777b a5c3767b a5c3777b +(119/256)*255 42ed1200 00000002 a577e17b a576e17b a577e17b +(119/256)*255 42ed1200 00000003 77c3e17b 76c3e17b 77c3e17b +(119/256)*255 42ed1200 fffffffd a5c3777b a5c3767b a5c3777b +(119/256)*255 42ed1200 fffffffc a5c3e177 a5c3e176 a5c3e177 +(119/256)*255 42ed1200 80000002 a577e17b a576e17b a577e17b +(119/256)*255 42ed1200 00000103 77c3e17b 76c3e17b 77c3e17b +(120/256)*255 42ef1000 00000000 a5c3e178 a5c3e177 a5c3e178 +(120/256)*255 42ef1000 00000001 a5c3787b a5c3777b a5c3787b +(120/256)*255 42ef1000 00000002 a578e17b a577e17b a578e17b +(120/256)*255 42ef1000 00000003 78c3e17b 77c3e17b 78c3e17b +(120/256)*255 42ef1000 fffffffd a5c3787b a5c3777b a5c3787b +(120/256)*255 42ef1000 fffffffc a5c3e178 a5c3e177 a5c3e178 +(120/256)*255 42ef1000 80000002 a578e17b a577e17b a578e17b +(120/256)*255 42ef1000 00000103 78c3e17b 77c3e17b 78c3e17b +(121/256)*255 42f10e00 00000000 a5c3e179 a5c3e178 a5c3e179 +(121/256)*255 42f10e00 00000001 a5c3797b a5c3787b a5c3797b +(121/256)*255 42f10e00 00000002 a579e17b a578e17b a579e17b +(121/256)*255 42f10e00 00000003 79c3e17b 78c3e17b 79c3e17b +(121/256)*255 42f10e00 fffffffd a5c3797b a5c3787b a5c3797b +(121/256)*255 42f10e00 fffffffc a5c3e179 a5c3e178 a5c3e179 +(121/256)*255 42f10e00 80000002 a579e17b a578e17b a579e17b +(121/256)*255 42f10e00 00000103 79c3e17b 78c3e17b 79c3e17b +(122/256)*255 42f30c00 00000000 a5c3e17a a5c3e179 a5c3e17a +(122/256)*255 42f30c00 00000001 a5c37a7b a5c3797b a5c37a7b +(122/256)*255 42f30c00 00000002 a57ae17b a579e17b a57ae17b +(122/256)*255 42f30c00 00000003 7ac3e17b 79c3e17b 7ac3e17b +(122/256)*255 42f30c00 fffffffd a5c37a7b a5c3797b a5c37a7b +(122/256)*255 42f30c00 fffffffc a5c3e17a a5c3e179 a5c3e17a +(122/256)*255 42f30c00 80000002 a57ae17b a579e17b a57ae17b +(122/256)*255 42f30c00 00000103 7ac3e17b 79c3e17b 7ac3e17b +(123/256)*255 42f50a00 00000000 a5c3e17b a5c3e17a a5c3e17b +(123/256)*255 42f50a00 00000001 a5c37b7b a5c37a7b a5c37b7b +(123/256)*255 42f50a00 00000002 a57be17b a57ae17b a57be17b +(123/256)*255 42f50a00 00000003 7bc3e17b 7ac3e17b 7bc3e17b +(123/256)*255 42f50a00 fffffffd a5c37b7b a5c37a7b a5c37b7b +(123/256)*255 42f50a00 fffffffc a5c3e17b a5c3e17a a5c3e17b +(123/256)*255 42f50a00 80000002 a57be17b a57ae17b a57be17b +(123/256)*255 42f50a00 00000103 7bc3e17b 7ac3e17b 7bc3e17b +(124/256)*255 42f70800 00000000 a5c3e17c a5c3e17b a5c3e17c +(124/256)*255 42f70800 00000001 a5c37c7b a5c37b7b a5c37c7b +(124/256)*255 42f70800 00000002 a57ce17b a57be17b a57ce17b +(124/256)*255 42f70800 00000003 7cc3e17b 7bc3e17b 7cc3e17b +(124/256)*255 42f70800 fffffffd a5c37c7b a5c37b7b a5c37c7b +(124/256)*255 42f70800 fffffffc a5c3e17c a5c3e17b a5c3e17c +(124/256)*255 42f70800 80000002 a57ce17b a57be17b a57ce17b +(124/256)*255 42f70800 00000103 7cc3e17b 7bc3e17b 7cc3e17b +(125/256)*255 42f90600 00000000 a5c3e17d a5c3e17c a5c3e17d +(125/256)*255 42f90600 00000001 a5c37d7b a5c37c7b a5c37d7b +(125/256)*255 42f90600 00000002 a57de17b a57ce17b a57de17b +(125/256)*255 42f90600 00000003 7dc3e17b 7cc3e17b 7dc3e17b +(125/256)*255 42f90600 fffffffd a5c37d7b a5c37c7b a5c37d7b +(125/256)*255 42f90600 fffffffc a5c3e17d a5c3e17c a5c3e17d +(125/256)*255 42f90600 80000002 a57de17b a57ce17b a57de17b +(125/256)*255 42f90600 00000103 7dc3e17b 7cc3e17b 7dc3e17b +(126/256)*255 42fb0400 00000000 a5c3e17e a5c3e17d a5c3e17e +(126/256)*255 42fb0400 00000001 a5c37e7b a5c37d7b a5c37e7b +(126/256)*255 42fb0400 00000002 a57ee17b a57de17b a57ee17b +(126/256)*255 42fb0400 00000003 7ec3e17b 7dc3e17b 7ec3e17b +(126/256)*255 42fb0400 fffffffd a5c37e7b a5c37d7b a5c37e7b +(126/256)*255 42fb0400 fffffffc a5c3e17e a5c3e17d a5c3e17e +(126/256)*255 42fb0400 80000002 a57ee17b a57de17b a57ee17b +(126/256)*255 42fb0400 00000103 7ec3e17b 7dc3e17b 7ec3e17b +(127/256)*255 42fd0200 00000000 a5c3e17f a5c3e17e a5c3e17f +(127/256)*255 42fd0200 00000001 a5c37f7b a5c37e7b a5c37f7b +(127/256)*255 42fd0200 00000002 a57fe17b a57ee17b a57fe17b +(127/256)*255 42fd0200 00000003 7fc3e17b 7ec3e17b 7fc3e17b +(127/256)*255 42fd0200 fffffffd a5c37f7b a5c37e7b a5c37f7b +(127/256)*255 42fd0200 fffffffc a5c3e17f a5c3e17e a5c3e17f +(127/256)*255 42fd0200 80000002 a57fe17b a57ee17b a57fe17b +(127/256)*255 42fd0200 00000103 7fc3e17b 7ec3e17b 7fc3e17b +(129/256)*255 43007f00 00000000 a5c3e180 a5c3e180 a5c3e180 +(129/256)*255 43007f00 00000001 a5c3807b a5c3807b a5c3807b +(129/256)*255 43007f00 00000002 a580e17b a580e17b a580e17b +(129/256)*255 43007f00 00000003 80c3e17b 80c3e17b 80c3e17b +(129/256)*255 43007f00 fffffffd a5c3807b a5c3807b a5c3807b +(129/256)*255 43007f00 fffffffc a5c3e180 a5c3e180 a5c3e180 +(129/256)*255 43007f00 80000002 a580e17b a580e17b a580e17b +(129/256)*255 43007f00 00000103 80c3e17b 80c3e17b 80c3e17b +(130/256)*255 43017e00 00000000 a5c3e181 a5c3e181 a5c3e181 +(130/256)*255 43017e00 00000001 a5c3817b a5c3817b a5c3817b +(130/256)*255 43017e00 00000002 a581e17b a581e17b a581e17b +(130/256)*255 43017e00 00000003 81c3e17b 81c3e17b 81c3e17b +(130/256)*255 43017e00 fffffffd a5c3817b a5c3817b a5c3817b +(130/256)*255 43017e00 fffffffc a5c3e181 a5c3e181 a5c3e181 +(130/256)*255 43017e00 80000002 a581e17b a581e17b a581e17b +(130/256)*255 43017e00 00000103 81c3e17b 81c3e17b 81c3e17b +(131/256)*255 43027d00 00000000 a5c3e182 a5c3e182 a5c3e182 +(131/256)*255 43027d00 00000001 a5c3827b a5c3827b a5c3827b +(131/256)*255 43027d00 00000002 a582e17b a582e17b a582e17b +(131/256)*255 43027d00 00000003 82c3e17b 82c3e17b 82c3e17b +(131/256)*255 43027d00 fffffffd a5c3827b a5c3827b a5c3827b +(131/256)*255 43027d00 fffffffc a5c3e182 a5c3e182 a5c3e182 +(131/256)*255 43027d00 80000002 a582e17b a582e17b a582e17b +(131/256)*255 43027d00 00000103 82c3e17b 82c3e17b 82c3e17b +(132/256)*255 43037c00 00000000 a5c3e183 a5c3e183 a5c3e183 +(132/256)*255 43037c00 00000001 a5c3837b a5c3837b a5c3837b +(132/256)*255 43037c00 00000002 a583e17b a583e17b a583e17b +(132/256)*255 43037c00 00000003 83c3e17b 83c3e17b 83c3e17b +(132/256)*255 43037c00 fffffffd a5c3837b a5c3837b a5c3837b +(132/256)*255 43037c00 fffffffc a5c3e183 a5c3e183 a5c3e183 +(132/256)*255 43037c00 80000002 a583e17b a583e17b a583e17b +(132/256)*255 43037c00 00000103 83c3e17b 83c3e17b 83c3e17b +(133/256)*255 43047b00 00000000 a5c3e184 a5c3e184 a5c3e184 +(133/256)*255 43047b00 00000001 a5c3847b a5c3847b a5c3847b +(133/256)*255 43047b00 00000002 a584e17b a584e17b a584e17b +(133/256)*255 43047b00 00000003 84c3e17b 84c3e17b 84c3e17b +(133/256)*255 43047b00 fffffffd a5c3847b a5c3847b a5c3847b +(133/256)*255 43047b00 fffffffc a5c3e184 a5c3e184 a5c3e184 +(133/256)*255 43047b00 80000002 a584e17b a584e17b a584e17b +(133/256)*255 43047b00 00000103 84c3e17b 84c3e17b 84c3e17b +(134/256)*255 43057a00 00000000 a5c3e185 a5c3e185 a5c3e185 +(134/256)*255 43057a00 00000001 a5c3857b a5c3857b a5c3857b +(134/256)*255 43057a00 00000002 a585e17b a585e17b a585e17b +(134/256)*255 43057a00 00000003 85c3e17b 85c3e17b 85c3e17b +(134/256)*255 43057a00 fffffffd a5c3857b a5c3857b a5c3857b +(134/256)*255 43057a00 fffffffc a5c3e185 a5c3e185 a5c3e185 +(134/256)*255 43057a00 80000002 a585e17b a585e17b a585e17b +(134/256)*255 43057a00 00000103 85c3e17b 85c3e17b 85c3e17b +(135/256)*255 43067900 00000000 a5c3e186 a5c3e186 a5c3e186 +(135/256)*255 43067900 00000001 a5c3867b a5c3867b a5c3867b +(135/256)*255 43067900 00000002 a586e17b a586e17b a586e17b +(135/256)*255 43067900 00000003 86c3e17b 86c3e17b 86c3e17b +(135/256)*255 43067900 fffffffd a5c3867b a5c3867b a5c3867b +(135/256)*255 43067900 fffffffc a5c3e186 a5c3e186 a5c3e186 +(135/256)*255 43067900 80000002 a586e17b a586e17b a586e17b +(135/256)*255 43067900 00000103 86c3e17b 86c3e17b 86c3e17b +(136/256)*255 43077800 00000000 a5c3e187 a5c3e187 a5c3e187 +(136/256)*255 43077800 00000001 a5c3877b a5c3877b a5c3877b +(136/256)*255 43077800 00000002 a587e17b a587e17b a587e17b +(136/256)*255 43077800 00000003 87c3e17b 87c3e17b 87c3e17b +(136/256)*255 43077800 fffffffd a5c3877b a5c3877b a5c3877b +(136/256)*255 43077800 fffffffc a5c3e187 a5c3e187 a5c3e187 +(136/256)*255 43077800 80000002 a587e17b a587e17b a587e17b +(136/256)*255 43077800 00000103 87c3e17b 87c3e17b 87c3e17b +(137/256)*255 43087700 00000000 a5c3e188 a5c3e188 a5c3e188 +(137/256)*255 43087700 00000001 a5c3887b a5c3887b a5c3887b +(137/256)*255 43087700 00000002 a588e17b a588e17b a588e17b +(137/256)*255 43087700 00000003 88c3e17b 88c3e17b 88c3e17b +(137/256)*255 43087700 fffffffd a5c3887b a5c3887b a5c3887b +(137/256)*255 43087700 fffffffc a5c3e188 a5c3e188 a5c3e188 +(137/256)*255 43087700 80000002 a588e17b a588e17b a588e17b +(137/256)*255 43087700 00000103 88c3e17b 88c3e17b 88c3e17b +(138/256)*255 43097600 00000000 a5c3e189 a5c3e189 a5c3e189 +(138/256)*255 43097600 00000001 a5c3897b a5c3897b a5c3897b +(138/256)*255 43097600 00000002 a589e17b a589e17b a589e17b +(138/256)*255 43097600 00000003 89c3e17b 89c3e17b 89c3e17b +(138/256)*255 43097600 fffffffd a5c3897b a5c3897b a5c3897b +(138/256)*255 43097600 fffffffc a5c3e189 a5c3e189 a5c3e189 +(138/256)*255 43097600 80000002 a589e17b a589e17b a589e17b +(138/256)*255 43097600 00000103 89c3e17b 89c3e17b 89c3e17b +(139/256)*255 430a7500 00000000 a5c3e18a a5c3e18a a5c3e18a +(139/256)*255 430a7500 00000001 a5c38a7b a5c38a7b a5c38a7b +(139/256)*255 430a7500 00000002 a58ae17b a58ae17b a58ae17b +(139/256)*255 430a7500 00000003 8ac3e17b 8ac3e17b 8ac3e17b +(139/256)*255 430a7500 fffffffd a5c38a7b a5c38a7b a5c38a7b +(139/256)*255 430a7500 fffffffc a5c3e18a a5c3e18a a5c3e18a +(139/256)*255 430a7500 80000002 a58ae17b a58ae17b a58ae17b +(139/256)*255 430a7500 00000103 8ac3e17b 8ac3e17b 8ac3e17b +(140/256)*255 430b7400 00000000 a5c3e18b a5c3e18b a5c3e18b +(140/256)*255 430b7400 00000001 a5c38b7b a5c38b7b a5c38b7b +(140/256)*255 430b7400 00000002 a58be17b a58be17b a58be17b +(140/256)*255 430b7400 00000003 8bc3e17b 8bc3e17b 8bc3e17b +(140/256)*255 430b7400 fffffffd a5c38b7b a5c38b7b a5c38b7b +(140/256)*255 430b7400 fffffffc a5c3e18b a5c3e18b a5c3e18b +(140/256)*255 430b7400 80000002 a58be17b a58be17b a58be17b +(140/256)*255 430b7400 00000103 8bc3e17b 8bc3e17b 8bc3e17b +(141/256)*255 430c7300 00000000 a5c3e18c a5c3e18c a5c3e18c +(141/256)*255 430c7300 00000001 a5c38c7b a5c38c7b a5c38c7b +(141/256)*255 430c7300 00000002 a58ce17b a58ce17b a58ce17b +(141/256)*255 430c7300 00000003 8cc3e17b 8cc3e17b 8cc3e17b +(141/256)*255 430c7300 fffffffd a5c38c7b a5c38c7b a5c38c7b +(141/256)*255 430c7300 fffffffc a5c3e18c a5c3e18c a5c3e18c +(141/256)*255 430c7300 80000002 a58ce17b a58ce17b a58ce17b +(141/256)*255 430c7300 00000103 8cc3e17b 8cc3e17b 8cc3e17b +(142/256)*255 430d7200 00000000 a5c3e18d a5c3e18d a5c3e18d +(142/256)*255 430d7200 00000001 a5c38d7b a5c38d7b a5c38d7b +(142/256)*255 430d7200 00000002 a58de17b a58de17b a58de17b +(142/256)*255 430d7200 00000003 8dc3e17b 8dc3e17b 8dc3e17b +(142/256)*255 430d7200 fffffffd a5c38d7b a5c38d7b a5c38d7b +(142/256)*255 430d7200 fffffffc a5c3e18d a5c3e18d a5c3e18d +(142/256)*255 430d7200 80000002 a58de17b a58de17b a58de17b +(142/256)*255 430d7200 00000103 8dc3e17b 8dc3e17b 8dc3e17b +(143/256)*255 430e7100 00000000 a5c3e18e a5c3e18e a5c3e18e +(143/256)*255 430e7100 00000001 a5c38e7b a5c38e7b a5c38e7b +(143/256)*255 430e7100 00000002 a58ee17b a58ee17b a58ee17b +(143/256)*255 430e7100 00000003 8ec3e17b 8ec3e17b 8ec3e17b +(143/256)*255 430e7100 fffffffd a5c38e7b a5c38e7b a5c38e7b +(143/256)*255 430e7100 fffffffc a5c3e18e a5c3e18e a5c3e18e +(143/256)*255 430e7100 80000002 a58ee17b a58ee17b a58ee17b +(143/256)*255 430e7100 00000103 8ec3e17b 8ec3e17b 8ec3e17b +(144/256)*255 430f7000 00000000 a5c3e18f a5c3e18f a5c3e18f +(144/256)*255 430f7000 00000001 a5c38f7b a5c38f7b a5c38f7b +(144/256)*255 430f7000 00000002 a58fe17b a58fe17b a58fe17b +(144/256)*255 430f7000 00000003 8fc3e17b 8fc3e17b 8fc3e17b +(144/256)*255 430f7000 fffffffd a5c38f7b a5c38f7b a5c38f7b +(144/256)*255 430f7000 fffffffc a5c3e18f a5c3e18f a5c3e18f +(144/256)*255 430f7000 80000002 a58fe17b a58fe17b a58fe17b +(144/256)*255 430f7000 00000103 8fc3e17b 8fc3e17b 8fc3e17b +(145/256)*255 43106f00 00000000 a5c3e190 a5c3e190 a5c3e190 +(145/256)*255 43106f00 00000001 a5c3907b a5c3907b a5c3907b +(145/256)*255 43106f00 00000002 a590e17b a590e17b a590e17b +(145/256)*255 43106f00 00000003 90c3e17b 90c3e17b 90c3e17b +(145/256)*255 43106f00 fffffffd a5c3907b a5c3907b a5c3907b +(145/256)*255 43106f00 fffffffc a5c3e190 a5c3e190 a5c3e190 +(145/256)*255 43106f00 80000002 a590e17b a590e17b a590e17b +(145/256)*255 43106f00 00000103 90c3e17b 90c3e17b 90c3e17b +(146/256)*255 43116e00 00000000 a5c3e191 a5c3e191 a5c3e191 +(146/256)*255 43116e00 00000001 a5c3917b a5c3917b a5c3917b +(146/256)*255 43116e00 00000002 a591e17b a591e17b a591e17b +(146/256)*255 43116e00 00000003 91c3e17b 91c3e17b 91c3e17b +(146/256)*255 43116e00 fffffffd a5c3917b a5c3917b a5c3917b +(146/256)*255 43116e00 fffffffc a5c3e191 a5c3e191 a5c3e191 +(146/256)*255 43116e00 80000002 a591e17b a591e17b a591e17b +(146/256)*255 43116e00 00000103 91c3e17b 91c3e17b 91c3e17b +(147/256)*255 43126d00 00000000 a5c3e192 a5c3e192 a5c3e192 +(147/256)*255 43126d00 00000001 a5c3927b a5c3927b a5c3927b +(147/256)*255 43126d00 00000002 a592e17b a592e17b a592e17b +(147/256)*255 43126d00 00000003 92c3e17b 92c3e17b 92c3e17b +(147/256)*255 43126d00 fffffffd a5c3927b a5c3927b a5c3927b +(147/256)*255 43126d00 fffffffc a5c3e192 a5c3e192 a5c3e192 +(147/256)*255 43126d00 80000002 a592e17b a592e17b a592e17b +(147/256)*255 43126d00 00000103 92c3e17b 92c3e17b 92c3e17b +(148/256)*255 43136c00 00000000 a5c3e193 a5c3e193 a5c3e193 +(148/256)*255 43136c00 00000001 a5c3937b a5c3937b a5c3937b +(148/256)*255 43136c00 00000002 a593e17b a593e17b a593e17b +(148/256)*255 43136c00 00000003 93c3e17b 93c3e17b 93c3e17b +(148/256)*255 43136c00 fffffffd a5c3937b a5c3937b a5c3937b +(148/256)*255 43136c00 fffffffc a5c3e193 a5c3e193 a5c3e193 +(148/256)*255 43136c00 80000002 a593e17b a593e17b a593e17b +(148/256)*255 43136c00 00000103 93c3e17b 93c3e17b 93c3e17b +(149/256)*255 43146b00 00000000 a5c3e194 a5c3e194 a5c3e194 +(149/256)*255 43146b00 00000001 a5c3947b a5c3947b a5c3947b +(149/256)*255 43146b00 00000002 a594e17b a594e17b a594e17b +(149/256)*255 43146b00 00000003 94c3e17b 94c3e17b 94c3e17b +(149/256)*255 43146b00 fffffffd a5c3947b a5c3947b a5c3947b +(149/256)*255 43146b00 fffffffc a5c3e194 a5c3e194 a5c3e194 +(149/256)*255 43146b00 80000002 a594e17b a594e17b a594e17b +(149/256)*255 43146b00 00000103 94c3e17b 94c3e17b 94c3e17b +(150/256)*255 43156a00 00000000 a5c3e195 a5c3e195 a5c3e195 +(150/256)*255 43156a00 00000001 a5c3957b a5c3957b a5c3957b +(150/256)*255 43156a00 00000002 a595e17b a595e17b a595e17b +(150/256)*255 43156a00 00000003 95c3e17b 95c3e17b 95c3e17b +(150/256)*255 43156a00 fffffffd a5c3957b a5c3957b a5c3957b +(150/256)*255 43156a00 fffffffc a5c3e195 a5c3e195 a5c3e195 +(150/256)*255 43156a00 80000002 a595e17b a595e17b a595e17b +(150/256)*255 43156a00 00000103 95c3e17b 95c3e17b 95c3e17b +(151/256)*255 43166900 00000000 a5c3e196 a5c3e196 a5c3e196 +(151/256)*255 43166900 00000001 a5c3967b a5c3967b a5c3967b +(151/256)*255 43166900 00000002 a596e17b a596e17b a596e17b +(151/256)*255 43166900 00000003 96c3e17b 96c3e17b 96c3e17b +(151/256)*255 43166900 fffffffd a5c3967b a5c3967b a5c3967b +(151/256)*255 43166900 fffffffc a5c3e196 a5c3e196 a5c3e196 +(151/256)*255 43166900 80000002 a596e17b a596e17b a596e17b +(151/256)*255 43166900 00000103 96c3e17b 96c3e17b 96c3e17b +(152/256)*255 43176800 00000000 a5c3e197 a5c3e197 a5c3e197 +(152/256)*255 43176800 00000001 a5c3977b a5c3977b a5c3977b +(152/256)*255 43176800 00000002 a597e17b a597e17b a597e17b +(152/256)*255 43176800 00000003 97c3e17b 97c3e17b 97c3e17b +(152/256)*255 43176800 fffffffd a5c3977b a5c3977b a5c3977b +(152/256)*255 43176800 fffffffc a5c3e197 a5c3e197 a5c3e197 +(152/256)*255 43176800 80000002 a597e17b a597e17b a597e17b +(152/256)*255 43176800 00000103 97c3e17b 97c3e17b 97c3e17b +(153/256)*255 43186700 00000000 a5c3e198 a5c3e198 a5c3e198 +(153/256)*255 43186700 00000001 a5c3987b a5c3987b a5c3987b +(153/256)*255 43186700 00000002 a598e17b a598e17b a598e17b +(153/256)*255 43186700 00000003 98c3e17b 98c3e17b 98c3e17b +(153/256)*255 43186700 fffffffd a5c3987b a5c3987b a5c3987b +(153/256)*255 43186700 fffffffc a5c3e198 a5c3e198 a5c3e198 +(153/256)*255 43186700 80000002 a598e17b a598e17b a598e17b +(153/256)*255 43186700 00000103 98c3e17b 98c3e17b 98c3e17b +(154/256)*255 43196600 00000000 a5c3e199 a5c3e199 a5c3e199 +(154/256)*255 43196600 00000001 a5c3997b a5c3997b a5c3997b +(154/256)*255 43196600 00000002 a599e17b a599e17b a599e17b +(154/256)*255 43196600 00000003 99c3e17b 99c3e17b 99c3e17b +(154/256)*255 43196600 fffffffd a5c3997b a5c3997b a5c3997b +(154/256)*255 43196600 fffffffc a5c3e199 a5c3e199 a5c3e199 +(154/256)*255 43196600 80000002 a599e17b a599e17b a599e17b +(154/256)*255 43196600 00000103 99c3e17b 99c3e17b 99c3e17b +(155/256)*255 431a6500 00000000 a5c3e19a a5c3e19a a5c3e19a +(155/256)*255 431a6500 00000001 a5c39a7b a5c39a7b a5c39a7b +(155/256)*255 431a6500 00000002 a59ae17b a59ae17b a59ae17b +(155/256)*255 431a6500 00000003 9ac3e17b 9ac3e17b 9ac3e17b +(155/256)*255 431a6500 fffffffd a5c39a7b a5c39a7b a5c39a7b +(155/256)*255 431a6500 fffffffc a5c3e19a a5c3e19a a5c3e19a +(155/256)*255 431a6500 80000002 a59ae17b a59ae17b a59ae17b +(155/256)*255 431a6500 00000103 9ac3e17b 9ac3e17b 9ac3e17b +(156/256)*255 431b6400 00000000 a5c3e19b a5c3e19b a5c3e19b +(156/256)*255 431b6400 00000001 a5c39b7b a5c39b7b a5c39b7b +(156/256)*255 431b6400 00000002 a59be17b a59be17b a59be17b +(156/256)*255 431b6400 00000003 9bc3e17b 9bc3e17b 9bc3e17b +(156/256)*255 431b6400 fffffffd a5c39b7b a5c39b7b a5c39b7b +(156/256)*255 431b6400 fffffffc a5c3e19b a5c3e19b a5c3e19b +(156/256)*255 431b6400 80000002 a59be17b a59be17b a59be17b +(156/256)*255 431b6400 00000103 9bc3e17b 9bc3e17b 9bc3e17b +(157/256)*255 431c6300 00000000 a5c3e19c a5c3e19c a5c3e19c +(157/256)*255 431c6300 00000001 a5c39c7b a5c39c7b a5c39c7b +(157/256)*255 431c6300 00000002 a59ce17b a59ce17b a59ce17b +(157/256)*255 431c6300 00000003 9cc3e17b 9cc3e17b 9cc3e17b +(157/256)*255 431c6300 fffffffd a5c39c7b a5c39c7b a5c39c7b +(157/256)*255 431c6300 fffffffc a5c3e19c a5c3e19c a5c3e19c +(157/256)*255 431c6300 80000002 a59ce17b a59ce17b a59ce17b +(157/256)*255 431c6300 00000103 9cc3e17b 9cc3e17b 9cc3e17b +(158/256)*255 431d6200 00000000 a5c3e19d a5c3e19d a5c3e19d +(158/256)*255 431d6200 00000001 a5c39d7b a5c39d7b a5c39d7b +(158/256)*255 431d6200 00000002 a59de17b a59de17b a59de17b +(158/256)*255 431d6200 00000003 9dc3e17b 9dc3e17b 9dc3e17b +(158/256)*255 431d6200 fffffffd a5c39d7b a5c39d7b a5c39d7b +(158/256)*255 431d6200 fffffffc a5c3e19d a5c3e19d a5c3e19d +(158/256)*255 431d6200 80000002 a59de17b a59de17b a59de17b +(158/256)*255 431d6200 00000103 9dc3e17b 9dc3e17b 9dc3e17b +(159/256)*255 431e6100 00000000 a5c3e19e a5c3e19e a5c3e19e +(159/256)*255 431e6100 00000001 a5c39e7b a5c39e7b a5c39e7b +(159/256)*255 431e6100 00000002 a59ee17b a59ee17b a59ee17b +(159/256)*255 431e6100 00000003 9ec3e17b 9ec3e17b 9ec3e17b +(159/256)*255 431e6100 fffffffd a5c39e7b a5c39e7b a5c39e7b +(159/256)*255 431e6100 fffffffc a5c3e19e a5c3e19e a5c3e19e +(159/256)*255 431e6100 80000002 a59ee17b a59ee17b a59ee17b +(159/256)*255 431e6100 00000103 9ec3e17b 9ec3e17b 9ec3e17b +(160/256)*255 431f6000 00000000 a5c3e19f a5c3e19f a5c3e19f +(160/256)*255 431f6000 00000001 a5c39f7b a5c39f7b a5c39f7b +(160/256)*255 431f6000 00000002 a59fe17b a59fe17b a59fe17b +(160/256)*255 431f6000 00000003 9fc3e17b 9fc3e17b 9fc3e17b +(160/256)*255 431f6000 fffffffd a5c39f7b a5c39f7b a5c39f7b +(160/256)*255 431f6000 fffffffc a5c3e19f a5c3e19f a5c3e19f +(160/256)*255 431f6000 80000002 a59fe17b a59fe17b a59fe17b +(160/256)*255 431f6000 00000103 9fc3e17b 9fc3e17b 9fc3e17b +(161/256)*255 43205f00 00000000 a5c3e1a0 a5c3e1a0 a5c3e1a0 +(161/256)*255 43205f00 00000001 a5c3a07b a5c3a07b a5c3a07b +(161/256)*255 43205f00 00000002 a5a0e17b a5a0e17b a5a0e17b +(161/256)*255 43205f00 00000003 a0c3e17b a0c3e17b a0c3e17b +(161/256)*255 43205f00 fffffffd a5c3a07b a5c3a07b a5c3a07b +(161/256)*255 43205f00 fffffffc a5c3e1a0 a5c3e1a0 a5c3e1a0 +(161/256)*255 43205f00 80000002 a5a0e17b a5a0e17b a5a0e17b +(161/256)*255 43205f00 00000103 a0c3e17b a0c3e17b a0c3e17b +(162/256)*255 43215e00 00000000 a5c3e1a1 a5c3e1a1 a5c3e1a1 +(162/256)*255 43215e00 00000001 a5c3a17b a5c3a17b a5c3a17b +(162/256)*255 43215e00 00000002 a5a1e17b a5a1e17b a5a1e17b +(162/256)*255 43215e00 00000003 a1c3e17b a1c3e17b a1c3e17b +(162/256)*255 43215e00 fffffffd a5c3a17b a5c3a17b a5c3a17b +(162/256)*255 43215e00 fffffffc a5c3e1a1 a5c3e1a1 a5c3e1a1 +(162/256)*255 43215e00 80000002 a5a1e17b a5a1e17b a5a1e17b +(162/256)*255 43215e00 00000103 a1c3e17b a1c3e17b a1c3e17b +(163/256)*255 43225d00 00000000 a5c3e1a2 a5c3e1a2 a5c3e1a2 +(163/256)*255 43225d00 00000001 a5c3a27b a5c3a27b a5c3a27b +(163/256)*255 43225d00 00000002 a5a2e17b a5a2e17b a5a2e17b +(163/256)*255 43225d00 00000003 a2c3e17b a2c3e17b a2c3e17b +(163/256)*255 43225d00 fffffffd a5c3a27b a5c3a27b a5c3a27b +(163/256)*255 43225d00 fffffffc a5c3e1a2 a5c3e1a2 a5c3e1a2 +(163/256)*255 43225d00 80000002 a5a2e17b a5a2e17b a5a2e17b +(163/256)*255 43225d00 00000103 a2c3e17b a2c3e17b a2c3e17b +(164/256)*255 43235c00 00000000 a5c3e1a3 a5c3e1a3 a5c3e1a3 +(164/256)*255 43235c00 00000001 a5c3a37b a5c3a37b a5c3a37b +(164/256)*255 43235c00 00000002 a5a3e17b a5a3e17b a5a3e17b +(164/256)*255 43235c00 00000003 a3c3e17b a3c3e17b a3c3e17b +(164/256)*255 43235c00 fffffffd a5c3a37b a5c3a37b a5c3a37b +(164/256)*255 43235c00 fffffffc a5c3e1a3 a5c3e1a3 a5c3e1a3 +(164/256)*255 43235c00 80000002 a5a3e17b a5a3e17b a5a3e17b +(164/256)*255 43235c00 00000103 a3c3e17b a3c3e17b a3c3e17b +(165/256)*255 43245b00 00000000 a5c3e1a4 a5c3e1a4 a5c3e1a4 +(165/256)*255 43245b00 00000001 a5c3a47b a5c3a47b a5c3a47b +(165/256)*255 43245b00 00000002 a5a4e17b a5a4e17b a5a4e17b +(165/256)*255 43245b00 00000003 a4c3e17b a4c3e17b a4c3e17b +(165/256)*255 43245b00 fffffffd a5c3a47b a5c3a47b a5c3a47b +(165/256)*255 43245b00 fffffffc a5c3e1a4 a5c3e1a4 a5c3e1a4 +(165/256)*255 43245b00 80000002 a5a4e17b a5a4e17b a5a4e17b +(165/256)*255 43245b00 00000103 a4c3e17b a4c3e17b a4c3e17b +(166/256)*255 43255a00 00000000 a5c3e1a5 a5c3e1a5 a5c3e1a5 +(166/256)*255 43255a00 00000001 a5c3a57b a5c3a57b a5c3a57b +(166/256)*255 43255a00 00000002 a5a5e17b a5a5e17b a5a5e17b +(166/256)*255 43255a00 00000003 a5c3e17b a5c3e17b a5c3e17b +(166/256)*255 43255a00 fffffffd a5c3a57b a5c3a57b a5c3a57b +(166/256)*255 43255a00 fffffffc a5c3e1a5 a5c3e1a5 a5c3e1a5 +(166/256)*255 43255a00 80000002 a5a5e17b a5a5e17b a5a5e17b +(166/256)*255 43255a00 00000103 a5c3e17b a5c3e17b a5c3e17b +(167/256)*255 43265900 00000000 a5c3e1a6 a5c3e1a6 a5c3e1a6 +(167/256)*255 43265900 00000001 a5c3a67b a5c3a67b a5c3a67b +(167/256)*255 43265900 00000002 a5a6e17b a5a6e17b a5a6e17b +(167/256)*255 43265900 00000003 a6c3e17b a6c3e17b a6c3e17b +(167/256)*255 43265900 fffffffd a5c3a67b a5c3a67b a5c3a67b +(167/256)*255 43265900 fffffffc a5c3e1a6 a5c3e1a6 a5c3e1a6 +(167/256)*255 43265900 80000002 a5a6e17b a5a6e17b a5a6e17b +(167/256)*255 43265900 00000103 a6c3e17b a6c3e17b a6c3e17b +(168/256)*255 43275800 00000000 a5c3e1a7 a5c3e1a7 a5c3e1a7 +(168/256)*255 43275800 00000001 a5c3a77b a5c3a77b a5c3a77b +(168/256)*255 43275800 00000002 a5a7e17b a5a7e17b a5a7e17b +(168/256)*255 43275800 00000003 a7c3e17b a7c3e17b a7c3e17b +(168/256)*255 43275800 fffffffd a5c3a77b a5c3a77b a5c3a77b +(168/256)*255 43275800 fffffffc a5c3e1a7 a5c3e1a7 a5c3e1a7 +(168/256)*255 43275800 80000002 a5a7e17b a5a7e17b a5a7e17b +(168/256)*255 43275800 00000103 a7c3e17b a7c3e17b a7c3e17b +(169/256)*255 43285700 00000000 a5c3e1a8 a5c3e1a8 a5c3e1a8 +(169/256)*255 43285700 00000001 a5c3a87b a5c3a87b a5c3a87b +(169/256)*255 43285700 00000002 a5a8e17b a5a8e17b a5a8e17b +(169/256)*255 43285700 00000003 a8c3e17b a8c3e17b a8c3e17b +(169/256)*255 43285700 fffffffd a5c3a87b a5c3a87b a5c3a87b +(169/256)*255 43285700 fffffffc a5c3e1a8 a5c3e1a8 a5c3e1a8 +(169/256)*255 43285700 80000002 a5a8e17b a5a8e17b a5a8e17b +(169/256)*255 43285700 00000103 a8c3e17b a8c3e17b a8c3e17b +(170/256)*255 43295600 00000000 a5c3e1a9 a5c3e1a9 a5c3e1a9 +(170/256)*255 43295600 00000001 a5c3a97b a5c3a97b a5c3a97b +(170/256)*255 43295600 00000002 a5a9e17b a5a9e17b a5a9e17b +(170/256)*255 43295600 00000003 a9c3e17b a9c3e17b a9c3e17b +(170/256)*255 43295600 fffffffd a5c3a97b a5c3a97b a5c3a97b +(170/256)*255 43295600 fffffffc a5c3e1a9 a5c3e1a9 a5c3e1a9 +(170/256)*255 43295600 80000002 a5a9e17b a5a9e17b a5a9e17b +(170/256)*255 43295600 00000103 a9c3e17b a9c3e17b a9c3e17b +(171/256)*255 432a5500 00000000 a5c3e1aa a5c3e1aa a5c3e1aa +(171/256)*255 432a5500 00000001 a5c3aa7b a5c3aa7b a5c3aa7b +(171/256)*255 432a5500 00000002 a5aae17b a5aae17b a5aae17b +(171/256)*255 432a5500 00000003 aac3e17b aac3e17b aac3e17b +(171/256)*255 432a5500 fffffffd a5c3aa7b a5c3aa7b a5c3aa7b +(171/256)*255 432a5500 fffffffc a5c3e1aa a5c3e1aa a5c3e1aa +(171/256)*255 432a5500 80000002 a5aae17b a5aae17b a5aae17b +(171/256)*255 432a5500 00000103 aac3e17b aac3e17b aac3e17b +(172/256)*255 432b5400 00000000 a5c3e1ab a5c3e1ab a5c3e1ab +(172/256)*255 432b5400 00000001 a5c3ab7b a5c3ab7b a5c3ab7b +(172/256)*255 432b5400 00000002 a5abe17b a5abe17b a5abe17b +(172/256)*255 432b5400 00000003 abc3e17b abc3e17b abc3e17b +(172/256)*255 432b5400 fffffffd a5c3ab7b a5c3ab7b a5c3ab7b +(172/256)*255 432b5400 fffffffc a5c3e1ab a5c3e1ab a5c3e1ab +(172/256)*255 432b5400 80000002 a5abe17b a5abe17b a5abe17b +(172/256)*255 432b5400 00000103 abc3e17b abc3e17b abc3e17b +(173/256)*255 432c5300 00000000 a5c3e1ac a5c3e1ac a5c3e1ac +(173/256)*255 432c5300 00000001 a5c3ac7b a5c3ac7b a5c3ac7b +(173/256)*255 432c5300 00000002 a5ace17b a5ace17b a5ace17b +(173/256)*255 432c5300 00000003 acc3e17b acc3e17b acc3e17b +(173/256)*255 432c5300 fffffffd a5c3ac7b a5c3ac7b a5c3ac7b +(173/256)*255 432c5300 fffffffc a5c3e1ac a5c3e1ac a5c3e1ac +(173/256)*255 432c5300 80000002 a5ace17b a5ace17b a5ace17b +(173/256)*255 432c5300 00000103 acc3e17b acc3e17b acc3e17b +(174/256)*255 432d5200 00000000 a5c3e1ad a5c3e1ad a5c3e1ad +(174/256)*255 432d5200 00000001 a5c3ad7b a5c3ad7b a5c3ad7b +(174/256)*255 432d5200 00000002 a5ade17b a5ade17b a5ade17b +(174/256)*255 432d5200 00000003 adc3e17b adc3e17b adc3e17b +(174/256)*255 432d5200 fffffffd a5c3ad7b a5c3ad7b a5c3ad7b +(174/256)*255 432d5200 fffffffc a5c3e1ad a5c3e1ad a5c3e1ad +(174/256)*255 432d5200 80000002 a5ade17b a5ade17b a5ade17b +(174/256)*255 432d5200 00000103 adc3e17b adc3e17b adc3e17b +(175/256)*255 432e5100 00000000 a5c3e1ae a5c3e1ae a5c3e1ae +(175/256)*255 432e5100 00000001 a5c3ae7b a5c3ae7b a5c3ae7b +(175/256)*255 432e5100 00000002 a5aee17b a5aee17b a5aee17b +(175/256)*255 432e5100 00000003 aec3e17b aec3e17b aec3e17b +(175/256)*255 432e5100 fffffffd a5c3ae7b a5c3ae7b a5c3ae7b +(175/256)*255 432e5100 fffffffc a5c3e1ae a5c3e1ae a5c3e1ae +(175/256)*255 432e5100 80000002 a5aee17b a5aee17b a5aee17b +(175/256)*255 432e5100 00000103 aec3e17b aec3e17b aec3e17b +(176/256)*255 432f5000 00000000 a5c3e1af a5c3e1af a5c3e1af +(176/256)*255 432f5000 00000001 a5c3af7b a5c3af7b a5c3af7b +(176/256)*255 432f5000 00000002 a5afe17b a5afe17b a5afe17b +(176/256)*255 432f5000 00000003 afc3e17b afc3e17b afc3e17b +(176/256)*255 432f5000 fffffffd a5c3af7b a5c3af7b a5c3af7b +(176/256)*255 432f5000 fffffffc a5c3e1af a5c3e1af a5c3e1af +(176/256)*255 432f5000 80000002 a5afe17b a5afe17b a5afe17b +(176/256)*255 432f5000 00000103 afc3e17b afc3e17b afc3e17b +(177/256)*255 43304f00 00000000 a5c3e1b0 a5c3e1b0 a5c3e1b0 +(177/256)*255 43304f00 00000001 a5c3b07b a5c3b07b a5c3b07b +(177/256)*255 43304f00 00000002 a5b0e17b a5b0e17b a5b0e17b +(177/256)*255 43304f00 00000003 b0c3e17b b0c3e17b b0c3e17b +(177/256)*255 43304f00 fffffffd a5c3b07b a5c3b07b a5c3b07b +(177/256)*255 43304f00 fffffffc a5c3e1b0 a5c3e1b0 a5c3e1b0 +(177/256)*255 43304f00 80000002 a5b0e17b a5b0e17b a5b0e17b +(177/256)*255 43304f00 00000103 b0c3e17b b0c3e17b b0c3e17b +(178/256)*255 43314e00 00000000 a5c3e1b1 a5c3e1b1 a5c3e1b1 +(178/256)*255 43314e00 00000001 a5c3b17b a5c3b17b a5c3b17b +(178/256)*255 43314e00 00000002 a5b1e17b a5b1e17b a5b1e17b +(178/256)*255 43314e00 00000003 b1c3e17b b1c3e17b b1c3e17b +(178/256)*255 43314e00 fffffffd a5c3b17b a5c3b17b a5c3b17b +(178/256)*255 43314e00 fffffffc a5c3e1b1 a5c3e1b1 a5c3e1b1 +(178/256)*255 43314e00 80000002 a5b1e17b a5b1e17b a5b1e17b +(178/256)*255 43314e00 00000103 b1c3e17b b1c3e17b b1c3e17b +(179/256)*255 43324d00 00000000 a5c3e1b2 a5c3e1b2 a5c3e1b2 +(179/256)*255 43324d00 00000001 a5c3b27b a5c3b27b a5c3b27b +(179/256)*255 43324d00 00000002 a5b2e17b a5b2e17b a5b2e17b +(179/256)*255 43324d00 00000003 b2c3e17b b2c3e17b b2c3e17b +(179/256)*255 43324d00 fffffffd a5c3b27b a5c3b27b a5c3b27b +(179/256)*255 43324d00 fffffffc a5c3e1b2 a5c3e1b2 a5c3e1b2 +(179/256)*255 43324d00 80000002 a5b2e17b a5b2e17b a5b2e17b +(179/256)*255 43324d00 00000103 b2c3e17b b2c3e17b b2c3e17b +(180/256)*255 43334c00 00000000 a5c3e1b3 a5c3e1b3 a5c3e1b3 +(180/256)*255 43334c00 00000001 a5c3b37b a5c3b37b a5c3b37b +(180/256)*255 43334c00 00000002 a5b3e17b a5b3e17b a5b3e17b +(180/256)*255 43334c00 00000003 b3c3e17b b3c3e17b b3c3e17b +(180/256)*255 43334c00 fffffffd a5c3b37b a5c3b37b a5c3b37b +(180/256)*255 43334c00 fffffffc a5c3e1b3 a5c3e1b3 a5c3e1b3 +(180/256)*255 43334c00 80000002 a5b3e17b a5b3e17b a5b3e17b +(180/256)*255 43334c00 00000103 b3c3e17b b3c3e17b b3c3e17b +(181/256)*255 43344b00 00000000 a5c3e1b4 a5c3e1b4 a5c3e1b4 +(181/256)*255 43344b00 00000001 a5c3b47b a5c3b47b a5c3b47b +(181/256)*255 43344b00 00000002 a5b4e17b a5b4e17b a5b4e17b +(181/256)*255 43344b00 00000003 b4c3e17b b4c3e17b b4c3e17b +(181/256)*255 43344b00 fffffffd a5c3b47b a5c3b47b a5c3b47b +(181/256)*255 43344b00 fffffffc a5c3e1b4 a5c3e1b4 a5c3e1b4 +(181/256)*255 43344b00 80000002 a5b4e17b a5b4e17b a5b4e17b +(181/256)*255 43344b00 00000103 b4c3e17b b4c3e17b b4c3e17b +(182/256)*255 43354a00 00000000 a5c3e1b5 a5c3e1b5 a5c3e1b5 +(182/256)*255 43354a00 00000001 a5c3b57b a5c3b57b a5c3b57b +(182/256)*255 43354a00 00000002 a5b5e17b a5b5e17b a5b5e17b +(182/256)*255 43354a00 00000003 b5c3e17b b5c3e17b b5c3e17b +(182/256)*255 43354a00 fffffffd a5c3b57b a5c3b57b a5c3b57b +(182/256)*255 43354a00 fffffffc a5c3e1b5 a5c3e1b5 a5c3e1b5 +(182/256)*255 43354a00 80000002 a5b5e17b a5b5e17b a5b5e17b +(182/256)*255 43354a00 00000103 b5c3e17b b5c3e17b b5c3e17b +(183/256)*255 43364900 00000000 a5c3e1b6 a5c3e1b6 a5c3e1b6 +(183/256)*255 43364900 00000001 a5c3b67b a5c3b67b a5c3b67b +(183/256)*255 43364900 00000002 a5b6e17b a5b6e17b a5b6e17b +(183/256)*255 43364900 00000003 b6c3e17b b6c3e17b b6c3e17b +(183/256)*255 43364900 fffffffd a5c3b67b a5c3b67b a5c3b67b +(183/256)*255 43364900 fffffffc a5c3e1b6 a5c3e1b6 a5c3e1b6 +(183/256)*255 43364900 80000002 a5b6e17b a5b6e17b a5b6e17b +(183/256)*255 43364900 00000103 b6c3e17b b6c3e17b b6c3e17b +(184/256)*255 43374800 00000000 a5c3e1b7 a5c3e1b7 a5c3e1b7 +(184/256)*255 43374800 00000001 a5c3b77b a5c3b77b a5c3b77b +(184/256)*255 43374800 00000002 a5b7e17b a5b7e17b a5b7e17b +(184/256)*255 43374800 00000003 b7c3e17b b7c3e17b b7c3e17b +(184/256)*255 43374800 fffffffd a5c3b77b a5c3b77b a5c3b77b +(184/256)*255 43374800 fffffffc a5c3e1b7 a5c3e1b7 a5c3e1b7 +(184/256)*255 43374800 80000002 a5b7e17b a5b7e17b a5b7e17b +(184/256)*255 43374800 00000103 b7c3e17b b7c3e17b b7c3e17b +(185/256)*255 43384700 00000000 a5c3e1b8 a5c3e1b8 a5c3e1b8 +(185/256)*255 43384700 00000001 a5c3b87b a5c3b87b a5c3b87b +(185/256)*255 43384700 00000002 a5b8e17b a5b8e17b a5b8e17b +(185/256)*255 43384700 00000003 b8c3e17b b8c3e17b b8c3e17b +(185/256)*255 43384700 fffffffd a5c3b87b a5c3b87b a5c3b87b +(185/256)*255 43384700 fffffffc a5c3e1b8 a5c3e1b8 a5c3e1b8 +(185/256)*255 43384700 80000002 a5b8e17b a5b8e17b a5b8e17b +(185/256)*255 43384700 00000103 b8c3e17b b8c3e17b b8c3e17b +(186/256)*255 43394600 00000000 a5c3e1b9 a5c3e1b9 a5c3e1b9 +(186/256)*255 43394600 00000001 a5c3b97b a5c3b97b a5c3b97b +(186/256)*255 43394600 00000002 a5b9e17b a5b9e17b a5b9e17b +(186/256)*255 43394600 00000003 b9c3e17b b9c3e17b b9c3e17b +(186/256)*255 43394600 fffffffd a5c3b97b a5c3b97b a5c3b97b +(186/256)*255 43394600 fffffffc a5c3e1b9 a5c3e1b9 a5c3e1b9 +(186/256)*255 43394600 80000002 a5b9e17b a5b9e17b a5b9e17b +(186/256)*255 43394600 00000103 b9c3e17b b9c3e17b b9c3e17b +(187/256)*255 433a4500 00000000 a5c3e1ba a5c3e1ba a5c3e1ba +(187/256)*255 433a4500 00000001 a5c3ba7b a5c3ba7b a5c3ba7b +(187/256)*255 433a4500 00000002 a5bae17b a5bae17b a5bae17b +(187/256)*255 433a4500 00000003 bac3e17b bac3e17b bac3e17b +(187/256)*255 433a4500 fffffffd a5c3ba7b a5c3ba7b a5c3ba7b +(187/256)*255 433a4500 fffffffc a5c3e1ba a5c3e1ba a5c3e1ba +(187/256)*255 433a4500 80000002 a5bae17b a5bae17b a5bae17b +(187/256)*255 433a4500 00000103 bac3e17b bac3e17b bac3e17b +(188/256)*255 433b4400 00000000 a5c3e1bb a5c3e1bb a5c3e1bb +(188/256)*255 433b4400 00000001 a5c3bb7b a5c3bb7b a5c3bb7b +(188/256)*255 433b4400 00000002 a5bbe17b a5bbe17b a5bbe17b +(188/256)*255 433b4400 00000003 bbc3e17b bbc3e17b bbc3e17b +(188/256)*255 433b4400 fffffffd a5c3bb7b a5c3bb7b a5c3bb7b +(188/256)*255 433b4400 fffffffc a5c3e1bb a5c3e1bb a5c3e1bb +(188/256)*255 433b4400 80000002 a5bbe17b a5bbe17b a5bbe17b +(188/256)*255 433b4400 00000103 bbc3e17b bbc3e17b bbc3e17b +(189/256)*255 433c4300 00000000 a5c3e1bc a5c3e1bc a5c3e1bc +(189/256)*255 433c4300 00000001 a5c3bc7b a5c3bc7b a5c3bc7b +(189/256)*255 433c4300 00000002 a5bce17b a5bce17b a5bce17b +(189/256)*255 433c4300 00000003 bcc3e17b bcc3e17b bcc3e17b +(189/256)*255 433c4300 fffffffd a5c3bc7b a5c3bc7b a5c3bc7b +(189/256)*255 433c4300 fffffffc a5c3e1bc a5c3e1bc a5c3e1bc +(189/256)*255 433c4300 80000002 a5bce17b a5bce17b a5bce17b +(189/256)*255 433c4300 00000103 bcc3e17b bcc3e17b bcc3e17b +(190/256)*255 433d4200 00000000 a5c3e1bd a5c3e1bd a5c3e1bd +(190/256)*255 433d4200 00000001 a5c3bd7b a5c3bd7b a5c3bd7b +(190/256)*255 433d4200 00000002 a5bde17b a5bde17b a5bde17b +(190/256)*255 433d4200 00000003 bdc3e17b bdc3e17b bdc3e17b +(190/256)*255 433d4200 fffffffd a5c3bd7b a5c3bd7b a5c3bd7b +(190/256)*255 433d4200 fffffffc a5c3e1bd a5c3e1bd a5c3e1bd +(190/256)*255 433d4200 80000002 a5bde17b a5bde17b a5bde17b +(190/256)*255 433d4200 00000103 bdc3e17b bdc3e17b bdc3e17b +(191/256)*255 433e4100 00000000 a5c3e1be a5c3e1be a5c3e1be +(191/256)*255 433e4100 00000001 a5c3be7b a5c3be7b a5c3be7b +(191/256)*255 433e4100 00000002 a5bee17b a5bee17b a5bee17b +(191/256)*255 433e4100 00000003 bec3e17b bec3e17b bec3e17b +(191/256)*255 433e4100 fffffffd a5c3be7b a5c3be7b a5c3be7b +(191/256)*255 433e4100 fffffffc a5c3e1be a5c3e1be a5c3e1be +(191/256)*255 433e4100 80000002 a5bee17b a5bee17b a5bee17b +(191/256)*255 433e4100 00000103 bec3e17b bec3e17b bec3e17b +(192/256)*255 433f4000 00000000 a5c3e1bf a5c3e1bf a5c3e1bf +(192/256)*255 433f4000 00000001 a5c3bf7b a5c3bf7b a5c3bf7b +(192/256)*255 433f4000 00000002 a5bfe17b a5bfe17b a5bfe17b +(192/256)*255 433f4000 00000003 bfc3e17b bfc3e17b bfc3e17b +(192/256)*255 433f4000 fffffffd a5c3bf7b a5c3bf7b a5c3bf7b +(192/256)*255 433f4000 fffffffc a5c3e1bf a5c3e1bf a5c3e1bf +(192/256)*255 433f4000 80000002 a5bfe17b a5bfe17b a5bfe17b +(192/256)*255 433f4000 00000103 bfc3e17b bfc3e17b bfc3e17b +(193/256)*255 43403f00 00000000 a5c3e1c0 a5c3e1c0 a5c3e1c0 +(193/256)*255 43403f00 00000001 a5c3c07b a5c3c07b a5c3c07b +(193/256)*255 43403f00 00000002 a5c0e17b a5c0e17b a5c0e17b +(193/256)*255 43403f00 00000003 c0c3e17b c0c3e17b c0c3e17b +(193/256)*255 43403f00 fffffffd a5c3c07b a5c3c07b a5c3c07b +(193/256)*255 43403f00 fffffffc a5c3e1c0 a5c3e1c0 a5c3e1c0 +(193/256)*255 43403f00 80000002 a5c0e17b a5c0e17b a5c0e17b +(193/256)*255 43403f00 00000103 c0c3e17b c0c3e17b c0c3e17b +(194/256)*255 43413e00 00000000 a5c3e1c1 a5c3e1c1 a5c3e1c1 +(194/256)*255 43413e00 00000001 a5c3c17b a5c3c17b a5c3c17b +(194/256)*255 43413e00 00000002 a5c1e17b a5c1e17b a5c1e17b +(194/256)*255 43413e00 00000003 c1c3e17b c1c3e17b c1c3e17b +(194/256)*255 43413e00 fffffffd a5c3c17b a5c3c17b a5c3c17b +(194/256)*255 43413e00 fffffffc a5c3e1c1 a5c3e1c1 a5c3e1c1 +(194/256)*255 43413e00 80000002 a5c1e17b a5c1e17b a5c1e17b +(194/256)*255 43413e00 00000103 c1c3e17b c1c3e17b c1c3e17b +(195/256)*255 43423d00 00000000 a5c3e1c2 a5c3e1c2 a5c3e1c2 +(195/256)*255 43423d00 00000001 a5c3c27b a5c3c27b a5c3c27b +(195/256)*255 43423d00 00000002 a5c2e17b a5c2e17b a5c2e17b +(195/256)*255 43423d00 00000003 c2c3e17b c2c3e17b c2c3e17b +(195/256)*255 43423d00 fffffffd a5c3c27b a5c3c27b a5c3c27b +(195/256)*255 43423d00 fffffffc a5c3e1c2 a5c3e1c2 a5c3e1c2 +(195/256)*255 43423d00 80000002 a5c2e17b a5c2e17b a5c2e17b +(195/256)*255 43423d00 00000103 c2c3e17b c2c3e17b c2c3e17b +(196/256)*255 43433c00 00000000 a5c3e1c3 a5c3e1c3 a5c3e1c3 +(196/256)*255 43433c00 00000001 a5c3c37b a5c3c37b a5c3c37b +(196/256)*255 43433c00 00000002 a5c3e17b a5c3e17b a5c3e17b +(196/256)*255 43433c00 00000003 c3c3e17b c3c3e17b c3c3e17b +(196/256)*255 43433c00 fffffffd a5c3c37b a5c3c37b a5c3c37b +(196/256)*255 43433c00 fffffffc a5c3e1c3 a5c3e1c3 a5c3e1c3 +(196/256)*255 43433c00 80000002 a5c3e17b a5c3e17b a5c3e17b +(196/256)*255 43433c00 00000103 c3c3e17b c3c3e17b c3c3e17b +(197/256)*255 43443b00 00000000 a5c3e1c4 a5c3e1c4 a5c3e1c4 +(197/256)*255 43443b00 00000001 a5c3c47b a5c3c47b a5c3c47b +(197/256)*255 43443b00 00000002 a5c4e17b a5c4e17b a5c4e17b +(197/256)*255 43443b00 00000003 c4c3e17b c4c3e17b c4c3e17b +(197/256)*255 43443b00 fffffffd a5c3c47b a5c3c47b a5c3c47b +(197/256)*255 43443b00 fffffffc a5c3e1c4 a5c3e1c4 a5c3e1c4 +(197/256)*255 43443b00 80000002 a5c4e17b a5c4e17b a5c4e17b +(197/256)*255 43443b00 00000103 c4c3e17b c4c3e17b c4c3e17b +(198/256)*255 43453a00 00000000 a5c3e1c5 a5c3e1c5 a5c3e1c5 +(198/256)*255 43453a00 00000001 a5c3c57b a5c3c57b a5c3c57b +(198/256)*255 43453a00 00000002 a5c5e17b a5c5e17b a5c5e17b +(198/256)*255 43453a00 00000003 c5c3e17b c5c3e17b c5c3e17b +(198/256)*255 43453a00 fffffffd a5c3c57b a5c3c57b a5c3c57b +(198/256)*255 43453a00 fffffffc a5c3e1c5 a5c3e1c5 a5c3e1c5 +(198/256)*255 43453a00 80000002 a5c5e17b a5c5e17b a5c5e17b +(198/256)*255 43453a00 00000103 c5c3e17b c5c3e17b c5c3e17b +(199/256)*255 43463900 00000000 a5c3e1c6 a5c3e1c6 a5c3e1c6 +(199/256)*255 43463900 00000001 a5c3c67b a5c3c67b a5c3c67b +(199/256)*255 43463900 00000002 a5c6e17b a5c6e17b a5c6e17b +(199/256)*255 43463900 00000003 c6c3e17b c6c3e17b c6c3e17b +(199/256)*255 43463900 fffffffd a5c3c67b a5c3c67b a5c3c67b +(199/256)*255 43463900 fffffffc a5c3e1c6 a5c3e1c6 a5c3e1c6 +(199/256)*255 43463900 80000002 a5c6e17b a5c6e17b a5c6e17b +(199/256)*255 43463900 00000103 c6c3e17b c6c3e17b c6c3e17b +(200/256)*255 43473800 00000000 a5c3e1c7 a5c3e1c7 a5c3e1c7 +(200/256)*255 43473800 00000001 a5c3c77b a5c3c77b a5c3c77b +(200/256)*255 43473800 00000002 a5c7e17b a5c7e17b a5c7e17b +(200/256)*255 43473800 00000003 c7c3e17b c7c3e17b c7c3e17b +(200/256)*255 43473800 fffffffd a5c3c77b a5c3c77b a5c3c77b +(200/256)*255 43473800 fffffffc a5c3e1c7 a5c3e1c7 a5c3e1c7 +(200/256)*255 43473800 80000002 a5c7e17b a5c7e17b a5c7e17b +(200/256)*255 43473800 00000103 c7c3e17b c7c3e17b c7c3e17b +(201/256)*255 43483700 00000000 a5c3e1c8 a5c3e1c8 a5c3e1c8 +(201/256)*255 43483700 00000001 a5c3c87b a5c3c87b a5c3c87b +(201/256)*255 43483700 00000002 a5c8e17b a5c8e17b a5c8e17b +(201/256)*255 43483700 00000003 c8c3e17b c8c3e17b c8c3e17b +(201/256)*255 43483700 fffffffd a5c3c87b a5c3c87b a5c3c87b +(201/256)*255 43483700 fffffffc a5c3e1c8 a5c3e1c8 a5c3e1c8 +(201/256)*255 43483700 80000002 a5c8e17b a5c8e17b a5c8e17b +(201/256)*255 43483700 00000103 c8c3e17b c8c3e17b c8c3e17b +(202/256)*255 43493600 00000000 a5c3e1c9 a5c3e1c9 a5c3e1c9 +(202/256)*255 43493600 00000001 a5c3c97b a5c3c97b a5c3c97b +(202/256)*255 43493600 00000002 a5c9e17b a5c9e17b a5c9e17b +(202/256)*255 43493600 00000003 c9c3e17b c9c3e17b c9c3e17b +(202/256)*255 43493600 fffffffd a5c3c97b a5c3c97b a5c3c97b +(202/256)*255 43493600 fffffffc a5c3e1c9 a5c3e1c9 a5c3e1c9 +(202/256)*255 43493600 80000002 a5c9e17b a5c9e17b a5c9e17b +(202/256)*255 43493600 00000103 c9c3e17b c9c3e17b c9c3e17b +(203/256)*255 434a3500 00000000 a5c3e1ca a5c3e1ca a5c3e1ca +(203/256)*255 434a3500 00000001 a5c3ca7b a5c3ca7b a5c3ca7b +(203/256)*255 434a3500 00000002 a5cae17b a5cae17b a5cae17b +(203/256)*255 434a3500 00000003 cac3e17b cac3e17b cac3e17b +(203/256)*255 434a3500 fffffffd a5c3ca7b a5c3ca7b a5c3ca7b +(203/256)*255 434a3500 fffffffc a5c3e1ca a5c3e1ca a5c3e1ca +(203/256)*255 434a3500 80000002 a5cae17b a5cae17b a5cae17b +(203/256)*255 434a3500 00000103 cac3e17b cac3e17b cac3e17b +(204/256)*255 434b3400 00000000 a5c3e1cb a5c3e1cb a5c3e1cb +(204/256)*255 434b3400 00000001 a5c3cb7b a5c3cb7b a5c3cb7b +(204/256)*255 434b3400 00000002 a5cbe17b a5cbe17b a5cbe17b +(204/256)*255 434b3400 00000003 cbc3e17b cbc3e17b cbc3e17b +(204/256)*255 434b3400 fffffffd a5c3cb7b a5c3cb7b a5c3cb7b +(204/256)*255 434b3400 fffffffc a5c3e1cb a5c3e1cb a5c3e1cb +(204/256)*255 434b3400 80000002 a5cbe17b a5cbe17b a5cbe17b +(204/256)*255 434b3400 00000103 cbc3e17b cbc3e17b cbc3e17b +(205/256)*255 434c3300 00000000 a5c3e1cc a5c3e1cc a5c3e1cc +(205/256)*255 434c3300 00000001 a5c3cc7b a5c3cc7b a5c3cc7b +(205/256)*255 434c3300 00000002 a5cce17b a5cce17b a5cce17b +(205/256)*255 434c3300 00000003 ccc3e17b ccc3e17b ccc3e17b +(205/256)*255 434c3300 fffffffd a5c3cc7b a5c3cc7b a5c3cc7b +(205/256)*255 434c3300 fffffffc a5c3e1cc a5c3e1cc a5c3e1cc +(205/256)*255 434c3300 80000002 a5cce17b a5cce17b a5cce17b +(205/256)*255 434c3300 00000103 ccc3e17b ccc3e17b ccc3e17b +(206/256)*255 434d3200 00000000 a5c3e1cd a5c3e1cd a5c3e1cd +(206/256)*255 434d3200 00000001 a5c3cd7b a5c3cd7b a5c3cd7b +(206/256)*255 434d3200 00000002 a5cde17b a5cde17b a5cde17b +(206/256)*255 434d3200 00000003 cdc3e17b cdc3e17b cdc3e17b +(206/256)*255 434d3200 fffffffd a5c3cd7b a5c3cd7b a5c3cd7b +(206/256)*255 434d3200 fffffffc a5c3e1cd a5c3e1cd a5c3e1cd +(206/256)*255 434d3200 80000002 a5cde17b a5cde17b a5cde17b +(206/256)*255 434d3200 00000103 cdc3e17b cdc3e17b cdc3e17b +(207/256)*255 434e3100 00000000 a5c3e1ce a5c3e1ce a5c3e1ce +(207/256)*255 434e3100 00000001 a5c3ce7b a5c3ce7b a5c3ce7b +(207/256)*255 434e3100 00000002 a5cee17b a5cee17b a5cee17b +(207/256)*255 434e3100 00000003 cec3e17b cec3e17b cec3e17b +(207/256)*255 434e3100 fffffffd a5c3ce7b a5c3ce7b a5c3ce7b +(207/256)*255 434e3100 fffffffc a5c3e1ce a5c3e1ce a5c3e1ce +(207/256)*255 434e3100 80000002 a5cee17b a5cee17b a5cee17b +(207/256)*255 434e3100 00000103 cec3e17b cec3e17b cec3e17b +(208/256)*255 434f3000 00000000 a5c3e1cf a5c3e1cf a5c3e1cf +(208/256)*255 434f3000 00000001 a5c3cf7b a5c3cf7b a5c3cf7b +(208/256)*255 434f3000 00000002 a5cfe17b a5cfe17b a5cfe17b +(208/256)*255 434f3000 00000003 cfc3e17b cfc3e17b cfc3e17b +(208/256)*255 434f3000 fffffffd a5c3cf7b a5c3cf7b a5c3cf7b +(208/256)*255 434f3000 fffffffc a5c3e1cf a5c3e1cf a5c3e1cf +(208/256)*255 434f3000 80000002 a5cfe17b a5cfe17b a5cfe17b +(208/256)*255 434f3000 00000103 cfc3e17b cfc3e17b cfc3e17b +(209/256)*255 43502f00 00000000 a5c3e1d0 a5c3e1d0 a5c3e1d0 +(209/256)*255 43502f00 00000001 a5c3d07b a5c3d07b a5c3d07b +(209/256)*255 43502f00 00000002 a5d0e17b a5d0e17b a5d0e17b +(209/256)*255 43502f00 00000003 d0c3e17b d0c3e17b d0c3e17b +(209/256)*255 43502f00 fffffffd a5c3d07b a5c3d07b a5c3d07b +(209/256)*255 43502f00 fffffffc a5c3e1d0 a5c3e1d0 a5c3e1d0 +(209/256)*255 43502f00 80000002 a5d0e17b a5d0e17b a5d0e17b +(209/256)*255 43502f00 00000103 d0c3e17b d0c3e17b d0c3e17b +(210/256)*255 43512e00 00000000 a5c3e1d1 a5c3e1d1 a5c3e1d1 +(210/256)*255 43512e00 00000001 a5c3d17b a5c3d17b a5c3d17b +(210/256)*255 43512e00 00000002 a5d1e17b a5d1e17b a5d1e17b +(210/256)*255 43512e00 00000003 d1c3e17b d1c3e17b d1c3e17b +(210/256)*255 43512e00 fffffffd a5c3d17b a5c3d17b a5c3d17b +(210/256)*255 43512e00 fffffffc a5c3e1d1 a5c3e1d1 a5c3e1d1 +(210/256)*255 43512e00 80000002 a5d1e17b a5d1e17b a5d1e17b +(210/256)*255 43512e00 00000103 d1c3e17b d1c3e17b d1c3e17b +(211/256)*255 43522d00 00000000 a5c3e1d2 a5c3e1d2 a5c3e1d2 +(211/256)*255 43522d00 00000001 a5c3d27b a5c3d27b a5c3d27b +(211/256)*255 43522d00 00000002 a5d2e17b a5d2e17b a5d2e17b +(211/256)*255 43522d00 00000003 d2c3e17b d2c3e17b d2c3e17b +(211/256)*255 43522d00 fffffffd a5c3d27b a5c3d27b a5c3d27b +(211/256)*255 43522d00 fffffffc a5c3e1d2 a5c3e1d2 a5c3e1d2 +(211/256)*255 43522d00 80000002 a5d2e17b a5d2e17b a5d2e17b +(211/256)*255 43522d00 00000103 d2c3e17b d2c3e17b d2c3e17b +(212/256)*255 43532c00 00000000 a5c3e1d3 a5c3e1d3 a5c3e1d3 +(212/256)*255 43532c00 00000001 a5c3d37b a5c3d37b a5c3d37b +(212/256)*255 43532c00 00000002 a5d3e17b a5d3e17b a5d3e17b +(212/256)*255 43532c00 00000003 d3c3e17b d3c3e17b d3c3e17b +(212/256)*255 43532c00 fffffffd a5c3d37b a5c3d37b a5c3d37b +(212/256)*255 43532c00 fffffffc a5c3e1d3 a5c3e1d3 a5c3e1d3 +(212/256)*255 43532c00 80000002 a5d3e17b a5d3e17b a5d3e17b +(212/256)*255 43532c00 00000103 d3c3e17b d3c3e17b d3c3e17b +(213/256)*255 43542b00 00000000 a5c3e1d4 a5c3e1d4 a5c3e1d4 +(213/256)*255 43542b00 00000001 a5c3d47b a5c3d47b a5c3d47b +(213/256)*255 43542b00 00000002 a5d4e17b a5d4e17b a5d4e17b +(213/256)*255 43542b00 00000003 d4c3e17b d4c3e17b d4c3e17b +(213/256)*255 43542b00 fffffffd a5c3d47b a5c3d47b a5c3d47b +(213/256)*255 43542b00 fffffffc a5c3e1d4 a5c3e1d4 a5c3e1d4 +(213/256)*255 43542b00 80000002 a5d4e17b a5d4e17b a5d4e17b +(213/256)*255 43542b00 00000103 d4c3e17b d4c3e17b d4c3e17b +(214/256)*255 43552a00 00000000 a5c3e1d5 a5c3e1d5 a5c3e1d5 +(214/256)*255 43552a00 00000001 a5c3d57b a5c3d57b a5c3d57b +(214/256)*255 43552a00 00000002 a5d5e17b a5d5e17b a5d5e17b +(214/256)*255 43552a00 00000003 d5c3e17b d5c3e17b d5c3e17b +(214/256)*255 43552a00 fffffffd a5c3d57b a5c3d57b a5c3d57b +(214/256)*255 43552a00 fffffffc a5c3e1d5 a5c3e1d5 a5c3e1d5 +(214/256)*255 43552a00 80000002 a5d5e17b a5d5e17b a5d5e17b +(214/256)*255 43552a00 00000103 d5c3e17b d5c3e17b d5c3e17b +(215/256)*255 43562900 00000000 a5c3e1d6 a5c3e1d6 a5c3e1d6 +(215/256)*255 43562900 00000001 a5c3d67b a5c3d67b a5c3d67b +(215/256)*255 43562900 00000002 a5d6e17b a5d6e17b a5d6e17b +(215/256)*255 43562900 00000003 d6c3e17b d6c3e17b d6c3e17b +(215/256)*255 43562900 fffffffd a5c3d67b a5c3d67b a5c3d67b +(215/256)*255 43562900 fffffffc a5c3e1d6 a5c3e1d6 a5c3e1d6 +(215/256)*255 43562900 80000002 a5d6e17b a5d6e17b a5d6e17b +(215/256)*255 43562900 00000103 d6c3e17b d6c3e17b d6c3e17b +(216/256)*255 43572800 00000000 a5c3e1d7 a5c3e1d7 a5c3e1d7 +(216/256)*255 43572800 00000001 a5c3d77b a5c3d77b a5c3d77b +(216/256)*255 43572800 00000002 a5d7e17b a5d7e17b a5d7e17b +(216/256)*255 43572800 00000003 d7c3e17b d7c3e17b d7c3e17b +(216/256)*255 43572800 fffffffd a5c3d77b a5c3d77b a5c3d77b +(216/256)*255 43572800 fffffffc a5c3e1d7 a5c3e1d7 a5c3e1d7 +(216/256)*255 43572800 80000002 a5d7e17b a5d7e17b a5d7e17b +(216/256)*255 43572800 00000103 d7c3e17b d7c3e17b d7c3e17b +(217/256)*255 43582700 00000000 a5c3e1d8 a5c3e1d8 a5c3e1d8 +(217/256)*255 43582700 00000001 a5c3d87b a5c3d87b a5c3d87b +(217/256)*255 43582700 00000002 a5d8e17b a5d8e17b a5d8e17b +(217/256)*255 43582700 00000003 d8c3e17b d8c3e17b d8c3e17b +(217/256)*255 43582700 fffffffd a5c3d87b a5c3d87b a5c3d87b +(217/256)*255 43582700 fffffffc a5c3e1d8 a5c3e1d8 a5c3e1d8 +(217/256)*255 43582700 80000002 a5d8e17b a5d8e17b a5d8e17b +(217/256)*255 43582700 00000103 d8c3e17b d8c3e17b d8c3e17b +(218/256)*255 43592600 00000000 a5c3e1d9 a5c3e1d9 a5c3e1d9 +(218/256)*255 43592600 00000001 a5c3d97b a5c3d97b a5c3d97b +(218/256)*255 43592600 00000002 a5d9e17b a5d9e17b a5d9e17b +(218/256)*255 43592600 00000003 d9c3e17b d9c3e17b d9c3e17b +(218/256)*255 43592600 fffffffd a5c3d97b a5c3d97b a5c3d97b +(218/256)*255 43592600 fffffffc a5c3e1d9 a5c3e1d9 a5c3e1d9 +(218/256)*255 43592600 80000002 a5d9e17b a5d9e17b a5d9e17b +(218/256)*255 43592600 00000103 d9c3e17b d9c3e17b d9c3e17b +(219/256)*255 435a2500 00000000 a5c3e1da a5c3e1da a5c3e1da +(219/256)*255 435a2500 00000001 a5c3da7b a5c3da7b a5c3da7b +(219/256)*255 435a2500 00000002 a5dae17b a5dae17b a5dae17b +(219/256)*255 435a2500 00000003 dac3e17b dac3e17b dac3e17b +(219/256)*255 435a2500 fffffffd a5c3da7b a5c3da7b a5c3da7b +(219/256)*255 435a2500 fffffffc a5c3e1da a5c3e1da a5c3e1da +(219/256)*255 435a2500 80000002 a5dae17b a5dae17b a5dae17b +(219/256)*255 435a2500 00000103 dac3e17b dac3e17b dac3e17b +(220/256)*255 435b2400 00000000 a5c3e1db a5c3e1db a5c3e1db +(220/256)*255 435b2400 00000001 a5c3db7b a5c3db7b a5c3db7b +(220/256)*255 435b2400 00000002 a5dbe17b a5dbe17b a5dbe17b +(220/256)*255 435b2400 00000003 dbc3e17b dbc3e17b dbc3e17b +(220/256)*255 435b2400 fffffffd a5c3db7b a5c3db7b a5c3db7b +(220/256)*255 435b2400 fffffffc a5c3e1db a5c3e1db a5c3e1db +(220/256)*255 435b2400 80000002 a5dbe17b a5dbe17b a5dbe17b +(220/256)*255 435b2400 00000103 dbc3e17b dbc3e17b dbc3e17b +(221/256)*255 435c2300 00000000 a5c3e1dc a5c3e1dc a5c3e1dc +(221/256)*255 435c2300 00000001 a5c3dc7b a5c3dc7b a5c3dc7b +(221/256)*255 435c2300 00000002 a5dce17b a5dce17b a5dce17b +(221/256)*255 435c2300 00000003 dcc3e17b dcc3e17b dcc3e17b +(221/256)*255 435c2300 fffffffd a5c3dc7b a5c3dc7b a5c3dc7b +(221/256)*255 435c2300 fffffffc a5c3e1dc a5c3e1dc a5c3e1dc +(221/256)*255 435c2300 80000002 a5dce17b a5dce17b a5dce17b +(221/256)*255 435c2300 00000103 dcc3e17b dcc3e17b dcc3e17b +(222/256)*255 435d2200 00000000 a5c3e1dd a5c3e1dd a5c3e1dd +(222/256)*255 435d2200 00000001 a5c3dd7b a5c3dd7b a5c3dd7b +(222/256)*255 435d2200 00000002 a5dde17b a5dde17b a5dde17b +(222/256)*255 435d2200 00000003 ddc3e17b ddc3e17b ddc3e17b +(222/256)*255 435d2200 fffffffd a5c3dd7b a5c3dd7b a5c3dd7b +(222/256)*255 435d2200 fffffffc a5c3e1dd a5c3e1dd a5c3e1dd +(222/256)*255 435d2200 80000002 a5dde17b a5dde17b a5dde17b +(222/256)*255 435d2200 00000103 ddc3e17b ddc3e17b ddc3e17b +(223/256)*255 435e2100 00000000 a5c3e1de a5c3e1de a5c3e1de +(223/256)*255 435e2100 00000001 a5c3de7b a5c3de7b a5c3de7b +(223/256)*255 435e2100 00000002 a5dee17b a5dee17b a5dee17b +(223/256)*255 435e2100 00000003 dec3e17b dec3e17b dec3e17b +(223/256)*255 435e2100 fffffffd a5c3de7b a5c3de7b a5c3de7b +(223/256)*255 435e2100 fffffffc a5c3e1de a5c3e1de a5c3e1de +(223/256)*255 435e2100 80000002 a5dee17b a5dee17b a5dee17b +(223/256)*255 435e2100 00000103 dec3e17b dec3e17b dec3e17b +(224/256)*255 435f2000 00000000 a5c3e1df a5c3e1df a5c3e1df +(224/256)*255 435f2000 00000001 a5c3df7b a5c3df7b a5c3df7b +(224/256)*255 435f2000 00000002 a5dfe17b a5dfe17b a5dfe17b +(224/256)*255 435f2000 00000003 dfc3e17b dfc3e17b dfc3e17b +(224/256)*255 435f2000 fffffffd a5c3df7b a5c3df7b a5c3df7b +(224/256)*255 435f2000 fffffffc a5c3e1df a5c3e1df a5c3e1df +(224/256)*255 435f2000 80000002 a5dfe17b a5dfe17b a5dfe17b +(224/256)*255 435f2000 00000103 dfc3e17b dfc3e17b dfc3e17b +(225/256)*255 43601f00 00000000 a5c3e1e0 a5c3e1e0 a5c3e1e0 +(225/256)*255 43601f00 00000001 a5c3e07b a5c3e07b a5c3e07b +(225/256)*255 43601f00 00000002 a5e0e17b a5e0e17b a5e0e17b +(225/256)*255 43601f00 00000003 e0c3e17b e0c3e17b e0c3e17b +(225/256)*255 43601f00 fffffffd a5c3e07b a5c3e07b a5c3e07b +(225/256)*255 43601f00 fffffffc a5c3e1e0 a5c3e1e0 a5c3e1e0 +(225/256)*255 43601f00 80000002 a5e0e17b a5e0e17b a5e0e17b +(225/256)*255 43601f00 00000103 e0c3e17b e0c3e17b e0c3e17b +(226/256)*255 43611e00 00000000 a5c3e1e1 a5c3e1e1 a5c3e1e1 +(226/256)*255 43611e00 00000001 a5c3e17b a5c3e17b a5c3e17b +(226/256)*255 43611e00 00000002 a5e1e17b a5e1e17b a5e1e17b +(226/256)*255 43611e00 00000003 e1c3e17b e1c3e17b e1c3e17b +(226/256)*255 43611e00 fffffffd a5c3e17b a5c3e17b a5c3e17b +(226/256)*255 43611e00 fffffffc a5c3e1e1 a5c3e1e1 a5c3e1e1 +(226/256)*255 43611e00 80000002 a5e1e17b a5e1e17b a5e1e17b +(226/256)*255 43611e00 00000103 e1c3e17b e1c3e17b e1c3e17b +(227/256)*255 43621d00 00000000 a5c3e1e2 a5c3e1e2 a5c3e1e2 +(227/256)*255 43621d00 00000001 a5c3e27b a5c3e27b a5c3e27b +(227/256)*255 43621d00 00000002 a5e2e17b a5e2e17b a5e2e17b +(227/256)*255 43621d00 00000003 e2c3e17b e2c3e17b e2c3e17b +(227/256)*255 43621d00 fffffffd a5c3e27b a5c3e27b a5c3e27b +(227/256)*255 43621d00 fffffffc a5c3e1e2 a5c3e1e2 a5c3e1e2 +(227/256)*255 43621d00 80000002 a5e2e17b a5e2e17b a5e2e17b +(227/256)*255 43621d00 00000103 e2c3e17b e2c3e17b e2c3e17b +(228/256)*255 43631c00 00000000 a5c3e1e3 a5c3e1e3 a5c3e1e3 +(228/256)*255 43631c00 00000001 a5c3e37b a5c3e37b a5c3e37b +(228/256)*255 43631c00 00000002 a5e3e17b a5e3e17b a5e3e17b +(228/256)*255 43631c00 00000003 e3c3e17b e3c3e17b e3c3e17b +(228/256)*255 43631c00 fffffffd a5c3e37b a5c3e37b a5c3e37b +(228/256)*255 43631c00 fffffffc a5c3e1e3 a5c3e1e3 a5c3e1e3 +(228/256)*255 43631c00 80000002 a5e3e17b a5e3e17b a5e3e17b +(228/256)*255 43631c00 00000103 e3c3e17b e3c3e17b e3c3e17b +(229/256)*255 43641b00 00000000 a5c3e1e4 a5c3e1e4 a5c3e1e4 +(229/256)*255 43641b00 00000001 a5c3e47b a5c3e47b a5c3e47b +(229/256)*255 43641b00 00000002 a5e4e17b a5e4e17b a5e4e17b +(229/256)*255 43641b00 00000003 e4c3e17b e4c3e17b e4c3e17b +(229/256)*255 43641b00 fffffffd a5c3e47b a5c3e47b a5c3e47b +(229/256)*255 43641b00 fffffffc a5c3e1e4 a5c3e1e4 a5c3e1e4 +(229/256)*255 43641b00 80000002 a5e4e17b a5e4e17b a5e4e17b +(229/256)*255 43641b00 00000103 e4c3e17b e4c3e17b e4c3e17b +(230/256)*255 43651a00 00000000 a5c3e1e5 a5c3e1e5 a5c3e1e5 +(230/256)*255 43651a00 00000001 a5c3e57b a5c3e57b a5c3e57b +(230/256)*255 43651a00 00000002 a5e5e17b a5e5e17b a5e5e17b +(230/256)*255 43651a00 00000003 e5c3e17b e5c3e17b e5c3e17b +(230/256)*255 43651a00 fffffffd a5c3e57b a5c3e57b a5c3e57b +(230/256)*255 43651a00 fffffffc a5c3e1e5 a5c3e1e5 a5c3e1e5 +(230/256)*255 43651a00 80000002 a5e5e17b a5e5e17b a5e5e17b +(230/256)*255 43651a00 00000103 e5c3e17b e5c3e17b e5c3e17b +(231/256)*255 43661900 00000000 a5c3e1e6 a5c3e1e6 a5c3e1e6 +(231/256)*255 43661900 00000001 a5c3e67b a5c3e67b a5c3e67b +(231/256)*255 43661900 00000002 a5e6e17b a5e6e17b a5e6e17b +(231/256)*255 43661900 00000003 e6c3e17b e6c3e17b e6c3e17b +(231/256)*255 43661900 fffffffd a5c3e67b a5c3e67b a5c3e67b +(231/256)*255 43661900 fffffffc a5c3e1e6 a5c3e1e6 a5c3e1e6 +(231/256)*255 43661900 80000002 a5e6e17b a5e6e17b a5e6e17b +(231/256)*255 43661900 00000103 e6c3e17b e6c3e17b e6c3e17b +(232/256)*255 43671800 00000000 a5c3e1e7 a5c3e1e7 a5c3e1e7 +(232/256)*255 43671800 00000001 a5c3e77b a5c3e77b a5c3e77b +(232/256)*255 43671800 00000002 a5e7e17b a5e7e17b a5e7e17b +(232/256)*255 43671800 00000003 e7c3e17b e7c3e17b e7c3e17b +(232/256)*255 43671800 fffffffd a5c3e77b a5c3e77b a5c3e77b +(232/256)*255 43671800 fffffffc a5c3e1e7 a5c3e1e7 a5c3e1e7 +(232/256)*255 43671800 80000002 a5e7e17b a5e7e17b a5e7e17b +(232/256)*255 43671800 00000103 e7c3e17b e7c3e17b e7c3e17b +(233/256)*255 43681700 00000000 a5c3e1e8 a5c3e1e8 a5c3e1e8 +(233/256)*255 43681700 00000001 a5c3e87b a5c3e87b a5c3e87b +(233/256)*255 43681700 00000002 a5e8e17b a5e8e17b a5e8e17b +(233/256)*255 43681700 00000003 e8c3e17b e8c3e17b e8c3e17b +(233/256)*255 43681700 fffffffd a5c3e87b a5c3e87b a5c3e87b +(233/256)*255 43681700 fffffffc a5c3e1e8 a5c3e1e8 a5c3e1e8 +(233/256)*255 43681700 80000002 a5e8e17b a5e8e17b a5e8e17b +(233/256)*255 43681700 00000103 e8c3e17b e8c3e17b e8c3e17b +(234/256)*255 43691600 00000000 a5c3e1e9 a5c3e1e9 a5c3e1e9 +(234/256)*255 43691600 00000001 a5c3e97b a5c3e97b a5c3e97b +(234/256)*255 43691600 00000002 a5e9e17b a5e9e17b a5e9e17b +(234/256)*255 43691600 00000003 e9c3e17b e9c3e17b e9c3e17b +(234/256)*255 43691600 fffffffd a5c3e97b a5c3e97b a5c3e97b +(234/256)*255 43691600 fffffffc a5c3e1e9 a5c3e1e9 a5c3e1e9 +(234/256)*255 43691600 80000002 a5e9e17b a5e9e17b a5e9e17b +(234/256)*255 43691600 00000103 e9c3e17b e9c3e17b e9c3e17b +(235/256)*255 436a1500 00000000 a5c3e1ea a5c3e1ea a5c3e1ea +(235/256)*255 436a1500 00000001 a5c3ea7b a5c3ea7b a5c3ea7b +(235/256)*255 436a1500 00000002 a5eae17b a5eae17b a5eae17b +(235/256)*255 436a1500 00000003 eac3e17b eac3e17b eac3e17b +(235/256)*255 436a1500 fffffffd a5c3ea7b a5c3ea7b a5c3ea7b +(235/256)*255 436a1500 fffffffc a5c3e1ea a5c3e1ea a5c3e1ea +(235/256)*255 436a1500 80000002 a5eae17b a5eae17b a5eae17b +(235/256)*255 436a1500 00000103 eac3e17b eac3e17b eac3e17b +(236/256)*255 436b1400 00000000 a5c3e1eb a5c3e1eb a5c3e1eb +(236/256)*255 436b1400 00000001 a5c3eb7b a5c3eb7b a5c3eb7b +(236/256)*255 436b1400 00000002 a5ebe17b a5ebe17b a5ebe17b +(236/256)*255 436b1400 00000003 ebc3e17b ebc3e17b ebc3e17b +(236/256)*255 436b1400 fffffffd a5c3eb7b a5c3eb7b a5c3eb7b +(236/256)*255 436b1400 fffffffc a5c3e1eb a5c3e1eb a5c3e1eb +(236/256)*255 436b1400 80000002 a5ebe17b a5ebe17b a5ebe17b +(236/256)*255 436b1400 00000103 ebc3e17b ebc3e17b ebc3e17b +(237/256)*255 436c1300 00000000 a5c3e1ec a5c3e1ec a5c3e1ec +(237/256)*255 436c1300 00000001 a5c3ec7b a5c3ec7b a5c3ec7b +(237/256)*255 436c1300 00000002 a5ece17b a5ece17b a5ece17b +(237/256)*255 436c1300 00000003 ecc3e17b ecc3e17b ecc3e17b +(237/256)*255 436c1300 fffffffd a5c3ec7b a5c3ec7b a5c3ec7b +(237/256)*255 436c1300 fffffffc a5c3e1ec a5c3e1ec a5c3e1ec +(237/256)*255 436c1300 80000002 a5ece17b a5ece17b a5ece17b +(237/256)*255 436c1300 00000103 ecc3e17b ecc3e17b ecc3e17b +(238/256)*255 436d1200 00000000 a5c3e1ed a5c3e1ed a5c3e1ed +(238/256)*255 436d1200 00000001 a5c3ed7b a5c3ed7b a5c3ed7b +(238/256)*255 436d1200 00000002 a5ede17b a5ede17b a5ede17b +(238/256)*255 436d1200 00000003 edc3e17b edc3e17b edc3e17b +(238/256)*255 436d1200 fffffffd a5c3ed7b a5c3ed7b a5c3ed7b +(238/256)*255 436d1200 fffffffc a5c3e1ed a5c3e1ed a5c3e1ed +(238/256)*255 436d1200 80000002 a5ede17b a5ede17b a5ede17b +(238/256)*255 436d1200 00000103 edc3e17b edc3e17b edc3e17b +(239/256)*255 436e1100 00000000 a5c3e1ee a5c3e1ee a5c3e1ee +(239/256)*255 436e1100 00000001 a5c3ee7b a5c3ee7b a5c3ee7b +(239/256)*255 436e1100 00000002 a5eee17b a5eee17b a5eee17b +(239/256)*255 436e1100 00000003 eec3e17b eec3e17b eec3e17b +(239/256)*255 436e1100 fffffffd a5c3ee7b a5c3ee7b a5c3ee7b +(239/256)*255 436e1100 fffffffc a5c3e1ee a5c3e1ee a5c3e1ee +(239/256)*255 436e1100 80000002 a5eee17b a5eee17b a5eee17b +(239/256)*255 436e1100 00000103 eec3e17b eec3e17b eec3e17b +(240/256)*255 436f1000 00000000 a5c3e1ef a5c3e1ef a5c3e1ef +(240/256)*255 436f1000 00000001 a5c3ef7b a5c3ef7b a5c3ef7b +(240/256)*255 436f1000 00000002 a5efe17b a5efe17b a5efe17b +(240/256)*255 436f1000 00000003 efc3e17b efc3e17b efc3e17b +(240/256)*255 436f1000 fffffffd a5c3ef7b a5c3ef7b a5c3ef7b +(240/256)*255 436f1000 fffffffc a5c3e1ef a5c3e1ef a5c3e1ef +(240/256)*255 436f1000 80000002 a5efe17b a5efe17b a5efe17b +(240/256)*255 436f1000 00000103 efc3e17b efc3e17b efc3e17b +(241/256)*255 43700f00 00000000 a5c3e1f0 a5c3e1f0 a5c3e1f0 +(241/256)*255 43700f00 00000001 a5c3f07b a5c3f07b a5c3f07b +(241/256)*255 43700f00 00000002 a5f0e17b a5f0e17b a5f0e17b +(241/256)*255 43700f00 00000003 f0c3e17b f0c3e17b f0c3e17b +(241/256)*255 43700f00 fffffffd a5c3f07b a5c3f07b a5c3f07b +(241/256)*255 43700f00 fffffffc a5c3e1f0 a5c3e1f0 a5c3e1f0 +(241/256)*255 43700f00 80000002 a5f0e17b a5f0e17b a5f0e17b +(241/256)*255 43700f00 00000103 f0c3e17b f0c3e17b f0c3e17b +(242/256)*255 43710e00 00000000 a5c3e1f1 a5c3e1f1 a5c3e1f1 +(242/256)*255 43710e00 00000001 a5c3f17b a5c3f17b a5c3f17b +(242/256)*255 43710e00 00000002 a5f1e17b a5f1e17b a5f1e17b +(242/256)*255 43710e00 00000003 f1c3e17b f1c3e17b f1c3e17b +(242/256)*255 43710e00 fffffffd a5c3f17b a5c3f17b a5c3f17b +(242/256)*255 43710e00 fffffffc a5c3e1f1 a5c3e1f1 a5c3e1f1 +(242/256)*255 43710e00 80000002 a5f1e17b a5f1e17b a5f1e17b +(242/256)*255 43710e00 00000103 f1c3e17b f1c3e17b f1c3e17b +(243/256)*255 43720d00 00000000 a5c3e1f2 a5c3e1f2 a5c3e1f2 +(243/256)*255 43720d00 00000001 a5c3f27b a5c3f27b a5c3f27b +(243/256)*255 43720d00 00000002 a5f2e17b a5f2e17b a5f2e17b +(243/256)*255 43720d00 00000003 f2c3e17b f2c3e17b f2c3e17b +(243/256)*255 43720d00 fffffffd a5c3f27b a5c3f27b a5c3f27b +(243/256)*255 43720d00 fffffffc a5c3e1f2 a5c3e1f2 a5c3e1f2 +(243/256)*255 43720d00 80000002 a5f2e17b a5f2e17b a5f2e17b +(243/256)*255 43720d00 00000103 f2c3e17b f2c3e17b f2c3e17b +(244/256)*255 43730c00 00000000 a5c3e1f3 a5c3e1f3 a5c3e1f3 +(244/256)*255 43730c00 00000001 a5c3f37b a5c3f37b a5c3f37b +(244/256)*255 43730c00 00000002 a5f3e17b a5f3e17b a5f3e17b +(244/256)*255 43730c00 00000003 f3c3e17b f3c3e17b f3c3e17b +(244/256)*255 43730c00 fffffffd a5c3f37b a5c3f37b a5c3f37b +(244/256)*255 43730c00 fffffffc a5c3e1f3 a5c3e1f3 a5c3e1f3 +(244/256)*255 43730c00 80000002 a5f3e17b a5f3e17b a5f3e17b +(244/256)*255 43730c00 00000103 f3c3e17b f3c3e17b f3c3e17b +(245/256)*255 43740b00 00000000 a5c3e1f4 a5c3e1f4 a5c3e1f4 +(245/256)*255 43740b00 00000001 a5c3f47b a5c3f47b a5c3f47b +(245/256)*255 43740b00 00000002 a5f4e17b a5f4e17b a5f4e17b +(245/256)*255 43740b00 00000003 f4c3e17b f4c3e17b f4c3e17b +(245/256)*255 43740b00 fffffffd a5c3f47b a5c3f47b a5c3f47b +(245/256)*255 43740b00 fffffffc a5c3e1f4 a5c3e1f4 a5c3e1f4 +(245/256)*255 43740b00 80000002 a5f4e17b a5f4e17b a5f4e17b +(245/256)*255 43740b00 00000103 f4c3e17b f4c3e17b f4c3e17b +(246/256)*255 43750a00 00000000 a5c3e1f5 a5c3e1f5 a5c3e1f5 +(246/256)*255 43750a00 00000001 a5c3f57b a5c3f57b a5c3f57b +(246/256)*255 43750a00 00000002 a5f5e17b a5f5e17b a5f5e17b +(246/256)*255 43750a00 00000003 f5c3e17b f5c3e17b f5c3e17b +(246/256)*255 43750a00 fffffffd a5c3f57b a5c3f57b a5c3f57b +(246/256)*255 43750a00 fffffffc a5c3e1f5 a5c3e1f5 a5c3e1f5 +(246/256)*255 43750a00 80000002 a5f5e17b a5f5e17b a5f5e17b +(246/256)*255 43750a00 00000103 f5c3e17b f5c3e17b f5c3e17b +(247/256)*255 43760900 00000000 a5c3e1f6 a5c3e1f6 a5c3e1f6 +(247/256)*255 43760900 00000001 a5c3f67b a5c3f67b a5c3f67b +(247/256)*255 43760900 00000002 a5f6e17b a5f6e17b a5f6e17b +(247/256)*255 43760900 00000003 f6c3e17b f6c3e17b f6c3e17b +(247/256)*255 43760900 fffffffd a5c3f67b a5c3f67b a5c3f67b +(247/256)*255 43760900 fffffffc a5c3e1f6 a5c3e1f6 a5c3e1f6 +(247/256)*255 43760900 80000002 a5f6e17b a5f6e17b a5f6e17b +(247/256)*255 43760900 00000103 f6c3e17b f6c3e17b f6c3e17b +(248/256)*255 43770800 00000000 a5c3e1f7 a5c3e1f7 a5c3e1f7 +(248/256)*255 43770800 00000001 a5c3f77b a5c3f77b a5c3f77b +(248/256)*255 43770800 00000002 a5f7e17b a5f7e17b a5f7e17b +(248/256)*255 43770800 00000003 f7c3e17b f7c3e17b f7c3e17b +(248/256)*255 43770800 fffffffd a5c3f77b a5c3f77b a5c3f77b +(248/256)*255 43770800 fffffffc a5c3e1f7 a5c3e1f7 a5c3e1f7 +(248/256)*255 43770800 80000002 a5f7e17b a5f7e17b a5f7e17b +(248/256)*255 43770800 00000103 f7c3e17b f7c3e17b f7c3e17b +(249/256)*255 43780700 00000000 a5c3e1f8 a5c3e1f8 a5c3e1f8 +(249/256)*255 43780700 00000001 a5c3f87b a5c3f87b a5c3f87b +(249/256)*255 43780700 00000002 a5f8e17b a5f8e17b a5f8e17b +(249/256)*255 43780700 00000003 f8c3e17b f8c3e17b f8c3e17b +(249/256)*255 43780700 fffffffd a5c3f87b a5c3f87b a5c3f87b +(249/256)*255 43780700 fffffffc a5c3e1f8 a5c3e1f8 a5c3e1f8 +(249/256)*255 43780700 80000002 a5f8e17b a5f8e17b a5f8e17b +(249/256)*255 43780700 00000103 f8c3e17b f8c3e17b f8c3e17b +(250/256)*255 43790600 00000000 a5c3e1f9 a5c3e1f9 a5c3e1f9 +(250/256)*255 43790600 00000001 a5c3f97b a5c3f97b a5c3f97b +(250/256)*255 43790600 00000002 a5f9e17b a5f9e17b a5f9e17b +(250/256)*255 43790600 00000003 f9c3e17b f9c3e17b f9c3e17b +(250/256)*255 43790600 fffffffd a5c3f97b a5c3f97b a5c3f97b +(250/256)*255 43790600 fffffffc a5c3e1f9 a5c3e1f9 a5c3e1f9 +(250/256)*255 43790600 80000002 a5f9e17b a5f9e17b a5f9e17b +(250/256)*255 43790600 00000103 f9c3e17b f9c3e17b f9c3e17b +(251/256)*255 437a0500 00000000 a5c3e1fa a5c3e1fa a5c3e1fa +(251/256)*255 437a0500 00000001 a5c3fa7b a5c3fa7b a5c3fa7b +(251/256)*255 437a0500 00000002 a5fae17b a5fae17b a5fae17b +(251/256)*255 437a0500 00000003 fac3e17b fac3e17b fac3e17b +(251/256)*255 437a0500 fffffffd a5c3fa7b a5c3fa7b a5c3fa7b +(251/256)*255 437a0500 fffffffc a5c3e1fa a5c3e1fa a5c3e1fa +(251/256)*255 437a0500 80000002 a5fae17b a5fae17b a5fae17b +(251/256)*255 437a0500 00000103 fac3e17b fac3e17b fac3e17b +(252/256)*255 437b0400 00000000 a5c3e1fb a5c3e1fb a5c3e1fb +(252/256)*255 437b0400 00000001 a5c3fb7b a5c3fb7b a5c3fb7b +(252/256)*255 437b0400 00000002 a5fbe17b a5fbe17b a5fbe17b +(252/256)*255 437b0400 00000003 fbc3e17b fbc3e17b fbc3e17b +(252/256)*255 437b0400 fffffffd a5c3fb7b a5c3fb7b a5c3fb7b +(252/256)*255 437b0400 fffffffc a5c3e1fb a5c3e1fb a5c3e1fb +(252/256)*255 437b0400 80000002 a5fbe17b a5fbe17b a5fbe17b +(252/256)*255 437b0400 00000103 fbc3e17b fbc3e17b fbc3e17b +(253/256)*255 437c0300 00000000 a5c3e1fc a5c3e1fc a5c3e1fc +(253/256)*255 437c0300 00000001 a5c3fc7b a5c3fc7b a5c3fc7b +(253/256)*255 437c0300 00000002 a5fce17b a5fce17b a5fce17b +(253/256)*255 437c0300 00000003 fcc3e17b fcc3e17b fcc3e17b +(253/256)*255 437c0300 fffffffd a5c3fc7b a5c3fc7b a5c3fc7b +(253/256)*255 437c0300 fffffffc a5c3e1fc a5c3e1fc a5c3e1fc +(253/256)*255 437c0300 80000002 a5fce17b a5fce17b a5fce17b +(253/256)*255 437c0300 00000103 fcc3e17b fcc3e17b fcc3e17b +(254/256)*255 437d0200 00000000 a5c3e1fd a5c3e1fd a5c3e1fd +(254/256)*255 437d0200 00000001 a5c3fd7b a5c3fd7b a5c3fd7b +(254/256)*255 437d0200 00000002 a5fde17b a5fde17b a5fde17b +(254/256)*255 437d0200 00000003 fdc3e17b fdc3e17b fdc3e17b +(254/256)*255 437d0200 fffffffd a5c3fd7b a5c3fd7b a5c3fd7b +(254/256)*255 437d0200 fffffffc a5c3e1fd a5c3e1fd a5c3e1fd +(254/256)*255 437d0200 80000002 a5fde17b a5fde17b a5fde17b +(254/256)*255 437d0200 00000103 fdc3e17b fdc3e17b fdc3e17b +(255/256)*255 437e0100 00000000 a5c3e1fe a5c3e1fe a5c3e1fe +(255/256)*255 437e0100 00000001 a5c3fe7b a5c3fe7b a5c3fe7b +(255/256)*255 437e0100 00000002 a5fee17b a5fee17b a5fee17b +(255/256)*255 437e0100 00000003 fec3e17b fec3e17b fec3e17b +(255/256)*255 437e0100 fffffffd a5c3fe7b a5c3fe7b a5c3fe7b +(255/256)*255 437e0100 fffffffc a5c3e1fe a5c3e1fe a5c3e1fe +(255/256)*255 437e0100 80000002 a5fee17b a5fee17b a5fee17b +(255/256)*255 437e0100 00000103 fec3e17b fec3e17b fec3e17b +(1/100)*255 40233333 00000000 a5c3e103 a5c3e102 a5c3e103 +(1/100)*255 40233333 00000001 a5c3037b a5c3027b a5c3037b +(1/100)*255 40233333 00000002 a503e17b a502e17b a503e17b +(1/100)*255 40233333 00000003 03c3e17b 02c3e17b 03c3e17b +(1/100)*255 40233333 fffffffd a5c3037b a5c3027b a5c3037b +(1/100)*255 40233333 fffffffc a5c3e103 a5c3e102 a5c3e103 +(1/100)*255 40233333 80000002 a503e17b a502e17b a503e17b +(1/100)*255 40233333 00000103 03c3e17b 02c3e17b 03c3e17b +(2/100)*255 40a33333 00000000 a5c3e105 a5c3e105 a5c3e105 +(2/100)*255 40a33333 00000001 a5c3057b a5c3057b a5c3057b +(2/100)*255 40a33333 00000002 a505e17b a505e17b a505e17b +(2/100)*255 40a33333 00000003 05c3e17b 05c3e17b 05c3e17b +(2/100)*255 40a33333 fffffffd a5c3057b a5c3057b a5c3057b +(2/100)*255 40a33333 fffffffc a5c3e105 a5c3e105 a5c3e105 +(2/100)*255 40a33333 80000002 a505e17b a505e17b a505e17b +(2/100)*255 40a33333 00000103 05c3e17b 05c3e17b 05c3e17b +(3/100)*255 40f4cccc 00000000 a5c3e108 a5c3e107 a5c3e108 +(3/100)*255 40f4cccc 00000001 a5c3087b a5c3077b a5c3087b +(3/100)*255 40f4cccc 00000002 a508e17b a507e17b a508e17b +(3/100)*255 40f4cccc 00000003 08c3e17b 07c3e17b 08c3e17b +(3/100)*255 40f4cccc fffffffd a5c3087b a5c3077b a5c3087b +(3/100)*255 40f4cccc fffffffc a5c3e108 a5c3e107 a5c3e108 +(3/100)*255 40f4cccc 80000002 a508e17b a507e17b a508e17b +(3/100)*255 40f4cccc 00000103 08c3e17b 07c3e17b 08c3e17b +(4/100)*255 41233333 00000000 a5c3e10a a5c3e10a a5c3e10a +(4/100)*255 41233333 00000001 a5c30a7b a5c30a7b a5c30a7b +(4/100)*255 41233333 00000002 a50ae17b a50ae17b a50ae17b +(4/100)*255 41233333 00000003 0ac3e17b 0ac3e17b 0ac3e17b +(4/100)*255 41233333 fffffffd a5c30a7b a5c30a7b a5c30a7b +(4/100)*255 41233333 fffffffc a5c3e10a a5c3e10a a5c3e10a +(4/100)*255 41233333 80000002 a50ae17b a50ae17b a50ae17b +(4/100)*255 41233333 00000103 0ac3e17b 0ac3e17b 0ac3e17b +(5/100)*255 414c0000 00000000 a5c3e10d a5c3e10c a5c3e10d +(5/100)*255 414c0000 00000001 a5c30d7b a5c30c7b a5c30d7b +(5/100)*255 414c0000 00000002 a50de17b a50ce17b a50de17b +(5/100)*255 414c0000 00000003 0dc3e17b 0cc3e17b 0dc3e17b +(5/100)*255 414c0000 fffffffd a5c30d7b a5c30c7b a5c30d7b +(5/100)*255 414c0000 fffffffc a5c3e10d a5c3e10c a5c3e10d +(5/100)*255 414c0000 80000002 a50de17b a50ce17b a50de17b +(5/100)*255 414c0000 00000103 0dc3e17b 0cc3e17b 0dc3e17b +(6/100)*255 4174cccc 00000000 a5c3e10f a5c3e10f a5c3e10f +(6/100)*255 4174cccc 00000001 a5c30f7b a5c30f7b a5c30f7b +(6/100)*255 4174cccc 00000002 a50fe17b a50fe17b a50fe17b +(6/100)*255 4174cccc 00000003 0fc3e17b 0fc3e17b 0fc3e17b +(6/100)*255 4174cccc fffffffd a5c30f7b a5c30f7b a5c30f7b +(6/100)*255 4174cccc fffffffc a5c3e10f a5c3e10f a5c3e10f +(6/100)*255 4174cccc 80000002 a50fe17b a50fe17b a50fe17b +(6/100)*255 4174cccc 00000103 0fc3e17b 0fc3e17b 0fc3e17b +(7/100)*255 418ecccd 00000000 a5c3e112 a5c3e111 a5c3e112 +(7/100)*255 418ecccd 00000001 a5c3127b a5c3117b a5c3127b +(7/100)*255 418ecccd 00000002 a512e17b a511e17b a512e17b +(7/100)*255 418ecccd 00000003 12c3e17b 11c3e17b 12c3e17b +(7/100)*255 418ecccd fffffffd a5c3127b a5c3117b a5c3127b +(7/100)*255 418ecccd fffffffc a5c3e112 a5c3e111 a5c3e112 +(7/100)*255 418ecccd 80000002 a512e17b a511e17b a512e17b +(7/100)*255 418ecccd 00000103 12c3e17b 11c3e17b 12c3e17b +(8/100)*255 41a33333 00000000 a5c3e114 a5c3e114 a5c3e114 +(8/100)*255 41a33333 00000001 a5c3147b a5c3147b a5c3147b +(8/100)*255 41a33333 00000002 a514e17b a514e17b a514e17b +(8/100)*255 41a33333 00000003 14c3e17b 14c3e17b 14c3e17b +(8/100)*255 41a33333 fffffffd a5c3147b a5c3147b a5c3147b +(8/100)*255 41a33333 fffffffc a5c3e114 a5c3e114 a5c3e114 +(8/100)*255 41a33333 80000002 a514e17b a514e17b a514e17b +(8/100)*255 41a33333 00000103 14c3e17b 14c3e17b 14c3e17b +(9/100)*255 41b7999a 00000000 a5c3e117 a5c3e116 a5c3e117 +(9/100)*255 41b7999a 00000001 a5c3177b a5c3167b a5c3177b +(9/100)*255 41b7999a 00000002 a517e17b a516e17b a517e17b +(9/100)*255 41b7999a 00000003 17c3e17b 16c3e17b 17c3e17b +(9/100)*255 41b7999a fffffffd a5c3177b a5c3167b a5c3177b +(9/100)*255 41b7999a fffffffc a5c3e117 a5c3e116 a5c3e117 +(9/100)*255 41b7999a 80000002 a517e17b a516e17b a517e17b +(9/100)*255 41b7999a 00000103 17c3e17b 16c3e17b 17c3e17b +(10/100)*255 41cc0000 00000000 a5c3e11a a5c3e119 a5c3e11a +(10/100)*255 41cc0000 00000001 a5c31a7b a5c3197b a5c31a7b +(10/100)*255 41cc0000 00000002 a51ae17b a519e17b a51ae17b +(10/100)*255 41cc0000 00000003 1ac3e17b 19c3e17b 1ac3e17b +(10/100)*255 41cc0000 fffffffd a5c31a7b a5c3197b a5c31a7b +(10/100)*255 41cc0000 fffffffc a5c3e11a a5c3e119 a5c3e11a +(10/100)*255 41cc0000 80000002 a51ae17b a519e17b a51ae17b +(10/100)*255 41cc0000 00000103 1ac3e17b 19c3e17b 1ac3e17b +(11/100)*255 41e06666 00000000 a5c3e11c a5c3e11c a5c3e11c +(11/100)*255 41e06666 00000001 a5c31c7b a5c31c7b a5c31c7b +(11/100)*255 41e06666 00000002 a51ce17b a51ce17b a51ce17b +(11/100)*255 41e06666 00000003 1cc3e17b 1cc3e17b 1cc3e17b +(11/100)*255 41e06666 fffffffd a5c31c7b a5c31c7b a5c31c7b +(11/100)*255 41e06666 fffffffc a5c3e11c a5c3e11c a5c3e11c +(11/100)*255 41e06666 80000002 a51ce17b a51ce17b a51ce17b +(11/100)*255 41e06666 00000103 1cc3e17b 1cc3e17b 1cc3e17b +(12/100)*255 41f4cccc 00000000 a5c3e11f a5c3e11e a5c3e11f +(12/100)*255 41f4cccc 00000001 a5c31f7b a5c31e7b a5c31f7b +(12/100)*255 41f4cccc 00000002 a51fe17b a51ee17b a51fe17b +(12/100)*255 41f4cccc 00000003 1fc3e17b 1ec3e17b 1fc3e17b +(12/100)*255 41f4cccc fffffffd a5c31f7b a5c31e7b a5c31f7b +(12/100)*255 41f4cccc fffffffc a5c3e11f a5c3e11e a5c3e11f +(12/100)*255 41f4cccc 80000002 a51fe17b a51ee17b a51fe17b +(12/100)*255 41f4cccc 00000103 1fc3e17b 1ec3e17b 1fc3e17b +(13/100)*255 42049999 00000000 a5c3e121 a5c3e121 a5c3e121 +(13/100)*255 42049999 00000001 a5c3217b a5c3217b a5c3217b +(13/100)*255 42049999 00000002 a521e17b a521e17b a521e17b +(13/100)*255 42049999 00000003 21c3e17b 21c3e17b 21c3e17b +(13/100)*255 42049999 fffffffd a5c3217b a5c3217b a5c3217b +(13/100)*255 42049999 fffffffc a5c3e121 a5c3e121 a5c3e121 +(13/100)*255 42049999 80000002 a521e17b a521e17b a521e17b +(13/100)*255 42049999 00000103 21c3e17b 21c3e17b 21c3e17b +(14/100)*255 420ecccd 00000000 a5c3e124 a5c3e123 a5c3e124 +(14/100)*255 420ecccd 00000001 a5c3247b a5c3237b a5c3247b +(14/100)*255 420ecccd 00000002 a524e17b a523e17b a524e17b +(14/100)*255 420ecccd 00000003 24c3e17b 23c3e17b 24c3e17b +(14/100)*255 420ecccd fffffffd a5c3247b a5c3237b a5c3247b +(14/100)*255 420ecccd fffffffc a5c3e124 a5c3e123 a5c3e124 +(14/100)*255 420ecccd 80000002 a524e17b a523e17b a524e17b +(14/100)*255 420ecccd 00000103 24c3e17b 23c3e17b 24c3e17b +(15/100)*255 42190000 00000000 a5c3e126 a5c3e126 a5c3e126 +(15/100)*255 42190000 00000001 a5c3267b a5c3267b a5c3267b +(15/100)*255 42190000 00000002 a526e17b a526e17b a526e17b +(15/100)*255 42190000 00000003 26c3e17b 26c3e17b 26c3e17b +(15/100)*255 42190000 fffffffd a5c3267b a5c3267b a5c3267b +(15/100)*255 42190000 fffffffc a5c3e126 a5c3e126 a5c3e126 +(15/100)*255 42190000 80000002 a526e17b a526e17b a526e17b +(15/100)*255 42190000 00000103 26c3e17b 26c3e17b 26c3e17b +(16/100)*255 42233333 00000000 a5c3e129 a5c3e128 a5c3e129 +(16/100)*255 42233333 00000001 a5c3297b a5c3287b a5c3297b +(16/100)*255 42233333 00000002 a529e17b a528e17b a529e17b +(16/100)*255 42233333 00000003 29c3e17b 28c3e17b 29c3e17b +(16/100)*255 42233333 fffffffd a5c3297b a5c3287b a5c3297b +(16/100)*255 42233333 fffffffc a5c3e129 a5c3e128 a5c3e129 +(16/100)*255 42233333 80000002 a529e17b a528e17b a529e17b +(16/100)*255 42233333 00000103 29c3e17b 28c3e17b 29c3e17b +(17/100)*255 422d6667 00000000 a5c3e12b a5c3e12b a5c3e12b +(17/100)*255 422d6667 00000001 a5c32b7b a5c32b7b a5c32b7b +(17/100)*255 422d6667 00000002 a52be17b a52be17b a52be17b +(17/100)*255 422d6667 00000003 2bc3e17b 2bc3e17b 2bc3e17b +(17/100)*255 422d6667 fffffffd a5c32b7b a5c32b7b a5c32b7b +(17/100)*255 422d6667 fffffffc a5c3e12b a5c3e12b a5c3e12b +(17/100)*255 422d6667 80000002 a52be17b a52be17b a52be17b +(17/100)*255 422d6667 00000103 2bc3e17b 2bc3e17b 2bc3e17b +(18/100)*255 4237999a 00000000 a5c3e12e a5c3e12d a5c3e12e +(18/100)*255 4237999a 00000001 a5c32e7b a5c32d7b a5c32e7b +(18/100)*255 4237999a 00000002 a52ee17b a52de17b a52ee17b +(18/100)*255 4237999a 00000003 2ec3e17b 2dc3e17b 2ec3e17b +(18/100)*255 4237999a fffffffd a5c32e7b a5c32d7b a5c32e7b +(18/100)*255 4237999a fffffffc a5c3e12e a5c3e12d a5c3e12e +(18/100)*255 4237999a 80000002 a52ee17b a52de17b a52ee17b +(18/100)*255 4237999a 00000103 2ec3e17b 2dc3e17b 2ec3e17b +(19/100)*255 4241cccd 00000000 a5c3e130 a5c3e130 a5c3e130 +(19/100)*255 4241cccd 00000001 a5c3307b a5c3307b a5c3307b +(19/100)*255 4241cccd 00000002 a530e17b a530e17b a530e17b +(19/100)*255 4241cccd 00000003 30c3e17b 30c3e17b 30c3e17b +(19/100)*255 4241cccd fffffffd a5c3307b a5c3307b a5c3307b +(19/100)*255 4241cccd fffffffc a5c3e130 a5c3e130 a5c3e130 +(19/100)*255 4241cccd 80000002 a530e17b a530e17b a530e17b +(19/100)*255 4241cccd 00000103 30c3e17b 30c3e17b 30c3e17b +(21/100)*255 42563333 00000000 a5c3e136 a5c3e135 a5c3e136 +(21/100)*255 42563333 00000001 a5c3367b a5c3357b a5c3367b +(21/100)*255 42563333 00000002 a536e17b a535e17b a536e17b +(21/100)*255 42563333 00000003 36c3e17b 35c3e17b 36c3e17b +(21/100)*255 42563333 fffffffd a5c3367b a5c3357b a5c3367b +(21/100)*255 42563333 fffffffc a5c3e136 a5c3e135 a5c3e136 +(21/100)*255 42563333 80000002 a536e17b a535e17b a536e17b +(21/100)*255 42563333 00000103 36c3e17b 35c3e17b 36c3e17b +(22/100)*255 42606666 00000000 a5c3e138 a5c3e138 a5c3e138 +(22/100)*255 42606666 00000001 a5c3387b a5c3387b a5c3387b +(22/100)*255 42606666 00000002 a538e17b a538e17b a538e17b +(22/100)*255 42606666 00000003 38c3e17b 38c3e17b 38c3e17b +(22/100)*255 42606666 fffffffd a5c3387b a5c3387b a5c3387b +(22/100)*255 42606666 fffffffc a5c3e138 a5c3e138 a5c3e138 +(22/100)*255 42606666 80000002 a538e17b a538e17b a538e17b +(22/100)*255 42606666 00000103 38c3e17b 38c3e17b 38c3e17b +(23/100)*255 426a999a 00000000 a5c3e13b a5c3e13a a5c3e13b +(23/100)*255 426a999a 00000001 a5c33b7b a5c33a7b a5c33b7b +(23/100)*255 426a999a 00000002 a53be17b a53ae17b a53be17b +(23/100)*255 426a999a 00000003 3bc3e17b 3ac3e17b 3bc3e17b +(23/100)*255 426a999a fffffffd a5c33b7b a5c33a7b a5c33b7b +(23/100)*255 426a999a fffffffc a5c3e13b a5c3e13a a5c3e13b +(23/100)*255 426a999a 80000002 a53be17b a53ae17b a53be17b +(23/100)*255 426a999a 00000103 3bc3e17b 3ac3e17b 3bc3e17b +(24/100)*255 4274cccc 00000000 a5c3e13d a5c3e13d a5c3e13d +(24/100)*255 4274cccc 00000001 a5c33d7b a5c33d7b a5c33d7b +(24/100)*255 4274cccc 00000002 a53de17b a53de17b a53de17b +(24/100)*255 4274cccc 00000003 3dc3e17b 3dc3e17b 3dc3e17b +(24/100)*255 4274cccc fffffffd a5c33d7b a5c33d7b a5c33d7b +(24/100)*255 4274cccc fffffffc a5c3e13d a5c3e13d a5c3e13d +(24/100)*255 4274cccc 80000002 a53de17b a53de17b a53de17b +(24/100)*255 4274cccc 00000103 3dc3e17b 3dc3e17b 3dc3e17b +(26/100)*255 42849999 00000000 a5c3e142 a5c3e142 a5c3e142 +(26/100)*255 42849999 00000001 a5c3427b a5c3427b a5c3427b +(26/100)*255 42849999 00000002 a542e17b a542e17b a542e17b +(26/100)*255 42849999 00000003 42c3e17b 42c3e17b 42c3e17b +(26/100)*255 42849999 fffffffd a5c3427b a5c3427b a5c3427b +(26/100)*255 42849999 fffffffc a5c3e142 a5c3e142 a5c3e142 +(26/100)*255 42849999 80000002 a542e17b a542e17b a542e17b +(26/100)*255 42849999 00000103 42c3e17b 42c3e17b 42c3e17b +(27/100)*255 4289b334 00000000 a5c3e145 a5c3e144 a5c3e145 +(27/100)*255 4289b334 00000001 a5c3457b a5c3447b a5c3457b +(27/100)*255 4289b334 00000002 a545e17b a544e17b a545e17b +(27/100)*255 4289b334 00000003 45c3e17b 44c3e17b 45c3e17b +(27/100)*255 4289b334 fffffffd a5c3457b a5c3447b a5c3457b +(27/100)*255 4289b334 fffffffc a5c3e145 a5c3e144 a5c3e145 +(27/100)*255 4289b334 80000002 a545e17b a544e17b a545e17b +(27/100)*255 4289b334 00000103 45c3e17b 44c3e17b 45c3e17b +(28/100)*255 428ecccd 00000000 a5c3e147 a5c3e147 a5c3e147 +(28/100)*255 428ecccd 00000001 a5c3477b a5c3477b a5c3477b +(28/100)*255 428ecccd 00000002 a547e17b a547e17b a547e17b +(28/100)*255 428ecccd 00000003 47c3e17b 47c3e17b 47c3e17b +(28/100)*255 428ecccd fffffffd a5c3477b a5c3477b a5c3477b +(28/100)*255 428ecccd fffffffc a5c3e147 a5c3e147 a5c3e147 +(28/100)*255 428ecccd 80000002 a547e17b a547e17b a547e17b +(28/100)*255 428ecccd 00000103 47c3e17b 47c3e17b 47c3e17b +(29/100)*255 4293e666 00000000 a5c3e14a a5c3e149 a5c3e14a +(29/100)*255 4293e666 00000001 a5c34a7b a5c3497b a5c34a7b +(29/100)*255 4293e666 00000002 a54ae17b a549e17b a54ae17b +(29/100)*255 4293e666 00000003 4ac3e17b 49c3e17b 4ac3e17b +(29/100)*255 4293e666 fffffffd a5c34a7b a5c3497b a5c34a7b +(29/100)*255 4293e666 fffffffc a5c3e14a a5c3e149 a5c3e14a +(29/100)*255 4293e666 80000002 a54ae17b a549e17b a54ae17b +(29/100)*255 4293e666 00000103 4ac3e17b 49c3e17b 4ac3e17b +(30/100)*255 42990000 00000000 a5c3e14c a5c3e14c a5c3e14c +(30/100)*255 42990000 00000001 a5c34c7b a5c34c7b a5c34c7b +(30/100)*255 42990000 00000002 a54ce17b a54ce17b a54ce17b +(30/100)*255 42990000 00000003 4cc3e17b 4cc3e17b 4cc3e17b +(30/100)*255 42990000 fffffffd a5c34c7b a5c34c7b a5c34c7b +(30/100)*255 42990000 fffffffc a5c3e14c a5c3e14c a5c3e14c +(30/100)*255 42990000 80000002 a54ce17b a54ce17b a54ce17b +(30/100)*255 42990000 00000103 4cc3e17b 4cc3e17b 4cc3e17b +(31/100)*255 429e199a 00000000 a5c3e14f a5c3e14f a5c3e14f +(31/100)*255 429e199a 00000001 a5c34f7b a5c34f7b a5c34f7b +(31/100)*255 429e199a 00000002 a54fe17b a54fe17b a54fe17b +(31/100)*255 429e199a 00000003 4fc3e17b 4fc3e17b 4fc3e17b +(31/100)*255 429e199a fffffffd a5c34f7b a5c34f7b a5c34f7b +(31/100)*255 429e199a fffffffc a5c3e14f a5c3e14f a5c3e14f +(31/100)*255 429e199a 80000002 a54fe17b a54fe17b a54fe17b +(31/100)*255 429e199a 00000103 4fc3e17b 4fc3e17b 4fc3e17b +(32/100)*255 42a33333 00000000 a5c3e152 a5c3e151 a5c3e152 +(32/100)*255 42a33333 00000001 a5c3527b a5c3517b a5c3527b +(32/100)*255 42a33333 00000002 a552e17b a551e17b a552e17b +(32/100)*255 42a33333 00000003 52c3e17b 51c3e17b 52c3e17b +(32/100)*255 42a33333 fffffffd a5c3527b a5c3517b a5c3527b +(32/100)*255 42a33333 fffffffc a5c3e152 a5c3e151 a5c3e152 +(32/100)*255 42a33333 80000002 a552e17b a551e17b a552e17b +(32/100)*255 42a33333 00000103 52c3e17b 51c3e17b 52c3e17b +(33/100)*255 42a84ccd 00000000 a5c3e154 a5c3e154 a5c3e154 +(33/100)*255 42a84ccd 00000001 a5c3547b a5c3547b a5c3547b +(33/100)*255 42a84ccd 00000002 a554e17b a554e17b a554e17b +(33/100)*255 42a84ccd 00000003 54c3e17b 54c3e17b 54c3e17b +(33/100)*255 42a84ccd fffffffd a5c3547b a5c3547b a5c3547b +(33/100)*255 42a84ccd fffffffc a5c3e154 a5c3e154 a5c3e154 +(33/100)*255 42a84ccd 80000002 a554e17b a554e17b a554e17b +(33/100)*255 42a84ccd 00000103 54c3e17b 54c3e17b 54c3e17b +(34/100)*255 42ad6667 00000000 a5c3e157 a5c3e156 a5c3e157 +(34/100)*255 42ad6667 00000001 a5c3577b a5c3567b a5c3577b +(34/100)*255 42ad6667 00000002 a557e17b a556e17b a557e17b +(34/100)*255 42ad6667 00000003 57c3e17b 56c3e17b 57c3e17b +(34/100)*255 42ad6667 fffffffd a5c3577b a5c3567b a5c3577b +(34/100)*255 42ad6667 fffffffc a5c3e157 a5c3e156 a5c3e157 +(34/100)*255 42ad6667 80000002 a557e17b a556e17b a557e17b +(34/100)*255 42ad6667 00000103 57c3e17b 56c3e17b 57c3e17b +(35/100)*255 42b28000 00000000 a5c3e159 a5c3e159 a5c3e159 +(35/100)*255 42b28000 00000001 a5c3597b a5c3597b a5c3597b +(35/100)*255 42b28000 00000002 a559e17b a559e17b a559e17b +(35/100)*255 42b28000 00000003 59c3e17b 59c3e17b 59c3e17b +(35/100)*255 42b28000 fffffffd a5c3597b a5c3597b a5c3597b +(35/100)*255 42b28000 fffffffc a5c3e159 a5c3e159 a5c3e159 +(35/100)*255 42b28000 80000002 a559e17b a559e17b a559e17b +(35/100)*255 42b28000 00000103 59c3e17b 59c3e17b 59c3e17b +(36/100)*255 42b7999a 00000000 a5c3e15c a5c3e15b a5c3e15c +(36/100)*255 42b7999a 00000001 a5c35c7b a5c35b7b a5c35c7b +(36/100)*255 42b7999a 00000002 a55ce17b a55be17b a55ce17b +(36/100)*255 42b7999a 00000003 5cc3e17b 5bc3e17b 5cc3e17b +(36/100)*255 42b7999a fffffffd a5c35c7b a5c35b7b a5c35c7b +(36/100)*255 42b7999a fffffffc a5c3e15c a5c3e15b a5c3e15c +(36/100)*255 42b7999a 80000002 a55ce17b a55be17b a55ce17b +(36/100)*255 42b7999a 00000103 5cc3e17b 5bc3e17b 5cc3e17b +(37/100)*255 42bcb333 00000000 a5c3e15e a5c3e15e a5c3e15e +(37/100)*255 42bcb333 00000001 a5c35e7b a5c35e7b a5c35e7b +(37/100)*255 42bcb333 00000002 a55ee17b a55ee17b a55ee17b +(37/100)*255 42bcb333 00000003 5ec3e17b 5ec3e17b 5ec3e17b +(37/100)*255 42bcb333 fffffffd a5c35e7b a5c35e7b a5c35e7b +(37/100)*255 42bcb333 fffffffc a5c3e15e a5c3e15e a5c3e15e +(37/100)*255 42bcb333 80000002 a55ee17b a55ee17b a55ee17b +(37/100)*255 42bcb333 00000103 5ec3e17b 5ec3e17b 5ec3e17b +(38/100)*255 42c1cccd 00000000 a5c3e161 a5c3e160 a5c3e161 +(38/100)*255 42c1cccd 00000001 a5c3617b a5c3607b a5c3617b +(38/100)*255 42c1cccd 00000002 a561e17b a560e17b a561e17b +(38/100)*255 42c1cccd 00000003 61c3e17b 60c3e17b 61c3e17b +(38/100)*255 42c1cccd fffffffd a5c3617b a5c3607b a5c3617b +(38/100)*255 42c1cccd fffffffc a5c3e161 a5c3e160 a5c3e161 +(38/100)*255 42c1cccd 80000002 a561e17b a560e17b a561e17b +(38/100)*255 42c1cccd 00000103 61c3e17b 60c3e17b 61c3e17b +(39/100)*255 42c6e666 00000000 a5c3e163 a5c3e163 a5c3e163 +(39/100)*255 42c6e666 00000001 a5c3637b a5c3637b a5c3637b +(39/100)*255 42c6e666 00000002 a563e17b a563e17b a563e17b +(39/100)*255 42c6e666 00000003 63c3e17b 63c3e17b 63c3e17b +(39/100)*255 42c6e666 fffffffd a5c3637b a5c3637b a5c3637b +(39/100)*255 42c6e666 fffffffc a5c3e163 a5c3e163 a5c3e163 +(39/100)*255 42c6e666 80000002 a563e17b a563e17b a563e17b +(39/100)*255 42c6e666 00000103 63c3e17b 63c3e17b 63c3e17b +(41/100)*255 42d11999 00000000 a5c3e169 a5c3e168 a5c3e169 +(41/100)*255 42d11999 00000001 a5c3697b a5c3687b a5c3697b +(41/100)*255 42d11999 00000002 a569e17b a568e17b a569e17b +(41/100)*255 42d11999 00000003 69c3e17b 68c3e17b 69c3e17b +(41/100)*255 42d11999 fffffffd a5c3697b a5c3687b a5c3697b +(41/100)*255 42d11999 fffffffc a5c3e169 a5c3e168 a5c3e169 +(41/100)*255 42d11999 80000002 a569e17b a568e17b a569e17b +(41/100)*255 42d11999 00000103 69c3e17b 68c3e17b 69c3e17b +(42/100)*255 42d63333 00000000 a5c3e16b a5c3e16b a5c3e16b +(42/100)*255 42d63333 00000001 a5c36b7b a5c36b7b a5c36b7b +(42/100)*255 42d63333 00000002 a56be17b a56be17b a56be17b +(42/100)*255 42d63333 00000003 6bc3e17b 6bc3e17b 6bc3e17b +(42/100)*255 42d63333 fffffffd a5c36b7b a5c36b7b a5c36b7b +(42/100)*255 42d63333 fffffffc a5c3e16b a5c3e16b a5c3e16b +(42/100)*255 42d63333 80000002 a56be17b a56be17b a56be17b +(42/100)*255 42d63333 00000103 6bc3e17b 6bc3e17b 6bc3e17b +(43/100)*255 42db4ccd 00000000 a5c3e16e a5c3e16d a5c3e16e +(43/100)*255 42db4ccd 00000001 a5c36e7b a5c36d7b a5c36e7b +(43/100)*255 42db4ccd 00000002 a56ee17b a56de17b a56ee17b +(43/100)*255 42db4ccd 00000003 6ec3e17b 6dc3e17b 6ec3e17b +(43/100)*255 42db4ccd fffffffd a5c36e7b a5c36d7b a5c36e7b +(43/100)*255 42db4ccd fffffffc a5c3e16e a5c3e16d a5c3e16e +(43/100)*255 42db4ccd 80000002 a56ee17b a56de17b a56ee17b +(43/100)*255 42db4ccd 00000103 6ec3e17b 6dc3e17b 6ec3e17b +(44/100)*255 42e06666 00000000 a5c3e170 a5c3e170 a5c3e170 +(44/100)*255 42e06666 00000001 a5c3707b a5c3707b a5c3707b +(44/100)*255 42e06666 00000002 a570e17b a570e17b a570e17b +(44/100)*255 42e06666 00000003 70c3e17b 70c3e17b 70c3e17b +(44/100)*255 42e06666 fffffffd a5c3707b a5c3707b a5c3707b +(44/100)*255 42e06666 fffffffc a5c3e170 a5c3e170 a5c3e170 +(44/100)*255 42e06666 80000002 a570e17b a570e17b a570e17b +(44/100)*255 42e06666 00000103 70c3e17b 70c3e17b 70c3e17b +(45/100)*255 42e58000 00000000 a5c3e173 a5c3e172 a5c3e173 +(45/100)*255 42e58000 00000001 a5c3737b a5c3727b a5c3737b +(45/100)*255 42e58000 00000002 a573e17b a572e17b a573e17b +(45/100)*255 42e58000 00000003 73c3e17b 72c3e17b 73c3e17b +(45/100)*255 42e58000 fffffffd a5c3737b a5c3727b a5c3737b +(45/100)*255 42e58000 fffffffc a5c3e173 a5c3e172 a5c3e173 +(45/100)*255 42e58000 80000002 a573e17b a572e17b a573e17b +(45/100)*255 42e58000 00000103 73c3e17b 72c3e17b 73c3e17b +(46/100)*255 42ea999a 00000000 a5c3e175 a5c3e175 a5c3e175 +(46/100)*255 42ea999a 00000001 a5c3757b a5c3757b a5c3757b +(46/100)*255 42ea999a 00000002 a575e17b a575e17b a575e17b +(46/100)*255 42ea999a 00000003 75c3e17b 75c3e17b 75c3e17b +(46/100)*255 42ea999a fffffffd a5c3757b a5c3757b a5c3757b +(46/100)*255 42ea999a fffffffc a5c3e175 a5c3e175 a5c3e175 +(46/100)*255 42ea999a 80000002 a575e17b a575e17b a575e17b +(46/100)*255 42ea999a 00000103 75c3e17b 75c3e17b 75c3e17b +(47/100)*255 42efb333 00000000 a5c3e178 a5c3e177 a5c3e178 +(47/100)*255 42efb333 00000001 a5c3787b a5c3777b a5c3787b +(47/100)*255 42efb333 00000002 a578e17b a577e17b a578e17b +(47/100)*255 42efb333 00000003 78c3e17b 77c3e17b 78c3e17b +(47/100)*255 42efb333 fffffffd a5c3787b a5c3777b a5c3787b +(47/100)*255 42efb333 fffffffc a5c3e178 a5c3e177 a5c3e178 +(47/100)*255 42efb333 80000002 a578e17b a577e17b a578e17b +(47/100)*255 42efb333 00000103 78c3e17b 77c3e17b 78c3e17b +(48/100)*255 42f4cccc 00000000 a5c3e17a a5c3e17a a5c3e17a +(48/100)*255 42f4cccc 00000001 a5c37a7b a5c37a7b a5c37a7b +(48/100)*255 42f4cccc 00000002 a57ae17b a57ae17b a57ae17b +(48/100)*255 42f4cccc 00000003 7ac3e17b 7ac3e17b 7ac3e17b +(48/100)*255 42f4cccc fffffffd a5c37a7b a5c37a7b a5c37a7b +(48/100)*255 42f4cccc fffffffc a5c3e17a a5c3e17a a5c3e17a +(48/100)*255 42f4cccc 80000002 a57ae17b a57ae17b a57ae17b +(48/100)*255 42f4cccc 00000103 7ac3e17b 7ac3e17b 7ac3e17b +(49/100)*255 42f9e667 00000000 a5c3e17d a5c3e17c a5c3e17d +(49/100)*255 42f9e667 00000001 a5c37d7b a5c37c7b a5c37d7b +(49/100)*255 42f9e667 00000002 a57de17b a57ce17b a57de17b +(49/100)*255 42f9e667 00000003 7dc3e17b 7cc3e17b 7dc3e17b +(49/100)*255 42f9e667 fffffffd a5c37d7b a5c37c7b a5c37d7b +(49/100)*255 42f9e667 fffffffc a5c3e17d a5c3e17c a5c3e17d +(49/100)*255 42f9e667 80000002 a57de17b a57ce17b a57de17b +(49/100)*255 42f9e667 00000103 7dc3e17b 7cc3e17b 7dc3e17b +(51/100)*255 43020ccd 00000000 a5c3e182 a5c3e182 a5c3e182 +(51/100)*255 43020ccd 00000001 a5c3827b a5c3827b a5c3827b +(51/100)*255 43020ccd 00000002 a582e17b a582e17b a582e17b +(51/100)*255 43020ccd 00000003 82c3e17b 82c3e17b 82c3e17b +(51/100)*255 43020ccd fffffffd a5c3827b a5c3827b a5c3827b +(51/100)*255 43020ccd fffffffc a5c3e182 a5c3e182 a5c3e182 +(51/100)*255 43020ccd 80000002 a582e17b a582e17b a582e17b +(51/100)*255 43020ccd 00000103 82c3e17b 82c3e17b 82c3e17b +(52/100)*255 43049999 00000000 a5c3e185 a5c3e184 a5c3e185 +(52/100)*255 43049999 00000001 a5c3857b a5c3847b a5c3857b +(52/100)*255 43049999 00000002 a585e17b a584e17b a585e17b +(52/100)*255 43049999 00000003 85c3e17b 84c3e17b 85c3e17b +(52/100)*255 43049999 fffffffd a5c3857b a5c3847b a5c3857b +(52/100)*255 43049999 fffffffc a5c3e185 a5c3e184 a5c3e185 +(52/100)*255 43049999 80000002 a585e17b a584e17b a585e17b +(52/100)*255 43049999 00000103 85c3e17b 84c3e17b 85c3e17b +(53/100)*255 43072666 00000000 a5c3e187 a5c3e187 a5c3e187 +(53/100)*255 43072666 00000001 a5c3877b a5c3877b a5c3877b +(53/100)*255 43072666 00000002 a587e17b a587e17b a587e17b +(53/100)*255 43072666 00000003 87c3e17b 87c3e17b 87c3e17b +(53/100)*255 43072666 fffffffd a5c3877b a5c3877b a5c3877b +(53/100)*255 43072666 fffffffc a5c3e187 a5c3e187 a5c3e187 +(53/100)*255 43072666 80000002 a587e17b a587e17b a587e17b +(53/100)*255 43072666 00000103 87c3e17b 87c3e17b 87c3e17b +(54/100)*255 4309b334 00000000 a5c3e18a a5c3e189 a5c3e18a +(54/100)*255 4309b334 00000001 a5c38a7b a5c3897b a5c38a7b +(54/100)*255 4309b334 00000002 a58ae17b a589e17b a58ae17b +(54/100)*255 4309b334 00000003 8ac3e17b 89c3e17b 8ac3e17b +(54/100)*255 4309b334 fffffffd a5c38a7b a5c3897b a5c38a7b +(54/100)*255 4309b334 fffffffc a5c3e18a a5c3e189 a5c3e18a +(54/100)*255 4309b334 80000002 a58ae17b a589e17b a58ae17b +(54/100)*255 4309b334 00000103 8ac3e17b 89c3e17b 8ac3e17b +(55/100)*255 430c4000 00000000 a5c3e18c a5c3e18c a5c3e18c +(55/100)*255 430c4000 00000001 a5c38c7b a5c38c7b a5c38c7b +(55/100)*255 430c4000 00000002 a58ce17b a58ce17b a58ce17b +(55/100)*255 430c4000 00000003 8cc3e17b 8cc3e17b 8cc3e17b +(55/100)*255 430c4000 fffffffd a5c38c7b a5c38c7b a5c38c7b +(55/100)*255 430c4000 fffffffc a5c3e18c a5c3e18c a5c3e18c +(55/100)*255 430c4000 80000002 a58ce17b a58ce17b a58ce17b +(55/100)*255 430c4000 00000103 8cc3e17b 8cc3e17b 8cc3e17b +(56/100)*255 430ecccd 00000000 a5c3e18f a5c3e18e a5c3e18f +(56/100)*255 430ecccd 00000001 a5c38f7b a5c38e7b a5c38f7b +(56/100)*255 430ecccd 00000002 a58fe17b a58ee17b a58fe17b +(56/100)*255 430ecccd 00000003 8fc3e17b 8ec3e17b 8fc3e17b +(56/100)*255 430ecccd fffffffd a5c38f7b a5c38e7b a5c38f7b +(56/100)*255 430ecccd fffffffc a5c3e18f a5c3e18e a5c3e18f +(56/100)*255 430ecccd 80000002 a58fe17b a58ee17b a58fe17b +(56/100)*255 430ecccd 00000103 8fc3e17b 8ec3e17b 8fc3e17b +(57/100)*255 43115999 00000000 a5c3e191 a5c3e191 a5c3e191 +(57/100)*255 43115999 00000001 a5c3917b a5c3917b a5c3917b +(57/100)*255 43115999 00000002 a591e17b a591e17b a591e17b +(57/100)*255 43115999 00000003 91c3e17b 91c3e17b 91c3e17b +(57/100)*255 43115999 fffffffd a5c3917b a5c3917b a5c3917b +(57/100)*255 43115999 fffffffc a5c3e191 a5c3e191 a5c3e191 +(57/100)*255 43115999 80000002 a591e17b a591e17b a591e17b +(57/100)*255 43115999 00000103 91c3e17b 91c3e17b 91c3e17b +(58/100)*255 4313e666 00000000 a5c3e194 a5c3e193 a5c3e194 +(58/100)*255 4313e666 00000001 a5c3947b a5c3937b a5c3947b +(58/100)*255 4313e666 00000002 a594e17b a593e17b a594e17b +(58/100)*255 4313e666 00000003 94c3e17b 93c3e17b 94c3e17b +(58/100)*255 4313e666 fffffffd a5c3947b a5c3937b a5c3947b +(58/100)*255 4313e666 fffffffc a5c3e194 a5c3e193 a5c3e194 +(58/100)*255 4313e666 80000002 a594e17b a593e17b a594e17b +(58/100)*255 4313e666 00000103 94c3e17b 93c3e17b 94c3e17b +(59/100)*255 43167333 00000000 a5c3e196 a5c3e196 a5c3e196 +(59/100)*255 43167333 00000001 a5c3967b a5c3967b a5c3967b +(59/100)*255 43167333 00000002 a596e17b a596e17b a596e17b +(59/100)*255 43167333 00000003 96c3e17b 96c3e17b 96c3e17b +(59/100)*255 43167333 fffffffd a5c3967b a5c3967b a5c3967b +(59/100)*255 43167333 fffffffc a5c3e196 a5c3e196 a5c3e196 +(59/100)*255 43167333 80000002 a596e17b a596e17b a596e17b +(59/100)*255 43167333 00000103 96c3e17b 96c3e17b 96c3e17b +(61/100)*255 431b8ccd 00000000 a5c3e19c a5c3e19b a5c3e19c +(61/100)*255 431b8ccd 00000001 a5c39c7b a5c39b7b a5c39c7b +(61/100)*255 431b8ccd 00000002 a59ce17b a59be17b a59ce17b +(61/100)*255 431b8ccd 00000003 9cc3e17b 9bc3e17b 9cc3e17b +(61/100)*255 431b8ccd fffffffd a5c39c7b a5c39b7b a5c39c7b +(61/100)*255 431b8ccd fffffffc a5c3e19c a5c3e19b a5c3e19c +(61/100)*255 431b8ccd 80000002 a59ce17b a59be17b a59ce17b +(61/100)*255 431b8ccd 00000103 9cc3e17b 9bc3e17b 9cc3e17b +(62/100)*255 431e199a 00000000 a5c3e19e a5c3e19e a5c3e19e +(62/100)*255 431e199a 00000001 a5c39e7b a5c39e7b a5c39e7b +(62/100)*255 431e199a 00000002 a59ee17b a59ee17b a59ee17b +(62/100)*255 431e199a 00000003 9ec3e17b 9ec3e17b 9ec3e17b +(62/100)*255 431e199a fffffffd a5c39e7b a5c39e7b a5c39e7b +(62/100)*255 431e199a fffffffc a5c3e19e a5c3e19e a5c3e19e +(62/100)*255 431e199a 80000002 a59ee17b a59ee17b a59ee17b +(62/100)*255 431e199a 00000103 9ec3e17b 9ec3e17b 9ec3e17b +(63/100)*255 4320a666 00000000 a5c3e1a1 a5c3e1a0 a5c3e1a1 +(63/100)*255 4320a666 00000001 a5c3a17b a5c3a07b a5c3a17b +(63/100)*255 4320a666 00000002 a5a1e17b a5a0e17b a5a1e17b +(63/100)*255 4320a666 00000003 a1c3e17b a0c3e17b a1c3e17b +(63/100)*255 4320a666 fffffffd a5c3a17b a5c3a07b a5c3a17b +(63/100)*255 4320a666 fffffffc a5c3e1a1 a5c3e1a0 a5c3e1a1 +(63/100)*255 4320a666 80000002 a5a1e17b a5a0e17b a5a1e17b +(63/100)*255 4320a666 00000103 a1c3e17b a0c3e17b a1c3e17b +(64/100)*255 43233333 00000000 a5c3e1a3 a5c3e1a3 a5c3e1a3 +(64/100)*255 43233333 00000001 a5c3a37b a5c3a37b a5c3a37b +(64/100)*255 43233333 00000002 a5a3e17b a5a3e17b a5a3e17b +(64/100)*255 43233333 00000003 a3c3e17b a3c3e17b a3c3e17b +(64/100)*255 43233333 fffffffd a5c3a37b a5c3a37b a5c3a37b +(64/100)*255 43233333 fffffffc a5c3e1a3 a5c3e1a3 a5c3e1a3 +(64/100)*255 43233333 80000002 a5a3e17b a5a3e17b a5a3e17b +(64/100)*255 43233333 00000103 a3c3e17b a3c3e17b a3c3e17b +(65/100)*255 4325c000 00000000 a5c3e1a6 a5c3e1a5 a5c3e1a6 +(65/100)*255 4325c000 00000001 a5c3a67b a5c3a57b a5c3a67b +(65/100)*255 4325c000 00000002 a5a6e17b a5a5e17b a5a6e17b +(65/100)*255 4325c000 00000003 a6c3e17b a5c3e17b a6c3e17b +(65/100)*255 4325c000 fffffffd a5c3a67b a5c3a57b a5c3a67b +(65/100)*255 4325c000 fffffffc a5c3e1a6 a5c3e1a5 a5c3e1a6 +(65/100)*255 4325c000 80000002 a5a6e17b a5a5e17b a5a6e17b +(65/100)*255 4325c000 00000103 a6c3e17b a5c3e17b a6c3e17b +(66/100)*255 43284ccd 00000000 a5c3e1a8 a5c3e1a8 a5c3e1a8 +(66/100)*255 43284ccd 00000001 a5c3a87b a5c3a87b a5c3a87b +(66/100)*255 43284ccd 00000002 a5a8e17b a5a8e17b a5a8e17b +(66/100)*255 43284ccd 00000003 a8c3e17b a8c3e17b a8c3e17b +(66/100)*255 43284ccd fffffffd a5c3a87b a5c3a87b a5c3a87b +(66/100)*255 43284ccd fffffffc a5c3e1a8 a5c3e1a8 a5c3e1a8 +(66/100)*255 43284ccd 80000002 a5a8e17b a5a8e17b a5a8e17b +(66/100)*255 43284ccd 00000103 a8c3e17b a8c3e17b a8c3e17b +(67/100)*255 432ad99a 00000000 a5c3e1ab a5c3e1aa a5c3e1ab +(67/100)*255 432ad99a 00000001 a5c3ab7b a5c3aa7b a5c3ab7b +(67/100)*255 432ad99a 00000002 a5abe17b a5aae17b a5abe17b +(67/100)*255 432ad99a 00000003 abc3e17b aac3e17b abc3e17b +(67/100)*255 432ad99a fffffffd a5c3ab7b a5c3aa7b a5c3ab7b +(67/100)*255 432ad99a fffffffc a5c3e1ab a5c3e1aa a5c3e1ab +(67/100)*255 432ad99a 80000002 a5abe17b a5aae17b a5abe17b +(67/100)*255 432ad99a 00000103 abc3e17b aac3e17b abc3e17b +(68/100)*255 432d6667 00000000 a5c3e1ad a5c3e1ad a5c3e1ad +(68/100)*255 432d6667 00000001 a5c3ad7b a5c3ad7b a5c3ad7b +(68/100)*255 432d6667 00000002 a5ade17b a5ade17b a5ade17b +(68/100)*255 432d6667 00000003 adc3e17b adc3e17b adc3e17b +(68/100)*255 432d6667 fffffffd a5c3ad7b a5c3ad7b a5c3ad7b +(68/100)*255 432d6667 fffffffc a5c3e1ad a5c3e1ad a5c3e1ad +(68/100)*255 432d6667 80000002 a5ade17b a5ade17b a5ade17b +(68/100)*255 432d6667 00000103 adc3e17b adc3e17b adc3e17b +(69/100)*255 432ff333 00000000 a5c3e1b0 a5c3e1af a5c3e1b0 +(69/100)*255 432ff333 00000001 a5c3b07b a5c3af7b a5c3b07b +(69/100)*255 432ff333 00000002 a5b0e17b a5afe17b a5b0e17b +(69/100)*255 432ff333 00000003 b0c3e17b afc3e17b b0c3e17b +(69/100)*255 432ff333 fffffffd a5c3b07b a5c3af7b a5c3b07b +(69/100)*255 432ff333 fffffffc a5c3e1b0 a5c3e1af a5c3e1b0 +(69/100)*255 432ff333 80000002 a5b0e17b a5afe17b a5b0e17b +(69/100)*255 432ff333 00000103 b0c3e17b afc3e17b b0c3e17b +(70/100)*255 43328000 00000000 a5c3e1b2 a5c3e1b2 a5c3e1b2 +(70/100)*255 43328000 00000001 a5c3b27b a5c3b27b a5c3b27b +(70/100)*255 43328000 00000002 a5b2e17b a5b2e17b a5b2e17b +(70/100)*255 43328000 00000003 b2c3e17b b2c3e17b b2c3e17b +(70/100)*255 43328000 fffffffd a5c3b27b a5c3b27b a5c3b27b +(70/100)*255 43328000 fffffffc a5c3e1b2 a5c3e1b2 a5c3e1b2 +(70/100)*255 43328000 80000002 a5b2e17b a5b2e17b a5b2e17b +(70/100)*255 43328000 00000103 b2c3e17b b2c3e17b b2c3e17b +(71/100)*255 43350ccc 00000000 a5c3e1b5 a5c3e1b5 a5c3e1b5 +(71/100)*255 43350ccc 00000001 a5c3b57b a5c3b57b a5c3b57b +(71/100)*255 43350ccc 00000002 a5b5e17b a5b5e17b a5b5e17b +(71/100)*255 43350ccc 00000003 b5c3e17b b5c3e17b b5c3e17b +(71/100)*255 43350ccc fffffffd a5c3b57b a5c3b57b a5c3b57b +(71/100)*255 43350ccc fffffffc a5c3e1b5 a5c3e1b5 a5c3e1b5 +(71/100)*255 43350ccc 80000002 a5b5e17b a5b5e17b a5b5e17b +(71/100)*255 43350ccc 00000103 b5c3e17b b5c3e17b b5c3e17b +(72/100)*255 4337999a 00000000 a5c3e1b8 a5c3e1b7 a5c3e1b8 +(72/100)*255 4337999a 00000001 a5c3b87b a5c3b77b a5c3b87b +(72/100)*255 4337999a 00000002 a5b8e17b a5b7e17b a5b8e17b +(72/100)*255 4337999a 00000003 b8c3e17b b7c3e17b b8c3e17b +(72/100)*255 4337999a fffffffd a5c3b87b a5c3b77b a5c3b87b +(72/100)*255 4337999a fffffffc a5c3e1b8 a5c3e1b7 a5c3e1b8 +(72/100)*255 4337999a 80000002 a5b8e17b a5b7e17b a5b8e17b +(72/100)*255 4337999a 00000103 b8c3e17b b7c3e17b b8c3e17b +(73/100)*255 433a2667 00000000 a5c3e1ba a5c3e1ba a5c3e1ba +(73/100)*255 433a2667 00000001 a5c3ba7b a5c3ba7b a5c3ba7b +(73/100)*255 433a2667 00000002 a5bae17b a5bae17b a5bae17b +(73/100)*255 433a2667 00000003 bac3e17b bac3e17b bac3e17b +(73/100)*255 433a2667 fffffffd a5c3ba7b a5c3ba7b a5c3ba7b +(73/100)*255 433a2667 fffffffc a5c3e1ba a5c3e1ba a5c3e1ba +(73/100)*255 433a2667 80000002 a5bae17b a5bae17b a5bae17b +(73/100)*255 433a2667 00000103 bac3e17b bac3e17b bac3e17b +(74/100)*255 433cb333 00000000 a5c3e1bd a5c3e1bc a5c3e1bd +(74/100)*255 433cb333 00000001 a5c3bd7b a5c3bc7b a5c3bd7b +(74/100)*255 433cb333 00000002 a5bde17b a5bce17b a5bde17b +(74/100)*255 433cb333 00000003 bdc3e17b bcc3e17b bdc3e17b +(74/100)*255 433cb333 fffffffd a5c3bd7b a5c3bc7b a5c3bd7b +(74/100)*255 433cb333 fffffffc a5c3e1bd a5c3e1bc a5c3e1bd +(74/100)*255 433cb333 80000002 a5bde17b a5bce17b a5bde17b +(74/100)*255 433cb333 00000103 bdc3e17b bcc3e17b bdc3e17b +(76/100)*255 4341cccd 00000000 a5c3e1c2 a5c3e1c1 a5c3e1c2 +(76/100)*255 4341cccd 00000001 a5c3c27b a5c3c17b a5c3c27b +(76/100)*255 4341cccd 00000002 a5c2e17b a5c1e17b a5c2e17b +(76/100)*255 4341cccd 00000003 c2c3e17b c1c3e17b c2c3e17b +(76/100)*255 4341cccd fffffffd a5c3c27b a5c3c17b a5c3c27b +(76/100)*255 4341cccd fffffffc a5c3e1c2 a5c3e1c1 a5c3e1c2 +(76/100)*255 4341cccd 80000002 a5c2e17b a5c1e17b a5c2e17b +(76/100)*255 4341cccd 00000103 c2c3e17b c1c3e17b c2c3e17b +(77/100)*255 43445999 00000000 a5c3e1c4 a5c3e1c4 a5c3e1c4 +(77/100)*255 43445999 00000001 a5c3c47b a5c3c47b a5c3c47b +(77/100)*255 43445999 00000002 a5c4e17b a5c4e17b a5c4e17b +(77/100)*255 43445999 00000003 c4c3e17b c4c3e17b c4c3e17b +(77/100)*255 43445999 fffffffd a5c3c47b a5c3c47b a5c3c47b +(77/100)*255 43445999 fffffffc a5c3e1c4 a5c3e1c4 a5c3e1c4 +(77/100)*255 43445999 80000002 a5c4e17b a5c4e17b a5c4e17b +(77/100)*255 43445999 00000103 c4c3e17b c4c3e17b c4c3e17b +(78/100)*255 4346e666 00000000 a5c3e1c7 a5c3e1c6 a5c3e1c7 +(78/100)*255 4346e666 00000001 a5c3c77b a5c3c67b a5c3c77b +(78/100)*255 4346e666 00000002 a5c7e17b a5c6e17b a5c7e17b +(78/100)*255 4346e666 00000003 c7c3e17b c6c3e17b c7c3e17b +(78/100)*255 4346e666 fffffffd a5c3c77b a5c3c67b a5c3c77b +(78/100)*255 4346e666 fffffffc a5c3e1c7 a5c3e1c6 a5c3e1c7 +(78/100)*255 4346e666 80000002 a5c7e17b a5c6e17b a5c7e17b +(78/100)*255 4346e666 00000103 c7c3e17b c6c3e17b c7c3e17b +(79/100)*255 43497334 00000000 a5c3e1c9 a5c3e1c9 a5c3e1c9 +(79/100)*255 43497334 00000001 a5c3c97b a5c3c97b a5c3c97b +(79/100)*255 43497334 00000002 a5c9e17b a5c9e17b a5c9e17b +(79/100)*255 43497334 00000003 c9c3e17b c9c3e17b c9c3e17b +(79/100)*255 43497334 fffffffd a5c3c97b a5c3c97b a5c3c97b +(79/100)*255 43497334 fffffffc a5c3e1c9 a5c3e1c9 a5c3e1c9 +(79/100)*255 43497334 80000002 a5c9e17b a5c9e17b a5c9e17b +(79/100)*255 43497334 00000103 c9c3e17b c9c3e17b c9c3e17b +(81/100)*255 434e8ccd 00000000 a5c3e1cf a5c3e1ce a5c3e1cf +(81/100)*255 434e8ccd 00000001 a5c3cf7b a5c3ce7b a5c3cf7b +(81/100)*255 434e8ccd 00000002 a5cfe17b a5cee17b a5cfe17b +(81/100)*255 434e8ccd 00000003 cfc3e17b cec3e17b cfc3e17b +(81/100)*255 434e8ccd fffffffd a5c3cf7b a5c3ce7b a5c3cf7b +(81/100)*255 434e8ccd fffffffc a5c3e1cf a5c3e1ce a5c3e1cf +(81/100)*255 434e8ccd 80000002 a5cfe17b a5cee17b a5cfe17b +(81/100)*255 434e8ccd 00000103 cfc3e17b cec3e17b cfc3e17b +(82/100)*255 43511999 00000000 a5c3e1d1 a5c3e1d1 a5c3e1d1 +(82/100)*255 43511999 00000001 a5c3d17b a5c3d17b a5c3d17b +(82/100)*255 43511999 00000002 a5d1e17b a5d1e17b a5d1e17b +(82/100)*255 43511999 00000003 d1c3e17b d1c3e17b d1c3e17b +(82/100)*255 43511999 fffffffd a5c3d17b a5c3d17b a5c3d17b +(82/100)*255 43511999 fffffffc a5c3e1d1 a5c3e1d1 a5c3e1d1 +(82/100)*255 43511999 80000002 a5d1e17b a5d1e17b a5d1e17b +(82/100)*255 43511999 00000103 d1c3e17b d1c3e17b d1c3e17b +(83/100)*255 4353a666 00000000 a5c3e1d4 a5c3e1d3 a5c3e1d4 +(83/100)*255 4353a666 00000001 a5c3d47b a5c3d37b a5c3d47b +(83/100)*255 4353a666 00000002 a5d4e17b a5d3e17b a5d4e17b +(83/100)*255 4353a666 00000003 d4c3e17b d3c3e17b d4c3e17b +(83/100)*255 4353a666 fffffffd a5c3d47b a5c3d37b a5c3d47b +(83/100)*255 4353a666 fffffffc a5c3e1d4 a5c3e1d3 a5c3e1d4 +(83/100)*255 4353a666 80000002 a5d4e17b a5d3e17b a5d4e17b +(83/100)*255 4353a666 00000103 d4c3e17b d3c3e17b d4c3e17b +(84/100)*255 43563333 00000000 a5c3e1d6 a5c3e1d6 a5c3e1d6 +(84/100)*255 43563333 00000001 a5c3d67b a5c3d67b a5c3d67b +(84/100)*255 43563333 00000002 a5d6e17b a5d6e17b a5d6e17b +(84/100)*255 43563333 00000003 d6c3e17b d6c3e17b d6c3e17b +(84/100)*255 43563333 fffffffd a5c3d67b a5c3d67b a5c3d67b +(84/100)*255 43563333 fffffffc a5c3e1d6 a5c3e1d6 a5c3e1d6 +(84/100)*255 43563333 80000002 a5d6e17b a5d6e17b a5d6e17b +(84/100)*255 43563333 00000103 d6c3e17b d6c3e17b d6c3e17b +(85/100)*255 4358c000 00000000 a5c3e1d9 a5c3e1d8 a5c3e1d9 +(85/100)*255 4358c000 00000001 a5c3d97b a5c3d87b a5c3d97b +(85/100)*255 4358c000 00000002 a5d9e17b a5d8e17b a5d9e17b +(85/100)*255 4358c000 00000003 d9c3e17b d8c3e17b d9c3e17b +(85/100)*255 4358c000 fffffffd a5c3d97b a5c3d87b a5c3d97b +(85/100)*255 4358c000 fffffffc a5c3e1d9 a5c3e1d8 a5c3e1d9 +(85/100)*255 4358c000 80000002 a5d9e17b a5d8e17b a5d9e17b +(85/100)*255 4358c000 00000103 d9c3e17b d8c3e17b d9c3e17b +(86/100)*255 435b4ccd 00000000 a5c3e1db a5c3e1db a5c3e1db +(86/100)*255 435b4ccd 00000001 a5c3db7b a5c3db7b a5c3db7b +(86/100)*255 435b4ccd 00000002 a5dbe17b a5dbe17b a5dbe17b +(86/100)*255 435b4ccd 00000003 dbc3e17b dbc3e17b dbc3e17b +(86/100)*255 435b4ccd fffffffd a5c3db7b a5c3db7b a5c3db7b +(86/100)*255 435b4ccd fffffffc a5c3e1db a5c3e1db a5c3e1db +(86/100)*255 435b4ccd 80000002 a5dbe17b a5dbe17b a5dbe17b +(86/100)*255 435b4ccd 00000103 dbc3e17b dbc3e17b dbc3e17b +(87/100)*255 435dd99a 00000000 a5c3e1de a5c3e1dd a5c3e1de +(87/100)*255 435dd99a 00000001 a5c3de7b a5c3dd7b a5c3de7b +(87/100)*255 435dd99a 00000002 a5dee17b a5dde17b a5dee17b +(87/100)*255 435dd99a 00000003 dec3e17b ddc3e17b dec3e17b +(87/100)*255 435dd99a fffffffd a5c3de7b a5c3dd7b a5c3de7b +(87/100)*255 435dd99a fffffffc a5c3e1de a5c3e1dd a5c3e1de +(87/100)*255 435dd99a 80000002 a5dee17b a5dde17b a5dee17b +(87/100)*255 435dd99a 00000103 dec3e17b ddc3e17b dec3e17b +(88/100)*255 43606666 00000000 a5c3e1e0 a5c3e1e0 a5c3e1e0 +(88/100)*255 43606666 00000001 a5c3e07b a5c3e07b a5c3e07b +(88/100)*255 43606666 00000002 a5e0e17b a5e0e17b a5e0e17b +(88/100)*255 43606666 00000003 e0c3e17b e0c3e17b e0c3e17b +(88/100)*255 43606666 fffffffd a5c3e07b a5c3e07b a5c3e07b +(88/100)*255 43606666 fffffffc a5c3e1e0 a5c3e1e0 a5c3e1e0 +(88/100)*255 43606666 80000002 a5e0e17b a5e0e17b a5e0e17b +(88/100)*255 43606666 00000103 e0c3e17b e0c3e17b e0c3e17b +(89/100)*255 4362f333 00000000 a5c3e1e3 a5c3e1e2 a5c3e1e3 +(89/100)*255 4362f333 00000001 a5c3e37b a5c3e27b a5c3e37b +(89/100)*255 4362f333 00000002 a5e3e17b a5e2e17b a5e3e17b +(89/100)*255 4362f333 00000003 e3c3e17b e2c3e17b e3c3e17b +(89/100)*255 4362f333 fffffffd a5c3e37b a5c3e27b a5c3e37b +(89/100)*255 4362f333 fffffffc a5c3e1e3 a5c3e1e2 a5c3e1e3 +(89/100)*255 4362f333 80000002 a5e3e17b a5e2e17b a5e3e17b +(89/100)*255 4362f333 00000103 e3c3e17b e2c3e17b e3c3e17b +(90/100)*255 43658000 00000000 a5c3e1e6 a5c3e1e5 a5c3e1e6 +(90/100)*255 43658000 00000001 a5c3e67b a5c3e57b a5c3e67b +(90/100)*255 43658000 00000002 a5e6e17b a5e5e17b a5e6e17b +(90/100)*255 43658000 00000003 e6c3e17b e5c3e17b e6c3e17b +(90/100)*255 43658000 fffffffd a5c3e67b a5c3e57b a5c3e67b +(90/100)*255 43658000 fffffffc a5c3e1e6 a5c3e1e5 a5c3e1e6 +(90/100)*255 43658000 80000002 a5e6e17b a5e5e17b a5e6e17b +(90/100)*255 43658000 00000103 e6c3e17b e5c3e17b e6c3e17b +(91/100)*255 43680ccd 00000000 a5c3e1e8 a5c3e1e8 a5c3e1e8 +(91/100)*255 43680ccd 00000001 a5c3e87b a5c3e87b a5c3e87b +(91/100)*255 43680ccd 00000002 a5e8e17b a5e8e17b a5e8e17b +(91/100)*255 43680ccd 00000003 e8c3e17b e8c3e17b e8c3e17b +(91/100)*255 43680ccd fffffffd a5c3e87b a5c3e87b a5c3e87b +(91/100)*255 43680ccd fffffffc a5c3e1e8 a5c3e1e8 a5c3e1e8 +(91/100)*255 43680ccd 80000002 a5e8e17b a5e8e17b a5e8e17b +(91/100)*255 43680ccd 00000103 e8c3e17b e8c3e17b e8c3e17b +(92/100)*255 436a999a 00000000 a5c3e1eb a5c3e1ea a5c3e1eb +(92/100)*255 436a999a 00000001 a5c3eb7b a5c3ea7b a5c3eb7b +(92/100)*255 436a999a 00000002 a5ebe17b a5eae17b a5ebe17b +(92/100)*255 436a999a 00000003 ebc3e17b eac3e17b ebc3e17b +(92/100)*255 436a999a fffffffd a5c3eb7b a5c3ea7b a5c3eb7b +(92/100)*255 436a999a fffffffc a5c3e1eb a5c3e1ea a5c3e1eb +(92/100)*255 436a999a 80000002 a5ebe17b a5eae17b a5ebe17b +(92/100)*255 436a999a 00000103 ebc3e17b eac3e17b ebc3e17b +(93/100)*255 436d2667 00000000 a5c3e1ed a5c3e1ed a5c3e1ed +(93/100)*255 436d2667 00000001 a5c3ed7b a5c3ed7b a5c3ed7b +(93/100)*255 436d2667 00000002 a5ede17b a5ede17b a5ede17b +(93/100)*255 436d2667 00000003 edc3e17b edc3e17b edc3e17b +(93/100)*255 436d2667 fffffffd a5c3ed7b a5c3ed7b a5c3ed7b +(93/100)*255 436d2667 fffffffc a5c3e1ed a5c3e1ed a5c3e1ed +(93/100)*255 436d2667 80000002 a5ede17b a5ede17b a5ede17b +(93/100)*255 436d2667 00000103 edc3e17b edc3e17b edc3e17b +(94/100)*255 436fb333 00000000 a5c3e1f0 a5c3e1ef a5c3e1f0 +(94/100)*255 436fb333 00000001 a5c3f07b a5c3ef7b a5c3f07b +(94/100)*255 436fb333 00000002 a5f0e17b a5efe17b a5f0e17b +(94/100)*255 436fb333 00000003 f0c3e17b efc3e17b f0c3e17b +(94/100)*255 436fb333 fffffffd a5c3f07b a5c3ef7b a5c3f07b +(94/100)*255 436fb333 fffffffc a5c3e1f0 a5c3e1ef a5c3e1f0 +(94/100)*255 436fb333 80000002 a5f0e17b a5efe17b a5f0e17b +(94/100)*255 436fb333 00000103 f0c3e17b efc3e17b f0c3e17b +(95/100)*255 43724000 00000000 a5c3e1f2 a5c3e1f2 a5c3e1f2 +(95/100)*255 43724000 00000001 a5c3f27b a5c3f27b a5c3f27b +(95/100)*255 43724000 00000002 a5f2e17b a5f2e17b a5f2e17b +(95/100)*255 43724000 00000003 f2c3e17b f2c3e17b f2c3e17b +(95/100)*255 43724000 fffffffd a5c3f27b a5c3f27b a5c3f27b +(95/100)*255 43724000 fffffffc a5c3e1f2 a5c3e1f2 a5c3e1f2 +(95/100)*255 43724000 80000002 a5f2e17b a5f2e17b a5f2e17b +(95/100)*255 43724000 00000103 f2c3e17b f2c3e17b f2c3e17b +(96/100)*255 4374cccc 00000000 a5c3e1f5 a5c3e1f4 a5c3e1f5 +(96/100)*255 4374cccc 00000001 a5c3f57b a5c3f47b a5c3f57b +(96/100)*255 4374cccc 00000002 a5f5e17b a5f4e17b a5f5e17b +(96/100)*255 4374cccc 00000003 f5c3e17b f4c3e17b f5c3e17b +(96/100)*255 4374cccc fffffffd a5c3f57b a5c3f47b a5c3f57b +(96/100)*255 4374cccc fffffffc a5c3e1f5 a5c3e1f4 a5c3e1f5 +(96/100)*255 4374cccc 80000002 a5f5e17b a5f4e17b a5f5e17b +(96/100)*255 4374cccc 00000103 f5c3e17b f4c3e17b f5c3e17b +(97/100)*255 4377599a 00000000 a5c3e1f7 a5c3e1f7 a5c3e1f7 +(97/100)*255 4377599a 00000001 a5c3f77b a5c3f77b a5c3f77b +(97/100)*255 4377599a 00000002 a5f7e17b a5f7e17b a5f7e17b +(97/100)*255 4377599a 00000003 f7c3e17b f7c3e17b f7c3e17b +(97/100)*255 4377599a fffffffd a5c3f77b a5c3f77b a5c3f77b +(97/100)*255 4377599a fffffffc a5c3e1f7 a5c3e1f7 a5c3e1f7 +(97/100)*255 4377599a 80000002 a5f7e17b a5f7e17b a5f7e17b +(97/100)*255 4377599a 00000103 f7c3e17b f7c3e17b f7c3e17b +(98/100)*255 4379e667 00000000 a5c3e1fa a5c3e1f9 a5c3e1fa +(98/100)*255 4379e667 00000001 a5c3fa7b a5c3f97b a5c3fa7b +(98/100)*255 4379e667 00000002 a5fae17b a5f9e17b a5fae17b +(98/100)*255 4379e667 00000003 fac3e17b f9c3e17b fac3e17b +(98/100)*255 4379e667 fffffffd a5c3fa7b a5c3f97b a5c3fa7b +(98/100)*255 4379e667 fffffffc a5c3e1fa a5c3e1f9 a5c3e1fa +(98/100)*255 4379e667 80000002 a5fae17b a5f9e17b a5fae17b +(98/100)*255 4379e667 00000103 fac3e17b f9c3e17b fac3e17b +(99/100)*255 437c7333 00000000 a5c3e1fc a5c3e1fc a5c3e1fc +(99/100)*255 437c7333 00000001 a5c3fc7b a5c3fc7b a5c3fc7b +(99/100)*255 437c7333 00000002 a5fce17b a5fce17b a5fce17b +(99/100)*255 437c7333 00000003 fcc3e17b fcc3e17b fcc3e17b +(99/100)*255 437c7333 fffffffd a5c3fc7b a5c3fc7b a5c3fc7b +(99/100)*255 437c7333 fffffffc a5c3e1fc a5c3e1fc a5c3e1fc +(99/100)*255 437c7333 80000002 a5fce17b a5fce17b a5fce17b +(99/100)*255 437c7333 00000103 fcc3e17b fcc3e17b fcc3e17b diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index e1b2a943a..9d75bc94a 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0xb1d4a12271e064e1 # compute_key of the parts above +KEY = 0x9f56f9821d4b83e0 # compute_key of the parts above def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-14cs': + for b in b'x2w-startup-shader-15cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack('= 255.0 else round(x) # Python round() is half to even + + def cvt_pk_u8(s0, s1, s2): shift = 8 * (s1 & 3) - return (s2 & ~(0xff << shift) & MASK) | ((int(struct.unpack(' 0.0' not in line) + check('guard on an SGPR', '((s4 - 1u) < 0x7f800000u)' in emitted('v_cvt_pk_u8_f32 v12, s4, v4, v8')) + check('guard on a constant', '((0x3f800000u - 1u) < 0x7f800000u)' in emitted('v_cvt_pk_u8_f32 v12, 1.0, v4, v8')) + for bits in (0x00000001, 0x007fffff, 0x7f800000): # smallest subnormal, largest subnormal, +inf pass the guard + check('guard open at %08x' % bits, ((bits - 1) & 0xffffffff) < 0x7f800000) + for bits in (0, 0x80000000, 0x80000001, 0xff800000, 0x7f800001, 0x7fc00000, 0xffffffff): + check('guard shut at %08x' % bits, not ((bits - 1) & 0xffffffff) < 0x7f800000) + check('a changed lowering text is reported, not a SyntaxError', + 'cannot parse' in (lambda: [str(e) for e in [catch(lambda: evaluate(line.replace('255.0', '255.0) ?'), {'v0': 0}))]][0])()) + + +STORED = Path(__file__).resolve().parent / 'data' / 'rdna_cvt_pk_u8_measured.tsv' + + +def trunc_byte(bits): + """Model of the round-toward-zero variant: truncate, saturate, NaN and negatives give 0.""" + x = as_float(bits) + if math.isnan(x) or x <= 0.0: + return 0 + return 255 if x >= 255.0 else math.trunc(x) + + +def merge_byte(byte, select, s2=SENTINEL): + shift = 8 * (select & 3) + return (s2 & ~(0xff << shift) & MASK) | (byte << shift) + + +def stored_data_controls(): + # Every row of the stored hardware output (no GPU needed): default = nearest even, rtz = truncation, flush = default. + text = STORED.read_text().splitlines() + check('stored file names both devices and the sentinel', + '# sentinel (S2) a5c3e17b' in text and sum(l.startswith('# device gfx1030') for l in text) == 1 + and sum(l.startswith('# device gfx1036') for l in text) == 1) + rows = [l.split('\t') for l in text if not l.startswith('#')] + check('stored file has 5432 rows of 6 fields', len(rows) == 5432 and all(len(r) == 6 for r in rows)) + check('stored rows are distinct', len({tuple(r[1:3]) for r in rows}) == len(rows)) + parsed = [(int(r[1], 16), int(r[2], 16), int(r[3], 16), int(r[4], 16), int(r[5], 16)) for r in rows] + check('all four byte selects are stored', {sel & 3 for _, sel, _, _, _ in parsed} == {0, 1, 2, 3}) + bad = [(i, rows[i][0]) for i, (bits, sel, d, _, _) in enumerate(parsed) if d != cvt_pk_u8(bits, sel, SENTINEL)] + check('stored default words equal the nearest-even model: %s' % bad[:3], not bad) + bad = [(i, rows[i][0]) for i, (bits, sel, _, z, _) in enumerate(parsed) if z != merge_byte(trunc_byte(bits), sel)] + check('stored rtz words equal the truncation model: %s' % bad[:3], not bad) + bad = [i for i, (_, _, d, _, f) in enumerate(parsed) if d != f] + check('stored flush words equal the default words', not bad) + # Negative controls: other conversions must disagree with stored rows, and each variant with the other model. + miss = lambda column, byte: sum(r[column] != merge_byte(byte(r[0]), r[1]) for r in parsed) + check('truncation disagrees with stored default words', miss(2, trunc_byte) > 1000) + check('nearest even disagrees with stored rtz words', miss(3, to_byte) > 1000) + check('round half away disagrees with stored default words', + miss(2, lambda b: 0 if math.isnan(as_float(b)) or as_float(b) <= 0.0 else half_away(min(as_float(b), 255.0))) > 0) + check('a wrap to 8 bits without saturation disagrees with stored default words', + miss(2, lambda b: 0 if math.isnan(as_float(b)) or as_float(b) <= 0.0 else + (round(min(as_float(b), 1e9)) & 0xff)) > 0) + # The stored select words reach the model unchanged: a model that drops select bit 0 must fail. + check('a model without select bit 0 disagrees', any( + d != merge_byte(to_byte(bits), sel & 2) for bits, sel, d, _, _ in parsed)) + # Through the translated text, every stored default word. + line = emitted('v_cvt_pk_u8_f32 v12, v0, v4, v8') + check('translated text reproduces every stored default word', + all(evaluate(line, {'v0': bits, 'v4': sel, 'v8': SENTINEL}) == d for bits, sel, d, _, _ in parsed)) def selector_controls(): @@ -117,54 +385,31 @@ def selector_controls(): check('overwritten S2 is detected', any(dropped_src2(a, b, c) != cvt_pk_u8(a, b, c) for a, b, c in DRAW_SETS)) check('all four selectors drawn', {s1 & 3 for _, s1, _ in DRAW_SETS} == {0, 1, 2, 3}) - # The reference itself, worked by hand: byte 2 of 0x11223344 replaced by 0xff. + # The reference itself, worked by hand: byte 2 of 0x11223344 replaced by 0xff, and a tie to the even byte. check('hand-worked word', cvt_pk_u8(f32(255.0), 2, 0x11223344) == 0x11ff3344) + check('hand-worked ties', [to_byte(f32(x)) for x in (0.5, 1.5, 2.5, 254.5, 255.5)] == [0, 2, 2, 254, 255]) shifted_high = evaluate(line, {'v0': f32(9.0), 'v4': 0x100, 'v8': 0x01020304}) check('S1 bits above [1:0] are ignored', shifted_high == evaluate(line, {'v0': f32(9.0), 'v4': 0, 'v8': 0x01020304})) def run_controls(): selector_controls() - check('constant inside the set is lowered', 'F(0x3f800000u)' in emitted('v_cvt_pk_u8_f32 v1, 1.0, v3, v4')) + measured_controls() + stored_data_controls() + check('constant is lowered', 'F(0x3f800000u)' in emitted('v_cvt_pk_u8_f32 v1, 1.0, v3, v4')) check('S1 and S2 constants are lowered', not refused('v_cvt_pk_u8_f32 v1, 1.0, 7, 0xffffffff')) - contract_controls() - - -def contract_controls(): - pk = 'v_cvt_pk_u8_f32 v1, v2, v3, v4' - # An unproven register S0 is refused in ordinary translation, with a message naming the register. - for asm in (pk, 'v_cvt_pk_u8_f32_e64 v1, v2, 3, s4', 'v_cvt_pk_u8_f32 v1, s2, v3, v4'): - check('unproven S0 refused without the contract: ' + asm, refuses([asm]) is not None) - check('refusal message', refuses([pk]) == 'v_cvt_pk_u8_f32 source v2 is not proven to be +0.0 or an integer in 1..255') - # The same words translate when the contract is selected, and the note records it. - probe = run([pk, 'v_cvt_pk_u8_f32_e64 v1, v2, 3, s4'], True) - check('unproven S0 accepted with the contract', len(probe.lines) == 2 and 'clamp(F(v2)' in probe.lines[0]) - check('the contract is recorded in the notes', any('pk_u8_s0_contract' in n for n in probe.pipe.notes)) - check('no note without a contract use', not run(['v_cvt_pk_u8_f32 v1, 1.0, v3, v4'], True).pipe.notes) - # Proven forms, each of the four bytes, need no contract. - for n in range(4): - cvt = 'v_cvt_f32_ubyte%d v2, v5' % n - check('ubyte%d result is proven' % n, refuses([cvt, pk]) is None) - check('ubyte%d result by the e64 spelling is proven' % n, refuses(['v_cvt_f32_ubyte%d_e64 v2, v5' % n, pk]) is None) - # Anything that writes the register afterwards, or a different register, is unproven again. - for label, lines in (('a float multiply', ['v_cvt_f32_ubyte0 v2, v5', 'v_mul_f32 v2, v2, v6', pk]), - ('a computed register', ['v_mul_f32 v2, v5, v6', pk]), - ('a move', ['v_cvt_f32_ubyte0 v2, v5', 'v_mov_b32 v2, v7', pk]), - ('another register', ['v_cvt_f32_ubyte0 v8, v5', pk]), - ('a saturating conversion', ['v_cvt_f32_ubyte0 v2, v5 clamp', pk]), - ('a scaled conversion', ['v_cvt_f32_ubyte0 v2, v5 mul:2', pk]), - ('an integer conversion', ['v_cvt_f32_u32 v2, v5', pk])): - check('%s is refused without the contract' % label, refuses(lines) is not None) - check('%s is accepted with the contract' % label, refuses(lines, True) is None) - # The proof needs straight-line code and the entry exec mask. - probe = make_probe() - probe.has_branches = True - probe.one('v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte0 v2, v5') - check('no proof in a program with branches', 2 not in getattr(probe, 'byte_float_v', ())) - probe = make_probe() - probe.exec_known = False - probe.one('v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte0 v2, v5') - check('no proof under a partial exec mask', 2 not in getattr(probe, 'byte_float_v', ())) + check('a register S0 needs no proof', refuses(['v_mul_f32 v2, v5, v6', 'v_cvt_pk_u8_f32 v1, v2, v3, v4']) is None) + # MODE writes that leave bits 1:0 alone stay accepted (the scratch base setup, the f16/f64 rounding field). + for asm in ('s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO), 0', 's_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3', + 's_setreg_imm32_b32 hwreg(HW_REG_MODE), 0xf0', 's_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 0'): + check('accepted: ' + asm, refuses([asm]) is None) + # An inline constant the disassembler prints as a float is read as its binary32 bits (1.0 is 0x3f800000). + for asm in ('s_setreg_imm32_b32 hwreg(HW_REG_MODE), 1.0', 's_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 0.5'): + check('accepted: ' + asm, refuses([asm]) is None) + reason = refuses(['s_setreg_imm32_b32 hwreg(HW_REG_MODE), 1.0e-45']) # bits 0x00000001 + check('float literal with MODE[1:0] set is a MODE write', reason is not None and 'writes the binary32 rounding mode' in reason) + reason = refuses(['s_setreg_imm32_b32 hwreg(HW_REG_MODE), foo']) + check('undecodable immediate says so', reason is not None and 'immediate not decoded' in reason) if __name__ == '__main__': diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index a8d4dbb05..c0d23090c 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -295,7 +295,7 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-14"; + constexpr char revision[] = "x2w-startup-shader-15"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 756a9015f..5270131e8 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -371,7 +371,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-14"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-15"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tools/rdna_cvt_pk_u8.py b/tools/rdna_cvt_pk_u8.py new file mode 100644 index 000000000..d7dccdc75 --- /dev/null +++ b/tools/rdna_cvt_pk_u8.py @@ -0,0 +1,615 @@ +#!/usr/bin/env python3 +"""Probe of v_cvt_pk_u8_f32 (VOP3A opcode 350) on RDNA 2/3 hardware. + +The RDNA ISA guides give D = (S2 & ~(0xff << 8*S1[1:0])) | ((flt32_to_uint8(S0) & 0xff) << 8*S1[1:0]) +but leave flt32_to_uint8 undefined (rounding, clamping, NaN). This tool builds small HSA kernels that run +the instruction on a table of inputs, launches them through HIP (ctypes only) and compares the readback with +independent candidate models. + +Usage: + python3 tools/rdna_cvt_pk_u8.py run on the first HIP device (every device is listed); writes + out/rdna_cvt_pk_u8.tsv and compares it with the stored rows + ... --device 1 HIP device 1 (e.g. the discrete card when an iGPU is device 0) + ... --arch gfx1032 override the target (default: from the device) + ... --asm-only --arch gfx1030 --keep DIR build only (no GPU needed) + ... --build asm hand-written assembly (llvm-mc + ld.lld) instead of clang + ... --self-test check the models and the merge logic (no GPU needed) + ... --out FILE / --compare FILE / --json FILE result file, reference to compare with, optional verbose JSON +Python 3 standard library only; needs clang (ROCm / HIP SDK ship it); --build asm needs llvm-mc and ld.lld. + +Stored result: tests/data/rdna_cvt_pk_u8_measured.tsv (see "Measured on RDNA 2" in docs/experiments.md). +The result file is compact: header lines starting with '#', then one tab separated row per (input, select): +label, input word, select word, then the output word of the default, rtz and flush variants. +A rerun is comparable with the stored file when the rows (lines not starting with '#') are equal; the +probe prints that verdict itself. +""" +import argparse +import ctypes +import json +import math +import os +import re +import shutil +import struct +import subprocess +import sys +import tempfile + +SENTINEL = 0xA5C3E17B +SELECTS = [0, 1, 2, 3, 0xFFFFFFFD, 0xFFFFFFFC, 0x80000002, 0x00000103] +BLOCK = 64 +DEFAULT_REFERENCE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'tests', 'data', + 'rdna_cvt_pk_u8_measured.tsv') + +# name -> (description, mode lines executed before the conversion) +VARIANTS = { + 'default': ('MODE left at the launch default', []), + # s_round_mode simm4: [1:0] f32 rounding, [3:2] f64/f16; 3 = toward zero. + 'rtz': ('s_round_mode 0xf (round toward zero)', ['s_round_mode 0xf']), + # s_denorm_mode simm4: [0] f32 input denormals, [1] f32 output denormals, [3:2] f64/f16; 0 = flush. + 'flush': ('s_denorm_mode 0 (denormals flushed)', ['s_denorm_mode 0']), +} + + +# ---------------------------------------------------------------- inputs + +def f32(x): + return struct.unpack(' 255 else n + + +def _is_nan(x): + return x != x + + +def model_rne_sat(x): + if _is_nan(x): + return 0 + if math.isinf(x): + return 255 if x > 0 else 0 + return _sat(int(round(x))) # Python round() is half-to-even on floats + + +def model_trunc_sat(x): + if _is_nan(x): + return 0 + if math.isinf(x): + return 255 if x > 0 else 0 + return _sat(int(x)) + + +def model_half_away_sat(x): + if _is_nan(x): + return 0 + if math.isinf(x): + return 255 if x > 0 else 0 + f = math.floor(abs(x)) + if abs(x) - f >= 0.5: + f += 1 + return _sat(int(math.copysign(f, x))) + + +def model_trunc_wrap(x): + # No saturation: low 8 bits of the truncated integer; NaN and infinities give 0 (arbitrary choice). + if _is_nan(x) or math.isinf(x): + return 0 + return int(x) & 0xFF + + +MODELS = { + 'rne_sat_nan0': model_rne_sat, + 'trunc_sat_nan0': model_trunc_sat, + 'half_away_sat_nan0': model_half_away_sat, + 'trunc_wrap8': model_trunc_wrap, +} + + +def merge(byte, sel, s2=SENTINEL): + sh = 8 * (sel & 3) + return ((s2 & ~(0xFF << sh)) | ((byte & 0xFF) << sh)) & 0xFFFFFFFF + + +def model_word(model, in_bits, sel): + return merge(MODELS[model](val(in_bits)), sel) + + +def extract_byte(word, sel): + return (word >> (8 * (sel & 3))) & 0xFF + + +def merge_ok(word, sel): + """The bytes other than the selected one must equal S2's.""" + mask = ~(0xFF << (8 * (sel & 3))) & 0xFFFFFFFF + return (word & mask) == (SENTINEL & mask) + + +# ---------------------------------------------------------------- assembly + +def gen_asm(arch, variant, cov=5): + name = 'cvt_pk_u8_' + variant + mode = '\n'.join(' ' + l for l in VARIANTS[variant][1]) + if mode: + mode += '\n s_nop 0' + meta_ver = '[1, 2]' if cov >= 5 else '[1, 1]' + return f""".amdgcn_target "amdgcn-amd-amdhsa--{arch}" +.amdhsa_code_object_version {cov} +.text +.globl {name} +.p2align 8 +.type {name},@function +{name}: + ; kernarg: in (u64 pairs of {{f32 word, select word}}), out (u64), n (u32) + s_load_dwordx2 s[4:5], s[0:1], 0x0 + s_load_dwordx2 s[6:7], s[0:1], 0x8 + s_load_dword s8, s[0:1], 0x10 + s_waitcnt lgkmcnt(0) + s_lshl_b32 s9, s2, 6 + v_add_nc_u32 v1, s9, v0 + v_cmp_gt_u32 vcc_lo, s8, v1 + s_and_saveexec_b32 s10, vcc_lo + s_cbranch_execz .Ldone_{variant} + v_lshlrev_b32 v2, 3, v1 + global_load_dwordx2 v[3:4], v2, s[4:5] + s_waitcnt vmcnt(0) +{mode} + v_mov_b32 v5, 0x{SENTINEL:08x} + v_cvt_pk_u8_f32 v6, v3, v4, v5 + v_lshlrev_b32 v7, 2, v1 + global_store_dword v7, v6, s[6:7] +.Ldone_{variant}: + s_endpgm +.Lend_{variant}: +.size {name}, .Lend_{variant}-{name} + +.rodata +.p2align 6 +.amdhsa_kernel {name} + .amdhsa_user_sgpr_kernarg_segment_ptr 1 + .amdhsa_system_sgpr_workgroup_id_x 1 + .amdhsa_system_vgpr_workitem_id 0 + .amdhsa_next_free_vgpr 8 + .amdhsa_next_free_sgpr 16 + .amdhsa_wavefront_size32 1 +.end_amdhsa_kernel + +.amdgpu_metadata +--- +amdhsa.version: {meta_ver} +amdhsa.target: amdgcn-amd-amdhsa--{arch} +amdhsa.kernels: + - .name: {name} + .symbol: {name}.kd + .language: Assembler + .kernarg_segment_size: 24 + .kernarg_segment_align: 8 + .group_segment_fixed_size: 0 + .private_segment_fixed_size: 0 + .sgpr_count: 16 + .vgpr_count: 8 + .max_flat_workgroup_size: {BLOCK} + .wavefront_size: 32 + .args: + - {{.name: in, .offset: 0, .size: 8, .value_kind: global_buffer, .address_space: global}} + - {{.name: out, .offset: 8, .size: 8, .value_kind: global_buffer, .address_space: global}} + - {{.name: n, .offset: 16, .size: 4, .value_kind: by_value}} +... +.end_amdgpu_metadata +""" + + +def gen_hip(arch, variant): + """Device-only HIP source: the compiler emits the code object metadata, only the asm block is ours.""" + name = 'cvt_pk_u8_' + variant + mode = ''.join(l + '\\n\\t' for l in VARIANTS[variant][1]) + if mode: + mode += 's_nop 0\\n\\t' + return f"""// target {arch}; no HIP headers needed (-nogpuinc -nogpulib) +extern "C" __attribute__((global)) __attribute__((amdgpu_flat_work_group_size(1, {BLOCK}))) +void {name}(const unsigned* in, unsigned* out, unsigned n) {{ + unsigned i = __builtin_amdgcn_workgroup_id_x() * {BLOCK}u + __builtin_amdgcn_workitem_id_x(); + if (i >= n) return; + unsigned x = in[2 * i], sel = in[2 * i + 1], d; + asm volatile("{mode}v_cvt_pk_u8_f32 %0, %1, %2, %3" + : "=v"(d) : "v"(x), "v"(sel), "v"(0x{SENTINEL:08x}u)); + out[i] = d; +}} +""" + + +def find_tool(names, override=None): + if override: + return override + dirs = [None] + for env in ('ROCM_PATH', 'HIP_PATH'): + if os.environ.get(env): + dirs += [os.path.join(os.environ[env], 'llvm', 'bin'), os.path.join(os.environ[env], 'bin')] + dirs += ['/opt/rocm/llvm/bin', '/opt/rocm/bin'] + for d in dirs: + for n in names: + p = shutil.which(n) if d is None else shutil.which(n, path=d) + if p: + return p + sys.exit('error: none of %s found (install ROCm / the HIP SDK or pass --clang / --llvm-mc / --lld)' % ', '.join(names)) + + +def run(cmd): + r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + if r.returncode: + sys.exit('error: %s failed (%d):\n%s' % (' '.join(cmd), r.returncode, r.stdout)) + return r.stdout + + +def build(arch, variant, workdir, args): + base = os.path.join(workdir, '%s_%s' % (variant, arch)) + if args.build == 'asm': + mc = find_tool(['llvm-mc', 'llvm-mc.exe'], args.llvm_mc) + lld = find_tool(['ld.lld', 'ld.lld.exe', 'lld'], args.lld) + with open(base + '.s', 'w') as f: + f.write(gen_asm(arch, variant, args.cov)) + run([mc, '-triple=amdgcn-amd-amdhsa', '-mcpu=' + arch, '-filetype=obj', '-o', base + '.o', base + '.s']) + run([lld, '-shared', '-o', base + '.hsaco', base + '.o']) + else: + clang = find_tool(['clang', 'clang.exe', 'clang++', 'clang++.exe'], args.clang) + with open(base + '.hip', 'w') as f: + f.write(gen_hip(arch, variant)) + run([clang, '-x', 'hip', '--cuda-device-only', '--offload-arch=' + arch, '-nogpuinc', '-nogpulib', + '-O1', '--no-gpu-bundle-output', '-o', base + '.hsaco', base + '.hip']) + with open(base + '.hsaco', 'rb') as f: + return f.read(), base + '.hsaco' + + +# ---------------------------------------------------------------- HIP + +class Hip: + def __init__(self): + names = ['amdhip64_7.dll', 'amdhip64_6.dll', 'amdhip64.dll'] \ + if os.name == 'nt' else ['libamdhip64.so', 'libamdhip64.so.7', 'libamdhip64.so.6', 'libamdhip64.so.5'] + dirs = [''] + for env in ('HIP_PATH', 'ROCM_PATH'): + if os.environ.get(env): + dirs.append(os.path.join(os.environ[env], 'bin' if os.name == 'nt' else 'lib')) + if os.name != 'nt': + dirs.append('/opt/rocm/lib') + self.lib, err = None, [] + for d in dirs: + for n in names: + try: + self.lib = ctypes.CDLL(os.path.join(d, n) if d else n) + break + except OSError as e: + err.append(str(e)) + if self.lib: + break + if not self.lib: + raise RuntimeError('cannot load the HIP runtime (%s); tried: %s' % (names, '; '.join(err[-3:]))) + self.lib.hipGetErrorString.restype = ctypes.c_char_p + self.lib.hipGetErrorString.argtypes = [ctypes.c_int] + + def check(self, code, what): + if code != 0: + raise RuntimeError('%s failed: HIP error %d (%s)' % ( + what, code, (self.lib.hipGetErrorString(code) or b'?').decode())) + + def call(self, fn, *a): + self.check(getattr(self.lib, fn)(*a), fn) + + device = 0 + + def count(self): + self.call('hipInit', 0) + n = ctypes.c_int() + self.call('hipGetDeviceCount', ctypes.byref(n)) + return n.value + + def arch(self, device=None): + """gcnArchName without relying on the struct layout: scan the property block for 'gfxNNNN'.""" + self.call('hipInit', 0) + buf = ctypes.create_string_buffer(16384) + fn = 'hipGetDevicePropertiesR0600' if hasattr(self.lib, 'hipGetDevicePropertiesR0600') \ + else 'hipGetDeviceProperties' + self.call(fn, buf, self.device if device is None else device) + m = re.search(rb'gfx[0-9a-f]{3,4}', buf.raw) + if not m: + raise RuntimeError('gcnArchName not found in the device properties; pass --arch') + return m.group(0).decode() + + def run_kernel(self, hsaco, kname, words): + """words: list of (in_bits, sel). Returns the list of output words.""" + lib, n = self.lib, len(words) + self.call('hipSetDevice', self.device) + mod, fn = ctypes.c_void_p(), ctypes.c_void_p() + img = ctypes.create_string_buffer(hsaco, len(hsaco)) + self.call('hipModuleLoadData', ctypes.byref(mod), img) + self.call('hipModuleGetFunction', ctypes.byref(fn), mod, kname.encode()) + din, dout = ctypes.c_void_p(), ctypes.c_void_p() + self.call('hipMalloc', ctypes.byref(din), ctypes.c_size_t(8 * n)) + self.call('hipMalloc', ctypes.byref(dout), ctypes.c_size_t(4 * n)) + host = (ctypes.c_uint32 * (2 * n))(*[w for pair in words for w in pair]) + self.call('hipMemcpy', din, host, ctypes.c_size_t(8 * n), 1) # hipMemcpyHostToDevice + zero = (ctypes.c_uint32 * n)() + self.call('hipMemcpy', dout, zero, ctypes.c_size_t(4 * n), 1) + a_in, a_out, a_n = ctypes.c_void_p(din.value), ctypes.c_void_p(dout.value), ctypes.c_uint32(n) + params = (ctypes.c_void_p * 3)(ctypes.addressof(a_in), ctypes.addressof(a_out), ctypes.addressof(a_n)) + blocks = (n + BLOCK - 1) // BLOCK + self.call('hipModuleLaunchKernel', fn, blocks, 1, 1, BLOCK, 1, 1, 0, None, params, None) + self.call('hipDeviceSynchronize') + res = (ctypes.c_uint32 * n)() + self.call('hipMemcpy', res, dout, ctypes.c_size_t(4 * n), 2) # hipMemcpyDeviceToHost + out = list(res) + self.call('hipFree', din) + self.call('hipFree', dout) + self.call('hipModuleUnload', mod) + return out + + +# ---------------------------------------------------------------- reporting + +def analyse(rows, results, show): + """results: variant -> list of words. Returns per-variant summary dict.""" + summary = {} + for var, words in results.items(): + info = {'merge_ok_rows': sum(merge_ok(w, r[2]) for w, r in zip(words, rows)), 'rows': len(rows), 'models': {}} + for m in MODELS: + bad = [i for i, (w, r) in enumerate(zip(words, rows)) if w != model_word(m, r[1], r[2])] + info['models'][m] = {'mismatches': len(bad), 'first': bad[:show]} + info['matching_models'] = [m for m, v in info['models'].items() if v['mismatches'] == 0] + summary[var] = info + return summary + + +def fmt_row(rows, words, i): + lab, b, s = rows[i] + return 'in=%08x (%s) sel=%08x -> hw=%08x' % (b, lab, s, words[i]) + + +def print_report(rows, results, summary, arch, show): + print('\n== device/arch: %s, %d rows (%d inputs x %d selects) ==' % (arch, len(rows), len(rows) // len(SELECTS), + len(SELECTS))) + for var, info in summary.items(): + print('\n-- variant %s: %s' % (var, VARIANTS[var][0])) + print(' S2 merge (other bytes == sentinel): %d/%d rows' % (info['merge_ok_rows'], info['rows'])) + for m, v in info['models'].items(): + print(' model %-20s mismatches %5d/%d %s' % (m, v['mismatches'], info['rows'], + 'MATCH' if v['mismatches'] == 0 else '')) + print(' models matching all rows: %s' % (info['matching_models'] or 'none')) + for m, v in info['models'].items(): + if v['mismatches']: + print(' first mismatches vs %s:' % m) + for i in v['first']: + print(' %s model=%08x' % (fmt_row(rows, results[var], i), model_word(m, rows[i][1], rows[i][2]))) + # compact table: select 0 only, byte value per variant and per model + print('\n-- compact table (sel=0, selected byte): input | %s | %s' % ( + ' '.join('%-7s' % v for v in results), ' '.join(m.split('_')[0][:7].ljust(7) for m in MODELS))) + shown = 0 + for i, (lab, b, s) in enumerate(rows): + if s != 0: + continue + hw = ['%7d' % (results[v][i] & 0xFF) for v in results] + md = ['%7d' % MODELS[m](val(b)) for m in MODELS] + flag = '' if len({results[v][i] & 0xFF for v in results} | {MODELS['rne_sat_nan0'](val(b))}) == 1 else ' *' + if lab.startswith('(') and not flag and shown > 60: + continue + shown += 1 + print('%-22s %08x | %s | %s%s' % (lab[:22], b, ' '.join(hw), ' '.join(md), flag)) + print('(* = a variant disagrees with the RNE model; (x/y)*255 rows are elided when all agree)') + + +# ---------------------------------------------------------------- self test + +def self_test(): + ok = True + + def check(name, got, want): + nonlocal ok + if got != want: + ok = False + print('FAIL %s: got %r want %r' % (name, got, want)) + + b = lambda x: bits(x) + # worked rows: (value, rne, trunc, half-away, wrap) + table = [ + (2.5, 2, 2, 3, 2), (1.5, 2, 1, 2, 1), (0.5, 0, 0, 1, 0), (127.5, 128, 127, 128, 127), + (254.5, 254, 254, 255, 254), (255.5, 255, 255, 255, 255), (256.0, 255, 255, 255, 0), + (-0.4, 0, 0, 0, 0), (-0.5, 0, 0, 0, 0), (-1.0, 0, 0, 0, 255), (-255.0, 0, 0, 0, 1), + (255.4, 255, 255, 255, 255), (1e10, 255, 255, 255, int(f32(1e10)) & 0xFF), + (math.inf, 255, 255, 255, 0), (-math.inf, 0, 0, 0, 0), (math.nan, 0, 0, 0, 0), + (0.0, 0, 0, 0, 0), (3.0, 3, 3, 3, 3), (254.75, 255, 254, 255, 254), + ] + for x, *want in table: + got = [MODELS[m](x) for m in MODELS] + check('models(%r)' % x, got, want) + # merge: sel selects the byte, high bits ignored + check('merge sel0', merge(0x11, 0), 0xA5C3E111) + check('merge sel1', merge(0x11, 1), 0xA5C3117B) + check('merge sel2', merge(0x11, 2), 0xA511E17B) + check('merge sel3', merge(0x11, 3), 0x11C3E17B) + check('merge sel high bits', merge(0x11, 0xFFFFFFFD), 0xA5C3117B) + check('merge byte masked', merge(0x1FF, 0), 0xA5C3E1FF) + check('extract', extract_byte(0xA5C3117B, 1), 0x11) + check('merge_ok good', merge_ok(0xA5C3117B, 1), True) + check('merge_ok bad', merge_ok(0xA5C3117C, 1), False) + # input table sanity + t = input_table() + check('unique bits', len({x for _, x in t}), len(t)) + for must in (0, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00000, 0x7FA00000, 0x00000001, 0x7F7FFFFF, bits(2.5)): + check('input has %08x' % must, must in {x for _, x in t}, True) + check('nextafter 2.5', val(bits(2.5) + 1) > 2.5, True) + check('rows count', len(build_rows()), len(t) * len(SELECTS)) + # models must differ on the interesting rows so the probe discriminates + rows = build_rows() + for m in MODELS: + check('model %s distinct' % m, any(model_word(m, r[1], r[2]) != model_word('rne_sat_nan0', r[1], r[2]) + for r in rows), m != 'rne_sat_nan0') + # asm text mentions the expected instructions + a = gen_asm('gfx1030', 'rtz') + check('asm rtz', 's_round_mode 0xf' in a and 'v_cvt_pk_u8_f32 v6, v3, v4, v5' in a, True) + check('asm flush', 's_denorm_mode 0' in gen_asm('gfx1030', 'flush'), True) + h = gen_hip('gfx1030', 'rtz') + check('hip rtz', 's_round_mode 0xf\\n\\ts_nop 0\\n\\tv_cvt_pk_u8_f32 %0, %1, %2, %3' in h and 'cvt_pk_u8_rtz(' in h + and '0xa5c3e17bu' in h, True) + check('hip flush', 's_denorm_mode 0' in gen_hip('gfx1030', 'flush'), True) + check('hip default has no mode', any(m in gen_hip('gfx1030', 'default') for m in ('s_round_mode', 's_denorm_mode', 's_nop')), False) + check('asm default has no mode', 's_round_mode' in gen_asm('gfx1030', 'default'), False) + print('self-test %s' % ('OK' if ok else 'FAILED')) + return 0 if ok else 1 + + +# ---------------------------------------------------------------- main + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--device', type=int, default=0, help='HIP device index (default 0; every device is listed)') + ap.add_argument('--arch', help='target, e.g. gfx1030, gfx1032, gfx1100 (default: from the HIP device)') + ap.add_argument('--asm-only', action='store_true', help='build only, do not launch (no GPU needed)') + ap.add_argument('--self-test', action='store_true', help='check the models without any device') + ap.add_argument('--keep', help='directory to keep .hip/.s/.o/.hsaco files (default: temporary)') + ap.add_argument('--out', default=os.path.join('out', 'rdna_cvt_pk_u8.tsv'), help='compact result file') + ap.add_argument('--compare', default=DEFAULT_REFERENCE, help='stored result file to compare the rows with') + ap.add_argument('--json', help='also write the verbose JSON (rows and model summary, about 860 KB)') + ap.add_argument('--show', type=int, default=8, help='first mismatching rows listed per model') + ap.add_argument('--cov', type=int, default=5, choices=(4, 5), help='HSA code object version') + ap.add_argument('--build', choices=('hip', 'asm'), default='hip', + help='hip: compile a device-only HIP source with clang (default); asm: hand-written assembly') + ap.add_argument('--clang', help='clang executable (--build hip)') + ap.add_argument('--llvm-mc', help='llvm-mc executable (--build asm)') + ap.add_argument('--lld', help='ld.lld executable (--build asm)') + args = ap.parse_args() + + if args.self_test: + return self_test() + + hip, arch = None, args.arch + if not args.asm_only: + try: + hip = Hip() + hip.device = args.device + for i in range(hip.count()): + print('HIP device %d: %s%s' % (i, hip.arch(i), ' <- used' if i == args.device else '')) + if not arch: + arch = hip.arch() + except RuntimeError as e: + print('error: %s' % e, file=sys.stderr) + return 2 + if not arch: + sys.exit('error: --asm-only needs --arch') + arch = arch.split(':')[0] + + workdir = args.keep or tempfile.mkdtemp(prefix='cvt_pk_u8_') + os.makedirs(workdir, exist_ok=True) + images = {} + for var in VARIANTS: + images[var] = build(arch, var, workdir, args) + print('built %s (%d bytes): %s' % (var, len(images[var][0]), images[var][1])) + if args.asm_only: + return 0 + + rows = build_rows() + words = [(r[1], r[2]) for r in rows] + results = {} + try: + for var in VARIANTS: + results[var] = hip.run_kernel(images[var][0], 'cvt_pk_u8_' + var, words) + except RuntimeError as e: + print('error: %s' % e, file=sys.stderr) + return 3 + summary = analyse(rows, results, args.show) + print_report(rows, results, summary, arch, args.show) + header = ['# rdna_cvt_pk_u8 v1: v_cvt_pk_u8_f32 vD, vIn, vSel, vS2 measured by tools/rdna_cvt_pk_u8.py', + '# sentinel (S2) %08x' % SENTINEL, '# device %s' % arch, + '# columns (tab separated, words in hex): label in sel default rtz flush', + '# default = MODE at launch default, rtz = s_round_mode 0xf, flush = s_denorm_mode 0'] + lines = ['\t'.join([r[0], '%08x' % r[1], '%08x' % r[2]] + ['%08x' % results[v][i] for v in VARIANTS]) + for i, r in enumerate(rows)] + os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) + with open(args.out, 'w', newline='\n') as f: + f.write('\n'.join(header + lines) + '\n') + print('\nresults written to %s' % os.path.abspath(args.out)) + if args.json: + with open(args.json, 'w') as f: + json.dump({'arch': arch, 'sentinel': SENTINEL, + 'rows': [{'label': r[0], 'in': '%08x' % r[1], 'sel': '%08x' % r[2], + **{v: '%08x' % results[v][i] for v in results}} for i, r in enumerate(rows)], + 'summary': summary}, f, indent=1) + print('verbose JSON written to %s' % os.path.abspath(args.json)) + if args.compare and os.path.exists(args.compare): + with open(args.compare) as f: + stored = [l.rstrip('\n') for l in f if not l.startswith('#')] + if stored == lines: + print('rows identical to %s' % args.compare) + else: + print('rows DIFFER from %s (%d of %d rows)' % (args.compare, sum(a != b for a, b in zip(stored, lines)), len(lines))) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 7b5e76021..aca010f90 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1317,7 +1317,6 @@ class Stage: low16_only_v = () # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load pinned_low16_v = () # low16_only_v live across basic-block boundaries whole_read_v = () # VGPRs read outside a proven low-16-bit consumer - byte_float_v = () # VGPRs proven to hold +0.0 or an integer in 1..255 (v_cvt_f32_ubyte0..3 result) used_atomic = () # atomic result types ('uint', 'int') needing declarations in main() # pixel: VGPR -> (attr, channel, high) of the v_interp_p1ll_f16 that wrote it. Created on first use, because # unit probes build a Stage without __init__. @@ -1555,8 +1554,6 @@ def clear_low16(self, n): def set_v(self, n, expr, *, low16_only=False): if getattr(self, 'interp_p1', None): self.interp_p1.pop(n, None) - if self.byte_float_v: - self.byte_float_v.discard(n) if hasattr(self, 'uniform_v'): self.uniform_v.discard(n) self.last_v = (n, expr) @@ -2474,12 +2471,37 @@ def lower(self, base, asm, ops, mods): if hasattr(self, 'scc_uniform'): self.scc_uniform = False # the hardware SCC result is not modelled return None + if base == 's_setreg_imm32_b32': + # The write itself changes nothing the lowering models, except MODE[1:0] (the binary32 rounding mode): + # v_cvt_pk_u8_f32 and the other conversions are lowered for round-to-nearest-even, and the hardware + # follows MODE.round (round toward zero truncates). s_round_mode and s_setreg_b32 are refused already. + field = re.fullmatch(r'hwreg\((HW_REG_MODE|1)(?:,\s*(\d+),\s*(\d+))?\)', ops[0].strip()) if ops else None + if field and int(field.group(2) or 0) < 2: # shortcut: an offset >= 2 cannot reach MODE[1:0] + # The immediate is known: the write is harmless when it leaves MODE[1:0] at 0 (nearest even). + offset, width = int(field.group(2) or 0), int(field.group(3) or 32) + try: + value = int(ops[1], 0) & 0xffffffff + except IndexError: + value = None + except ValueError: + # The disassembler prints some inline constants as floats (1.0, 0.5): take their binary32 bits. + try: + value = struct.unpack(' dict(index, kind): images a pixel stage stores to (u registers); None until the first store def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, - refusals=None, decoded=None, ps_attr_map=None, srv_formats=(), pk_u8_s0_contract=False): - # pk_u8_s0_contract: the caller guarantees that every v_cvt_pk_u8_f32 S0 register not proven in domain - # holds +0.0 or an integer in 1..255 (fixtures only; ordinary translation never selects it). - self.pk_u8_s0_contract = pk_u8_s0_contract + refusals=None, decoded=None, ps_attr_map=None, srv_formats=()): self.root = parse_root(root_blob) self.ps_attr_map = ps_attr_map # stream_interface(): pixel attribute -> (vertex parameter, component mask); None pairs by number self.vs_fetch = vs_fetch # stream_fetch(): the loads the vertex stage's entry call stands for @@ -6117,7 +6120,7 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-14')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-15')))) return fnv(layout, key) if layout else key @@ -6126,7 +6129,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-14cs') + key = fnv(b'x2w-startup-shader-15cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack(' Date: Wed, 25 Nov 2026 23:17:45 +0300 Subject: [PATCH 143/232] textures: measure block-compressed copy bounds in whole blocks (#2527) list_copy_texture.h compared the copy region of a block-compressed CopyTextureRegion against the subresource size in texels. A 2x2 or 1x1 BC mip (and any mip whose size is not a multiple of 4, such as 6x6) has a 4x4-block-aligned footprint from GetCopyableFootprints, so the canonical whole-footprint upload with a null box was refused as dest_overflow and never forwarded, although D3D12 accepts it. Round each side's extent up to the block before the bounds checks, as D3D12 does (its debug layer reports a 1x1 BC1 mip as 4x4). A second block or an 8x8 footprint into a 1x1 mip is still refused. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/startup-runtime.md | 3 ++- src/startup_stubs/list_copy_texture.h | 22 +++++++++++++++------- tests/startup_list_copy_texture_check.cpp | 13 +++++++++++++ 3 files changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a89434bd9..d57babc3c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2971,7 +2971,8 @@ check only: - Argument checks (`src/startup_stubs/list_copy_texture.h`): footprint on both sides, empty or inverted box, source and destination bounds, row pitch (multiple of 256), offset (multiple of 512), footprint end inside the buffer (includes the destination origin, the source box origin and the footprint-height slice stride), - block alignment, every multiply and add in the footprint arithmetic checked for wrapping. + block alignment, every multiply and add in the footprint arithmetic checked for wrapping. Block-compressed + bounds are whole 4x4 blocks, as in D3D12: a 2x2 or 1x1 mip takes the 4x4 footprint GetCopyableFootprints gives it. - Subresource index: `mip + slice * mips + plane * mips * array_size` must lie inside the resource's `mips * array_size * planes`; a mip-only modulo would read an out-of-range slice as mip 0 (`bad_subresource`). A planar format (more than one plane) is refused (`planar_unsupported`). diff --git a/src/startup_stubs/list_copy_texture.h b/src/startup_stubs/list_copy_texture.h index 96603cf2b..4ca6f57a3 100644 --- a/src/startup_stubs/list_copy_texture.h +++ b/src/startup_stubs/list_copy_texture.h @@ -12,8 +12,8 @@ namespace x2w_list_copy_texture { enum class Kind : std::uint32_t { subresource = 0, placed_footprint = 1 }; // What the check needs to know about one side of the copy. For a subresource side, width/height/depth are -// the subresource's size in blocks (texels for an uncompressed format). For a footprint side, the footprint -// size in blocks, the row pitch in bytes, the byte offset and the bytes per block are used, and +// the subresource's size in texels (a 2x2 mip of a block-compressed format is 2x2). For a footprint side, the +// footprint size in texels, the row pitch in bytes, the byte offset and the bytes per block are used, and // resource_bytes is the size of the buffer. struct Side { Kind kind; @@ -140,19 +140,27 @@ inline Verdict check(const Side& dst, std::uint32_t x, std::uint32_t y, std::uin } if (dst.samples != src.samples) return Verdict::sample_mismatch; if (dst.format != src.format) return Verdict::format_mismatch; - const Box whole{0, 0, 0, src.width, src.height, src.depth}; + const Side& tex = dst.kind == Kind::subresource ? dst : src; // the side that knows the block size + // D3D12 measures a block-compressed region in whole blocks: a 2x2 or 1x1 mip spans one 4x4 block, and + // GetCopyableFootprints describes it as a 4x4 footprint, so each side's extent rounds up to the block. + const auto extent = [](std::uint32_t v, std::uint32_t block) { + return block > 1 ? (std::uint64_t{v} + block - 1) / block * block : std::uint64_t{v}; + }; + const std::uint64_t src_w = extent(src.width, tex.block_w), src_h = extent(src.height, tex.block_h); + const std::uint64_t dst_w = extent(dst.width, tex.block_w), dst_h = extent(dst.height, tex.block_h); + const auto narrow = [](std::uint64_t v) { return static_cast(v > 0xffffffffu ? 0xffffffffu : v); }; + const Box whole{0, 0, 0, narrow(src_w), narrow(src_h), src.depth}; const Box use = box ? *box : whole; if (use.left >= use.right || use.top >= use.bottom || use.front >= use.back) return Verdict::bad_box; - if (use.right > src.width || use.bottom > src.height || use.back > src.depth) return Verdict::source_overflow; - const Side& tex = dst.kind == Kind::subresource ? dst : src; // the side that knows the block size + if (use.right > src_w || use.bottom > src_h || use.back > src.depth) return Verdict::source_overflow; if (x % tex.block_w || use.left % tex.block_w || y % tex.block_h || use.top % tex.block_h) return Verdict::bad_alignment; const std::uint32_t w = use.right - use.left, h = use.bottom - use.top, d = use.back - use.front; // D3D12 requires a null source box even if an explicit box would cover the whole subresource. const bool depth_stencil = src.depth_stencil || dst.depth_stencil; if ((src.samples > 1 || depth_stencil) && - (box || x || y || z || w != dst.width || h != dst.height || d != dst.depth)) + (box || x || y || z || w != dst_w || h != dst_h || d != dst.depth)) return src.samples > 1 ? Verdict::partial_multisample : Verdict::partial_depth_stencil; - if (std::uint64_t{x} + w > dst.width || std::uint64_t{y} + h > dst.height || std::uint64_t{z} + d > dst.depth) + if (std::uint64_t{x} + w > dst_w || std::uint64_t{y} + h > dst_h || std::uint64_t{z} + d > dst.depth) return Verdict::dest_overflow; for (const Side* s : {&dst, &src}) { if (s->kind != Kind::placed_footprint) continue; diff --git a/tests/startup_list_copy_texture_check.cpp b/tests/startup_list_copy_texture_check.cpp index bfd55e9c8..22a5d948e 100644 --- a/tests/startup_list_copy_texture_check.cpp +++ b/tests/startup_list_copy_texture_check.cpp @@ -57,6 +57,19 @@ int main(int argc, char** argv) // Block-compressed: 4x4 blocks of 8 bytes; a 6-texel start is not on a block. expect(check(texture(64, 64, 4), 6, 0, 0, texture(64, 64, 4), nullptr), Verdict::bad_alignment, "block alignment"); expect(check(footprint(64, 64, 0, 256, 8, 256 * 16, 4), 0, 0, 0, texture(64, 64, 4), nullptr), Verdict::ok, "bc footprint"); + // A 2x2 or 1x1 BC mip spans one 4x4 block: GetCopyableFootprints gives it a 4x4 footprint (one 8-byte row + // on a 256-byte pitch) and D3D12 accepts the whole-footprint upload (WARP with the debug layer: no message). + expect(check(texture(2, 2, 4), 0, 0, 0, footprint(4, 4, 512, 256, 8, 1032, 4), nullptr), Verdict::ok, "bc 2x2 mip upload"); + expect(check(texture(1, 1, 4), 0, 0, 0, footprint(4, 4, 1024, 256, 8, 1032, 4), nullptr), Verdict::ok, "bc 1x1 mip upload"); + expect(check(texture(6, 6, 4), 0, 0, 0, footprint(8, 8, 0, 256, 8, 272, 4), nullptr), Verdict::ok, "bc 6x6 mip upload"); + expect(check(texture(2, 2, 4), 0, 0, 0, footprint(4, 4, 512, 256, 8, 1032, 4), &(const Box&)Box{0, 0, 0, 4, 4, 1}), + Verdict::ok, "bc 2x2 mip, 4x4 box"); + expect(check(footprint(4, 4, 0, 256, 8, 8, 4), 0, 0, 0, texture(1, 1, 4), nullptr), Verdict::ok, "bc 1x1 mip readback"); + // The rounded extent is still one block: a second block, or an 8x8 footprint, leaves the 1x1 mip (the debug + // layer reports both as a destination region past the subresource). + expect(check(texture(2, 2, 4), 4, 0, 0, footprint(4, 4, 512, 256, 8, 1032, 4), nullptr), Verdict::dest_overflow, "bc 2x2 mip, second block"); + expect(check(texture(1, 1, 4), 0, 0, 0, footprint(8, 8, 0, 256, 8, 272, 4), nullptr), Verdict::dest_overflow, "bc 1x1 mip, 8x8 footprint"); + expect(check(texture(2, 2, 4), 0, 0, 0, texture(4, 4, 4), &(const Box&)Box{0, 0, 0, 8, 4, 1}), Verdict::source_overflow, "bc 4x4 source, 8-wide box"); // The destination origin counts: a 1x1 RGBA8 copy at Y=63 of a 64x64, 256-pitch footprint ends at byte 16132. expect(check(footprint(64, 64, 0, 256, 4, 256), 0, 63, 0, texture(1, 1), nullptr), Verdict::footprint_overflow, "dest origin counts"); From 7d92b5a4d286ba6c232f7a581ca7a189103cf21b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:18:26 +0300 Subject: [PATCH 144/232] pe: map raw section data past VirtualSize up to the page end (#2534) Windows maps a section in whole pages: raw file data past VirtualSize stays visible up to the end of the section's last page. pe_map cut the copy at VirtualSize and zero-filled the rest of that page, so a copy of the register probe with .rdata VirtualSize 0x40 differed from LoadLibraryExW at byte 0x44. Clamp the sector-rounded raw copy to the page-rounded span instead. native_section_check now compares each section up to its page end and adds a "raw data past VirtualSize" case. --- tests/cpu/native_section_check.py | 14 +++++++++++--- tools/pe_map.cpp | 7 ++++++- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/tests/cpu/native_section_check.py b/tests/cpu/native_section_check.py index 74ebedb2d..283bfef02 100644 --- a/tests/cpu/native_section_check.py +++ b/tests/cpu/native_section_check.py @@ -1,6 +1,7 @@ """Compare every mapped section of the register probe with the Windows loader, on copies with patched section file fields. Windows reads raw section data in whole 0x200-byte file sectors, and leaves a section with PointerToRawData 0 zero-filled. +Each section is compared up to the end of its last page: raw data past VirtualSize stays visible up to that page end. Raw data past the end of the file reads as zero, except that the last section's raw data must end inside the file and no raw range may reach 4 GiB; copies that break either rule must be refused by both loaders. """ @@ -19,6 +20,7 @@ FIELDS = {"VirtualSize": 8, "SizeOfRawData": 16, "PointerToRawData": 20} # offsets in IMAGE_SECTION_HEADER SECTOR = 0x200 +PAGE = 0x1000 # x64 Windows page size ERROR_BAD_EXE_FORMAT = 193 kernel = ctypes.WinDLL("kernel32", use_last_error=True) kernel.LoadLibraryExW.argtypes = [wintypes.LPCWSTR, wintypes.HANDLE, wintypes.DWORD] @@ -33,6 +35,7 @@ ("start inside a sector", ".rdata", lambda s, n: {"PointerToRawData": s.PointerToRawData + 0x10}, 0, True), ("start in the first sector", ".rdata", lambda s, n: {"PointerToRawData": SECTOR // 2}, 0, True), ("raw size below a sector", ".rdata", lambda s, n: {"SizeOfRawData": 0x10}, 0, True), + ("raw data past VirtualSize", ".rdata", lambda s, n: {"VirtualSize": 0x40}, 0, True), ("raw data crossing a sector", ".rdata", lambda s, n: {"PointerToRawData": s.PointerToRawData + SECTOR - 0x10, "SizeOfRawData": 0x20}, 0, True), ("rounded end past the file", ".rsrc", @@ -51,14 +54,19 @@ def layout(image): - """Return (name, rva, span) for each section; refuse images whose load would run code.""" + """Return (name, rva, extent) for each section, the extent rounded up to whole pages; refuse images whose load + would run code.""" with pefile.PE(str(image), fast_load=True) as pe: if pe.OPTIONAL_HEADER.AddressOfEntryPoint or pe.OPTIONAL_HEADER.DATA_DIRECTORY[1].Size: raise AssertionError(f"{image.name}: needs no entry point and no imports to be loaded safely") - return [(s.Name.rstrip(b"\0").decode(), s.VirtualAddress, s.Misc_VirtualSize or s.SizeOfRawData) + return [(s.Name.rstrip(b"\0").decode(), s.VirtualAddress, pages(s.Misc_VirtualSize or s.SizeOfRawData)) for s in pe.sections] +def pages(size): + return -(-size // PAGE) * PAGE + + def patch(source, target, name, edits, cut): """Copy source with one section header edited and the file shortened; return the exact-read bytes.""" data = bytearray(source.read_bytes()) @@ -76,7 +84,7 @@ def patch(source, target, name, edits, cut): offset = fields.get("PointerToRawData", section.PointerToRawData) size = fields.get("SizeOfRawData", section.SizeOfRawData) exact = bytes(data[offset:offset + min(size, span)]) - return (exact + bytes(span))[:span] + return (exact + bytes(pages(span)))[:pages(span)] def read(base, sections): diff --git a/tools/pe_map.cpp b/tools/pe_map.cpp index e15327043..347bc17ff 100644 --- a/tools/pe_map.cpp +++ b/tools/pe_map.cpp @@ -1156,7 +1156,12 @@ extern "C" __declspec(dllexport) void* pe_map_image(const wchar_t* path, Resolve std::uint64_t end = (raw_end + 0x1ff) & ~std::uint64_t{0x1ff}; if (end > raw.size()) end = raw.size(); if (first >= end) continue; - const std::uint64_t length = end - first < span ? end - first : span; + // Windows maps the section in whole pages: raw data past VirtualSize stays visible up to the + // end of the section's last page, and never reaches the next page. The section starts on a + // page and its span lies inside SizeOfImage, so the rounded window stays in the allocation. + const std::uint64_t page = system.dwPageSize; + const std::uint64_t window = (std::uint64_t{span} + page - 1) & ~(page - 1); + const std::uint64_t length = end - first < window ? end - first : window; std::memcpy(base + s.VirtualAddress, raw.data() + first, static_cast(length)); } From bbe711fcdf3fe9fc51da42f33935b2d8ca16f0a9 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 04:19:24 +0800 Subject: [PATCH 145/232] shader: read concrete src_scc words in bounded mesh lowerers (#2434) AI-assisted with Codex + GPT-6.2 Astra (xhigh). Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 6 ++++++ tests/mesh_dynamic_aot_check.py | 38 +++++++++++++++++++++++++++++++++ tools/mesh_entry_aot.py | 6 ++++++ 3 files changed, 50 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index f5c8cb13a..b3d293324 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -3808,6 +3808,12 @@ exporting vertices 0–63. Wave 1 passes one more barrier and writes vertices it the position of vertex 2 collapses the triangle and changes 528 pixels. The CPU check also runs the waves in both host evaluation orders. +The static and runtime mesh lowerers read a concrete `src_scc` as the word +0 or 1. The fixture compares the triangle allocation word, then compares that +SCC with 1 for equality or 0 for inequality before taking the branch. Both +forms preserve the triangle and quad outputs. Reading an undefined SCC or +one that still depends on a constant-buffer value produces a refusal. + [`tools/mesh_dynamic_aot.py`](../tools/mesh_dynamic_aot.py) emits one desktop mesh shader for a two-wave64 triangle entry. It splits runtime input cases at scalar equality tests and reruns the existing wave model for each case. diff --git a/tests/mesh_dynamic_aot_check.py b/tests/mesh_dynamic_aot_check.py index 3e7090071..e3c1f8ee5 100644 --- a/tests/mesh_dynamic_aot_check.py +++ b/tests/mesh_dynamic_aot_check.py @@ -29,6 +29,43 @@ def expect_refusal(decoded, geometry_word_count, text, limits=MESH_LIMITS): raise AssertionError(f"Expected refusal: {text}") +def check_scc_operand(): + # Preserve the geometry comparison's truth value before its conditional branch. + # LLVM gfx1013 wave64: s_cmp_eq_u32 src_scc, 1 / s_cmp_lg_u32 0, src_scc. + body = decode(CODE) + offset = next(pc for pc, op in body if op.startswith("s_cbranch_scc0 ")) + expected = enumerate_variants(body, 2, MESH_LIMITS) + for instruction in ("fd8106bf", "80fd07bf"): + program = decode(CODE[:offset] + bytes.fromhex(instruction) + CODE[offset:]) + assert enumerate_variants(program, 2, MESH_LIMITS) == expected + for geometry in ([0x1003, SECOND], [0x2004, SECOND]): + assert lower_static(program, geometry, MESH_LIMITS) == lower_static(body, geometry, MESH_LIMITS) + + # The first instruction cannot read an undefined SCC. + undefined = decode(bytes.fromhex("fd8106bf") + CODE) + for lowerer, inputs in ((lower_static, [0x1003, SECOND]), (lower, 2)): + try: + lowerer(undefined, inputs, MESH_LIMITS) + except ValueError as error: + assert "Undefined scalar predicate in src_scc" in str(error), error + else: + raise AssertionError("Accepted src_scc before a predicate was defined") + wave = Wave(0, []) + for addend, carry in (("0", 0), ("1", 1)): + wave.scalar_op("s_add_u32", ["s6", "0xffffffff", addend]) + wave.scalar_op("s_mov_b32", ["s7", "src_scc"]) + assert wave.scalar("s7") == carry + # A constant-buffer comparison has no concrete result at translation time. + wave.s[7] = "pointData[0].x" + wave.scalar_op("s_cmp_eq_u32", ["s7", "0"]) + try: + wave.scalar_op("s_cmp_eq_u32", ["src_scc", "1"]) + except ValueError as error: + assert "Dynamic scalar predicate in src_scc" in str(error), error + else: + raise AssertionError("Treated a dynamic SCC as a concrete word") + + def check_retired_wave(): body = decode(CODE) decoded = decode(RETIRED_PREFIX + CODE) @@ -137,6 +174,7 @@ def check_exec_restore(decoded): def check(): + check_scc_operand() check_retired_wave() decoded = decode(CODE) variants = enumerate_variants(decoded, 2, MESH_LIMITS) diff --git a/tools/mesh_entry_aot.py b/tools/mesh_entry_aot.py index d53d0365f..7a9c0afd0 100644 --- a/tools/mesh_entry_aot.py +++ b/tools/mesh_entry_aot.py @@ -198,6 +198,12 @@ def scalar(self, t, allow_undef=False): if self.vcc is None: raise ValueError("Undefined wave predicate") return self.vcc + if t == "src_scc": + if self.scc is None: + raise ValueError("Undefined scalar predicate in src_scc") + if isinstance(self.scc, Dyn): + raise ValueError("Dynamic scalar predicate in src_scc") + return int(self.scc) if re.fullmatch(r"-?\d+\.\d+", t): return struct.unpack(" Date: Thu, 26 Nov 2026 01:49:56 +0530 Subject: [PATCH 146/232] startup: lower v_cvt_off_f32_i4 in gfx2hlsl (#2452) * shader: lower v_cvt_off_f32_i4 in startup gfx2hlsl * tests: pin the DPP16 quad-broadcast acceptance for v_cvt_off_f32_i4 The generic Stage.dpp_broadcast path is op-agnostic: it proves whole-quad activity, reads the lane quad_perm names with QuadReadLaneAt, and then lowers the base operation on that value. v_cvt_off_f32_i4 is now in VEC_U_TO_F, so it takes that path like any other unary VOP1; the merge base refused every form of the op, which is why the DPP form was refused there too. Pin the acceptance (lane 2 and lane 3, the shader-model bump, and the nibble sign-extend on the broadcast value) plus the refusals that keep it sound: a non-broadcast and a mixed quad_perm, a partial row_mask, bound_ctrl:0, an entry mask that is not proven whole-quad, and a vertex stage. Refs #2452 --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 10 + CMakePresets.json | 2 +- docs/experiments.md | 25 + .../startup_gfx2hlsl_cvt_off_f32_i4_check.py | 804 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 17 +- 7 files changed, 856 insertions(+), 4 deletions(-) create mode 100644 tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 1aad82663..aacd07c45 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -227,6 +227,7 @@ jobs: tests/startup_live_telemetry_check.py \ tests/startup_gfx2hlsl_cvt_alu_check.py \ tests/startup_gfx2hlsl_cvt_pk_u8_check.py \ + tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py \ tests/startup_gfx2hlsl_int_med3_check.py \ tests/startup_gfx2hlsl_cselect_mask_check.py \ tests/startup_gfx2hlsl_mask_overwrite_check.py \ diff --git a/AGENTS.md b/AGENTS.md index da7d4c281..4a0be0ba8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -230,6 +230,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_image_gather_lz_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_c_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cvt_alu_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py ./out/pe-env/bin/python -B tests/startup_triage_run_check.py ./out/pe-env/bin/python -B tests/startup_run_ps1_check.py ./out/pe-env/bin/python -B tests/startup_run_sh_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 34c78eb0b..b85216ccf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3224,6 +3224,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_u8_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_cvt_off_f32_i4 (VOP1 0x0e and VOP3A 0x18e): signed 4-bit nibble conversion with output modifiers, + # low16_only provenance, uniformity tracking, refusals, and WARP/hardware draws with mutated controls. + add_test(NAME startup_gfx2hlsl_cvt_off_f32_i4_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cvt_off_f32_i4_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cvt_off_f32_i4_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 16-bit integer VOPC compares (v_cmp/v_cmpx _i16/_u16, #1723): translation controls, then draws of a # census-shaped v_cmpx kill and of every condition folded into mask words, with mutated lowerings. add_test(NAME startup_gfx2hlsl_cmp16_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/CMakePresets.json b/CMakePresets.json index ffb951925..398176d5b 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index b3d293324..f47b5d13d 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15185,6 +15185,31 @@ data, because a refusal is observable at the `Stage` entry point. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sad_(controls|warp|hardware)$' -V +## Startup translator: signed 4-bit offset conversion (`v_cvt_off_f32_i4`) + +`tools/startup/gfx2hlsl.py` lowers `v_cvt_off_f32_i4` in VOP1 `_e32` (`0x0e`) and VOP3A `_e64` (`0x18e`) via +`VEC_U_TO_F` as `(float(int({0} << 28) >> 28) * 0.0625)`, matching RDNA 2 ISA semantics: the offset is inherent +in the signed 4-bit two's-complement nibble (`[3:0]` in `[-8, +7]`, with no separate `- 8` bias term subtracted), +scaled by `1/16` to produce exact binary32 steps in `[-0.5, +0.4375]`. As a `VEC_U_TO_F` +conversion, it accepts output modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`, scaled before `clamp`), marks its source +`low16_only=True` in `Stage.lower` because only bits `[3:0]` are read, and participates in `UNIFORM_VALU` tracking for +`v_readfirstlane_b32`. VOP3A source `abs`/`neg` bits, `op_sel`, wrong operand counts, and SDWA forms (`_sdwa`) are +refused. + +[The check fixture](../tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py) constructs synthetic gfx1013 VOP1 `_e32` and +VOP3A `_e64` words decoded via `gfx2hlsl.decode()` (no game data), verifies all 16 nibble values `0..15` with upper-bit +garbage (`0x12345678`, `0xfffffff8`), output modifiers, `low16_only` provenance (odd-dmask `d16` `image_load` followed +by `v_cvt_off_f32_i4`, in-place overwrite clearing, and whole-word read refusal), `UNIFORM_VALU` propagation and refusals, +`abs`/`neg`/`op_sel`/arity/SDWA refusals, and an unlowered control. On WARP (`Microsoft Basic Render Driver`, driver +`10.0.26100.9818`, debug layer unavailable) with FXC `ps_5_1` and DXC `ps_6_0`, all 14 draws matched (7 per compiler, +covering all 16 nibbles, upper-bit garbage, and output modifiers) and all 6 mutated draws (`unsigned_nibble`, +`5bit_signext`, and `early_clamp`) failed against the reference with their mutated output words. Not covered: hardware +GPU draw (`startup_gfx2hlsl_cvt_off_f32_i4_hardware` not run here) and SDWA/DPP forms (refused). + +```powershell +python -B tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py +python -B tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py draw warp +ctest --preset dev --no-tests=error -R "^startup_gfx2hlsl_cvt_off_f32_i4_(controls|warp|hardware)$" -V ``` ## Opt-in release of retired slot-133 title-memory textures (Slice 2) diff --git a/tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py b/tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py new file mode 100644 index 000000000..e8a8a2907 --- /dev/null +++ b/tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py @@ -0,0 +1,804 @@ +"""`v_cvt_off_f32_i4` (VOP1 0x0e and VOP3A 0x18e) in tools/startup/gfx2hlsl.py. + + (no arguments) translation, decoder, evaluator, provenance, uniformity, refusal, and + unlowered-control checks, pure Python + draw [fxc] + compile the translated pairs with FXC ps_5_1 (when given) and DXC ps_6_0, + draw all 16 nibble values, upper-bit garbage, and e64 output modifiers on the + adapter, and require mutated lowerings to fail with their mutated words + +RDNA 2 ISA semantics: + `v_cvt_off_f32_i4` reads bits `[3:0]` of SRC0 as a signed 4-bit two's-complement integer in `[-8, +7]` and returns + `float(i4) * 0.0625` (exact steps of `1/16`, `[-0.5, +0.4375]`). As a float-result conversion in `VEC_U_TO_F`, it + accepts output modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`, applied with scaling before `clamp`), reads only bits + `[3:0]` (`low16_only=True`), and preserves uniformity (`UNIFORM_VALU`). Source `abs`/`neg`, `op_sel`, wrong operand + counts, and SDWA forms stay refused. + +Every instruction tested here is constructed as synthetic gfx1013 machine words from the layouts in +`tools/disasm_rdna2.py` and decoded via `gfx2hlsl.decode()` (no game data). +""" +import re +import struct +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 compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import POST_WORDS, PRE_WORDS, vs_words, words_text # noqa: E402 +from startup_image_3d_check import VS_WORDS as FULLSCREEN_VS_WORDS, root_blob as table_root_blob # noqa: E402 + +MASK = 0xffffffff +VOP1_CVT_OFF_F32_I4 = 0x0e +VOP1_CVT_F32_UBYTE2 = 0x13 +VOP1_E64_BASE = 0x180 +VOP2_ADD_NC_U32 = 0x25 +VOP1_READFIRSTLANE_B32 = 0x02 +VOPC_CMPX_EQ_U32 = 0xd2 + +OMOD = {None: 0, '': 0, 'mul:2': 1, 'mul:4': 2, 'div:2': 3} +OMOD_SCALE = {None: 1.0, '': 1.0, 'mul:2': 2.0, 'mul:4': 4.0, 'div:2': 0.5} +INLINE_INT = {n: 128 + n for n in range(65)} +INLINE_INT.update({-n: 192 + n for n in range(1, 17)}) +LITERAL = 255 +S_LOAD_DESC_X8 = bytes.fromhex('04040cf4000000fa') # s_load_dwordx8 s[16:23], s[8:9], 0x0 +S_WAITCNT_LGKMCNT0 = bytes.fromhex('7fc08cbf') # s_waitcnt lgkmcnt(0) +S_WAITCNT_VMCNT0 = bytes.fromhex('703f8cbf') # s_waitcnt vmcnt(0) +S_ENDPGM = 0xbf810000 +EXP_MRT0_V12_V15 = bytes.fromhex('0f1800f80c0d0e0f') + + +def V(n): + return 256 + n + + +def S(n): + return n + + +# ---- Synthetic gfx1013 encoders ------------------------------------------------------------------------------------- + +def encode_vop1_e32(op, vdst, src0, *, literal=None): + w0 = 0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff) + return struct.pack('> 2) & 0x1f) << 16) | (1 << 31) + return struct.pack('> 1) & 0x3f) + w1 = offset_imm & 0x1fffff + return struct.pack('= 8 else nibble + val = i4 * 0.0625 + if omod: + val *= OMOD_SCALE[omod] + if clamp: + if val <= 0.0: + val = 0.0 + elif val >= 1.0: + val = 1.0 + return f32_bits(val) + + +def wrong_unsigned_nibble(word, *, omod='', clamp=False): + """Mutated reference: treats bits[3:0] as unsigned 0..15 instead of signed -8..+7.""" + val = (word & 0xf) * 0.0625 + if omod: + val *= OMOD_SCALE[omod] + if clamp: + val = min(max(val, 0.0), 1.0) + return f32_bits(val) + + +def wrong_5bit_nibble(word, *, omod='', clamp=False): + """Mutated reference: sign-extends 5 bits (<< 27 >> 27) instead of 4 bits (<< 28 >> 28).""" + low5 = word & 0x1f + i5 = low5 - 32 if low5 >= 16 else low5 + val = i5 * 0.0625 + if omod: + val *= OMOD_SCALE[omod] + if clamp: + val = min(max(val, 0.0), 1.0) + return f32_bits(val) + + +class U32(int): + def __new__(cls, value): + return super().__new__(cls, int(value) & MASK) + + def __lshift__(self, n): + return U32((int(self) << (int(n) & 31)) & MASK) + + def __rshift__(self, n): + return U32((int(self) & MASK) >> (int(n) & 31)) + + def __and__(self, other): + return U32(int(self) & int(other)) + + def __rand__(self, other): + return U32(int(other) & int(self)) + + +class I32(int): + def __new__(cls, value): + u = int(value) & MASK + return super().__new__(cls, u - 0x100000000 if u & 0x80000000 else u) + + def __rshift__(self, n): + return I32(int(self) >> (int(n) & 31)) + + +class F32: + def __init__(self, bits): + self.bits = int(bits) & MASK + + @classmethod + def from_float(cls, value): + return cls(f32_bits(value)) + + def to_float(self): + return bits_to_f32(self.bits) + + def __mul__(self, factor): + return F32.from_float(self.to_float() * float(factor)) + + +def hlsl_saturate(val): + f = val.to_float() + if f <= 0.0: + return F32(0) + if f >= 1.0: + return F32(0x3f800000) + return val + + +HLSL_ENV = { + 'U32': U32, + 'uint': U32, + 'int': I32, + 'float': lambda x: F32.from_float(int(x)), + 'saturate': hlsl_saturate, + 'U': lambda f: U32(f.bits), +} + + +def eval_hlsl_expr(expr, regs): + py_expr = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'U32(\1)', expr) + return int(eval(py_expr, {'__builtins__': {}}, {**HLSL_ENV, **{k: U32(v) for k, v in regs.items()}})) + + +# ---- Test harness helpers ------------------------------------------------------------------------------------------- + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}", flush=True) + if not condition: + failures.append(label) + if detail: + print(' ' + detail, flush=True) + + +def make_pipeline(ps_body_bytes, *, use_table_root=False): + """Build a full G.Pipeline from synthetic gfx1013 bytes (calls G.decode() and G.Stage).""" + if use_table_root: + return G.Pipeline(FULLSCREEN_VS_WORDS, ps_body_bytes, table_root_blob()) + return G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_body_bytes, root_blob()) + + +def decode_and_one(code, *, sym=None, low16_v=()): + """Decode bytes with G.decode() and execute them on a straight-line Stage.""" + ins = G.decode(code) + stage = G.Stage.__new__(G.Stage) + stage.kind = 'ps' + stage.lines = [] + stage.sym = dict(sym or {}) + stage.used_s, stage.used_v, stage.uniform_v = set(), set(), set() + stage.varying_s = set() + stage.scc_uniform = True + stage.uniform_expr = {} + stage.past_entry = False + stage.has_branches = False + stage.exec_known = True + stage.masks = set() + stage.exports = {} + stage.low16_only_v = set(low16_v) + stage.pinned_low16_v = set() + stage.whole_read_v = set() + stage.byte_float_v = set() + stage.bad_sgprs = set() + stage.defined_uniform_s = None + stage.since_join = None + pipe = type('Pipe', (), {'resources': {}, 'notes': set(), 'modified': set(), 'sampler_heap': False})() + stage.pipe = pipe + for _off, _sz, name, asm in ins: + stage.one(name, asm) + return ins, stage + + +def is_refused_bytes(code, expected_substr='', *, via_pipeline=False): + try: + if via_pipeline: + G.Pipeline(vs_words([(0, 0, 0)] * 4), code, root_blob()) + else: + decode_and_one(code) + except G.Unsupported as err: + return expected_substr in str(err) + return False + + +def is_refused_asm(asm, expected_substr=''): + stage = G.Stage.__new__(G.Stage) + stage.lines, stage.sym = [], {} + stage.used_s, stage.used_v, stage.uniform_v = set(), set(), set() + stage.exec_known = True + try: + stage.one(asm.split(' ', 1)[0], asm) + except G.Unsupported as err: + return expected_substr in str(err) + return False + + +# ---- Pure-Python controls ------------------------------------------------------------------------------------------- + +def check_decode_and_lowering(): + # 1. VOP1 _e32 and VOP3A _e64 decoding via G.decode() + decode_vectors = ( + (encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, V(2)), 'v_cvt_off_f32_i4_e32 v4, v2'), + (encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, S(2)), 'v_cvt_off_f32_i4_e32 v4, s2'), + (encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, INLINE_INT[3]), 'v_cvt_off_f32_i4_e32 v4, 3'), + (encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, LITERAL, literal=0x12345678), + 'v_cvt_off_f32_i4_e32 v4, 0x12345678'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2)), 'v_cvt_off_f32_i4_e64 v4, v2'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), clamp=1), 'v_cvt_off_f32_i4_e64 v4, v2 clamp'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), omod='mul:2'), 'v_cvt_off_f32_i4_e64 v4, v2 mul:2'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), omod='mul:4'), 'v_cvt_off_f32_i4_e64 v4, v2 mul:4'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), omod='div:2'), 'v_cvt_off_f32_i4_e64 v4, v2 div:2'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), clamp=1, omod='mul:4'), + 'v_cvt_off_f32_i4_e64 v4, v2 clamp mul:4'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, S(2), omod='div:2'), 'v_cvt_off_f32_i4_e64 v4, s2 div:2'), + (encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, LITERAL, literal=0xfffffff8), + 'v_cvt_off_f32_i4_e64 v4, 0xfffffff8'), + ) + for code, expected_asm in decode_vectors: + ins, st = decode_and_one(code) + check(f'decode+lower {expected_asm}', + len(ins) == 1 and ins[0][3] == expected_asm and len(st.lines) == 1, + f'got ins={ins!r} lines={st.lines!r}') + + # 2. All 16 nibble values 0..15 + upper-bit garbage across e32 and e64 * (omod x clamp) + garbage_prefixes = (0x00000000, 0x12345670, 0xfffffff0, 0x80000000, 0xdeadbee0) + samples = [prefix | nib for prefix in garbage_prefixes for nib in range(16)] + samples.extend((0x12345678, 0xfffffff8)) + + eval_count = 0 + eval_mismatches = [] + for enc_name, code in ( + ('e32', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, V(2))), + ('e64', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2))), + ): + _, st = decode_and_one(code) + expr = st.lines[0][len('v4 = '):-1] + for word in samples: + eval_count += 1 + got = eval_hlsl_expr(expr, {'v2': word}) + want = isa_cvt_off_f32_i4(word) + if got != want and len(eval_mismatches) < 3: + eval_mismatches.append((enc_name, hex(word), hex(got), hex(want))) + + for omod in ('', 'mul:2', 'mul:4', 'div:2'): + for clamp in (0, 1): + code = encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), omod=omod, clamp=clamp) + _, st = decode_and_one(code) + expr = st.lines[0][len('v4 = '):-1] + for word in samples: + eval_count += 1 + got = eval_hlsl_expr(expr, {'v2': word}) + want = isa_cvt_off_f32_i4(word, omod=omod, clamp=bool(clamp)) + if got != want and len(eval_mismatches) < 3: + eval_mismatches.append((omod, clamp, hex(word), hex(got), hex(want))) + + check(f'all {eval_count} nibble/garbage/modifier evaluations match RDNA2 ISA', + not eval_mismatches, repr(eval_mismatches)) + + # 3. Verify hardware order: omod before clamp (5 -> 0.3125 * 4 = 1.25 -> saturate = 1.0, not 1.25; + # 8 -> -0.5 * 2 = -1.0 -> saturate = 0.0) + _, st_cm4 = decode_and_one(encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), omod='mul:4', clamp=1)) + expr_cm4 = st_cm4.lines[0][len('v4 = '):-1] + check('clamp applies after mul:4 on nibble 5 (0.3125 * 4 -> 1.0)', + eval_hlsl_expr(expr_cm4, {'v2': 0x12345675}) == f32_bits(1.0), expr_cm4) + check('clamp clamps negative nibble 8 (-0.5 * 4 -> 0.0)', + eval_hlsl_expr(expr_cm4, {'v2': 0xfffffff8}) == f32_bits(0.0), expr_cm4) + + # 4. Literal and inline constant sources via G.decode() + for desc, code, want_val in ( + ('e32 literal 0x12345678', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, LITERAL, literal=0x12345678), -0.5), + ('e32 literal 0xfffffff8', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, LITERAL, literal=0xfffffff8), -0.5), + ('e64 literal 0x12345678', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, LITERAL, literal=0x12345678), -0.5), + ('e64 literal 0xfffffff8', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, LITERAL, literal=0xfffffff8), -0.5), + ('e32 inline 7', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, INLINE_INT[7]), 0.4375), + ('e32 inline -1', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, INLINE_INT[-1]), -0.0625), + ('e64 inline -8', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, INLINE_INT[-8]), -0.5), + ): + _, st = decode_and_one(code) + expr = st.lines[0][len('v4 = '):-1] + got = eval_hlsl_expr(expr, {}) + check(f'constant source {desc}', got == f32_bits(want_val), f'{expr} -> {hex(got)}') + + +def check_low16_provenance(): + # Build full synthetic pixel shaders starting with an odd-dmask d16 image_load into v4, + # making v4 low16_only_v via real decoded MIMG words through G.Pipeline / G.decode(). + load_prefix = (S_LOAD_DESC_X8 + S_WAITCNT_LGKMCNT0 + + encode_vop1_e32(0x01, 0, INLINE_INT[0]) + + encode_vop1_e32(0x01, 1, INLINE_INT[0]) + + encode_mimg_load_d16(vdata=4, vaddr=0, srsrc=16, dmask=0x1) + + S_WAITCNT_VMCNT0) + exp_v5 = encode_exp_mrt0(5, 5, 5, 5) + encode_endpgm() + + # Accepted: v_cvt_off_f32_i4_e32 and _e64 reading low16_only v4 into v5 + for tag, cvt in ( + ('e32', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 5, V(4))), + ('e64', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 5, V(4), omod='mul:2', clamp=1)), + ): + ps_bytes = load_prefix + cvt + exp_v5 + try: + pipe = make_pipeline(ps_bytes, use_table_root=True) + hlsl = pipe.hlsl_ps() + ok = 4 in pipe.ps.low16_only_v and 5 not in pipe.ps.low16_only_v and '<< 28' in hlsl + detail = '' + except G.Unsupported as err: + ok = False + detail = str(err) + check(f'low16_only accepted by v_cvt_off_f32_i4_{tag}', ok, detail) + + # Accepted: in-place overwrite v4 <- v_cvt_off_f32_i4(v4) clears low16_only on v4 so whole-word read succeeds + ps_inplace = (load_prefix + encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, V(4)) + + encode_vop2_e32(VOP2_ADD_NC_U32, 6, INLINE_INT[1], V(4)) + + encode_exp_mrt0(6, 6, 6, 6) + encode_endpgm()) + try: + pipe = make_pipeline(ps_inplace, use_table_root=True) + ok = 4 not in pipe.ps.low16_only_v + detail = '' + except G.Unsupported as err: + ok = False + detail = str(err) + check('in-place v_cvt_off_f32_i4 v4, v4 clears low16_only for subsequent whole-word read', ok, detail) + + # Negative control: reading v4 whole-word AFTER v_cvt_off_f32_i4 v5, v4 must still fail + ps_leak = (load_prefix + encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 5, V(4)) + + encode_vop2_e32(VOP2_ADD_NC_U32, 6, INLINE_INT[1], V(4)) + + encode_exp_mrt0(6, 6, 6, 6) + encode_endpgm()) + try: + make_pipeline(ps_leak, use_table_root=True) + except G.Unsupported as err: + ok = 'whole-word read of v4' in str(err) + detail = str(err) + else: + ok = False + detail = 'unexpectedly accepted' + check('low16_only still catches whole-word read of v4 after v_cvt_off_f32_i4 v5, v4', ok, detail) + + # Negative control: ubyte2 reads bits[23:16] of v4 and must still be refused on odd d16 image_load + ps_ubyte2 = load_prefix + encode_vop1_e32(VOP1_CVT_F32_UBYTE2, 5, V(4)) + exp_v5 + try: + make_pipeline(ps_ubyte2, use_table_root=True) + except G.Unsupported as err: + ok = 'whole-word read of v4' in str(err) + detail = str(err) + else: + ok = False + detail = 'unexpectedly accepted' + check('low16_only negative control: v_cvt_f32_ubyte2 v5, v4 refused', ok, detail) + + +def check_uniform_valu(): + # table_root_blob gives s9 = root constant 1 (uniform user-data scalar). + # Translate real pixel programs via G.Pipeline -> G.decode() -> G.Stage with v_readfirstlane_b32. + rfl = encode_vop1_e32(VOP1_READFIRSTLANE_B32, 10, V(7)) + copy_to_v5 = encode_vop1_e32(0x01, 5, S(10)) + tail = copy_to_v5 + encode_exp_mrt0(5, 5, 5, 5) + encode_endpgm() + + for tag, body in ( + ('e32 uniform s9', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 7, S(9)) + rfl), + ('e64 uniform s9 mul:2 clamp', + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 7, S(9), omod='mul:2', clamp=1) + rfl), + ('chained uniform v7 -> v8 -> readfirstlane', + encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 7, S(9)) + + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 8, V(7), omod='div:2') + + encode_vop1_e32(VOP1_READFIRSTLANE_B32, 10, V(8))), + ): + try: + pipe = make_pipeline(body + tail, use_table_root=True) + lines = [line for _, blk, _ in pipe.ps.blocks for line in blk] + ok = any(line.startswith('s10 = v') for line in lines) + detail = repr(lines) + except G.Unsupported as err: + ok = False + detail = str(err) + check(f'UNIFORM_VALU accepted ({tag})', ok, detail) + + # Negative control 1: varying VGPR v0 -> v7 -> v_readfirstlane_b32 s10, v7 must be refused + ps_varying = encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 7, V(0)) + rfl + tail + try: + make_pipeline(ps_varying, use_table_root=True) + except G.Unsupported as err: + ok = 'v_readfirstlane_b32 requires a proven uniform source' in str(err) + detail = str(err) + else: + ok = False + detail = 'unexpectedly accepted' + check('UNIFORM_VALU refuses varying VGPR source in v_readfirstlane_b32', ok, detail) + + # Negative control 2: unknown exec after v_cmpx_eq_u32 -> v_cvt_off_f32_i4 v7, s9 -> v_readfirstlane_b32 + ps_exec_unknown = (encode_vopc_e32(VOPC_CMPX_EQ_U32, INLINE_INT[0], 0) + + encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 7, S(9)) + rfl + tail) + try: + make_pipeline(ps_exec_unknown, use_table_root=True) + except G.Unsupported as err: + ok = 'v_readfirstlane_b32 requires a proven uniform source' in str(err) + detail = str(err) + else: + ok = False + detail = 'unexpectedly accepted' + check('UNIFORM_VALU refuses v_readfirstlane_b32 when exec is unknown', ok, detail) + + +def check_dpp_broadcast(): + """The generic DPP16 `quad_perm:[k,k,k,k]` broadcast path accepts this VOP1 op, and only where it is sound. + + The merge base refused every `v_cvt_off_f32_i4` form because the op was not lowered at all, so it also + refused the DPP form. The op is now in `VEC_U_TO_F`, and `Stage.dpp_broadcast` is op-agnostic: it proves + whole-quad activity, reads the named lane of the quad with `QuadReadLaneAt`, and then lowers the base + operation on that value (for a unary op the broadcast happens before the conversion, which is the ISA + order). Accepting the broadcast is therefore intended rather than incidental, and the rows below pin the + acceptance, the lane it reads, the shader-model bump, and the four refusals that keep the rest out. + """ + def probe(**state): + stage = G.Stage.__new__(G.Stage) + stage.kind = 'ps' + stage.lines, stage.sym = [], {} + stage.used_s, stage.used_v, stage.uniform_v = set(), set(), set() + stage.varying_s = set() + stage.scc_uniform = True + stage.uniform_expr = {} + stage.past_entry = False + stage.has_branches = False + stage.exec_known = True + stage.masks = set() + stage.exports = {} + stage.low16_only_v = set() + stage.pinned_low16_v = set() + stage.whole_read_v = set() + stage.byte_float_v = set() + stage.bad_sgprs = set() + stage.defined_uniform_s = None + stage.since_join = None + stage.wqm_exec = True + stage.needs_sm6 = False + stage.pipe = type('Pipe', (), {'resources': {}, 'notes': set(), 'modified': set(), + 'sampler_heap': False})() + for key, value in state.items(): + setattr(stage, key, value) + return stage + + def translate(asm, **state): + stage = probe(**state) + try: + stage.one(asm.split(' ', 1)[0], asm) + except G.Unsupported as error: + return None, str(error) + return stage, None + + accepted = 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf' + stage, reason = translate(accepted) + check('dpp_broadcast accepts quad_perm:[2,2,2,2] for v_cvt_off_f32_i4', + stage is not None, str(reason)) + check('dpp_broadcast reads lane 2 of the quad with QuadReadLaneAt', + stage is not None and any('QuadReadLaneAt(v1, 2u)' in line for line in stage.lines), + str(stage and stage.lines)) + check('dpp_broadcast lowers the conversion on the broadcast value (nibble sign-extend x 1/16)', + stage is not None and any('int(v256 << 28) >> 28' in line and '0.0625' in line + for line in stage.lines), + str(stage and stage.lines)) + check('dpp_broadcast requires shader model 6 for QuadReadLaneAt', + stage is not None and stage.needs_sm6 is True) + # The same broadcast at a different lane, to prove the lane is not hard-coded. + lane3, reason = translate('v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[3,3,3,3] row_mask:0xf bank_mask:0xf') + check('dpp_broadcast reads the lane quad_perm names, not a fixed one', + lane3 is not None and any('QuadReadLaneAt(v1, 3u)' in line for line in lane3.lines), + str(reason) or str(lane3 and lane3.lines)) + for label, asm, state, message in ( + ('a non-broadcast quad_perm', 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf', + {}, ''), + ('a mixed quad_perm', 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[2,2,2,3] row_mask:0xf bank_mask:0xf', + {}, 'only the swaps'), + ('a partial row_mask', 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[2,2,2,2] row_mask:0x7 bank_mask:0xf', + {}, 'partial row_mask'), + ('bound_ctrl:0', 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf bound_ctrl:0', + {}, 'bound_ctrl'), + ('an entry mask not proven whole-quad', + 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf', {'wqm_exec': False}, + 'whole-quad'), + ('a vertex stage', 'v_cvt_off_f32_i4_dpp v2, v1 quad_perm:[2,2,2,2] row_mask:0xf bank_mask:0xf', + {'kind': 'vs'}, 'straight-line pixel stage'), + ): + refused, detail = translate(asm, **state) + check('dpp_broadcast refuses %s' % label, + refused is None and message in (detail or ''), str(detail)) + + +def check_refusals_and_unlowered(): + # Refusals: abs, neg, op_sel, SDWA (all decoded from synthetic gfx1013 bytes via G.decode()) + byte_refusals = ( + ('e64 abs on v2', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), abs0=1), ''), + ('e64 neg on v2', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), neg0=1), ''), + ('e64 neg on s2', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, S(2), neg0=1), ''), + ('e64 neg on inline 3', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, INLINE_INT[3], neg0=1), 'neg/abs'), + ('e64 op_sel src0', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), opsel=(1, 0, 0, 0)), 'op_sel'), + ('e64 op_sel src1', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), opsel=(0, 1, 0, 0)), 'op_sel'), + ('e64 op_sel dst', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2), opsel=(0, 0, 0, 1)), 'op_sel'), + ('SDWA BYTE_1', encode_vop1_sdwa(VOP1_CVT_OFF_F32_I4, 4, 2, src0_sel=1), 'SDWA form of v_cvt_off_f32_i4'), + ('SDWA DWORD clamp', encode_vop1_sdwa(VOP1_CVT_OFF_F32_I4, 4, 2, src0_sel=6, clamp=1), + 'SDWA form of v_cvt_off_f32_i4'), + ('SDWA neg', encode_vop1_sdwa(VOP1_CVT_OFF_F32_I4, 4, 2, src0_sel=1, neg=1), ''), + ('SDWA abs', encode_vop1_sdwa(VOP1_CVT_OFF_F32_I4, 4, 2, src0_sel=1, abs_=1), ''), + ) + for label, code, msg in byte_refusals: + check(f'refused: {label}', is_refused_bytes(code, msg)) + + # Arity refusals + for asm, expected_err in ( + ('v_cvt_off_f32_i4 v4', 'with 1 operands, expected 2'), + ('v_cvt_off_f32_i4 v4, v2, v3', 'with 3 operands, expected 2'), + ('v_cvt_off_f32_i4_e64 v4', 'with 1 operands, expected 2'), + ('v_cvt_off_f32_i4_e64 v4, v2, 0', 'with 3 operands, expected 2'), + ): + check(f'refused arity: {asm}', is_refused_asm(asm, expected_err)) + + # Unlowered control: temporarily remove 'v_cvt_off_f32_i4' from G.VEC_U_TO_F and assert both e32 and e64 refuse + saved = G.VEC_U_TO_F.pop('v_cvt_off_f32_i4') + try: + for tag, code in ( + ('e32', encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 4, V(2))), + ('e64', encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 4, V(2))), + ): + check(f'unlowered control ({tag})', is_refused_bytes(code, 'v_cvt_off_f32_i4')) + finally: + G.VEC_U_TO_F['v_cvt_off_f32_i4'] = saved + + +def controls(): + check_decode_and_lowering() + check_low16_provenance() + check_uniform_valu() + check_dpp_broadcast() + check_refusals_and_unlowered() + if failures: + print('FAILED:', ', '.join(failures)) + sys.exit(1) + print('startup_gfx2hlsl_cvt_off_f32_i4_check: all controls passed') + + +# ---- Draw fixtures and mutated controls ----------------------------------------------------------------------------- + +# Base pixel body: 4 lanes alternating VOP1 _e32 (lanes 0, 2) and VOP3A _e64 (lanes 1, 3), reading v0..v3 -> v12..v15. +PLAIN_BODY = ( + encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 12, V(0)) + + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 13, V(1)) + + encode_vop1_e32(VOP1_CVT_OFF_F32_I4, 14, V(2)) + + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 15, V(3)) +) + +# Output-modifier pixel body: 4 lanes in VOP3A _e64 carrying clamp, mul:2, mul:4, and clamp + div:2. +MOD_SPEC = ( + ('', True), # lane 0: clamp + ('mul:2', False), # lane 1: mul:2 + ('mul:4', True), # lane 2: clamp mul:4 (tests scaling before clamp) + ('div:2', False), # lane 3: div:2 +) +MOD_BODY = ( + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 12, V(0), clamp=1) + + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 13, V(1), omod='mul:2') + + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 14, V(2), omod='mul:4', clamp=1) + + encode_vop1_e64(VOP1_CVT_OFF_F32_I4, 15, V(3), omod='div:2') +) + +# 20 inputs (5 draws x 4 lanes): all 16 nibble values 0..15 plus upper-bit garbage including 0x12345678 and 0xfffffff8. +PLAIN_DRAWS = [ + # Draw 0: exercises sign bit (0x8), upper-bit garbage (0x12345678, 0xfffffff8), and positive + negative nibbles + [(0x12345678, 0, 0), (0xfffffff8, 0, 0), (0x80000007, 0, 0), (0xdeadbeef, 0, 0)], + # Nibbles 0..3 with distinct upper-bit patterns + [(0x00000000, 0, 0), (0x11111111, 0, 0), (0x22222222, 0, 0), (0x33333333, 0, 0)], + # Nibbles 4..7 with distinct upper-bit patterns + [(0x44444444, 0, 0), (0x55555555, 0, 0), (0x66666666, 0, 0), (0x77777777, 0, 0)], + # Nibbles 8..11 with distinct upper-bit patterns + [(0x88888888, 0, 0), (0x99999999, 0, 0), (0xaaaaaaa0 | 0xa, 0, 0), (0xbbbbbbb0 | 0xb, 0, 0)], + # Nibbles 12..15 with distinct upper-bit patterns + [(0xccccccc0 | 0xc, 0, 0), (0xddddddd0 | 0xd, 0, 0), (0xeeeeeee0 | 0xe, 0, 0), (0xffffffff, 0, 0)], +] + +MOD_DRAWS = [ + # Lane 0 (clamp): -0.5 -> 0.0; Lane 1 (mul:2): -0.5 -> -1.0; + # Lane 2 (clamp mul:4): 5 (0.3125 * 4 = 1.25 -> 1.0); Lane 3 (div:2): 7 -> 0.21875 + [(0xfffffff8, 0, 0), (0x12345678, 0, 0), (0x12345675, 0, 0), (0x80000007, 0, 0)], + # Lane 0 (clamp): +0.4375 -> 0.4375; Lane 1 (mul:2): +0.4375 -> 0.875; + # Lane 2 (clamp mul:4): -1 -> 0.0; Lane 3 (div:2): -8 -> -0.25 + [(0x00000007, 0, 0), (0xabcdef07, 0, 0), (0xffffffff, 0, 0), (0x00000008, 0, 0)], +] + + +def mutate_plain_unsigned(text): + mutated, count = re.subn(r'int\((v\d+) << 28\) >> 28', r'(\1 & 15u)', text) + assert count == 4 and mutated != text, count + return mutated + + +def mutate_plain_5bit(text): + mutated, count = re.subn(r'int\((v\d+) << 28\) >> 28', r'int(\1 << 27) >> 27', text) + assert count == 4 and mutated != text, count + return mutated + + +def mutate_mod_early_clamp(text): + # Swap saturate((...) * 4.0) into (saturate(...)) * 4.0 on lane 2 (v14) + pattern = r'saturate\(\(\(float\(int\(v2 << 28\) >> 28\) \* 0\.0625\)\) \* 4\.0\)' + replacement = r'(saturate((float(int(v2 << 28) >> 28) * 0.0625))) * 4.0' + mutated, count = re.subn(pattern, replacement, text) + assert count == 1 and mutated != text, (count, text) + return mutated + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + assert {x[0] & 0xf for chunk in PLAIN_DRAWS for x in chunk} == set(range(16)) + + plain_ps_words = PRE_WORDS + PLAIN_BODY + POST_WORDS + mod_ps_words = PRE_WORDS + MOD_BODY + POST_WORDS + plain_ps_hlsl = G.Pipeline(vs_words([(0, 0, 0)] * 4), plain_ps_words, root_blob()).hlsl_ps() + mod_ps_hlsl = G.Pipeline(vs_words([(0, 0, 0)] * 4), mod_ps_words, root_blob()).hlsl_ps() + + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + draws = mutations = 0 + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + plain_cso = compile_hlsl(compiler, kind, plain_ps_hlsl, f'ps_plain_{kind}', ps_profile, directory) + for idx, chunk in enumerate(PLAIN_DRAWS): + vs_hlsl = G.Pipeline(vs_words(chunk), plain_ps_words, root_blob()).hlsl_vs() + vs_cso = compile_hlsl(compiler, kind, vs_hlsl, f'vs_plain_{idx}_{kind}', vs_profile, directory) + want = words_text([isa_cvt_off_f32_i4(x[0]) for x in chunk]) + run = draw(renderer, adapter, vs_cso, plain_cso, want) + if run.returncode: + raise AssertionError(f'{kind} plain draw {idx} {chunk}\n{run.stdout}\n{run.stderr}') + draws += 1 + print(f'{kind} plain[{idx}] {[hex(x[0]) for x in chunk]}: {want}', flush=True) + + if idx == 0: + for mname, mut_fn, ref_fn in ( + ('unsigned_nibble', mutate_plain_unsigned, wrong_unsigned_nibble), + ('5bit_signext', mutate_plain_5bit, wrong_5bit_nibble), + ): + wrong = words_text([ref_fn(x[0]) for x in chunk]) + assert wrong != want + bad_cso = compile_hlsl(compiler, kind, mut_fn(plain_ps_hlsl), + f'ps_mut_{mname}_{kind}', ps_profile, directory) + mrun = draw(renderer, adapter, vs_cso, bad_cso, want) + if mrun.returncode == 0 or f'actual={wrong}' not in mrun.stderr: + raise AssertionError( + f'{kind} mutation {mname} did not read {wrong}\n{mrun.stdout}\n{mrun.stderr}') + mutations += 1 + print(f'{kind} mutation {mname}: fails as expected, reads {wrong}', flush=True) + + mod_cso = compile_hlsl(compiler, kind, mod_ps_hlsl, f'ps_mod_{kind}', ps_profile, directory) + for idx, chunk in enumerate(MOD_DRAWS): + vs_hlsl = G.Pipeline(vs_words(chunk), mod_ps_words, root_blob()).hlsl_vs() + vs_cso = compile_hlsl(compiler, kind, vs_hlsl, f'vs_mod_{idx}_{kind}', vs_profile, directory) + want = words_text([ + isa_cvt_off_f32_i4(x[0], omod=omod, clamp=clamp) + for x, (omod, clamp) in zip(chunk, MOD_SPEC) + ]) + run = draw(renderer, adapter, vs_cso, mod_cso, want) + if run.returncode: + raise AssertionError(f'{kind} mod draw {idx} {chunk}\n{run.stdout}\n{run.stderr}') + draws += 1 + print(f'{kind} mod[{idx}] {[hex(x[0]) for x in chunk]}: {want}', flush=True) + + if idx == 0: + # Early clamp on lane 2: saturate(0.3125) * 4.0 = 1.25 (0x3fa00000) instead of 1.0 (0x3f800000) + wrong_words = [ + isa_cvt_off_f32_i4(x[0], omod=omod, clamp=clamp) + for x, (omod, clamp) in zip(chunk, MOD_SPEC) + ] + wrong_words[2] = f32_bits(bits_to_f32(isa_cvt_off_f32_i4(chunk[2][0], clamp=True)) * 4.0) + wrong = words_text(wrong_words) + assert wrong != want + bad_cso = compile_hlsl(compiler, kind, mutate_mod_early_clamp(mod_ps_hlsl), + f'ps_mut_early_clamp_{kind}', ps_profile, directory) + mrun = draw(renderer, adapter, vs_cso, bad_cso, want) + if mrun.returncode == 0 or f'actual={wrong}' not in mrun.stderr: + raise AssertionError( + f'{kind} mutation early_clamp did not read {wrong}\n{mrun.stdout}\n{mrun.stderr}') + mutations += 1 + print(f'{kind} mutation early_clamp: fails as expected, reads {wrong}', flush=True) + + print(f'{adapter}: {draws} draws matched, {mutations} mutated draws read their mutated words') + + +def main(): + if len(sys.argv) == 1: + controls() + return + if sys.argv[1] == 'draw' and len(sys.argv) in (5, 6): + check_draw(*sys.argv[2:]) + return + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index aca010f90..74244559c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -373,6 +373,14 @@ def check_encoding(code, off, n, name, asm): word0, word1 = struct.unpack_from('<2I', code, off) if word0 & 0x700 or word1 & 0xe0000000: raise Unsupported('%s with neg/abs' % name) + if name == 'v_cvt_off_f32_i4_e64': + # Integer-nibble conversion: the instruction has one source, so only src0's VOP3A ABS (w0[8]) and NEG + # (w1[29]) can carry a modifier. Masking all three bit positions of each field (w0[10:8], w1[31:29]) + # also refuses the unused src1/src2 bits, which keeps an inline constant from masquerading as a + # negative integer and keeps a hidden modifier out of the printed operand. + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & 0x700 or word1 & 0xe0000000: + raise Unsupported('%s with neg/abs: not a 4-bit integer source modifier' % name) if name == 'v_cndmask_b32_e64': # The printed -1 is ambiguous: it can be plain inline -1 or inline 1 with NEG. word0, word1 = struct.unpack_from('<2I', code, off) @@ -678,8 +686,8 @@ def smem_mods(mods): # Multiply, fused multiply-add (including the literal form), reciprocal and median of three use # only local arithmetic. Move copies its input bits. None reads a lane ID or another lane. UNIFORM_VALU = frozenset(( - 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_ubyte0', 'v_mul_f32', - 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', + 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_ubyte0', 'v_cvt_off_f32_i4', + 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', )) @@ -2589,7 +2597,7 @@ def lower(self, base, asm, ops, mods): if any(m not in ('clamp', 'mul:2', 'mul:4', 'div:2') for m in mods): raise Unsupported('%s with %s' % (base, mods)) dst = reg_range(ops[0])[1] - low16 = base in ('v_cvt_f32_f16', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1') + low16 = base in ('v_cvt_f32_f16', 'v_cvt_f32_ubyte0', 'v_cvt_f32_ubyte1', 'v_cvt_off_f32_i4') self.set_vf(dst, text_f.format(*[self.u(o, low16_only=low16) for o in ops[1:1 + arity]]), mods) return None if base in VEC_U: @@ -2736,6 +2744,8 @@ def dpp(self, base, ops, mods): # VEC_U_TO_F conversions apply output modifiers before dst_sel, VEC_F forms stay refused, and # dst_unused UNUSED_SEXT has no lowering. def sdwa(self, base, ops, mods): + if base == 'v_cvt_off_f32_i4': + raise Unsupported('SDWA form of %s' % base) fields = {} out_mods = [] float_result = base in VEC_U_TO_F @@ -5437,6 +5447,7 @@ def declarations(self): 'v_cvt_f32_ubyte0': (1, 'float({0} & 255)'), 'v_cvt_f32_ubyte1': (1, 'float(({0} >> 8) & 255)'), 'v_cvt_f32_ubyte2': (1, 'float(({0} >> 16) & 255)'), 'v_cvt_f32_ubyte3': (1, 'float({0} >> 24)'), 'v_cvt_f32_f16': (1, 'f16tof32({0})'), + 'v_cvt_off_f32_i4': (1, '(float(int({0} << 28) >> 28) * 0.0625)'), } # operands are uints; the result is a uint expression VEC_U = { From 5a219a3c89ec822d4789d4e8d464706e997de8b0 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:21:10 +0100 Subject: [PATCH 147/232] startup: translate slot 57 mesh requests without a pixel stage (#2520) A slot 57 request whose req_.ps57 is empty was refused with "slot 57 mesh without a pixel stage is not covered" (#2413, item T5, no-pixel half). translate_mesh57 now builds the pipeline with no pixel stage and emits and compiles the mesh stage alone (.ms57.hlsl, .ms57.cso), keeping the position and primitive exports and dropping parameter writes (the rest of each export line, including mesh_vertex = true, stays), which nothing reads. The manifest gets a "ps none" line, and pending_keys counts such a result as done with .ms57.cso alone, so it is not retranslated each pass. Pairs with a pixel stage are unchanged; the null-export depth-only pixel stage stays refused. Tests: startup_mesh57_skeleton_check.py checks the mesh-only files, manifest, interface and pending_keys cases, and in draw mode that DXC compiles the mesh-only stage. startup_gfx2hlsl_watch_check.py's synthetic no-pixel mesh now reaches the shape check, like the paired one. Part of #2413. AI-assisted. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- docs/experiments.md | 18 +++++++--- tests/startup_gfx2hlsl_watch_check.py | 3 +- tests/startup_mesh57_skeleton_check.py | 48 +++++++++++++++++++++++--- tools/startup/gfx2hlsl.py | 39 +++++++++++++++------ 4 files changed, 86 insertions(+), 22 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index f47b5d13d..b14397347 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9247,7 +9247,8 @@ the root in `.root`, the pixel program (or an empty file) in `.ps57`, and writes the mesh program last in `.m57`. The offline reader validates the request key and stage exports. It translates a mesh program of one group-memory shape, with a pixel program, to `.ms57.hlsl` and `.ps57.hlsl` -and compiles them as `ms_6_5` and `ps_6_0`. In that shape lane 0 of wave 0 +and compiles them as `ms_6_5` and `ps_6_0` (without a pixel program, to +`.ms57.hlsl` alone; see below). In that shape lane 0 of wave 0 stores the primitive and vertex counts, every wave passes a barrier, wave 0 sends one allocation request and the other wave reads the counts back; the code around it is straight-line and exports vertex and primitive `thread` @@ -9270,10 +9271,17 @@ the published bytes and key, compiles the recorded pair with its serialized root, and compares all 1,024 desktop readback pixels with the CPU reference. The one-pixel negative control uses that same published pair. -The pending scan checks the DXContainer header and file length for both -slot 57 bytecode artifacts. A missing or truncated artifact leaves the -request pending even if its manifest exists. In manifest-only mode the -manifest still completes the request. +The translator also accepts the same slot 57 mesh shape with an empty +`req_.ps57`. It emits the mesh stage alone, keeping position and +primitive exports, and records `ps none` in `.ms57.txt`. A null-export +depth-only pixel stage is still refused. Run +`python -B tests/startup_mesh57_skeleton_check.py` for the source and cache +checks, or run the `startup_mesh57_skeleton` CTest checks below for the DXC mode. + +The pending scan checks the DXContainer header and file length for every +required slot 57 bytecode artifact. A `ps none` result needs the mesh artifact +only. A missing or truncated required artifact leaves the request pending +even if its manifest exists. In manifest-only mode the manifest completes it. Set `X2W_REFUSE_FIXED_MESH=1` to report unavailable fixed mesh pipelines at slot 57 creation. The descriptor must name a registered root, have an empty diff --git a/tests/startup_gfx2hlsl_watch_check.py b/tests/startup_gfx2hlsl_watch_check.py index aacda35a9..99e552a10 100644 --- a/tests/startup_gfx2hlsl_watch_check.py +++ b/tests/startup_gfx2hlsl_watch_check.py @@ -104,7 +104,8 @@ def mesh57_fixture(ms, ps, expected, tamper=False): pixel = struct.pack('<3I', 0xf800080f, 0x03020100, endpgm) vertex = struct.pack('<3I', *position, endpgm) mesh57_fixture(mesh, pixel, 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') -mesh57_fixture(mesh, b'', 'slot 57 mesh without a pixel stage is not covered') +# A pair without a pixel stage is translated when the mesh has the accepted shape; this synthetic mesh does not. +mesh57_fixture(mesh, b'', 'slot 57 mesh group-index exchange: instruction 1 of the accepted shape (s_mov_b64) is absent') mesh57_fixture(vertex, pixel, 'slot 57 mesh stage has no verified allocation and primitive export') # A pixel stage whose only export is the null target (done, vm, no channels) is a depth-only stage and passes the role check. null_export = struct.pack('<3I', 0xf8001890, 0, endpgm) diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 04c032521..ba0c10bcc 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -126,6 +126,10 @@ def controls(): names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) expect('published files', names, ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) expect('a translated request is not pending', G.pending_keys(tmp, False), []) + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + expect('paired manifest stage information', + [line for line in manifest if line.startswith(('params ', 'targets ', 'ps '))], + ['params 1', 'targets 0']) text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() body = [line.strip() for line in text[text.index('void main('):].splitlines()] want = ['if (tid == 0u) { lds[0] = s13; lds[1] = s14; }', 'GroupMemoryBarrierWithGroupSync();', @@ -145,11 +149,38 @@ def controls(): expect(what + ': only the refusal is published', sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), ['%016x.fail' % key]) with tempfile.TemporaryDirectory() as tmp: - ms, blob = code(MESH), root() - key = G.mesh57_key(ms, b'', blob) - for ext, data in (('.root', blob), ('.ps57', b''), ('.m57', ms)): - (Path(tmp) / ('req_%016x%s' % (key, ext))).write_bytes(data) - expect('no pixel stage', G.translate_request(tmp, key), 'unsupported: slot 57 mesh without a pixel stage is not covered') + key, result = request(tmp, MESH, []) + expect('the fixture translates without a pixel stage', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('mesh-only source and manifest', names, ['.ms57.hlsl', '.ms57.txt']) + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + expect('mesh-only manifest stage information', + [line for line in manifest if line.startswith(('params ', 'targets ', 'ps '))], + ['params 0', 'ps none']) + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect('mesh-only vertex fields', re.findall(r'struct VSOut \{([^}]*)\}', text), ['\n float4 pos : SV_Position;\n']) + expect('mesh-only shader omits parameter writes', re.findall(r'\bo\.[fh]?param\d+', text), []) + expect('mesh-only shader writes position and indices', 'o.pos =' in text and 'tris[tid] =' in text, True) + expect('mesh-only manifest is enough in source-only mode', G.pending_keys(tmp, False), []) + paired, result = request(tmp, MESH) + expect('paired request for polling translates', result, 'ok') + paired_text = (Path(tmp) / ('%016x.ms57.hlsl' % paired)).read_text() + expect('mesh-only shader keeps every mesh_vertex mark of the pair', + text.count('mesh_vertex = true'), paired_text.count('mesh_vertex = true')) + # The poller needs a complete container envelope, without compiling a shader here. + part = struct.pack('<4sI4s', b'DXIL', 4, b'test') + bytecode = struct.pack('<4s16sHHIII', b'DXBC', bytes(16), 1, 0, 36 + len(part), 1, 36) + part + os.environ.pop('X2W_FXC') + mesh_bytecode = Path(tmp) / ('%016x.ms57.cso' % key) + mesh_bytecode.write_bytes(bytecode) + (Path(tmp) / ('%016x.ms57.cso' % paired)).write_bytes(bytecode) + expect('only the pair missing its pixel bytecode is pending', G.pending_keys(tmp, False), [paired]) + mesh_bytecode.write_bytes(bytecode[:-1]) + expect('mesh-only result with truncated bytecode is pending', G.pending_keys(tmp, False), sorted([key, paired])) + mesh_bytecode.unlink() + expect('mesh-only result missing mesh bytecode is pending', G.pending_keys(tmp, False), sorted([key, paired])) + os.environ['X2W_FXC'] = '' # exp null off, off, off, off done vm; s_endpgm: a pixel stage without a colour output. with tempfile.TemporaryDirectory() as tmp: expect('a depth-only pixel stage', request(tmp, MESH, 'f8001890 00000000 bf810000'.split())[1], @@ -263,6 +294,13 @@ def publish_request(directory, publisher, adapter): def draw(dxc, renderer, adapter, publisher=None): os.environ['X2W_DXC'] = dxc os.environ.pop('X2W_FXC', None) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH, []) + expect('the fixture compiles without a pixel stage', result, 'ok') + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('mesh-only compiled files', names, ['.ms57.cso', '.ms57.hlsl', '.ms57.txt']) + expect('complete mesh-only bytecode was published', + G.has_complete_mesh57_bytecode(Path(tmp) / ('%016x.ms57.cso' % key)), True) points, colours, indices = geometry() with tempfile.TemporaryDirectory() as tmp: if publisher: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 74244559c..5d26a723b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5685,11 +5685,16 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.rect = self.ud(('rect',)) if refusals is None: self.vs = Stage(self, self.vertex_kind, vs_code) - self.ps = Stage(self, 'ps', ps_code) + self.ps = Stage(self, 'ps', ps_code) if ps_code is not None else None else: decoded = {} if decoded is None else decoded self.vs = Stage(self, self.vertex_kind, vs_code, refusals=refusals, decoded=decoded.get('vs')) - self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded.get('ps')) + self.ps = Stage(self, 'ps', ps_code, refusals=refusals, decoded=decoded.get('ps')) if ps_code is not None else None + if self.ps is None: + self.params, self.flat, self.f16_plain = [], [], [] + if 'pos' not in self.vs.exports: + raise Unsupported('vertex stage exports no position') + return self.params = sorted(int(k[5:]) for k in self.vs.exports if k.startswith('param')) self.flat = sorted(a for a, how in self.ps.attrs.items() if 'flat' in how) for a, how in self.ps.attrs.items(): @@ -6014,6 +6019,9 @@ def manifest(self): if self.uses_sampler_heap: lines.append('smpheap %d %d fallback %d' % (SAMPLER_HEAP_SIZE, SAMPLER_HEAP_SPACE, SAMPLER_HEAP_FALLBACK)) lines.append('params %d' % (max(self.params) + 1 if self.params else 0)) + if self.ps is None: + lines.append('ps none') + return '\n'.join(lines) + '\n' lines.append('targets %s' % ' '.join(k[3:] for k in sorted(self.ps.exports) if k.startswith('mrt'))) # 'wmask ': the export leaves the channels outside the mask unwritten, so the # runtime keeps them out of that target's RenderTargetWriteMask. Full masks are not written. @@ -6103,7 +6111,7 @@ def manifest(self): class MeshPipeline(Pipeline): - """A slot 57 mesh and pixel pair. The mesh stage is the vertex-producing stage of the pair (self.vs).""" + """A slot 57 mesh pipeline with an optional pixel stage. The mesh stage is self.vs.""" vertex_kind = 'ms' def hlsl_ms(self): @@ -6114,6 +6122,10 @@ def hlsl_ms(self): re.sub(r' o\.hparam(\d+)_(?:lo|hi) = [^;]*;', lambda m: m[0] if int(m[1]) in self.f16_plain else '', line)) for line in s.body()] + if self.ps is None: + # Nothing reads a parameter without a pixel stage: drop its writes but keep the rest of the export + # line (its exec guard and mesh_vertex = true), as for unread fparam/hparam fields above. + lines = [re.sub(r' o\.param\d+ = [^;]*;', '', line) for line in lines] return '\n'.join( self.common() + ['struct VSOut {'] + self.interface(False) + [ '};', 'groupshared uint lds[2];', '[numthreads(%d, 1, 1)]' % MESH_THREADS, '[outputtopology("triangle")]', @@ -6473,7 +6485,7 @@ def mesh57_key(ms, ps, root): def translate_mesh57(out_dir, key): """Translate a fixed-descriptor mesh request of the accepted shape (mesh_skeleton), or raise Unsupported. - Writes .ms57.hlsl, .ps57.hlsl, the compiled .ms57.cso and .ps57.cso, and .ms57.txt (last). + Writes .ms57.hlsl and the compiled .ms57.cso, their .ps57 counterparts if present, and .ms57.txt (last). No runtime path loads these names yet.""" source = os.path.join(out_dir, 'req_%016x' % key) ms, ps, root = (open(source + ext, 'rb').read() for ext in ('.m57', '.ps57', '.root')) @@ -6494,10 +6506,10 @@ def translate_mesh57(out_dir, key): raise Unsupported('slot 57 pixel stage has an incompatible export or termination') if null_only: raise Unsupported('slot 57 mesh with a depth-only pixel stage is not covered') - if not ps: - raise Unsupported('slot 57 mesh without a pixel stage is not covered') - pipe = MeshPipeline(ms, ps, root) - sources = (('ms', 'ms_6_5', pipe.hlsl_ms()), ('ps', 'ps_6_0', pipe.hlsl_ps())) + pipe = MeshPipeline(ms, ps or None, root) + sources = [('ms', 'ms_6_5', pipe.hlsl_ms())] + if ps: + sources.append(('ps', 'ps_6_0', pipe.hlsl_ps())) manifest = pipe.manifest() name = os.path.join(out_dir, '%016x' % key) for stage, _, hlsl in sources: @@ -6507,7 +6519,7 @@ def translate_mesh57(out_dir, key): if compiler is None: raise Unsupported('dxc not found (X2W_DXC=%s): a mesh stage needs shader model 6.5' % os.environ.get('X2W_DXC', '')) import subprocess - # Publish only bytecode from a successful pair. + # Publish bytecode only after all requested stages compile successfully. with tempfile.TemporaryDirectory(prefix='.dxc-', dir=out_dir) as staging: for stage, profile, _ in sources: bytecode = os.path.join(staging, stage + '.cso') @@ -6870,8 +6882,13 @@ def pending_keys(out_dir, skip_failed): ready_bytecode = has_complete_mesh57_bytecode if mesh else has_bytecode manifest = result + ('.ms57.txt' if mesh else '.txt') # A published manifest with bytecode (or manifest-only mode) is done; otherwise resume (#2008). - if os.path.isfile(manifest) and (manifest_only or all(ready_bytecode(result + s) for s in stages)): - continue + if os.path.isfile(manifest): + if manifest_only or all(ready_bytecode(result + s) for s in stages): + continue + if mesh and has_complete_mesh57_bytecode(result + '.ms57.cso'): + with suppress(OSError), open(manifest, 'rb') as published: + if b'ps none' in published.read().splitlines(): + continue fail = os.path.join(out_dir, '%016x.fail' % key) # A repeated pass retries a failure only once its request is rewritten. if skip_failed and os.path.exists(fail) and os.path.getmtime(fail) >= os.path.getmtime(os.path.join(out_dir, name)): From ce530846a8fe6acf41bd060faf09c821c1bed448 Mon Sep 17 00:00:00 2001 From: Maledetto Date: Wed, 25 Nov 2026 21:22:13 +0100 Subject: [PATCH 148/232] startup: refuse NEG on an inline-integer or literal VOP3 source in gfx2hlsl (#2529) * startup: refuse VOP3 NEG on a non-negative integer inline or literal The decoder prints inline 1 with NEG as -1, the text of inline -1, so the two encodings translated to the same 0xffffffff, and a literal 5 with NEG became 0xfffffffb. Refuse NEG (w1[31:29]) on an inline 0..64 or literal source of any VOP3 instruction except the v_cndmask_b32_e64 data sources, which model NEG as the sign bit flipped. Inline floats, registers and negative inlines are unchanged; ABS is not tested because it is SDST on the VOP3b forms. * docs: record the NEG refusal on inline-integer VOP3 sources --------- Co-authored-by: Maledetto <20729264+Makto94@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 2 + tests/startup_gfx2hlsl_refusals_check.py | 112 +++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 14 +++ 3 files changed, 128 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index b14397347..6f76d654f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13853,6 +13853,8 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp16_' -V python -B tests/startup_gfx2hlsl_cmp16_check.py binary ``` +`tools/startup/gfx2hlsl.py` also refuses the NEG bit of a VOP3 source that is a non-negative inline integer (0 to 64) or a literal. The disassembler prints inline 1 with NEG as `-1`, the same text as inline -1, so the text cannot tell the two encodings apart. The exception is the two data operands of `v_cndmask_b32_e64`, which model NEG as a flip of bit 31. The hardware behavior of NEG on integer sources is not measured. Check: `tests/startup_gfx2hlsl_refusals_check.py`. + ## Startup translator: explicit-LOD image sampling `tools/startup/gfx2hlsl.py` now lowers the gfx1013 `image_sample_l` form of a 2D or 3D texture sample to `tex.SampleLevel(smp, uv, level)`. The level is the last address register: the third for a contiguous 2D address, the fourth for 3D, and the last element of an NSA list. `tests/startup_image_sample_l_check.py` translates source-built fixtures (the words are checked against `llvm-mc`) and requires the level to come from that register; an address list `[v0, v1, v3]` must use `v3`, not the third consecutive register. Replacing the level with 0, replacing the call with implicit `Sample`, or reading the third register in every form each make the check fail. Offset (`_o`), compare (`_c_l`), gather, 1D, array, cube and multisample dimensions, an empty `dmask`, and the `unorm`, `r128`, `tfe`, `lwe`, `a16` and `d16` modifiers or any set reserved MIMG bit are refused with an `Unsupported` message; only the cache-policy bits `glc`, `slc` and `dlc` are accepted because they do not change the sampled value. The disassembler previously read `lwe` from reserved bit 14 of word 0; `llvm-mc` (19, gfx1013) encodes it in bit 17, and the check now has one `llvm-mc`-built fixture per refused modifier plus patched reserved-bit fixtures. Not measured: no draw samples a mip level on WARP or hardware through this lowering, so the level selection is checked on the generated HLSL text only. [HLSL SampleLevel](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-samplelevel) diff --git a/tests/startup_gfx2hlsl_refusals_check.py b/tests/startup_gfx2hlsl_refusals_check.py index 4f1f77b6d..f2f22d966 100644 --- a/tests/startup_gfx2hlsl_refusals_check.py +++ b/tests/startup_gfx2hlsl_refusals_check.py @@ -72,6 +72,117 @@ def broken(self, ops, mods): found == preceding + [(label + ' in v_census_probe: TypeError', 'ps'), (SECOND, 'ps')]) +class Probe(G.Stage): + """A Stage with no pipeline: enough state for decoded instructions to be translated.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.masks = set() + self.exec_known = True + + +def vop3(op, srcs, vdst=4, sdst=0, neg=0, absolute=0, literal=None): + """One VOP3 instruction: w0 = 0b110101 | op | abs | SDST (VOP3b) or VDST, w1 = three 9-bit sources | NEG.""" + w0 = (0b110101 << 26) | (op << 16) | (absolute << 8) | (sdst << 8) | vdst + w1 = srcs[0] | (srcs[1] << 9) | (srcs[2] << 18) | (neg << 29) + return struct.pack('<2I', w0, w1) + (b'' if literal is None else struct.pack(' 100 and cndmask in accepted) + loose = [] + for op in accepted: + for slot in range(3): + srcs = list(sentinels) + srcs[slot] = inline(1) + plain = translate_one(vop3(op, srcs)) + result = translate_one(vop3(op, srcs, neg=1 << slot)) + modeled = op == cndmask and slot < 2 + if isinstance(plain, str) or modeled: + continue + # Ops with their own, earlier refusal of NEG and ABS (the 16-bit compares, v_sad_*) keep it. + if not (isinstance(result, str) and ('NEG on an integer or literal source %d' % slot in result + or ' with neg/abs' in result)): + loose.append((hex(op), slot, result)) + check('NEG on inline 1 is refused for every accepted opcode and slot except v_cndmask_b32_e64 data sources', + not loose) + if loose: + print(' first misses: %s' % loose[:4]) + + def refused(code, slot): + text = translate_one(code) + return isinstance(text, str) and 'NEG on an integer or literal source %d' % slot in text + + iadd, fadd, cmp_lt, add_co, shl64 = names['v_mad_u32_u24'], 0x103, 0x81, names['v_add_co_u32'], names['v_lshlrev_b64'] + for slot in range(3): + srcs = list(sentinels) + srcs[slot] = inline(1) + check('v_mad_u32_u24 slot %d: inline 1 with NEG refused' % slot, + refused(vop3(iadd, srcs, neg=1 << slot), slot)) + check('v_mad_u32_u24 slot %d: the same word without NEG still translates' % slot, + not isinstance(translate_one(vop3(iadd, srcs)), str)) + check('inline 0 with NEG refused', refused(vop3(iadd, [inline(0), sentinels[1], sentinels[2]], neg=1), 0)) + check('inline 64 with NEG refused', refused(vop3(iadd, [inline(64), sentinels[1], sentinels[2]], neg=1), 0)) + check('literal with NEG refused', refused(vop3(iadd, [255, sentinels[1], sentinels[2]], neg=1, literal=5), 0)) + check('literal without NEG translates', not isinstance( + translate_one(vop3(iadd, [255, sentinels[1], sentinels[2]], literal=5)), str)) + check('v_add_f32_e64 with an integer inline and NEG refused', refused(vop3(fadd, [inline(1), v(12), 0], neg=1), 0)) + check('compare with inline 1 and NEG refused', refused(vop3(cmp_lt, [inline(1), v(12), 0], sdst=4, neg=1), 0)) + check('compare slot 1 with literal and NEG refused', refused( + vop3(cmp_lt, [v(10), 255, 0], sdst=4, neg=2, literal=7), 1)) + check('v_add_co_u32 (carry out) with inline 1 and NEG refused', + refused(vop3(add_co, [inline(1), v(12), 0], sdst=4, neg=1), 0)) + check('v_lshlrev_b64 with NEG on the shift inline refused', refused(vop3(shl64, [inline(1), v(12), 0], neg=1), 0)) + + # Negative controls. + minus_one = translate_one(vop3(iadd, [193, sentinels[1], sentinels[2]])) + check('plain inline -1 still reads 0xffffffff', + not isinstance(minus_one, str) and '0xffffffffu' in ' '.join(minus_one[1])) + negative = translate_one(vop3(iadd, [193, sentinels[1], sentinels[2]], neg=1)) + check('inline -1 with NEG is not refused by this rule', + not (isinstance(negative, str) and 'NEG on an integer' in negative)) + for code in range(240, 249): + result = translate_one(vop3(fadd, [code, v(12), 0], neg=1)) + check('inline float %d with NEG is not refused by this rule' % code, + not (isinstance(result, str) and 'NEG on an integer' in result)) + check('v_add_co_u32 with sdst s4 and register sources translates', + not isinstance(translate_one(vop3(add_co, [v(10), v(12), 0], sdst=4)), str)) + check('v_add_co_u32 with sdst s4 and an inline source translates', + not isinstance(translate_one(vop3(add_co, [inline(1), v(12), 0], sdst=4)), str)) + for slot in range(2): + srcs = [v(10), v(12), 106] + srcs[slot] = inline(1) + result = translate_one(vop3(cndmask, srcs, neg=1 << slot)) + check('v_cndmask_b32_e64 slot %d: inline 1 with NEG still translates' % slot, + not isinstance(result, str) and '0x80000001u' in ' '.join(result[1])) + check('v_cndmask_b32_e64 mask slot: inline 1 with NEG is refused', + refused(vop3(cndmask, [v(10), v(12), inline(1)], neg=4), 2)) + + def check_decode(): code = struct.pack('<2I', 0, END) with patch.object(G.D, 'decode_instruction', decode_instruction), patch.object( @@ -314,6 +425,7 @@ def check_normalization(): with patch.dict(os.environ, {'X2W_FXC': ''}): check_stage() check_decode() + check_neg_integer_sources() check_cli() check_request_failures() check_pairs() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 5d26a723b..f4613d11f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -409,6 +409,20 @@ def check_encoding(code, off, n, name, asm): operand = fields[i + 1] fields[i + 1] = operand[:len(operand) - len(operand.lstrip())] + '0x%08x' % (bits ^ 0x80000000) asm = ','.join(fields) + if n >= 8 and struct.unpack_from('> 26 == 0b110101: + # VOP3 NEG (w1[31:29], bit 29 + i for source i) on a non-negative inline integer (128..192) or a literal (255). + # The decoder prints inline 1 with NEG as `-1`, the text of the plain inline -1 (193), so both would translate to + # 0xffffffff, and a literal 5 would become 0xfffffffb. Only v_cndmask_b32_e64 models NEG on its two data + # sources (above, as the sign bit flipped). Inline floats, registers and negative inlines are not affected. + # ABS is not tested: on the VOP3b forms w0[10:8] is SDST, not a modifier. + word1, = struct.unpack_from('> (9 * i)) & 0x1ff + if 128 <= source <= 192 or source == 255: + raise Unsupported('%s with NEG on an integer or literal source %d: the printed sign would read as inline -N' + % (name, i)) return asm From 780f3c0a914f19af211f86178879cfafdbf78a6a Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:22:49 +0200 Subject: [PATCH 149/232] cpu: add dedicated cpu_x87_exp_log_aot lifter for F2XM1, FYL2X, and FYL2XP1 (#2423) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 19 + tests/cpu/x87_exp_log_aot.asm | 282 +++++++ tests/cpu/x87_exp_log_aot.def | 22 + tests/cpu/x87_exp_log_aot_check.py | 1031 +++++++++++++++++++++++ tools/cpu_x87_exp_log_aot.py | 1239 ++++++++++++++++++++++++++++ 5 files changed, 2593 insertions(+) create mode 100644 tests/cpu/x87_exp_log_aot.asm create mode 100644 tests/cpu/x87_exp_log_aot.def create mode 100644 tests/cpu/x87_exp_log_aot_check.py create mode 100644 tools/cpu_x87_exp_log_aot.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b85216ccf..cffb43f70 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7297,6 +7297,25 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME cpu_aot_x87_trig COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/x87_trig.py" check "$" "$" "$" ${x87_trig_control_files}) + set(cpu_x87_exp_log_aot_exports + "op_f2xm1_m80,op_f2xm1_m64,op_f2xm1_m32,op_f2xm1_fst_m64,op_f2xm1_fst_m32,op_f2xm1_sw," + "op_fyl2x_m80,op_fyl2x_m64,op_fyl2x_m32,op_fyl2x_sw,op_fyl2x_pop_depth,op_fyl2x_depth8," + "op_fyl2xp1_m80,op_fyl2xp1_m64,op_fyl2xp1_m32,op_fyl2xp1_sw,op_fyl2xp1_pop_depth," + "op_exp_log_roundtrip,op_fcw_roundtrip,op_fninit_cw_sw,op_fninit_sw") + string(CONCAT cpu_x87_exp_log_aot_exports ${cpu_x87_exp_log_aot_exports}) + foreach(variant IN ITEMS original altered) + cpu_asm_fixture(cpu_x87_exp_log_aot_${variant} x87_exp_log_aot) + cpu_translation(cpu_x87_exp_log_aot_${variant} cpu_x87_exp_log_aot "${cpu_x87_exp_log_aot_exports}") + endforeach() + target_compile_definitions(cpu_x87_exp_log_aot_altered PRIVATE ALTER_X87_EXP_LOG) + add_test(NAME cpu_aot_x87_exp_log COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu/x87_exp_log_aot_check.py" + "$" + "$" + "$" + "$") + set_tests_properties(cpu_aot_x87_exp_log PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/cpu_aot_x87_exp_log.txt") cpu_asm_fixture(cpu_create create_context) set(create_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_create_lifted.cpp") add_custom_command(OUTPUT "${create_fixture}" diff --git a/tests/cpu/x87_exp_log_aot.asm b/tests/cpu/x87_exp_log_aot.asm new file mode 100644 index 000000000..e402f4515 --- /dev/null +++ b/tests/cpu/x87_exp_log_aot.asm @@ -0,0 +1,282 @@ +; coverage: record cpu_aot_x87_exp_log +; Source-owned differential fixture for x87 F2XM1, FYL2X, and FYL2XP1 plus +; bounded x87 stack/control/status transport over flat [rcx|rdx|r8] memory. +; RCX = const void* input_a (m32/m64/m80 operand or m16 control word) +; RDX = const void* input_b (m32/m64/m80 operand or m16 control word) +; R8 = void* output (m32/m64/m80/m16 output; also carries input m16 +; control word on binary FYL2X/FYL2XP1 exports) +.code + +op_f2xm1_m80 PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld tbyte ptr [rcx] +IFDEF ALTER_X87_EXP_LOG + fldz + fyl2xp1 +ELSE + f2xm1 +ENDIF + fstp tbyte ptr [r8] + ret +op_f2xm1_m80 ENDP + +op_f2xm1_m64 PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld qword ptr [rcx] + f2xm1 + fstp qword ptr [r8] + ret +op_f2xm1_m64 ENDP + +op_f2xm1_m32 PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld dword ptr [rcx] + f2xm1 + fstp dword ptr [r8] + ret +op_f2xm1_m32 ENDP + +op_f2xm1_fst_m64 PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld qword ptr [rcx] + f2xm1 + fst qword ptr [r8] + fstp st(0) + ret +op_f2xm1_fst_m64 ENDP + +op_f2xm1_fst_m32 PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld dword ptr [rcx] + f2xm1 + fst dword ptr [r8] + fstp st(0) + ret +op_f2xm1_fst_m32 ENDP + +op_f2xm1_sw PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld tbyte ptr [rcx] + f2xm1 + fnstsw ax + fstp st(0) + mov word ptr [r8], ax + ret +op_f2xm1_sw ENDP + +op_fyl2x_m80 PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] +IFDEF ALTER_X87_EXP_LOG + fyl2xp1 +ELSE + fyl2x +ENDIF + fstp tbyte ptr [r8] + ret +op_fyl2x_m80 ENDP + +op_fyl2x_m64 PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld qword ptr [rcx] + fld qword ptr [rdx] + fyl2x + fstp qword ptr [r8] + ret +op_fyl2x_m64 ENDP + +op_fyl2x_m32 PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld dword ptr [rcx] + fld dword ptr [rdx] + fyl2x + fstp dword ptr [r8] + ret +op_fyl2x_m32 ENDP + +op_fyl2x_sw PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] + fyl2x + fnstsw ax + fstp st(0) + mov word ptr [r8], ax + ret +op_fyl2x_sw ENDP + +; Verifies FYL2X pops ST(0) and preserves the underlying stack slot (+1.0 sentinel). +op_fyl2x_pop_depth PROC FRAME + .endprolog + fninit + fld1 + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] + fyl2x + fstp st(0) + fstp tbyte ptr [r8] + ret +op_fyl2x_pop_depth ENDP + +; Exercises FYL2X at maximum x87 stack depth (8 entries) and unwinds cleanly. +op_fyl2x_depth8 PROC FRAME + .endprolog + fninit + fldz + fldz + fldz + fldz + fldz + fldz + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] + fyl2x + fstp tbyte ptr [r8] + fstp st(0) + fstp st(0) + fstp st(0) + fstp st(0) + fstp st(0) + fstp st(0) + ret +op_fyl2x_depth8 ENDP + +op_fyl2xp1_m80 PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] +IFDEF ALTER_X87_EXP_LOG + fyl2x +ELSE + fyl2xp1 +ENDIF + fstp tbyte ptr [r8] + ret +op_fyl2xp1_m80 ENDP + +op_fyl2xp1_m64 PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld qword ptr [rcx] + fld qword ptr [rdx] + fyl2xp1 + fstp qword ptr [r8] + ret +op_fyl2xp1_m64 ENDP + +op_fyl2xp1_m32 PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld dword ptr [rcx] + fld dword ptr [rdx] + fyl2xp1 + fstp dword ptr [r8] + ret +op_fyl2xp1_m32 ENDP + +op_fyl2xp1_sw PROC FRAME + .endprolog + fninit + fldcw word ptr [r8] + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] + fyl2xp1 + fnstsw ax + fstp st(0) + mov word ptr [r8], ax + ret +op_fyl2xp1_sw ENDP + +; Verifies FYL2XP1 pops ST(0) and preserves the underlying stack slot (+0.0 sentinel). +op_fyl2xp1_pop_depth PROC FRAME + .endprolog + fninit + fldz + fld tbyte ptr [rcx] + fld tbyte ptr [rdx] + fyl2xp1 + fstp st(0) + fstp tbyte ptr [r8] + ret +op_fyl2xp1_pop_depth ENDP + +; Composition: 2^(1 * log2(x + 1)) - 1 == x for x in [-(1-sqrt(2)/2), 1-sqrt(2)/2]. +op_exp_log_roundtrip PROC FRAME + .endprolog + fninit + fldcw word ptr [rdx] + fld1 + fld tbyte ptr [rcx] + fyl2xp1 +IFDEF ALTER_X87_EXP_LOG + fstp st(0) + fldz +ELSE + f2xm1 +ENDIF + fstp tbyte ptr [r8] + ret +op_exp_log_roundtrip ENDP + +; Control word transport: fldcw -> fnstcw preserves rounding and precision control bits. +op_fcw_roundtrip PROC FRAME + .endprolog + fninit +IFDEF ALTER_X87_EXP_LOG + fld1 + fstp st(0) +ELSE + fldcw word ptr [rcx] +ENDIF + fnstcw word ptr [r8] + ret +op_fcw_roundtrip ENDP + +; FNINIT resets FCW to 0x037F and empties any live x87 stack entries. +op_fninit_cw_sw PROC FRAME + .endprolog + fldcw word ptr [rcx] + fld tbyte ptr [rdx] + f2xm1 + fninit + fnstcw word ptr [r8] + ret +op_fninit_cw_sw ENDP + +; FNINIT clears sticky status flags and resets TOP to 0. +op_fninit_sw PROC FRAME + .endprolog + fld tbyte ptr [rcx] + f2xm1 + fninit + fnstsw ax + mov word ptr [r8], ax + ret +op_fninit_sw ENDP + +END diff --git a/tests/cpu/x87_exp_log_aot.def b/tests/cpu/x87_exp_log_aot.def new file mode 100644 index 000000000..b877b8735 --- /dev/null +++ b/tests/cpu/x87_exp_log_aot.def @@ -0,0 +1,22 @@ +EXPORTS + op_f2xm1_m80 + op_f2xm1_m64 + op_f2xm1_m32 + op_f2xm1_fst_m64 + op_f2xm1_fst_m32 + op_f2xm1_sw + op_fyl2x_m80 + op_fyl2x_m64 + op_fyl2x_m32 + op_fyl2x_sw + op_fyl2x_pop_depth + op_fyl2x_depth8 + op_fyl2xp1_m80 + op_fyl2xp1_m64 + op_fyl2xp1_m32 + op_fyl2xp1_sw + op_fyl2xp1_pop_depth + op_exp_log_roundtrip + op_fcw_roundtrip + op_fninit_cw_sw + op_fninit_sw diff --git a/tests/cpu/x87_exp_log_aot_check.py b/tests/cpu/x87_exp_log_aot_check.py new file mode 100644 index 000000000..3e452bcfa --- /dev/null +++ b/tests/cpu/x87_exp_log_aot_check.py @@ -0,0 +1,1031 @@ +"""Differential, mathematical-reference, MXCSR-isolation, FCW, mutation, and rejection checks +for x87 F2XM1, FYL2X, and FYL2XP1 AOT lifting (`tools/cpu_x87_exp_log_aot.py`). + +Tested domains and precision bounds (80-bit extended, 64-bit explicit significand): + - F2XM1 : Intel SDM domain [-1, +1]; exact on +-0, +1, -1; lifted vs arbitrary-precision + Decimal reference <= 1 ULP (observed 0 ULP); lifted vs native x87 <= 1 ULP. + - FYL2X : x > 0 plus all SDM special cases (x <= 0, +-inf, NaN, unnormal); exact on + x == 1 and powers of 2 with exact products; lifted vs reference <= 1 ULP; + lifted vs native x87 <= 1 ULP. + - FYL2XP1 : Intel SDM domain [-(1 - sqrt(2)/2), +(1 - sqrt(2)/2)] plus SDM special cases + (+-0, NaN, unnormal); lifted vs reference <= 1 ULP; lifted vs native x87 <= 1 ULP. + Outside the SDM domain, x == -1 (#Z for finite nonzero y, #IA for y == +-0) and + x < -1 (#IA) are checked on the lifted DLL against the mathematical spec, because + hardware results outside [-(1 - sqrt(2)/2), 1 - sqrt(2)/2] are SDM-undefined. +""" + +import ctypes +from decimal import Decimal, getcontext +import os +from pathlib import Path +import random +import struct +import sys + +from iced_x86 import ( + Code, + Decoder, + Encoder, + Formatter, + FormatterSyntax, + Instruction, + MemoryOperand, + Register as R, +) +import pefile + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import bounded_code, export_rva # noqa: E402 +from cpu_x87_exp_log_aot import lift_code # noqa: E402 + +getcontext().prec = 80 +DEC_LN2 = Decimal(2).ln() + +EXPORTS = ( + "op_f2xm1_m80", + "op_f2xm1_m64", + "op_f2xm1_m32", + "op_f2xm1_fst_m64", + "op_f2xm1_fst_m32", + "op_f2xm1_sw", + "op_fyl2x_m80", + "op_fyl2x_m64", + "op_fyl2x_m32", + "op_fyl2x_sw", + "op_fyl2x_pop_depth", + "op_fyl2x_depth8", + "op_fyl2xp1_m80", + "op_fyl2xp1_m64", + "op_fyl2xp1_m32", + "op_fyl2xp1_sw", + "op_fyl2xp1_pop_depth", + "op_exp_log_roundtrip", + "op_fcw_roundtrip", + "op_fninit_cw_sw", + "op_fninit_sw", +) + +ALTERED_EXPORTS = ( + "op_f2xm1_m80", + "op_fyl2x_m80", + "op_fyl2xp1_m80", + "op_exp_log_roundtrip", + "op_fcw_roundtrip", +) + +GUARD_PRE = bytes(range(0xA0, 0xB0)) +GUARD_POST = bytes(range(0xC0, 0xD0)) + +J = 1 << 63 +QBIT = 1 << 62 +MASKED_CWS = [0x007F | (pc << 8) | (rc << 10) for pc in (0, 2, 3) for rc in range(4)] + +SW_IE = 0x0001 +SW_DE = 0x0002 +SW_ZE = 0x0004 +SW_OE = 0x0008 +SW_UE = 0x0010 +SW_PE = 0x0020 +SW_TOP_MASK = 0x3800 +# Mandatory architectural status flags compared strictly against native hardware: +# IE, DE, ZE, OE, UE, SF(0x40), ES(0x80), TOP(0x3800), B(0x8000). +SW_STRICT_MASK = SW_IE | SW_DE | SW_ZE | SW_OE | SW_UE | 0x00C0 | SW_TOP_MASK | 0x8000 + +POS_ZERO = (0, 0x0000) +NEG_ZERO = (0, 0x8000) +POS_ONE = (J, 0x3FFF) +NEG_ONE = (J, 0xBFFF) +POS_HALF = (J, 0x3FFE) +NEG_HALF = (J, 0xBFFE) +POS_TWO = (J, 0x4000) +POS_FOUR = (J, 0x4001) +POS_INF = (J, 0x7FFF) +NEG_INF = (J, 0xFFFF) +INDEF = (J | QBIT, 0xFFFF) +QNAN_A = (J | QBIT | 0x12345678, 0x7FFF) +QNAN_B = (J | QBIT | 0x00000042, 0xFFFF) +SNAN_A = (J | 0x00005678, 0x7FFF) +SNAN_B = (J | 0x00009ABC, 0xFFFF) +UNNORM = (0x0000123456789ABC, 0x3FFF) +SUB_POS_MIN = (1, 0x0000) +SUB_NEG_MIN = (1, 0x8000) +SUB_POS_MID = (0x0000123456789ABC, 0x0000) +SUB_NEG_MID = (0x0000123456789ABC, 0x8000) +TINY_NORM_POS = (J, 0x0001) +TINY_NORM_NEG = (J, 0x8001) +HUGE_POS = (0xFFFFFFFFFFFFFFFF, 0x7FFE) +HUGE_NEG = (0xFFFFFFFFFFFFFFFF, 0xFFFE) + + +# --- 80-bit extended encoding/decoding & ULP distance --- + +def pack80(val): + return struct.pack("= scale * two: + e += 1 + scale = two ** e + biased = e + 16383 + if biased <= 0: + # Denormal: unit is 2^(1 - 16383 - 63) = 2^-16445. + q = mag * (two ** 16445) + fl = int(q) + rem = q - fl + up = _round_dir(sign, fl, rem, rc) + sig = fl + (1 if up else 0) + if sig >= J: + return (sig, (sign << 15) | 1) + return (sig, (sign << 15)) + q = (mag / scale) * (1 << 63) + fl = int(q) + rem = q - fl + up = _round_dir(sign, fl, rem, rc) + sig = fl + (1 if up else 0) + if sig >= (1 << 64): + sig = J + biased += 1 + if biased > 0x7FFE: + to_inf = (rc == 0) or (rc == 1 and sign) or (rc == 2 and not sign) + if to_inf: + return (J, (sign << 15) | 0x7FFF) + return (0xFFFFFFFFFFFFFFFF, (sign << 15) | 0x7FFE) + return (sig, (sign << 15) | biased) + + +def _round_dir(sign, fl, rem, rc): + if rem == 0: + return False + if rc == 0: + half = Decimal("0.5") + return rem > half or (rem == half and (fl & 1) != 0) + if rc == 1: + return bool(sign) + if rc == 2: + return not bool(sign) + return False + + +def m80_to_decimal(val): + sig, se = val + sign = (se >> 15) & 1 + exp = se & 0x7FFF + assert exp != 0x7FFF and (exp == 0 or (sig & J)), f"non-finite/unsupported m80 {val}" + if exp == 0 and sig == 0: + return Decimal("-0") if sign else Decimal("0") + unbiased = (1 - 16383 - 63) if exp == 0 else (exp - 16383 - 63) + mag = Decimal(sig) * (Decimal(2) ** unbiased) + return -mag if sign else mag + + +def m80_is_finite(val): + sig, se = val + exp = se & 0x7FFF + return exp != 0x7FFF and (exp == 0 or (sig & J) != 0) + + +def m80_ordinal(val): + """Monotonic signed integer index over all canonical finite 80-bit encodings (1 step = 1 ULP).""" + sig, se = val + sign = (se >> 15) & 1 + exp = se & 0x7FFF + if exp == 0: + idx = sig + else: + idx = (exp << 63) | (sig & (J - 1)) + return -idx if sign else idx + + +def m80_ulp_diff(a, b): + if a == b: + return 0 + if not (m80_is_finite(a) and m80_is_finite(b)): + return 1 << 64 + # Require matching sign of zero when both are zero. + if (a[0] == 0 and (a[1] & 0x7FFF) == 0) or (b[0] == 0 and (b[1] & 0x7FFF) == 0): + if a[1] != b[1] and a[0] == 0 and b[0] == 0: + return 1 << 64 + return abs(m80_ordinal(a) - m80_ordinal(b)) + + +def f64_ulp_diff(a_bytes, b_bytes): + if a_bytes == b_bytes: + return 0 + a = struct.unpack("> 63) else a + sb = -(b & 0x7FFFFFFFFFFFFFFF) if (b >> 63) else b + return abs(sa - sb) + + +def f32_ulp_diff(a_bytes, b_bytes): + if a_bytes == b_bytes: + return 0 + a = struct.unpack("> 31) else a + sb = -(b & 0x7FFFFFFF) if (b >> 31) else b + return abs(sa - sb) + + +# --- Independent arbitrary-precision Python reference --- + +def ref_f2xm1(x, cw=0x037F): + rc = (cw >> 10) & 3 + if x == POS_ZERO or x == NEG_ZERO: + return x + if x == POS_ONE: + return POS_ONE + if x == NEG_ONE: + return NEG_HALF + if x == POS_INF: + return POS_INF + if x == NEG_INF: + return NEG_ONE + dx = m80_to_decimal(x) + # 2^x - 1 = exp(x * ln(2)) - 1; for tiny |x|, use Taylor series to avoid Decimal cancellation. + u = dx * DEC_LN2 + if abs(u) < Decimal("1e-20"): + exact = u + (u * u) / 2 + (u * u * u) / 6 + else: + exact = u.exp() - Decimal(1) + return m80_from_decimal(exact, rc=rc) + + +def ref_fyl2x(y, x, cw=0x037F): + rc = (cw >> 10) & 3 + dx = m80_to_decimal(x) + dy = m80_to_decimal(y) + assert dx > 0 + if dx == 1: + return NEG_ZERO if (y[1] & 0x8000) else POS_ZERO + if dy == 0: + sign = ((y[1] >> 15) & 1) ^ (1 if dx < 1 else 0) + return NEG_ZERO if sign else POS_ZERO + exact = dy * (dx.ln() / DEC_LN2) + return m80_from_decimal(exact, rc=rc) + + +def ref_fyl2xp1(y, x, cw=0x037F): + rc = (cw >> 10) & 3 + dx = m80_to_decimal(x) + dy = m80_to_decimal(y) + assert dx > -1 + if dx == 0: + sign = ((y[1] >> 15) & 1) ^ ((x[1] >> 15) & 1) + return NEG_ZERO if sign else POS_ZERO + if dy == 0: + sign = ((y[1] >> 15) & 1) ^ ((x[1] >> 15) & 1) + return NEG_ZERO if sign else POS_ZERO + if abs(dx) < Decimal("1e-20"): + ln1p = dx - (dx * dx) / 2 + (dx * dx * dx) / 3 + else: + ln1p = (Decimal(1) + dx).ln() + exact = dy * (ln1p / DEC_LN2) + return m80_from_decimal(exact, rc=rc) + + +# --- Guarded buffer invocation --- + +def alloc_guarded(payload): + size = 32 + len(GUARD_PRE) + len(payload) + len(GUARD_POST) + raw = ctypes.create_string_buffer(size) + base = ctypes.addressof(raw) + data_addr = (base + len(GUARD_PRE) + 15) & ~15 + pre_off = (data_addr - len(GUARD_PRE)) - base + data_off = data_addr - base + post_off = data_off + len(payload) + raw[pre_off:data_off] = GUARD_PRE + raw[data_off:post_off] = payload + raw[post_off:post_off + len(GUARD_POST)] = GUARD_POST + return raw, pre_off, data_off, post_off, data_addr + + +def call3(fn, a_bytes, b_bytes, out_init, *, out_len=None, check_inputs=True): + if out_len is None: + out_len = len(out_init) + buf_a, a_pre, a_off, a_post, a_addr = alloc_guarded(a_bytes) + buf_b, b_pre, b_off, b_post, b_addr = alloc_guarded(b_bytes) + buf_o, o_pre, o_off, o_post, o_addr = alloc_guarded(out_init) + fn(a_addr, b_addr, o_addr) + assert buf_a.raw[a_pre:a_off] == GUARD_PRE and buf_a.raw[a_post:a_post + 16] == GUARD_POST, "A guards corrupted" + assert buf_b.raw[b_pre:b_off] == GUARD_PRE and buf_b.raw[b_post:b_post + 16] == GUARD_POST, "B guards corrupted" + assert buf_o.raw[o_pre:o_off] == GUARD_PRE and buf_o.raw[o_post:o_post + 16] == GUARD_POST, "out guards corrupted" + if check_inputs: + assert buf_a.raw[a_off:a_post] == a_bytes, "input A mutated" + assert buf_b.raw[b_off:b_post] == b_bytes, "input B mutated" + return buf_o.raw[o_off:o_off + out_len] + + +def bind(path, prefix): + lib = ctypes.CDLL(str(Path(path).resolve())) + funcs = {} + for name in EXPORTS: + fn = getattr(lib, prefix + name) + fn.argtypes = [ctypes.c_uint64] * 3 + fn.restype = None + funcs[name] = fn + return lib, funcs + + +# --- Translator positive and negative controls --- + +def encode_seq(*instructions): + enc = Encoder(64) + rip = 0x1000 + for ins in instructions: + rip += enc.encode(ins, rip) + return enc.take_buffer() + + +def check_translator(): + ret = Instruction.create(Code.RETNQ) + fninit = Instruction.create(Code.FNINIT) + fld1 = Instruction.create(Code.FLD1) + fldz = Instruction.create(Code.FLDZ) + fld_m32 = Instruction.create_mem(Code.FLD_M32FP, MemoryOperand(R.RCX)) + fld_m64 = Instruction.create_mem(Code.FLD_M64FP, MemoryOperand(R.RCX)) + fld_m80 = Instruction.create_mem(Code.FLD_M80FP, MemoryOperand(R.RCX)) + fld_m80_rdx = Instruction.create_mem(Code.FLD_M80FP, MemoryOperand(R.RDX)) + fst_m32 = Instruction.create_mem(Code.FST_M32FP, MemoryOperand(R.R8)) + fst_m64 = Instruction.create_mem(Code.FST_M64FP, MemoryOperand(R.R8)) + fstp_m32 = Instruction.create_mem(Code.FSTP_M32FP, MemoryOperand(R.R8)) + fstp_m64 = Instruction.create_mem(Code.FSTP_M64FP, MemoryOperand(R.R8)) + fstp_m80 = Instruction.create_mem(Code.FSTP_M80FP, MemoryOperand(R.R8)) + fstp_st0 = Instruction.create_reg(Code.FSTP_STI, R.ST0) + f2xm1 = Instruction.create(Code.F2XM1) + fyl2x = Instruction.create(Code.FYL2X) + fyl2xp1 = Instruction.create(Code.FYL2XP1) + fnstsw_ax = Instruction.create_reg(Code.FNSTSW_AX, R.AX) + mov_r8_ax = Instruction.create_mem_reg(Code.MOV_RM16_R16, MemoryOperand(R.R8), R.AX) + fldcw_rdx = Instruction.create_mem(Code.FLDCW_M2BYTE, MemoryOperand(R.RDX)) + fnstcw_r8 = Instruction.create_mem(Code.FNSTCW_M2BYTE, MemoryOperand(R.R8)) + + # Positive acceptance across all supported instruction forms. + positive = [ + ("f2xm1_m80", (fninit, fldcw_rdx, fld_m80, f2xm1, fstp_m80, ret), "x87_f2xm1(x87);"), + ("f2xm1_m64_fst", (fninit, fld_m64, f2xm1, fst_m64, fstp_st0, ret), "x87_store_f64(x87, r8, false);"), + ("f2xm1_m32_fst", (fninit, fld_m32, f2xm1, fst_m32, fstp_m32, ret), "x87_store_f32(x87, r8, true);"), + ("fyl2x_m80", (fninit, fld_m80, fld_m80_rdx, fyl2x, fstp_m80, ret), "x87_fyl2x(x87);"), + ("fyl2xp1_m80", (fninit, fld1, fld_m80, fyl2xp1, fstp_m80, ret), "x87_fyl2xp1(x87);"), + ("sw_and_cw", (fninit, fldcw_rdx, fldz, f2xm1, fnstsw_ax, fstp_st0, mov_r8_ax, fnstcw_r8, ret), "x87_status_word(x87)"), + ] + for label, seq, needle in positive: + src, _ = lift_code(label, 0x1000, encode_seq(*seq)) + assert needle in src, f"{label}: missing {needle!r}" + assert "long double" not in src and "" not in src, f"{label}: forbidden host FP type/header" + + # Negative rejection controls. + rep_ret = Instruction.create(Code.RETNQ) + rep_ret.has_rep_prefix = True + fs_fld = Instruction.create_mem(Code.FLD_M80FP, MemoryOperand(R.RCX)) + fs_fld.segment_prefix = R.FS + + rejections = [ + ("trig_fsin", (fld_m80, Instruction.create(Code.FSIN), fstp_m80, ret), "unsupported x87 trigonometric instruction"), + ("trig_fcos", (fld_m80, Instruction.create(Code.FCOS), fstp_m80, ret), "unsupported x87 trigonometric instruction"), + ("trig_fsincos", (fld_m80, Instruction.create(Code.FSINCOS), fstp_m80, fstp_st0, ret), "unsupported x87 trigonometric instruction"), + ("trig_fptan", (fld_m80, Instruction.create(Code.FPTAN), fstp_st0, fstp_m80, ret), "unsupported x87 trigonometric instruction"), + ("trig_fpatan", (fld_m80, fld_m80_rdx, Instruction.create(Code.FPATAN), fstp_m80, ret), "unsupported x87 trigonometric instruction"), + ("stack_overflow_9", (*([fld1] * 9), *([fstp_st0] * 9), ret), "x87 stack overflow"), + ("underflow_f2xm1", (f2xm1, ret), "x87 stack underflow"), + ("underflow_fyl2x_0", (fyl2x, ret), "x87 stack underflow"), + ("underflow_fyl2x_1", (fld1, fyl2x, fstp_st0, ret), "x87 stack underflow"), + ("underflow_fyl2xp1_1", (fld1, fyl2xp1, fstp_st0, ret), "x87 stack underflow"), + ("underflow_after_pop", (fld1, fld1, fyl2x, fstp_st0, fstp_st0, ret), "x87 stack underflow"), + ("underflow_fst", (fst_m64, ret), "x87 stack underflow"), + ("nonempty_at_ret_1", (fld_m80, f2xm1, ret), "non-empty x87 stack at ret"), + ("nonempty_at_ret_fyl2x", (fld1, fld_m80, fyl2x, ret), "non-empty x87 stack at ret"), + ("xmm_addps", (Instruction.create_reg_reg(Code.ADDPS_XMM_XMMM128, R.XMM0, R.XMM1), ret), "unsupported vector instruction"), + ("xmm_movaps", (Instruction.create_reg_mem(Code.MOVAPS_XMM_XMMM128, R.XMM0, MemoryOperand(R.RCX)), ret), "unsupported vector instruction"), + ("vex_vaddps", (Instruction.create_reg_reg_reg(Code.VEX_VADDPS_YMM_YMM_YMMM256, R.YMM0, R.YMM0, R.YMM1), ret), "unsupported VEX encoding"), + ("evex_vmovdqu32", (Instruction.create_reg_mem(Code.EVEX_VMOVDQU32_ZMM_K1Z_ZMMM512, R.ZMM0, MemoryOperand(R.RCX)), ret), "unsupported EVEX encoding"), + ("displaced_fld", (Instruction.create_mem(Code.FLD_M80FP, MemoryOperand(R.RCX, displ=16, displ_size=1)), fstp_m80, ret), "unsupported displaced memory operand"), + ("displaced_fstp", (fld_m80, Instruction.create_mem(Code.FSTP_M80FP, MemoryOperand(R.R8, displ=16, displ_size=1)), ret), "unsupported displaced memory operand"), + ("indexed_mem", (Instruction.create_mem(Code.FLD_M64FP, MemoryOperand(R.RCX, index=R.RDX)), fstp_m64, ret), "unsupported memory operand"), + ("rip_rel_mem", (Instruction.create_mem(Code.FLD_M64FP, MemoryOperand(R.RIP, displ=0x1200, displ_size=4)), fstp_m64, ret), "unsupported memory operand"), + ("rsp_mem", (Instruction.create_mem(Code.FLD_M64FP, MemoryOperand(R.RSP)), fstp_m64, ret), "unsupported memory operand"), + ("non_arg_base_rax", (Instruction.create_mem(Code.FLD_M64FP, MemoryOperand(R.RAX)), fstp_m64, ret), "unsupported memory base"), + ("nonvol_base_rbx", (Instruction.create_mem(Code.FLD_M64FP, MemoryOperand(R.RBX)), fstp_m64, ret), "nonvolatile GPR base"), + ("store_outside_r8_rcx", (fld_m80, Instruction.create_mem(Code.FSTP_M80FP, MemoryOperand(R.RCX)), ret), "store outside output buffer r8"), + ("store_outside_r8_rdx", (fld_m64, Instruction.create_mem(Code.FST_M64FP, MemoryOperand(R.RDX)), fstp_st0, ret), "store outside output buffer r8"), + ("fnstcw_outside_r8", (Instruction.create_mem(Code.FNSTCW_M2BYTE, MemoryOperand(R.RCX)), ret), "store outside output buffer r8"), + ("mov_ax_outside_r8", (fnstsw_ax, Instruction.create_mem_reg(Code.MOV_RM16_R16, MemoryOperand(R.RCX), R.AX), ret), "store outside output buffer r8"), + ("undef_ax_store", (mov_r8_ax, ret), "undefined register ax"), + ("fstp_st1", (fld1, fld1, Instruction.create_reg(Code.FSTP_STI, R.ST1), fstp_st0, ret), "unsupported fstp register operand"), + ("prefix_fs", (fs_fld, fstp_m80, ret), "unsupported instruction prefix"), + ("prefix_rep_ret", (fld1, fstp_st0, rep_ret), "unsupported instruction prefix"), + ("wait_prefix", (Instruction.create(Code.WAIT), fninit, ret), "unsupported instruction"), + ("branch_jmp", (Instruction.create_branch(Code.JMP_REL8_64, 0x1010), ret), "unsupported control-flow instruction"), + ("missing_ret", (fninit, fld1, fstp_st0), "missing terminal ret"), + ("trailing_after_ret", (fninit, ret, fninit), "unreachable instruction after ret"), + ] + for label, seq, reason in rejections: + try: + lift_code(label, 0x1000, encode_seq(*seq)) + except ValueError as exc: + if reason not in str(exc): + raise AssertionError(f"{label}: expected {reason!r}, got {exc!r}") from exc + else: + raise AssertionError(f"{label}: translator accepted rejected sequence") + + return len(positive), len(rejections) + + +# --- Case builders --- + +def f2xm1_domain_values(): + rng = random.Random(0xF21A07) + vals = [ + POS_ZERO, NEG_ZERO, POS_ONE, NEG_ONE, POS_HALF, NEG_HALF, + SUB_POS_MIN, SUB_NEG_MIN, SUB_POS_MID, SUB_NEG_MID, + TINY_NORM_POS, TINY_NORM_NEG, + # Near +-1 endpoints: 1 - 2^-63, -(1 - 2^-63), 1 - 2^-64 + (0xFFFFFFFFFFFFFFFF, 0x3FFE), + (0xFFFFFFFFFFFFFFFF, 0xBFFE), + # Near +-0.25, +-0.75, +-1/3 + (J, 0x3FFD), (J, 0xBFFD), + (0xC000000000000000, 0x3FFE), (0xC000000000000000, 0xBFFE), + (0xAAAAAAAAAAAAAAAA, 0x3FFD), (0xAAAAAAAAAAAAAAAA, 0xBFFD), + # Very small normal exponents + (J | 0x123456789ABCDEF0, 0x3FFF - 50), + (J | 0x123456789ABCDEF0, 0xBFFF - 50), + (J | 0xFEDCBA9876543210, 0x3FFF - 63), + (J | 0xFEDCBA9876543210, 0x3FFF - 200), + ] + for _ in range(80): + sign = rng.getrandbits(1) << 15 + exp = rng.randint(0x3FFF - 40, 0x3FFE) + sig = J | rng.getrandbits(63) + vals.append((sig, sign | exp)) + return vals + + +def fyl2x_domain_pairs(): + rng = random.Random(0xF12A07) + pairs = [ + # (y, x) with x > 0 + (POS_ONE, POS_ONE), (NEG_ONE, POS_ONE), + (POS_ZERO, POS_ONE), (NEG_ZERO, POS_ONE), + (POS_ONE, POS_TWO), (NEG_ONE, POS_TWO), + (POS_ONE, POS_HALF), (NEG_ONE, POS_HALF), + (POS_ONE, (0xC000000000000000, 0x4000)), # y=1, x=3 + (NEG_HALF, (0xC000000000000000, 0x4000)), + # Near x = 1 (cancellation resistance) + (POS_ONE, (J | 1, 0x3FFF)), # 1 + 2^-63 + (POS_ONE, (0xFFFFFFFFFFFFFFFF, 0x3FFE)), # 1 - 2^-64 + (POS_ONE, (J | (1 << 30), 0x3FFF)), + (NEG_ONE, (0xFFFFFFFFC0000000, 0x3FFE)), + # Near sqrt(2) range-reduction boundary + (POS_ONE, (0xB504F333F9DE6484, 0x3FFF)), + (POS_ONE, (0xB504F333F9DE6485, 0x3FFF)), + # Subnormal and tiny normal x + (POS_ONE, SUB_POS_MIN), + (POS_ONE, SUB_POS_MID), + (POS_ONE, TINY_NORM_POS), + (SUB_POS_MIN, POS_TWO), + (SUB_NEG_MIN, POS_HALF), + # Large positive x + (POS_ONE, HUGE_POS), + (POS_HALF, (J, 0x7FFE)), + # Overflow under RC: huge * log2(4) = 2 * huge + (HUGE_POS, POS_FOUR), + (HUGE_NEG, POS_FOUR), + # Underflow: tiny * log2(1 + 2^-63) + (TINY_NORM_POS, (J | 1, 0x3FFF)), + (TINY_NORM_NEG, (J | 1, 0x3FFF)), + # Zero y with finite x != 1 + (POS_ZERO, POS_TWO), (NEG_ZERO, POS_TWO), + (POS_ZERO, POS_HALF), (NEG_ZERO, POS_HALF), + ] + for _ in range(64): + ys = rng.getrandbits(1) << 15 + ye = rng.randint(0x3FFF - 40, 0x3FFF + 40) + xe = rng.randint(0x3FFF - 80, 0x3FFF + 80) + pairs.append(((J | rng.getrandbits(63), ys | ye), (J | rng.getrandbits(63), xe))) + return pairs + + +def fyl2xp1_domain_pairs(): + """Pairs (y, x) with x inside the exact Intel SDM domain [-(1-sqrt(2)/2), 1-sqrt(2)/2].""" + rng = random.Random(0xF12B07) + # 1 - sqrt(2)/2 ~= 0.292893218813452475599... -> 0x3FFD / 0x95F619980C4336F7 + dom_pos = (0x95F619980C4336F6, 0x3FFD) + dom_neg = (0x95F619980C4336F6, 0xBFFD) + pairs = [ + (POS_ONE, POS_ZERO), (NEG_ONE, POS_ZERO), + (POS_ONE, NEG_ZERO), (NEG_ONE, NEG_ZERO), + (POS_ZERO, POS_ZERO), (NEG_ZERO, POS_ZERO), + (POS_ZERO, NEG_ZERO), (NEG_ZERO, NEG_ZERO), + (POS_ONE, (J, 0x3FFD)), (POS_ONE, (J, 0xBFFD)), # +-0.25 + (NEG_ONE, (J, 0x3FFD)), (NEG_ONE, (J, 0xBFFD)), + (POS_ONE, dom_pos), (POS_ONE, dom_neg), + (NEG_HALF, dom_pos), (NEG_HALF, dom_neg), + (POS_ONE, SUB_POS_MIN), (POS_ONE, SUB_NEG_MIN), + (POS_ONE, SUB_POS_MID), (POS_ONE, SUB_NEG_MID), + (POS_ONE, TINY_NORM_POS), (POS_ONE, TINY_NORM_NEG), + (POS_TWO, (J | 0x123456789ABCDEF0, 0x3FFF - 60)), + (POS_TWO, (J | 0x123456789ABCDEF0, 0xBFFF - 60)), + (POS_ZERO, (J, 0x3FFD)), (NEG_ZERO, (J, 0x3FFD)), + (POS_ZERO, (J, 0xBFFD)), (NEG_ZERO, (J, 0xBFFD)), + (HUGE_POS, (J, 0x3FFD)), (HUGE_NEG, (J, 0xBFFD)), + ] + for _ in range(64): + ys = rng.getrandbits(1) << 15 + ye = rng.randint(0x3FFF - 40, 0x3FFF + 40) + xs = rng.getrandbits(1) << 15 + xe = rng.randint(0x3FFF - 60, 0x3FFC) # |x| < 0.25, safely inside SDM domain + pairs.append(((J | rng.getrandbits(63), ys | ye), (J | rng.getrandbits(63), xs | xe))) + return pairs + + +# --- Core differential & hardware fidelity checks --- + +def check_differential(native, lifted, altered, altered_lifted): + total = 0 + max_ulp_ref = 0 + max_ulp_nat = 0 + dummy = b"\x00" * 16 + + # 1. F2XM1 across domain + all 12 masked FCWs (PC 24/53/64 x RC RN/RD/RU/RZ). + f2_vals = f2xm1_domain_values() + for x in f2_vals: + for cw in (0x037F,): + nat = unpack80(call3(native["op_f2xm1_m80"], pack80(x), pack16(cw), b"\x5a" * 10)) + lif = unpack80(call3(lifted["op_f2xm1_m80"], pack80(x), pack16(cw), b"\x5a" * 10)) + ref = ref_f2xm1(x, cw) + u_ref = m80_ulp_diff(lif, ref) + u_nat = m80_ulp_diff(lif, nat) + max_ulp_ref = max(max_ulp_ref, u_ref) + max_ulp_nat = max(max_ulp_nat, u_nat) + if u_ref > 1 or u_nat > 1: + raise AssertionError(f"f2xm1 x={x} cw={cw:#x}: ref={ref} nat={nat} lif={lif} ulp=({u_ref},{u_nat})") + if x in (POS_ZERO, NEG_ZERO, POS_ONE, NEG_ONE) and (lif != ref or lif != nat): + raise AssertionError(f"f2xm1 exact point x={x}: ref={ref} nat={nat} lif={lif}") + total += 1 + + # Verify all 12 FCWs (PC 24/53/64 x RC RN/RD/RU/RZ) on F2XM1, FYL2X, FYL2XP1! + for cw in MASKED_CWS: + # F2XM1(0.5) and F2XM1(-0.5) and F2XM1(-0.0) + for x in (POS_HALF, NEG_HALF, NEG_ZERO, POS_ZERO, (0xAAAAAAAAAAAAAAAA, 0x3FFD)): + nat = unpack80(call3(native["op_f2xm1_m80"], pack80(x), pack16(cw), b"\x5a" * 10)) + lif = unpack80(call3(lifted["op_f2xm1_m80"], pack80(x), pack16(cw), b"\x5a" * 10)) + ref = ref_f2xm1(x, cw) + assert m80_ulp_diff(lif, ref) <= 1 and m80_ulp_diff(lif, nat) <= 1, (x, hex(cw), ref, nat, lif) + if x in (POS_ZERO, NEG_ZERO): + assert lif == nat == x + total += 1 + # Verify PC independence matches Intel hardware: PC=0 and PC=2 equal PC=3 for each RC! + rc = (cw >> 10) & 3 + cw_pc64 = 0x037F | (rc << 10) + for op_name, a, b in ( + ("op_f2xm1_m80", pack80(POS_HALF), None), + ("op_fyl2x_m80", pack80(POS_ONE), pack80((0xC000000000000000, 0x4000))), + ("op_fyl2xp1_m80", pack80(POS_ONE), pack80((J, 0x3FFD))), + ): + if b is None: + got_pc = unpack80(call3(lifted[op_name], a, pack16(cw), b"\x5a" * 10)) + got_64 = unpack80(call3(lifted[op_name], a, pack16(cw_pc64), b"\x5a" * 10)) + nat_pc = unpack80(call3(native[op_name], a, pack16(cw), b"\x5a" * 10)) + nat_64 = unpack80(call3(native[op_name], a, pack16(cw_pc64), b"\x5a" * 10)) + else: + got_pc = unpack80(call3(lifted[op_name], a, b, pack16(cw) + b"\x5a" * 8)) + got_64 = unpack80(call3(lifted[op_name], a, b, pack16(cw_pc64) + b"\x5a" * 8)) + nat_pc = unpack80(call3(native[op_name], a, b, pack16(cw) + b"\x5a" * 8)) + nat_64 = unpack80(call3(native[op_name], a, b, pack16(cw_pc64) + b"\x5a" * 8)) + assert got_pc == got_64 and nat_pc == nat_64 and m80_ulp_diff(got_pc, nat_pc) <= 1 + total += 1 + + # Verify RC monotonicity (RD <= RN <= RU) on irrational points! + for x in (POS_HALF, NEG_HALF): + r_rd = m80_ordinal(unpack80(call3(lifted["op_f2xm1_m80"], pack80(x), pack16(0x077F), b"\x5a" * 10))) + r_rn = m80_ordinal(unpack80(call3(lifted["op_f2xm1_m80"], pack80(x), pack16(0x037F), b"\x5a" * 10))) + r_ru = m80_ordinal(unpack80(call3(lifted["op_f2xm1_m80"], pack80(x), pack16(0x0B7F), b"\x5a" * 10))) + assert r_rd <= r_rn <= r_ru and r_ru - r_rd == 1, (x, r_rd, r_rn, r_ru) + + # 2. FYL2X across positive domain + all 4 RCs on boundary cases. + for y, x in fyl2x_domain_pairs(): + cws = (0x037F, 0x077F, 0x0B7F, 0x0F7F) if y in (HUGE_POS, HUGE_NEG, POS_ONE) else (0x037F,) + for cw in cws: + out_init = pack16(cw) + b"\x5a" * 8 + nat = unpack80(call3(native["op_fyl2x_m80"], pack80(y), pack80(x), out_init)) + lif = unpack80(call3(lifted["op_fyl2x_m80"], pack80(y), pack80(x), out_init)) + ref = ref_fyl2x(y, x, cw) + u_ref = m80_ulp_diff(lif, ref) + u_nat = m80_ulp_diff(lif, nat) + max_ulp_ref = max(max_ulp_ref, u_ref) + max_ulp_nat = max(max_ulp_nat, u_nat) + if u_ref > 1 or u_nat > 1: + raise AssertionError(f"fyl2x y={y} x={x} cw={cw:#x}: ref={ref} nat={nat} lif={lif} ulp=({u_ref},{u_nat})") + total += 1 + + # 3. FYL2XP1 across SDM domain [-(1-sqrt(2)/2), +(1-sqrt(2)/2)]. + for y, x in fyl2xp1_domain_pairs(): + cws = (0x037F, 0x077F, 0x0B7F, 0x0F7F) if y in (POS_ONE, HUGE_POS) else (0x037F,) + for cw in cws: + out_init = pack16(cw) + b"\x5a" * 8 + nat = unpack80(call3(native["op_fyl2xp1_m80"], pack80(y), pack80(x), out_init)) + lif = unpack80(call3(lifted["op_fyl2xp1_m80"], pack80(y), pack80(x), out_init)) + ref = ref_fyl2xp1(y, x, cw) + u_ref = m80_ulp_diff(lif, ref) + u_nat = m80_ulp_diff(lif, nat) + max_ulp_ref = max(max_ulp_ref, u_ref) + max_ulp_nat = max(max_ulp_nat, u_nat) + if u_ref > 1 or u_nat > 1: + raise AssertionError(f"fyl2xp1 y={y} x={x} cw={cw:#x}: ref={ref} nat={nat} lif={lif} ulp=({u_ref},{u_nat})") + total += 1 + + # 4. m64 / m32 loads & fst / fstp stores across all 4 RCs. + f64_f2_inputs = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 0.125, -0.75, 1e-300, 0x0000000000000001, 0x8000000000000001] + f32_f2_inputs = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 0.25, -0.75, 0x00000001, 0x80000001] + for cw in (0x037F, 0x077F, 0x0B7F, 0x0F7F): + for v in f64_f2_inputs: + inp = pack_f64(v) + for name in ("op_f2xm1_m64", "op_f2xm1_fst_m64"): + nat = call3(native[name], inp, pack16(cw), b"\x5a" * 8) + lif = call3(lifted[name], inp, pack16(cw), b"\x5a" * 8) + assert f64_ulp_diff(nat, lif) <= 1, (name, v, hex(cw), nat.hex(), lif.hex()) + total += 1 + for v in f32_f2_inputs: + inp = pack_f32(v) + for name in ("op_f2xm1_m32", "op_f2xm1_fst_m32"): + nat = call3(native[name], inp, pack16(cw), b"\x5a" * 4) + lif = call3(lifted[name], inp, pack16(cw), b"\x5a" * 4) + assert f32_ulp_diff(nat, lif) <= 1, (name, v, hex(cw), nat.hex(), lif.hex()) + total += 1 + for yv, xv in ((1.0, 3.0), (-2.5, 0.5), (1.0, 0x0000000000000001)): + out_init = pack16(cw) + b"\x5a" * 6 + nat = call3(native["op_fyl2x_m64"], pack_f64(yv), pack_f64(xv), out_init) + lif = call3(lifted["op_fyl2x_m64"], pack_f64(yv), pack_f64(xv), out_init) + assert f64_ulp_diff(nat, lif) <= 1 + total += 1 + for yv, xv in ((1.0, 3.0), (-2.5, 0.5), (1.0, 0x00000001)): + out_init = pack16(cw) + b"\x5a" * 2 + nat = call3(native["op_fyl2x_m32"], pack_f32(yv), pack_f32(xv), out_init) + lif = call3(lifted["op_fyl2x_m32"], pack_f32(yv), pack_f32(xv), out_init) + assert f32_ulp_diff(nat, lif) <= 1 + total += 1 + for yv, xv in ((1.0, 0.25), (-1.5, -0.125), (1.0, 0x0000000000000001)): + out_init = pack16(cw) + b"\x5a" * 6 + nat = call3(native["op_fyl2xp1_m64"], pack_f64(yv), pack_f64(xv), out_init) + lif = call3(lifted["op_fyl2xp1_m64"], pack_f64(yv), pack_f64(xv), out_init) + assert f64_ulp_diff(nat, lif) <= 1 + total += 1 + for yv, xv in ((1.0, 0.25), (-1.5, -0.125), (1.0, 0x00000001)): + out_init = pack16(cw) + b"\x5a" * 2 + nat = call3(native["op_fyl2xp1_m32"], pack_f32(yv), pack_f32(xv), out_init) + lif = call3(lifted["op_fyl2xp1_m32"], pack_f32(yv), pack_f32(xv), out_init) + assert f32_ulp_diff(nat, lif) <= 1 + total += 1 + + # 5. Special values & exact status word flags (IE, DE, ZE, OE, UE, TOP). + f2_special = [ + ("f2xm1_+0", POS_ZERO, POS_ZERO, 0), + ("f2xm1_-0", NEG_ZERO, NEG_ZERO, 0), + ("f2xm1_+inf", POS_INF, POS_INF, 0), + ("f2xm1_-inf", NEG_INF, NEG_ONE, 0), + ("f2xm1_qnan", QNAN_A, QNAN_A, 0), + ("f2xm1_snan", SNAN_A, (SNAN_A[0] | QBIT, SNAN_A[1]), SW_IE), + ("f2xm1_unnorm", UNNORM, INDEF, SW_IE), + ("f2xm1_+sub", SUB_POS_MIN, SUB_POS_MIN, SW_DE | SW_UE), + ("f2xm1_-sub", SUB_NEG_MIN, SUB_NEG_MIN, SW_DE | SW_UE), + ("f2xm1_+tiny", TINY_NORM_POS, None, SW_UE), + ] + for label, x, want_val, want_flags in f2_special: + nat_v = unpack80(call3(native["op_f2xm1_m80"], pack80(x), pack16(0x037F), b"\x5a" * 10)) + lif_v = unpack80(call3(lifted["op_f2xm1_m80"], pack80(x), pack16(0x037F), b"\x5a" * 10)) + nat_sw = unpack16(call3(native["op_f2xm1_sw"], pack80(x), pack16(0x037F), b"\x5a" * 2)) + lif_sw = unpack16(call3(lifted["op_f2xm1_sw"], pack80(x), pack16(0x037F), b"\x5a" * 2)) + if want_val is not None: + assert lif_v == want_val and nat_v == want_val, (label, nat_v, lif_v, want_val) + else: + assert m80_ulp_diff(lif_v, nat_v) <= 1, (label, nat_v, lif_v) + assert (lif_sw & SW_STRICT_MASK) == (nat_sw & SW_STRICT_MASK) == (0x3800 | want_flags), ( + label, hex(nat_sw), hex(lif_sw), hex(0x3800 | want_flags) + ) + total += 2 + + fyl2x_special = [ + ("fyl2x_+1_+0", POS_ONE, POS_ZERO, NEG_INF, SW_ZE), + ("fyl2x_-1_+0", NEG_ONE, POS_ZERO, POS_INF, SW_ZE), + ("fyl2x_+1_-0", POS_ONE, NEG_ZERO, NEG_INF, SW_ZE), + ("fyl2x_-1_-0", NEG_ONE, NEG_ZERO, POS_INF, SW_ZE), + ("fyl2x_+0_+0", POS_ZERO, POS_ZERO, INDEF, SW_IE), + ("fyl2x_-0_+0", NEG_ZERO, POS_ZERO, INDEF, SW_IE), + ("fyl2x_+inf_+0", POS_INF, POS_ZERO, NEG_INF, 0), + ("fyl2x_-inf_+0", NEG_INF, POS_ZERO, POS_INF, 0), + ("fyl2x_+inf_+1", POS_INF, POS_ONE, INDEF, SW_IE), + ("fyl2x_-inf_+1", NEG_INF, POS_ONE, INDEF, SW_IE), + ("fyl2x_+1_+inf", POS_ONE, POS_INF, POS_INF, 0), + ("fyl2x_-1_+inf", NEG_ONE, POS_INF, NEG_INF, 0), + ("fyl2x_+0_+inf", POS_ZERO, POS_INF, INDEF, SW_IE), + ("fyl2x_-0_+inf", NEG_ZERO, POS_INF, INDEF, SW_IE), + ("fyl2x_+1_-1", POS_ONE, NEG_ONE, INDEF, SW_IE), + ("fyl2x_+0_-1", POS_ZERO, NEG_ONE, INDEF, SW_IE), + ("fyl2x_+1_-inf", POS_ONE, NEG_INF, INDEF, SW_IE), + ("fyl2x_+1_-sub", POS_ONE, SUB_NEG_MIN, INDEF, SW_IE), + ("fyl2x_+1_+sub", POS_ONE, SUB_POS_MIN, (0x807A000000000000, 0xC00D), SW_DE), + ("fyl2x_+inf_+2", POS_INF, POS_TWO, POS_INF, 0), + ("fyl2x_+inf_+0.5", POS_INF, POS_HALF, NEG_INF, 0), + ("fyl2x_snan_2", SNAN_A, POS_TWO, (SNAN_A[0] | QBIT, SNAN_A[1]), SW_IE), + ("fyl2x_2_snan", POS_TWO, SNAN_B, (SNAN_B[0] | QBIT, SNAN_B[1]), SW_IE), + ("fyl2x_qnan_snan", QNAN_A, SNAN_B, QNAN_A, SW_IE), + ("fyl2x_snan_qnan", SNAN_B, QNAN_A, QNAN_A, SW_IE), + ("fyl2x_unnorm_2", UNNORM, POS_TWO, INDEF, SW_IE), + ("fyl2x_2_unnorm", POS_TWO, UNNORM, INDEF, SW_IE), + ("fyl2x_overflow", HUGE_POS, POS_FOUR, POS_INF, SW_OE), + ] + for label, y, x, want_val, want_flags in fyl2x_special: + out_v = pack16(0x037F) + b"\x5a" * 8 + out_sw = pack16(0x037F) + nat_v = unpack80(call3(native["op_fyl2x_m80"], pack80(y), pack80(x), out_v)) + lif_v = unpack80(call3(lifted["op_fyl2x_m80"], pack80(y), pack80(x), out_v)) + nat_sw = unpack16(call3(native["op_fyl2x_sw"], pack80(y), pack80(x), out_sw)) + lif_sw = unpack16(call3(lifted["op_fyl2x_sw"], pack80(y), pack80(x), out_sw)) + assert lif_v == want_val and nat_v == want_val, (label, nat_v, lif_v, want_val) + assert (lif_sw & SW_STRICT_MASK) == (nat_sw & SW_STRICT_MASK) == (0x3800 | want_flags), ( + label, hex(nat_sw), hex(lif_sw), hex(0x3800 | want_flags) + ) + total += 2 + + fyl2xp1_sdm_special = [ + ("fyl2xp1_+1_+0", POS_ONE, POS_ZERO, POS_ZERO, 0), + ("fyl2xp1_-1_+0", NEG_ONE, POS_ZERO, NEG_ZERO, 0), + ("fyl2xp1_+1_-0", POS_ONE, NEG_ZERO, NEG_ZERO, 0), + ("fyl2xp1_-1_-0", NEG_ONE, NEG_ZERO, POS_ZERO, 0), + ("fyl2xp1_+inf_+0", POS_INF, POS_ZERO, INDEF, SW_IE), + ("fyl2xp1_-inf_-0", NEG_INF, NEG_ZERO, INDEF, SW_IE), + ("fyl2xp1_+inf_+0.25", POS_INF, (J, 0x3FFD), POS_INF, 0), + ("fyl2xp1_+inf_-0.25", POS_INF, (J, 0xBFFD), NEG_INF, 0), + ("fyl2xp1_+1_+sub", POS_ONE, SUB_POS_MIN, SUB_POS_MIN, SW_DE | SW_UE), + ("fyl2xp1_+1_-sub", POS_ONE, SUB_NEG_MIN, SUB_NEG_MIN, SW_DE | SW_UE), + ("fyl2xp1_snan_+0", SNAN_A, POS_ZERO, (SNAN_A[0] | QBIT, SNAN_A[1]), SW_IE), + ("fyl2xp1_+1_snan", POS_ONE, SNAN_A, (SNAN_A[0] | QBIT, SNAN_A[1]), SW_IE), + ("fyl2xp1_+1_qnan", POS_ONE, QNAN_B, QNAN_B, 0), + ("fyl2xp1_unnorm_+0", UNNORM, POS_ZERO, INDEF, SW_IE), + ] + for label, y, x, want_val, want_flags in fyl2xp1_sdm_special: + out_v = pack16(0x037F) + b"\x5a" * 8 + out_sw = pack16(0x037F) + nat_v = unpack80(call3(native["op_fyl2xp1_m80"], pack80(y), pack80(x), out_v)) + lif_v = unpack80(call3(lifted["op_fyl2xp1_m80"], pack80(y), pack80(x), out_v)) + nat_sw = unpack16(call3(native["op_fyl2xp1_sw"], pack80(y), pack80(x), out_sw)) + lif_sw = unpack16(call3(lifted["op_fyl2xp1_sw"], pack80(y), pack80(x), out_sw)) + assert lif_v == want_val and nat_v == want_val, (label, nat_v, lif_v, want_val) + assert (lif_sw & SW_STRICT_MASK) == (nat_sw & SW_STRICT_MASK) == (0x3800 | want_flags), ( + label, hex(nat_sw), hex(lif_sw), hex(0x3800 | want_flags) + ) + total += 2 + + # Lifted-only singularity checks for FYL2XP1(x == -1, y) and x < -1 + # (outside Intel SDM domain [-(1-sqrt(2)/2), 1-sqrt(2)/2], where hardware is undefined). + for label, y, x, want_val, want_flags in ( + ("fyl2xp1_+1_-1_singularity", POS_ONE, NEG_ONE, NEG_INF, SW_ZE), + ("fyl2xp1_-1_-1_singularity", NEG_ONE, NEG_ONE, POS_INF, SW_ZE), + ("fyl2xp1_+0_-1_indef", POS_ZERO, NEG_ONE, INDEF, SW_IE), + ("fyl2xp1_+inf_-1", POS_INF, NEG_ONE, NEG_INF, 0), + ("fyl2xp1_+1_-2_domain", POS_ONE, (J, 0xC000), INDEF, SW_IE), + ("fyl2xp1_+1_-inf_domain", POS_ONE, NEG_INF, INDEF, SW_IE), + ): + lif_v = unpack80(call3(lifted["op_fyl2xp1_m80"], pack80(y), pack80(x), pack16(0x037F) + b"\x5a" * 8)) + lif_sw = unpack16(call3(lifted["op_fyl2xp1_sw"], pack80(y), pack80(x), pack16(0x037F))) + assert lif_v == want_val, (label, lif_v, want_val) + assert (lif_sw & SW_STRICT_MASK) == (0x3800 | want_flags), (label, hex(lif_sw), hex(0x3800 | want_flags)) + total += 2 + + # 6. Stack pop depth & depth-8 checks. + for y, x in ((POS_ONE, POS_TWO), (NEG_HALF, (0xC000000000000000, 0x4000))): + nat_s = unpack80(call3(native["op_fyl2x_pop_depth"], pack80(y), pack80(x), b"\x5a" * 10)) + lif_s = unpack80(call3(lifted["op_fyl2x_pop_depth"], pack80(y), pack80(x), b"\x5a" * 10)) + assert nat_s == POS_ONE and lif_s == POS_ONE + nat_8 = unpack80(call3(native["op_fyl2x_depth8"], pack80(y), pack80(x), b"\x5a" * 10)) + lif_8 = unpack80(call3(lifted["op_fyl2x_depth8"], pack80(y), pack80(x), b"\x5a" * 10)) + assert m80_ulp_diff(nat_8, lif_8) <= 1 + nat_p = unpack80(call3(native["op_fyl2xp1_pop_depth"], pack80(y), pack80((J, 0x3FFD)), b"\x5a" * 10)) + lif_p = unpack80(call3(lifted["op_fyl2xp1_pop_depth"], pack80(y), pack80((J, 0x3FFD)), b"\x5a" * 10)) + assert nat_p == POS_ZERO and lif_p == POS_ZERO + total += 3 + + # 7. Composition roundtrip: 2^(log2(x+1)) - 1 == x within <= 2 ULP. + for x in (POS_ZERO, NEG_ZERO, (J, 0x3FFD), (J, 0xBFFD), (0x95F619980C4336F6, 0x3FFD), SUB_POS_MID): + nat_r = unpack80(call3(native["op_exp_log_roundtrip"], pack80(x), pack16(0x037F), b"\x5a" * 10)) + lif_r = unpack80(call3(lifted["op_exp_log_roundtrip"], pack80(x), pack16(0x037F), b"\x5a" * 10)) + assert m80_ulp_diff(lif_r, x) <= 2 and m80_ulp_diff(nat_r, lif_r) <= 2, (x, nat_r, lif_r) + if x in (POS_ZERO, NEG_ZERO): + assert lif_r == nat_r == x + total += 1 + + # 8. FCW & FNINIT transport checks across all 12 masked control words. + for cw in MASKED_CWS: + nat_cw = unpack16(call3(native["op_fcw_roundtrip"], pack16(cw), dummy, b"\x5a" * 2)) + lif_cw = unpack16(call3(lifted["op_fcw_roundtrip"], pack16(cw), dummy, b"\x5a" * 2)) + assert nat_cw == cw and lif_cw == cw, (hex(cw), hex(nat_cw), hex(lif_cw)) + nat_icw = unpack16(call3(native["op_fninit_cw_sw"], pack16(cw), pack80(SNAN_A), b"\x5a" * 2)) + lif_icw = unpack16(call3(lifted["op_fninit_cw_sw"], pack16(cw), pack80(SNAN_A), b"\x5a" * 2)) + assert nat_icw == 0x037F and lif_icw == 0x037F + total += 2 + nat_isw = unpack16(call3(native["op_fninit_sw"], pack80(SNAN_A), dummy, b"\x5a" * 2)) + lif_isw = unpack16(call3(lifted["op_fninit_sw"], pack80(SNAN_A), dummy, b"\x5a" * 2)) + assert nat_isw == 0x0000 and lif_isw == 0x0000 + total += 1 + + # 9. Altered-build controls (ALTER_X87_EXP_LOG): altered lifted matches altered native and diverges from original. + altered_probes = ( + ("op_f2xm1_m80", pack80(POS_HALF), pack16(0x037F), b"\x5a" * 10), + ("op_fyl2x_m80", pack80(POS_ONE), pack80((J, 0x3FFD)), pack16(0x037F) + b"\x5a" * 8), + ("op_fyl2xp1_m80", pack80(POS_ONE), pack80((J, 0x3FFD)), pack16(0x037F) + b"\x5a" * 8), + ("op_exp_log_roundtrip", pack80((J, 0x3FFD)), pack16(0x037F), b"\x5a" * 10), + ("op_fcw_roundtrip", pack16(0x077F), dummy, b"\x5a" * 2), + ) + for name, a_b, b_b, o_b in altered_probes: + orig_n = call3(native[name], a_b, b_b, o_b) + alt_n = call3(altered[name], a_b, b_b, o_b) + alt_l = call3(altered_lifted[name], a_b, b_b, o_b) + if len(o_b) == 10: + assert m80_ulp_diff(unpack80(alt_n), unpack80(alt_l)) <= 1, (name, alt_n.hex(), alt_l.hex()) + else: + assert alt_n == alt_l, (name, alt_n.hex(), alt_l.hex()) + assert alt_n != orig_n, f"altered build did not diverge on {name}" + total += 1 + + return total, max_ulp_ref, max_ulp_nat + + +def check_mxcsr_isolation(native, lifted, lifted_lib): + """Verify x87 80-bit subnormals do NOT flush under MXCSR 0x1fc0 (DAZ) / 0x9fc0 (DAZ+FTZ) + and lifted exports never clobber host MXCSR.""" + get_mxcsr = lifted_lib.host_get_mxcsr + get_mxcsr.argtypes, get_mxcsr.restype = [], ctypes.c_uint32 + xchg_mxcsr = lifted_lib.host_exchange_mxcsr + xchg_mxcsr.argtypes, xchg_mxcsr.restype = [ctypes.c_uint32], ctypes.c_uint32 + + saved = get_mxcsr() + modes = (0x1F80, 0x1FC0, 0x9FC0, 0x3FC0) + probes = [ + ("op_f2xm1_m80", pack80(SUB_POS_MIN), pack16(0x037F), b"\x5a" * 10), + ("op_f2xm1_m80", pack80(SUB_NEG_MIN), pack16(0x037F), b"\x5a" * 10), + ("op_f2xm1_m80", pack80(TINY_NORM_POS), pack16(0x037F), b"\x5a" * 10), + ("op_f2xm1_m64", pack_f64(0x0000000000000001), pack16(0x037F), b"\x5a" * 8), + ("op_f2xm1_m32", pack_f32(0x00000001), pack16(0x037F), b"\x5a" * 4), + ("op_fyl2x_m80", pack80(POS_ONE), pack80(SUB_POS_MIN), pack16(0x037F) + b"\x5a" * 8), + ("op_fyl2x_m80", pack80(SUB_POS_MIN), pack80(POS_TWO), pack16(0x037F) + b"\x5a" * 8), + ("op_fyl2xp1_m80", pack80(POS_ONE), pack80(SUB_POS_MIN), pack16(0x037F) + b"\x5a" * 8), + ("op_fyl2xp1_m80", pack80(POS_ONE), pack80(SUB_NEG_MID), pack16(0x037F) + b"\x5a" * 8), + ] + checked = 0 + try: + baselines = {} + for mxcsr in modes: + xchg_mxcsr(mxcsr) + for idx, (name, a_b, b_b, o_b) in enumerate(probes): + before = get_mxcsr() + assert before == mxcsr, f"failed to set MXCSR {mxcsr:#x} (got {before:#x})" + lif = call3(lifted[name], a_b, b_b, o_b) + after = get_mxcsr() + assert after == mxcsr, f"lifted {name} clobbered MXCSR: {mxcsr:#x} -> {after:#x}" + nat = call3(native[name], a_b, b_b, o_b) + assert get_mxcsr() == mxcsr, f"native {name} clobbered MXCSR" + if idx not in baselines: + baselines[idx] = (nat, lif) + else: + # Must be BIT-IDENTICAL across 0x1f80, 0x1fc0 (DAZ), 0x9fc0 (DAZ+FTZ), 0x3fc0! + assert lif == baselines[idx][1], f"lifted {name} changed under MXCSR {mxcsr:#x}" + assert nat == baselines[idx][0], f"native {name} changed under MXCSR {mxcsr:#x}" + # Subnormal outputs must remain non-zero! + assert any(byte != 0 for byte in lif[:8]), f"subnormal flushed to zero on {name} under {mxcsr:#x}" + if len(o_b) == 10: + assert m80_ulp_diff(unpack80(nat), unpack80(lif)) <= 1 + elif len(o_b) == 8: + assert f64_ulp_diff(nat, lif) <= 1 + else: + assert f32_ulp_diff(nat, lif) <= 1 + checked += 1 + finally: + xchg_mxcsr(saved) + return checked + + +def check_mutants(lifted): + """Faulty reference models must each be caught by the lifted outputs.""" + caught = 0 + # 1. Dropping -0.0 sign in F2XM1(-0.0) + got_neg0 = unpack80(call3(lifted["op_f2xm1_m80"], pack80(NEG_ZERO), pack16(0x037F), b"\x5a" * 10)) + assert got_neg0 != POS_ZERO + caught += 1 + # 2. Truncating 80-bit F2XM1(0.5) to 53-bit MSVC `long double` precision + got_half = unpack80(call3(lifted["op_f2xm1_m80"], pack80(POS_HALF), pack16(0x037F), b"\x5a" * 10)) + trunc_53 = (got_half[0] & ~0x7FF, got_half[1]) + assert got_half != trunc_53 + caught += 1 + # 3. Ignoring RC=RU on F2XM1(0.5) + got_ru = unpack80(call3(lifted["op_f2xm1_m80"], pack80(POS_HALF), pack16(0x0B7F), b"\x5a" * 10)) + assert got_ru != got_half + caught += 1 + # 4. Flushing 80-bit subnormal input to zero in FYL2X(1, 2^-16445) + got_sub = unpack80(call3(lifted["op_fyl2x_m80"], pack80(POS_ONE), pack80(SUB_POS_MIN), pack16(0x037F) + b"\x5a" * 8)) + assert got_sub != NEG_INF + caught += 1 + # 5. Missing #Z (ZE) flag on FYL2X(1, +0) and FYL2XP1(1, -1) + sw_z1 = unpack16(call3(lifted["op_fyl2x_sw"], pack80(POS_ONE), pack80(POS_ZERO), pack16(0x037F))) + sw_z2 = unpack16(call3(lifted["op_fyl2xp1_sw"], pack80(POS_ONE), pack80(NEG_ONE), pack16(0x037F))) + assert (sw_z1 & SW_ZE) != 0 and (sw_z2 & SW_ZE) != 0 + caught += 1 + # 6. Missing #IA (IE) flag on negative FYL2X base or sNaN + sw_ia1 = unpack16(call3(lifted["op_fyl2x_sw"], pack80(POS_ONE), pack80(NEG_ONE), pack16(0x037F))) + sw_ia2 = unpack16(call3(lifted["op_f2xm1_sw"], pack80(SNAN_A), pack16(0x037F), b"\x5a" * 2)) + assert (sw_ia1 & SW_IE) != 0 and (sw_ia2 & SW_IE) != 0 + caught += 1 + return caught + + +def record_covered_forms(original_path): + record = os.environ.get("FORM_COVERAGE_RECORD") + if not record: + return + formatter = Formatter(FormatterSyntax.INTEL) + forms = set() + with pefile.PE(str(original_path), fast_load=True) as pe: + for name in EXPORTS: + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + for ins in Decoder(64, raw, ip=entry): + forms.add(formatter.format_mnemonic(ins).lower()) + out_path = Path(record) + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text("".join(word + "\n" for word in sorted(forms)), encoding="utf-8") + + +def main(): + if os.environ.get("FORM_COVERAGE_RECORD"): + Path(os.environ["FORM_COVERAGE_RECORD"]).unlink(missing_ok=True) + + original_path, lifted_path, altered_path, altered_lifted_path = (Path(p) for p in sys.argv[1:5]) + + accepted, rejected = check_translator() + print(f"{accepted} x87 exp/log sequences accepted; {rejected} rejection controls passed") + + _, native = bind(original_path, "") + lifted_lib, lifted = bind(lifted_path, "lifted_") + _, altered = bind(altered_path, "") + _, altered_lifted = bind(altered_lifted_path, "lifted_") + + diff_total, max_ulp_ref, max_ulp_nat = check_differential(native, lifted, altered, altered_lifted) + mxcsr_total = check_mxcsr_isolation(native, lifted, lifted_lib) + mutant_count = check_mutants(lifted) + # Restore clean x87 state after native runs. + call3(native["op_fninit_sw"], pack80(POS_ZERO), b"\x00" * 16, b"\x5a" * 2) + + print( + f"{diff_total} differential/FCW/status/special cases matched " + f"(max ULP vs Decimal ref={max_ulp_ref}, vs native x87={max_ulp_nat}); " + f"{mxcsr_total} MXCSR DAZ/FTZ isolation checks passed; " + f"{mutant_count} mutant controls + {len(ALTERED_EXPORTS)} altered-build controls caught" + ) + record_covered_forms(original_path) + + +if __name__ == "__main__": + main() diff --git a/tools/cpu_x87_exp_log_aot.py b/tools/cpu_x87_exp_log_aot.py new file mode 100644 index 000000000..770ededbe --- /dev/null +++ b/tools/cpu_x87_exp_log_aot.py @@ -0,0 +1,1239 @@ +"""Lift bounded Windows x64 leaf functions using x87 F2XM1, FYL2X, and FYL2XP1 to C++. + +Each export uses the straight-line leaf ABI: + void lifted_(word rcx, word rdx, word r8) +where rcx, rdx, and r8 carry flat zero-displacement host pointers to caller-owned +buffers (rcx, rdx, and r8 may be read; only r8 may be written). + +All x87 values use a portable software 80-bit extended-precision representation +(explicit 64-bit significand + 15-bit biased exponent + sign bit) and pure +integer 128-bit intermediate arithmetic (zero host float/double/long double or +SSE/x87 instructions). This avoids MSVC's 64-bit `long double` truncation and +guarantees complete isolation from host MXCSR (DAZ/FTZ/rounding) without +clobbering MXCSR. + +Supported x87 transcendental instructions (docs/coverage/x64_zen2.tsv group x87): + - F2XM1 : ST(0) <- 2^ST(0) - 1 on the Intel SDM domain [-1, +1] + (<= 1 ULP vs hardware, <= 0.5 ULP vs exact math in 80-bit extended; + exact on +-0, +1, -1; preserves signed zero F2XM1(-0.0) == -0.0). + - FYL2X : ST(1) <- ST(1) * log2(ST(0)), then pop x87 stack (x > 0; + #Z (ZE) on x == +-0 with finite nonzero y; #IA (IE) on negative x, + (+-0, +-0), (+inf, +-0), (1, +-inf)). + - FYL2XP1 : ST(1) <- ST(1) * log2(ST(0) + 1), then pop x87 stack on the Intel + SDM domain [-(1 - sqrt(2)/2), +(1 - sqrt(2)/2)] (and models #Z (ZE) + on x == -1 with finite nonzero y, #IA (IE) on x < -1 or (+-0, +-inf)). + +Bounded leaf x87 stack/status/control transport: + - fld m32 / m64 / m80, fld1, fldz + - fst m32 / m64 + - fstp m32 / m64 / m80 / st(0) + - fnstsw ax (paired with mov word ptr [r8], ax when ax is defined) + - fldcw m16, fnstcw m16, fninit + - terminal ret (requires an empty x87 stack at ret) + +FCW rounding modes (RN/RD/RU/RZ) apply to transcendental results and m32/m64 +stores; FCW precision control (PC 24/53/64) is modeled in the control word +(preserved across fldcw/fnstcw) and, matching Intel SDM Vol. 1 8.1.5.2 and x87 +hardware, does not truncate F2XM1, FYL2X, or FYL2XP1 results. + +FSIN/FCOS/FSINCOS/FPTAN/FPATAN, stack overflow/underflow, non-empty x87 stack +at ret, XMM/YMM/ZMM/VEX/EVEX encodings, prefixes (including WAIT/9B), non-flat, +displaced, or indexed memory, stores outside [r8], branches, undefined ax reads, +missing ret, and trailing instructions after ret are rejected. +""" + +import argparse +from pathlib import Path + +import pefile +from iced_x86 import ( + Code, + Decoder, + EncodingKind, + FlowControl, + MemorySizeExt, + OpKind, + Register as R, + RegisterExt, +) + +from cpu_leaf_aot import bounded_code, export_rva + + +ARGUMENTS = {R.RCX: "rcx", R.RDX: "rdx", R.R8: "r8"} + +NONVOLATILE_GPR = { + R.RBX, R.EBX, R.BX, R.BL, R.BH, + R.RBP, R.EBP, R.BP, R.BPL, + R.RSI, R.ESI, R.SI, R.SIL, + R.RDI, R.EDI, R.DI, R.DIL, + R.RSP, R.ESP, R.SP, R.SPL, + R.R12, R.R12D, R.R12W, R.R12L, + R.R13, R.R13D, R.R13W, R.R13L, + R.R14, R.R14D, R.R14W, R.R14L, + R.R15, R.R15D, R.R15W, R.R15L, +} + +TRIG_REJECT_CODES = { + Code.FSIN, + Code.FCOS, + Code.FSINCOS, + Code.FPTAN, + Code.FPATAN, +} + +FLD_MEM_CODES = { + Code.FLD_M32FP: (4, "x87_load_f32"), + Code.FLD_M64FP: (8, "x87_load_f64"), + Code.FLD_M80FP: (10, "x87_load_m80"), +} + +FST_MEM_CODES = { + Code.FST_M32FP: (4, "x87_store_f32", False), + Code.FST_M64FP: (8, "x87_store_f64", False), + Code.FSTP_M32FP: (4, "x87_store_f32", True), + Code.FSTP_M64FP: (8, "x87_store_f64", True), + Code.FSTP_M80FP: (10, "x87_store_m80", True), +} + +ALLOWED_CODES = { + Code.RETNQ, + Code.F2XM1, + Code.FYL2X, + Code.FYL2XP1, + *FLD_MEM_CODES, + Code.FLD1, + Code.FLDZ, + *FST_MEM_CODES, + Code.FSTP_STI, + Code.FNSTSW_AX, + Code.FLDCW_M2BYTE, + Code.FNSTCW_M2BYTE, + Code.FNINIT, + Code.MOV_RM16_R16, +} + + +PRELUDE = r"""#include +#include +#include +#if defined(_MSC_VER) +#include +#endif + +#if defined(_MSC_VER) +// Test-only host MXCSR accessors used by tests/cpu/x87_exp_log_aot_check.py to +// verify DAZ/FTZ isolation and non-clobbering; lifted_* functions never touch SSE/MXCSR. +extern "C" __declspec(dllexport) std::uint32_t host_get_mxcsr() { + return _mm_getcsr(); +} + +extern "C" __declspec(dllexport) std::uint32_t host_exchange_mxcsr(std::uint32_t next) { + const std::uint32_t current = _mm_getcsr(); + _mm_setcsr(next); + return current; +} +#endif + +using word = std::uint64_t; + +// ---- Portable 80-bit extended-precision x87 state (pure integer arithmetic) ---- + +struct X87Val { + std::uint64_t sig; // Explicit integer bit in bit 63 + std::uint16_t se; // bit 15 = sign, bits 14:0 = biased exponent (bias 16383) +}; + +static constexpr std::uint64_t X87_JBIT = 0x8000000000000000ull; +static constexpr std::uint64_t X87_QBIT = 0x4000000000000000ull; +static constexpr X87Val X87_INDEF{0xc000000000000000ull, 0xffffu}; +static constexpr X87Val X87_POS_ZERO{0ull, 0x0000u}; +static constexpr X87Val X87_POS_ONE{X87_JBIT, 0x3fffu}; +static constexpr X87Val X87_NEG_ONE{X87_JBIT, 0xbfffu}; +static constexpr X87Val X87_NEG_HALF{X87_JBIT, 0xbffeu}; +static constexpr X87Val X87_POS_INF{X87_JBIT, 0x7fffu}; + +static constexpr std::uint16_t SW_IE = 0x0001u; +static constexpr std::uint16_t SW_DE = 0x0002u; +static constexpr std::uint16_t SW_ZE = 0x0004u; +static constexpr std::uint16_t SW_OE = 0x0008u; +static constexpr std::uint16_t SW_UE = 0x0010u; +static constexpr std::uint16_t SW_PE = 0x0020u; +static constexpr std::uint16_t SW_C1 = 0x0200u; + +struct X87State { + X87Val regs[8]{}; + std::uint16_t cw = 0x037fu; + std::uint16_t sw = 0x0000u; + unsigned top = 0u; +}; + +static inline std::uint16_t load16(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::uint16_t out = 0u; + std::memcpy(&out, reinterpret_cast(address), sizeof(out)); + const volatile std::uint16_t observed = out; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +static inline std::uint32_t load32(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::uint32_t out = 0u; + std::memcpy(&out, reinterpret_cast(address), sizeof(out)); + const volatile std::uint32_t observed = out; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +static inline std::uint64_t load64(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::uint64_t out = 0ull; + std::memcpy(&out, reinterpret_cast(address), sizeof(out)); + const volatile std::uint64_t observed = out; + std::atomic_signal_fence(std::memory_order_seq_cst); + return observed; +} + +static inline X87Val load80(word address) { + std::atomic_signal_fence(std::memory_order_seq_cst); + X87Val out{}; + std::memcpy(&out.sig, reinterpret_cast(address), 8); + std::memcpy(&out.se, reinterpret_cast(address + 8ull), 2); + const volatile std::uint64_t osig = out.sig; + const volatile std::uint16_t ose = out.se; + std::atomic_signal_fence(std::memory_order_seq_cst); + return {osig, ose}; +} + +static inline void store16(word address, std::uint16_t value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(value)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store32(word address, std::uint32_t value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(value)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store64(word address, std::uint64_t value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value, sizeof(value)); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline void store80(word address, X87Val value) { + std::atomic_signal_fence(std::memory_order_seq_cst); + std::memcpy(reinterpret_cast(address), &value.sig, 8); + std::memcpy(reinterpret_cast(address + 8ull), &value.se, 2); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +static inline int clz64(std::uint64_t x) { + if (x == 0ull) return 64; + int n = 0; + if ((x & 0xffffffff00000000ull) == 0ull) { n += 32; x <<= 32; } + if ((x & 0xffff000000000000ull) == 0ull) { n += 16; x <<= 16; } + if ((x & 0xff00000000000000ull) == 0ull) { n += 8; x <<= 8; } + if ((x & 0xf000000000000000ull) == 0ull) { n += 4; x <<= 4; } + if ((x & 0xc000000000000000ull) == 0ull) { n += 2; x <<= 2; } + if ((x & 0x8000000000000000ull) == 0ull) { n += 1; } + return n; +} + +static inline void mul64x64(std::uint64_t a, std::uint64_t b, std::uint64_t& hi, std::uint64_t& lo) { + const std::uint64_t a0 = a & 0xffffffffull, a1 = a >> 32; + const std::uint64_t b0 = b & 0xffffffffull, b1 = b >> 32; + const std::uint64_t p00 = a0 * b0; + const std::uint64_t p01 = a0 * b1; + const std::uint64_t p10 = a1 * b0; + const std::uint64_t p11 = a1 * b1; + const std::uint64_t mid = (p00 >> 32) + (p01 & 0xffffffffull) + (p10 & 0xffffffffull); + lo = (p00 & 0xffffffffull) | (mid << 32); + hi = p11 + (p01 >> 32) + (p10 >> 32) + (mid >> 32); +} + +static inline void shr128_sticky(std::uint64_t& hi, std::uint64_t& lo, int n) { + if (n <= 0) return; + if (n >= 128) { + lo = (hi | lo) != 0ull ? 1ull : 0ull; + hi = 0ull; + return; + } + std::uint64_t sticky = 0ull; + if (n >= 64) { + const int m = n - 64; + sticky = (lo != 0ull || (m != 0 && (hi << (64 - m)) != 0ull)) ? 1ull : 0ull; + lo = (m != 0) ? (hi >> m) : hi; + hi = 0ull; + } else { + sticky = ((lo << (64 - n)) != 0ull) ? 1ull : 0ull; + lo = (lo >> n) | (hi << (64 - n)); + hi >>= n; + } + lo |= sticky; +} + +static inline unsigned x87_rc(std::uint16_t cw) { return (cw >> 10) & 3u; } +static inline unsigned x87_exp(X87Val v) { return v.se & 0x7fffu; } +static inline bool x87_sign(X87Val v) { return (v.se & 0x8000u) != 0u; } +static inline bool x87_unsupported(X87Val v) { return x87_exp(v) != 0u && (v.sig & X87_JBIT) == 0ull; } +static inline bool x87_is_nan(X87Val v) { return x87_exp(v) == 0x7fffu && (v.sig & X87_JBIT) != 0ull && (v.sig << 1) != 0ull; } +static inline bool x87_is_snan(X87Val v) { return x87_is_nan(v) && (v.sig & X87_QBIT) == 0ull; } +static inline bool x87_is_qnan(X87Val v) { return x87_is_nan(v) && (v.sig & X87_QBIT) != 0ull; } +static inline bool x87_is_inf(X87Val v) { return x87_exp(v) == 0x7fffu && v.sig == X87_JBIT; } +static inline bool x87_is_zero(X87Val v) { return x87_exp(v) == 0u && v.sig == 0ull; } +static inline bool x87_is_denorm(X87Val v) { return x87_exp(v) == 0u && v.sig != 0ull; } +static inline X87Val x87_quiet(X87Val v) { v.sig |= X87_QBIT; return v; } + +static inline X87Val x87_make_zero(bool sign) { return {0ull, sign ? std::uint16_t{0x8000u} : std::uint16_t{0x0000u}}; } +static inline X87Val x87_make_inf(bool sign) { return {X87_JBIT, static_cast((sign ? 0x8000u : 0u) | 0x7fffu)}; } + +static inline void x87_set_c1(std::uint16_t& sw, bool up) { + if (up) sw |= SW_C1; + else sw &= static_cast(~SW_C1); +} + +static inline void x87_push(X87State& st, X87Val v) { + st.top = (st.top - 1u) & 7u; + st.regs[st.top] = v; +} + +static inline X87Val x87_pop(X87State& st) { + const X87Val v = st.regs[st.top]; + st.top = (st.top + 1u) & 7u; + return v; +} + +static inline X87Val& x87_st(X87State& st, unsigned i) { + return st.regs[(st.top + i) & 7u]; +} + +static inline std::uint16_t x87_status_word(const X87State& st) { + return static_cast((st.sw & ~0x3800u) | ((st.top & 7u) << 11)); +} + +static inline void x87_fninit(X87State& st) { + for (unsigned i = 0u; i < 8u; ++i) st.regs[i] = X87_POS_ZERO; + st.cw = 0x037fu; + st.sw = 0x0000u; + st.top = 0u; +} + +// ---- Binary32 / Binary64 / Raw80 load and store conversions ---- + +static inline X87Val x87_from_binary(std::uint64_t bits, int frac_bits, int exp_bits, int bias, std::uint16_t& sw) { + const bool sign = ((bits >> (frac_bits + exp_bits)) & 1ull) != 0ull; + const std::uint16_t s = sign ? 0x8000u : 0u; + const std::uint64_t exp_mask = (1ull << exp_bits) - 1ull; + const std::uint64_t frac_mask = (1ull << frac_bits) - 1ull; + const int exponent = static_cast((bits >> frac_bits) & exp_mask); + const std::uint64_t fraction = bits & frac_mask; + if (exponent == static_cast(exp_mask)) { + if (fraction == 0ull) return {X87_JBIT, static_cast(s | 0x7fffu)}; + X87Val nan{X87_JBIT | (fraction << (63 - frac_bits)), static_cast(s | 0x7fffu)}; + if (x87_is_snan(nan)) sw |= SW_IE; + return x87_quiet(nan); + } + if (exponent == 0) { + if (fraction == 0ull) return {0ull, s}; + sw |= SW_DE; + const int shift = clz64(fraction); + const int e = 1 - bias - frac_bits + (63 - shift); + return {fraction << shift, static_cast(s | static_cast(e + 16383))}; + } + return {X87_JBIT | (fraction << (63 - frac_bits)), + static_cast(s | static_cast(exponent - bias + 16383))}; +} + +static inline void x87_load_f32(X87State& st, word addr) { + x87_push(st, x87_from_binary(load32(addr), 23, 8, 127, st.sw)); +} + +static inline void x87_load_f64(X87State& st, word addr) { + x87_push(st, x87_from_binary(load64(addr), 52, 11, 1023, st.sw)); +} + +static inline void x87_load_m80(X87State& st, word addr) { + x87_push(st, load80(addr)); +} + +static inline std::uint64_t x87_to_binary(X87Val v, int frac_bits, int exp_bits, int bias, int emax, + std::uint16_t cw, std::uint16_t& sw) { + const int sign_bit = frac_bits + exp_bits; + const std::uint64_t sign_mask = static_cast(x87_sign(v) ? 1u : 0u) << sign_bit; + const std::uint64_t exp_all = static_cast(emax + 1) << frac_bits; + const std::uint64_t qbit = 1ull << (frac_bits - 1); + const std::uint64_t frac_mask = (1ull << frac_bits) - 1ull; + if (x87_unsupported(v)) { + sw |= SW_IE; + return (1ull << sign_bit) | exp_all | qbit; + } + if (x87_is_nan(v)) { + if (x87_is_snan(v)) sw |= SW_IE; + return sign_mask | exp_all | qbit | ((v.sig >> (63 - frac_bits)) & frac_mask); + } + if (x87_is_inf(v)) return sign_mask | exp_all; + if (x87_is_zero(v)) return sign_mask; + + const bool sign = x87_sign(v); + std::int32_t e = 0; + std::uint64_t hi = v.sig, lo = 0ull; + if (x87_exp(v) != 0u) { + e = static_cast(x87_exp(v)) - 16383; + } else { + const int shift = clz64(v.sig); + e = 1 - 16383 - shift; + hi = v.sig << shift; + } + std::int32_t biased = e + bias; + bool tiny = false; + if (biased <= 0) { + shr128_sticky(hi, lo, 1 - biased); + biased = 0; + tiny = true; + } + const int precision = frac_bits + 1; + const int drop = 64 - precision; + const std::uint64_t unit = 1ull << drop; + const std::uint64_t mask = unit - 1ull; + const std::uint64_t rest = hi & mask; + const std::uint64_t middle = unit >> 1; + const bool above = (rest > middle) || (rest == middle && lo != 0ull); + const bool half = (rest == middle && lo == 0ull); + const bool inexact = (rest != 0ull || lo != 0ull); + hi &= ~mask; + const unsigned rc = x87_rc(cw); + bool up = false; + switch (rc) { + case 0u: up = above || (half && (hi & unit) != 0ull); break; + case 1u: up = sign && inexact; break; + case 2u: up = !sign && inexact; break; + default: break; + } + if (up) { + hi += unit; + if (hi == 0ull) { hi = X87_JBIT; ++biased; } + } + if (biased == 0 && (hi & X87_JBIT) != 0ull) biased = 1; + if (biased > emax) { + sw |= static_cast(SW_OE | SW_PE); + const bool to_inf = (rc == 0u) || (rc == 1u && sign) || (rc == 2u && !sign); + x87_set_c1(sw, to_inf); + if (to_inf) return sign_mask | exp_all; + return sign_mask | (static_cast(emax) << frac_bits) | frac_mask; + } + if (tiny && inexact) sw |= SW_UE; + if (inexact) sw |= SW_PE; + x87_set_c1(sw, up); + return sign_mask | (static_cast(biased) << frac_bits) | ((hi >> (63 - frac_bits)) & frac_mask); +} + +static inline void x87_store_f32(X87State& st, word addr, bool pop) { + const X87Val v = pop ? x87_pop(st) : x87_st(st, 0u); + store32(addr, static_cast(x87_to_binary(v, 23, 8, 127, 0xfe, st.cw, st.sw))); +} + +static inline void x87_store_f64(X87State& st, word addr, bool pop) { + const X87Val v = pop ? x87_pop(st) : x87_st(st, 0u); + store64(addr, x87_to_binary(v, 52, 11, 1023, 0x7fe, st.cw, st.sw)); +} + +static inline void x87_store_m80(X87State& st, word addr, bool pop) { + const X87Val v = pop ? x87_pop(st) : x87_st(st, 0u); + store80(addr, v); +} + +// ---- 128-bit normalized software floating-point engine (BigF) ---- +// Value = (-1)^sign * (hi:lo / 2^127) * 2^exp with bit 63 of hi set when !zero. + +struct BigF { + bool sign; + bool zero; + std::int32_t exp; + std::uint64_t hi; + std::uint64_t lo; +}; + +static constexpr BigF BIGF_ZERO{false, true, 0, 0ull, 0ull}; +static constexpr BigF BIGF_ONE{false, false, 0, X87_JBIT, 0ull}; +static constexpr BigF BIGF_TWO{false, false, 1, X87_JBIT, 0ull}; +// Exact 128-bit constants computed to >100 decimal digits: +static constexpr BigF BIGF_LN2{false, false, -1, 0xb17217f7d1cf79abull, 0xc9e3b39803f2f6afull}; +static constexpr BigF BIGF_INV_LN2{false, false, 0, 0xb8aa3b295c17f0bbull, 0xbe87fed0691d3e89ull}; +static constexpr std::uint64_t SQRT2_HI = 0xb504f333f9de6484ull; +static constexpr std::uint64_t SQRT2_LO = 0x597d89b3754abe9full; + +static inline BigF bigf_neg(BigF a) { + if (!a.zero) a.sign = !a.sign; + return a; +} + +static inline BigF bigf_from_x87(X87Val v) { + if (x87_is_zero(v)) return {x87_sign(v), true, 0, 0ull, 0ull}; + if (x87_exp(v) != 0u) { + return {x87_sign(v), false, static_cast(x87_exp(v)) - 16383, v.sig, 0ull}; + } + const int shift = clz64(v.sig); + return {x87_sign(v), false, 1 - 16383 - shift, v.sig << shift, 0ull}; +} + +static inline BigF bigf_from_i32(std::int32_t n) { + if (n == 0) return BIGF_ZERO; + const bool sign = n < 0; + const std::uint64_t mag = sign ? (0ull - static_cast(static_cast(n))) + : static_cast(n); + const int shift = clz64(mag); + return {sign, false, 63 - shift, mag << shift, 0ull}; +} + +static inline BigF bigf_norm_round(bool sign, std::int32_t exp, std::uint64_t hi, std::uint64_t lo, std::uint64_t guard) { + if (hi == 0ull && lo == 0ull && guard == 0ull) return BIGF_ZERO; + while ((hi & X87_JBIT) == 0ull) { + if (hi == 0ull && lo == 0ull) { + const int s = clz64(guard); + hi = guard << s; + guard = 0ull; + exp -= 128 + s; + break; + } + if (hi == 0ull) { + hi = lo; + lo = guard; + guard = 0ull; + exp -= 64; + continue; + } + const int s = clz64(hi); + hi = (hi << s) | (lo >> (64 - s)); + lo = (lo << s) | (guard >> (64 - s)); + guard <<= s; + exp -= s; + break; + } + if (guard > X87_JBIT || (guard == X87_JBIT && (lo & 1ull) != 0ull)) { + ++lo; + if (lo == 0ull) { + ++hi; + if (hi == 0ull) { + hi = X87_JBIT; + ++exp; + } + } + } + return {sign, false, exp, hi, lo}; +} + +static inline BigF bigf_add(BigF a, BigF b) { + if (a.zero) return b; + if (b.zero) return a; + const bool a_lt_b = (a.exp < b.exp) || (a.exp == b.exp && (a.hi < b.hi || (a.hi == b.hi && a.lo < b.lo))); + if (a_lt_b) { + const BigF t = a; + a = b; + b = t; + } + const std::int32_t diff = a.exp - b.exp; + if (diff >= 130) return a; + std::uint64_t bhi = b.hi, blo = b.lo, bg = 0ull; + if (diff > 0) { + if (diff >= 128) { + const int m = diff - 128; + const std::uint64_t sticky = (blo != 0ull || (m != 0 && (bhi << (64 - m)) != 0ull)) ? 1ull : 0ull; + bg = ((m != 0) ? (bhi >> m) : bhi) | sticky; + bhi = 0ull; + blo = 0ull; + } else if (diff >= 64) { + const int m = diff - 64; + const std::uint64_t sticky = (m != 0 && (blo << (64 - m)) != 0ull) ? 1ull : 0ull; + bg = ((m != 0) ? ((blo >> m) | (bhi << (64 - m))) : blo) | sticky; + blo = (m != 0) ? (bhi >> m) : bhi; + bhi = 0ull; + } else { + const std::uint64_t sticky = 0ull; + bg = (blo << (64 - diff)) | sticky; + blo = (blo >> diff) | (bhi << (64 - diff)); + bhi >>= diff; + } + } + std::int32_t exp = a.exp; + if (a.sign == b.sign) { + const std::uint64_t g = bg; + const std::uint64_t lo = a.lo + blo; + const std::uint64_t c0 = (lo < a.lo) ? 1ull : 0ull; + const std::uint64_t hi_t = a.hi + bhi; + const std::uint64_t c1 = (hi_t < a.hi) ? 1ull : 0ull; + const std::uint64_t hi = hi_t + c0; + const std::uint64_t carry = c1 + ((hi < hi_t) ? 1ull : 0ull); + if (carry != 0ull) { + const std::uint64_t ng = (g >> 1) | (lo << 63) | (g & 1ull); + const std::uint64_t nlo = (lo >> 1) | (hi << 63); + const std::uint64_t nhi = (hi >> 1) | X87_JBIT; + return bigf_norm_round(a.sign, exp + 1, nhi, nlo, ng); + } + return bigf_norm_round(a.sign, exp, hi, lo, g); + } else { + const std::uint64_t borrow_g = (bg != 0ull) ? 1ull : 0ull; + const std::uint64_t g = 0ull - bg; + const std::uint64_t blo_b = blo + borrow_g; + const std::uint64_t c_lo = (borrow_g != 0ull && blo_b == 0ull) ? 1ull : 0ull; + const std::uint64_t borrow_lo = (c_lo != 0ull || a.lo < blo_b) ? 1ull : 0ull; + const std::uint64_t lo = a.lo - blo_b; + const std::uint64_t hi = a.hi - bhi - borrow_lo; + return bigf_norm_round(a.sign, exp, hi, lo, g); + } +} + +static inline BigF bigf_sub(BigF a, BigF b) { + return bigf_add(a, bigf_neg(b)); +} + +static inline BigF bigf_mul(BigF a, BigF b) { + if (a.zero || b.zero) return BIGF_ZERO; + std::uint64_t hh_hi, hh_lo, hl_hi, hl_lo, lh_hi, lh_lo, ll_hi, ll_lo; + mul64x64(a.hi, b.hi, hh_hi, hh_lo); + mul64x64(a.hi, b.lo, hl_hi, hl_lo); + mul64x64(a.lo, b.hi, lh_hi, lh_lo); + mul64x64(a.lo, b.lo, ll_hi, ll_lo); + + std::uint64_t w1 = ll_hi; + std::uint64_t c1 = 0ull; + w1 += hl_lo; if (w1 < hl_lo) ++c1; + w1 += lh_lo; if (w1 < lh_lo) ++c1; + + std::uint64_t w2 = hh_lo; + std::uint64_t c2 = 0ull; + w2 += hl_hi; if (w2 < hl_hi) ++c2; + w2 += lh_hi; if (w2 < lh_hi) ++c2; + w2 += c1; if (w2 < c1) ++c2; + + const std::uint64_t w3 = hh_hi + c2; + std::uint64_t guard = w1 | (ll_lo != 0ull ? 1ull : 0ull); + std::int32_t exp = a.exp + b.exp; + if ((w3 & X87_JBIT) != 0ull) { + return bigf_norm_round(a.sign != b.sign, exp + 1, w3, w2, guard); + } + const std::uint64_t nhi = (w3 << 1) | (w2 >> 63); + const std::uint64_t nlo = (w2 << 1) | (guard >> 63); + const std::uint64_t ng = (guard << 1) | (ll_lo != 0ull ? 1ull : 0ull); + return bigf_norm_round(a.sign != b.sign, exp, nhi, nlo, ng); +} + +static inline BigF bigf_div_u32(BigF a, std::uint32_t d) { + if (a.zero) return BIGF_ZERO; + const std::uint64_t limbs[6] = { + a.hi >> 32, a.hi & 0xffffffffull, a.lo >> 32, a.lo & 0xffffffffull, 0ull, 0ull + }; + std::uint64_t q[6]{}; + std::uint64_t rem = 0ull; + for (int i = 0; i < 6; ++i) { + const std::uint64_t cur = (rem << 32) | limbs[i]; + q[i] = cur / d; + rem = cur % d; + } + const std::uint64_t hi = (q[0] << 32) | q[1]; + const std::uint64_t lo = (q[2] << 32) | q[3]; + const std::uint64_t guard = (q[4] << 32) | q[5] | (rem != 0ull ? 1ull : 0ull); + return bigf_norm_round(a.sign, a.exp, hi, lo, guard); +} + +static inline BigF bigf_div(BigF a, BigF b) { + if (a.zero) return BIGF_ZERO; + std::uint64_t q_hi = 0ull, q_lo = 0ull; + std::uint64_t r_top = 0ull, r_hi = a.hi, r_lo = a.lo; + std::int32_t exp = a.exp - b.exp; + + auto ge_b = [&]() -> bool { + return r_top != 0ull || r_hi > b.hi || (r_hi == b.hi && r_lo >= b.lo); + }; + auto sub_b = [&]() { + const std::uint64_t b0 = (r_lo < b.lo) ? 1ull : 0ull; + const std::uint64_t nlo = r_lo - b.lo; + const std::uint64_t bhi_b = b.hi + b0; + const std::uint64_t b1 = ((b0 != 0ull && bhi_b == 0ull) || r_hi < bhi_b) ? 1ull : 0ull; + r_hi -= bhi_b; + r_lo = nlo; + r_top -= b1; + }; + auto shl_r = [&]() { + r_top = r_hi >> 63; + r_hi = (r_hi << 1) | (r_lo >> 63); + r_lo <<= 1; + }; + + if (!ge_b()) { + shl_r(); + --exp; + } + for (int bit = 127; bit >= 0; --bit) { + if (ge_b()) { + sub_b(); + if (bit >= 64) q_hi |= (1ull << (bit - 64)); + else q_lo |= (1ull << bit); + } + shl_r(); + } + std::uint64_t guard = 0ull; + if (ge_b()) { + sub_b(); + guard = X87_JBIT; + } + if (r_top != 0ull || r_hi != 0ull || r_lo != 0ull) guard |= 1ull; + return bigf_norm_round(a.sign != b.sign, exp, q_hi, q_lo, guard); +} + +static inline X87Val bigf_to_x87(BigF v, std::uint16_t cw, std::uint16_t& sw) { + if (v.zero) { + x87_set_c1(sw, false); + return x87_make_zero(v.sign); + } + std::int32_t biased = v.exp + 16383; + std::uint64_t sig = v.hi; + std::uint64_t rem = v.lo; + bool tiny = false; + if (biased <= 0) { + shr128_sticky(sig, rem, 1 - biased); + biased = 0; + tiny = true; + } + const bool above = rem > X87_JBIT; + const bool half = rem == X87_JBIT; + const bool inexact = rem != 0ull; + const unsigned rc = x87_rc(cw); + bool up = false; + switch (rc) { + case 0u: up = above || (half && (sig & 1ull) != 0ull); break; + case 1u: up = v.sign && inexact; break; + case 2u: up = !v.sign && inexact; break; + default: break; + } + if (up) { + ++sig; + if (sig == 0ull) { + sig = X87_JBIT; + ++biased; + } + } + if (biased == 0 && (sig & X87_JBIT) != 0ull) biased = 1; + if (biased > 0x7ffe) { + sw |= static_cast(SW_OE | SW_PE); + const bool to_inf = (rc == 0u) || (rc == 1u && v.sign) || (rc == 2u && !v.sign); + x87_set_c1(sw, to_inf); + if (to_inf) return x87_make_inf(v.sign); + return {0xffffffffffffffffull, static_cast((v.sign ? 0x8000u : 0u) | 0x7ffeu)}; + } + if (tiny && inexact) sw |= SW_UE; + if (inexact) sw |= SW_PE; + x87_set_c1(sw, up); + if (biased == 0 && sig == 0ull) return x87_make_zero(v.sign); + return {sig, static_cast((v.sign ? 0x8000u : 0u) | static_cast(biased))}; +} + +// ---- Core 128-bit transcendental kernels ---- + +// expm1(u) = e^u - 1 via argument halving (|z| < 2^-8) + 16-term Taylor series + +// exact doubling identity expm1(2t) = 2*expm1(t) + expm1(t)^2. +static inline BigF bigf_expm1(BigF u) { + if (u.zero) return u; + int k = 0; + BigF z = u; + while (z.exp >= -8 && k < 24) { + --z.exp; + ++k; + } + BigF term = z; + BigF sum = z; + for (std::uint32_t n = 2u; n <= 18u; ++n) { + term = bigf_div_u32(bigf_mul(term, z), n); + if (term.zero) break; + sum = bigf_add(sum, term); + if (!sum.zero && term.exp < sum.exp - 130) break; + } + for (int i = 0; i < k; ++i) { + BigF two_sum = sum; + if (!two_sum.zero) ++two_sum.exp; + sum = bigf_add(two_sum, bigf_mul(sum, sum)); + } + return sum; +} + +// 2 * atanh(s) = 2 * (s + s^3/3 + s^5/5 + ...) for |s| <= 3 - 2*sqrt(2) (~0.1716). +static inline BigF bigf_two_atanh(BigF s) { + if (s.zero) return BIGF_ZERO; + const BigF s2 = bigf_mul(s, s); + BigF power = s; + BigF sum = s; + for (std::uint32_t d = 3u; d <= 57u; d += 2u) { + power = bigf_mul(power, s2); + if (power.zero) break; + const BigF term = bigf_div_u32(power, d); + sum = bigf_add(sum, term); + if (!sum.zero && term.exp < sum.exp - 130) break; + } + if (!sum.zero) ++sum.exp; // multiply by 2 + return sum; +} + +// log2(m * 2^e) for positive BigF v = m * 2^e. +static inline BigF bigf_log2_pos(BigF v) { + std::int32_t e = v.exp; + BigF m = {false, false, 0, v.hi, v.lo}; // m in [1, 2) + if (m.hi > SQRT2_HI || (m.hi == SQRT2_HI && m.lo > SQRT2_LO)) { + m.exp = -1; // m in (sqrt(2)/2, 1) + ++e; + } + if (m.exp == 0 && m.hi == X87_JBIT && m.lo == 0ull) { + return bigf_from_i32(e); + } + const BigF num = bigf_sub(m, BIGF_ONE); + const BigF den = bigf_add(m, BIGF_ONE); + const BigF ln_m = bigf_two_atanh(bigf_div(num, den)); + const BigF log2_m = bigf_mul(ln_m, BIGF_INV_LN2); + if (e == 0) return log2_m; + return bigf_add(bigf_from_i32(e), log2_m); +} + +// ---- x87 NaN/unsupported helper ---- + +static inline bool x87_binary_special(X87Val a, X87Val b, std::uint16_t& sw, X87Val& out) { + if (x87_unsupported(a) || x87_unsupported(b)) { + sw |= SW_IE; + out = X87_INDEF; + return true; + } + const bool na = x87_is_nan(a); + const bool nb = x87_is_nan(b); + if (!na && !nb) return false; + if (x87_is_snan(a) || x87_is_snan(b)) sw |= SW_IE; + if (na && nb) { + if (x87_is_qnan(a) != x87_is_qnan(b)) out = x87_is_qnan(a) ? a : b; + else out = (b.sig > a.sig || (b.sig == a.sig && !x87_sign(b))) ? b : a; + } else { + out = na ? a : b; + } + out = x87_quiet(out); + return true; +} + +// ---- F2XM1, FYL2X, FYL2XP1 ---- + +static inline void x87_f2xm1(X87State& st) { + X87Val& x = x87_st(st, 0u); + if (x87_unsupported(x)) { + st.sw |= SW_IE; + x = X87_INDEF; + return; + } + if (x87_is_nan(x)) { + if (x87_is_snan(x)) st.sw |= SW_IE; + x = x87_quiet(x); + return; + } + if (x87_is_zero(x)) { + // Preserves signed zero: F2XM1(+0.0) == +0.0, F2XM1(-0.0) == -0.0. + x87_set_c1(st.sw, false); + return; + } + if (x87_is_inf(x)) { + x87_set_c1(st.sw, false); + x = x87_sign(x) ? X87_NEG_ONE : X87_POS_INF; + return; + } + if (x87_is_denorm(x)) st.sw |= SW_DE; + if (x.se == 0x3fffu && x.sig == X87_JBIT) { + x87_set_c1(st.sw, false); + x = X87_POS_ONE; + return; + } + if (x.se == 0xbfffu && x.sig == X87_JBIT) { + x87_set_c1(st.sw, false); + x = X87_NEG_HALF; + return; + } + const BigF u = bigf_mul(bigf_from_x87(x), BIGF_LN2); + const BigF r = bigf_expm1(u); + x = bigf_to_x87(r, st.cw, st.sw); +} + +static inline void x87_fyl2x(X87State& st) { + const X87Val x = x87_pop(st); // ST(0) + X87Val& y = x87_st(st, 0u); // Former ST(1) + X87Val special{}; + if (x87_binary_special(y, x, st.sw, special)) { + y = special; + return; + } + const bool x_zero = x87_is_zero(x); + const bool y_zero = x87_is_zero(y); + const bool x_inf = x87_is_inf(x); + const bool y_inf = x87_is_inf(y); + if (x87_sign(x) && !x_zero) { + // Negative base (finite, subnormal, or -inf): #IA -> indefinite. + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (x_zero) { + if (y_zero) { + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (y_inf) { + x87_set_c1(st.sw, false); + y = x87_make_inf(!x87_sign(y)); + return; + } + if (x87_is_denorm(y)) st.sw |= SW_DE; + st.sw |= SW_ZE; + x87_set_c1(st.sw, false); + y = x87_make_inf(!x87_sign(y)); + return; + } + if (x_inf) { + if (y_zero) { + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (x87_is_denorm(y)) st.sw |= SW_DE; + x87_set_c1(st.sw, false); + y = x87_make_inf(x87_sign(y)); + return; + } + if (x.se == 0x3fffu && x.sig == X87_JBIT) { + // x == +1.0 -> log2(1) == +0.0. + if (y_inf) { + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (x87_is_denorm(y)) st.sw |= SW_DE; + x87_set_c1(st.sw, false); + y = x87_make_zero(x87_sign(y)); + return; + } + if (x87_is_denorm(x) || x87_is_denorm(y)) st.sw |= SW_DE; + const bool log_neg = x87_exp(x) < 0x3fffu; + if (y_zero) { + x87_set_c1(st.sw, false); + y = x87_make_zero(x87_sign(y) != log_neg); + return; + } + if (y_inf) { + x87_set_c1(st.sw, false); + y = x87_make_inf(x87_sign(y) != log_neg); + return; + } + const BigF log2_x = bigf_log2_pos(bigf_from_x87(x)); + const BigF prod = bigf_mul(bigf_from_x87(y), log2_x); + y = bigf_to_x87(prod, st.cw, st.sw); +} + +static inline void x87_fyl2xp1(X87State& st) { + const X87Val x = x87_pop(st); // ST(0) + X87Val& y = x87_st(st, 0u); // Former ST(1) + X87Val special{}; + if (x87_binary_special(y, x, st.sw, special)) { + y = special; + return; + } + const bool x_zero = x87_is_zero(x); + const bool y_zero = x87_is_zero(y); + const bool x_inf = x87_is_inf(x); + const bool y_inf = x87_is_inf(y); + if (x_zero) { + if (y_inf) { + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (x87_is_denorm(y)) st.sw |= SW_DE; + x87_set_c1(st.sw, false); + y = x87_make_zero(x87_sign(y) != x87_sign(x)); + return; + } + if (x.se == 0xbfffu && x.sig == X87_JBIT) { + // x == -1.0 -> log2(0) == -inf (#Z for finite nonzero y; #IA for y == +-0). + if (y_zero) { + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (y_inf) { + x87_set_c1(st.sw, false); + y = x87_make_inf(!x87_sign(y)); + return; + } + if (x87_is_denorm(y)) st.sw |= SW_DE; + st.sw |= SW_ZE; + x87_set_c1(st.sw, false); + y = x87_make_inf(!x87_sign(y)); + return; + } + if (x87_sign(x) && (x_inf || x87_exp(x) > 0x3fffu || (x87_exp(x) == 0x3fffu && x.sig > X87_JBIT))) { + // x < -1.0 -> log2(x + 1) domain error (#IA). + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (x_inf) { + if (y_zero) { + st.sw |= SW_IE; + y = X87_INDEF; + return; + } + if (x87_is_denorm(y)) st.sw |= SW_DE; + x87_set_c1(st.sw, false); + y = x87_make_inf(x87_sign(y)); + return; + } + if (x87_is_denorm(x) || x87_is_denorm(y)) st.sw |= SW_DE; + const bool log_neg = x87_sign(x); + if (y_zero) { + x87_set_c1(st.sw, false); + y = x87_make_zero(x87_sign(y) != log_neg); + return; + } + if (y_inf) { + x87_set_c1(st.sw, false); + y = x87_make_inf(x87_sign(y) != log_neg); + return; + } + const BigF bx = bigf_from_x87(x); + BigF log2_xp1{}; + if (bx.exp <= -2) { + // |x| < 0.5 (covers entire SDM domain |x| <= 1 - sqrt(2)/2 without cancellation): + // log2(1 + x) = 2 * atanh(x / (2 + x)) / ln(2). + const BigF s = bigf_div(bx, bigf_add(BIGF_TWO, bx)); + log2_xp1 = bigf_mul(bigf_two_atanh(s), BIGF_INV_LN2); + } else { + log2_xp1 = bigf_log2_pos(bigf_add(BIGF_ONE, bx)); + } + const BigF prod = bigf_mul(bigf_from_x87(y), log2_xp1); + y = bigf_to_x87(prod, st.cw, st.sw); +} +""" + + +def flat_address(ins, *, width, store=False): + """Lower a flat zero-displacement [rcx|rdx|r8] memory operand of exact byte width.""" + base = ins.memory_base + if ( + ins.is_ip_rel_memory_operand + or base in (R.NONE, R.RIP, R.EIP, R.RSP, R.ESP) + or ins.memory_index != R.NONE + or not RegisterExt.is_gpr64(base) + ): + raise ValueError(f"unsupported memory operand at RVA {ins.ip:#x}: {ins}") + if base in NONVOLATILE_GPR: + raise ValueError(f"nonvolatile GPR base {base} in memory operand at RVA {ins.ip:#x}: {ins}") + if base not in ARGUMENTS: + raise ValueError(f"unsupported memory base {base} at RVA {ins.ip:#x}: {ins}") + if MemorySizeExt.size(ins.memory_size) != width: + raise ValueError(f"unsupported memory width at RVA {ins.ip:#x}: {ins}") + if store and base != R.R8: + raise ValueError(f"store outside output buffer r8 at RVA {ins.ip:#x}: {ins}") + disp = ins.memory_displacement & ((1 << 64) - 1) + if disp != 0: + raise ValueError(f"unsupported displaced memory operand at RVA {ins.ip:#x}: {ins}") + return ARGUMENTS[base] + + +def _has_vector_register(ins): + for i in range(ins.op_count): + if ins.op_kind(i) == OpKind.REGISTER: + reg = ins.op_register(i) + if RegisterExt.is_vector_register(reg): + return True + return False + + +def lift_code(name, start, raw): + """Decode and lift one bounded straight-line x87 exp/log leaf function.""" + instructions = list(Decoder(64, raw, ip=start)) + if not instructions or instructions[-1].next_ip != start + len(raw): + raise ValueError(f"truncated instruction stream in {name} at RVA {start:#x}") + if any(ins.is_invalid for ins in instructions): + bad = next(ins for ins in instructions if ins.is_invalid) + raise ValueError(f"invalid instruction at RVA {bad.ip:#x}") + + depth = 0 + ax_defined = False + used_ax = False + statements = [] + returned = False + + def push_check(ins): + nonlocal depth + if depth >= 8: + raise ValueError(f"x87 stack overflow at RVA {ins.ip:#x}: {ins}") + depth += 1 + + def need_depth(ins, n): + if depth < n: + raise ValueError(f"x87 stack underflow at RVA {ins.ip:#x}: {ins}") + + for ins in instructions: + if returned: + raise ValueError(f"unreachable instruction after ret at RVA {ins.ip:#x}: {ins}") + if ( + ins.has_lock_prefix + or ins.has_rep_prefix + or ins.has_repne_prefix + or ins.has_segment_prefix + or ins.has_xacquire_prefix + or ins.has_xrelease_prefix + ): + raise ValueError(f"unsupported instruction prefix at RVA {ins.ip:#x}: {ins}") + op_code = ins.op_code() + if ( + op_code.encoding == EncodingKind.EVEX + or ins.op_mask != R.NONE + or ins.zeroing_masking + or ins.is_broadcast + ): + raise ValueError(f"unsupported EVEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding == EncodingKind.VEX: + raise ValueError(f"unsupported VEX encoding at RVA {ins.ip:#x}: {ins}") + if op_code.encoding != EncodingKind.LEGACY: + raise ValueError(f"unsupported non-legacy encoding at RVA {ins.ip:#x}: {ins}") + if _has_vector_register(ins): + raise ValueError(f"unsupported vector instruction at RVA {ins.ip:#x}: {ins}") + if ins.code in TRIG_REJECT_CODES: + raise ValueError(f"unsupported x87 trigonometric instruction at RVA {ins.ip:#x}: {ins}") + if ins.flow_control not in (FlowControl.NEXT, FlowControl.RETURN): + raise ValueError(f"unsupported control-flow instruction at RVA {ins.ip:#x}: {ins}") + if ins.code not in ALLOWED_CODES: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if ins.code == Code.RETNQ: + if depth != 0: + raise ValueError(f"non-empty x87 stack at ret (depth={depth}) at RVA {ins.ip:#x}") + statements.append("return;") + returned = True + + elif ins.code == Code.FNINIT: + depth = 0 + statements.append("x87_fninit(x87);") + + elif ins.code == Code.FLDCW_M2BYTE: + addr = flat_address(ins, width=2, store=False) + statements.append(f"x87.cw = load16({addr});") + + elif ins.code == Code.FNSTCW_M2BYTE: + addr = flat_address(ins, width=2, store=True) + statements.append(f"store16({addr}, x87.cw);") + + elif ins.code == Code.FNSTSW_AX: + ax_defined = True + used_ax = True + statements.append("ax = x87_status_word(x87);") + + elif ins.code == Code.MOV_RM16_R16: + if ins.op0_kind != OpKind.MEMORY or ins.op1_kind != OpKind.REGISTER or ins.op1_register != R.AX: + raise ValueError(f"unsupported mov16 form at RVA {ins.ip:#x}: {ins}") + if not ax_defined: + raise ValueError(f"undefined register ax at RVA {ins.ip:#x}: {ins}") + addr = flat_address(ins, width=2, store=True) + statements.append(f"store16({addr}, ax);") + + elif ins.code in FLD_MEM_CODES: + width, helper = FLD_MEM_CODES[ins.code] + addr = flat_address(ins, width=width, store=False) + push_check(ins) + statements.append(f"{helper}(x87, {addr});") + + elif ins.code == Code.FLD1: + push_check(ins) + statements.append("x87_push(x87, X87_POS_ONE);") + + elif ins.code == Code.FLDZ: + push_check(ins) + statements.append("x87_push(x87, X87_POS_ZERO);") + + elif ins.code in FST_MEM_CODES: + width, helper, pop = FST_MEM_CODES[ins.code] + need_depth(ins, 1) + addr = flat_address(ins, width=width, store=True) + if pop: + depth -= 1 + statements.append(f"{helper}(x87, {addr}, {'true' if pop else 'false'});") + + elif ins.code == Code.FSTP_STI: + if ins.op0_kind != OpKind.REGISTER or ins.op0_register != R.ST0: + raise ValueError(f"unsupported fstp register operand at RVA {ins.ip:#x}: {ins}") + need_depth(ins, 1) + depth -= 1 + statements.append("(void)x87_pop(x87);") + + elif ins.code == Code.F2XM1: + need_depth(ins, 1) + statements.append("x87_f2xm1(x87);") + + elif ins.code == Code.FYL2X: + need_depth(ins, 2) + depth -= 1 + statements.append("x87_fyl2x(x87);") + + elif ins.code == Code.FYL2XP1: + need_depth(ins, 2) + depth -= 1 + statements.append("x87_fyl2xp1(x87);") + + else: + raise ValueError(f"unsupported instruction at RVA {ins.ip:#x}: {ins}") + + if not returned: + raise ValueError(f"missing terminal ret in {name} at RVA {start + len(raw):#x}") + + decls = [" X87State x87{};"] + if used_ax: + decls.append(" std::uint16_t ax = 0u;") + body = [f" {stmt}" for stmt in statements] + lines = [ + f'extern "C" __declspec(dllexport) void lifted_{name}(word rcx, word rdx, word r8) {{', + " (void)rcx; (void)rdx; (void)r8;", + *decls, + *body, + "}", + ] + return "\n".join(lines), len(instructions) + + +def lift(pe, name): + entry = export_rva(pe, name) + raw = bounded_code(pe, entry) + source, count = lift_code(name, entry, raw) + return source, entry, count + + +def translate_pe(pe, names): + if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: + raise ValueError("expected AMD64 PE32+") + lifted = [lift(pe, name) for name in names] + source = PRELUDE + "\n".join(f"\n{text}" for text, _, _ in lifted) + "\n" + meta = [(name, entry, count) for name, (_, entry, count) in zip(names, lifted)] + return source, meta + + +def translate(image, names): + with pefile.PE(str(image), fast_load=True) as pe: + return translate_pe(pe, names) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("image", type=Path) + parser.add_argument("exports", help="comma-separated export names") + parser.add_argument("output", type=Path) + args = parser.parse_args() + try: + source, meta = translate(args.image, args.exports.split(",")) + args.output.write_text(source, encoding="utf-8") + for name, entry, count in meta: + print(f"{name} at RVA {entry:#x}: {count} instructions") + except (ValueError, OSError, pefile.PEFormatError) as error: + parser.exit(1, f"{error}\n") From 4000644494de39f91f9314c17322838ac32ef374 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:24:21 +0300 Subject: [PATCH 150/232] runtime: express CONSTANT_ALPHA on the alpha channel without the alpha blend factor feature (#2531) cb_blend::decode refused CONSTANT_ALPHA (19) and ONE_MINUS_CONSTANT_ALPHA (20) in the alpha factor fields of CB_BLENDn_CONTROL whenever AlphaBlendFactorSupported was false. On the alpha channel those factors read the blend constant's alpha, which is what BLEND_FACTOR / INV_BLEND_FACTOR give in SrcBlendAlpha / DestBlendAlpha, so D3D12 can express them on every device. state_block_blend always decodes with the feature off, so any slot 57 pipeline with such a word lost its register blend state for all eight targets. The alpha fields now map 19 / 20 to BLEND_FACTOR / INV_BLEND_FACTOR when the feature is absent. The colour fields still need ALPHA_FACTOR and are refused without it, as before. Test: startup_cb_blend_decode expects the alpha-field mapping for every slot and a raw word, and keeps the colour-field refusal (raw 0x72911433). startup_state_block_blend decodes a block with separate CONSTANT_ALPHA alpha factors. Both fail on the unfixed header. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- src/startup_stubs/cb_blend.h | 14 ++++++++-- tests/startup_cb_blend_check.cpp | 32 +++++++++++++++++------ tests/startup_state_block_blend_check.cpp | 6 ++++- 3 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/startup_stubs/cb_blend.h b/src/startup_stubs/cb_blend.h index 8c9eebd62..56b2e6329 100644 --- a/src/startup_stubs/cb_blend.h +++ b/src/startup_stubs/cb_blend.h @@ -73,6 +73,16 @@ inline D3D12_BLEND alpha_form(D3D12_BLEND f) } } +// BlendOp enum -> D3D12_BLEND for SrcBlendAlpha / DestBlendAlpha. On the alpha channel CONSTANT_ALPHA +// reads the constant's alpha, as CONSTANT_COLOR does there, so BLEND_FACTOR / INV_BLEND_FACTOR express +// it without AlphaBlendFactorSupported. Only the colour slots need ALPHA_FACTOR for it. +inline D3D12_BLEND alpha_factor(std::uint32_t op, bool alpha_factor_supported) +{ + if (!alpha_factor_supported && op == 19) return D3D12_BLEND_BLEND_FACTOR; + if (!alpha_factor_supported && op == 20) return D3D12_BLEND_INV_BLEND_FACTOR; + return factor(op, alpha_factor_supported); +} + // CombFunc enum -> D3D12_BLEND_OP; 0 when unknown. inline D3D12_BLEND_OP combine(std::uint32_t fcn) { @@ -92,7 +102,7 @@ inline bool min_max(D3D12_BLEND_OP op) { return op == D3D12_BLEND_OP_MIN || op = // control: CB_BLENDn_CONTROL. target_mask: the render target's CB_TARGET_MASK nibble, taken as // R=1, G=2, B=4, A=8 (component order of an unswapped colour format). alpha_factor_supported: -// D3D12_FEATURE_DATA_D3D12_OPTIONS13::AlphaBlendFactorSupported, needed for CONSTANT_ALPHA. +// D3D12_FEATURE_DATA_D3D12_OPTIONS13::AlphaBlendFactorSupported, needed for CONSTANT_ALPHA in a colour slot. inline Decoded decode(std::uint32_t control, std::uint32_t target_mask, bool alpha_factor_supported) { using namespace detail; @@ -118,7 +128,7 @@ inline Decoded decode(std::uint32_t control, std::uint32_t target_mask, bool alp const std::uint32_t alpha_dst = separate ? field(control, 24, 28) : color_dst; const D3D12_BLEND src = factor(color_src, alpha_factor_supported), dst = factor(color_dst, alpha_factor_supported); - const D3D12_BLEND src_a = factor(alpha_src, alpha_factor_supported), dst_a = factor(alpha_dst, alpha_factor_supported); + const D3D12_BLEND src_a = alpha_factor(alpha_src, alpha_factor_supported), dst_a = alpha_factor(alpha_dst, alpha_factor_supported); if (!src || !dst || !src_a || !dst_a) { const std::uint32_t bad = !src ? color_src : !dst ? color_dst : !src_a ? alpha_src : alpha_dst; out.reason = bad == 11 || bad == 12 ? "BOTH_SRC_ALPHA / BOTH_INV_SRC_ALPHA factor" diff --git a/tests/startup_cb_blend_check.cpp b/tests/startup_cb_blend_check.cpp index aa864232d..e9d4b159b 100644 --- a/tests/startup_cb_blend_check.cpp +++ b/tests/startup_cb_blend_check.cpp @@ -55,10 +55,21 @@ void fail(const std::string& name, const std::string& what) ++failures; } -bool refused_factor(std::uint32_t f, bool alpha_factor) +// alpha_field: SrcBlendAlpha / DestBlendAlpha, where CONSTANT_ALPHA reads the constant's alpha as +// CONSTANT_COLOR does, so BLEND_FACTOR expresses it without the alpha blend factor feature. +bool refused_factor(std::uint32_t f, bool alpha_factor, bool alpha_field = false) { return f == BOTH_SRC_ALPHA || f == BOTH_INV_SRC_ALPHA || f > ONE_MINUS_CONSTANT_ALPHA || - (!alpha_factor && (f == CONSTANT_ALPHA || f == ONE_MINUS_CONSTANT_ALPHA)); + (!alpha_factor && !alpha_field && (f == CONSTANT_ALPHA || f == ONE_MINUS_CONSTANT_ALPHA)); +} + +// The D3D12 factor of a BlendOp value in SrcBlendAlpha / DestBlendAlpha for a device with or without +// AlphaBlendFactorSupported. +D3D12_BLEND want_alpha(std::uint32_t f, bool alpha_factor) +{ + if (!alpha_factor && f == CONSTANT_ALPHA) return D3D12_BLEND_BLEND_FACTOR; + if (!alpha_factor && f == ONE_MINUS_CONSTANT_ALPHA) return D3D12_BLEND_INV_BLEND_FACTOR; + return alpha_slot[f]; } const char* factor_reason(std::uint32_t f) @@ -98,7 +109,7 @@ void expect_blend(const std::string& name, const Decoded& d, const Want& w, std: } } -D3D12_BLEND want_dest_alpha(std::uint32_t f) { return colour_dest_alpha ? colour_slot[f] : alpha_slot[f]; } +D3D12_BLEND want_dest_alpha(std::uint32_t f, bool alpha_factor) { return colour_dest_alpha ? colour_slot[f] : want_alpha(f, alpha_factor); } // Each 5-bit value in each slot, with the other three slots at ONE / ZERO. void check_slots() @@ -112,15 +123,15 @@ void check_slots() const auto d = x2w_cb_blend::decode(control_word(v[0], ADD, v[1], v[2], ADD, v[3], true, true), 0xF, alpha_factor); const std::string name = std::string(slot_names[slot]) + " factor " + std::to_string(f) + (alpha_factor ? " (alpha blend factor)" : ""); - if (refused_factor(f, alpha_factor)) { + if (refused_factor(f, alpha_factor, slot >= 2)) { expect_refused(name, d, factor_reason(f)); continue; } Want w{D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD}; if (slot == 0) w.s = colour_slot[f]; if (slot == 1) w.d = colour_slot[f]; - if (slot == 2) w.sa = alpha_slot[f]; - if (slot == 3) w.da = want_dest_alpha(f); + if (slot == 2) w.sa = want_alpha(f, alpha_factor); + if (slot == 3) w.da = want_dest_alpha(f, alpha_factor); expect_blend(name, d, w); } } @@ -140,7 +151,7 @@ void check_slots() expect_blend("shared source factor " + tag, as_source, {colour_slot[f], D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, alpha_slot[f], D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD}); expect_blend("shared destination factor " + tag, as_dest, - {D3D12_BLEND_ONE, colour_slot[f], D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, want_dest_alpha(f), D3D12_BLEND_OP_ADD}); + {D3D12_BLEND_ONE, colour_slot[f], D3D12_BLEND_OP_ADD, D3D12_BLEND_ONE, want_dest_alpha(f, alpha_factor), D3D12_BLEND_OP_ADD}); } } } @@ -233,7 +244,12 @@ void check_words() expect_blend("raw 74331291 (alpha blend factor)", x2w_cb_blend::decode(0x74331291, 0xF, true), {D3D12_BLEND_SRC1_ALPHA, D3D12_BLEND_INV_SRC1_ALPHA, D3D12_BLEND_OP_REV_SUBTRACT, D3D12_BLEND_ALPHA_FACTOR, D3D12_BLEND_INV_ALPHA_FACTOR, D3D12_BLEND_OP_SUBTRACT}); - expect_refused("raw 74331291", x2w_cb_blend::decode(0x74331291, 0xF, false), "CONSTANT_ALPHA"); + // Without the feature, CONSTANT_ALPHA on the alpha channel is the blend factor's alpha. + expect_blend("raw 74331291", x2w_cb_blend::decode(0x74331291, 0xF, false), + {D3D12_BLEND_SRC1_ALPHA, D3D12_BLEND_INV_SRC1_ALPHA, D3D12_BLEND_OP_REV_SUBTRACT, D3D12_BLEND_BLEND_FACTOR, + D3D12_BLEND_INV_BLEND_FACTOR, D3D12_BLEND_OP_SUBTRACT}); + // In a colour slot it needs ALPHA_FACTOR: the same fields swapped between the channels. + expect_refused("raw 72911433", x2w_cb_blend::decode(0x72911433, 0xF, false), "CONSTANT_ALPHA"); } } // namespace diff --git a/tests/startup_state_block_blend_check.cpp b/tests/startup_state_block_blend_check.cpp index 5ed860a1d..ea34974ca 100644 --- a/tests/startup_state_block_blend_check.cpp +++ b/tests/startup_state_block_blend_check.cpp @@ -52,6 +52,10 @@ int main() expect_target0("straight colour, one alpha", 0xE5010504, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_ONE, D3D12_BLEND_INV_SRC_ALPHA); expect_target0("premultiplied", 0xE5010501, D3D12_BLEND_ONE, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_ONE, D3D12_BLEND_INV_SRC_ALPHA); expect_target0("additive", 0xE1000104, D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_ONE); + // Separate alpha with CONSTANT_ALPHA / ONE_MINUS_CONSTANT_ALPHA: the blend factor's alpha, which the + // device-independent read (no alpha blend factor feature) expresses as BLEND_FACTOR / INV_BLEND_FACTOR. + expect_target0("constant alpha on the alpha channel", x2w_cb_blend::control_word(4, 0, 5, 19, 0, 20, true, true), D3D12_BLEND_SRC_ALPHA, + D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_BLEND_FACTOR, D3D12_BLEND_INV_BLEND_FACTOR); D3D12_BLEND_DESC blend{}; const char* reason = nullptr; @@ -142,6 +146,6 @@ int main() std::printf("startup_state_block_blend: %d FAILED\n", failures); return 1; } - std::printf("startup_state_block_blend: PASS (4 measured words, enable clear, 5 controls, dual source)\n"); + std::printf("startup_state_block_blend: PASS (4 measured words, constant alpha, enable clear, 5 controls, dual source)\n"); return 0; } From 1cce2a32430271df8f7412399fa50c188c82ec83 Mon Sep 17 00:00:00 2001 From: dnn <55638248+denn0x@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:25:15 +0000 Subject: [PATCH 151/232] tooling: end a startup debugger run when /stop appears (#2476) debug_launch.py checks twice a second for a file named stop in the log directory. When it appears, the run ends as at the timeout (thread stacks, X2W_DUMP, the rip histogram), and the summary says "stopped by request after X s (stop file)" instead of "timeout". A stop file left from an earlier run in a reused directory is removed at start. This lets a caller end a long run early without killing the debugger, which would skip the final thread dump. Test: startup_debug_check.py creates the file 1.5 s into a probe run (the probe waits 3 s): the run is stopped by request, events.txt logs it and threads.txt has stacks. Control: a stop file present before the run is removed and the probe exits 0. With main's debug_launch.py the new case fails (the probe runs to its exit). Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- tests/startup_debug_check.py | 40 ++++++++++++++++++++++++++++++++++- tools/startup/debug_launch.py | 16 ++++++++++++-- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index e09524c72..11f74805b 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -3,7 +3,8 @@ X2W_STOP_AT stops at a chosen main-image breakpoint while --continue-asserts steps over the others, X2W_DUMP_AT writes thread stacks at a time during the run, and X2W_VALLOC_MIN logs large virtual-memory allocations with their callers. X2W_LOG_AT captures registers and qwords at a -function entry, then removes the breakpoint at the hit limit. The launcher keeps the debug heap off unless +function entry, then removes the breakpoint at the hit limit. A `stop` file created in the log directory +ends the run as the timeout does; one left from an earlier run is removed at start. The launcher keeps the debug heap off unless the caller sets _NO_DEBUG_HEAP=0. tests/startup_debug_probe.cpp is the main input: it hits two breakpoints, reserves 256 MiB, prints its debug-heap flags, waits 3 s and exits 0. @@ -21,6 +22,7 @@ import subprocess import sys import tempfile +import time REPO = Path(__file__).resolve().parents[1] DEBUG = REPO / "tools/startup/debug_launch.py" @@ -47,6 +49,28 @@ def run(probe, work, name, variables, options=("--continue-asserts", "10")): return result.stdout + result.stderr, logdir +def run_with_stop(probe, work, name): + """Create /stop once the launcher records the running probe.""" + logdir = work / name + env = {k: v for k, v in os.environ.items() if not k.startswith("X2W_") and k.upper() != "_NO_DEBUG_HEAP"} + command = [sys.executable, "-B", str(DEBUG), str(probe), str(work), str(logdir), "--timeout", "0", "--console", "0", + "--continue-asserts", "10"] + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env) + try: + deadline = time.monotonic() + 10 + while f"process {probe.name} at " not in text(logdir / "events.txt"): + if process.poll() is not None or time.monotonic() >= deadline: + raise AssertionError("stop-file probe did not start") + time.sleep(0.025) + (logdir / "stop").write_text("", encoding="utf-8") + out, _ = process.communicate(timeout=120) + finally: + if process.poll() is None: + process.kill() + process.communicate() + return out, logdir + + def text(path): return path.read_text(encoding="utf-8", errors="replace") if path.exists() else "" @@ -158,6 +182,20 @@ def stack_read(address, size): assert "rip=" in text(logdir / "threads_1.txt"), text(logdir / "threads_1.txt") assert not (work / "baseline" / "threads_1.txt").exists() + # /stop ends the run with thread stacks even when the timer is disabled, while the probe + # (which waits 3 s) is still alive. Control: a stop file left in the directory before the run is removed at + # start, so that run exits normally. + out, logdir = run_with_stop(probe, work, "stop-file") + assert "stopped by request after" in out and "process exited" not in out, out + assert "stop file found" in text(logdir / "events.txt"), text(logdir / "events.txt") + assert "rip=" in text(logdir / "threads.txt"), text(logdir / "threads.txt") + stale = work / "stop-stale" + stale.mkdir(exist_ok=True) + (stale / "stop").write_text("", encoding="utf-8") + out, logdir = run(probe, work, "stop-stale", {}) + assert "process exited with 0x00000000" in out and "stopped by request" not in out, out + assert not (logdir / "stop").exists(), "stale stop file kept" + # X2W_VALLOC_MIN: the 256 MiB reservation is logged with a caller in the probe; a higher # threshold logs nothing. out, logdir = run(probe, work, "valloc", {"X2W_VALLOC_MIN": "10000000"}) diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 472bd5289..5bc7afa6e 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -6,6 +6,8 @@ the stopping exception, the integer registers, the stack words and the code bytes around RIP. Stops at a second-chance exception, an uncontinued main-image breakpoint, or the timeout. A timeout of zero disables the timer. An assertion continuation limit of -1 removes that limit. +A file named `stop` created in during the run ends it as the timeout does (checked twice a +second; a stop file left from an earlier run is removed at start). """ import ctypes import ctypes.wintypes as wt @@ -135,7 +137,8 @@ def print(*args, **kwargs): stub_area = [0, 0] # next free address and end of the block the stubs go to os.makedirs(logdir, exist_ok=True) trap_log = os.path.join(logdir, "trap.log") - for stale in (trap_log, os.path.join(logdir, "finished.txt")): # a reused run directory starts clean + stop_file = os.path.join(logdir, "stop") # created from outside: end the run as at the timeout + for stale in (trap_log, os.path.join(logdir, "finished.txt"), stop_file): # a reused run directory starts clean if os.path.exists(stale): os.remove(stale) if os.path.exists(trap_log): @@ -614,7 +617,15 @@ def poll_watches(): watch_values[rva] = blob log(f"{time.time() - start:7.3f} watch +{rva:#x} = {blob.hex(' ')}") + stop_requested = False + stop_next = 0.0 while not timeout or time.time() - start < timeout: + if time.time() >= stop_next: + stop_next = time.time() + 0.5 + if os.path.exists(stop_file): + stop_requested = True + log(f"{time.time() - start:7.3f} stop file found: ending the run") + break if dump_at and time.time() - start >= dump_at[0]: dump_threads(os.path.join(logdir, f"threads_{dump_at.pop(0):g}.txt")) if watches and time.time() >= watch_next: @@ -840,7 +851,8 @@ def poll_watches(): elif exit_code is not None: print(f"process exited with {exit_code:#010x} after {elapsed:.2f} s") else: - print(f"timeout after {elapsed:.2f} s") + print(f"stopped by request after {elapsed:.2f} s (stop file)" if stop_requested + else f"timeout after {elapsed:.2f} s") dumped = dump_threads(os.path.join(logdir, "threads.txt")) for item in filter(None, os.environ.get("X2W_DUMP", "").split(",")): rva, _, size = item.partition(":") From 99af3da015890b9f3842590ea463fef6c7e951cd Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 21:28:35 +0100 Subject: [PATCH 152/232] gfx2hlsl: cache instruction parsing in the exec-write dataflow (#2535) The exec-write pass parsed the same instruction text once per visit and join_writes rescanned every instruction for every branch. Cache the parse and the clear shape per text, and compute the written registers once. Three large compute requests: 19.1 s -> 8.4 s, same refusals. Co-authored-by: Claude Fable 5.2 --- tools/startup/gfx2hlsl.py | 65 ++++++++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 25 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f4613d11f..6745335fa 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5,6 +5,7 @@ values (tables, vertex-buffer table, root buffers) turn into HLSL resources instead of arithmetic. The output is HLSL for both stages plus a manifest that tells the runtime what to bind where. """ +import bisect from contextlib import suppress import functools import os @@ -552,6 +553,23 @@ def mask_words(tok, count): return words if len(words) == count else None +@functools.lru_cache(maxsize=None) +def clear_shape(name, asm): + """What clear_after needs from one instruction's text, which the fixed point would otherwise parse again on every + visit: 'cmpx', None for a form that carries no fact, or (operation, saving suffix, word count, operand words).""" + base = re.sub(r'_e(32|64)$', '', name) + if base.startswith('v_cmpx'): + return 'cmpx' + m = re.fullmatch(r's_(mov|and|or|xor|andn2)(_saveexec|_wrexec)?_b(32|64)', base) + if not m or (m.group(2) and m.group(1) == 'mov'): + return None + count = 2 if m.group(3) == '64' else 1 + words = [mask_words(op, count) for op in parse(asm)[1]] + if None in words or len(words) != (2 if m.group(2) or m.group(1) == 'mov' else 3): + return None + return m.group(1), m.group(2), count, tuple(tuple(word) for word in words) + + def clear_after(name, asm, may, clear): """Forward step of the proof Stage.execz_refusals runs over a block that s_cbranch_execz skips. A fact (key, h) says: for every lane of wave half h (0: lanes 0 to 31, 1: lanes 32 to 63) whose exec bit was clear at the branch, @@ -562,22 +580,18 @@ def clear_after(name, asm, may, clear): source holds; A | B and A ^ B what both hold; A & ~B and a move what A holds. A saveexec or wrexec form is its operation on exec plus the copy it saves, and v_cmpx ANDs its result into exec. Any other write, a compare result included, drops the facts of what it may write.""" - base = re.sub(r'_e(32|64)$', '', name) - _, ops, _ = parse(asm) out = {fact for fact in clear if fact[0] not in may - EXEC_KEYS} - if base.startswith('v_cmpx'): + shape = clear_shape(name, asm) + if shape == 'cmpx': return out - halves = lambda word: {0, 1} if word == '0' else {h for key, h in clear if key == word} - m = re.fullmatch(r's_(mov|and|or|xor|andn2)(_saveexec|_wrexec)?_b(32|64)', base) - saving = m and m.group(2) - count = 2 if m and m.group(3) == '64' else 1 - words = [mask_words(op, count) for op in ops] if m and not (saving and m.group(1) == 'mov') else [None] - if None in words or len(words) != (2 if saving or m.group(1) == 'mov' else 3): + if shape is None: return {fact for fact in out if fact[0] not in may} - dest, srcs = words[0], words[1:] + op, saving, count, words = shape + halves = lambda word: {0, 1} if word == '0' else {h for key, h in clear if key == word} + dest, srcs = words[0], list(words[1:]) if saving: # RDNA 2 ISA SOP1: the operation is S0 op EXEC, so andn2 is S0 & ~EXEC - srcs.append(['exec', 'exec_hi'][:count]) - combine = {'and': set.union, 'or': set.intersection, 'xor': set.intersection}.get(m.group(1), lambda a, *b: a) + srcs.append(('exec', 'exec_hi')[:count]) + combine = {'and': set.union, 'or': set.intersection, 'xor': set.intersection}.get(op, lambda a, *b: a) value = [combine(*(halves(src[j]) for src in srcs)) for j in range(count)] writes = list(zip(dest, value)) if saving: # saveexec keeps the old exec in D; wrexec writes the result to both @@ -2296,21 +2310,22 @@ def descriptor_scc_reads(self, branches, effects): def join_writes(self, branches): """Branch target -> the scalar registers another path can write before it reaches the target: the loop body [target, branch] for a backward branch, and the skipped instructions (branch, target) for a forward one.""" + offs, written = [], [] # per instruction, once: a program has hundreds of branches over thousands of instructions + for off, _n, name, asm in self.ins: + regs = set(range(128)) if name.startswith('s_movreld') else set() # M0 picks the destination + for tok in destinations(name, parse(asm)[1]): + r = reg_range(tok) + if r and r[0] == 's': + regs.update(range(r[1], r[2] + 1)) + elif tok == 'm0': + regs.add('m0') + offs.append(off) + written.append(regs) writes = {} for branch, target in branches: - regs = writes.setdefault(target, set()) - for off, _n, name, asm in self.ins: - if not (target <= off <= branch if target <= branch else branch < off < target): - continue - _, ops, _ = parse(asm) - if name.startswith('s_movreld'): - regs.update(range(128)) # M0 picks the destination - for tok in destinations(name, ops): - r = reg_range(tok) - if r and r[0] == 's': - regs.update(range(r[1], r[2] + 1)) - elif tok == 'm0': - regs.add('m0') + lo, hi = ((bisect.bisect_left(offs, target), bisect.bisect_right(offs, branch)) if target <= branch else + (bisect.bisect_right(offs, branch), bisect.bisect_left(offs, target))) + writes.setdefault(target, set()).update(*written[lo:hi]) return writes def tracks_uniformity(self): From ef71ca20f5f4c1b291c1ea41433258562732612a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:32:10 +0300 Subject: [PATCH 153/232] runtime: report the GameInput virtual pad as GameInputFamilyXboxOne (#2539) The GameInput stand-in's GameInputDeviceInfo put 2 in deviceFamily (+0x60), commented as "Xbox One". In GameInputDeviceFamily 2 is GameInputFamilyXbox360 (the XUSB22 driver); GameInputFamilyXboxOne (XboxGIP / XInputHID) is 1. The same info names vendor 045E product 0B12, an Xbox Series pad, which is a GIP device. A title that branches on the family saw an Xbox 360 controller. Test: startup_gameinput_contracts_check reads the gamepad's device info through FindDeviceFromObject and expects vendor 045E, product 0B12 and deviceFamily 1. On the unfixed stand-in it fails with "gamepad deviceFamily 2, expected 1". Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- src/startup_stubs/gameinput.cpp | 5 ++++- tests/startup_gameinput_contracts_check.cpp | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index 3b3ab90a9..b135633ec 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -35,6 +35,7 @@ constexpr HRESULT reading_too_old = static_cast(0x838A0004); constexpr std::uint32_t kind_keyboard = 0x00000010; constexpr std::uint32_t kind_gamepad = 0x00040000, kind_controller_bits = 0x0000000E; constexpr std::uint32_t status_connected = 0x47; // connected, input enabled, output enabled, synchronized +constexpr std::uint32_t family_xbox_one = 1; // GameInputFamilyXboxOne (GameInputDeviceFamily) constexpr std::size_t max_keys = 32; constexpr std::size_t history_capacity = 64; @@ -859,7 +860,9 @@ void build() std::memcpy(device_info + 4, ids, 4); for (int i = 0; i < 32; ++i) device_info[0x20 + i] = static_cast(0xA0 + i); // deviceId for (int i = 0; i < 32; ++i) device_info[0x40 + i] = static_cast(0xA0 + i); // deviceRootId - const std::uint32_t tail[4] = {2 /* family: Xbox One */, 0, kind_gamepad | kind_controller_bits, 0xF /* rumble motors */}; + // GameInputDeviceFamily: Virtual -1, XboxOne 1 (XboxGIP / XInputHID), Xbox360 2 (XUSB22), Hid 3, I8042 4. The + // vendor/product above name an Xbox Series pad, a GIP device, so the family is XboxOne. + const std::uint32_t tail[4] = {family_xbox_one, 0, kind_gamepad | kind_controller_bits, 0xF /* rumble motors */}; std::memcpy(device_info + 0x60, tail, sizeof(tail)); // Virtual keyboard device info. std::memcpy(keyboard_device_info, &size, 4); diff --git a/tests/startup_gameinput_contracts_check.cpp b/tests/startup_gameinput_contracts_check.cpp index 3041ed590..ef56832b4 100644 --- a/tests/startup_gameinput_contracts_check.cpp +++ b/tests/startup_gameinput_contracts_check.cpp @@ -16,6 +16,7 @@ namespace { constexpr std::uint32_t kind_keyboard = 0x00000010; constexpr std::uint32_t kind_gamepad = 0x00040000; constexpr std::uint32_t status_connected = 0x47; +constexpr std::uint32_t family_xbox_one = 1; // GameInputFamilyXboxOne constexpr std::uint32_t blocking_enumeration = 2; constexpr HRESULT device_not_found = static_cast(0x838A0002L); constexpr GUID dummy_iid = {0x11223344u, 0x5566u, 0x7788u, {0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00}}; @@ -423,6 +424,18 @@ int main(int argc, char** argv) by_handle == nullptr, "FindDeviceFromPlatformHandle sets out to null and returns device_not_found"); if (by_obj) { + // GameInputDeviceInfo: vendorId +4, productId +6, deviceFamily +0x60. 045E:0B12 is an Xbox Series pad, + // a GIP device: GameInputFamilyXboxOne (1), not GameInputFamilyXbox360 (2, the XUSB22 driver). + const unsigned char* info = by_obj->GetDeviceInfo(); + std::uint16_t ids[2]{}; + std::uint32_t family = 0; + if (info) { + std::memcpy(ids, info + 4, sizeof(ids)); + std::memcpy(&family, info + 0x60, sizeof(family)); + } + check(info && ids[0] == 0x045E && ids[1] == 0x0B12, "gamepad GetDeviceInfo names vendor 045E product 0B12"); + if (family != family_xbox_one) std::printf("gamepad deviceFamily %u, expected %u\n", family, family_xbox_one); + check(family == family_xbox_one, "gamepad GetDeviceInfo deviceFamily == GameInputFamilyXboxOne"); check(by_obj->GetDeviceStatus() == status_connected, "IGameInputDevice::GetDeviceStatus == status_connected"); const std::uint32_t rumble[4] = {0, 0, 0, 0}; by_obj->SetRumbleState(rumble); From 1807f2a54ca8d302b019c330c05be5bc2b9e4fc8 Mon Sep 17 00:00:00 2001 From: triggered02 <153171514+triggered02@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:03:08 +0530 Subject: [PATCH 154/232] mesh_entry_aot: lower s_clause and s_bitcmp{0,1}_b{32,64} (#2438) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + docs/experiments.md | 31 ++ tests/mesh_bitcmp_clause_check.py | 551 ++++++++++++++++++++++++++++++ tools/mesh_entry_aot.py | 18 + 4 files changed, 602 insertions(+) create mode 100644 tests/mesh_bitcmp_clause_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index cffb43f70..faa983917 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8570,6 +8570,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(mesh_amplification_refusal PROPERTIES TIMEOUT 30) add_test(NAME mesh_entry_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_entry_aot_cli_check.py") + add_test(NAME mesh_bitcmp_clause_cpu COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_bitcmp_clause_check.py") foreach(adapter IN ITEMS hardware warp) add_test(NAME mesh_dynamic_aot_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_dynamic_aot_draw_check.py" "${DXC_EXECUTABLE}" diff --git a/docs/experiments.md b/docs/experiments.md index 6f76d654f..560fa1c27 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4071,6 +4071,37 @@ python3 -B tests/mesh_dynamic_aot_check.py python3 -B tests/mesh_loop_census_check.py ``` +## Mesh hard-clause hints and scalar bit-test predicates + +[`tools/mesh_entry_aot.py`](../tools/mesh_entry_aot.py) (and [`tools/mesh_dynamic_aot.py`](../tools/mesh_dynamic_aot.py) +through `Wave`) now lower the SOPP hard-clause hint `s_clause` and the four +SOPC scalar bit-test instructions `s_bitcmp0_b32`, `s_bitcmp1_b32`, +`s_bitcmp0_b64` and `s_bitcmp1_b64` (Refs #2413). + +`s_clause` accepts integer operands in `0..63` (`0x0..0x3f`) as a scheduling +no-op in both top-level execution and uniform descriptor join arms, and refuses +out-of-range or non-integer operands. `s_bitcmp0_b32` / `s_bitcmp1_b32` test +`((S0.u32 >> (S1.u32 & 31)) & 1) == 0 / 1`; `s_bitcmp0_b64` / `s_bitcmp1_b64` +test `((S0.u64 >> (S1.u32 & 63)) & 1) == 0 / 1` across 64-bit SGPR pairs, +`exec`, `vcc`, and sign-extended inline constants. An `UNDEF` operand clears +`scc` to `None` (refused only if a branch or select reads `scc`), while +`RuntimeWord` and non-concrete scalar operands raise `ValueError`. + +```text +python3 -B tests/mesh_bitcmp_clause_check.py +ctest --preset dev --no-tests=error -R "^mesh_bitcmp_clause_cpu$" -V +``` + +[`tests/mesh_bitcmp_clause_check.py`](../tests/mesh_bitcmp_clause_check.py) +builds synthetic gfx1013 machine-code bytes, decodes them solely through +[`tools/disasm_rdna2.py`](../tools/disasm_rdna2.py) `decode_instruction`, and +checks both `mesh_entry_aot.lower` and `mesh_dynamic_aot.enumerate_variants`: +`s_clause` `0x0`/`0x3f` accepted at top level and inside a join arm with `0x40` +and `0xffff` refused; 32-bit and 64-bit bit tests across bit 0, bit 31, bit 35, +bit 63, and index wraps (`33 & 31 == 1`, `65 & 63 == 1`) with SGPRs, inline +constants, `exec`, and `vcc`; and `UNDEF`, `RuntimeWord`, dynamic string/`Select`, +and undefined-`vcc` refusals. No GPU draw or DXIL compilation was run here. + ## Amplification and mesh pipeline forms `tests/mesh_amplified_check.py` builds an amplification shader (`as_6_5`) and a diff --git a/tests/mesh_bitcmp_clause_check.py b/tests/mesh_bitcmp_clause_check.py new file mode 100644 index 000000000..dee8ace75 --- /dev/null +++ b/tests/mesh_bitcmp_clause_check.py @@ -0,0 +1,551 @@ +"""Check s_clause and s_bitcmp{0,1}_b{32,64} lowering on synthetic gfx1013 machine code.""" + +import re +from pathlib import Path +import struct +import sys + +from mesh_dynamic_geometry_check import CODE, MESH_LIMITS, SECOND + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import disasm_rdna2 as D # noqa: E402 +from mesh_dynamic_aot import enumerate_variants, lower as lower_dynamic # noqa: E402 +from mesh_entry_aot import lower as lower_static # noqa: E402 + +U32 = 0xFFFFFFFF +STATIC_GEOMETRY = [0x1003, SECOND] +HALF_FLOAT_WORD = 0x3F000000 + + +def decode(code): + """Decode gfx1013 machine-code bytes via disasm_rdna2.decode_instruction in wave64 mode.""" + instructions = [] + pc = 0 + while pc < len(code): + size, _, text, _ = D.decode_instruction(code, pc) + assert size and pc + size <= len(code), (pc, size) + op, _, operands = text.partition(" ") + if op == "s_branch" or op.startswith("s_cbranch_"): + target = re.fullmatch(r"label_(0x[0-9a-f]+)", operands) + assert target, (pc, text) + displacement = int(target[1], 16) - pc - size + assert displacement % 4 == 0, (pc, text) + text = f"{op} {displacement // 4}" + elif text == "s_sendmsg 0x9": + text = "s_sendmsg sendmsg(MSG_GS_ALLOC_REQ)" + elif text == "s_barrier 0x0": + text = "s_barrier" + elif text.startswith("exp target_20 "): + text = "exp prim " + operands.removeprefix("target_20 ") + elif op in ("v_cmp_eq_u32_e64", "v_cmp_gt_u32_e64", "v_cndmask_b32_e64"): + args = operands.split(", ") + mask = 0 if op.startswith("v_cmp_") else -1 + if args[mask] == "vcc_lo": + args[mask] = "vcc" + else: + match = re.fullmatch(r"s(\d+)", args[mask]) + assert match and int(match[1]) % 2 == 0, args[mask] + low = int(match[1]) + args[mask] = f"s[{low}:{low + 1}]" + text = op + " " + ", ".join(args) + elif op == "s_buffer_load_dword" and operands.endswith(", 0x0"): + text = text.removesuffix("0x0") + "null" + instructions.append((pc, text)) + pc += size + return instructions + + +def opcode(table, name): + return next(op for op, info in table.items() if info[0] == name) + + +def ssrc(operand): + if isinstance(operand, str): + if operand.startswith("v") and operand[1:].isdigit(): + return 256 + int(operand[1:]), None + if operand.startswith("s[") and operand.endswith("]"): + return int(operand[2:-1].split(":")[0]), None + if operand.startswith("s") and operand[1:].isdigit(): + return int(operand[1:]), None + specials = { + "vcc": 106, + "m0": 124, + "null": 125, + "exec": 126, + "0.5": 240, + "1.0": 242, + } + return specials[operand], None + if 0 <= operand <= 64: + return 128 + operand, None + if -16 <= operand < 0: + return 192 - operand, None + return 255, operand & U32 + + +def sopp(name, simm=0): + return [0xBF800000 | (opcode(D.SOPP_OPS, name) << 16) | (simm & 0xFFFF)] + + +def sop1(name, dst, src): + src_code, lit = ssrc(src) + dst_code, _ = ssrc(dst) + out = [0xBE800000 | (dst_code << 16) | (opcode(D.SOP1_OPS, name) << 8) | src_code] + if lit is not None: + out.append(lit) + return out + + +def sopc(name, a, b): + sa, la = ssrc(a) + sb, lb = ssrc(b) + assert la is None or lb is None, (a, b) + out = [0xBF000000 | (opcode(D.SOPC_OPS, name) << 16) | (sb << 8) | sa] + lit = la if la is not None else lb + if lit is not None: + out.append(lit) + return out + + +def vop1(name, dst, src): + src_code, lit = ssrc(src) + assert dst.startswith("v") and dst[1:].isdigit() + out = [0x7E000000 | (int(dst[1:]) << 17) | (opcode(D.VOP1_OPS, name) << 9) | src_code] + if lit is not None: + out.append(lit) + return out + + +def vop3_cmp(name, dst, a, b): + sa, la = ssrc(a) + sb, lb = ssrc(b) + assert la is None and lb is None, (a, b) + dst_code, _ = ssrc(dst) + op = opcode(D.VOPC_OPS, name.replace("_e64", "_e32")) + w0 = 0xD4000000 | (op << 16) | dst_code + w1 = (sb << 9) | sa + return [w0, w1] + + +def smem_load(name, dst, base, imm_offset): + op = next(code for code, op_name in D.SMEM_OPS.items() if op_name == name) + sdata, _ = ssrc(dst) + sbase, _ = ssrc(base) + assert sbase % 2 == 0 + w0 = 0xF4000000 | (op << 18) | (sdata << 6) | (sbase // 2) + w1 = (125 << 25) | (imm_offset & 0x1FFFFF) + return [w0, w1] + + +def find_pc(code, prefix): + matches = [pc for pc, text in decode(code) if text.startswith(prefix)] + assert len(matches) == 1, (prefix, matches) + return matches[0] + + +def insert_words(code, at_pc, inserted_words): + """Insert machine-code dwords at `at_pc` and shift any SOPP branch that spans `at_pc`.""" + shift_dwords = len(inserted_words) + out = bytearray() + pc = 0 + while pc < len(code): + if pc == at_pc: + out.extend(struct.pack(f"<{shift_dwords}I", *inserted_words)) + size, op_name, _, _ = D.decode_instruction(code, pc) + chunk = bytearray(code[pc : pc + size]) + if op_name == "s_branch" or op_name.startswith("s_cbranch"): + w0, = struct.unpack_from(" scc = None. + # Dead bitcmp leaves scc = None without refusing; branching on scc is refused. + alloc_pc = find_pc(CODE, "s_mov_b32 m0, s15") + pos0_pc = find_pc(CODE, "exp pos0 ") + skipped_code = insert_words(CODE, alloc_pc, [*sop1("s_mov_b32", "s32", 1), *sop1("s_mov_b32", "s33", 2)]) + skipped_pos0 = find_pc(skipped_code, "exp pos0 ") + + dead_32 = insert_words(skipped_code, skipped_pos0, sopc("s_bitcmp0_b32", "s32", 0)) + assert lower_static(decode(dead_32), STATIC_GEOMETRY, MESH_LIMITS) + assert enumerate_variants(decode(dead_32), 2, MESH_LIMITS) + + dead_64 = insert_words(skipped_code, skipped_pos0, sopc("s_bitcmp1_b64", "s[32:33]", 35)) + assert lower_static(decode(dead_64), STATIC_GEOMETRY, MESH_LIMITS) + + # Make only s32 defined on both waves while s33 stays UNDEF on wave 1 -> pair is still UNDEF. + partial_pair = insert_words( + insert_words(CODE, alloc_pc, sop1("s_mov_b32", "s33", 2)), + pos0_pc + 4, + [*sop1("s_mov_b32", "s32", 1), *sopc("s_bitcmp1_b64", "s[32:33]", 0), *sopp("s_cbranch_scc0", 0)], + ) + expect_refused(decode(partial_pair), "Undefined branch predicate") + + for cmp_op, src0, bit, branch_op in ( + ("s_bitcmp0_b32", "s32", 0, "s_cbranch_scc0"), + ("s_bitcmp1_b32", 1, "s32", "s_cbranch_scc1"), + ("s_bitcmp0_b64", "s[32:33]", 35, "s_cbranch_scc0"), + ("s_bitcmp1_b64", "s[32:33]", "s32", "s_cbranch_scc1"), + ): + branch_undef = insert_words( + skipped_code, + skipped_pos0, + [*sopc(cmp_op, src0, bit), *sopp(branch_op, 0)], + ) + expect_refused(decode(branch_undef), "Undefined branch predicate") + + # 2. RuntimeWord operands in mesh_dynamic_aot.enumerate_variants must be refused cleanly. + cmp_entry_pc = find_pc(CODE, "s_cmp_eq_u32 s15, 0x1003") + for words_patch in ( + sopc("s_bitcmp0_b32", "s15", 0), + sopc("s_bitcmp1_b32", "s14", 31), + sopc("s_bitcmp0_b64", "s[14:15]", 35), + [*sop1("s_mov_b32", "s4", 1), *sopc("s_bitcmp1_b32", "s4", "s14")], + ): + runtime_code = insert_words(CODE, cmp_entry_pc, words_patch) + expect_refused(decode(runtime_code), "Unproven runtime geometry word", static_ok=True) + + # 3. Dynamic constant-buffer scalar string operand -> ValueError("Dynamic scalar predicate" / pair concrete). + for patch_tail, expected_msg in ( + ([*sopc("s_bitcmp0_b32", "s4", 0)], "Dynamic scalar predicate"), + ([*sopc("s_bitcmp1_b32", 1, "s4")], "Dynamic scalar predicate"), + ([*sop1("s_mov_b32", "s5", 0), *sopc("s_bitcmp0_b64", "s[4:5]", 35)], "Scalar pair requires concrete words"), + ([*sop1("s_mov_b32", "s6", 0), *sop1("s_mov_b32", "s7", 0), *sopc("s_bitcmp1_b64", "s[6:7]", "s4")], "Dynamic scalar predicate"), + ): + dyn_code = insert_words( + CODE, + pos0_pc, + [ + *smem_load("s_load_dwordx4", "s[36:39]", "s[10:11]", 0x60), + *sopp("s_waitcnt", 0xC07F), + *smem_load("s_buffer_load_dword", "s4", "s[36:39]", 0x4), + *sopp("s_waitcnt", 0xC07F), + *patch_tail, + ], + ) + expect_refused(decode(dyn_code), expected_msg) + + # 4. Undefined VCC -> ValueError("Undefined wave predicate"). + undef_vcc = insert_words(CODE, pos0_pc, sopc("s_bitcmp0_b64", "vcc", 0)) + expect_refused(decode(undef_vcc), "Undefined wave predicate") + + +def check(): + check_s_clause() + check_bitcmp_32() + check_bitcmp_64() + check_refusals() + print("s_clause and s_bitcmp{0,1}_b{32,64} machine-code checks passed") + + +if __name__ == "__main__": + check() diff --git a/tools/mesh_entry_aot.py b/tools/mesh_entry_aot.py index 7a9c0afd0..7da3427ee 100644 --- a/tools/mesh_entry_aot.py +++ b/tools/mesh_entry_aot.py @@ -386,6 +386,20 @@ def scalar_op(self, op, args): ): self.load(op, args) return + if op in ("s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64"): + if len(args) != 2: + raise ValueError(f"Expected two operands for {op}") + a, b = (self.scalar(t, True) for t in args) + if a is UNDEF or b is UNDEF: + self.scc = None + return + if type(a) is not int or type(b) is not int: + raise ValueError("Dynamic scalar predicate") + mask = 63 if op.endswith("_b64") else 31 + width = WAVE if op.endswith("_b64") else U32 + bit = ((a & width) >> (b & mask)) & 1 + self.scc = bit == (1 if op.startswith("s_bitcmp1_") else 0) + return if op.startswith("s_cmp_"): a, b = (self.scalar(t, True) for t in args) if a is UNDEF or b is UNDEF: @@ -767,6 +781,10 @@ def exec_range(self, decoded, expressions, jumps, pc, stop, arm=False): return True if op in ("s_inst_prefetch", "s_nop"): continue + if op == "s_clause": + if not re.fullmatch(r"0x[0-9a-fA-F]+|0|[1-9]\d*", tail) or not 0 <= int(tail, 0) <= 0x3F: + raise ValueError(f"Invalid s_clause operand: {tail}") + continue if op == "s_barrier": if self.ds_writes_pending: raise ValueError("LDS store not waited before the barrier") From 5f51daaa7c22fb53dc1d3b5f7a2cbf9ec13693aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:34:01 +0300 Subject: [PATCH 155/232] cpu: run SQRTSD on the processor in the SSE2 leaf translator (#2545) op_sqrtsd_q decided negative inputs with a C sign test and took the root with std::sqrt. Under MXCSR.DAZ the processor reads a negative denormal operand as -0 and SQRTSD returns -0; the lifted code returned the real indefinite (0xFFF8000000000000). The helper now executes SQRTSD through _mm_sqrt_sd on a volatile operand, as op_maxsd_q and op_minsd_q already do, so NaN quieting, negative operands, rounding and DAZ come from the host instruction. tests/cpu/sse2_regs_check.py extends its DAZ case with op_sqrtsd_reg and op_sqrtsd_mem on positive and negative denormals, computing the unflushed controls before MXCSR is written. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/cpu/sse2_regs_check.py | 20 +++++++++++++------- tools/cpu_sse2_aot.py | 17 +++++++---------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/tests/cpu/sse2_regs_check.py b/tests/cpu/sse2_regs_check.py index 06492fc3c..96d289c7f 100644 --- a/tests/cpu/sse2_regs_check.py +++ b/tests/cpu/sse2_regs_check.py @@ -547,8 +547,9 @@ def check_differential(native_path, lifted_path, altered_path): def check_daz_extrema(native_path, lifted_path): - """MAXSD and MINSD under MXCSR.DAZ return a denormal operand as a zero of its sign.""" - names = ("op_maxsd_reg", "op_minsd_reg") + """MAXSD and MINSD under MXCSR.DAZ return a denormal operand as a zero of its sign, and SQRTSD + takes the root of that zero: a negative denormal gives -0, not the real indefinite.""" + names = ("op_maxsd_reg", "op_minsd_reg", "op_sqrtsd_reg", "op_sqrtsd_mem") native, lifted = bind_exports(native_path, "", names), bind_exports(lifted_path, "lifted_", names) host = ctypes.CDLL(str(Path(native_path).resolve())) for function in (host.read_mxcsr, host.write_mxcsr): @@ -556,22 +557,27 @@ def check_daz_extrema(native_path, lifted_path): denormal, sign, minus_one, one = 0x000123456789ABCD, 1 << 63, 0xBFF0000000000000, 0x3FF0000000000000 # (export, destination, source, result): the result is the second operand or the first, flushed by DAZ. cases = (("op_maxsd_reg", denormal, minus_one, 0), ("op_maxsd_reg", denormal | sign, minus_one, sign), - ("op_minsd_reg", one, denormal | sign, sign), ("op_minsd_reg", one, denormal, 0)) + ("op_minsd_reg", one, denormal | sign, sign), ("op_minsd_reg", one, denormal, 0), + ("op_sqrtsd_reg", one, denormal | sign, sign), ("op_sqrtsd_mem", one, denormal | sign, sign), + ("op_sqrtsd_reg", one, denormal, 0), ("op_sqrtsd_mem", one, 1, 0)) + # What a C comparison returns for MAXSD/MINSD, and the root of the unflushed operand for SQRTSD. Python's + # own float operations run under the MXCSR written below, so these are computed before it is written. + unflushed = [a0 if name == "op_maxsd_reg" else b0 if name == "op_minsd_reg" else ref_sqrtsd(b0) + for name, a0, b0, _ in cases] saved = ctypes.c_uint32() host.read_mxcsr(ctypes.byref(saved)) try: host.write_mxcsr(ctypes.byref(ctypes.c_uint32(0x1FC0))) - for name, a0, b0, result in cases: + for (name, a0, b0, result), unflushed_result in zip(cases, unflushed): a, b = pk_q(a0, 7), pk_q(b0, 9) - unflushed = a0 if name == "op_maxsd_reg" else b0 # what a C comparison returns - if unflushed == result: + if unflushed_result == result: raise AssertionError(f"{name}: control case cannot tell a flushed result apart") for label, function in (("native", native[name]), ("lifted", lifted[name])): assert_equal_output(f"{label} DAZ", name, hex(a0), invoke(function, a, b), pk_q(result, 7) + FILL[16:]) finally: host.write_mxcsr(ctypes.byref(saved)) - print(f"{len(cases)} MAXSD/MINSD denormal results under MXCSR.DAZ matched the native instruction") + print(f"{len(cases)} MAXSD/MINSD/SQRTSD denormal results under MXCSR.DAZ matched the native instruction") # --- Alternative-encoding acceptance & translator rejection controls --- diff --git a/tools/cpu_sse2_aot.py b/tools/cpu_sse2_aot.py index 62e0eeeba..43ab51704 100644 --- a/tools/cpu_sse2_aot.py +++ b/tools/cpu_sse2_aot.py @@ -271,17 +271,14 @@ return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(_mm_min_sd(x, y)))); } -// SQRTSD keeps the NaN payload (quieted) and yields the real-indefinite QNaN -// for negative nonzero inputs, matching the host instruction. +// SQRTSD runs on the processor, on a run-time operand: it keeps the NaN payload (quieted), yields the +// real-indefinite QNaN for negative nonzero inputs and rounds as the MXCSR says. Under MXCSR.DAZ it reads a +// denormal operand as a zero of its sign, so a negative denormal gives -0 (a C sign test and std::sqrt give +// the real indefinite). static std::uint64_t op_sqrtsd_q(std::uint64_t b) { - const double v = q_as_double(b); - if (v != v) { - return b | 0x0008000000000000ull; - } - if (v < 0.0) { - return 0xfff8000000000000ull; - } - return double_as_q(std::sqrt(v)); + volatile std::uint64_t vb = b; + const __m128d x = _mm_castsi128_pd(_mm_cvtsi64_si128(static_cast(vb))); + return static_cast(_mm_cvtsi128_si64(_mm_castpd_si128(_mm_sqrt_sd(x, x)))); } // MXCSR rounding under the default round-to-nearest-even mode. NaN, infinity From d82df00f5b9ab4a0e977337eef25db1622d99cd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:36:16 +0300 Subject: [PATCH 156/232] tooling: count accumulator destinations as reads in ps_input_scan (#2537) ps_input_scan.py derives a pixel shader's live-in vector registers from the registers read before any write, but treated the first operand of every form with a vector destination as a pure write. The multiply- and dot-accumulate forms (v_mac_*, v_fmac_*, v_pk_fmac_f16, v_dot*c_*) add to their destination and v_writelane_b32 keeps its other lanes, so an accumulator that was never written is an input register. It was left out of the contract, which loosens the coverage rule (C1) and miscounts tight pipelines for that shader. Read the destination of those forms as a source too. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- tests/startup_ps_input_scan_check.py | 12 ++++++++++++ tools/startup/ps_input_scan.py | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/startup_ps_input_scan_check.py b/tests/startup_ps_input_scan_check.py index 52771d87a..fe2c44463 100644 --- a/tests/startup_ps_input_scan_check.py +++ b/tests/startup_ps_input_scan_check.py @@ -199,12 +199,24 @@ def lines(*asm): (['exp mrt0 off, off, v6, v7 done vm'], [6, 7]), (['exp mrt0 v5, v6, v7, v8 done vm'], [5, 6, 7, 8]), (['v_cmpx_lt_f32_sdwa v1, v2 src0_sel:WORD_0 src1_sel:WORD_1'], [1, 2]), + # Accumulating forms read their destination; v_writelane_b32 keeps the other lanes of it. + (['v_fmac_f32_e64 v2, v0, v1'], [0, 1, 2]), + (['v_writelane_b32 v2, s0, 1'], [2]), + (['v_mov_b32_e32 v2, 0', 'v_fmac_f32_e32 v2, v0, v1'], [0, 1]), ) for asm, live in cases: got = sorted(S.contract_of_decoded(lines(*asm)).live_in) assert got == live, (asm, got, live) print('destination rule: %d decoded-text cases' % len(cases)) + # The same on gfx1013 VOP2 encodings: an accumulator that was never written is a live-in register. + accumulators = ((0x1f, 'v_mac_f32_e32'), (0x2b, 'v_fmac_f32_e32'), (0x06, 'v_mac_legacy_f32_e32'), + (0x36, 'v_fmac_f16_e32'), (0x3c, 'v_pk_fmac_f16')) + for op, name in accumulators: + code = shader((w(vop2(op, 2, 1, v(0))), '%s v2, v0, v1' % name), exp(2, 2, 2, 2)) + assert sets(contract_of(code)) == ([0, 1, 2], [], []), (name, sets(contract_of(code))) + print('accumulator rule: %d encoded forms read their destination' % len(accumulators)) + # A flow the text cannot resolve makes every written-later first read ambiguous. for flow in ('s_setpc_b64 s[2:3]', 's_branch 0x4', 's_cbranch_join s2'): got = S.contract_of_decoded(lines('v_add_f32_e32 v6, v5, v5', flow, 'v_mov_b32_e32 v5, 0')) diff --git a/tools/startup/ps_input_scan.py b/tools/startup/ps_input_scan.py index fed2b2666..d2ff96a44 100644 --- a/tools/startup/ps_input_scan.py +++ b/tools/startup/ps_input_scan.py @@ -59,6 +59,9 @@ # Forms whose operands are all sources even though the first one may be a vector register. ALL_SOURCE_PREFIXES = ('v_cmp', 'ds_write', 'v_nop') READ_WRITE = ('v_swap_b32', 'v_swaprel_b32') +# Forms that also read their destination: the multiply-accumulate and dot-accumulate forms add to it, and +# v_writelane_b32 keeps every other lane of it. +DESTINATION_READ_PREFIXES = ('v_mac_', 'v_fmac_', 'v_pk_fmac_', 'v_dot2c_', 'v_dot4c_', 'v_dot8c_', 'v_writelane_b32') UNKNOWN_FLOW = ('s_setpc_b64', 's_swappc_b64', 's_rfe_b64', 's_call_b64') @@ -108,7 +111,7 @@ def parse_instruction(asm): ops[0] = ops[0].partition(' ')[2] destination = operand_vregs(ops[0]) if ops else None has_destination = destination is not None and not all_source(base) and base not in READ_WRITE - sources = ops[1:] if has_destination else ops + sources = ops[1:] if has_destination and not base.startswith(DESTINATION_READ_PREFIXES) else ops if base in READ_WRITE: # both operands are read, then both are rewritten writes = [span for span in map(operand_vregs, ops) if span] else: From 004540669f9bb474099166954f35c6e4435e33f5 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:38:08 +0200 Subject: [PATCH 157/232] pe: add atomic report writes and path/error guards in compat_report with CLI suite (#2542) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/compat_report_cli_check.py | 565 +++++++++++++++++++++++++++++++ tools/compat_report.py | 54 ++- 3 files changed, 613 insertions(+), 8 deletions(-) create mode 100644 tests/compat_report_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index faa983917..485a83325 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9800,6 +9800,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/bidi_controls_check.py") add_test(NAME compat_report COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compat_report_check.py") + add_test(NAME pe_compat_report_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compat_report_cli_check.py") add_test(NAME form_coverage COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/form_coverage_check.py") add_test(NAME gpu_report_format COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/compat_report_cli_check.py b/tests/compat_report_cli_check.py new file mode 100644 index 000000000..50f634acf --- /dev/null +++ b/tests/compat_report_cli_check.py @@ -0,0 +1,565 @@ +"""CLI, atomic output, path/error guard, and mutation suite for tools/compat_report.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "compat_report.py" +sys.path.insert(0, str(ROOT / "tools")) + +import compat_report # noqa: E402 + + +SECTION_RVA = 0x1000 +RAW_OFFSET = 0x200 +RAW_SIZE = 0x1000 +IMAGE_BASE = 0x180000000 + +CLEAN_IMPORTS = [ + ("normal", "kernel32.dll", "ExitProcess"), + ("normal", "xmem.dll", "XMemAlloc"), + ("delay", "xgameruntime.dll", "XUserGetId"), +] +UNKNOWN_IMPORTS = CLEAN_IMPORTS + [("normal", "mystery.dll", "MissingExport")] + + +def _build_synthetic_pe32_plus(imports, *, machine=0x8664): + """Build a minimal synthetic PE32+ image with normal and delay imports.""" + data = bytearray(RAW_SIZE) + cursor = 0 + + def alloc(size, align): + nonlocal cursor + cursor = (cursor + align - 1) & ~(align - 1) + rva = SECTION_RVA + cursor + if cursor + size > len(data): + raise AssertionError("synthetic section overflow") + cursor += size + return rva + + def put(rva, blob): + offset = rva - SECTION_RVA + data[offset:offset + len(blob)] = blob + + module_rvas = {} + for module in sorted({mod for _, mod, _ in imports}): + raw = module.encode("ascii") + b"\0" + rva = alloc(len(raw), 2) + put(rva, raw) + module_rvas[module] = rva + + hint_rvas = {} + for kind, module, symbol in imports: + raw = struct.pack(" mystery.dll!MissingExport", proc.stdout) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json", "report.md"]) + + report = json.loads(json_out.read_text(encoding="utf-8")) + self.assertEqual(report["sections"]["import_routing"]["summary"]["unknown"], 1) + self.assertIn("mystery.dll", md_out.read_text(encoding="utf-8")) + + proc_clean = _run_subprocess( + str(clean_pe), "--json", str(json_out), "--markdown", str(md_out) + ) + self.assertEqual(proc_clean.returncode, 0, proc_clean.stderr) + self.assertEqual(proc_clean.stdout, "") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json", "report.md"]) + self.assertEqual( + json.loads(json_out.read_text(encoding="utf-8"))["sections"]["import_routing"]["summary"]["unknown"], + 0, + ) + + def test_main_sys_argv_forwarding_and_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + image = root / "entry.exe" + json_out = root / "entry.json" + md_out = root / "entry.md" + image.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS)) + cli_argv = [str(TOOL), str(image), "--json", str(json_out), "--markdown", str(md_out)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertTrue(json_out.is_file() and md_out.is_file()) + + json_out.unlink() + md_out.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(json_out.is_file() and md_out.is_file()) + + +class CompatReportCliNegativeAndMutationTests(unittest.TestCase): + def _assert_exit_2_clean(self, argv, *, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("compat_report:", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("compat_report:", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_missing_directory_corrupt_and_wrong_machine_pe_exit_2(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.exe" + json_out = root / "nested" / "report.json" + md_out = root / "nested" / "report.md" + self._assert_exit_2_clean( + [str(missing), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="missing.exe", + ) + self.assertFalse(json_out.parent.exists()) + + image_dir = root / "dir.exe" + image_dir.mkdir() + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean( + [str(image_dir), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="directory", + check_subprocess=False, + ) + build_mock.assert_not_called() + self.assertFalse(json_out.parent.exists()) + proc = _run_subprocess(str(image_dir), "--json", str(json_out), "--markdown", str(md_out)) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("compat_report:", proc.stderr) + self.assertIn("directory", proc.stderr) + + corrupt = root / "corrupt.exe" + corrupt.write_bytes(b"NOT_A_PE_IMAGE") + self._assert_exit_2_clean( + [str(corrupt), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="corrupt.exe", + ) + self.assertFalse(json_out.parent.exists()) + + x86_pe = root / "x86.exe" + x86_pe.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS, machine=0x014C)) + self._assert_exit_2_clean( + [str(x86_pe), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="IMAGE_FILE_MACHINE_I386", + ) + + def test_struct_error_in_pe_parse_returns_exit_2_without_traceback(self): + # Kills removal of struct.error from the PE parse exception guard. + with TemporaryDirectory() as tmp: + root = Path(tmp) + image = root / "sample.exe" + image.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS)) + json_out = root / "out" / "report.json" + md_out = root / "out" / "report.md" + + with mock.patch.object( + compat_report, "import_tables", side_effect=struct.error("truncated import table") + ): + self._assert_exit_2_clean( + [str(image), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="truncated import table", + check_subprocess=False, + ) + self.assertFalse(json_out.parent.exists()) + + with mock.patch.object( + compat_report.pefile, "PE", side_effect=struct.error("truncated PE header") + ): + self._assert_exit_2_clean( + [str(image), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="truncated PE header", + check_subprocess=False, + ) + self.assertFalse(json_out.parent.exists()) + + def test_output_directory_rejected_upfront_before_building_report(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + image = root / "image.exe" + image.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS)) + existing_dir = root / "existing_dir" + existing_dir.mkdir() + json_file = root / "json_parent" / "report.json" + md_file = root / "md_parent" / "report.md" + + for bad_argv, missing_parent in ( + ([str(image), "--json", str(existing_dir), "--markdown", str(md_file)], md_file.parent), + ([str(image), "--json", str(json_file), "--markdown", str(existing_dir)], json_file.parent), + ): + with self.subTest(argv=bad_argv): + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean( + bad_argv, + expected_fragment="existing directory", + check_subprocess=False, + ) + build_mock.assert_not_called() + self.assertFalse(missing_parent.exists()) + proc = _run_subprocess(*bad_argv) + self.assertEqual(proc.returncode, 2) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("existing directory", proc.stderr) + self.assertFalse(missing_parent.exists()) + + def test_output_paths_colliding_or_containing_each_other_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + image = root / "image.exe" + image.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS)) + sub = root / "sub" + sub.mkdir() + + # 1) Non-existent --json and --markdown colliding via resolve() (kills resolve() check). + ghost_json = root / "out" / "report.out" + alias_md = root / "out" / ".." / "out" / "report.out" + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean( + [str(image), "--json", str(ghost_json), "--markdown", str(alias_md)], + expected_fragment="collide", + ) + build_mock.assert_not_called() + self.assertFalse(ghost_json.parent.exists()) + + # 2) Pre-existing hardlink alias where resolve() differs (kills samefile() check). + real_out = root / "report_a.out" + link_out = sub / "report_b.out" + real_out.write_text("keep-a\n", encoding="utf-8") + os.link(real_out, link_out) + self.assertNotEqual(real_out.resolve(), link_out.resolve()) + self.assertTrue(real_out.samefile(link_out)) + + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean( + [str(image), "--json", str(real_out), "--markdown", str(link_out)], + expected_fragment="collide", + ) + build_mock.assert_not_called() + self.assertEqual(real_out.read_text(encoding="utf-8"), "keep-a\n") + + # 3) --json and --markdown containing one another (kills parent containment guard). + parent_out = root / "nested_pair" / "item" + child_out = parent_out / "child.md" + for j_path, m_path in ((parent_out, child_out), (child_out, parent_out)): + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean( + [str(image), "--json", str(j_path), "--markdown", str(m_path)], + expected_fragment="contain one another", + check_subprocess=False, + ) + build_mock.assert_not_called() + self.assertFalse(parent_out.parent.exists()) + + def test_output_collision_with_image_via_resolve_and_samefile_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + other_out = root / "other_out" / "side.txt" + + # 1) Non-existent image + alias colliding via resolve() (kills resolve() vs image). + ghost_img = root / "missing.exe" + alias_path = root / "sub" / ".." / "missing.exe" + for argv in ( + [str(ghost_img), "--json", str(alias_path), "--markdown", str(other_out)], + [str(ghost_img), "--json", str(other_out), "--markdown", str(alias_path)], + ): + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean(argv, expected_fragment="collides with image") + build_mock.assert_not_called() + self.assertFalse(other_out.parent.exists()) + + # 2) Existing image + hardlink alias where resolve() differs (kills samefile() vs image). + real_img = root / "real.exe" + hardlink = sub / "hardlink.out" + pe_bytes = _build_synthetic_pe32_plus(CLEAN_IMPORTS) + real_img.write_bytes(pe_bytes) + os.link(real_img, hardlink) + self.assertNotEqual(real_img.resolve(), hardlink.resolve()) + self.assertTrue(real_img.samefile(hardlink)) + + for argv in ( + [str(real_img), "--json", str(hardlink), "--markdown", str(other_out)], + [str(real_img), "--json", str(other_out), "--markdown", str(hardlink)], + ): + with mock.patch.object(compat_report, "build_report") as build_mock: + self._assert_exit_2_clean(argv, expected_fragment="collides with image") + build_mock.assert_not_called() + self.assertEqual(real_img.read_bytes(), pe_bytes) + self.assertFalse(other_out.parent.exists()) + + def test_os_replace_and_staging_failures_leave_zero_temp_dirs_and_preserve_files(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + image = root / "image.exe" + image.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS)) + out_dir = root / "out" + json_out = out_dir / "report.json" + md_out = out_dir / "report.md" + + def failing_replace(src, dst): + src_path = Path(src) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), Path(dst).parent.resolve()) + raise OSError("simulated replace failure") + + # 1) Fresh outputs: os.replace OSError -> exit 2, zero output files and zero temp dirs. + with mock.patch.object(compat_report.os, "replace", side_effect=failing_replace): + self._assert_exit_2_clean( + [str(image), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(list(out_dir.iterdir()), []) + + # 2) Pre-existing outputs: os.replace OSError -> prior files preserved, zero temp dirs. + json_out.write_text("prior-json\n", encoding="utf-8") + md_out.write_text("prior-md\n", encoding="utf-8") + with mock.patch.object(compat_report.os, "replace", side_effect=failing_replace): + self._assert_exit_2_clean( + [str(image), "--json", str(json_out), "--markdown", str(md_out)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(json_out.read_text(encoding="utf-8"), "prior-json\n") + self.assertEqual(md_out.read_text(encoding="utf-8"), "prior-md\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json", "report.md"]) + + # 3) Direct _write_text staging write failure -> os.replace never called, zero temp dirs. + with ( + mock.patch.object(compat_report.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated stage write failure")), + ): + with self.assertRaises(OSError): + compat_report._write_text(json_out, "new-json\n") + replace_mock.assert_not_called() + self.assertEqual(json_out.read_text(encoding="utf-8"), "prior-json\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json", "report.md"]) + + def test_argparse_missing_required_flags_exit_2_without_traceback(self): + with TemporaryDirectory() as tmp: + image = Path(tmp) / "image.exe" + image.write_bytes(_build_synthetic_pe32_plus(CLEAN_IMPORTS)) + for bad_argv in ([str(image)], [str(image), "--json", str(Path(tmp) / "r.json")]): + proc = _run_subprocess(*bad_argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("usage:", proc.stderr.lower()) + self.assertIn("--markdown", proc.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/compat_report.py b/tools/compat_report.py index 0b93fa6f0..7fd519888 100644 --- a/tools/compat_report.py +++ b/tools/compat_report.py @@ -8,8 +8,11 @@ import argparse import hashlib import json +import os from pathlib import Path +import struct import sys +import tempfile import pefile @@ -251,9 +254,36 @@ def markdown_report(report): return "\n".join(lines) + "\n" +def _same_path(left, right): + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _validate_paths(image, json_path, markdown_path): + for flag, out_path in (("--json", json_path), ("--markdown", markdown_path)): + if out_path.exists() and out_path.is_dir(): + raise ValueError(f"{flag} output path is an existing directory: {out_path}") + if _same_path(json_path, markdown_path): + raise ValueError(f"--json and --markdown output paths collide: {json_path}") + json_resolved = json_path.resolve() + markdown_resolved = markdown_path.resolve() + if json_resolved in markdown_resolved.parents or markdown_resolved in json_resolved.parents: + raise ValueError("--json and --markdown output paths cannot contain one another") + for flag, out_path in (("--json", json_path), ("--markdown", markdown_path)): + if _same_path(image, out_path): + raise ValueError(f"{flag} output path collides with image: {out_path}") + if image.is_dir(): + raise ValueError(f"image path is a directory: {image}") + + def _write_text(path, text): + path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8", newline="\n") + with tempfile.TemporaryDirectory(dir=path.parent) as staging_dir: + staged = Path(staging_dir) / path.name + staged.write_text(text, encoding="utf-8", newline="\n") + os.replace(staged, path) def main(argv=None): @@ -263,26 +293,34 @@ def main(argv=None): parser.add_argument("--markdown", type=Path, required=True, help="deterministic Markdown output") args = parser.parse_args(argv) - image_name = args.image.name + image_name = args.image.name or str(args.image) + try: + _validate_paths(args.image, args.json, args.markdown) + except (OSError, ValueError) as exc: + print(f"compat_report: {exc}", file=sys.stderr) + return 2 + try: image_bytes = args.image.read_bytes() except OSError as exc: - detail = getattr(exc, "strerror", None) or type(exc).__name__ + detail = getattr(exc, "strerror", None) or str(exc) or type(exc).__name__ print(f"compat_report: cannot read {image_name}: {detail}", file=sys.stderr) return 2 try: report = build_report(image_bytes, image_name) - except (pefile.PEFormatError, ValueError) as exc: + except (pefile.PEFormatError, ValueError, struct.error) as exc: print(f"compat_report: cannot read {image_name}: {exc}", file=sys.stderr) return 2 try: - _write_text(args.json, json.dumps( - report, sort_keys=True, indent=2, ensure_ascii=True) + "\n") - _write_text(args.markdown, markdown_report(report)) + json_text = json.dumps( + report, sort_keys=True, indent=2, ensure_ascii=True) + "\n" + markdown_text = markdown_report(report) + _write_text(args.json, json_text) + _write_text(args.markdown, markdown_text) except OSError as exc: - detail = getattr(exc, "strerror", None) or type(exc).__name__ + detail = getattr(exc, "strerror", None) or str(exc) or type(exc).__name__ print(f"compat_report: cannot write report: {detail}", file=sys.stderr) return 2 From c6b5a109da7ef84b3d0628488ff9793dd836cbed Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Wed, 25 Nov 2026 20:40:57 +0000 Subject: [PATCH 158/232] startup: lower cube coordinate operations in gfx2hlsl (#2514) * startup: lower cube coordinate operations in gfx2hlsl Implement v_cubeid_f32, v_cubesc_f32, v_cubetc_f32 and v_cubema_f32 with LLVM's major-axis and face-sign rules, clamp, source neg/abs, and a source-built WARP/hardware draw. Add negative controls for swapped id/sc, tie order and the cubema factor. Refs #1723. Tests: startup_gfx2hlsl_cube_controls, startup_gfx2hlsl_cube_warp, startup_gfx2hlsl_cube_hardware; 103 non-hardware startup_gfx2hlsl tests pass. * ci: assemble the cube fixture against LLVM 15 Run startup_gfx2hlsl_cube_check.py binary in the gfx1013 fixture job so the recorded VOP3A words are checked. --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 11 ++ docs/experiments.md | 15 ++ tests/startup_gfx2hlsl_cube_check.py | 221 +++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 45 ++++++ 5 files changed, 293 insertions(+) create mode 100644 tests/startup_gfx2hlsl_cube_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index aacd07c45..878cf7bdf 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -116,6 +116,7 @@ jobs: (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mul_mad_i24_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_cube_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_vopc_sdwa_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_sop2_complement_check.py", "binary", "llvm-mc-15"], {}), diff --git a/CMakeLists.txt b/CMakeLists.txt index 485a83325..fc98d0106 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3041,6 +3041,9 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl lowers s_bitcmp1_b32 and s_bitcmp0_b32 (SOPC): CPU evaluation of the translated SCC test. add_test(NAME startup_gfx2hlsl_s_bitcmp COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_s_bitcmp_check.py") + # gfx2hlsl lowers v_cube{id,sc,tc,ma}_f32: device-free translation controls. + add_test(NAME startup_gfx2hlsl_cube_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py") # gfx2hlsl.py --watch consumes only ready requests and does not retry an unchanged failure. add_test(NAME startup_gfx2hlsl_watch COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_watch_check.py") @@ -3386,6 +3389,14 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_bit_alu_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_cube{id,sc,tc,ma}_f32: the source-built cube directions are drawn and compared with the + # LLVM ConstantFoldAMDGCNCubeIntrinsic model; swapped id/sc, tie-order and cubema-factor controls must fail. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cube_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cube_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cube_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_interp_p1ll_f16 / v_interp_p2_f16 (#1996): translation controls with a high-half inversion # control, then a desktop draw of the translated pair with DXC 6_0. add_test(NAME startup_gfx2hlsl_interp_f16_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 560fa1c27..c05fe98dd 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7816,6 +7816,21 @@ Build `offscreen_check`, then run `ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_mul_hi_' -V`. [Refs #1792](https://github.com/R0Y00/Xbox2Windows/issues/1792) +**Cube coordinate operations.** Startup translation now lowers `v_cubeid_f32`, +`v_cubesc_f32`, `v_cubetc_f32` and `v_cubema_f32` (VOP3A) with the same +major-axis rule as LLVM's `ConstantFoldAMDGCNCubeIntrinsic`: z wins when +`|z| >= |x|` and `|z| >= |y|`, otherwise y wins when `|y| >= |x|`, otherwise +x. A face is negative only for a nonzero, non-NaN negative coordinate, and +`v_cubema_f32` returns twice the signed major coordinate. The source-built +fixture covers all six faces, the y/x and z/x ties, and `-0.0` on the major axis. +The draw compares all four result words on WARP and hardware; a swapped id/sc, +a changed tie order and a dropped `* 2.0f` factor must each mismatch. The +translation controls also cover `clamp`, source neg/abs, a missing operand, a +vector destination and unsupported modifiers. NaN coordinates are not drawn. +Build `offscreen_check`, then run +`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cube' -V`. +[Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) + **Scalar bit tests.** Startup translation sets SCC for `s_bitcmp0_b32` and `s_bitcmp1_b32` by comparing the selected bit of the first word to zero or one. Only the low five bits of the index are used. EXEC, VCC and SGPRs tracked diff --git a/tests/startup_gfx2hlsl_cube_check.py b/tests/startup_gfx2hlsl_cube_check.py new file mode 100644 index 000000000..3b3f1b67e --- /dev/null +++ b/tests/startup_gfx2hlsl_cube_check.py @@ -0,0 +1,221 @@ +"""v_cube{id,sc,tc,ma}_f32 in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls, pure Python + binary reassemble the fixture sources and compare them with the words below + draw [fxc] + compile the translated pair and compare four output words per + direction on a source-built full-screen triangle + +The four operations follow LLVM's ConstantFoldAMDGCNCubeIntrinsic. The major axis is z when |z| is at +least |x| and |y|, otherwise y when |y| is at least |x|, otherwise x. A face is negative only for a +nonzero, non-NaN negative coordinate. cubema returns twice the signed major coordinate. +""" +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, vs_source, vs_words, +) + +OPS = ('v_cubeid_f32', 'v_cubesc_f32', 'v_cubetc_f32', 'v_cubema_f32') +BODY_SOURCE = '''\ +v_cubeid_f32 v12, v0, v4, v8 +v_cubesc_f32 v13, v1, v5, v9 +v_cubetc_f32 v14, v2, v6, v10 +v_cubema_f32 v15, v3, v7, v11 +''' +BODY_WORDS = bytes.fromhex( + '0c0044d500092204' '0d0045d5010b2604' '0e0046d5020d2a04' '0f0047d5030f2e04') +# The first pair is swapped as a negative control: the same inputs then write sc to v12 and id to v13. +BAD_BODY = bytes.fromhex( + '0c0045d500092204' '0d0044d5010b2604' '0e0046d5020d2a04' '0f0047d5030f2e04') + +# Each direction covers a face; the first group also contains y/x and z/x ties and -0.0 on the major axis. +DIRECTIONS = ( + (2.0, -2.0, 1.0), + (-1.5, 0.25, -1.5), + (-3.0, 1.0, 2.0), + (0.0, 0.0, -0.0), + (1.0, 0.5, -0.25), + (0.25, 1.0, 0.5), + (0.5, -1.0, -0.5), + (-0.25, -0.5, 1.0), +) + + +class Probe(G.Stage): + """A Stage with no pipeline: enough state for one instruction to be translated.""" + + def __init__(self): + self.lines, self.sym = [], {} + self.used_s, self.used_v, self.uniform_v = set(), set(), set() + self.exec_known = True + + +def one(assembly): + Probe().one(assembly.split(' ', 1)[0], assembly) + + +def refused(assembly): + try: + one(assembly) + except G.Unsupported as reason: + return str(reason) + return None + + +def word(value): + return struct.unpack('= abs(x) and abs(z) >= abs(y): + face, sc, tc, ma = (5.0, -x, -y, z) if z < 0 else (4.0, x, -y, z) + elif abs(y) >= abs(x): + face, sc, tc, ma = (3.0, x, -z, y) if y < 0 else (2.0, x, z, y) + else: + face, sc, tc, ma = (1.0, z, -y, x) if x < 0 else (0.0, -z, -y, x) + return [face, sc, tc, ma + ma] + + +def expected_text(directions): + return ','.join('%08x' % word(value) for d in directions for value in cube_reference(*d)) + + +def translate(directions, body=BODY_WORDS): + return G.Pipeline(vs_words(direction_words(directions)), PRE_WORDS + body + POST_WORDS, root_blob()) + + +def controls(): + checks = { + 'v_cubeid_f32': ('? 5.0f : 4.0f', '? 3.0f : 2.0f', '? 1.0f : 0.0f'), + 'v_cubesc_f32': ('-cube0.x', 'cube0.x', '-cube0.z', 'cube0.z'), + 'v_cubetc_f32': ('-cube0.y', '-cube0.z', 'cube0.z'), + 'v_cubema_f32': ('* 2.0f',), + } + for op in OPS: + stage = Probe() + stage.one(op, '%s v12, v0, v4, v8' % op) + assert stage.lines[0] == 'float3 cube0 = float3(F(v0), F(v4), F(v8));', stage.lines + assert stage.lines[1].startswith('v12 = U('), stage.lines + for needle in checks[op]: + assert needle in stage.lines[1], (op, needle, stage.lines) + print('%s: translated' % op) + + clamp = Probe() + clamp.one('v_cubeid_f32', 'v_cubeid_f32 v12, v0, v4, v8 clamp') + assert 'saturate(' in clamp.lines[1], clamp.lines + print('clamp: saturates the result') + + modified = Probe() + modified.one('v_cubeid_f32', 'v_cubeid_f32 v12, -v0, |v4|, v8') + assert '(-F(v0))' in modified.lines[0] and 'abs(F(v4))' in modified.lines[0], modified.lines + print('source neg/abs: applied before the cube operation') + + separate = Probe() + separate.one('v_cubeid_f32', 'v_cubeid_f32 v12, v0, v4, v8') + first_temp = separate.lines[0] + separate.lines = [] + separate.one('v_cubema_f32', 'v_cubema_f32 v13, v1, v5, v9') + assert 'float3 cube0' in first_temp and 'float3 cube1' in separate.lines[0], (first_temp, separate.lines) + print('separate blocks: temporary names stay unique') + + for assembly, needle in ( + ('v_cubeid_f32 v12, v0, v4', 'expected 4'), + ('v_cubeid_f32 v256, v0, v4, v8', 'destination'), + ('v_cubeid_f32 v12, v0, v4, v8 mul:2', 'with mul:2'), + ('v_cubeid_f32 v12, v0, v4, v8 op_sel:[1,0,0]', 'with op_sel'), + ): + reason = refused(assembly) + assert reason and needle in reason, (assembly, reason) + print('refused: %s (%s)' % (assembly, reason)) + + +def check_binary(llvm_mc): + assert assemble(llvm_mc, BODY_SOURCE) == BODY_WORDS + assert assemble(llvm_mc, PRE_SOURCE) == PRE_WORDS + assert assemble(llvm_mc, POST_SOURCE) == POST_WORDS + for index in range(0, len(DIRECTIONS), 4): + directions = DIRECTIONS[index:index + 4] + assert assemble(llvm_mc, vs_source(direction_words(directions))) == vs_words(direction_words(directions)) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for index, direction in enumerate(DIRECTIONS): + pipe = translate((direction,) * 4) + vs = compile_hlsl(compiler, kind, pipe.hlsl_vs(), + 'cube_vs_%d_%s' % (index, kind), vs_profile, directory) + ps = compile_hlsl(compiler, kind, pipe.hlsl_ps(), + 'cube_ps_%d_%s' % (index, kind), ps_profile, directory) + expected = expected_text((direction,)) + run = draw(renderer, adapter, vs, ps, expected) + if run.returncode: + raise AssertionError('%s cube direction %s\n%s\n%s' % (kind, direction, run.stdout, run.stderr)) + print('%s cube direction %s: %s' % (kind, direction, expected), flush=True) + + first = DIRECTIONS[0] + first_pipe = translate((first,) * 4) + first_vs = compile_hlsl(compiler, kind, first_pipe.hlsl_vs(), + 'cube_first_vs_%s' % kind, vs_profile, directory) + first_expected = expected_text((first,)) + + bad_ps = compile_hlsl(compiler, kind, translate((first,) * 4, BAD_BODY).hlsl_ps(), + 'cube_bad_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, first_vs, bad_ps, first_expected) + if run.returncode == 0: + raise AssertionError('%s swapped id/sc did not mismatch\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s swapped id/sc: mismatch as expected' % kind, flush=True) + + tie = DIRECTIONS[1] + tie_pipe = translate((tie,) * 4) + tie_vs = compile_hlsl(compiler, kind, tie_pipe.hlsl_vs(), + 'cube_tie_vs_%s' % kind, vs_profile, directory) + tie_ps = compile_hlsl(compiler, kind, tie_pipe.hlsl_ps().replace('>=', '>'), + 'cube_tie_ps_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, tie_vs, tie_ps, expected_text((tie,))) + if run.returncode == 0: + raise AssertionError('%s tie-order control did not mismatch\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s tie-order control: mismatch as expected' % kind, flush=True) + + doubled_ps = compile_hlsl(compiler, kind, first_pipe.hlsl_ps().replace('* 2.0f', '* 1.0f'), + 'cube_double_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, first_vs, doubled_ps, first_expected) + if run.returncode == 0: + raise AssertionError('%s cubema factor control did not mismatch\n%s\n%s' + % (kind, run.stdout, run.stderr)) + print('%s cubema factor control: mismatch as expected' % kind, flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6745335fa..49fb8304c 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4922,6 +4922,51 @@ def op_v_fma_mixlo_f16(self, ops, mods): def op_v_fma_mixhi_f16(self, ops, mods): self.mix(ops, mods, True) + def cube(self, kind, ops, mods): + """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. + + The major axis is z when |z| is at least |x| and |y|, otherwise y when |y| is at + least |x|, otherwise x. A face is negative only for a nonzero, non-NaN negative + coordinate. cubema returns twice the signed major coordinate. + """ + if len(ops) != 4: + raise Unsupported('v_cube%s_f32 with %d operands, expected 4' % (kind, len(ops))) + if any(m != 'clamp' for m in mods): + raise Unsupported('v_cube%s_f32 with %s' % (kind, ', '.join(mods))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] != dst[1] or dst[2] > 255: + raise Unsupported('v_cube%s_f32 destination %s' % (kind, ops[0])) + x, y, z = [self.f(o) for o in ops[1:4]] + temp = 'cube%d' % getattr(self, 'cube_temps', 0) + self.cube_temps = getattr(self, 'cube_temps', 0) + 1 + self.emit('float3 %s = float3(%s, %s, %s);' % (temp, x, y, z)) + c = temp + a = 'abs(%s)' % c + zmajor = '(%s.z >= %s.x && %s.z >= %s.y)' % (a, a, a, a) + ymajor = '(%s.y >= %s.x)' % (a, a) + expression = { + 'id': '(%s ? (%s.z < 0.0f ? 5.0f : 4.0f) : %s ? (%s.y < 0.0f ? 3.0f : 2.0f) ' + ': (%s.x < 0.0f ? 1.0f : 0.0f))' % (zmajor, c, ymajor, c, c), + 'sc': '(%s ? (%s.z < 0.0f ? -%s.x : %s.x) : %s ? %s.x ' + ': (%s.x < 0.0f ? %s.z : -%s.z))' % (zmajor, c, c, c, ymajor, c, c, c, c), + 'tc': '(%s ? -%s.y : %s ? (%s.y < 0.0f ? -%s.z : %s.z) : -%s.y)' % ( + zmajor, c, ymajor, c, c, c, c), + 'ma': '((%s ? %s.z : %s ? %s.y : %s.x) * 2.0f)' % (zmajor, c, ymajor, c, c), + }[kind] + self.set_vf(dst[1], expression, mods) + + def op_v_cubeid_f32(self, ops, mods): + self.cube('id', ops, mods) + + def op_v_cubesc_f32(self, ops, mods): + self.cube('sc', ops, mods) + + def op_v_cubetc_f32(self, ops, mods): + self.cube('tc', ops, mods) + + def op_v_cubema_f32(self, ops, mods): + self.cube('ma', ops, mods) + def i64_words(self, tok): """(low, high) uint expressions of a 64-bit integer source: a VGPR/SGPR pair or an inline int.""" pair = reg_range(tok) From 822b207eb6cb35e09a8c8d621c8dc2bd129b2323 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 04:42:15 +0800 Subject: [PATCH 159/232] tests: draw all eight integer predicate groups on one device (#2541) Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 18 +++++++++--------- tests/pixel_aot_check.py | 34 +++++++++++++++++++++++----------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c05fe98dd..c55c94743 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7459,15 +7459,15 @@ sets the process exit code to 1. The remaining pairs still report a status. Run `ctest --preset dev --no-tests=error -R '^pixel_batch_pairs_(hardware|warp)$' -V` to compare two shaders with isolated draws and exercise mismatch and missing-file controls. -The 32-bit integer, 16-bit integer and SDWA predicate draws use the same -runner, one batch per compiled group, with the same references. The -signed-against-unsigned control of the first `i32` e32 group and the -inverted-unordered control of each SDWA group run inside their batch as -expected mismatches, each followed by a passing draw. The three 16-bit -`must_mismatch` controls, two of them on mutated shaders, keep one single-case -draw each. These three suites -go from 108 device creations to 23, and DXC compiles one shader fewer, because -the signed/unsigned control now reuses the group's compiled shader. +The 32-bit integer predicate fixture passes eight compiled shaders and 33 +references to one `--check-pixel-pairs` process. The signed-against-unsigned +reference in the first `i32` e32 group must mismatch, and the following draw +must pass. Each 16-bit integer or SDWA predicate group uses a single-shader +batch. Each SDWA inverted-unordered control still precedes a passing draw. +The three 16-bit `must_mismatch` controls use one single-case draw each. +The original per-shader batching cut device creations across these three +suites from 108 to 23 and saved one compile by reusing the signed shader. +Combining the eight 32-bit groups saves seven more device creations. The remaining multi-case `--check-pixel-case` loops across `draw-core`, `draw-predicate-rounding`, `draw-blend-scalar`, `draw-e64`, `draw-integer-nc`, diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 43f65bd72..52b5d7f4b 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -3637,9 +3637,7 @@ def predicate_group_e64(first): return with_constants(body) -def run_pixel_batch_statuses(renderer, backend, shader, paths): - command = [renderer, backend, "--check-pixel-batch", shader, *paths] - result = subprocess.run(command, capture_output=True, text=True) +def pixel_batch_statuses(result, count): if result.returncode == 77: result.check_returncode() statuses = [] @@ -3648,11 +3646,17 @@ def run_pixel_batch_statuses(renderer, backend, shader, paths): if not line.startswith(prefix): raise AssertionError(f"Unexpected batch line {line!r}\n{result.stdout}\n{result.stderr}") statuses.append(line[len(prefix):]) - if len(statuses) != len(paths) or any(status not in ("pass", "mismatch") for status in statuses): + if len(statuses) != count or any(status not in ("pass", "mismatch") for status in statuses): raise AssertionError(f"Unexpected batch statuses {statuses}\n{result.stdout}\n{result.stderr}") if result.returncode != int("mismatch" in statuses): raise AssertionError(f"Unexpected batch exit code {result.returncode}\n{result.stdout}\n{result.stderr}") - return statuses, result + return statuses + + +def run_pixel_batch_statuses(renderer, backend, shader, paths): + command = [renderer, backend, "--check-pixel-batch", shader, *paths] + result = subprocess.run(command, capture_output=True, text=True) + return pixel_batch_statuses(result, len(paths)), result def run_pixel_batch(renderer, backend, shader, cases): @@ -3976,7 +3980,6 @@ def check_predicate_draws(directory, compiler, renderer, backend): def check_int_predicate_draws(directory, compiler, renderer, backend): source = directory / "int_predicates.hlsl" - shader = directory / "int_predicates.cso" # Normal and signed-zero IEEE-754 bit patterns avoid denormal/NaN canonicalization while covering # signed/unsigned order flips (-0.0 vs +0.0, +1.0 vs -1.0) and integer-vs-float order (-2.0 vs -1.0). pairs = ( @@ -3994,9 +3997,11 @@ def relation(left_u, right_u, kind): left_v, right_v = left_u, right_u return 0 if left_v < right_v else (1 if left_v == right_v else 2) + draws = [] for kind in ("i32", "u32"): for encoding in ("e32", "e64"): for first in (0, 4): + shader = directory / f"int_predicates-{kind}-{encoding}-{first}.cso" source.write_text(translate(int_predicate_group(kind, encoding, first)), encoding="ascii") compile_shader(compiler, source, shader) cases = [] @@ -4017,11 +4022,18 @@ def relation(left_u, right_u, kind): wrong = directory / f"int_predicates-{kind}-{encoding}-{first}-unsigned-reference.case" wrong.write_bytes(constants + wrong_pixel * 64) cases.insert(-1, (wrong, "mismatch")) - try: - run_pixel_batch(renderer, backend, shader, cases) - except AssertionError as error: - error.add_note(f"Integer predicate draw on {backend}, {kind} {encoding} first={first}") - raise + draws.extend((shader, case, status) for case, status in cases) + + # Relative input names keep the Windows command line short even under a long temp path. + # Resolve an explicitly supplied executable before changing its working directory. + executable = Path(renderer).resolve() if Path(renderer).is_file() else None + paths = [name for shader, case, _ in draws for name in (shader.name, case.name)] + result = subprocess.run([renderer, backend, "--check-pixel-pairs", *paths], cwd=directory, + executable=executable, capture_output=True, text=True) + for (shader, case, expected), actual in zip(draws, pixel_batch_statuses(result, len(draws))): + if actual != expected: + raise AssertionError(f"{backend}: {shader.name} / {case.name}: expected {expected}, got {actual}\n" + f"{result.stdout}\n{result.stderr}") def check_unsigned_less_than_draws(directory, compiler, renderer, backend): From e26ade7f4a55d5b1022258e9b44ac73461058e48 Mon Sep 17 00:00:00 2001 From: yjs <1245206726@qq.com> Date: Thu, 26 Nov 2026 04:43:04 +0800 Subject: [PATCH 160/232] shader: lower 32-bit 2D compute image_store and unorm in gfx2hlsl (#2399) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 6 + docs/experiments.md | 23 +++ docs/startup-runtime.md | 2 +- tests/startup_compute_image_store_check.py | 153 ++++++++++++++++++ .../startup_compute_image_store_d16_check.py | 1 - tests/startup_pixel_image_store_check.py | 10 +- tools/startup/gfx2hlsl.py | 15 +- 9 files changed, 199 insertions(+), 14 deletions(-) create mode 100644 tests/startup_compute_image_store_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 878cf7bdf..1865740c6 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -91,6 +91,7 @@ jobs: (["tests/startup_image_sample_lod_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_compute_image_store_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_image_store_d16_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), @@ -211,6 +212,7 @@ jobs: tests/startup_image_sample_lod_check.py \ tests/startup_image_gather_lz_check.py \ tests/startup_compute_gather_lz_check.py \ + tests/startup_compute_image_store_check.py \ tests/startup_compute_image_store_d16_check.py \ tests/startup_compute_gather_l_check.py \ tests/startup_compute_buffer_atomics_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 4a0be0ba8..6aeaaa468 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,6 +166,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_table_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py +./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fc98d0106..1d18a86b8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2983,6 +2983,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_image_gather_lz_check.py") add_test(NAME startup_compute_gather_lz COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_gather_lz_check.py") + add_test(NAME startup_compute_image_store COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_check.py") add_test(NAME startup_compute_image_store_d16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py") add_test(NAME startup_compute_readfirstlane COMMAND "${INTAKE_PYTHON}" -B @@ -9604,6 +9606,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_compute_gather_lz_check.py" --dispatch "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(startup_compute_gather_lz_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) + add_test(NAME startup_compute_image_store_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_image_store_check.py" --dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_image_store_${adapter} PROPERTIES TIMEOUT 90 SKIP_RETURN_CODE 77) add_test(NAME startup_compute_image_store_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_image_store_d16_check.py" --dispatch "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index c55c94743..c7efb0451 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14111,6 +14111,29 @@ cmake --build --preset release --target offscreen_check ctest --preset release --no-tests=error -R '^startup_compute_image_store_d16' -V ``` +### Startup compute 32-bit float image store + +The startup compute translator also accepts a 2D 32-bit `image_store` (with or +without the integer-coordinate `unorm` modifier) when all four DMASK bits are +set, coordinates are two full-width VGPRs, data comes from four consecutive +VGPRs and the eight image descriptor words come from an unmodified fixed table +offset. The translator emits `asfloat(uint4(...))` into a `RWTexture2D` +under the lane's EXEC bit and records `uav N tex2d float table P O channels 4` +in the version 2 compute manifest. Pixel-stage 2D `image_store` also accepts +`unorm`. + +The standalone dispatch reuses the source and CPU reference from the +[gfx1013 2D float store fixture](#gfx1013-2d-float-image-stores-and-mip-loads). +Two groups write 16 texels to mip zero of an `R32G32B32A32_FLOAT` UAV while +comparing all 1,344 words across three mips. A second program masks out the +second row. Omitting the store, swapping R/B, swapping RG/BA and dropping the +EXEC guard produce 64, 32, 64 and 32 mismatches respectively. + +```powershell +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -R '^startup_compute_image_store(_warp|_hardware)?$' -V +``` + ### Explicit-LOD 2D gather The startup pixel and compute translators lower gfx1013 `image_gather4_l` on a diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index d57babc3c..430d211db 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1938,7 +1938,7 @@ These are measured on one executable; treat them as hypotheses for others. lane's exec bit, and the manifest becomes version 2 with a `uav tex2d table ` line. The cache-policy bits are accepted. A partial channel mask (a typed store writes all four channels), other dimensions, `d16`, `a16`, `tfe`, - `lwe`, `r128`, `unorm`, `image_store_mip`, a store outside a pixel stage, and a program that loads + `lwe`, `r128`, `image_store_mip`, a store outside a pixel or compute stage, and a program that loads and stores the same image are refused by name. The runtime does not bind UAVs on the translated graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. A hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 diff --git a/tests/startup_compute_image_store_check.py b/tests/startup_compute_image_store_check.py new file mode 100644 index 000000000..e3833dbea --- /dev/null +++ b/tests/startup_compute_image_store_check.py @@ -0,0 +1,153 @@ +"""Check 32-bit float compute image stores (with and without unorm) from the startup translator.""" +import argparse +from pathlib import Path +import struct +import subprocess +import tempfile + +import compute_mimg_float_store_check as fixture +from startup_gfx2hlsl_compute_check import G, TGID_X, TGID_Y, assemble, refused, root_blob, tidig + + +# Reuse #2105's source and CPU reference unchanged. Three constants put the descriptor table at s7. +RSRC2 = (10 << 1) | TGID_X | TGID_Y | tidig(2) +PREFIX, STORE, END = fixture.WORDS[:-12], fixture.WORDS[-12:-4], fixture.WORDS[-4:] +STORE_UNORM = bytes.fromhex('081f20f0080e0600') # image_store v[14:17], v[8:9], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm +MASK = bytes.fromhex('8002a47d') # v_cmpx_eq_u32_e32 0, v1 +LINE = 'w0[uint2(v8, v9)] = asfloat(uint4(v14, v15, v16, v17));' + + +def pipeline(body): + return G.ComputePipeline(PREFIX + body + END, root_blob(3), RSRC2, fixture.GROUP) + + +def controls(llvm_mc): + def encoded(line, hex_words): + words = bytes.fromhex(hex_words) + if llvm_mc: + assert assemble(llvm_mc, line + '\n') == words, line + return words + + if llvm_mc: + assert assemble(llvm_mc, '\n'.join(fixture.LINES) + '\n') == fixture.WORDS + assert assemble(llvm_mc, fixture.STORE + ' unorm\n') == STORE_UNORM + assert assemble(llvm_mc, 'v_cmpx_eq_u32_e32 0, v1\n') == MASK + + pipe = pipeline(STORE) + assert pipe.manifest().splitlines()[-2:] == [ + 'srv 0 tex2d table 1 96', + 'uav 0 tex2d float table 1 64 channels 4', + ] + assert LINE in pipe.hlsl_cs() and 'RWTexture2D w0 : register(u0);' in pipe.hlsl_cs() + # unorm is a no-op on image_store (integer texel coordinates) and emits identical HLSL and manifest. + unorm_pipe = pipeline(STORE_UNORM) + assert unorm_pipe.hlsl_cs() == pipe.hlsl_cs() + assert unorm_pipe.manifest() == pipe.manifest() + assert 'if (exec & 1) ' + LINE in pipeline(MASK + STORE_UNORM).hlsl_cs() + + mods = ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D', 'unorm'] + for data in ('v14', 'v[14:15]', 'v[14:16]', 'v[253:256]'): + refused('four VGPRs expected', lambda: pipe.cs.op_image_store([data, 'v[8:9]', 's[24:31]'], mods)) + refused('fixed table image descriptor', + lambda: pipe.cs.op_image_store(['v[14:17]', 'v[8:9]', 's[28:35]'], mods)) + + for asm, code, reason in ( + (fixture.STORE.replace('v[14:17]', 'v[14:15]').replace('dmask:0xf', 'dmask:0x3'), + '080320f0080e0600', 'typed UAV store writes all four channels'), + (fixture.STORE.replace('v[8:9]', 'v8') + ' a16', '080f20f0080e0640', 'modifier a16'), + (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), + '100f20f0080e0600', 'only 2D images'), + ): + instruction = encoded(asm, code) + refused(reason, lambda: pipeline(instruction)) + + wait = encoded('s_waitcnt lgkmcnt(0)', '7fc08cbf') + changed = encoded('s_mov_b32 s26, 0', '80039abe') + refused('modified image descriptor', lambda: pipeline(changed + STORE)) + duplicate = encoded('s_load_dwordx8 s[40:47], s[12:13], 0x40', '060a0cf4400000fa') + changed_alias = encoded('s_or_b32 s46, s46, 0x40000', '2eff2e8800000400') + refused('modified image descriptor', lambda: pipeline(duplicate + wait + changed_alias + STORE)) + + raw = encoded('buffer_store_dword v14, v0, s[32:35], 0 offen', '001070e0000e0880') + read = encoded('buffer_load_dword v5, v0, s[32:35], 0 offen', '001030e000050880') + for offset in (64, 128): + load = encoded(f's_load_dwordx4 s[32:35], s[12:13], {offset}', f'060808f4{offset:02x}0000fa') + for body in (raw + STORE, STORE + raw): + if offset == 64: + refused('used as', lambda: pipeline(load + wait + body)) + continue + mixed = pipeline(load + wait + body) + raw_slot, image_slot = (0, 1) if body.startswith(raw) else (1, 0) + assert f'uav {raw_slot} table 1 128' in mixed.manifest().splitlines() + assert f'uav {image_slot} tex2d float table 1 64 channels 4' in mixed.manifest().splitlines() + assert f'RWByteAddressBuffer u{raw_slot} : register(u{raw_slot});' in mixed.hlsl_cs() + assert f'RWTexture2D w{image_slot} : register(u{image_slot});' in mixed.hlsl_cs() + if offset == 64: + for body in (read + STORE, STORE + read): + refused('used for a load and a store', lambda: pipeline(load + wait + body)) + print('Compute 32-bit float image_store, unorm, EXEC, raw/texture binding order, alias and refusal checks passed') + + +def draw_cases(directory, compiler, renderer, adapter, payload, cases): + hlsl, cso, case = (directory / f'image.{ext}' for ext in ('hlsl', 'cso', 'case')) + case.write_bytes(struct.pack(f'<2I{len(payload)}I', fixture.GROUPS | fixture.FLOAT_TEXTURE_FLAG, 0, *payload)) + for name, source, expected_mismatches, needle in cases: + hlsl.write_text(source, encoding='ascii') + subprocess.run([compiler, '-T', 'cs_6_0', '-E', 'main', '-Fo', cso, hlsl], check=True) + result = subprocess.run([renderer, adapter, '--compute-texture-store-case', cso, case], + capture_output=True, text=True, timeout=15) + print(f'{name}:\n{result.stdout}{result.stderr}', end='', flush=True) + if result.returncode == 77: + return 77 + if 'debug_layer=enabled' in result.stdout: + assert 'debug_errors=0 debug_warnings=0' in result.stdout, name + assert f'compared_words=1344 mismatches={expected_mismatches}' in result.stdout, name + if expected_mismatches == 0: + assert result.returncode == 0, name + else: + assert result.returncode == 1 and needle in result.stderr, name + return 0 + + +def dispatch(directory, compiler, renderer, adapter): + source = pipeline(STORE_UNORM).hlsl_cs() + assert source.count(LINE) == 1 + cases = ( + ('full EXEC (unorm)', source, 0, None), + ('omit store', source.replace(LINE, ''), 64, 'mip=0 word=0 expected=3f100000 actual=bf000000'), + ('swap R/B channels', + source.replace('uint4(v14, v15, v16, v17)', 'uint4(v15, v14, v16, v17)'), + 32, 'mip=0 word=0 expected=3f100000 actual=3f100004'), + ('swap RG/BA pairs', + source.replace('uint4(v14, v15, v16, v17)', 'uint4(v16, v17, v14, v15)'), + 64, 'mip=0 word=0 expected=3f100000 actual=40810000'), + ) + payload = fixture.reference() + if draw_cases(directory, compiler, renderer, adapter, payload, cases) == 77: + return 77 + # v1 is the local Y. Only row zero of the two dispatched rows may change. + words_per_image = len(payload) // 3 + row = 32 * 4 + payload[words_per_image + row:words_per_image + 2 * row] = payload[row:2 * row] + masked = pipeline(MASK + STORE_UNORM).hlsl_cs() + guard = 'if (exec & 1) ' + LINE + assert masked.count(guard) == 1 + cases = ( + ('partial EXEC', masked, 0, None), + ('drop EXEC guard', masked.replace(guard, LINE), 32, 'mip=0 word=128 expected=bf001000 actual=3f101000'), + ) + return draw_cases(directory, compiler, renderer, adapter, payload, cases) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument('--llvm-mc') + mode.add_argument('--dispatch', nargs=3, metavar=('DXC', 'RENDERER', 'ADAPTER')) + args = parser.parse_args() + if args.dispatch: + out = Path(__file__).resolve().parents[1] / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + raise SystemExit(dispatch(Path(tmp), *args.dispatch)) + controls(args.llvm_mc) diff --git a/tests/startup_compute_image_store_d16_check.py b/tests/startup_compute_image_store_d16_check.py index 279220dd6..a16a78d0c 100644 --- a/tests/startup_compute_image_store_d16_check.py +++ b/tests/startup_compute_image_store_d16_check.py @@ -46,7 +46,6 @@ def encoded(line, hex_words): (fixture.STORE.replace('v[8:9]', 'v8').replace(' d16', ' a16 d16'), '080f20f0080e06c0', 'modifier a16'), (fixture.STORE.replace('v[8:9]', 'v[8:10]').replace('IMG_2D', 'IMG_3D'), '100f20f0080e0680', 'only 2D images'), - (fixture.STORE.replace('v[14:15]', 'v[14:17]').removesuffix(' d16'), '080f20f0080e0600', 'requires d16'), ): instruction = encoded(asm, code) refused(reason, lambda: pipeline(instruction)) diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 89b31d07d..7c1c0c4ac 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -99,17 +99,17 @@ def controls(): assert manifest.startswith('x2w-manifest 2\n'), manifest print('store: %s manifest uav 0 tex2d table 0 0' % STORE_LINE) - # Cache-policy bits do not change the written texel. - for name, store in (('glc', patched(1, 0x20)), ('slc', patched(3, 0x02)), ('dlc', patched(0, 0x80))): + # Cache-policy bits and unorm (integer texel coordinates) do not change the written texel. + for name, store in (('glc', patched(1, 0x20)), ('slc', patched(3, 0x02)), + ('dlc', patched(0, 0x80)), ('unorm', patched(1, 0x10))): assert D.decode_instruction(store, 0)[2].endswith(' ' + name), D.decode_instruction(store, 0) assert STORE_LINE in translate(with_store(store)).hlsl_ps(), name - print('glc, slc and dlc accepted') + print('glc, slc, dlc and unorm accepted') - # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, unorm, + # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, # a partial channel mask and other image dimensions. cases = (('d16', patched(7, 0x80)), ('a16', patched(7, 0x40)), ('tfe', patched(2, 0x01)), ('lwe', patched(2, 0x02)), ('r128', patched(1, 0x80)), ('reserved', patched(1, 0x40)), - ('unorm', patched(1, 0x10)), ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), ('SQ_RSRC_IMG_2D_ARRAY', bytes.fromhex('280f20f000040400')), ('SQ_RSRC_IMG_1D', bytes.fromhex('000f20f000040400'))) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 49fb8304c..6957344fd 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4285,17 +4285,16 @@ def op_image_store(self, ops, mods): hardware drops them for lanes outside exec. """ name = 'image_store' - d16 = self.kind == 'cs' and mods.count('d16') == 1 - if self.kind == 'cs' and not d16: - raise Unsupported('compute image_store requires d16') - if not d16 and self.kind != 'ps': + if self.kind not in ('ps', 'cs'): raise Unsupported('%s outside a pixel stage' % name) + d16 = self.kind == 'cs' and mods.count('d16') == 1 if len(ops) != 3: raise Unsupported('%s with %d operands' % (name, len(ops))) for m in mods: if d16 and m == 'd16': continue - if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + # IMAGE_STORE always uses integer texel coordinates, so unorm is a no-op like on image_load. + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc', 'unorm')): raise Unsupported('%s modifier %s' % (name, m)) dims = [m[4:] for m in mods if m.startswith('dim:')] masks = [m[6:] for m in mods if m.startswith('dmask:')] @@ -4322,15 +4321,17 @@ def op_image_store(self, ops, mods): if len(cs) != 2: raise Unsupported('%s with %d address registers: x and y expected' % (name, len(cs))) words = [self.u('v%d' % n) for n in range(data[1], data[2] + 1)] - if d16: + if self.kind == 'cs': if not all(re.fullmatch(r'v\d+', c) and int(c[1:]) <= 255 for c in cs): raise Unsupported('compute image_store requires full-width VGPR coordinates') key = self.fixed_table_image(ops[2], name) + else: + key = self.descriptor(ops[2]) + if d16: # RDNA 2 ISA §8.2.5: RG occupy VDATA, BA occupy VDATA+1, low half first. rgba = ['f16tof32(%s & 0xffffu), f16tof32(%s >> 16)' % (word, word) for word in words] value = 'float4(%s)' % ', '.join(rgba) else: - key = self.descriptor(ops[2]) value = 'asfloat(uint4(%s))' % ', '.join(words) image = self.pipe.uav(key, 'tex2d') body = '%s[uint2(%s, %s)] = %s;' % (image, self.u(cs[0]), self.u(cs[1]), value) From 264cc6f10792d9faa6e321b75c58f86c17453fe2 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:46:30 +0200 Subject: [PATCH 161/232] runtime: extract main(argv), bounds validation, and struct.error guards in resource_root with CLI suite (#2543) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/resource_root_cli_check.py | 522 +++++++++++++++++++++++++++++++ tools/resource_root.py | 18 +- 3 files changed, 538 insertions(+), 4 deletions(-) create mode 100644 tests/resource_root_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d18a86b8..8f1f43f9c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8496,6 +8496,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/script_state_check.py") add_test(NAME resource_relocated_root COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/resource_root_check.py") + add_test(NAME runtime_resource_root_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/resource_root_cli_check.py") add_test(NAME pe_authentihash COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_authentihash_check.py") add_test(NAME pe_authentihash_oracle COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/resource_root_cli_check.py b/tests/resource_root_cli_check.py new file mode 100644 index 000000000..a7fcdae26 --- /dev/null +++ b/tests/resource_root_cli_check.py @@ -0,0 +1,522 @@ +"""CLI, bounds-validation, error-guard, and mutation control suite for tools/resource_root.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import re +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "resource_root.py" +sys.path.insert(0, str(ROOT / "tools")) + +import resource_root # noqa: E402 + +BASE = 0x50000000 +ROOT_TYPE = 0x1234ABCD +ALT_TYPE = 0x00008888 +TWO_MIB = 2 << 20 + + +def _build_prd0( + total_size: int = 400, + *, + root_index: int = 2, + root_type: int = ROOT_TYPE, + root_bytes: int = 32, + alt_type: int = ALT_TYPE, + alt_bytes: int = 16, +) -> bytearray: + """Build a synthetic relocated PRD0 v0x7a resource buffer.""" + data = bytearray(total_size) + struct.pack_into(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = resource_root.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class ResourceRootCliPositiveTests(unittest.TestCase): + def _assert_json_schema(self, stdout_text: str, expected_hash: str, expected_bytes: int) -> None: + payload = json.loads(stdout_text) + self.assertEqual(set(payload), {"root_type_hash", "root_bytes"}) + self.assertRegex(payload["root_type_hash"], r"^0x[0-9a-f]{8}$") + self.assertIs(type(payload["root_bytes"]), int) + self.assertEqual(payload, {"root_type_hash": expected_hash, "root_bytes": expected_bytes}) + + def test_zero_and_nonzero_decimal_and_hex_arguments_return_zero_and_exact_json(self) -> None: + primary = bytes(_build_prd0(root_index=2)) + primary_packed = zlib.compress(primary) + alternate = bytes(_build_prd0(root_index=1)) + alternate_packed = zlib.compress(alternate) + + cases = ( + ( + "zero_offset_decimal", + b"", + primary_packed, + b"", + "0", + str(len(primary_packed)), + str(len(primary)), + "0x1234abcd", + 32, + ), + ( + "nonzero_decimal_offset_hex_sizes", + b"PREFIX_13BYTE", + alternate_packed, + b"SUFFIX", + "13", + hex(len(alternate_packed)), + hex(len(alternate)), + "0x00008888", + 16, + ), + ( + "hex_offset_decimal_stored_hex_decoded", + b"A" * 0x20, + primary_packed, + b"TAIL", + "0x20", + str(len(primary_packed)), + hex(len(primary)), + "0x1234abcd", + 32, + ), + ) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + for label, prefix, packed, suffix, offset_arg, stored_arg, decoded_arg, exp_hash, exp_bytes in cases: + with self.subTest(label=label): + archive = root / f"{label}.bin" + archive.write_bytes(prefix + packed + suffix) + argv = [ + str(archive), + "--offset", + offset_arg, + "--stored", + stored_arg, + "--decoded", + decoded_arg, + ] + + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self._assert_json_schema(out, exp_hash, exp_bytes) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self._assert_json_schema(proc.stdout, exp_hash, exp_bytes) + + def test_exact_two_mib_decoded_boundary_succeeds(self) -> None: + decoded = bytes(_build_prd0(total_size=TWO_MIB)) + packed = zlib.compress(decoded) + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "exact_2mib.bin" + archive.write_bytes(b"PAD" + packed) + for decoded_arg in (str(TWO_MIB), hex(TWO_MIB)): + with self.subTest(decoded_arg=decoded_arg): + argv = [ + str(archive), + "--offset", + "3", + "--stored", + str(len(packed)), + "--decoded", + decoded_arg, + ] + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self._assert_json_schema(out, "0x1234abcd", 32) + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self._assert_json_schema(proc.stdout, "0x1234abcd", 32) + + def test_main_forwards_default_sys_argv_and_script_entrypoint_returns_zero(self) -> None: + decoded = bytes(_build_prd0(root_index=2)) + packed = zlib.compress(decoded) + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "entry.bin" + archive.write_bytes(b"HEAD" + packed) + cli_argv = [ + str(TOOL), + str(archive), + "--offset", + "0x4", + "--stored", + str(len(packed)), + "--decoded", + str(len(decoded)), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self._assert_json_schema(out, "0x1234abcd", 32) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self._assert_json_schema(stdout.getvalue(), "0x1234abcd", 32) + + +class ResourceRootCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected non-empty stderr for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected non-empty subprocess stderr for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + + def test_missing_and_directory_archives_rejected_cleanly(self) -> None: + # Kills removal of OSError from except and removal of args.archive.is_dir() guard. + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.bin" + self._assert_clean_failure( + [str(missing), "--offset", "0", "--stored", "16", "--decoded", "400"], + expected_fragments=(f"{missing}: ",), + ) + + dir_archive = root / "archive_dir" + dir_archive.mkdir() + argv = [str(dir_archive), "--offset", "0", "--stored", "16", "--decoded", "400"] + with mock.patch.object(resource_root, "read_member") as read_mock: + self._assert_clean_failure( + argv, + expected_fragments=(f"{dir_archive}: ", "Archive path is a directory"), + check_subprocess=False, + ) + read_mock.assert_not_called() + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(f"{dir_archive}: ", proc.stderr) + self.assertIn("Archive path is a directory", proc.stderr) + + def test_negative_offset_rejected_before_opening_archive(self) -> None: + # Testing existing + missing archives kills removal/reordering of args.offset < 0. + decoded = bytes(_build_prd0()) + packed = zlib.compress(decoded) + with TemporaryDirectory() as tmp: + root = Path(tmp) + existing = root / "existing.bin" + existing.write_bytes(packed) + missing = root / "missing.bin" + for archive in (existing, missing): + for offset_args in (["--offset", "-1"], ["--offset=-0x10"]): + with self.subTest(archive=archive.name, offset_args=offset_args): + argv = [ + str(archive), + *offset_args, + "--stored", + str(len(packed)), + "--decoded", + str(len(decoded)), + ] + with mock.patch.object(resource_root, "read_member") as read_mock: + self._assert_clean_failure( + argv, + expected_fragments=(f"{archive}: ", "--offset", "non-negative"), + check_subprocess=False, + ) + read_mock.assert_not_called() + + proc = _run_subprocess( + str(missing), + "--offset", + "-1", + "--stored", + str(len(packed)), + "--decoded", + str(len(decoded)), + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(f"{missing}: ", proc.stderr) + self.assertIn("--offset", proc.stderr) + + def test_non_positive_stored_and_decoded_rejected_before_opening_archive(self) -> None: + # Testing 0 and negative values on existing + missing archives kills <= 0 -> < 0 and removal/reordering. + decoded = bytes(_build_prd0()) + packed = zlib.compress(decoded) + with TemporaryDirectory() as tmp: + root = Path(tmp) + existing = root / "existing.bin" + existing.write_bytes(packed) + missing = root / "missing.bin" + for archive in (existing, missing): + for stored_args in (["--stored", "0"], ["--stored", "-1"], ["--stored=-0x10"]): + with self.subTest(archive=archive.name, stored_args=stored_args): + argv = [ + str(archive), + "--offset", + "0", + *stored_args, + "--decoded", + str(len(decoded)), + ] + with mock.patch.object(resource_root, "read_member") as read_mock: + self._assert_clean_failure( + argv, + expected_fragments=(f"{archive}: ", "--stored", "positive"), + check_subprocess=False, + ) + read_mock.assert_not_called() + + for decoded_args in (["--decoded", "0"], ["--decoded", "-1"], ["--decoded=-0x10"]): + with self.subTest(archive=archive.name, decoded_args=decoded_args): + argv = [ + str(archive), + "--offset", + "0", + "--stored", + str(len(packed)), + *decoded_args, + ] + with mock.patch.object(resource_root, "read_member") as read_mock: + self._assert_clean_failure( + argv, + expected_fragments=(f"{archive}: ", "--decoded", "positive"), + check_subprocess=False, + ) + read_mock.assert_not_called() + + for flag in ("--stored", "--decoded"): + proc = _run_subprocess( + str(missing), + "--offset", + "0", + "--stored", + "0" if flag == "--stored" else str(len(packed)), + "--decoded", + "0" if flag == "--decoded" else str(len(decoded)), + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(f"{missing}: ", proc.stderr) + self.assertIn(flag, proc.stderr) + + def test_over_budget_stored_and_decoded_rejected(self) -> None: + decoded = bytes(_build_prd0()) + packed = zlib.compress(decoded) + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "budget.bin" + archive.write_bytes(packed) + for stored_val, decoded_val in ((TWO_MIB + 1, len(decoded)), (len(packed), TWO_MIB + 1)): + with self.subTest(stored=stored_val, decoded=decoded_val): + self._assert_clean_failure( + [ + str(archive), + "--offset", + "0", + "--stored", + str(stored_val), + "--decoded", + str(decoded_val), + ], + expected_fragments=(f"{archive}: ", "2 MiB", "budget"), + ) + + def test_corrupt_zlib_and_zlib_error_guard(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + corrupt = root / "corrupt_zlib.bin" + payload = b"not-a-valid-zlib-stream-at-all!" + corrupt.write_bytes(payload) + self._assert_clean_failure( + [str(corrupt), "--offset", "0", "--stored", str(len(payload)), "--decoded", "400"], + expected_fragments=(f"{corrupt}: ", "Invalid compressed segment"), + ) + + # Kills removal of zlib.error from except (OSError, ValueError, struct.error, zlib.error). + valid_decoded = bytes(_build_prd0()) + valid_packed = zlib.compress(valid_decoded) + valid = root / "valid.bin" + valid.write_bytes(valid_packed) + with mock.patch.object( + resource_root, + "read_member", + side_effect=zlib.error("Error -3 while decompressing data: incorrect header check"), + ): + self._assert_clean_failure( + [ + str(valid), + "--offset", + "0", + "--stored", + str(len(valid_packed)), + "--decoded", + str(len(valid_decoded)), + ], + expected_fragments=(f"{valid}: ", "Error -3 while decompressing data"), + check_subprocess=False, + ) + + def test_truncated_and_malformed_prd0_and_struct_error_guard(self) -> None: + def patch_prd0(offset: int, fmt: str, value: int | bytes) -> bytes: + buf = _build_prd0() + struct.pack_into(fmt, buf, offset, value) + return bytes(buf) + + bad_prd0_cases = ( + ("truncated_header", b"\x00" * 64, "PRD0 v0x7a"), + ("bad_magic", patch_prd0(16, "<4s", b"BAD!"), "PRD0 v0x7a"), + ("bad_version", patch_prd0(20, " None: + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "dummy.bin" + archive.write_bytes(b"x") + + for missing_argv in ( + [str(archive)], + [str(archive), "--offset", "0", "--stored", "1"], + [str(archive), "--offset", "0", "--decoded", "1"], + [str(archive), "--stored", "1", "--decoded", "1"], + ): + with self.subTest(missing_argv=missing_argv): + self._assert_clean_failure(missing_argv, expected_code=2) + + for flag in ("--offset", "--stored", "--decoded"): + with self.subTest(invalid_flag=flag): + argv = [ + str(archive), + "--offset", + "not_an_int" if flag == "--offset" else "0", + "--stored", + "1.5" if flag == "--stored" else "1", + "--decoded", + "xyz" if flag == "--decoded" else "1", + ] + self._assert_clean_failure( + argv, + expected_code=2, + expected_fragments=(flag,), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/resource_root.py b/tools/resource_root.py index cb4941aea..bd5926ee7 100644 --- a/tools/resource_root.py +++ b/tools/resource_root.py @@ -1,5 +1,6 @@ """Check the root instance of a relocated PRD0 v0x7a resource in one zlib member.""" import argparse +from collections.abc import Sequence import json from pathlib import Path import struct @@ -56,20 +57,29 @@ def integer(text: str) -> int: return int(text, 0) -def main() -> None: +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--offset", type=integer, required=True, help="Byte offset of the zlib member") parser.add_argument("--stored", type=integer, required=True, help="Exact compressed size in bytes") parser.add_argument("--decoded", type=integer, required=True, help="Exact uncompressed size in bytes") - args = parser.parse_args() + args = parser.parse_args(argv) try: + if args.offset < 0: + raise ValueError(f"Expected non-negative --offset, got {args.offset}") + if args.stored <= 0: + raise ValueError(f"Expected positive --stored, got {args.stored}") + if args.decoded <= 0: + raise ValueError(f"Expected positive --decoded, got {args.decoded}") + if args.archive.is_dir(): + raise ValueError(f"Archive path is a directory: {args.archive}") with args.archive.open("rb") as stream: kind, size = read_member(stream, args.offset, args.stored, args.decoded) - except (OSError, ValueError, zlib.error) as error: + except (OSError, ValueError, struct.error, zlib.error) as error: parser.exit(1, f"{args.archive}: {error}\n") print(json.dumps({"root_type_hash": f"0x{kind:08x}", "root_bytes": size})) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 4a8acf51014b87d556fcba74c1433228c600bfcc Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:47:46 -0700 Subject: [PATCH 162/232] d3d12: support unplaced buffer memory SRVs in device slot 70 (#2395) * d3d12: support unplaced buffer memory SRVs in device slot 70 Device slot 70 resolves buffer memory SRVs when the requested buffer was placed via slot 133 or committed via slot 127. When no placed buffer wrapper exists at the address (e.g. dynamic or sub-allocated buffers in title memory heaps), calls previously failed with buffer_unavailable. Add unplaced buffer memory SRV backing: - unplaced_buffer_extent calculates 64 KiB page-aligned extents and spans with overflow guards and a 256 MiB sanity limit. - unplaced_memory_buffer validates committed coverage via measure_placed_buffer and checks placed_buffer_range for conflicting placed aliases. - Uses OpenExistingHeapFromAddress to create zero-copy placed resource aliases when D3D12_FEATURE_EXISTING_HEAPS is supported for MEM_PRIVATE memory, and falls back to committed UPLOAD buffers on WARP or unsupported adapters with host synchronization. - Caches entries per device matching the base allocation, re-verifying committed status to handle memory deallocation/reallocation. - Cleans up cached unplaced buffers when the device wrapper is released. - Adds unplaced-extent and unplaced-covers negative controls to startup_memory_srv_buffer_check and verifies unplaced buffer drawing in startup_address_buffer_srv_{warp,hardware}. # Conflicts: # CMakeLists.txt * d3d12: reject unplaced buffer memory SRVs overlapping live resources --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 8 +- docs/startup-runtime.md | 21 ++- src/startup_stubs/d3d12_memory_srv.inl | 182 ++++++++++++++++++++++ src/startup_stubs/d3d12_xs_device.cpp | 3 + src/startup_stubs/memory_srv_buffer.h | 26 ++++ tests/startup_address_buffer_srv_check.py | 2 +- tests/startup_address_srv.cpp | 11 +- tests/startup_memory_srv_buffer_check.cpp | 41 ++++- 8 files changed, 275 insertions(+), 19 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f1f43f9c..f5cb679dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1877,6 +1877,10 @@ add_executable(startup_memory_srv_buffer_check tests/startup_memory_srv_buffer_c target_include_directories(startup_memory_srv_buffer_check PRIVATE src) target_compile_features(startup_memory_srv_buffer_check PRIVATE cxx_std_17) add_test(NAME startup_memory_srv_buffer COMMAND startup_memory_srv_buffer_check) +foreach(mutation IN ITEMS height exact-fit first-32 unplaced-extent unplaced-covers) + add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) + set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) +endforeach() # Descriptor word 3 for formatted buffer loads (src/startup_stubs/buffer_format_word3.h); the mutated run must fail. add_executable(startup_buffer_format_word3_check tests/startup_buffer_format_word3_check.cpp) target_include_directories(startup_buffer_format_word3_check PRIVATE src) @@ -1884,10 +1888,6 @@ target_compile_features(startup_buffer_format_word3_check PRIVATE cxx_std_17) add_test(NAME startup_buffer_format_word3 COMMAND startup_buffer_format_word3_check) add_test(NAME startup_buffer_format_word3_mapping_control COMMAND startup_buffer_format_word3_check --mutate mapping) set_tests_properties(startup_buffer_format_word3_mapping_control PROPERTIES WILL_FAIL TRUE) -foreach(mutation IN ITEMS height exact-fit first-32) - add_test(NAME startup_memory_srv_buffer_${mutation}_control COMMAND startup_memory_srv_buffer_check --mutate ${mutation}) - set_tests_properties(startup_memory_srv_buffer_${mutation}_control PROPERTIES WILL_FAIL TRUE) -endforeach() # Acceleration-structure memory SRV validation for device slot 70 (src/startup_stubs/memory_srv_as.h); the # mutated runs are negative controls. add_executable(startup_memory_srv_as_check tests/startup_memory_srv_as_check.cpp) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 430d211db..18a7e87e5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2911,9 +2911,17 @@ descriptions with: - `D3D12_SRV_DIMENSION_BUFFER` (raw `R32_TYPELESS`, structured `Format == UNKNOWN` with a stride that is a multiple of 4 up to 2048, or typed buffers). It resolves an existing live placed (slot 133) or committed (slot 127) - buffer covering `[address, address + (FirstElement + NumElements) * element_bytes)`, checks - alignment and bounds, adjusts `FirstElement` by `(address - base) / element_bytes`, and forwards - to `CreateShaderResourceView` (slot 18). + buffer covering `[address, address + (FirstElement + NumElements) * element_bytes)`. When no live + buffer exists at the address, `unplaced_memory_buffer` backs the unplaced range: it calculates a + 64 KiB page-aligned extent via `unplaced_buffer_extent`, verifies committed pages through + `measure_placed_buffer`, and avoids placed alias conflicts (`placed_buffer_range`). It reuses + cached unplaced buffers per device matching the base allocation when `unplaced_buffer_covers` is true, + re-checking committed status to handle title memory deallocation/reallocation. On adapters supporting + `D3D12_FEATURE_EXISTING_HEAPS` for `MEM_PRIVATE` memory, it opens the existing heap and creates a + zero-copy placed resource alias; otherwise (or on WARP), it falls back to a committed upload buffer and + synchronizes memory from the host. When the device wrapper is released (`refs == 0`), + `clear_unplaced_buffers` safely cleans up cached entries. Once resolved, it checks alignment and bounds, + adjusts `FirstElement` by `(address - base) / element_bytes`, and forwards to `CreateShaderResourceView` (slot 18). Acceleration-structure views (`D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE`, `src/startup_stubs/memory_srv_as.h`) take their address from the view's `Location`, or from the call's @@ -2939,9 +2947,10 @@ Checks: `startup_memory_srv_buffer` is device-free and owns every rejection (bounds, alignment, format, stride). It changes each buffer description and view field alone, checks the element bytes of every typed format, views that end exactly at the end of the buffer, raw alignment of the adjusted first -element, and widths, addresses and first elements above 4 GiB. Its `_control` runs (`height`, -`exact-fit`, `first-32`) expect wrong answers and must fail. `startup_address_buffer_srv_*` exercises -only the resolve path with valid addresses on a device, so it does not cover the rejections. +element, widths, addresses and first elements above 4 GiB, page extent calculation, and cache range +coverage. Its `_control` runs (`height`, `exact-fit`, `first-32`, `unplaced-extent`, `unplaced-covers`) +expect wrong answers and must fail. `startup_address_buffer_srv_*` exercises placed and unplaced buffer +views with valid addresses on a device (WARP and hardware), and verifies the refusal lines. `startup_memory_srv_volume` is device-free and validates volume (Texture3D) memory SRVs in device slot 70 (`supports_volume_memory_srv`, `address_view_fits`, `volume_texture_bytes`). diff --git a/src/startup_stubs/d3d12_memory_srv.inl b/src/startup_stubs/d3d12_memory_srv.inl index b441d4401..673084c38 100644 --- a/src/startup_stubs/d3d12_memory_srv.inl +++ b/src/startup_stubs/d3d12_memory_srv.inl @@ -257,6 +257,185 @@ Wrapper* existing_memory_buffer(Wrapper* device, u64 address, u64 bytes) return match; } +// Backing for unplaced buffer memory SRVs: 64 KiB page-aligned placed resource on an existing heap +// (OpenExistingHeapFromAddress zero-copy aliasing on hardware) or committed UPLOAD buffer (fallback). +struct UnplacedBufferEntry { + Wrapper* device = nullptr; + void* allocation_base = nullptr; + u64 page_start = 0; + u64 page_span = 0; + bool is_upload = false; + x2w_startup::ComPtr resource; + Wrapper* wrapper = nullptr; +}; + +std::mutex unplaced_buffer_mutex; +std::vector unplaced_buffers; + +void clear_unplaced_buffers(Wrapper* device) +{ + std::lock_guard lock(unplaced_buffer_mutex); + for (auto it = unplaced_buffers.begin(); it != unplaced_buffers.end();) { + if (it->device == device) { + if (it->wrapper) { + retire_placement(it->wrapper); + if (it->wrapper->own().budget) it->wrapper->own().budget->end_use(); + if (it->wrapper->own().backing_budget) it->wrapper->own().backing_budget->end_use(); + it->wrapper->own().real = nullptr; + InterlockedDecrement(&it->wrapper->own().refs); + } + it->resource.Reset(); + it = unplaced_buffers.erase(it); + } else { + ++it; + } + } +} + +Wrapper* unplaced_memory_buffer(Wrapper* device, u64 address, u64 span_bytes, const D3D12_RESOURCE_DESC& requested_desc) +{ + if (address_resource_overlap(address, span_bytes)) return nullptr; + u64 page_start = 0, page_span = 0; + if (!x2w_startup::unplaced_buffer_extent(address, span_bytes, page_start, page_span)) + return nullptr; + + x2w_startup::PlacedBufferRange memory{}; + if (!x2w_startup::measure_placed_buffer(reinterpret_cast(page_start), page_span, memory) || + !memory.covered) + return nullptr; + + const auto nearby = placed_buffer_range(device, page_start, page_span, true); + if (nearby.reject || nearby.owner) return nullptr; + + auto* desktop = device_of(device); + if (!desktop) return nullptr; + + std::lock_guard lock(unplaced_buffer_mutex); + for (auto& entry : unplaced_buffers) { + if (entry.device == device && entry.allocation_base == memory.base && + x2w_startup::unplaced_buffer_covers(entry.page_start, entry.page_span, address, span_bytes)) { + x2w_startup::PlacedBufferRange verify{}; + if (!x2w_startup::measure_placed_buffer(reinterpret_cast(entry.page_start), entry.page_span, verify) || + !verify.covered || verify.base != memory.base) { + continue; + } + if (entry.is_upload && entry.resource) { + void* mapped = nullptr; + D3D12_RANGE read_range{0, 0}; + if (SUCCEEDED(entry.resource->Map(0, &read_range, &mapped))) { + std::memcpy(mapped, reinterpret_cast(entry.page_start), static_cast(entry.page_span)); + entry.resource->Unmap(0, nullptr); + } + } + return entry.wrapper; + } + } + + x2w_startup::ComPtr native_resource; + bool is_upload = false; + ID3D12Heap* heap = nullptr; + x2w_budget::Ticket* backing_budget = nullptr; + + D3D12_FEATURE_DATA_EXISTING_HEAPS existing_support{}; + const bool existing_heaps_supported = + SUCCEEDED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &existing_support, sizeof(existing_support))) && + existing_support.Supported; + + if (existing_heaps_supported && memory.type == MEM_PRIVATE) { + std::lock_guard placed_lock(placed_mutex); + for (const auto& [known, h] : existing_heaps) { + if (known == memory.base) { + heap = h.real; + backing_budget = h.budget; + break; + } + } + if (!heap) { + ID3D12Device3* device3 = nullptr; + if (SUCCEEDED(desktop->QueryInterface(IID_PPV_ARGS(&device3)))) { + if (SUCCEEDED(device3->OpenExistingHeapFromAddress(memory.base, IID_PPV_ARGS(&heap)))) { + backing_budget = x2w_budget::backing_heap(heap, 0); + existing_heaps.emplace_back(memory.base, ExistingHeap{heap, backing_budget}); + } + device3->Release(); + } + } + if (heap) { + const u64 base_u64 = reinterpret_cast(memory.base); + const u64 heap_offset = page_start - base_u64; + const u64 heap_size = heap->GetDesc().SizeInBytes; + if (heap_offset <= heap_size && page_span <= heap_size - heap_offset) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = page_span; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + + desktop->CreatePlacedResource(heap, heap_offset, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&native_resource)); + } + } + } + + if (!native_resource) { + D3D12_HEAP_PROPERTIES props{D3D12_HEAP_TYPE_UPLOAD}; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = page_span; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + + if (SUCCEEDED(desktop->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&native_resource)))) { + is_upload = true; + void* mapped = nullptr; + D3D12_RANGE read_range{0, 0}; + if (SUCCEEDED(native_resource->Map(0, &read_range, &mapped))) { + std::memcpy(mapped, reinterpret_cast(page_start), static_cast(page_span)); + native_resource->Unmap(0, nullptr); + } + } + } + + if (!native_resource) return nullptr; + + Wrapper* w = wrap(native_resource.Get(), resource_kind); + w->own().title_memory = reinterpret_cast(page_start); + D3D12_RESOURCE_DESC rdesc{}; + rdesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rdesc.Width = page_span; + rdesc.Height = 1; + rdesc.DepthOrArraySize = 1; + rdesc.MipLevels = 1; + rdesc.Format = DXGI_FORMAT_UNKNOWN; + rdesc.SampleDesc.Count = 1; + rdesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + rdesc.Flags = is_upload ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; + + note_resource(w, &rdesc, page_span); + if (!is_upload) { + w->own().budget = x2w_budget::resource(desktop, native_resource.Get(), x2w_budget::placed); + w->own().backing_budget = backing_budget; + if (backing_budget) backing_budget->begin_use(); + } else { + w->own().budget = x2w_budget::committed(desktop, native_resource.Get(), D3D12_HEAP_TYPE_UPLOAD); + } + + unplaced_buffers.push_back(UnplacedBufferEntry{device, memory.base, page_start, page_span, is_upload, native_resource, w}); + return w; +} + // Keep metadata for published tiled SRVs; allocate GPU memory only when a // translated draw actually samples one. A later write to the same address is // picked up by the uploader even when the description and view token are reused. @@ -519,6 +698,9 @@ void __stdcall device_memory_srv(Wrapper* self, const D3D12_RESOURCE_DESC* resou const u64 elem_bytes = x2w_startup::buffer_srv_element_bytes(input->view); const u64 span_bytes = (input->view.Buffer.FirstElement + input->view.Buffer.NumElements) * elem_bytes; Wrapper* buffer = existing_memory_buffer(self, input->address, span_bytes); + if (!buffer) { + buffer = unplaced_memory_buffer(self, input->address, span_bytes, *resource); + } const ResourceInfo* info = buffer ? resource_info(buffer) : nullptr; D3D12_SHADER_RESOURCE_VIEW_DESC adjusted{}; if (!buffer || !info || diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0c2a5caae..d67871bf2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -943,6 +943,7 @@ void retire_note_submission(ID3D12CommandQueue* queue, const std::vectorown().refs); @@ -960,6 +961,8 @@ ULONG __stdcall release(Wrapper* self) retire_drop_recording(self); } if (self->own().retire_when_idle) retire_resource(self); + if (self->own().kind == device_kind) + clear_unplaced_buffers(self); } return static_cast(refs); } diff --git a/src/startup_stubs/memory_srv_buffer.h b/src/startup_stubs/memory_srv_buffer.h index 331edcf8e..4031efe12 100644 --- a/src/startup_stubs/memory_srv_buffer.h +++ b/src/startup_stubs/memory_srv_buffer.h @@ -127,4 +127,30 @@ inline bool resolve_buffer_srv_desc(std::uint64_t buffer_title_base, std::uint64 return true; } +// Calculates 64 KiB page-aligned extent and byte span for unplaced buffer memory SRVs. +// Returns false on zero address/bytes, arithmetic overflow, or when the span exceeds the maximum allowable limit (256 MiB). +inline bool unplaced_buffer_extent(std::uint64_t address, std::uint64_t span_bytes, + std::uint64_t& page_start, std::uint64_t& page_span) +{ + constexpr std::uint64_t alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; + constexpr std::uint64_t mask = alignment - 1; + constexpr std::uint64_t max_span = 256ull << 20; + if (!address || !span_bytes || span_bytes > ~std::uint64_t{0} - address) return false; + page_start = address & ~mask; + const std::uint64_t end = address + span_bytes; + if (end > ~std::uint64_t{0} - mask) return false; + const std::uint64_t page_end = (end + mask) & ~mask; + page_span = page_end - page_start; + return page_span <= max_span && page_span >= span_bytes; +} + +// Checks whether an existing cached page range completely covers the requested [address, address + span_bytes). +inline bool unplaced_buffer_covers(std::uint64_t cached_start, std::uint64_t cached_span, + std::uint64_t address, std::uint64_t span_bytes) +{ + if (!cached_span || !span_bytes || address < cached_start) return false; + const std::uint64_t offset = address - cached_start; + return offset <= cached_span && span_bytes <= cached_span - offset; +} + } // namespace x2w_startup diff --git a/tests/startup_address_buffer_srv_check.py b/tests/startup_address_buffer_srv_check.py index c05bd59f8..44c6304f0 100644 --- a/tests/startup_address_buffer_srv_check.py +++ b/tests/startup_address_buffer_srv_check.py @@ -56,7 +56,7 @@ def check(directory, consumer, backend): if actual != expected: raise AssertionError(f"actual {actual.hex()} expected {expected.hex()}") check_refusal_lines(trap_log.read_text(errors="replace")) - print(f"{backend}: buffer memory SRV (raw base, raw interior, structured, refused unaligned, refused acceleration structure view) exact") + print(f"{backend}: buffer memory SRV (raw base, raw interior, unplaced buffer, structured, refused unaligned, refused acceleration structure view) exact") return 0 diff --git a/tests/startup_address_srv.cpp b/tests/startup_address_srv.cpp index 2e02f53ce..d2a72fc2d 100644 --- a/tests/startup_address_srv.cpp +++ b/tests/startup_address_srv.cpp @@ -453,9 +453,9 @@ int draw_formatted_view(void* guest, void* list) int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) { static std::array raw_buf0{}; - static std::array raw_buf1{}; + static auto* const buf1 = static_cast( + VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); auto* const buf0 = reinterpret_cast((ptr(raw_buf0.data()) + 0xffff) & ~Word{0xffff}); - auto* const buf1 = reinterpret_cast((ptr(raw_buf1.data()) + 0xffff) & ~Word{0xffff}); std::memset(buf0, 0, 256); std::memset(buf1, 0, 256); buf0[0] = 17; @@ -469,11 +469,10 @@ int draw_address_buffer_srvs(ID3D12Device* desktop, void* guest, void* list) desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - void* placed[2]{}; + void* placed = nullptr; if (FAILED(static_cast(invoke(guest, 133, ptr(buf0), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, - 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[0]))))) return 47; - if (FAILED(static_cast(invoke(guest, 133, ptr(buf1), ptr(&desc), D3D12_RESOURCE_STATE_COMMON, - 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed[1]))))) return 47; + 0, ptr(&__uuidof(ID3D12Resource)), ptr(&placed))))) return 47; + // buf1 is intentionally not placed in slot 133 to verify unplaced buffer backing in device slot 70. Word cpu = 0; if (!bind_view_table(guest, list, cpu)) return 42; diff --git a/tests/startup_memory_srv_buffer_check.cpp b/tests/startup_memory_srv_buffer_check.cpp index df2d3b450..abc4c7005 100644 --- a/tests/startup_memory_srv_buffer_check.cpp +++ b/tests/startup_memory_srv_buffer_check.cpp @@ -3,6 +3,8 @@ // --mutate height: expect a buffer description with Height 2 to be accepted. // --mutate exact-fit: expect a view that ends exactly at the end of the buffer to be refused. // --mutate first-32: expect a resolved FirstElement above 4 Gi elements to be cut to 32 bits. +// --mutate unplaced-extent: expect page span calculation crossing a 64 KiB boundary to return a single page. +// --mutate unplaced-covers: expect a buffer range past the end of the cached page to be accepted as covered. // Each mutated run is a negative control and must fail. #include "startup_stubs/memory_srv_buffer.h" @@ -81,10 +83,11 @@ int main(int argc, char** argv) { if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && (std::strcmp(argv[2], "height") == 0 || std::strcmp(argv[2], "exact-fit") == 0 || - std::strcmp(argv[2], "first-32") == 0)) { + std::strcmp(argv[2], "first-32") == 0 || + std::strcmp(argv[2], "unplaced-extent") == 0 || std::strcmp(argv[2], "unplaced-covers") == 0)) { mutation = argv[2]; } else if (argc != 1) { - std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32]\n"); + std::printf("usage: startup_memory_srv_buffer_check [--mutate height|exact-fit|first-32|unplaced-extent|unplaced-covers]\n"); return 2; } const auto buf = buffer_desc(1024); @@ -264,6 +267,40 @@ int main(int argc, char** argv) typed_view(DXGI_FORMAT_R8_UINT, 0x100000000, 0x10), resolved) && resolved.Buffer.FirstElement == (mutated("first-32") ? 0 : 0x100000000)); + // Unplaced buffer extent calculation and page alignment. + std::uint64_t page_start = 0, page_span = 0; + check("unplaced extent zero address", !x2w_startup::unplaced_buffer_extent(0, 1024, page_start, page_span)); + check("unplaced extent zero span", !x2w_startup::unplaced_buffer_extent(0x10000, 0, page_start, page_span)); + check("unplaced extent 48B aligned", + x2w_startup::unplaced_buffer_extent(0x10000, 48, page_start, page_span) && + page_start == 0x10000 && page_span == 65536); + check("unplaced extent interior 128B", + x2w_startup::unplaced_buffer_extent(0x10800, 128, page_start, page_span) && + page_start == 0x10000 && page_span == 65536); + const std::uint64_t expected_cross_span = mutated("unplaced-extent") ? 65536 : 131072; + check("unplaced extent crossing page", + x2w_startup::unplaced_buffer_extent(0x1fff0, 32, page_start, page_span) && + page_start == 0x10000 && page_span == expected_cross_span); + check("unplaced extent 128 KiB", + x2w_startup::unplaced_buffer_extent(0x10000, 128 * 1024, page_start, page_span) && + page_start == 0x10000 && page_span == 128 * 1024); + check("unplaced extent overflow address", + !x2w_startup::unplaced_buffer_extent(~std::uint64_t{0} - 15, 32, page_start, page_span)); + check("unplaced extent overflow span", + !x2w_startup::unplaced_buffer_extent(0x10000, ~std::uint64_t{0}, page_start, page_span)); + check("unplaced extent exceeds 256 MiB", + !x2w_startup::unplaced_buffer_extent(0x10000, (256ull << 20) + 1, page_start, page_span)); + + // Unplaced buffer cache coverage checks. + check("unplaced covers interior", x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x10200, 128)); + check("unplaced covers start exact", x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x10000, 65536)); + check("unplaced covers end exact", x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x1ff00, 256)); + check("unplaced covers past end", + x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x1ff00, 257) == mutated("unplaced-covers")); + check("unplaced covers before start", !x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x0fff0, 32)); + check("unplaced covers zero cached span", !x2w_startup::unplaced_buffer_covers(0x10000, 0, 0x10000, 48)); + check("unplaced covers zero requested span", !x2w_startup::unplaced_buffer_covers(0x10000, 65536, 0x10000, 0)); + if (failures) return 1; std::printf("slot 70 buffer memory SRV validation: all checks passed\n"); return 0; From 9ae25a094ce2d0ed2ad336f8c0accf4c233ebc0d Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:48:25 +0200 Subject: [PATCH 163/232] tooling: extract main(argv), path/collision guards, and error handling in emit_variants with CLI suite (#2551) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/emit_variants_cli_check.py | 331 +++++++++++++++++++++++++++++++ tools/emit_variants.py | 108 ++++++++-- 3 files changed, 423 insertions(+), 18 deletions(-) create mode 100644 tests/emit_variants_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index f5cb679dd..44222663c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3903,6 +3903,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/docs_links_check.py") add_test(NAME emit_variants COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/emit_variants_check.py") + add_test(NAME emit_variants_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/emit_variants_cli_check.py") add_test(NAME coverage_svg COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/coverage_svg_check.py") # Compile-only: outcome classification and GVN pass shares, no wall-time threshold (#775). diff --git a/tests/emit_variants_cli_check.py b/tests/emit_variants_cli_check.py new file mode 100644 index 000000000..ebedaefc3 --- /dev/null +++ b/tests/emit_variants_cli_check.py @@ -0,0 +1,331 @@ +"""CLI, path/collision guard, error handling, and mutation suite for tools/emit_variants.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "emit_variants.py" +sys.path.insert(0, str(ROOT / "tools")) + +import emit_variants # noqa: E402 + + +VALID_FIXTURE = '''\ +from pathlib import Path + +CALLS = [] + + +def emit(image, output, control="lifted"): + CALLS.append((image.name, control)) + output.write_text(f"{image.name}:{control}:{len(CALLS)}\\n", encoding="ascii") +''' + +RAISING_VALUE_ERROR_FIXTURE = '''\ +def emit(image, output, control): + raise ValueError(f"unsupported control {control}") +''' + +NO_EMIT_FIXTURE = '''\ +VALUE = 42 +''' + +NON_CALLABLE_EMIT_FIXTURE = '''\ +emit = "not_callable" +''' + +SYNTAX_ERROR_FIXTURE = '''\ +def emit( +''' + +IMPORT_ERROR_FIXTURE = '''\ +import nonexistent_xbox2windows_module_xyz + +def emit(image, output, control): + pass +''' + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = emit_variants.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class EmitVariantsCliPositiveTests(unittest.TestCase): + def test_nested_output_parents_created_and_variants_emitted_in_order(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + script = root / "sample_emit.py" + image = root / "sample.dll" + script.write_text(VALID_FIXTURE, encoding="ascii") + image.write_bytes(b"MZ") + + out1 = root / "nested" / "a" / "first.cpp" + out2 = root / "nested" / "b" / "second.cpp" + self.assertFalse(out1.parent.exists()) + self.assertFalse(out2.parent.exists()) + + code, out, err = _run_main( + [str(script), str(image), f"lifted={out1}", f"pc64={out2}"] + ) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(err, "") + self.assertEqual(out1.read_text(encoding="ascii"), "sample.dll:lifted:1\n") + self.assertEqual(out2.read_text(encoding="ascii"), "sample.dll:pc64:2\n") + + def test_main_sys_argv_forwarding_and_script_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + script = root / "entry_emit.py" + image = root / "entry.dll" + out_file = root / "out" / "entry.cpp" + script.write_text(VALID_FIXTURE, encoding="ascii") + image.write_bytes(b"MZ") + cli_argv = [str(TOOL), str(script), str(image), f"lifted={out_file}"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(out, "") + self.assertEqual(out_file.read_text(encoding="ascii"), "entry.dll:lifted:1\n") + + out_file.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(out_file.is_file()) + + +class EmitVariantsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, 1, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn("emit_variants:", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("emit_variants:", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_script_and_image_missing_or_directory_rejected_before_loading(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + script = root / "ok_script.py" + image = root / "ok_image.dll" + script.write_text(VALID_FIXTURE, encoding="ascii") + image.write_bytes(b"MZ") + missing_script = root / "missing_script.py" + missing_image = root / "missing_image.dll" + dir_path = root / "some_dir" + dir_path.mkdir() + nested_out = root / "never_created" / "out.cpp" + + for argv, frag in ( + ([str(missing_script), str(image), f"v={nested_out}"], "script not found"), + ([str(dir_path), str(image), f"v={nested_out}"], "regular file"), + ([str(script), str(missing_image), f"v={nested_out}"], "image not found"), + ([str(script), str(dir_path), f"v={nested_out}"], "regular file"), + ): + with self.subTest(argv=argv): + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure(argv, expected_fragment=frag) + load_mock.assert_not_called() + self.assertFalse(nested_out.parent.exists()) + + def test_malformed_and_duplicate_variants_rejected_before_loading(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + script = root / "ok_script.py" + image = root / "ok_image.dll" + script.write_text(VALID_FIXTURE, encoding="ascii") + image.write_bytes(b"MZ") + out1 = root / "never" / "a.cpp" + out2 = root / "never" / "b.cpp" + + for bad_pair in ("no-equals", f"={out1}", "lifted="): + with self.subTest(bad_pair=bad_pair): + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), bad_pair], + expected_fragment="expected =", + ) + load_mock.assert_not_called() + + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), f"lifted={out1}", f"lifted={out2}"], + expected_fragment="duplicate variant", + ) + load_mock.assert_not_called() + self.assertFalse(out1.parent.exists()) + + def test_output_directory_duplicate_containment_and_input_collisions_rejected(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + script = root / "script.py" + image = root / "image.dll" + script.write_text(VALID_FIXTURE, encoding="ascii") + image.write_bytes(b"MZ") + existing_dir = root / "existing_dir" + existing_dir.mkdir() + other_out = root / "never_created" / "other.cpp" + + # 1) Existing directory output rejected upfront. + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), f"v1={existing_dir}", f"v2={other_out}"], + expected_fragment="existing directory", + ) + load_mock.assert_not_called() + self.assertFalse(other_out.parent.exists()) + + # 2) Duplicate output via resolve() (kills resolve() in _same_path). + ghost_a = root / "out" / "shared.cpp" + alias_b = root / "out" / ".." / "out" / "shared.cpp" + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), f"a={ghost_a}", f"b={alias_b}"], + expected_fragment="collides with 'a'", + ) + load_mock.assert_not_called() + self.assertFalse(ghost_a.parent.exists()) + + # 3) Duplicate output via hardlink samefile() (kills samefile() in _same_path). + real_out = root / "real_out.cpp" + link_out = sub / "link_out.cpp" + real_out.write_text("keep-out\n", encoding="ascii") + os.link(real_out, link_out) + self.assertNotEqual(real_out.resolve(), link_out.resolve()) + self.assertTrue(real_out.samefile(link_out)) + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), f"a={real_out}", f"b={link_out}"], + expected_fragment="collides with 'a'", + ) + load_mock.assert_not_called() + self.assertEqual(real_out.read_text(encoding="ascii"), "keep-out\n") + + # 4) Output parent containment rejected upfront. + parent_out = root / "nest" / "item" + child_out = parent_out / "child.cpp" + for pairs in ([f"a={parent_out}", f"b={child_out}"], [f"a={child_out}", f"b={parent_out}"]): + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), *pairs], + expected_fragment="cannot contain one another", + check_subprocess=False, + ) + load_mock.assert_not_called() + self.assertFalse(parent_out.parent.exists()) + + # 5) Output colliding with script or image via resolve() and hardlink samefile(). + script_alias = root / "sub" / ".." / "script.py" + image_alias = root / "sub" / ".." / "image.dll" + script_link = sub / "script_link.cpp" + image_link = sub / "image_link.cpp" + os.link(script, script_link) + os.link(image, image_link) + + for out_path, frag in ( + (script_alias, "collides with script"), + (script_link, "collides with script"), + (image_alias, "collides with image"), + (image_link, "collides with image"), + ): + with self.subTest(out_path=out_path): + with mock.patch.object(emit_variants, "load") as load_mock: + self._assert_clean_failure( + [str(script), str(image), f"v={out_path}"], + expected_fragment=frag, + ) + load_mock.assert_not_called() + + def test_missing_non_callable_emit_syntax_import_and_value_errors_caught_cleanly(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + image = root / "image.dll" + image.write_bytes(b"MZ") + nested_out = root / "out_dir" / "out.cpp" + + cases = [ + ("no_emit.py", NO_EMIT_FIXTURE, "does not define callable emit"), + ("non_callable_emit.py", NON_CALLABLE_EMIT_FIXTURE, "does not define callable emit"), + ("syntax_err.py", SYNTAX_ERROR_FIXTURE, "syntax_err.py"), + ("import_err.py", IMPORT_ERROR_FIXTURE, "nonexistent_xbox2windows_module_xyz"), + ] + for name, content, frag in cases: + with self.subTest(script=name): + script = root / name + script.write_text(content, encoding="ascii") + self._assert_clean_failure( + [str(script), str(image), f"v={nested_out}"], + expected_fragment=frag, + ) + self.assertFalse(nested_out.parent.exists()) + + val_script = root / "val_err.py" + val_script.write_text(RAISING_VALUE_ERROR_FIXTURE, encoding="ascii") + self._assert_clean_failure( + [str(val_script), str(image), f"bad={nested_out}"], + expected_fragment="unsupported control bad", + ) + + def test_argparse_missing_arguments_exit_2_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + script = root / "script.py" + image = root / "image.dll" + script.write_text(VALID_FIXTURE, encoding="ascii") + image.write_bytes(b"MZ") + for bad_argv in ([], [str(script)], [str(script), str(image)]): + proc = _run_subprocess(*bad_argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("usage:", proc.stderr.lower()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/emit_variants.py b/tools/emit_variants.py index cb0cee7a5..da1dc22d6 100644 --- a/tools/emit_variants.py +++ b/tools/emit_variants.py @@ -7,38 +7,110 @@ interpreter, the lifter modules and the PE reader load once instead of once per variant. The script is loaded as a module (its `__main__` block does not run) and its `emit(image, output, control)` is called. """ +import argparse import importlib.util -import sys from pathlib import Path +import sys + + +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) def load(script): path = Path(script).resolve() - sys.path.insert(0, str(path.parent)) # as when the script itself is the program + parent_str = str(path.parent) + if not sys.path or sys.path[0] != parent_str: + sys.path.insert(0, parent_str) # as when the script itself is the program spec = importlib.util.spec_from_file_location(path.stem, path) if spec is None or spec.loader is None: - raise SystemExit(f"cannot load {path}") + raise ImportError(f"cannot load {path}") module = importlib.util.module_from_spec(spec) sys.modules[path.stem] = module - spec.loader.exec_module(module) + try: + spec.loader.exec_module(module) + except Exception: + sys.modules.pop(path.stem, None) + raise return module -def main(argv): - if len(argv) < 3: - raise SystemExit(__doc__) - script, image, *pairs = argv - jobs = [] +def _validate_regular_file(path: Path, label: str) -> None: + if not path.exists(): + raise FileNotFoundError(f"{label} not found: {path}") + if path.is_dir() or not path.is_file(): + raise ValueError(f"{label} path must be a regular file: {path}") + + +def _parse_and_validate_jobs( + pairs: list[str], + script_path: Path, + image_path: Path, +) -> list[tuple[str, Path]]: + seen_variants: set[str] = set() + jobs: list[tuple[str, Path]] = [] for pair in pairs: - variant, separator, output = pair.partition("=") - if not separator or not variant or not output: - raise SystemExit(f"expected =, got {pair!r}") - jobs.append((variant, Path(output))) - emit = load(script).emit - image_path = Path(image) - for variant, output in jobs: - emit(image_path, output, variant) + variant, separator, raw_output = pair.partition("=") + if not separator or not variant or not raw_output: + raise ValueError(f"expected =, got {pair!r}") + if variant in seen_variants: + raise ValueError(f"duplicate variant {variant!r}") + seen_variants.add(variant) + output = Path(raw_output) + if output.exists() and output.is_dir(): + raise ValueError(f"output path for {variant!r} is an existing directory: {output}") + if _same_path(output, script_path): + raise ValueError(f"output path for {variant!r} collides with script: {output}") + if _same_path(output, image_path): + raise ValueError(f"output path for {variant!r} collides with image: {output}") + output_resolved = output.resolve() + for prev_variant, prev_output in jobs: + if _same_path(output, prev_output): + raise ValueError( + f"output path for {variant!r} collides with {prev_variant!r}: {output}" + ) + prev_resolved = prev_output.resolve() + if output_resolved in prev_resolved.parents or prev_resolved in output_resolved.parents: + raise ValueError( + f"output paths for {variant!r} and {prev_variant!r} cannot contain one another" + ) + jobs.append((variant, output)) + return jobs + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("script", type=Path, help="CPU fixture script exposing emit(image, output, control)") + parser.add_argument("image", type=Path, help="PE image passed to emit()") + parser.add_argument( + "pairs", + nargs="+", + metavar="variant=output", + help="variant=output pairs to emit", + ) + args = parser.parse_args(argv) + + try: + _validate_regular_file(args.script, "script") + _validate_regular_file(args.image, "image") + jobs = _parse_and_validate_jobs(args.pairs, args.script, args.image) + module = load(args.script) + emit = getattr(module, "emit", None) + if not callable(emit): + raise ValueError( + f"script {args.script} does not define callable emit(image, output, control)" + ) + for _, output in jobs: + output.parent.mkdir(parents=True, exist_ok=True) + for variant, output in jobs: + emit(args.image, output, variant) + except (OSError, SyntaxError, ImportError, ValueError) as exc: + print(f"emit_variants: {exc}", file=sys.stderr) + return 1 + return 0 if __name__ == "__main__": - main(sys.argv[1:]) + raise SystemExit(main()) From d82d587110eadb37907700fa4c7bde6fd2ac4bd0 Mon Sep 17 00:00:00 2001 From: Vladimir <39053957+Vladimir-Human@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:49:14 +0300 Subject: [PATCH 164/232] shader: lower bounded 128-bit LDS exchange and mixed-width reads in gfx2hlsl (#2404) Refs #1541. Extends check_lds_exchange and Stage.lower in tools/startup/gfx2hlsl.py (building on #2327, #2347, and #2345) to support bounded 128-bit group-shared LDS exchanges (ds_write_b128 and ds_read_b128) across s_barrier in 1D compute groups and unify mixed 32/64/128-bit reads over the shared groupshared uint lds[N] array: - Adds _lds_vgpr_span / _lds_quad validating exact 4-VGPR quads v[n:n+3] in v0..v255 and validates 16-bit immediate byte offset <= 0xffff on ds_write_b128 / ds_read_b128 (RDNA 2 DS 0xdf and 0xff). - Validates v_lshlrev_b32 addr, 4, v0 on ds_write_b128, 4-byte aligned offsets (natural 16-byte alignment is not required on GFX10/RDNA2 dword-addressed LDS), and offset + group[0] * 16 <= lds_words * 4 (idx + 3 < lds_words). - Tracks the initialized byte span [fill_start, fill_end) so any post-barrier read (ds_read_b32, ds_read2_b32, ds_read_b64, ds_read_b128) sharing groupshared uint lds[N] succeeds when all accessed dwords lie 4-byte aligned inside [fill_start, fill_end) with s_waitcnt lgkmcnt(0). - Snapshots a = (addr + offset) >> 2 before reading/writing lds[a]..lds[a+3u] so vdst[0..3] overlapping vaddr stays alias-safe. - Adds tests/startup_compute_lds_b128_check.py (offline sizing, quad validation, dword-aligned masks/offsets, mixed 32/64/128-bit interop, refusals, plus 4 GPU dispatch cases Q, B, M, R and 6 mutated controls), updates tests/startup_compute_lds_b64_check.py for mixed-width interop, and wires CMakeLists.txt, .github/workflows/windows.yml, and docs/experiments.md. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 16 + docs/experiments.md | 23 +- tests/startup_compute_lds_b128_check.py | 507 ++++++++++++++++++++++++ tests/startup_compute_lds_b64_check.py | 14 +- tools/startup/gfx2hlsl.py | 95 +++-- 6 files changed, 612 insertions(+), 45 deletions(-) create mode 100644 tests/startup_compute_lds_b128_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 1865740c6..83c701882 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -112,6 +112,7 @@ jobs: (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_compute_lds_b64_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_compute_lds_b128_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), @@ -271,6 +272,7 @@ jobs: tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_compute_check.py \ tests/startup_compute_lds_b64_check.py \ + tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 44222663c..fc16bb57b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3524,6 +3524,22 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl bounded 128-bit LDS exchanges (ds_write_b128, ds_read_b128) and mixed 32/64/128-bit ops (Refs #1541). + add_test(NAME startup_compute_lds_b128_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b128_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_lds_b128_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b128_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_lds_b128_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS q-same-lane q-swap-dwords q-drop-fourth b-wrong-mask m-wrong-b64-off r-wrong-mask) + add_test(NAME startup_compute_lds_b128_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_b128_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_lds_b128_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl 64-bit VOP3 shifts: binary round-trip, overlap, guards and WARP/hardware draws (Refs #1723). add_test(NAME startup_gfx2hlsl_shift64_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_shift64_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index c7efb0451..55b31b2cd 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14603,7 +14603,7 @@ python -B tests/startup_gfx2hlsl_compute_check.py binary llvm-mc-15 [The startup translator](../tools/startup/gfx2hlsl.py) (`check_lds_exchange`, refs `#2274`, `#1541`) extends the bounded group-shared LDS exchange to 64-bit contiguous pairs (`ds_write_b64` and `ds_read_b64`, RDNA 2 DS `0x4d` and `0x76`): - `ds_write_b64 addr, v[d0:d1] [offset:k]` requires a single VGPR byte address from `v_lshlrev_b32 addr, 3, v0`, a contiguous `v[d0:d1]` pair in `v0..v255`, 4-byte aligned `offset`, and `offset + group[0] * 8 <= lds_words * 4`. -- `ds_read_b64 v[r0:r1], addr [offset:k]` requires matching 64-bit fill width (mixed `b32`/`b64` exchanges stay refused), a completed `s_waitcnt lgkmcnt(0)` before `s_barrier` and after each read, an exact `v[r0:r1]` pair, and literal or literal-masked (`v_and_b32`) byte addresses proving `[a + offset, a + offset + 8)` lies 4-byte aligned inside `[first, first + group[0] * 8)`. It computes `a = (addr + offset) >> 2` before assigning `r0 = lds[a]` and `r1 = lds[a + 1u]` (alias-safe when `addr` overlaps `v[r0:r1]`). +- `ds_read_b64 v[r0:r1], addr [offset:k]` requires a completed `s_waitcnt lgkmcnt(0)` before `s_barrier` and after each read, an exact `v[r0:r1]` pair, and literal or literal-masked (`v_and_b32`) byte addresses proving `[a + offset, a + offset + 8)` lies 4-byte aligned inside `[fill_start, fill_end)`. It computes `a = (addr + offset) >> 2` before assigning `r0 = lds[a]` and `r1 = lds[a + 1u]` (alias-safe when `addr` overlaps `v[r0:r1]`). [The 64-bit LDS check](../tests/startup_compute_lds_b64_check.py) verifies offline sizing/mask/pair/mixed-width/overflow/refusal controls and runs two `gfx1013` programs on D3D12 (`cs_6_0`, `debug_layer=enabled`): `P` (`[numthreads(64,1,1)]`, `groups=(2,1,1)`, `LDS_SIZE=2`, `offset:16`, cross-wave `X ^ 32` peer swap with `v[8:9], v8` aliasing) and `B` (`[numthreads(64,1,1)]`, `groups=(1,1,1)`, `LDS_SIZE=1`, peer `v[8:9]` plus lane-37 broadcast `v[10:11]` at `offset:296`). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`), both cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), and all five shader mutants rejected cleanly (`p-same-lane`: `word=0`, 256 mismatches; `p-swap-dwords`: `word=0`, 256 mismatches; `p-drop-high`: `word=1`, 128 mismatches; `b-wrong-mask`: `word=0`, 64 mismatches; `b-wrong-lane`: `word=2`, 128 mismatches). @@ -14615,7 +14615,26 @@ ctest --preset release --no-tests=error -j 1 -R "^startup_compute_lds_b64" -V python -B tests/startup_compute_lds_b64_check.py binary llvm-mc-15 ``` -Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), sub-dword or mixed-width LDS exchanges, non-1D groups, divergent `EXEC`, and real title shaders. +Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), sub-dword LDS exchanges, non-1D groups, divergent `EXEC`, and real title shaders. + +### Startup compute 128-bit LDS exchange + +[The startup translator](../tools/startup/gfx2hlsl.py) (`check_lds_exchange`, `#1541`) extends the bounded group-shared LDS exchange to 128-bit contiguous quads (`ds_write_b128` and `ds_read_b128`, RDNA 2 DS `0xdf` and `0xff`) and unifies 32/64/128-bit reads over the same dword-indexed `groupshared uint lds[N]` array: + +- `ds_write_b128 addr, v[d0:d3] [offset:k]` requires a single VGPR byte address from `v_lshlrev_b32 addr, 4, v0`, a contiguous `v[d0:d3]` quad in `v0..v255`, 4-byte aligned `offset` (`offset % 4 == 0`, natural 16-byte alignment is not required on GFX10/RDNA2 dword-addressed LDS), and `offset + group[0] * 16 <= lds_words * 4` (`idx + 3 < lds_words`). It writes `lds[a]..lds[a + 3u]` from `a = (addr + offset) >> 2`. +- `ds_read_b128 v[r0:r3], addr [offset:k]` (and mixed `ds_read_b32`, `ds_read2_b32`, `ds_read_b64` after any valid `b32`/`b64`/`b128` fill) requires a completed `s_waitcnt lgkmcnt(0)` before `s_barrier` and after each read, an exact `v[r0:r3]` quad, and literal or literal-masked (`v_and_b32`) byte addresses proving `[a + offset, a + offset + width)` lies 4-byte aligned inside `[fill_start, fill_end)`. It snapshots `a = (addr + offset) >> 2` before assigning `r0..r3 = lds[a]..lds[a + 3u]` (alias-safe across all four destination VGPRs). + +[The 128-bit LDS check](../tests/startup_compute_lds_b128_check.py) verifies offline sizing, quad validation, dword-aligned masks/offsets, mixed 32/64/128-bit interoperability and refusals, and dispatches four `gfx1013` programs on D3D12 (`cs_6_0`, `debug_layer=enabled`): `Q` (`[numthreads(32,1,1)]`, `groups=(2,1,1)`, `LDS_SIZE=2`, `offset:16`, `X ^ 17` with `v[9:12], v9` aliasing), `B` (`[numthreads(64,1,1)]`, `groups=(1,1,1)`, `LDS_SIZE=2`, `X ^ 32` with `v[9:12], v10` aliasing plus lane-37 broadcast at `offset:592`), `M` (128-bit fill read by `ds_read_b128`, `ds_read_b64`, and `ds_read_b32`), and `R` (32-bit fill read by `ds_read_b128`), alongside six mutated controls (`q-same-lane`, `q-swap-dwords`, `q-drop-fourth`, `b-wrong-mask`, `m-wrong-b64-off`, `r-wrong-mask`). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`), all four cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), and all six shader mutants rejected cleanly (`q-same-lane`: `word=0`, 256 mismatches; `q-swap-dwords`: `word=2`, 128 mismatches; `q-drop-fourth`: `word=3`, 64 mismatches; `b-wrong-mask`: `word=0`, 64 mismatches; `m-wrong-b64-off`: `word=4`, 64 mismatches; `r-wrong-mask`: `word=0`, 128 mismatches). + +```powershell +. .\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -j 1 -R "^startup_compute_lds_b128" -V +python -B tests/startup_compute_lds_b128_check.py binary llvm-mc-15 +``` + +Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), sub-dword LDS exchanges, non-1D groups, divergent `EXEC`, and real title shaders. ## Startup translator: refusal census diff --git a/tests/startup_compute_lds_b128_check.py b/tests/startup_compute_lds_b128_check.py new file mode 100644 index 000000000..314727cbf --- /dev/null +++ b/tests/startup_compute_lds_b128_check.py @@ -0,0 +1,507 @@ +#!/usr/bin/env python3 +"""Verify bounded 128-bit LDS exchanges (ds_write_b128, ds_read_b128) and mixed 32/64/128-bit ops across s_barrier. + +With no arguments, checks offline RSRC2 sizing, 4-VGPR quad validation, dword alignment/bounds, mixed 32/64/128-bit +LDS interoperability, and barrier/waitcnt/branch/EXEC/1D-group/gds/non-compute refusals. +With 'binary ', validates assembled gfx1013 machine-code bytes. With 'dispatch' or 'control ', +compiles with DXC (cs_6_0) and runs WARP / hardware GPU readback verification via offscreen_check. +""" + +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_compute_check import TGID_X, USER7, patch, refused, root_blob # noqa: E402 + + +PREAMBLE = ( + 's_mov_b32 s10, s6\n' + 's_mov_b32 s11, 0\n' + 's_load_dwordx8 s[12:19], s[10:11], 0x0\n' + 's_waitcnt lgkmcnt(0)\n' +) + +# Case Q: [numthreads(32, 1, 1)], groups=(2, 1, 1), LDS_SIZE=2 (1024 bytes = 256 uints). +# 128-bit peer exchange (X ^ 17) at byte offset 16..528, including vdst[0] == vaddr aliasing (ds_read_b128 v[9:12], v9 offset:16). +SOURCE_Q = PREAMBLE + """\ +s_lshl_b32 s20, s7, 8 +v_add_nc_u32 v5, s20, v0 +v_xor_b32 v6, 0xa5a50000, v5 +v_add_nc_u32 v7, 0x5a5a0000, v5 +v_not_b32 v8, v5 +v_lshlrev_b32 v4, 4, v0 +ds_write_b128 v4, v[5:8] offset:16 +s_waitcnt lgkmcnt(0) +s_barrier +v_xor_b32 v9, 0x110, v4 +v_and_b32 v9, 0x1f0, v9 +ds_read_b128 v[9:12], v9 offset:16 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s21, s7, 5 +v_add_nc_u32 v13, s21, v0 +v_lshlrev_b32 v13, 4, v13 +buffer_store_dwordx4 v[9:12], v13, s[16:19], 0 offen +s_endpgm +""" + +WORDS_Q = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf' + '0788148f14000a4aff0a0c3a0000a5a5ff0a0e4a00005a5a056f107e84000834' + '10007cdb040500007fc08cbf00008abfff08123a10010000' + 'ff121236f00100001000fcdb090000097fc08cbf' + '0785158f15001a4a841a1a34001078e00d090480000081bf' +) + +# Case B: [numthreads(64, 1, 1)], groups=(1, 1, 1), LDS_SIZE=2 (1024 bytes exact fit: 64 * 16 = 1024). +# Cross-wave peer exchange (X ^ 32) with vdst[1] == vaddr aliasing (ds_read_b128 v[9:12], v10) +# plus lane-37 128-bit broadcast at offset:592 (combined peer low qword + broadcast high qword). +SOURCE_B = PREAMBLE + """\ +v_mov_b32 v5, v0 +v_xor_b32 v6, 0x5a5a0000, v5 +v_add_nc_u32 v7, 0x11223300, v5 +v_not_b32 v8, v5 +v_lshlrev_b32 v4, 4, v0 +ds_write_b128 v4, v[5:8] +s_waitcnt lgkmcnt(0) +s_barrier +v_xor_b32 v10, 0x200, v4 +v_and_b32 v10, 0x3f0, v10 +ds_read_b128 v[9:12], v10 +s_waitcnt lgkmcnt(0) +v_mov_b32 v17, 0 +ds_read_b128 v[13:16], v17 offset:592 +s_waitcnt lgkmcnt(0) +v_mov_b32 v11, v15 +v_mov_b32 v12, v16 +v_lshlrev_b32 v18, 4, v0 +buffer_store_dwordx4 v[9:12], v18, s[16:19], 0 offen +s_endpgm +""" + +WORDS_B = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf' + '00030a7eff0a0c3a00005a5aff0a0e4a00332211056f107e84000834' + '00007cdb040500007fc08cbf00008abfff08143a00020000' + 'ff141436f00300000000fcdb0a0000097fc08cbf' + '8002227e5002fcdb1100000d7fc08cbf0f03167e1003187e' + '84002434001078e012090480000081bf' +) + +# Case M: [numthreads(32, 1, 1)], groups=(1, 1, 1), LDS_SIZE=1 (512 bytes exact fit: 32 * 16 = 512). +# Mixed 128-bit write -> 128-bit peer read (X ^ 16, vdst[1] == vaddr) + 64-bit read (lane 18 dwords 2..3, offset:296) +# + 32-bit reads (lane 31 dword 3 at offset:508, lane 0 dword 0 at offset:0) sharing groupshared uint lds[128]. +SOURCE_M = PREAMBLE + """\ +v_mov_b32 v5, v0 +v_xor_b32 v6, 0x55aa0000, v5 +v_add_nc_u32 v7, 0x12340000, v5 +v_not_b32 v8, v5 +v_lshlrev_b32 v4, 4, v0 +ds_write_b128 v4, v[5:8] +s_waitcnt lgkmcnt(0) +s_barrier +v_xor_b32 v10, 0x100, v4 +v_and_b32 v10, 0x1f0, v10 +ds_read_b128 v[9:12], v10 +s_waitcnt lgkmcnt(0) +v_mov_b32 v17, 0 +ds_read_b64 v[13:14], v17 offset:296 +s_waitcnt lgkmcnt(0) +v_mov_b32 v17, 0 +ds_read_b32 v15, v17 offset:508 +s_waitcnt lgkmcnt(0) +v_mov_b32 v17, 0 +ds_read_b32 v16, v17 +s_waitcnt lgkmcnt(0) +v_lshlrev_b32 v18, 5, v0 +buffer_store_dwordx4 v[9:12], v18, s[16:19], 0 offen +buffer_store_dwordx4 v[13:16], v18, s[16:19], 0 offen offset:16 +s_endpgm +""" + +WORDS_M = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf' + '00030a7eff0a0c3a0000aa55ff0a0e4a00003412056f107e84000834' + '00007cdb040500007fc08cbf00008abfff08143a00010000' + 'ff141436f00100000000fcdb0a0000097fc08cbf' + '8002227e2801d8d91100000d7fc08cbf' + '8002227efc01d8d81100000f7fc08cbf' + '8002227e0000d8d8110000107fc08cbf' + '85002434001078e012090480101078e0120d0480000081bf' +) + +# Case R: [numthreads(32, 1, 1)], groups=(2, 1, 1), LDS_SIZE=1 (512 bytes = 128 uints). +# Mixed 32-bit fill (offset:16..144) -> 128-bit quad-dword read of 4 consecutive peer lanes ((X ^ 16) & ~3). +SOURCE_R = PREAMBLE + """\ +s_lshl_b32 s20, s7, 8 +v_add_nc_u32 v5, s20, v0 +v_xor_b32 v5, 0xa5000000, v5 +v_lshlrev_b32 v4, 2, v0 +ds_write_b32 v4, v5 offset:16 +s_waitcnt lgkmcnt(0) +s_barrier +v_xor_b32 v9, 64, v4 +v_and_b32 v9, 0x70, v9 +ds_read_b128 v[9:12], v9 offset:16 +s_waitcnt lgkmcnt(0) +s_lshl_b32 s21, s7, 5 +v_add_nc_u32 v13, s21, v0 +v_lshlrev_b32 v13, 4, v13 +buffer_store_dwordx4 v[9:12], v13, s[16:19], 0 offen +s_endpgm +""" + +WORDS_R = bytes.fromhex( + '06038abe80038bbe05030cf4000000fa7fc08cbf' + '0788148f14000a4aff0a0a3a000000a582000834100034d804050000' + '7fc08cbf00008abfc008123aff121236700000001000fcdb09000009' + '7fc08cbf0785158f15001a4a841a1a34001078e00d090480000081bf' +) + +CASES = { + 'Q': (SOURCE_Q, WORDS_Q, USER7 | TGID_X | (2 << 15), (32, 1, 1), (2, 1, 1)), + 'B': (SOURCE_B, WORDS_B, USER7 | TGID_X | (2 << 15), (64, 1, 1), (1, 1, 1)), + 'M': (SOURCE_M, WORDS_M, USER7 | TGID_X | (1 << 15), (32, 1, 1), (1, 1, 1)), + 'R': (SOURCE_R, WORDS_R, USER7 | TGID_X | (1 << 15), (32, 1, 1), (2, 1, 1)), +} + +VERIFIED_SNIPPETS = { + 'ds_write_b128 v4, v[5:8]': '00007cdb04050000', + 'ds_write_b128 v4, v[5:8] offset:16': '10007cdb04050000', + 'ds_write_b128 v2, v[8:11] offset:32': '20007cdb02080000', + 'ds_read_b128 v[24:27], v2': '0000fcdb02000018', + 'ds_read_b128 v[9:12], v9 offset:16': '1000fcdb09000009', + 'ds_read_b128 v[13:16], v17 offset:592': '5002fcdb1100000d', +} + +WORDS = 320 +SENTINEL = 0xc5c5c5c5 + + +def expected_words(name): + out = [SENTINEL] * WORDS + if name == 'Q': + for g in range(2): + for l in range(32): + peer = (g << 8) + (l ^ 17) + idx = (g * 32 + l) * 4 + out[idx] = peer + out[idx + 1] = peer ^ 0xa5a50000 + out[idx + 2] = (0x5a5a0000 + peer) & 0xffffffff + out[idx + 3] = peer ^ 0xffffffff + elif name == 'B': + b2 = (0x11223300 + 37) & 0xffffffff + b3 = 37 ^ 0xffffffff + for l in range(64): + peer = l ^ 32 + idx = l * 4 + out[idx] = peer + out[idx + 1] = peer ^ 0x5a5a0000 + out[idx + 2] = b2 + out[idx + 3] = b3 + elif name == 'M': + l18_w2 = (0x12340000 + 18) & 0xffffffff + l18_w3 = 18 ^ 0xffffffff + l31_w3 = 31 ^ 0xffffffff + l0_w0 = 0 + for l in range(32): + peer = l ^ 16 + idx = l * 8 + out[idx] = peer + out[idx + 1] = peer ^ 0x55aa0000 + out[idx + 2] = (0x12340000 + peer) & 0xffffffff + out[idx + 3] = peer ^ 0xffffffff + out[idx + 4] = l18_w2 + out[idx + 5] = l18_w3 + out[idx + 6] = l31_w3 + out[idx + 7] = l0_w0 + elif name == 'R': + for g in range(2): + for l in range(32): + base_lane = (l ^ 16) & ~3 + idx = (g * 32 + l) * 4 + for k in range(4): + out[idx + k] = ((g << 8) + base_lane + k) ^ 0xa5000000 + else: + raise KeyError(name) + return out + + +def translate_case(name, code=None, rsrc2=None, group=None): + _, words, default_rsrc2, local, _groups = CASES[name] + return G.ComputePipeline(words if code is None else code, root_blob(), + default_rsrc2 if rsrc2 is None else rsrc2, local if group is None else group) + + +def check_controls(): + # Positive HLSL lowering: declarations, single-eval alias-safe index, barrier, and all 4 dwords. + hlsl_q = translate_case('Q').hlsl_cs() + assert 'groupshared uint lds[256];' in hlsl_q, hlsl_q + assert hlsl_q.count('GroupMemoryBarrierWithGroupSync();') == 1, hlsl_q + assert ('a = (v4 + 16u) >> 2;\n lds[a] = v5;\n lds[a + 1u] = v6;\n' + ' lds[a + 2u] = v7;\n lds[a + 3u] = v8;') in hlsl_q, hlsl_q + assert ('a = (v9 + 16u) >> 2;\n v9 = lds[a];\n v10 = lds[a + 1u];\n' + ' v11 = lds[a + 2u];\n v12 = lds[a + 3u];') in hlsl_q, hlsl_q + + hlsl_b = translate_case('B').hlsl_cs() + assert 'groupshared uint lds[256];' in hlsl_b, hlsl_b + assert ('a = (v4 + 0u) >> 2;\n lds[a] = v5;\n lds[a + 1u] = v6;\n' + ' lds[a + 2u] = v7;\n lds[a + 3u] = v8;') in hlsl_b, hlsl_b + assert ('a = (v10 + 0u) >> 2;\n v9 = lds[a];\n v10 = lds[a + 1u];\n' + ' v11 = lds[a + 2u];\n v12 = lds[a + 3u];') in hlsl_b, hlsl_b + assert ('a = (v17 + 592u) >> 2;\n v13 = lds[a];\n v14 = lds[a + 1u];\n' + ' v15 = lds[a + 2u];\n v16 = lds[a + 3u];') in hlsl_b, hlsl_b + + # Mixed 32/64/128-bit LDS lowering sharing groupshared uint lds[128]. + hlsl_m = translate_case('M').hlsl_cs() + assert 'groupshared uint lds[128];' in hlsl_m, hlsl_m + assert 'a = (v17 + 296u) >> 2;\n v13 = lds[a];\n v14 = lds[a + 1u];' in hlsl_m, hlsl_m + assert 'v15 = lds[(v17 + 508u) >> 2];' in hlsl_m, hlsl_m + assert 'v16 = lds[(v17 + 0u) >> 2];' in hlsl_m, hlsl_m + + hlsl_r = translate_case('R').hlsl_cs() + assert 'groupshared uint lds[128];' in hlsl_r, hlsl_r + assert 'lds[(v4 + 16u) >> 2] = v5;' in hlsl_r, hlsl_r + assert ('a = (v9 + 16u) >> 2;\n v9 = lds[a];\n v10 = lds[a + 1u];\n' + ' v11 = lds[a + 2u];\n v12 = lds[a + 3u];') in hlsl_r, hlsl_r + + # vdst[3] == vaddr aliasing and nonzero dword-aligned non-16B offset (offset:4) on ds_write_b128 / ds_read_b128. + alias_hi = patch(WORDS_B, '0000fcdb0a000009', '0000fcdb0c000009') + alias_hi = patch(alias_hi, 'ff08143a00020000', 'ff08183a00020000') + alias_hi = patch(alias_hi, 'ff141436f0030000', 'ff181836f0030000') + hlsl_alias = translate_case('B', code=alias_hi).hlsl_cs() + assert 'a = (v12 + 0u) >> 2;\n v9 = lds[a];' in hlsl_alias, hlsl_alias + + # Dword-aligned (non-16B) offset:4 fill and read on ds_write_b128 / ds_read_b128. + store_q = '10007cdb04050000' + read_q = '1000fcdb09000009' + dword_off = patch(WORDS_Q, store_q, '04007cdb04050000') + dword_off = patch(dword_off, read_q, '0400fcdb09000009') + hlsl_dw = translate_case('Q', code=dword_off).hlsl_cs() + assert 'a = (v4 + 4u) >> 2;' in hlsl_dw and 'a = (v9 + 4u) >> 2;' in hlsl_dw, hlsl_dw + + # Tight capacity boundaries: + # Case Q: offset:16 + 32*16 = 528 exceeds 1 unit (512B), fits at 2 units and at 32 KiB. + # Case B: offset:0 + 64*16 = 1024 exact fit at 2 units; offset:4 (1028B) refuses at 2 units. + base = USER7 | TGID_X + refused('one bounded quad-dword', lambda: translate_case('Q', rsrc2=base | (1 << 15))) + refused('allocation', lambda: translate_case('Q', rsrc2=base | (0 << 15))) + refused('allocation', lambda: translate_case('Q', rsrc2=base | (65 << 15))) + assert 'groupshared uint lds[8192];' in translate_case('Q', rsrc2=base | (64 << 15)).hlsl_cs() + refused('one bounded quad-dword', + lambda: translate_case('B', code=patch(WORDS_B, '00007cdb04050000', '04007cdb04050000'))) + + # Mask alignment and +12/+16 boundary checks on ds_read_b128. + mask_1f0 = 'ff121236f0010000' + mask_1c = 'ff1212361c000000' + mask_1e = 'ff1212361e000000' + mask_1fc = 'ff121236fc010000' + ok_1c = translate_case('Q', code=patch(WORDS_Q, mask_1f0, mask_1c)).hlsl_cs() + assert 'v9 = 0x0000001cu & v9;' in ok_1c, ok_1c + refused('aligned', lambda: translate_case('Q', code=patch(WORDS_Q, mask_1f0, mask_1e))) + refused('initialized span', lambda: translate_case('Q', code=patch(WORDS_Q, mask_1f0, mask_1fc))) + + # Broadcast upper boundary: B fills [0, 1024), so offset:1008 reads [1008, 1024) (valid), offset:1012 overflows. + bcast_b = '5002fcdb1100000d' + ok_1008 = translate_case('B', code=patch(WORDS_B, bcast_b, 'f003fcdb1100000d')).hlsl_cs() + assert 'a = (v17 + 1008u) >> 2;' in ok_1008, ok_1008 + refused('initialized span', lambda: translate_case('B', code=patch(WORDS_B, bcast_b, 'f403fcdb1100000d'))) + + # Mixed-width boundary checks: + # - Case R fills [16, 144) via ds_write_b32; ds_read_b128 with mask 0x70 + offset:16 covers [16, 144). + # Mask 0x74 reaches [16, 148) -> refused. + refused('initialized span', lambda: translate_case('R', code=patch(WORDS_R, 'ff12123670000000', 'ff12123674000000'))) + # - Case M fills [0, 512) via ds_write_b128; ds_read_b64 at offset:504 fits, offset:508 refuses. + bcast_m64 = '2801d8d91100000d' + assert 'a = (v17 + 504u) >> 2;' in translate_case('M', code=patch(WORDS_M, bcast_m64, 'f801d8d91100000d')).hlsl_cs() + refused('initialized span', lambda: translate_case('M', code=patch(WORDS_M, bcast_m64, 'fc01d8d91100000d'))) + # - Case M with ds_read2_b32 inside [0, 512) succeeds; out-of-span offset1 refuses. + ok_read2 = translate_case('M', code=patch(WORDS_M, bcast_m64, '047fdcd81100000d')).hlsl_cs() # offset0:4 (16), offset1:127 (508) + assert 'v13 = lds[(a + 16u) >> 2];\n v14 = lds[(a + 508u) >> 2];' in ok_read2, ok_read2 + refused('initialized span', lambda: translate_case('M', code=patch(WORDS_M, bcast_m64, '0480dcd81100000d'))) + + # Additional mixed b64 fill -> b128 read positive + out-of-span refusal. + b64_to_b128 = [ + (0, 4, 'v_lshlrev_b32', 'v_lshlrev_b32 v4, 3, v0'), + (4, 8, 'ds_write_b64', 'ds_write_b64 v4, v[5:6] offset:8'), + (12, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (16, 4, 's_barrier', 's_barrier 0x0'), + (20, 4, 'v_mov_b32', 'v_mov_b32 v8, 0'), + (24, 8, 'ds_read_b128', 'ds_read_b128 v[8:11], v8 offset:24'), + (32, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (36, 4, 's_endpgm', 's_endpgm'), + ] + G.check_lds_exchange(b64_to_b128, (4, 1, 1), 128) # [8, 40): read [24, 40) fits + bad_b64_to_b128 = list(b64_to_b128) + bad_b64_to_b128[5] = (24, 8, 'ds_read_b128', 'ds_read_b128 v[8:11], v8 offset:28') # [28, 44) overflows 40 + refused('initialized span', lambda: G.check_lds_exchange(bad_b64_to_b128, (4, 1, 1), 128)) + + # Unaligned offsets, wrong shift, missing barrier/waitcnt, double fill/barrier, unprovable address, gds, EXEC/branch/non-1D. + wait = '7fc08cbf' + barrier = '00008abf' + nop = '000080bf' + refused('one bounded quad-dword', lambda: translate_case('Q', code=patch(WORDS_Q, store_q, '12007cdb04050000'))) # write offset:18 + refused('one bounded quad-dword', lambda: translate_case('Q', code=patch(WORDS_Q, store_q, '11007cdb04050000'))) # write offset:17 + refused('aligned', lambda: translate_case('Q', code=patch(WORDS_Q, read_q, '1200fcdb09000009'))) # read offset:18 + refused('initialized span', lambda: translate_case('Q', code=patch(WORDS_Q, read_q, '0c00fcdb09000009'))) # before span (offset:12) + refused('one bounded quad-dword', lambda: translate_case('Q', code=patch(WORDS_Q, '84000834', '83000834'))) # shift 3 instead of 4 + refused('one bounded quad-dword', lambda: translate_case('Q', code=patch(WORDS_Q, store_q, store_q + store_q))) # double fill + refused('completed fill', lambda: translate_case('Q', code=patch(WORDS_Q, wait + barrier, nop + barrier))) + refused('after the fill barrier', lambda: translate_case('Q', code=patch(WORDS_Q, barrier, nop))) + refused('one barrier', lambda: translate_case('Q', code=patch(WORDS_Q, barrier, barrier + barrier))) + refused('completed LGKM wait', lambda: translate_case('Q', code=patch(WORDS_Q, read_q + wait, read_q + nop))) + refused('optional byte offset', lambda: translate_case('Q', code=patch(WORDS_Q, store_q, '10007edb04050000'))) # write GDS + refused('optional byte offset', lambda: translate_case('Q', code=patch(WORDS_Q, read_q, '1000fedb09000009'))) # read GDS + refused('literal or literal-masked', + lambda: translate_case('Q', code=patch(WORDS_Q, 'ff121236f0010000', '0403127e'))) # unbounded v_mov v9, v4 + refused('after the fill barrier', + lambda: translate_case('Q', code=patch(WORDS_Q, 'ff121236f0010000', nop))) # non-producer s_nop before read + refused('entry EXEC', lambda: translate_case('Q', code=patch(WORDS_Q, store_q, '8003febe' + store_q))) + refused('straight-line', lambda: translate_case('Q', code=patch(WORDS_Q, store_q, '020084bf' + store_q))) + refused('1D group', lambda: translate_case('Q', group=(16, 2, 1))) + refused('completed read', lambda: G.check_lds_exchange(b64_to_b128[:4] + [b64_to_b128[-1]], (4, 1, 1), 128)) + refused('does not cover', lambda: G.check_lds_exchange([ + (0, 4, 'v_lshlrev_b32', 'v_lshlrev_b32 v4, 4, v0'), + (4, 8, 'ds_write_b96', 'ds_write_b96 v4, v[5:7]'), + (12, 4, 's_endpgm', 's_endpgm'), + ], (4, 1, 1), 128)) + + # 4-VGPR quad validation and >0xffff offset refusal on ds_write_b128 / ds_read_b128. + assert G._lds_quad('v[0:3]') == 0 + assert G._lds_quad('v[4:7]') == 4 + assert G._lds_quad('v[252:255]') == 252 + for bad_quad in ('v5', 'v[5:5]', 'v[5:6]', 'v[5:7]', 'v[5:9]', 'v[8:5]', 'v[253:256]', 's[4:7]'): + assert G._lds_quad(bad_quad) is None, bad_quad + decoded_w = [(0, 4, 'v_lshlrev_b32', 'v_lshlrev_b32 v4, 4, v0'), + (4, 8, 'ds_write_b128', f'ds_write_b128 v4, {bad_quad}'), + (12, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (16, 4, 's_barrier', 's_barrier 0x0'), + (20, 4, 'v_mov_b32', 'v_mov_b32 v8, 0'), + (24, 8, 'ds_read_b128', 'ds_read_b128 v[8:11], v8'), + (32, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (36, 4, 's_endpgm', 's_endpgm')] + refused('4-VGPR quad', lambda d=decoded_w: G.check_lds_exchange(d, (4, 1, 1), 128)) + decoded_r = [(0, 4, 'v_lshlrev_b32', 'v_lshlrev_b32 v4, 4, v0'), + (4, 8, 'ds_write_b128', 'ds_write_b128 v4, v[5:8]'), + (12, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (16, 4, 's_barrier', 's_barrier 0x0'), + (20, 4, 'v_mov_b32', 'v_mov_b32 v8, 0'), + (24, 8, 'ds_read_b128', f'ds_read_b128 {bad_quad}, v8'), + (32, 4, 's_waitcnt', 's_waitcnt lgkmcnt(0)'), + (36, 4, 's_endpgm', 's_endpgm')] + refused('4-VGPR quad', lambda d=decoded_r: G.check_lds_exchange(d, (4, 1, 1), 128)) + + bad_off = list(b64_to_b128) + bad_off[5] = (24, 8, 'ds_read_b128', 'ds_read_b128 v[8:11], v8 offset:65536') + refused('optional byte offset', lambda: G.check_lds_exchange(bad_off, (4, 1, 1), 128)) + + # Non-compute stage and missing pipe metadata refusals for b128 DS ops. + for stage_kind in ('vs', 'ps'): + s = G.Stage.__new__(G.Stage) + s.kind = stage_kind + refused('ds_write_b128', lambda st=s: st.lower('ds_write_b128', 'ds_write_b128 v4, v[5:8]', ['v4', 'v[5:8]'], [])) + refused('ds_read_b128', lambda st=s: st.lower('ds_read_b128', 'ds_read_b128 v[8:11], v8', ['v[8:11]', 'v8'], [])) + + bare = G.Stage.__new__(G.Stage) + bare.kind = 'cs' + bare.pipe = None + refused('metadata', lambda: bare.lower('ds_write_b128', 'ds_write_b128 v4, v[5:8]', ['v4', 'v[5:8]'], [])) + + print('bounded 128-bit LDS exchange sizing, quad validation, mixed 32/64/128-bit interop, bounds and refusals pass') + + +def assemble(llvm_mc, source): + from startup_flat_param_check import assemble as run + return run(llvm_mc, source) + + +def check_binary(llvm_mc): + for name, (source, words, *_rest) in CASES.items(): + built = assemble(llvm_mc, source) + assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, hex_words in VERIFIED_SNIPPETS.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == hex_words, '%s: assembled %s, recorded %s' % (line, built, hex_words) + print('128-bit LDS fixture words match llvm-mc (%d programs, %d snippets)' % (len(CASES), len(VERIFIED_SNIPPETS))) + + +CONTROLS = { + 'q-same-lane': ('Q', ' v9 = 0x00000110u ^ v4;\n', ' v9 = v4;\n'), + 'q-swap-dwords': ('Q', ' v11 = lds[a + 2u];\n v12 = lds[a + 3u];\n', + ' v11 = lds[a + 3u];\n v12 = lds[a + 2u];\n'), + 'q-drop-fourth': ('Q', ' lds[a + 3u] = v8;\n', ''), + 'b-wrong-mask': ('B', ' v10 = 0x000003f0u & v10;\n', ' v10 = 0x000001f0u & v10;\n'), + 'm-wrong-b64-off': ('M', ' a = (v17 + 296u) >> 2;\n', ' a = (v17 + 288u) >> 2;\n'), + 'r-wrong-mask': ('R', ' v9 = 0x00000070u & v9;\n', ' v9 = 0x00000030u & v9;\n'), +} + + +def mutate(hlsl, control): + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate_case(name).hlsl_cs() + if control: + hlsl = mutate(hlsl, control) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = CASES[name][4] + constants = [0] * 16 + case.write_bytes( + struct.pack('> 2];' in mixed_b32, mixed_b32 + refused('initialized span', + lambda: translate_case('P', code=patch(WORDS_P, read_p, '0408dcd808000008'))) # ds_read2_b32 offset1:8 past 528 + refused('initialized span', + lambda: translate_case('P', code=patch(WORDS_P, '83000834' + store, '82000834' + '100034d804050000'))) # ds_write_b32 + ds_read_b64 past 272 # Register-range validation: reject 1-VGPR, 3-VGPR, >v255, and SGPR operands on ds_write_b64 / ds_read_b64. assert G._lds_pair('v[5:6]') == 5 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6957344fd..e94ec7c71 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -995,13 +995,23 @@ def _lds_single(tok): return int(m.group(1)) if m and int(m.group(1)) < 256 else None -def _lds_pair(tok): - """Exact contiguous 2-VGPR pair v[n:n+1] (v0..v255) for bounded 64-bit LDS exchanges.""" +def _lds_vgpr_span(tok, count): + """Exact contiguous `count`-VGPR range v[n:n+count-1] (v0..v255) for bounded wide LDS exchanges.""" m = re.fullmatch(r'v\[(\d+):(\d+)\]', tok) if not m: return None lo, hi = int(m.group(1)), int(m.group(2)) - return lo if hi == lo + 1 and hi < 256 else None + return lo if hi == lo + count - 1 and hi < 256 else None + + +def _lds_pair(tok): + """Exact contiguous 2-VGPR pair v[n:n+1] (v0..v255) for bounded 64-bit LDS exchanges.""" + return _lds_vgpr_span(tok, 2) + + +def _lds_quad(tok): + """Exact contiguous 4-VGPR quad v[n:n+3] (v0..v255) for bounded 128-bit LDS exchanges.""" + return _lds_vgpr_span(tok, 4) def lds_byte_offsets(name, mods): @@ -1009,7 +1019,9 @@ def lds_byte_offsets(name, mods): if not mods: return (0,) if len(mods) == 1 and re.fullmatch(r'offset:\d+', mods[0]): - return (int(mods[0][7:]),) + offset = int(mods[0][7:]) + if offset <= 0xffff: + return (offset,) raise Unsupported('LDS exchange needs two VGPRs and an optional byte offset') # DS_READ2 encodes each offset independently in dwords. An omitted field is zero. offsets = {} @@ -1024,17 +1036,30 @@ def lds_byte_offsets(name, mods): return first, second +# (is_write, byte_width, fill_shift, fill_unit_name) +LDS_EXCHANGE_OPS = { + 'ds_write_b32': (True, 4, '2', 'dword'), + 'ds_read_b32': (False, 4, None, 'dword'), + 'ds_read2_b32': (False, 4, None, 'dword'), + 'ds_write_b64': (True, 8, '3', 'qword'), + 'ds_read_b64': (False, 8, None, 'qword'), + 'ds_write_b128': (True, 16, '4', 'quad-dword'), + 'ds_read_b128': (False, 16, None, 'quad-dword'), +} + + def check_lds_exchange(ins, group, words): - """Prove one race-free 32-bit or 64-bit fill of a contiguous LDS span, one uniform barrier, then reads of initialized words. + """Prove one race-free 32/64/128-bit fill of a contiguous LDS span, one uniform barrier, then mixed-width reads of initialized dwords. - RDNA 2 ISA (Ch. 9 DS): ds_write_b32 / ds_read_b32 / ds_read2_b32 access 4-byte dwords and - ds_write_b64 / ds_read_b64 access two contiguous little-endian dwords (v[n] at addr+offset, v[n+1] at addr+offset+4). + RDNA 2 ISA (Ch. 9 DS): ds_write_b32 / ds_read_b32 / ds_read2_b32 access 4-byte dwords, + ds_write_b64 / ds_read_b64 access two contiguous little-endian dwords (v[n] at addr+offset, v[n+1] at addr+offset+4), and + ds_write_b128 / ds_read_b128 access four contiguous little-endian dwords (v[n]..v[n+3] at addr+offset..addr+offset+12). + All widths share the dword-indexed groupshared uint lds[N] array and require 4-byte alignment (natural 8/16-byte alignment is not required on GFX10/RDNA2 LDS). LLVM 15 AMDGPUUsage defines COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE in 128-dword (512-byte) units on gfx10. """ - if not 0 < words <= 8192 or group[1:] != (1, 1): + if not 0 < words <= 8192 or group[0] < 1 or group[1:] != (1, 1): raise Unsupported('LDS exchange needs a 1D group and a nonzero allocation of at most 32 KiB') - first = None - elem_bytes = None + fill_span = None published = False read = False prev = (None, [], []) @@ -1045,42 +1070,37 @@ def check_lds_exchange(ins, group, words): or base == 's_endpgm' and i + 1 < len(ins)): raise Unsupported('LDS exchange needs straight-line code and entry EXEC') if base == 's_barrier': - if (first is None or published or prev != ('s_waitcnt', ['lgkmcnt(0)'], []) + if (fill_span is None or published or prev != ('s_waitcnt', ['lgkmcnt(0)'], []) or mods or ops not in ([], ['0'], ['0x0'])): raise Unsupported('LDS exchange needs one barrier after a completed fill') published = True - elif base in ('ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 'ds_write_b64', 'ds_read_b64'): - write = base.startswith('ds_write') - width = 8 if base.endswith('_b64') else 4 + elif base in LDS_EXCHANGE_OPS: + write, width, shift, unit_name = LDS_EXCHANGE_OPS[base] + dwords = width // 4 addr_op = ops[0] if (write and len(ops) == 2) else (ops[1] if len(ops) == 2 else '') val_op = ops[1] if (write and len(ops) == 2) else (ops[0] if len(ops) == 2 else '') if base == 'ds_read2_b32': if len(ops) != 2 or _lds_pair(val_op) is None or _lds_single(addr_op) is None: raise Unsupported('LDS read2 needs a VGPR pair and a byte address VGPR') elif (len(ops) != 2 or _lds_single(addr_op) is None - or (_lds_pair(val_op) is None if width == 8 else _lds_single(val_op) is None)): + or (_lds_single(val_op) is None if dwords == 1 else _lds_vgpr_span(val_op, dwords) is None)): + need_val = ('a matching data VGPR' if dwords == 1 + else 'an aligned %d-VGPR %s' % (dwords, 'pair' if dwords == 2 else 'quad')) raise Unsupported('LDS exchange needs %s, %s and an optional byte offset' - % ('two VGPRs' if width == 4 else 'a VGPR address', - 'an aligned 2-VGPR pair' if width == 8 else 'a matching data VGPR')) + % ('two VGPRs' if dwords == 1 else 'a VGPR address', need_val)) offsets = lds_byte_offsets(base, mods) producer, args, modifiers = prev if write: offset, = offsets - shift = '3' if width == 8 else '2' # The prefix below preserves the entry X ID in v0. Each lane writes exactly one distinct element. - # 8-byte alignment is not required for LDS dword-addressed writes. - if (first is not None or producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] + # 8-byte / 16-byte alignment is not required for LDS dword-addressed writes. + if (fill_span is not None or producer != 'v_lshlrev_b32' or args != [addr_op, shift, 'v0'] or modifiers or offset % 4 or offset + group[0] * width > words * 4): - raise Unsupported('LDS exchange needs one bounded %s per local X ID' - % ('qword' if width == 8 else 'dword')) - first = offset - elem_bytes = width + raise Unsupported('LDS exchange needs one bounded %s per local X ID' % unit_name) + fill_span = (offset, offset + group[0] * width) else: if not published or modifiers or not args or args[0] != addr_op: raise Unsupported('LDS read needs a bounded address after the fill barrier') - if elem_bytes != width: - raise Unsupported('LDS read width (%dB) does not match initialized fill (%dB)' - % (width, elem_bytes or 0)) if producer == 'v_mov_b32' and len(args) == 2 and re.fullmatch(r'0x[0-9a-f]+|\d+', args[1]): low = high = int(args[1], 0) elif (producer == 'v_and_b32' and len(args) == 3 and re.fullmatch(r'0x[0-9a-f]+|\d+', args[1]) @@ -1088,9 +1108,11 @@ def check_lds_exchange(ins, group, words): low, high = 0, int(args[1], 0) else: raise Unsupported('LDS read needs a literal or literal-masked byte address') + fill_start, fill_end = fill_span # Every byte offset in [a + offset, a + offset + width) must be 4-byte aligned and inside the filled span. + # Mixed 32/64/128-bit reads share the same dword-indexed LDS array once all read dwords lie in [fill_start, fill_end). if (low % 4 or high % 4 - or any(offset % 4 or low + offset < first or high + offset + (width - 4) >= first + group[0] * width + or any(offset % 4 or low + offset < fill_start or high + offset + width > fill_end for offset in offsets)): raise Unsupported('LDS read outside the aligned, initialized span') if i + 1 >= len(ins) or ins[i + 1][3] != 's_waitcnt lgkmcnt(0)': @@ -1098,7 +1120,7 @@ def check_lds_exchange(ins, group, words): read = True elif base.startswith('ds_') or 'lds' in mods: raise Unsupported('LDS exchange does not cover ' + asm) - elif first is None and not base.startswith('s_'): + elif fill_span is None and not base.startswith('s_'): # Simple VALU instructions only write their single destination. Other forms, e.g. v_swap_b32, # can also change a source. After the fill, each read proves its own address without the entry X ID. if (base not in VEC_U and base not in VEC_F and base != 'v_mov_b32' @@ -2550,7 +2572,7 @@ def lower(self, base, asm, ops, mods): return ('branch', cond, int(ops[0].split('_')[1], 16)) if base == 'exp': return self.export(asm) - if base in ('ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 'ds_write_b64', 'ds_read_b64', 's_barrier'): + if base in (*LDS_EXCHANGE_OPS, 's_barrier'): if getattr(self, 'kind', None) != 'cs': raise Unsupported(base) # The refusal census continues past failed instructions. Scan this program only once. @@ -2583,16 +2605,17 @@ def lower(self, base, asm, ops, mods): for index, offset in enumerate(offsets): self.set_v(start + index, 'lds[(%s + %du) >> 2]' % (address, offset)) else: - lo = _lds_pair(ops[1 if write else 0]) + dwords = 4 if base.endswith('_b128') else 2 + lo = _lds_vgpr_span(ops[1 if write else 0], dwords) if write: - d0, d1 = self.u('v%d' % lo), self.u('v%d' % (lo + 1)) + vals = [self.u('v%d' % (lo + k)) for k in range(dwords)] self.emit('a = (%s + %du) >> 2;' % (address, offsets[0])) - self.emit('lds[a] = %s;' % d0) - self.emit('lds[a + 1u] = %s;' % d1) + for k, val in enumerate(vals): + self.emit('lds[%s] = %s;' % ('a' if k == 0 else 'a + %du' % k, val)) else: self.emit('a = (%s + %du) >> 2;' % (address, offsets[0])) - self.set_v(lo, 'lds[a]') - self.set_v(lo + 1, 'lds[a + 1u]') + for k in range(dwords): + self.set_v(lo + k, 'lds[%s]' % ('a' if k == 0 else 'a + %du' % k)) return None if base.endswith('_dpp'): return self.dpp(base[:-len('_dpp')], ops, mods) From 3490df18b8d18e2de4be3c27836bdf8a103a176d Mon Sep 17 00:00:00 2001 From: Matheus Sergio Date: Wed, 25 Nov 2026 17:50:44 -0300 Subject: [PATCH 165/232] startup: lower CLAMP_BORDER comparison samplers with fixed border colors (#2549) Allow `SQ_TEX_CLAMP_BORDER` (6) alongside `SQ_TEX_CLAMP_LAST_TEXEL` (2) on X and Y for `image_sample_c` and `image_sample_c_lz` in `tools/startup/gfx2hlsl.py`, and decode `SQ_IMG_SAMP_WORD3` bits 31:30 (`BORDER_COLOR_TYPE`, Mesa `gfx10-rsrc.json`) to the three static D3D12 border colors (`TRANS_BLACK`, `OPAQUE_BLACK`, `OPAQUE_WHITE`) in `src/startup_stubs/translated_sampler_bindings.h` (as well as dynamic heap sampler border colors). Also record 32-bit inline float constants written by `s_mov_b32` (such as `0x40000000` / `2.0` for `OPAQUE_BLACK`) for `const_words()` without altering runtime SGPR materialization. `BORDER_COLOR_TYPE == REGISTER` (3) when X or Y uses `CLAMP_BORDER`, half-border / mirror-once-border / wrap / mirror modes, and the standalone `pixel_aot.comparison_sampler_state` default remain refused. Part of #2023 AI-assisted. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 9 + .../translated_sampler_bindings.h | 14 +- tests/startup_image_sample_c_border_check.py | 436 ++++++++++++++++++ tests/startup_sampler_comparison_check.cpp | 19 + ...rtup_translated_sampler_bindings_check.cpp | 32 +- tools/pixel_aot.py | 40 +- tools/startup/gfx2hlsl.py | 26 +- 7 files changed, 562 insertions(+), 14 deletions(-) create mode 100644 tests/startup_image_sample_c_border_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index fc16bb57b..989e0ed27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3327,6 +3327,15 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_image_sample_a16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl comparison sampling with CLAMP_BORDER and fixed border colors (#2023 item F). + add_test(NAME startup_image_sample_c_border_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_c_border_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_image_sample_c_border_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_c_border_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_image_sample_c_border_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_image_sample_b_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_sample_b_check.py" draw "${DXC_EXECUTABLE}" diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index e11626430..a4aca72dd 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -47,7 +47,12 @@ inline D3D12_STATIC_SAMPLER_DESC decode_sampler(const SamplerWords& words, UINT s.Filter = D3D12_ENCODE_BASIC_FILTER(min & 1, mag & 1, mip == 2 ? 1 : 0, D3D12_FILTER_REDUCTION_TYPE_COMPARISON); s.ComparisonFunc = static_cast(((words[0] >> 12) & 7) + 1); } - s.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; + // SQ_IMG_SAMP_WORD3 bits 31:30 (BORDER_COLOR_TYPE, Mesa gfx10-rsrc.json): 0 = TRANS_BLACK, 1 = OPAQUE_BLACK, + // 2 = OPAQUE_WHITE. Value 3 (REGISTER, indexed by BORDER_COLOR_PTR) has no palette here and falls back to 0. + const UINT border_type = (words[3] >> 30) & 3u; + s.BorderColor = border_type == 2u ? D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE + : border_type == 1u ? D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK + : D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK; s.MaxLOD = D3D12_FLOAT32_MAX; if (lod_limits) { s.MinLOD = static_cast(words[1] & 0xfffu) / 256.0f; @@ -184,10 +189,13 @@ inline SamplerSnapshot snapshot_samplers(SamplerSource source, bool reserved_fal inline D3D12_SAMPLER_DESC dynamic_sampler(const SamplerWords& words) { - // A heap entry is the title's own descriptor, so its MIN_LOD and MAX_LOD apply (#2221). + // A heap entry is the title's own descriptor, so its MIN_LOD, MAX_LOD (#2221) and fixed border color apply. const auto s = decode_sampler(words, 0, false, true); + const float rgb = s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE ? 1.0f : 0.0f; + const float alpha = (s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || + s.BorderColor == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK) ? 1.0f : 0.0f; return {s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, s.ComparisonFunc, - {}, s.MinLOD, s.MaxLOD}; + {rgb, rgb, rgb, alpha}, s.MinLOD, s.MaxLOD}; } inline D3D12_SAMPLER_DESC border_sampler() diff --git a/tests/startup_image_sample_c_border_check.py b/tests/startup_image_sample_c_border_check.py new file mode 100644 index 000000000..5b29da82b --- /dev/null +++ b/tests/startup_image_sample_c_border_check.py @@ -0,0 +1,436 @@ +"""Comparison sampling with CLAMP_BORDER and fixed border colors in tools/startup/gfx2hlsl.py (Part of #2023, item F). + + (no arguments) translation, manifest and refusal controls, 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) and draw + against the 2x2 R32_FLOAT and R32G32B32A32_FLOAT fixtures: checks + in-bounds, negative/positive out-of-bounds, mixed X/Y clamp+border, + bilinear border-edge PCF, all three fixed border colors, and mutants + +SQ_IMG_SAMP_WORD0 bits 2:0 (CLAMP_X) and 5:3 (CLAMP_Y) select CLAMP_LAST_TEXEL (2) or CLAMP_BORDER (6). +When either axis uses CLAMP_BORDER, SQ_IMG_SAMP_WORD3 bits 31:30 (BORDER_COLOR_TYPE, Mesa gfx10-rsrc.json) +select TRANS_BLACK (0, depth 0.0), OPAQUE_BLACK (1, depth 0.0, alpha 1.0) or OPAQUE_WHITE (2, depth 1.0). +Value 3 (REGISTER, indexed by BORDER_COLOR_PTR in bits 11:0) has no D3D12 static-sampler equivalent and is +refused whenever X or Y uses CLAMP_BORDER, while remaining ignored when both X and Y use CLAMP_LAST_TEXEL. +""" +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 disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +import pixel_aot as P # noqa: E402 +from startup_image_3d_check import ( # noqa: E402 + FULLSCREEN_VS, + VS_WORDS, + CompileQueue, + assemble, + compile_hlsl, + root_blob, +) + +CLAMP_LAST_TEXEL = 2 +CLAMP_BORDER = 6 +LESS = 1 << 12 +TRUNC_COORD = 1 << 27 +BILINEAR_W2 = (1 << 20) | (1 << 22) + +TRANS_BLACK = 0 << 30 +OPAQUE_BLACK = 1 << 30 +OPAQUE_WHITE = 2 << 30 +REGISTER_BORDER = 3 << 30 + +IMG_SAMPLE_LZ = 0x27 +IMG_SAMPLE_C = 0x28 +IMG_SAMPLE_C_LZ = 0x2F +DIM_2D = 1 +DIM_2D_ARRAY = 5 + + +INLINE_FLOATS = { + 0x3f000000: 0xf0, + 0xbf000000: 0xf1, + 0x3f800000: 0xf2, + 0xbf800000: 0xf3, + 0x40000000: 0xf4, + 0xc0000000: 0xf5, + 0x40800000: 0xf6, + 0xc0800000: 0xf7, + 0x3e22f983: 0xf8, +} + + +def s_mov_b32(sdst, imm): + """s_mov_b32 with the operand coding llvm-mc picks: an inline constant when one exists.""" + imm &= 0xffffffff + code = INLINE_FLOATS.get( + imm, + 0x80 + imm if imm <= 64 else 0xc0 + (1 << 32) - imm if imm >= 0xfffffff0 else None, + ) + if code is not None: + return struct.pack(' 0 and not mnemonic.startswith(('v_unknown', 's_unknown', 'unknown')), (name, off, mnemonic, asm) + decoded.append(asm) + off += size + assert off == len(raw) and decoded[-1] == 's_endpgm', (name, off, len(raw), decoded[-1]) + + +def controls(): + check_disassembly() + + # Accepted comparison-sampler combinations and their exact smpc manifest lines. + expected_smpc = { + 'border_white': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_BORDER_W0, OPAQUE_WHITE), + 'border_trans_black': 'smpc 0 0x%x 0x0 0x0 0x0' % POINT_BORDER_W0, + 'border_opaque_black': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_BORDER_W0, OPAQUE_BLACK | 0xfff), + 'border_opaque_black_inline': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_BORDER_W0, OPAQUE_BLACK), + 'border_x_clamp_y': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_BORDER_X_CLAMP_Y_W0, OPAQUE_WHITE), + 'clamp_x_border_y': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_CLAMP_X_BORDER_Y_W0, OPAQUE_WHITE), + 'border_c_max0': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_BORDER_W0, OPAQUE_WHITE), + 'border_array': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_BORDER_W0, OPAQUE_WHITE), + 'clamp_ignored_reg_border': 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_CLAMP_W0, REGISTER_BORDER | 0xfff), + 'bilinear_border_white': 'smpc 0 0x%x 0x0 0x%x 0x%x' % (BILINEAR_BORDER_W0, BILINEAR_W2, OPAQUE_WHITE), + } + for name, want_line in expected_smpc.items(): + pipe = pipeline(name) + ps = pipe.hlsl_ps() + assert 'SamplerComparisonState q0 : register(s0);' in ps, (name, ps) + assert ps.count('.SampleCmpLevelZero(q0,') == 4, (name, ps) + got_line = manifest_sampler(pipe) + assert got_line == want_line, (name, got_line, want_line) + + # Standalone pixel_aot.comparison_sampler_state default (allow_border=False) keeps refusing CLAMP_BORDER. + for w0 in (POINT_BORDER_W0, POINT_BORDER_X_CLAMP_Y_W0, POINT_CLAMP_X_BORDER_Y_W0): + try: + P.comparison_sampler_state((w0, 0, 0, OPAQUE_WHITE)) + except ValueError as error: + assert 'CLAMP_LAST_TEXEL in X and Y' in str(error), error + else: + raise AssertionError('standalone pixel_aot accepted CLAMP_BORDER: %#x' % w0) + + # Refused sampler configurations in gfx2hlsl. + refusals = ( + ('refuse_reg_border_xy', 'register border color'), + ('refuse_reg_border_x', 'register border color'), + ('refuse_reg_border_y', 'register border color'), + ('refuse_half_border_x', 'CLAMP_LAST_TEXEL or CLAMP_BORDER'), + ('refuse_mirror_once_border_y', 'CLAMP_LAST_TEXEL or CLAMP_BORDER'), + ('refuse_mirror_once_x', 'CLAMP_LAST_TEXEL or CLAMP_BORDER'), + ('refuse_mirror_y', 'CLAMP_LAST_TEXEL or CLAMP_BORDER'), + ('refuse_w3_reserved', 'word 3 bits 12-29'), + ) + for name, msg in refusals: + try: + pipeline(name).hlsl_ps() + except G.Unsupported as error: + assert msg in str(error), (name, str(error)) + else: + raise AssertionError('%s was accepted' % name) + print('controls: CLAMP_BORDER + fixed border colors accepted; register border, half-border and wrap/mirror refused') + + +def check_binary(llvm_mc): + for name, (src, recorded) in FIXTURES.items(): + built = assemble(llvm_mc, src) + if built != recorded: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), recorded.hex())) + print('fixture words match llvm-mc (%d programs)' % len(FIXTURES)) + + +def check_draw(dxc, renderer, adapter, fxc=None): + # 2x2 R32_FLOAT depths in startup_image_3d.cpp: (0,0)=0.125, (1,0)=0.250, (0,1)=0.375, (1,1)=0.500. + draw_cases = ( + # Point border_white (border=1.0): ref=0.75 -> in-bounds (1,1)=0.500 fails (0), -X/+X/+Y border=1.0 pass (1). + ('border_white', '0.75', f32_hex(0.0, 1.0, 1.0, 1.0)), + # Same shader at ref=0.25 -> in-bounds (1,1)=0.500 passes (1), and all three border probes also pass (1). + ('border_white', '0.25', f32_hex(1.0, 1.0, 1.0, 1.0)), + # Point border_trans_black & border_opaque_black (border=0.0): ref=0.0625 -> in-bounds passes (1), borders fail (0). + ('border_trans_black', '0.0625', f32_hex(1.0, 0.0, 0.0, 0.0)), + ('border_opaque_black', '0.0625', f32_hex(1.0, 0.0, 0.0, 0.0)), + ('border_opaque_black_inline', '0.0625', f32_hex(1.0, 0.0, 0.0, 0.0)), + # Mixed X/Y addressing with OPAQUE_WHITE at ref=0.75: only the border axis returns 1.0 out of bounds. + ('border_x_clamp_y', '0.75', f32_hex(0.0, 1.0, 1.0, 0.0)), + ('clamp_x_border_y', '0.75', f32_hex(0.0, 0.0, 0.0, 1.0)), + # Implicit image_sample_c with MAX_LOD 0 and OPAQUE_WHITE border. + ('border_c_max0', '0.75', f32_hex(0.0, 1.0, 1.0, 1.0)), + # Bilinear PCF on 2x2 with OPAQUE_WHITE: (0.5,0.5)=0, (0,0.25)=0.5, (0.25,0)=0.5, (0,0)=0.75 at ref=0.75; + # at ref=0.3125, two of four interior texels (0.375, 0.500) pass -> (0.5, 0.5, 0.5, 0.75). + ('bilinear_border_white', '0.75', f32_hex(0.0, 0.5, 0.5, 0.75)), + ('bilinear_border_white', '0.3125', f32_hex(0.5, 0.5, 0.5, 0.75)), + # Ordinary RGBA sample at (1.25, 0.25) separates OPAQUE_BLACK (0,0,0,1) from TRANS_BLACK (0,0,0,0) and OPAQUE_WHITE. + ('rgba_trans_black', '0', f32_hex(0.0, 0.0, 0.0, 0.0)), + ('rgba_opaque_black', '0', f32_hex(0.0, 0.0, 0.0, 1.0)), + ('rgba_opaque_white', '0', f32_hex(1.0, 1.0, 1.0, 1.0)), + ) + shader_names = sorted({name for name, _, _ in draw_cases}) + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + + pipes = {name: pipeline(name) for name in shader_names} + samplers = {name: manifest_sampler(pipes[name]) for name in shader_names} + + with tempfile.TemporaryDirectory() as tmp, CompileQueue() as queue: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + queue.submit(compile_hlsl, compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + for name in shader_names: + queue.submit(compile_hlsl, compiler, kind, pipes[name].hlsl_ps(), + '%s_%s' % (name, kind), ps_profile, directory) + + for kind, compiler, vs_profile, ps_profile in compilers: + vs = queue.call(compile_hlsl, compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + cso = { + name: queue.call(compile_hlsl, compiler, kind, pipes[name].hlsl_ps(), + '%s_%s' % (name, kind), ps_profile, directory) + for name in shader_names + } + for name, ref, expected in draw_cases: + cmd = [renderer, adapter, '--startup-image-2d', str(vs), str(cso[name]), ref, expected, samplers[name]] + run = subprocess.run(cmd, capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + if run.returncode != 0: + raise AssertionError('%s %s ref=%s failed:\n%s\n%s' + % (kind, name, ref, run.stdout, run.stderr)) + print('%s %s ref=%s: %s' % (kind, name, ref, expected), flush=True) + + # Negative controls on the GPU: dropping w3 border color (the pre-fix TRANSPARENT_BLACK behavior), + # forcing CLAMP_LAST_TEXEL, swapping X/Y addressing, and dropping OPAQUE_BLACK alpha must all fail. + mutants = ( + ('dropped_w3_border_color', 'border_white', '0.75', f32_hex(0.0, 1.0, 1.0, 1.0), + samplers['border_trans_black'], f32_hex(0.0, 0.0, 0.0, 0.0)), + ('forced_clamp_last_texel', 'border_white', '0.75', f32_hex(0.0, 1.0, 1.0, 1.0), + 'smpc 0 0x%x 0x0 0x0 0x%x' % (POINT_CLAMP_W0, OPAQUE_WHITE), f32_hex(0.0, 0.0, 0.0, 0.0)), + ('swapped_xy_addressing', 'border_x_clamp_y', '0.75', f32_hex(0.0, 1.0, 1.0, 0.0), + samplers['clamp_x_border_y'], f32_hex(0.0, 0.0, 0.0, 1.0)), + ('opaque_black_as_trans_black', 'rgba_opaque_black', '0', f32_hex(0.0, 0.0, 0.0, 1.0), + samplers['rgba_trans_black'], f32_hex(0.0, 0.0, 0.0, 0.0)), + ) + for label, name, ref, expected, bad_sampler, want_actual in mutants: + cmd = [renderer, adapter, '--startup-image-2d', str(vs), str(cso[name]), ref, expected, bad_sampler] + failed = subprocess.run(cmd, capture_output=True, text=True) + if failed.returncode == 0 or ('actual=' + want_actual) not in failed.stderr: + raise AssertionError('%s mutant %s did not produce %s:\n%s\n%s' + % (kind, label, want_actual, failed.stdout, failed.stderr)) + print('%s mutant %s caught (%s)' % (kind, label, want_actual), flush=True) + + +def main(): + if len(sys.argv) == 1: + controls() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + check_binary(sys.argv[2]) + elif len(sys.argv) in (5, 6) and sys.argv[1] == 'draw': + controls() + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_sampler_comparison_check.cpp b/tests/startup_sampler_comparison_check.cpp index dd57e8377..5608401c6 100644 --- a/tests/startup_sampler_comparison_check.cpp +++ b/tests/startup_sampler_comparison_check.cpp @@ -76,6 +76,25 @@ int main() expect(bounded[0].Filter == bounded[1].Filter && bounded[0].AddressU == bounded[1].AddressU, "smpl decodes the other fields like smp", bounded[0].Filter, bounded[1].Filter); } + // Comparison samplers with CLAMP_BORDER (6) on either axis and fixed BORDER_COLOR_TYPE 0..2 in word 3 bits 31:30. + const D3D12_STATIC_BORDER_COLOR border_colors[3] = { + D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK, + D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK, + D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE, + }; + for (unsigned btype = 0; btype < 3; ++btype) { + char line[96]; + const unsigned w0 = 6u | 2u << 3 | 1u << 12 | 1u << 27; + const unsigned w3 = btype << 30; + std::snprintf(line, sizeof(line), "smpc 0 0x%x 0x0 0x0 0x%x", w0, w3); + x2w_startup::TranslatedSamplers border_smp; + expect(border_smp.read_manifest_line(line) && border_smp.statics.size() == 1, "border smpc parsed", btype); + const auto decoded = x2w_startup::decode_statics(border_smp); + if (decoded.size() != 1) continue; + expect(decoded[0].AddressU == D3D12_TEXTURE_ADDRESS_MODE_BORDER && + decoded[0].AddressV == D3D12_TEXTURE_ADDRESS_MODE_CLAMP, "per-axis border/clamp addressing", btype); + expect(decoded[0].BorderColor == border_colors[btype], "comparison border color", decoded[0].BorderColor, border_colors[btype]); + } std::printf(failures ? "startup_sampler_comparison failed\n" : "startup_sampler_comparison ok\n"); return failures ? 1 : 0; } diff --git a/tests/startup_translated_sampler_bindings_check.cpp b/tests/startup_translated_sampler_bindings_check.cpp index 4d0c6766a..5bbec00df 100644 --- a/tests/startup_translated_sampler_bindings_check.cpp +++ b/tests/startup_translated_sampler_bindings_check.cpp @@ -202,8 +202,9 @@ int main(int argc, char** argv) decoded("anisotropic mag", {0, 0, 2u << 20, 0}, wrap, wrap, wrap, anisotropic, 1); decoded("anisotropic min", {0, 0, 2u << 22, 0}, wrap, wrap, wrap, anisotropic, 1); decoded("anisotropic mag 3, ratio 4", {word0(0, 0, 0, 4), 0, 3u << 20, 0}, wrap, wrap, wrap, anisotropic, 16); - // Bits the decoder does not read: PERF_MIP and PERF_Z in word 1, word 3, Z_FILTER and the high bits of - // words 0 and 2. MIN_LOD and MAX_LOD are both 0xfff, 4095 / 256, for a table entry. + // Bits the decoder does not read: PERF_MIP and PERF_Z in word 1, word 3 bits 29:0 (and BORDER_COLOR_TYPE 3 + // falls back to transparent black), Z_FILTER and the high bits of words 0 and 2. MIN_LOD and MAX_LOD are + // both 0xfff, 4095 / 256, for a table entry. decoded("ignored bits", {word0(2, 1, 3, 0) | 0xfffff000u, ~0u, 1u << 22 | 3u << 24 | 0xf0000000u | 0xfffffu, ~0u}, clamp, mirror, mirror_once, min_linear, 1, 7, 15.99609375f, 15.99609375f); // Word 1: MIN_LOD bits 11:0 and MAX_LOD bits 23:12, unsigned 4.8 fixed point. Each field is read on its @@ -219,6 +220,33 @@ int main(int argc, char** argv) decoded("lod with perf bits", {0, 0xff000000u | 0x080u | 0x300u << 12, 0, 0}, wrap, wrap, wrap, point, 1, 0, 0.5f, 3.0f); + // Word 3 bits 31:30 (BORDER_COLOR_TYPE): 0 = TRANS_BLACK, 1 = OPAQUE_BLACK, 2 = OPAQUE_WHITE, and 3 = REGISTER + // (falls back to TRANS_BLACK). BORDER_COLOR_PTR in bits 11:0 does not alter the fixed border colors. + { + const struct { + const char* label; + std::uint32_t w3; + unsigned static_border; + float rgba[4]; + } border_cases[] = { + {"border trans black", 0u << 30 | 0xfffu, 0, {0.0f, 0.0f, 0.0f, 0.0f}}, + {"border opaque black", 1u << 30 | 0xfffu, 1, {0.0f, 0.0f, 0.0f, 1.0f}}, + {"border opaque white", 2u << 30 | 0xfffu, 2, {1.0f, 1.0f, 1.0f, 1.0f}}, + {"border register fallback", 3u << 30 | 0xfffu, 0, {0.0f, 0.0f, 0.0f, 0.0f}}, + }; + for (const auto& bc : border_cases) { + ++cases; + const SamplerWords words{word0(6, 6, 6, 0), 0, 0, bc.w3}; + const D3D12_STATIC_SAMPLER_DESC s = decode_sampler(words, 2); + expect(bc.label, "static BorderColor", s.BorderColor, bc.static_border); + expect(bc.label, "static AddressU", s.AddressU, border); + expect(bc.label, "static AddressV", s.AddressV, border); + const D3D12_SAMPLER_DESC d = dynamic_sampler(words); + for (unsigned ch = 0; ch < 4; ++ch) + if (d.BorderColor[ch] != bc.rgba[ch]) fail(bc.label, "dynamic BorderColor", unsigned(d.BorderColor[ch]), unsigned(bc.rgba[ch])); + } + } + // The border sampler a missing table entry uses: border on all three axes, point, transparent black. { ++cases; diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 652dee1b8..b33fdd6dd 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -319,8 +319,18 @@ def sample_offset_arg(reg, vector, sample_dest, known_ssa_bits): # with anisotropy refused and no partially resident texture, none of them changes the result. LEVEL_ZERO_IGNORED_W2 = 0x7 +# SQ_TEX_CLAMP modes accepted when the caller binds per-axis D3D12 addressing (2 = CLAMP_LAST_TEXEL, 6 = CLAMP_BORDER). +COMPARISON_ADDRESS_MODES = {2: "clamp", 6: "border"} +# SQ_IMG_SAMP_WORD3 bits 31:30 (BORDER_COLOR_TYPE): fixed border colors matching D3D12_STATIC_BORDER_COLOR 0..2. +# Value 3 (SQ_TEX_BORDER_COLOR_REGISTER, indexed via BORDER_COLOR_PTR in bits 11:0) has no static-sampler representation. +STATIC_BORDER_COLORS = { + 0: ("transparent_black", 0), + 1: ("opaque_black", 1), + 2: ("opaque_white", 2), +} + -def comparison_sampler_state(words, level_zero=False): +def comparison_sampler_state(words, level_zero=False, allow_border=False): """Decode the sampler descriptor fields that change an image_sample_c_lz result on a 2D texture. level_zero=True is for a caller that samples explicitly at level zero (the startup translator's c_lz form): @@ -328,11 +338,18 @@ def comparison_sampler_state(words, level_zero=False): only on anisotropic filtering (refused above) and BLEND_ZERO_PRT only on partially resident textures. Bit 31 stays refused. The default keeps the strict check the pixel AOT path is verified against. + allow_border=True is for a caller whose runtime binds per-axis addressing and D3D12_STATIC_BORDER_COLOR from the + sampler words (tools/startup/gfx2hlsl.py via smpc and src/startup_stubs/translated_sampler_bindings.h). CLAMP_X and + CLAMP_Y may then be CLAMP_LAST_TEXEL (2) or CLAMP_BORDER (6); half-border, mirror-once-border and wrap/mirror modes + stay refused. When either axis uses CLAMP_BORDER, word 3 bits 31:30 (BORDER_COLOR_TYPE) must be TRANS_BLACK (0), + OPAQUE_BLACK (1) or OPAQUE_WHITE (2); REGISTER (3) is refused. + Field positions are those of SQ_IMG_SAMP_WORD0..3 (registers 0x8F30..0x8F3C in Mesa src/amd/registers/gfx10-rsrc.json; enum values in the Linux navi10_enum.h). Not read, because the accepted profile makes them irrelevant: CLAMP_Z, DISABLE_CUBE_WRAP and Z_FILTER (2D only), ANISO_THRESHOLD and ANISO_BIAS (ratio 1), word 0 bit 31 (degamma control; no effect on a float depth texel), MAX_LOD, PERF_MIP and PERF_Z (LOD 0 only), and - BORDER_COLOR_PTR and BORDER_COLOR_TYPE (no border addressing). Any other non-zero field is refused, + BORDER_COLOR_PTR (only indexed when BORDER_COLOR_TYPE is REGISTER; BORDER_COLOR_TYPE itself is ignored when neither + axis uses CLAMP_BORDER). Any other non-zero field is refused, including word 2 bits 28-31 (MIP_POINT_PRECLAMP, ANISO_OVERRIDE, BLEND_ZERO_PRT) and word 3 bits 12-29, which gfx10 leaves unnamed (bit 29 is UPGRADED_DEPTH on GFX8). @@ -345,7 +362,11 @@ def comparison_sampler_state(words, level_zero=False): contract where the texel-space position is a multiple of 1/64, so the rounding is exact on both sides. """ w0, w1, w2, w3 = words - if (w0 & 7, (w0 >> 3) & 7) != (2, 2): + ux, uy = w0 & 7, (w0 >> 3) & 7 + if allow_border: + if ux not in COMPARISON_ADDRESS_MODES or uy not in COMPARISON_ADDRESS_MODES: + raise ValueError("Comparison sampling requires CLAMP_LAST_TEXEL or CLAMP_BORDER in X and Y") + elif (ux, uy) != (2, 2): raise ValueError("Comparison sampling requires CLAMP_LAST_TEXEL in X and Y") if (w0 >> 9) & 7: raise ValueError("Comparison sampling with anisotropy is not supported") @@ -372,9 +393,16 @@ def comparison_sampler_state(words, level_zero=False): if trunc_coord != (filter_name == "point"): raise ValueError(f"Comparison sampling with {filter_name} filtering requires TRUNC_COORD " f"{int(filter_name == 'point')}") - return {"compare": DEPTH_COMPARE[func], "d3d12_comparison_func": func + 1, - "filter": filter_name, "d3d12_filter": d3d_filter, "address": "clamp", - "trunc_coord": trunc_coord} + address = "clamp" if (ux, uy) == (2, 2) else (COMPARISON_ADDRESS_MODES[ux], COMPARISON_ADDRESS_MODES[uy]) + state = {"compare": DEPTH_COMPARE[func], "d3d12_comparison_func": func + 1, + "filter": filter_name, "d3d12_filter": d3d_filter, "address": address, + "trunc_coord": trunc_coord} + if 6 in (ux, uy): + border_type = (w3 >> 30) & 3 + if border_type not in STATIC_BORDER_COLORS: + raise ValueError("Comparison sampling with register border color is not supported") + state["border_color"], state["d3d12_static_border_color"] = STATIC_BORDER_COLORS[border_type] + return state def comparison_resources(state): diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index e94ec7c71..6aaaa60bf 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1698,6 +1698,7 @@ def set_s(self, n, expr, sym=None, scc=None, uniform=None): if getattr(self, 'since_join', None) is not None: (self.since_join.add if uniform else self.since_join.discard)(n) getattr(self, 'masks', set()).discard(n) # unit probes build a Stage without __init__ + getattr(self, 'float_const_s', {}).pop(n, None) if sym is not None: self.sym[n] = sym if sym[0] != 'const': @@ -1738,7 +1739,9 @@ def heap_sampler(self, tok): def const_words(self, tok): r = reg_range(tok) - words = [self.is_const(n) for n in range(r[1], r[2] + 1)] + fconst = getattr(self, 'float_const_s', {}) + words = [self.is_const(n) if self.is_const(n) is not None else fconst.get(n) + for n in range(r[1], r[2] + 1)] return None if any(w is None for w in words) else words def execz_refusals(self): @@ -2125,6 +2128,7 @@ def translate(self): self.low16_only_v = set() # VGPRs whose upper 16 bits are undefined after odd-dmask d16 image_load self.pinned_low16_v = set() # low16_only_v live across basic-block boundaries self.whole_read_v = set() # VGPRs read outside a proven low-16-bit consumer + self.float_const_s = {} # SGPR -> 32-bit pattern from s_mov_b32 of an inline float constant self.has_branches = bool(targets) self.entry_table_pointers = { reg: sym[1] for reg, sym in init_sym.items() @@ -2212,6 +2216,9 @@ def translate(self): if (self.sym.get(reg) or ('',))[0] == 'const'} for reg in self.unjoined(off, last_write, consts): del self.sym[reg] + fconsts = (join_writes.get(off, set()) | (clobber & every_sgpr)) & set(self.float_const_s) + for reg in self.unjoined(off, last_write, fconsts): + self.float_const_s.pop(reg, None) self.defined_uniform_s = set(kept_u) | { k for k, v in self.sym.items() if isinstance(k, int) and v and ( @@ -2236,6 +2243,12 @@ def translate(self): dests = scalar_destinations(name, asm) written |= every_sgpr if 'any' in dests else dests last_write.update(dict.fromkeys(every_sgpr if 'any' in dests else dests, off)) + self._pre_fconst = dict(self.float_const_s) + if 'any' in dests: + self.float_const_s.clear() + else: + for reg in dests: + self.float_const_s.pop(reg, None) try: if off in refused: raise Unsupported(refused[off]) @@ -3037,7 +3050,10 @@ def src_sym(t): def known(tok): r = reg_range(tok) if r and r[0] == 's' and r[1] == r[2]: - return self.is_const(r[1]) + c = self.is_const(r[1]) + return c if c is not None else getattr(self, '_pre_fconst', getattr(self, 'float_const_s', {})).get(r[1]) + if tok in FLOATS: + return fbits(FLOATS[tok]) if re.fullmatch(r'-?(0x[0-9a-f]+|\d+)', tok) and tok not in FLOATS: return int(tok, 0) & 0xffffffff return None @@ -3066,6 +3082,10 @@ def known(tok): high_uniform = (self.tracks_uniformity() and high != d and self.uniform_source(high_source)) self.set_s(d, expr, scc=None if lane_complement else scc) + if base == 's_mov_b32' and srcs[0] in FLOATS and not is_mask: + # Keep the runtime SGPR assignment intact while letting const_words() read inline float patterns + # such as 0x40000000 (OPAQUE_BLACK, encoded as inline 244 / '2.0'). + self.__dict__.setdefault('float_const_s', {})[d] = fbits(FLOATS[srcs[0]]) if lane_complement: # The guest SCC is (the whole complemented word != 0), which the bits of every other lane decide (an # idle lane's bit is set). It is not emitted: translate() refuses a program that can read it. @@ -4199,7 +4219,7 @@ def image_compare(self, ops, mods, how): raise Unsupported('%s with a sampler that is not constant' % base) import pixel_aot try: - pixel_aot.comparison_sampler_state(tuple(words), level_zero=how == 'c_lz') + pixel_aot.comparison_sampler_state(tuple(words), level_zero=how == 'c_lz', allow_border=True) except ValueError as error: raise Unsupported('%s sampler: %s' % (base, error)) tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2da' if array else 'tex2d') From e9ae884f81fb72ba54596d1a4f14e1d2ad8e91d7 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:51:54 -0700 Subject: [PATCH 166/232] d3d12: forward ClearDepthStencilView on console command lists (#2451) * d3d12: forward ClearDepthStencilView on console command lists Implement list slot 51 (ClearDepthStencilView) in d3d12_xs.dll. Resolves the descriptor through the DSV shadow records with creation map fallback, validates readable rect bounds and non-zero flags, checks against read-only DSV plane flags, and transitions the depth target to D3D12_RESOURCE_STATE_DEPTH_WRITE before forwarding to the desktop graphics command list. Adds synthetic fixture tests/startup_clear_depth_stencil.cpp checking WARP and hardware backends, verifying valid depth clears with and without rects, read-only DSV refusal, non-DSV (RTV) handle rejection, and empty descriptor handling. # Conflicts: # CMakeLists.txt * d3d12: document why slot 51 is set in both table paths Add a one-line reason for setting tables[list_kind][51] directly while siblings 52-55 only write list_typed: the ClearDepthStencilView fixture calls list vtable[51] directly via invoke(), so the slot must be reachable through both the typed dispatch and the generic table path. Co-Authored-By: Claude Code --------- Co-authored-by: Claude Code --- CMakeLists.txt | 10 + src/startup_stubs/d3d12_xs_device.cpp | 78 +++++- tests/startup_clear_depth_stencil.cpp | 331 ++++++++++++++++++++++++++ 3 files changed, 418 insertions(+), 1 deletion(-) create mode 100644 tests/startup_clear_depth_stencil.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 989e0ed27..d50ed4736 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1511,6 +1511,16 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") endforeach() +# List slot 51: ClearDepthStencilView on a console command list, read back on the desktop device. +add_executable(startup_clear_depth_stencil tests/startup_clear_depth_stencil.cpp) +target_compile_features(startup_clear_depth_stencil PRIVATE cxx_std_17) +target_link_libraries(startup_clear_depth_stencil PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_clear_depth_stencil_${backend} COMMAND startup_clear_depth_stencil ${backend}) + set_tests_properties(startup_clear_depth_stencil_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=1") +endforeach() + add_executable(startup_nv12_draw tests/startup_nv12_draw.cpp tests/desktop_gpu.cpp) target_compile_features(startup_nv12_draw PRIVATE cxx_std_17) target_include_directories(startup_nv12_draw PRIVATE src) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index d67871bf2..b5b79f444 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3074,7 +3074,7 @@ ResolvedView resolve_view(u64 handle, int slot) ReleaseSRWLockShared(¬e_lock); } if (!known) { - if (slot == 20) out.resource = view_target(handle, slot); + if (slot == 20 || slot == 21) out.resource = view_target(handle, slot); return out; } if (static_cast(record.slot) != slot) { @@ -3094,6 +3094,77 @@ bool format_has_stencil(DXGI_FORMAT format) return format == DXGI_FORMAT_D24_UNORM_S8_UINT || format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT || format == DXGI_FORMAT_R24G8_TYPELESS || format == DXGI_FORMAT_R32G8X24_TYPELESS; } +// List slot 51 (desktop 47 + 4), ClearDepthStencilView(view, flags, depth, stencil, rect count, rects). Desktop +// resources rest in COMMON here, so the target is moved to DEPTH_WRITE around the clear. The view is +// read from its shadow record, as OMSetRenderTargets does, so a descriptor the title copied clears the +// resource it now holds; a handle with no record falls back to the creation-time map. +void __stdcall list_clear_depth_stencil(Wrapper* self, u64 handle, D3D12_CLEAR_FLAGS flags, float depth, UINT8 stencil, + UINT rect_count, const D3D12_RECT* rects) +{ + if (!self || !self->own().list_open) return; + Timed timed(time_list); + InterlockedIncrement(&draw_calls_seen); + InterlockedIncrement64(&list_slot_calls[51]); + InterlockedIncrement64(&list_slot_census[51]); + if (trace_frame_active) { + const auto ret = reinterpret_cast(_ReturnAddress()) - reinterpret_cast(GetModuleHandleW(nullptr)); + log("x2w-frame tid=%lu list=%llx slot51(0x%llx, 0x%x, %.3f, %u | %u, %p) ret=+0x%llx", + GetCurrentThreadId(), reinterpret_cast(self), handle, static_cast(flags), + depth, static_cast(stencil), rect_count, static_cast(rects), ret); + } + const u64 desktop = desktop_cpu_handle(handle); + const ResolvedView view = resolve_view(desktop, 21); + ID3D12Resource* target = view.resource; + static LONG logged; + if (first_calls(logged, 4)) + log("x2w-render ClearDepthStencilView view=0x%llx target=%p flags=0x%x depth=%.3f stencil=%u rects=%u", handle, + static_cast(target), static_cast(flags), depth, static_cast(stencil), rect_count); + if (!target) { + InterlockedIncrement(&render_target_unresolved); + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 ClearDepthStencilView skipped: view 0x%llx is %s", handle, + view.wrong_kind ? "not a depth stencil view" + : view.skipped ? "a skipped depth stencil view" : "not a known depth stencil view"); + return; + } + if (!(flags & (D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL))) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 ClearDepthStencilView skipped: zero clear flags 0x%x", static_cast(flags)); + return; + } + if ((flags & D3D12_CLEAR_FLAG_DEPTH) && (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_DEPTH)) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 ClearDepthStencilView skipped: depth clear requested on read-only depth view 0x%llx", handle); + return; + } + if ((flags & D3D12_CLEAR_FLAG_STENCIL) && (view.dsv_flags & D3D12_DSV_FLAG_READ_ONLY_STENCIL)) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 ClearDepthStencilView skipped: stencil clear requested on read-only stencil view 0x%llx", handle); + return; + } + const DXGI_FORMAT format = view_format_of(desktop, target); + if ((flags & D3D12_CLEAR_FLAG_STENCIL) && !format_has_stencil(format)) { + flags = static_cast(flags & ~D3D12_CLEAR_FLAG_STENCIL); + if (!flags) return; + } + if (rect_count && !x2w_local::readable(rects, std::size_t{rect_count} * sizeof(D3D12_RECT))) { + static LONG refused; + if (first_calls(refused, 6)) + log("x2w-d3d12 ClearDepthStencilView skipped: unreadable rects array (%u rects at %p)", rect_count, static_cast(rects)); + return; + } + auto* list = static_cast(self->own().real); + require_state(self, target, D3D12_RESOURCE_STATE_DEPTH_WRITE); + const auto red_sample = red_producers().before(self, list, target, "clear-dsv", 0, 0); + list->ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(desktop)}, flags, depth, stencil, + rect_count, rect_count ? rects : nullptr); + red_producers().after(self, red_sample); + InterlockedIncrement(&render_clears); +} // List slot 52 (desktop 48 + 4), ClearRenderTargetView(view, colour, rect count, rects). Desktop // resources rest in COMMON here, so the target is moved to RENDER_TARGET around the clear. The view is // read from its shadow record, as OMSetRenderTargets does, so a descriptor the title copied clears the @@ -5578,6 +5649,11 @@ void build_tables() } if (render_mode()) { list_typed[9] = reinterpret_cast(&list_close); + list_typed[51] = reinterpret_cast(&list_clear_depth_stencil); + // Slot 51 is also entered through the generic invoke() path (the fixture calls list vtable[51] + // directly), so it must be present in tables[list_kind] as well as list_typed; siblings 52-55 + // are only reached through list_typed and do not set both. + tables[list_kind][51] = reinterpret_cast(&list_clear_depth_stencil); list_typed[52] = reinterpret_cast(&list_clear_target); list_typed[15] = reinterpret_cast(&list_copy_buffer_region); list_typed[17] = reinterpret_cast(&list_copy_resource); diff --git a/tests/startup_clear_depth_stencil.cpp b/tests/startup_clear_depth_stencil.cpp new file mode 100644 index 000000000..50eadb698 --- /dev/null +++ b/tests/startup_clear_depth_stencil.cpp @@ -0,0 +1,331 @@ +// ClearDepthStencilView on a console command list (list slot 51, device slot 21). +// +// startup_clear_depth_stencil (X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 X2W_D3D12_DEBUG=1) +// +// Through D3D12XboxCreateDevice the probe makes D32_FLOAT depth targets and records, on one list: +// +// A 1x1 D32_FLOAT ClearDepthStencilView(0.25f, DEPTH) read back: 0.25f (0x3e800000) +// B 2x2 D32_FLOAT cleared 0.75f with rect covering surface, +// then a clear with a read-only DSV (refused, no overwrite) +// read back: 0.75f (0x3f400000) +// C 1x1 RGBA8 RTV a clear through an RTV handle (wrong kind, refused, counted) +// - Empty handle a clear through a CPU handle that holds no view (refused, counted) +// - Zero flags a clear with flags == 0 (refused, no-op) +// +// The desktop device must not be removed and the debug layer must report no errors. +// +// Exit codes: 0 pass, 77 no physical adapter, other values name the failing step. +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) void x2w_d3d12_render_target_stats(unsigned* binds, unsigned* unresolved); + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0, Word f = 0, Word g = 0) +{ + using Slot = Word (WINAPI*)(void*, Word, Word, Word, Word, Word, Word, Word); + return reinterpret_cast((*static_cast(object))[index])(object, a, b, c, d, e, f, g); +} +bool ok(Word hr) { return SUCCEEDED(static_cast(hr)); } + +using ClearDepthStencilFn = void (WINAPI*)(void* list, D3D12_CPU_DESCRIPTOR_HANDLE handle, D3D12_CLEAR_FLAGS flags, + FLOAT depth, UINT8 stencil, UINT rect_count, const D3D12_RECT* rects); +void clear_dsv(void* list, D3D12_CPU_DESCRIPTOR_HANDLE handle, D3D12_CLEAR_FLAGS flags, + FLOAT depth, UINT8 stencil, UINT rect_count, const D3D12_RECT* rects) +{ + auto fn = reinterpret_cast((*static_cast(list))[51]); + fn(list, handle, flags, depth, stencil, rect_count, rects); +} + +void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* res, D3D12_RESOURCE_STATES from, D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition.pResource = res; + barrier.Transition.StateBefore = from; + barrier.Transition.StateAfter = to; + barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + list->ResourceBarrier(1, &barrier); +} + +unsigned unresolved_now() +{ + unsigned binds = 0, unresolved = 0; + x2w_d3d12_render_target_stats(&binds, &unresolved); + return unresolved; +} + +std::atomic debug_error_count{0}; +void WINAPI on_message(D3D12_MESSAGE_CATEGORY, D3D12_MESSAGE_SEVERITY severity, D3D12_MESSAGE_ID, LPCSTR text, void*) +{ + if (severity > D3D12_MESSAGE_SEVERITY_ERROR) return; + if (++debug_error_count <= 12) std::printf("debug layer: %.300s\n", text); +} + +struct Probe { + ComPtr desktop; + void* queue = nullptr; + void* fence = nullptr; + Word fence_value = 0; + + bool submit(void* list) + { + void* lists[] = {list}; + invoke(queue, 10, 1, arg(lists)); + if (!ok(invoke(queue, 14, arg(fence), ++fence_value))) return false; + const auto deadline = GetTickCount64() + 10000; + while (invoke(fence, 8) < fence_value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; + } + + DWORD cookie = 0; + ComPtr queue1; + bool watch() + { + return SUCCEEDED(desktop.As(&queue1)) && + SUCCEEDED(queue1->RegisterMessageCallback(on_message, D3D12_MESSAGE_CALLBACK_FLAG_NONE, nullptr, &cookie)); + } + + bool readback_depth(ID3D12Resource* target, UINT width, UINT height, std::vector& out) + { + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 total = 0; + const auto desc = target->GetDesc(); + desktop->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + ComPtr readback; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&readback)))) + return false; + + D3D12_COMMAND_QUEUE_DESC qdesc{}; + ComPtr observer; + ComPtr allocator; + ComPtr copy; + ComPtr done; + if (FAILED(desktop->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&observer))) || + FAILED(desktop->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(desktop->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, IID_PPV_ARGS(©))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))) + return false; + + transition(copy.Get(), target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + copy->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(copy.Get(), target, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + + if (FAILED(copy->Close())) return false; + ID3D12CommandList* lists[] = {copy.Get()}; + observer->ExecuteCommandLists(1, lists); + + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool finished = event && SUCCEEDED(observer->Signal(done.Get(), 1)) && + SUCCEEDED(done->SetEventOnCompletion(1, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + if (!finished) return false; + + void* memory = nullptr; + if (FAILED(readback->Map(0, nullptr, &memory))) return false; + + out.resize(width * height); + for (UINT y = 0; y < height; ++y) { + const auto* row = reinterpret_cast(static_cast(memory) + + footprint.Offset + footprint.Footprint.RowPitch * y); + std::memcpy(&out[y * width], row, width * sizeof(float)); + } + readback->Unmap(0, nullptr); + return true; + } +}; + +bool check_count(const char* name, unsigned& before, unsigned expected_added) +{ + const unsigned now = unresolved_now(); + const bool good = now - before == expected_added; + std::printf("%s: refused +%u (expected +%u)\n", name, now - before, expected_added); + before = now; + return good; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return 2; + ComPtr factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + ComPtr adapter; + if (std::strcmp(argv[1], "hardware") == 0) { + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 3; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (!(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (std::strcmp(argv[1], "warp") != 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 3; + } + DXGI_ADAPTER_DESC adapter_desc{}; + if (FAILED(adapter->GetDesc(&adapter_desc))) return 3; + std::printf("adapter=%ls\n", adapter_desc.Description); + + Probe probe; + std::array parameters{}; + void* device = nullptr; + if (FAILED(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), &device))) return 4; + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&probe.desktop)))) return 4; + + if (!probe.watch()) std::printf("no debug layer message callback: validation not counted\n"); + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto depth_desc = [](UINT w, UINT h) { + return D3D12_RESOURCE_DESC{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, w, h, 1, 1, DXGI_FORMAT_D32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}; + }; + D3D12_CLEAR_VALUE clear_val{}; + clear_val.Format = DXGI_FORMAT_D32_FLOAT; + clear_val.DepthStencil = {1.0f, 0}; + + ComPtr a, b, c; + const D3D12_RESOURCE_DESC desc_a = depth_desc(1, 1); + const D3D12_RESOURCE_DESC desc_b = depth_desc(2, 2); + const D3D12_RESOURCE_DESC desc_c{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 1, 1, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE rtv_clear{DXGI_FORMAT_R8G8B8A8_UNORM, {0, 0, 0, 0}}; + + if (FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc_a, D3D12_RESOURCE_STATE_COMMON, + &clear_val, IID_PPV_ARGS(&a))) || + FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc_b, D3D12_RESOURCE_STATE_COMMON, + &clear_val, IID_PPV_ARGS(&b))) || + FAILED(probe.desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc_c, D3D12_RESOURCE_STATE_COMMON, + &rtv_clear, IID_PPV_ARGS(&c)))) + return 5; + + // DSV heap with 4 descriptors: + // 0: DSV for A (writable) + // 1: DSV for B (writable) + // 2: DSV for B (read-only) + // 3: Empty (unmapped) + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word backing, bytes; + } dsv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 4, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}, + rtv_heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}; + + void* dsv_heap = nullptr; + void* rtv_heap = nullptr; + if (!ok(invoke(device, 14, arg(&dsv_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&dsv_heap))) || + !ok(invoke(device, 14, arg(&rtv_heap_desc), arg(&__uuidof(ID3D12DescriptorHeap)), arg(&rtv_heap)))) + return 6; + + const UINT dsv_stride = probe.desktop->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + const Word dsv_cpu = invoke(dsv_heap, 9); + const Word rtv_cpu = invoke(rtv_heap, 9); + + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_writable{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_NONE, {}}; + const D3D12_DEPTH_STENCIL_VIEW_DESC dsv_readonly{DXGI_FORMAT_D32_FLOAT, D3D12_DSV_DIMENSION_TEXTURE2D, D3D12_DSV_FLAG_READ_ONLY_DEPTH, {}}; + const D3D12_RENDER_TARGET_VIEW_DESC rtv_desc{DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RTV_DIMENSION_TEXTURE2D, {}}; + + // Create DSVs: + // Slot 21: CreateDepthStencilView(resource, desc, dest) + invoke(device, 21, arg(a.Get()), arg(&dsv_writable), dsv_cpu); + invoke(device, 21, arg(b.Get()), arg(&dsv_writable), dsv_cpu + dsv_stride); + invoke(device, 21, arg(b.Get()), arg(&dsv_readonly), dsv_cpu + 2 * dsv_stride); + + // Create RTV: + // Slot 20: CreateRenderTargetView(resource, desc, dest) + invoke(device, 20, arg(c.Get()), arg(&rtv_desc), rtv_cpu); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + const unsigned list_desc[] = {D3D12_COMMAND_LIST_TYPE_DIRECT, 2, 1, 0}; + void *allocator = nullptr, *list = nullptr; + if (!ok(invoke(device, 8, arg(&queue_desc), arg(&__uuidof(ID3D12CommandQueue)), arg(&probe.queue))) || + !ok(invoke(device, 36, 0, 0, arg(&__uuidof(ID3D12Fence)), arg(&probe.fence))) || + !ok(invoke(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, arg(&__uuidof(ID3D12CommandAllocator)), arg(&allocator))) || + !ok(invoke(device, 73, arg(list_desc), arg(allocator), 0, arg(&__uuidof(ID3D12GraphicsCommandList)), arg(&list)))) + return 7; + if (!ok(invoke(list, 139, arg(allocator), 0))) return 8; + + unsigned seen = unresolved_now(); + + // 1. Valid clear of A to depth 0.25f + const D3D12_CPU_DESCRIPTOR_HANDLE handle_a{static_cast(dsv_cpu)}; + clear_dsv(list, handle_a, D3D12_CLEAR_FLAG_DEPTH, 0.25f, 0, 0, nullptr); + if (!check_count("1 valid clear of A to 0.25", seen, 0)) return 10; + + // 2. Valid clear of B to depth 0.75f with rect covering surface + const D3D12_CPU_DESCRIPTOR_HANDLE handle_b{static_cast(dsv_cpu + dsv_stride)}; + const D3D12_RECT whole_b{0, 0, 2, 2}; + clear_dsv(list, handle_b, D3D12_CLEAR_FLAG_DEPTH, 0.75f, 0, 1, &whole_b); + if (!check_count("2 valid clear of B with rect to 0.75", seen, 0)) return 11; + + // 3. Clear with read-only DSV (attempting to clear to 0.125f) -> refused without overwriting B + const D3D12_CPU_DESCRIPTOR_HANDLE handle_b_ro{static_cast(dsv_cpu + 2 * dsv_stride)}; + clear_dsv(list, handle_b_ro, D3D12_CLEAR_FLAG_DEPTH, 0.125f, 0, 0, nullptr); + if (!check_count("3 read-only DSV clear refusal", seen, 0)) return 12; + + // 4. Negative test: RTV handle passed -> wrong kind, refused and counted + const D3D12_CPU_DESCRIPTOR_HANDLE handle_c_rtv{static_cast(rtv_cpu)}; + clear_dsv(list, handle_c_rtv, D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0, 0, nullptr); + if (!check_count("4 RTV handle passed as DSV (wrong kind)", seen, 1)) return 13; + + // 5. Negative test: CPU handle holding no view -> refused and counted + const D3D12_CPU_DESCRIPTOR_HANDLE handle_empty{static_cast(dsv_cpu + 3 * dsv_stride)}; + clear_dsv(list, handle_empty, D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0, 0, nullptr); + if (!check_count("5 empty descriptor handle", seen, 1)) return 14; + + // 6. Negative test: clear flags == 0 -> refused + clear_dsv(list, handle_a, static_cast(0), 0.5f, 0, 0, nullptr); + if (!check_count("6 zero clear flags", seen, 0)) return 15; + + // Close and submit + invoke(list, 9); + if (!probe.submit(list)) return 16; + + // Read back depth values + std::vector values_a, values_b; + if (!probe.readback_depth(a.Get(), 1, 1, values_a)) return 17; + if (!probe.readback_depth(b.Get(), 2, 2, values_b)) return 18; + + std::printf("7 A depth: %.4f (expected 0.2500)\n", values_a[0]); + if (values_a[0] != 0.25f) return 19; + + for (int i = 0; i < 4; ++i) { + std::printf("8 B[%d] depth: %.4f (expected 0.7500)\n", i, values_b[i]); + if (values_b[i] != 0.75f) return 20; + } + + const HRESULT removed = probe.desktop->GetDeviceRemovedReason(); + const unsigned long long errors = debug_error_count.load(); + std::printf("device removed reason: 0x%08lx, debug layer errors: %llu\n", static_cast(removed), + static_cast(errors)); + return removed == S_OK && errors == 0 ? 0 : 70; +} From 11519862e8d6f4d7dfee07e2c546b12d16402776 Mon Sep 17 00:00:00 2001 From: KomaGuy Date: Wed, 25 Nov 2026 23:55:01 +0300 Subject: [PATCH 167/232] pixel_aot: lower 12 integer SDWA forms (bitscan, sat_pk, mul24, co_ci) (#2550) * pixel_aot: lower 12 integer SDWA forms (bitscan, sat_pk, mul24, co_ci) * pixel_aot: enforce GFX10 constant-bus rule on SDWA carry-in and fix co_ci binary fixture --------- Co-authored-by: KomaGuy <265821007+KomaGuy@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 18 +++ tests/form_coverage_check.py | 39 +++++- tests/pixel_aot_check.py | 250 ++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 81 ++++++++++++ 5 files changed, 386 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d50ed4736..e4f59ccd7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9225,6 +9225,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(pixel_aot_sdwa_f16_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_f16_${adapter}.txt") + add_test(NAME pixel_aot_sdwa_int_extra_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-sdwa-int-extra "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_sdwa_int_extra_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_int_extra_${adapter}.txt") add_test(NAME pixel_aot_dpp_extra_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-dpp-extra "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 55b31b2cd..5e0a44784 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15342,3 +15342,21 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_f16_warp|pixel_aot_sdwa ``` Linux controls, `form_coverage_check.check_sdwa_f16_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. + +## Extended 32-bit integer SDWA forms (bit-scan, sat_pk, mul24, carry-in) in pixel_aot + +[The pixel shader translator](../tools/pixel_aot.py) adds 12 integer `SDWA` forms (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): + +- Bit-scan & reverse (4): `v_bfrev_b32_sdwa`, `v_ffbl_b32_sdwa`, `v_ffbh_u32_sdwa`, `v_ffbh_i32_sdwa` +- Saturate-pack (1): `v_sat_pk_u8_i16_sdwa` +- 24-bit integer multiply (4): `v_mul_u32_u24_sdwa`, `v_mul_i32_i24_sdwa`, `v_mul_hi_u32_u24_sdwa`, `v_mul_hi_i32_i24_sdwa` +- Carry-in add/sub/subrev (3): `v_add_co_ci_u32_sdwa`, `v_sub_co_ci_u32_sdwa`, `v_subrev_co_ci_u32_sdwa` + +All 12 extract/sign-extend VGPR or SGPR sources with `BYTE_0..3`, `WORD_0..1`, or `DWORD` and optional `sext()`, place the result via `dst_sel` + `UNUSED_PAD`/`UNUSED_PRESERVE`, and refuse `UNUSED_SEXT`, float modifiers, inline constants, `clamp`, and `omod`. Carry-in forms read and update tracked `vcc`/`vcc_lo` conditions using the full 32-bit carry/borrow before destination placement. + +```powershell +python3 tests/pixel_aot_check.py +ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_int_extra_warp|pixel_aot_sdwa_int_extra_hardware|pixel_aot_binary)$' -V +``` + +Linux controls, `form_coverage_check.check_sdwa_int_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 9ecb93f87..6edf044ac 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -392,7 +392,7 @@ def check_shader_records(): sop2_scalar_alu_forms = {("SOP2", op) for op in pixel.SCALAR_ALU_SOP2_OPS} rejected_forms = { "s_or_saveexec_b64", "s_andn2_saveexec_b64", - "v_mul_i32_i24_sdwa", + "v_cvt_pkrtz_f16_f32_sdwa", "v_cvt_pk_u8_f32", "v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", "s_lshl0_add_u32", "s_lshl5_add_u32", @@ -1534,6 +1534,42 @@ def check_sdwa_f16_forms(): pixel.ACCEPTED.update(saved) +def check_sdwa_int_extra_forms(): + """The 12 extended integer SDWA forms (bit-scan/reverse, sat_pk_u8_i16, 24-bit multiply, and + carry-in add/sub/subrev) count as covered once the translator accepts their fixtures.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for body in pixel.SDWA_INT_EXTRA_PROGRAMS.values(): + pixel.translate_int(pixel.uncompressed_export(body)) + ops = ( + "v_bfrev_b32_sdwa", "v_ffbl_b32_sdwa", "v_ffbh_u32_sdwa", "v_ffbh_i32_sdwa", + "v_sat_pk_u8_i16_sdwa", + "v_mul_u32_u24_sdwa", "v_mul_i32_i24_sdwa", "v_mul_hi_u32_u24_sdwa", "v_mul_hi_i32_i24_sdwa", + "v_add_co_ci_u32_sdwa", "v_sub_co_ci_u32_sdwa", "v_subrev_co_ci_u32_sdwa", + ) + forms = {("SDWA", op) for op in ops} + assert len(forms) == 12 + neighbours = { + ("SDWA", "v_cndmask_b32_sdwa"), ("SDWA", "v_cvt_i32_f32_sdwa"), + ("SDWA", "v_cvt_u32_f32_sdwa"), ("SDWA", "v_cvt_pkrtz_f16_f32_sdwa"), + ("SDWA", "v_frexp_exp_i32_f32_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not (neighbours & covered), (name, sorted(neighbours & covered)) + stripped = pixel.ACCEPTED - {"v_add_co_ci_u32_sdwa"} + assert ("SDWA", "v_add_co_ci_u32_sdwa") not in fc.gfx_forms(stripped, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + if __name__ == "__main__": check_denominators() check_example() @@ -1557,6 +1593,7 @@ def check_sdwa_f16_forms(): check_dpp_f16_arith_round_forms() check_dpp_f16_cvt_fmac_ldexp_forms() check_sdwa_f16_forms() + check_sdwa_int_extra_forms() check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 52b5d7f4b..484c35134 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -11114,6 +11114,241 @@ def check_sdwa_f16_draw(directory, compiler, renderer, backend): return 0 +# Extended 32-bit integer SDWA fixtures covering 12 SDWA forms: bit-scan/reverse (bfrev/ffbl/ffbh_u32/ffbh_i32), +# saturate-pack (sat_pk_u8_i16), 24-bit multiplies (mul/mul_hi i24/u24), and carry-in add/sub/subrev (co_ci_u32). +# Runtime inputs arrive in constant buffer words s44..s47 (with v18 = s45) so DXC never folds the operations. +SDWA_INT_EXTRA_PROGRAMS = { + "bitscan_satpk": [ + "v_mov_b32_e32 v18, s45", + # ch0: reverse bits of zero-extended WORD_1(s44). + "v_bfrev_b32_sdwa v12, s44 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + # ch1: ffbl(sext(BYTE_1(v18))) in WORD_0, ffbh_u32(WORD_0(s46)) in WORD_1 with UNUSED_PRESERVE. + "v_ffbl_b32_sdwa v13, sext(v18) dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:BYTE_1", + "v_ffbh_u32_sdwa v13, s46 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + # ch2: ffbh_i32(sext(BYTE_0(s44))). + "v_ffbh_i32_sdwa v14, sext(s44) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", + # ch3: sat_pk_u8_i16(s47) in WORD_0, sat_pk_u8_i16(sext(BYTE_2(v18))) in WORD_1 with UNUSED_PRESERVE. + "v_sat_pk_u8_i16_sdwa v15, s47 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_sat_pk_u8_i16_sdwa v15, sext(v18) dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_2", + ], + "mul24": [ + "v_mov_b32_e32 v18, s45", + "v_mov_b32_e32 v15, 0x0000cafe", + # ch0: unsigned 24-bit multiply low of WORD_1(s44) and DWORD(v18) (bits 31:24 of v18 masked off). + "v_mul_u32_u24_sdwa v12, s44, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD", + # ch1: signed 24-bit multiply low of sext(WORD_0(s44)) and sext(BYTE_3(s45)). + "v_mul_i32_i24_sdwa v13, sext(s44), sext(s45) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:BYTE_3", + # ch2: unsigned 24-bit multiply high of DWORD(s46) and DWORD(s47), placed in WORD_0 with UNUSED_PAD. + "v_mul_hi_u32_u24_sdwa v14, s46, s47 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD", + # ch3: signed 24-bit multiply high of DWORD(s46) and sext(WORD_1(s47)), placed in WORD_1 keeping 0xcafe. + "v_mul_hi_i32_i24_sdwa v15, s46, sext(s47) dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:WORD_1", + ], + "co_ci": [ + "v_mov_b32_e32 v18, s45", + "v_mov_b32_e32 v19, s46", + "v_mov_b32_e32 v20, s47", + "v_mov_b32_e32 v14, 0x00001337", + "v_cmp_lt_u32_e32 vcc_lo, s44, v18", + # ch0: sext(BYTE_0(s44)) + WORD_0(v19) + ci0 -> v12, updates vcc_lo with 32-bit carry-out. + "v_add_co_ci_u32_sdwa v12, vcc_lo, sext(s44), v19, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:WORD_0", + # ch1: WORD_1(s47) - WORD_1(v18) - borrow_in -> WORD_0 of v13, updates vcc_lo with 32-bit borrow-out. + "v_sub_co_ci_u32_sdwa v13, vcc_lo, s47, v18, vcc_lo dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_1", + # ch2: BYTE_0(v20) - sext(BYTE_1(s44)) - borrow_in -> WORD_1 of v14 keeping 0x1337, updates vcc_lo. + "v_subrev_co_ci_u32_sdwa v14, vcc_lo, sext(s44), v20, vcc_lo dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_1 src1_sel:BYTE_0", + # ch3: final borrow-out flag (0 or 1). + "v_cndmask_b32_e64 v15, 0, 1, vcc_lo", + ], +} +SDWA_INT_EXTRA_ROWS = { + "bitscan_satpk": ( + (0x123400fe, 0x007f8000, 0x11110080, 0x012cfff6), + (0x8001007f, 0x00800000, 0xdead0000, 0x00c8002a), + (0x000000ff, 0x00ff0400, 0x00008000, 0x80007fff), + ), + "mul24": ( + (0x0003fffe, 0xfd123456, 0xaa800001, 0x8000ffff), + (0xffff0005, 0xfeffffff, 0x557fffff, 0x7fff0001), + (0x12348000, 0x02abcdef, 0xff010000, 0xfffe0000), + ), + "co_ci": ( + # Row 0: s44 < s45 -> ci0=1; add(-1, 5, 1)=5 carry=1; sub(2, 5, 1)=-4 borrow=1; subrev(sext(0xfe)=-2, 10, 1)=11 borrow=0. + (0x0000feff, 0x00050000, 0x00000005, 0x0002000a), + # Row 1: s44 > s45 -> ci0=0; add(3, 7, 0)=10 carry=0; sub(9, 4, 0)=5 borrow=0; subrev(sext(0x05)=5, 2, 0)=-3 borrow=1. + (0x10000503, 0x00040000, 0x00000007, 0x00090002), + # Row 2: boundary carry propagation: ci0=1; add(-1, 0, 1)=0 carry=1; sub(0, 0, 1)=-1 borrow=1; subrev(0, 0, 1)=-1 borrow=1. + (0x000000ff, 0x00001000, 0x00000000, 0x00000000), + ), +} +SDWA_INT_EXTRA_MUTATIONS = { + "bitscan_satpk": ( + ("src0_sel:WORD_1", "src0_sel:WORD_0"), + ("v_ffbl_b32_sdwa v13, sext(v18)", "v_ffbh_u32_sdwa v13, sext(v18)"), + ("v_ffbh_u32_sdwa v13, s46 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_ffbh_u32_sdwa v13, s46 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ("v_ffbh_i32_sdwa v14, sext(s44)", "v_ffbh_u32_sdwa v14, sext(s44)"), + ("v_sat_pk_u8_i16_sdwa v15, sext(v18) dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_sat_pk_u8_i16_sdwa v15, sext(v18) dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), + "mul24": ( + ("v_mul_u32_u24_sdwa v12, s44, v18", "v_mul_i32_i24_sdwa v12, s44, v18"), + ("v_mul_i32_i24_sdwa v13, sext(s44), sext(s45)", "v_mul_u32_u24_sdwa v13, sext(s44), sext(s45)"), + ("v_mul_hi_u32_u24_sdwa v14, s46, s47", "v_mul_hi_i32_i24_sdwa v14, s46, s47"), + ("v_mul_hi_i32_i24_sdwa v15, s46, sext(s47) dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_mul_hi_i32_i24_sdwa v15, s46, sext(s47) dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), + "co_ci": ( + ("v_add_co_ci_u32_sdwa v12, vcc_lo, sext(s44), v19, vcc_lo", + "v_sub_co_ci_u32_sdwa v12, vcc_lo, sext(s44), v19, vcc_lo"), + ("v_sub_co_ci_u32_sdwa v13, vcc_lo, s47, v18, vcc_lo", + "v_subrev_co_ci_u32_sdwa v13, vcc_lo, s47, v18, vcc_lo"), + ("v_subrev_co_ci_u32_sdwa v14, vcc_lo, sext(s44), v20, vcc_lo dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_sub_co_ci_u32_sdwa v14, vcc_lo, sext(s44), v20, vcc_lo dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE"), + ("v_subrev_co_ci_u32_sdwa v14, vcc_lo, sext(s44), v20, vcc_lo dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_subrev_co_ci_u32_sdwa v14, vcc_lo, sext(s44), v20, vcc_lo dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), +} + + +def sdwa_int_extra_reference(group, row): + """Independent Python reference words for SDWA_INT_EXTRA_PROGRAMS.""" + a, b, c, d = row + sel_u32 = lambda w, off, wid, sx: ( + ((w >> off) & ((1 << wid) - 1)) | ((~((1 << wid) - 1) & 0xffffffff) if (sx and ((w >> (off + wid - 1)) & 1)) else 0) + ) & 0xffffffff + bfrev = lambda x: int(f"{x & 0xffffffff:032b}"[::-1], 2) + ffbl = lambda x: 0xffffffff if (x & 0xffffffff) == 0 else ((x & 0xffffffff) & -(x & 0xffffffff)).bit_length() - 1 + ffbh_u = lambda x: 0xffffffff if (x & 0xffffffff) == 0 else 32 - (x & 0xffffffff).bit_length() + def ffbh_i(x): + x &= 0xffffffff + if x in (0, 0xffffffff): + return 0xffffffff + target = ~x & 0xffffffff if x & 0x80000000 else x + return 32 - target.bit_length() + def sat_pk(x): + lo = (x & 0xffff) - 0x10000 if x & 0x8000 else (x & 0xffff) + hi = ((x >> 16) & 0xffff) - 0x10000 if x & 0x80000000 else ((x >> 16) & 0xffff) + return min(max(lo, 0), 255) | (min(max(hi, 0), 255) << 8) + s24 = lambda x: (x & 0xffffff) - 0x1000000 if x & 0x800000 else (x & 0xffffff) + if group == "bitscan_satpk": + ch0 = bfrev(sel_u32(a, 16, 16, False)) + ch1 = (ffbl(sel_u32(b, 8, 8, True)) & 0xffff) | ((ffbh_u(sel_u32(c, 0, 16, False)) & 0xffff) << 16) + ch2 = ffbh_i(sel_u32(a, 0, 8, True)) + ch3 = (sat_pk(d) & 0xffff) | ((sat_pk(sel_u32(b, 16, 8, True)) & 0xffff) << 16) + return (ch0, ch1, ch2, ch3) + if group == "mul24": + ch0 = ((sel_u32(a, 16, 16, False) & 0xffffff) * (b & 0xffffff)) & 0xffffffff + ch1 = (s24(sel_u32(a, 0, 16, True)) * s24(sel_u32(b, 24, 8, True))) & 0xffffffff + ch2 = (((c & 0xffffff) * (d & 0xffffff)) >> 32) & 0xffff + ch3_hi = ((s24(c) * s24(sel_u32(d, 16, 16, True))) >> 32) & 0xffff + return (ch0, ch1, ch2, (ch3_hi << 16) | 0xcafe) + # co_ci: + ci = 1 if a < b else 0 + s0_0, s1_0 = sel_u32(a, 0, 8, True), sel_u32(c, 0, 16, False) + sum0 = s0_0 + s1_0 + ci + ch0, ci = sum0 & 0xffffffff, 1 if sum0 >> 32 else 0 + s0_1, s1_1 = sel_u32(d, 16, 16, False), sel_u32(b, 16, 16, False) + diff1 = s0_1 - s1_1 - ci + ch1, ci = diff1 & 0xffff, 1 if diff1 < 0 else 0 + s0_2, s1_2 = sel_u32(a, 8, 8, True), sel_u32(d, 0, 8, False) + diff2 = s1_2 - s0_2 - ci + ch2, ci = ((diff2 & 0xffff) << 16) | 0x1337, 1 if diff2 < 0 else 0 + return (ch0, ch1, ch2, ci) + + +def check_sdwa_int_extra_controls(): + """Static lowering and refusal controls for the 12 extended integer SDWA forms.""" + for name, body in SDWA_INT_EXTRA_PROGRAMS.items(): + prog = uncompressed_export(body) + hlsl = translate_int(prog) + if name == "bitscan_satpk": + assert "reversebits(" in hlsl and "firstbitlow(" in hlsl + assert "dpp_ffbh_u32(" in hlsl and "dpp_ffbh_i32(" in hlsl + elif name == "mul24": + for helper in ("mul24_u32(", "mul24_i32(", "mul24_hi_u32(", "mul24_hi_i32("): + assert helper in hlsl, (helper, hlsl) + for old, new in SDWA_INT_EXTRA_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + assert translate_int(mutated) != hlsl, (name, old, new) + sdwa1 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD" + sdwa2 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD" + cmp_vcc = ["v_mov_b32_e32 v18, s45", "v_cmp_lt_u32_e32 vcc_lo, s44, v18"] + # Refusals for SDWA_INT_EXTRA and co_ci SDWA: UNUSED_SEXT, untracked UNUSED_PRESERVE, float modifiers, + # clamp/omod, inline constants, unbalanced sext, wrong arity, untracked/mismatched carry mask, and scheduling. + for prefix, bad, message in ( + (["v_mov_b32_e32 v18, s45"], "v_bfrev_b32_sdwa v12, v18 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:DWORD", + "UNUSED_SEXT is not lowered"), + (["v_mov_b32_e32 v18, s45"], "v_mul_i32_i24_sdwa v20, s44, v18 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:DWORD", + "UNUSED_PRESERVE needs a tracked numeric destination"), + (["v_mov_b32_e32 v18, s45"], f"v_bfrev_b32_sdwa v12, -v18 {sdwa1}", "Unsupported SDWA integer operands"), + (["v_mov_b32_e32 v18, s45"], f"v_mul_u32_u24_sdwa v12, s44, |v18| {sdwa2}", "Unsupported SDWA integer operands"), + (["v_mov_b32_e32 v18, s45"], f"v_sat_pk_u8_i16_sdwa v12, v18 clamp {sdwa1}", "Unsupported SDWA integer operands"), + (["v_mov_b32_e32 v18, s45"], f"v_mul_i32_i24_sdwa v12, 1, v18 {sdwa2}", "Unsupported SDWA integer operands"), + (["v_mov_b32_e32 v18, s45"], f"v_bfrev_b32_sdwa v12, sext(v18 {sdwa1}", "Unbalanced sext()"), + (["v_mov_b32_e32 v18, s45"], f"v_bfrev_b32_sdwa v12, s44, v18 {sdwa2}", "takes 1 source(s)"), + (["v_mov_b32_e32 v18, s45"], f"v_mul_u32_u24_sdwa v12, v18 {sdwa1}", "takes 2 source(s)"), + (["v_mov_b32_e32 v18, s45"], f"v_mul_u32_u24_sdwa v256, s44, v18 {sdwa2}", "Invalid integer operation"), + (["v_mov_b32_e32 v18, s45"], f"v_add_co_ci_u32_sdwa v12, vcc_lo, s44, v18, vcc_lo {sdwa2}", + "Carry mask is not a tracked condition"), + (cmp_vcc, f"v_add_co_ci_u32_sdwa v12, vcc_lo, v18, v18, vcc {sdwa2}", "Invalid carry-in operation"), + (cmp_vcc, f"v_add_co_ci_u32_sdwa v12, vcc_lo, s44, s46, vcc_lo {sdwa2}", + "SDWA carry-in reads at most one distinct SGPR source"), + (cmp_vcc, f"v_sub_co_ci_u32_sdwa v12, s52, s44, v18, s52 {sdwa2}", "Unsupported SDWA carry-in operands"), + (cmp_vcc, "v_subrev_co_ci_u32_sdwa v12, vcc_lo, s44, v18, vcc_lo dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:DWORD src1_sel:DWORD", + "UNUSED_SEXT is not lowered"), + (cmp_vcc, "v_add_co_ci_u32_sdwa v20, vcc_lo, s44, v18, vcc_lo dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:DWORD", + "UNUSED_PRESERVE needs a tracked numeric destination"), + (cmp_vcc, f"v_add_co_ci_u32_sdwa v12, vcc_lo, -s44, v18, vcc_lo {sdwa2}", "Unsupported SDWA carry-in operands"), + (cmp_vcc, f"v_add_co_ci_u32_sdwa v12, vcc_lo, sext(s44, v18, vcc_lo {sdwa2}", "Unbalanced sext()"), + (cmp_vcc, f"v_add_co_ci_u32_sdwa v12, vcc_lo, s44, v18, vcc_lo clamp {sdwa2}", "Unsupported SDWA carry-in operands"), + (cmp_vcc, f"v_add_co_ci_u32_sdwa v256, vcc_lo, s44, v18, vcc_lo {sdwa2}", "Invalid carry-in operation"), + ): + expect_value_error(translate_int, uncompressed_export([*prefix, bad]), message) + # Scheduling: pending scalar load, outstanding sample, and non-entry EXEC mask must refuse. + base = uncompressed_export([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + expect_value_error(translate_int, base[:load + 1] + [f"v_bfrev_b32_sdwa v24, s44 {sdwa1}"] + base[load + 1:], + "Constant read before load completion") + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(translate_int, base[:sample + 1] + [f"v_bfrev_b32_sdwa v12, s44 {sdwa1}"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(translate_int, base[:sample + 1] + [f"v_bfrev_b32_sdwa v24, v12 {sdwa1}"] + base[sample + 1:], + "Sample used before vmcnt wait") + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(translate_int, base[:masked] + [f"v_bfrev_b32_sdwa v24, s44 {sdwa1}"] + base[masked:], + "Invalid integer operation") + + +def check_sdwa_int_extra_draw(directory, compiler, renderer, backend): + check_sdwa_int_extra_controls() + for name, body in SDWA_INT_EXTRA_PROGRAMS.items(): + prog = uncompressed_export(body) + src_path = directory / f"sdwa_int_extra_{name}.hlsl" + cso_path = directory / f"sdwa_int_extra_{name}.cso" + src_path.write_text(translate_int(prog), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + cases = [] + for idx, row in enumerate(SDWA_INT_EXTRA_ROWS[name]): + expected = sdwa_int_extra_reference(name, row) + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *row) + case_path = directory / f"sdwa_int_extra_{name}_{idx}.case" + case_path.write_bytes(bytes(constants) + struct.pack("<4I", *expected) * 64 + b"\x01") + cases.append((case_path, "pass")) + run_pixel_batch(renderer, backend, cso_path, cases) + case_paths = [p for p, _ in cases] + for old, new in SDWA_INT_EXTRA_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + src_path.write_text(translate_int(mutated), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cso_path, case_paths) + print(f"sdwa_int_extra {name} mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"sdwa_int_extra {name} mutation {old!r} -> {new!r} escaped detection") + return 0 + + # Quad-local DPP16 and DPP8 integer/bitwise/shift/bit-scan/saturate fixture covering 24 VOP1/VOP2 DPP forms. # Derives integer quad lane ID {0, 1, 2, 3} from interpolated uv.x/uv.y (v8/v9), verifies quad # swizzles across lanes, folds all 23 ops into a 32-bit accumulator, and exports all 4 bytes as @@ -13406,7 +13641,7 @@ def statement(*body): expect_value_error(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad]), message) must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", good.replace("v18", "v106")])) # Operations outside the table keep their refusal in the SDWA spelling. - for bad in (f"v_bfi_b32_sdwa v12, s44, v18 {sdwa}", f"v_mul_u32_u24_sdwa v12, s44, v18 {sdwa}", + for bad in (f"v_bfi_b32_sdwa v12, s44, v18 {sdwa}", f"v_mul_lo_u32_sdwa v12, s44, v18 {sdwa}", f"v_add_nc_i32_sdwa v12, s44, v18 {sdwa}", f"v_min3_u32_sdwa v12, s44, v18 {sdwa}"): must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad])) @@ -13590,7 +13825,7 @@ def check_sat_pack_u8_lowering(): "v_sat_pk_u8_i16_e64 v12, -v18", "v_sat_pk_u8_i16_e32 v12, v18, s44", "v_sat_pk_u8_i16_e32 v12, 0x100000000", - "v_sat_pk_u8_i16_sdwa v12, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_sat_pk_u8_i16_sdwa v12, v18 clamp dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", ): must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", invalid])) @@ -14430,7 +14665,7 @@ def check_carry_in_lowering(): f"{op}_e64 v12, s[64:65], v18, s44, s60", f"{op}_e64 v12, s61, v18, s44, s[62:63]", f"{op}_e64 v12, s61, v18, s44, s58", f"{op}_e64 v12, s61, v18, s44, s61", f"{op}_dpp v12, vcc_lo, v18, v18, vcc_lo row_shl:1 row_mask:0xf bank_mask:0xf", - f"{op}_sdwa v12, vcc_lo, v18, v18, vcc_lo dst_sel:DWORD dst_unused:UNUSED_PAD " + f"{op}_sdwa v12, vcc_lo, v18, v18, vcc_lo dst_sel:DWORD dst_unused:UNUSED_SEXT " "src0_sel:DWORD src1_sel:DWORD"): must_reject(translate_int, uncompressed_export([*setup, bad])) # A carry-in that is no lane mask at all: vcc before anything writes it, and an SGPR holding a constant. @@ -19327,7 +19562,7 @@ def _check_controls_inline(directory): "v_mul_u32_u24_e64 v23, s47, s44 clamp", "v_mul_hi_i32_i24_e64 v25, s46, s47 clamp", "v_mul_hi_u32_u24_e64 v27, s47, s44 clamp", - "v_mul_i32_i24_sdwa v21, s46, s47 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD", + "v_mul_i32_i24_sdwa v21, s46, s47 clamp dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD", "v_mul_i32_i24_e64 v21, s46", "v_mul_u32_u24_e32 v256, s45, v29", "v_mul_hi_u32_u24_e64 v27, s47, 0x100000000", @@ -19350,6 +19585,7 @@ def _check_controls_inline(directory): "check_dpp_cvt_refusals", "check_dpp_f16_contract_controls", "check_sdwa_f16_controls", + "check_sdwa_int_extra_controls", "check_smem_pointer_controls", "check_masked_controls", "check_masked_mov_close_controls", @@ -20001,6 +20237,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append((uncompressed_export(DPP_F16_CVT_I16_LANES), translate_f16)) fixtures.extend((uncompressed_export(body), translate_f16) for body in SDWA_F16_PROGRAMS.values()) fixtures.append((uncompressed_export(SDWA_F16_CVT_F32_BODY), translate_f16)) + fixtures.extend((uncompressed_export(body), translate_int) for body in SDWA_INT_EXTRA_PROGRAMS.values()) fixtures.extend((bit_program(op), translate) for op in BIT_OPERATIONS) fixtures.extend((program, function) for _, program, function, _ in e64_spelling_programs()) fixtures.append((vop1_nop_program(), translate)) @@ -26747,7 +26984,7 @@ def main(): "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", - "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-dpp-extra", "draw-pk-fmac"): + "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, "draw-dpp-cvt": check_dpp_cvt_draw, @@ -26810,7 +27047,8 @@ def main(): "draw-sopp-round-mode": check_sopp_round_mode_draw, "draw-smem-pointers": check_smem_pointer_draw, "draw-dpp-f16": check_dpp_f16_draw, - "draw-sdwa-f16": check_sdwa_f16_draw}[mode] + "draw-sdwa-f16": check_sdwa_f16_draw, + "draw-sdwa-int-extra": check_sdwa_int_extra_draw}[mode] return draw(directory, *args) except subprocess.CalledProcessError as error: if error.returncode == 77 and str(error.cmd[0]) == str(args[1]): diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index b33fdd6dd..396a21290 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -3016,6 +3016,19 @@ def sdwa_cmp_bits(token, sel, sext, scalar, vector, pending, sample_dest, *, f16 rf"(v\d+), {SDWA_INT_SOURCE}(?:, {SDWA_INT_SOURCE})? dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" r" dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" r"(?: src1_sel:(BYTE_[0-3]|WORD_[01]|DWORD))?") +# Additional 32-bit integer SDWA forms (bit-scan/reverse, 24-bit multiplies, saturate-pack), kept +# alongside SDWA_INT so existing 15-op SDWA_INT scanner/test assertions remain unchanged. +SDWA_INT_EXTRA = { + op: INTEGER[op] for op in ( + "bfrev_b32", "ffbl_b32", "ffbh_u32", "ffbh_i32", "sat_pk_u8_i16", + "mul_u32_u24", "mul_i32_i24", "mul_hi_u32_u24", "mul_hi_i32_i24", + ) +} +SDWA_CO_CI_OPERANDS = re.compile( + rf"(v\d+), (vcc(?:_lo)?), {SDWA_INT_SOURCE}, {SDWA_INT_SOURCE}, (vcc(?:_lo)?)" + r" dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" + r" dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE)" + r" src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD) src1_sel:(BYTE_[0-3]|WORD_[01]|DWORD)") SDWA_F16_SRC = re.compile(r"(-?)(?:abs\(([vs]\d+)\)|\|([vs]\d+)\||([vs]\d+))") SDWA_F16_UNARY_OPERANDS = re.compile( r"(v\d+), ([^,\s]+) dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" @@ -5358,6 +5371,74 @@ def sample_coord(reg): result = sdwa_dest(f"({template.format(*args)})", dst_sel, unused, vector.get(dst)) vector[dst] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({result});") + elif m := match(rf"v_({'|'.join(SDWA_INT_EXTRA)})_sdwa (.+)"): + # SDWA forms of bit-scan/reverse, 24-bit multiply, and saturate-pack integer ops. + op, rest = m.groups() + arity, template = SDWA_INT_EXTRA[op] + parsed = SDWA_INT_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported SDWA integer operands: v_{op}_sdwa {rest}") + dst, sext0, src0, close0, sext1, src1, close1, dst_sel, unused, sel0, sel1 = parsed.groups() + if bool(src1) != (arity == 2) or bool(sel1) != (arity == 2): + raise ValueError(f"v_{op}_sdwa takes {arity} source(s), each with its own selection") + if bool(sext0) != bool(close0) or bool(sext1) != bool(close1): + raise ValueError("Unbalanced sext() on an SDWA source") + if unused == "UNUSED_SEXT": + raise ValueError("UNUSED_SEXT is not lowered") + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid integer operation") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + raw_args = [ + sdwa_source(int_operand(token, scalar, vector, pending, sample_dest, signed=False), sel, bool(sext)) + for token, sel, sext in ((src0, sel0, sext0), (src1, sel1, sext1))[:arity] + ] + arg_names = [] + for k, expr in enumerate(raw_args): + lines.append(f" uint sd{i}_{k} = {expr};") + arg_names.append(f"sd{i}_{k}") + if op in MUL24_HELPERS: + helpers.update(MUL24_HELPERS[op]) + helpers.update(INTEGER_HELPERS.get(op, ())) + result = sdwa_dest(f"({template.format(*arg_names)})", dst_sel, unused, vector.get(dst)) + vector[dst] = f"alu{i}" + lines.append(f" precise float alu{i} = asfloat({result});") + elif m := match(r"v_(add|sub|subrev)_co_ci_u32_sdwa (.+)"): + # SDWA forms of carry-in 32-bit add/sub/subrev: extract/extend sources via SDWA, perform + # the 32-bit carry-in ALU op and update VCC with the 32-bit carry/borrow-out, then place + # the result according to dst_sel/dst_unused. + op, rest = m.groups() + parsed = SDWA_CO_CI_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported SDWA carry-in operands: v_{op}_co_ci_u32_sdwa {rest}") + dst, carry_out_tok, sext0, src0, close0, sext1, src1, close1, carry_in_tok, dst_sel, unused, sel0, sel1 = ( + parsed.groups() + ) + if bool(sext0) != bool(close0) or bool(sext1) != bool(close1): + raise ValueError("Unbalanced sext() on an SDWA source") + if unused == "UNUSED_SEXT": + raise ValueError("UNUSED_SEXT is not lowered") + if mask != "entry" or not 0 <= int(dst[1:]) <= 255 or dst in sample_dest or carry_out_tok != carry_in_tok: + raise ValueError("Invalid carry-in operation") + if src0.startswith("s") and src1.startswith("s") and src0 != src1: + raise ValueError("SDWA carry-in reads at most one distinct SGPR source") + condition = scalar.get("vcc") + if ("vcc" in pending or not isinstance(condition, tuple) + or condition[0] != "condition" or condition[2:] != (0, 1)): + raise ValueError("Carry mask is not a tracked condition") + a_expr = sdwa_source(int_operand(src0, scalar, vector, pending, sample_dest, signed=False), sel0, bool(sext0)) + b_expr = sdwa_source(int_operand(src1, scalar, vector, pending, sample_dest, signed=False), sel1, bool(sext1)) + partial, result_tmpl, carry_out_tmpl = CARRY_IN[op] + lines.append(f" uint sa{i} = {a_expr};") + lines.append(f" uint sb{i} = {b_expr};") + lines.append(f" uint ci{i} = {condition[1]} ? 1u : 0u;") + lines.append(f" uint cp{i} = {partial.format(f'sa{i}', f'sb{i}')};") + lines.append(f" uint co{i} = {result_tmpl.format(p=f'cp{i}', c=f'ci{i}')};") + lines.append(f" bool cmp{i} = {carry_out_tmpl.format(f'sa{i}', f'sb{i}', p=f'cp{i}', c=f'ci{i}', r=f'co{i}')};") + placed = sdwa_dest(f"co{i}", dst_sel, unused, vector.get(dst)) + lines.append(f" precise float alu{i} = asfloat({placed});") + scalar["vcc"] = ("condition", f"cmp{i}", 0, 1) + vector[dst] = f"alu{i}" elif m := match(r"v_cvt_f16_f32_sdwa (.+)"): # SDWA binary32-to-binary16 conversion under the declared entry profile (half_denorm="preserve" # and HW_REG_MODE RNE). Takes a whole-dword register source (so f32 denormal mode never touches From 6dc95200422a24a0a84aafe35010b0bc90d47b4a Mon Sep 17 00:00:00 2001 From: saii <120340942+Not-Saii@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:55:40 +0200 Subject: [PATCH 168/232] shader: lower v_fma_mix_f32 in gfx2hlsl (#2055) * shader: lower v_fma_mix_f32 in gfx2hlsl v_fma_mix_f32 was refused by the startup translator (58 code pairs in the #1723 refusal snapshot). It now shares Stage.mix() with the two binary16-destination forms and writes the binary32 result to the whole VGPR. Source selection follows LLVM 15 SelectVOP3PMadMixModsImpl: op_sel_hi marks a binary16 source and op_sel picks its high half; abs then neg apply after widening. The shared handler now reads high halves, accepts neg/abs on binary16 registers, and refuses op_sel on a binary32 source, unknown modifiers, and inline floats or literals on binary16 sources (mixlo/mixhi used to read the binary32 bits of 1.0 as 0). Refs #1723 Co-Authored-By: Claude Opus 5.5 * shader: keep -0 on fma_mix sources and anchor the VOP3P encoder Restore the negated inline zero on binary16 sources, read it as -0.0 on every source, and check the test encoder against two llvm-mc words. Refs #1723 Co-Authored-By: Claude Opus 5.5 * shader: refuse ambiguous negated sources in gfx2hlsl fma_mix Emit neg on a negative inline float (`--0.5`) as `(-(-0.5))` instead of an HLSL decrement, and refuse binary32 sources printed as a negative integer or literal, where the decoder text loses the sign-bit flip (review on #2055). Refs #1723 Co-Authored-By: Claude Opus 5.5 * shader: compile the fma_mix translations and tidy review nits Check op_sel on a binary32 source before the -0 shortcut, drop a stray tool marker from a comment, and fix the docs wording about earlier op_sel handling. Add a check mode that compiles every translated line with FXC for ps_5_1 (startup_gfx2hlsl_fma_mix_fxc when FXC is found), and cases for a register with undefined upper bits after an odd-dmask D16 image_load: a low-half read is accepted, high-half and binary32 reads are refused. Refs #1723 Co-Authored-By: Claude Opus 5.5 * startup: select the binary16 half of a mixed FMA literal * docs: describe literal half selection and inline 0.5 in fma_mix Refs #1723 Co-Authored-By: Claude Opus 5.5 * tests: dispatch the gfx2hlsl fma_mix translations against a CPU reference Add a dispatch mode to startup_gfx2hlsl_fma_mix_check.py. Every translated line runs in a DXC cs_6_0 thread on WARP or a hardware adapter, and each result word is compared with a CPU reference that decodes the VOP3P word itself (LLVM 15 reading). A control drops the high-half shift and must then follow a reference with op_sel cleared. Registered as startup_gfx2hlsl_fma_mix_dispatch_warp and _hardware (review on #2055). Refs #1723 Co-Authored-By: Claude Opus 5.5 * shader: note the unfused multiply-add in gfx2hlsl fma_mix Review nit on #2055. Refs #1723 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 17 + docs/experiments.md | 29 ++ tests/startup_gfx2hlsl_fma_mix_check.py | 452 ++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 81 ++++- 6 files changed, 566 insertions(+), 15 deletions(-) create mode 100644 tests/startup_gfx2hlsl_fma_mix_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 83c701882..6045f6964 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -275,6 +275,7 @@ jobs: tests/startup_compute_lds_b128_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 6aeaaa468..28e2f1cb5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,6 +170,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py ./out/pe-env/bin/python -B tests/startup_image_load_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e4f59ccd7..9393083bd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3069,6 +3069,9 @@ if(EXISTS "${INTAKE_PYTHON}") # them as an index error before it checked the count. add_test(NAME startup_gfx2hlsl_image_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_arity_check.py") + # gfx2hlsl lowers v_fma_mix_f32 and selects binary16 source halves on all three mixed-precision FMAs. + add_test(NAME startup_gfx2hlsl_fma_mix COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py") # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B @@ -3171,6 +3174,11 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with # DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with. find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") + if(STARTUP_FXC) + # The v_fma_mix* translations from startup_gfx2hlsl_fma_mix, compiled for ps_5_1. + add_test(NAME startup_gfx2hlsl_fma_mix_fxc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py" fxc "${STARTUP_FXC}") + endif() # gfx2hlsl conversion operations: translation controls, then a draw of the translated pairs with # reference words and one mutated lowering per operation (v_cvt_f16_f32 through DXC only). # Compute translator: integer inequality lane guards. @@ -3506,6 +3514,15 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_fma_mix*: every translated form dispatched against a CPU reference that decodes the VOP3P + # word itself, plus a control that drops the high-half shift. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_fma_mix_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_fma_mix_dispatch_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 5e0a44784..7e5b84ea3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14299,6 +14299,35 @@ The binary32 table (`VEC_F`) applies the same operand-count rule. Before this ch `tests/startup_gfx2hlsl_swap_check.py` (`startup_gfx2hlsl_swap`) decodes the documented VOP1 words, evaluates the translated text of seven programs on the CPU against a plain exchange of two list entries, and checks the refusals. Two mutations (write before read, only one destination written) are loaded from the translator source and must fail the fixtures. `python -B tests/startup_gfx2hlsl_swap_check.py binary llvm-mc-15` also reassembles the source lines. This is translation only; no draw was run. +## Startup translator: v_fma_mix_f32 + +`tools/startup/gfx2hlsl.py` now lowers `v_fma_mix_f32` (VOP3P, opcode 0x20), which it used to refuse. It shares one handler with `v_fma_mixlo_f16` and `v_fma_mixhi_f16`. Each source is read as LLVM 15 selects it (`SelectVOP3PMadMixModsImpl`): `op_sel_hi` set means a binary16 source, and `op_sel` then picks its high half. abs and then neg apply after widening. The binary32 result is written to the whole VGPR, with optional `clamp`. + +The shared handler now also: + +- reads the high half of a binary16 source with `op_sel` (previously refused on all three forms); +- accepts `-` and `|...|` on binary16 register sources; +- still refuses `op_sel` on a binary32 source, including a negated inline zero (it was refused on every source before); +- refuses any other modifier it does not model (previously ignored); +- reads only bits 15:0 of a low-half binary16 source, so a register left with undefined upper bits by an odd-dmask D16 `image_load` stays usable there; a high-half read is still refused for such a register; +- reads a literal on a binary16 source through the selected half, so `0x40003c00` gives 1.0 from the low half and 2.0 from the high half; +- accepts inline `0.5` on a low-half binary16 source and refuses the high half of an inline constant and every other inline float there. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; +- reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`; +- emits neg on a negative inline float (printed `--0.5`) as `(-(-0.5))`. Before, `(--0.5)` was an HLSL decrement and did not compile; +- refuses a binary32 source printed as a negative integer or literal (`-1`, `-17`, `-0x…`). The decoder prints neg on inline 1..64 or on a literal that way, and reading it as an integer loses the sign-bit flip: neg on inline 1 is `0x80000001`, not `0xffffffff`. Inline `-1` prints the same text as neg on inline 1, so it is refused too until the decoder resolves the operand from the encoding, as it does for `v_cndmask_b32_e64` (#1932). + +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of seventeen forms. They include a register with undefined upper bits read through its low half, both halves of one literal, and inline `0.5` on a low half. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eleven forms must be refused. On the translator before this change the check fails at the first form. + +With `fxc `, the check also compiles all seventeen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. The refusal census was not re-measured. + +With `dispatch warp|hardware`, all seventeen translated lines run in one DXC cs_6_0 thread. CMake registers this as `startup_gfx2hlsl_fma_mix_dispatch_warp` and `_hardware`. Each case loads its register words through the raw UAV fill pattern, so the compiler cannot fold them, runs the line and stores the destination. The check compares each word with a CPU reference that decodes the VOP3P word itself, without the decoder or the translator. The reference applies the LLVM 15 reading: binary16 if `op_sel_hi`, high half if `op_sel`, abs then neg, clamp. Inputs have short mantissas, so a fused and an unfused multiply-add give the same word; this check does not separate the two. A control drops the high-half shift from the emitted lines. Its readback must then follow a reference with `op_sel` cleared, and must differ from the correct result in at least one case. It differs in 3 of 4: the `-0` case has a zero product, so the half it reads does not show. + +Measured at `741ff02c` plus the dispatch mode, `dev` preset, Windows 11 26300.9974. On WARP (Microsoft Basic Render Driver, 1414:008c) and on an NVIDIA GeForce RTX 4090 (10de:2684, driver 32.0.16.1088), 17 of 17 words matched the reference, and the control read the low half in all 4 high-half cases. Neither run reported a capability skip. The fixture does not report D3D12 debug-layer status. + +```powershell +ctest --preset dev --no-tests=error -j1 -R '^startup_gfx2hlsl_fma_mix(_fxc|_dispatch_(warp|hardware))?$' -V +``` + ## Non-fused multiply-add in the startup translator The gfx1013 `v_mad_f32`, `v_mac_f32`, `v_madmk_f32`, `v_madak_f32` and diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py new file mode 100644 index 000000000..b2f25cc64 --- /dev/null +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -0,0 +1,452 @@ +"""Mixed-precision VOP3P FMA (`v_fma_mix_f32`, `v_fma_mix{lo,hi}_f16`) in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_fma_mix_check.py [fxc | dispatch warp|hardware] + +With `fxc`, every translated line is also compiled for ps_5_1 (the profile the startup tools use), +so emitted text that is not valid HLSL fails here and not only in a later draw. With `dispatch`, every +translated line runs in a DXC cs_6_0 shader on WARP or a hardware adapter, and each result word is +compared with a CPU reference that decodes the VOP3P word itself. Exit code 77 is a capability skip. + +`v_fma_mix_f32` was refused outright (58 code pairs in the #1723 refusal snapshot). It now shares +`Stage.mix()` with the two binary16-destination forms. + +Source selection follows LLVM 15 (`AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl`, llvmorg-15.0.7): +"If the source's op_sel_hi is set, it indicates to do a conversion from fp16. If the sources's op_sel +is set, it picks the high half of the source register." `AMDGPUInstPrinter::printOpSelHi` prints +`SISrcMods::OP_SEL_1`, the bit that function sets for an fp16 source. abs, then neg, apply after +the conversion. + +The instruction bytes are **constructed here** from the VOP3P layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, VOP3P branch): + w0: [31:23] = 0b110011000, [22:16] opcode, [15] clamp, [14] op_sel_hi[2], [13:11] op_sel, + [10:8] abs (neg_hi on other VOP3P), [7:0] vdst + w1: [8:0] src0, [17:9] src1, [26:18] src2, [28:27] op_sel_hi[1:0], [31:29] neg (neg_lo) +""" +import os +import re +import struct +import subprocess +import sys +import tempfile + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] +translated = [] # every emitted line, compiled together in fxc mode +cases = [] # (label, encoding, emitted line), run in dispatch mode + +MIX_F32, MIXLO_F16, MIXHI_F16 = 0x20, 0x21, 0x22 +V = 0x100 # VGPR source base +S5 = 5 +ZERO = 128 # inline integer 0 +ONE = 129 # inline integer 1 +SEVENTEEN = 145 # inline integer 17 +MINUS_ONE = 193 # inline integer -1 +MINUS_HALF_F = 241 # inline float -0.5 +ONE_F = 242 # inline float 1.0 +LITERAL = 255 + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def encode(op, vdst, srcs, *, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0), abs_bits=(0, 0, 0), + neg=(0, 0, 0), clamp=0, literal=None): + w0 = (0b110011000 << 23) | (op << 16) | (clamp << 15) | (op_sel_hi[2] << 14) | (vdst & 0xff) + w1 = srcs[0] | (srcs[1] << 9) | (srcs[2] << 18) | (op_sel_hi[0] << 27) | (op_sel_hi[1] << 28) + for i in range(3): + w0 |= op_sel[i] << (11 + i) + w0 |= abs_bits[i] << (8 + i) + w1 |= neg[i] << (29 + i) + code = struct.pack('> 16) * F(v3) + F(v4));') +check('control: op_sel changes the selected half', low != high) +check('control: op_sel_hi changes the source format', plain != low) +expect('abs then neg after widening a high half, scalar source, clamp', + encode(MIX_F32, 1, (v2, S5, v4), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), + abs_bits=(0, 1, 0), neg=(0, 1, 0), clamp=1), + 'v_fma_mix_f32 v1, v2, -|s5|, v4 op_sel:[0,1,0] op_sel_hi:[0,1,0] clamp', + 'v1 = U(saturate(F(v2) * (-abs(f16tof32(s5 >> 16))) + F(v4)));') +expect('inline 0 as a binary16 addend', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1)), + 'v_fma_mix_f32 v1, v2, v3, 0 op_sel_hi:[1,1,1]', + 'v1 = U(f16tof32(v2) * f16tof32(v3) + 0.0);') +expect('negated inline 0 addend keeps a -0 product', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), neg=(0, 0, 1)), + 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]', + 'v1 = U(F(v2) * f16tof32(v3 >> 16) + (-0.0));') +expect('inline float on a binary32 source', + encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(v2) * 1.0 + F(v4));') +# neg on inline -0.5 prints as `--0.5`; `(--0.5)` would be an HLSL decrement (review on #2055). +expect('negated negative inline float', + encode(MIX_F32, 1, (MINUS_HALF_F, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, --0.5, v3, v4', + 'v1 = U((-(-0.5)) * F(v3) + F(v4));') +expect('control: an unnegated literal on a binary32 source still translates', + encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x3f800000), + 'v_fma_mix_f32 v1, 0x3f800000, v3, v4', + 'v1 = U(F(0x3f800000u) * F(v3) + F(v4));') + +# --- the binary16-destination forms keep their packing -------------------------------------------- +expect('mixlo writes the low half', + encode(MIXLO_F16, 1, (v2, v3, v4), op_sel_hi=(1, 1, 0)), + 'v_fma_mixlo_f16 v1, v2, v3, v4 op_sel_hi:[1,1,0]', + 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + F(v4));') +expect('mixlo with a negated inline 0 on a binary16 source', + encode(MIXLO_F16, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1), neg=(0, 0, 1)), + 'v_fma_mixlo_f16 v1, v2, v3, -0 op_sel_hi:[1,1,1]', + 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + (-0.0));') +expect('mixhi writes the high half from a high-half source', + encode(MIXHI_F16, 1, (v2, v3, v4), op_sel=(0, 0, 1), op_sel_hi=(0, 0, 1)), + 'v_fma_mixhi_f16 v1, v2, v3, v4 op_sel:[0,0,1] op_sel_hi:[0,0,1]', + 'v1 = (v1 & 0xffffu) | (f32tof16(F(v2) * F(v3) + f16tof32(v4 >> 16)) << 16);') + +# A register whose upper 16 bits are undefined (odd-dmask D16 image_load) can feed a low-half read. +expect('low half of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(v2) * F(v3) + F(v4));', low16_only_v={2}) + +# --- refusals ------------------------------------------------------------------------------------- +expect_refused('high half of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]', low16_only_v={2}) +expect_refused('binary32 use of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4)), + 'v_fma_mix_f32 v1, v2, v3, v4', low16_only_v={2}) +expect_refused('op_sel on a binary32 negated inline 0', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 0, 1), neg=(0, 0, 1)), + 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,0,1]') +expect_refused('op_sel without op_sel_hi (high half of a binary32 source)', + encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0]') +# The binary16 encoding of an inline float on a half source is unverified. The old mixlo/mixhi path +# read the binary32 bits of 1.0 through f16tof32, i.e. 0.0; it is now refused rather than wrong. +expect_refused('inline float on a binary16 source', + encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), + 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') +expect_refused('inline float on a binary16 source of mixlo', + encode(MIXLO_F16, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), + 'v_fma_mixlo_f16 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') +expect('literal on a binary16 source', + encode(MIX_F32, 1, (LITERAL, v3, v4), op_sel_hi=(1, 0, 0), literal=0x3c00), + 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(0x3c00u) * F(v3) + F(v4));') +# The decoder prints neg on inline 1..64 or a literal as a negative integer. Read as an integer, the +# sign-bit flip is lost (neg on inline 1 is 0x80000001, not 0xffffffff), so these stay refused. +# Inline -1 prints the same text as neg on inline 1, so it is refused too. +expect_refused('neg on inline 1 (binary32)', + encode(MIX_F32, 1, (ONE, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, -1, v3, v4') +expect_refused('inline -1 (same text as neg on inline 1)', + encode(MIX_F32, 1, (MINUS_ONE, v3, v4)), + 'v_fma_mix_f32 v1, -1, v3, v4') +expect_refused('neg on inline 17 (binary32)', + encode(MIX_F32, 1, (SEVENTEEN, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, -17, v3, v4') +expect_refused('neg on a literal (binary32)', + encode(MIX_F32, 1, (LITERAL, v3, v4), neg=(1, 0, 0), literal=0x3f800000), + 'v_fma_mix_f32 v1, -0x3f800000, v3, v4') + +# Both halves contain normal binary16 numbers: 1.0 in the low word and 2.0 in the high word. +for high, bits in ((0, 0x3c00), (1, 0x4000)): + raw = encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x40003c00, + op_sel=(high, 0, 0), op_sel_hi=(1, 0, 0)) + suffix = (' op_sel:[1,0,0]' if high else '') + ' op_sel_hi:[1,0,0]' + expect('select literal half %d' % high, raw, + 'v_fma_mix_f32 v1, 0x40003c00, v3, v4' + suffix, + 'v1 = U(f16tof32(0x%04xu) * F(v3) + F(v4));' % bits) + +expect('inline half on a low binary16 source', + encode(MIX_F32, 1, (240, v3, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(0.5 * F(v3) + F(v4));') +expect_refused('unverified high half of inline constant', + encode(MIX_F32, 1, (240, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]') + + +def compile_translated(fxc): + """Compile every translated line in one ps_5_1 entry point; returns FXC's exit status and output.""" + regs = sorted({int(n) for line in translated for n in re.findall(r'\bv(\d+)\b', line)}) + body = ['#define F asfloat', '#define U asuint', + 'uint main(nointerpolation uint4 p : TEXCOORD0) : SV_Target {', + ' uint s5 = p.y;'] + body += [' uint v%d = p.x + %du;' % (r, r) for r in regs] + body += [' ' + line for line in translated] + body += [' return %s;' % ' ^ '.join('v%d' % r for r in regs), '}'] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, 'fma_mix.hlsl') + with open(src, 'w') as fh: + fh.write('\n'.join(body) + '\n') + run = subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', os.path.join(d, 'fma_mix.cso'), src], + capture_output=True, text=True) + return run.returncode, (run.stdout + run.stderr).strip() + + +# --- dispatch mode: run the translated lines on a D3D12 device and compare with a CPU reference ---- +# +# The reference decodes each VOP3P word itself (layout in the module docstring), without +# tools/disasm_rdna2.py or gfx2hlsl, and applies the LLVM 15 reading: op_sel_hi = binary16 source, +# op_sel = its high half, abs then neg after widening, clamp = saturate. Inputs have short mantissas, +# so the product and sum are exact in binary32 and binary16, and a fused and an unfused multiply-add +# give the same word. + +INLINE_F32 = {240: 0.5, 241: -0.5, 242: 1.0, 243: -1.0, 244: 2.0, 245: -2.0, 246: 4.0, 247: -4.0} +F32_INPUT = {'v2': 1.25, 'v3': -0.75, 'v4': 3.0, 's5': 0.5} # binary32 reads +F16_INPUT = {'v2': (1.5, -2.5), 'v3': (0.75, 4.0), 'v4': (-1.25, 0.5), 's5': (2.0, -3.0)} # (low, high) +V1_BEFORE = 0x13579bdf # mixlo/mixhi keep one half of the destination +# The -0 case needs a zero product: a +0 addend would give +0, the -0 addend keeps -0. +OVERRIDES = {'negated inline 0 addend keeps a -0 product': {'v2': 0x80000000}} + + +def f32_word(value): + return struct.unpack('= 12 else None + return { + 'op': (w0 >> 16) & 0x7f, 'clamp': (w0 >> 15) & 1, + 'srcs': [w1 & 0x1ff, (w1 >> 9) & 0x1ff, (w1 >> 18) & 0x1ff], + 'op_sel': [(w0 >> (11 + i)) & 1 for i in range(3)], + 'op_sel_hi': [(w1 >> 27) & 1, (w1 >> 28) & 1, (w0 >> 14) & 1], + 'abs': [(w0 >> (8 + i)) & 1 for i in range(3)], + 'neg': [(w1 >> (29 + i)) & 1 for i in range(3)], + 'literal': literal, + } + + +def is_register(src): + return src >= V or src < 106 + + +def register_name(src): + return 'v%d' % (src - V) if src >= V else 's%d' % src + + +def case_inputs(label, fields): + """Register words for one case: each source register gets a value in the format it is read as.""" + words = {'v1': V1_BEFORE} + for src, half in zip(fields['srcs'], fields['op_sel_hi']): + if is_register(src): + name = register_name(src) + if half: + low, high = F16_INPUT[name] + words[name] = f16_word(low) | (f16_word(high) << 16) + else: + words[name] = f32_word(F32_INPUT[name]) + words.update(OVERRIDES.get(label, {})) + return words + + +def source_value(src, half, high, words, literal): + if is_register(src): + word = words[register_name(src)] + elif src == 255: + word = literal + elif src == 128: + return 0.0 + elif src in INLINE_F32: + assert not high, 'the translator refuses the high half of an inline constant' + return INLINE_F32[src] + else: + raise ValueError('source %d has no reference' % src) + if half: + return struct.unpack('> (16 * high)) & 0xffff))[0] + return struct.unpack('> 16)', ')') for line in lines] + changed = [i for i, (a, b) in enumerate(zip(lines, mutated)) if a != b] + control = run_dispatch(dxc, runner, adapter, dispatch_source(rows, mutated), len(rows) * 6, directory, + 'fma_mix_control') + low_reads = [] + for i in changed: + fields = decode_mix(cases[i][1]) + fields['op_sel'] = [0, 0, 0] + low_reads.append(reference(fields, rows[i][1])) + follows = all(control[i * 6 + 5] == want for i, want in zip(changed, low_reads)) + caught = [i for i in changed if control[i * 6 + 5] != expected[i]] + check('%s: control without the high-half shift reads the low half in all %d high-half cases' + % (adapter, len(changed)), bool(changed) and follows) + check('%s: control changes %d of %d high-half results' % (adapter, len(caught), len(changed)), + len(caught) > 0) + + +if len(sys.argv) == 3 and sys.argv[1] == 'fxc': + status, output = compile_translated(sys.argv[2]) + check(f'fxc ps_5_1 compiles all {len(translated)} translated lines', status == 0, output) +elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) +elif len(sys.argv) != 1: + print(__doc__) + sys.exit(2) + +if failures: + print(f'FAILED: {len(failures)} check(s): {", ".join(failures)}') + sys.exit(1) +print('all fma_mix checks passed') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6aaaa60bf..3024ca8a4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4937,34 +4937,85 @@ def note_attr(self, tok, how): self.attrs.setdefault(attr, set()).add(how) return attr, component - def mix(self, ops, mods, high): - """v_fma_mix{lo,hi}_f16: fma of operands that are f32 or f16 halves; the f16 result goes to one half.""" - sel = [0, 0, 0] + def mix(self, ops, mods, dest): + """v_fma_mix_f32 / v_fma_mix{lo,hi}_f16: fma of sources that are binary32 words or binary16 halves. + + Per source (LLVM 15 SelectVOP3PMadMixModsImpl): op_sel_hi set means the source is binary16, and + op_sel set picks its high half. abs, then neg, apply after widening. dest is 'f32', 'lo' or 'hi'. + """ + half, hi, clamp = [0, 0, 0], [0, 0, 0], False for m in mods: - if m.startswith('op_sel_hi:'): - sel = [int(x) for x in m[11:-1].split(',')] - elif m.startswith('op_sel:'): - raise Unsupported('op_sel on fma_mix') - def operand(tok, is_half): - if not is_half or tok in ('-0', '0'): + if m.startswith('op_sel_hi:['): + half = [int(x) for x in m[11:-1].split(',')] + elif m.startswith('op_sel:['): + hi = [int(x) for x in m[8:-1].split(',')] + elif m == 'clamp': + clamp = True + else: + raise Unsupported('fma_mix modifier %s' % m) + + def operand(tok, is_half, is_hi): + if not is_half and is_hi: + raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) + if tok == '-0': + # neg on inline 0 is -0.0 in either format; f() would print +0.0, which changes a -0 product. + return '(-0.0)' + if not is_half: + if tok.startswith('--') and tok[1:] in FLOATS: + # neg on a negative inline float prints as `--0.5`; `(--0.5)` is an HLSL decrement. + return '(-(%s))' % self.f(tok[1:]) + if re.fullmatch(r'-(\d+|0x[0-9a-fA-F]+)', tok): + # The decoder prints neg on inline 1..64 or a literal as a negative integer, which f() + # reads without the sign-bit flip. Refuse until the decoder resolves it from the encoding. + raise Unsupported('negated integer or literal fma_mix source %s' % tok) return self.f(tok) - return 'f16tof32(%s)' % self.u(tok, low16_only=True) - expr = '%s * %s + %s' % tuple(operand(t, s) for t, s in zip(ops[1:4], sel)) - if 'clamp' in mods: + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + r = reg_range(tok) + if tok == '0': + text = '0.0' + elif re.fullmatch(r'0x[0-9a-fA-F]{1,8}', tok): + word = (int(tok, 16) >> (16 if is_hi else 0)) & 0xffff + text = 'f16tof32(0x%04xu)' % word + elif tok == '0.5' and not is_hi: + text = '0.5' + elif r and r[1] == r[2]: + # Only a high-half read needs the upper 16 bits defined. + text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') + else: + raise Unsupported('binary16 fma_mix source %s' % tok) + if absolute: + text = 'abs(%s)' % text + return '(-%s)' % text if neg else text + + # v_fma_mix* is fused, but HLSL may round `a * b` before the add, so binary32 sources with long + # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). + expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) + if clamp: expr = 'saturate(%s)' % expr d = reg_range(ops[0])[1] + if dest == 'f32': + self.set_v(d, 'U(%s)' % expr) + return self.used_v.add(d) - if high: + if dest == 'hi': self.set_v(d, '(v%d & 0xffffu) | (f32tof16(%s) << 16)' % (d, expr)) else: keep_low16 = d in self.low16_only_v self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr), low16_only=keep_low16) + def op_v_fma_mix_f32(self, ops, mods): + self.mix(ops, mods, 'f32') + def op_v_fma_mixlo_f16(self, ops, mods): - self.mix(ops, mods, False) + self.mix(ops, mods, 'lo') def op_v_fma_mixhi_f16(self, ops, mods): - self.mix(ops, mods, True) + self.mix(ops, mods, 'hi') def cube(self, kind, ops, mods): """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic. From c15db1286a074d7d2fd20f1b53ae0b9d057f9d47 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:55:59 +0200 Subject: [PATCH 169/232] runtime: extract main(argv) and add path/collision/OSError guards in archive_requests with CLI suite (#2555) --- CMakeLists.txt | 2 + tests/startup_archive_requests_cli_check.py | 410 ++++++++++++++++++++ tools/startup/archive_requests.py | 100 +++-- 3 files changed, 480 insertions(+), 32 deletions(-) create mode 100644 tests/startup_archive_requests_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 9393083bd..d9e869f2d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3033,6 +3033,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_archive_requests COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_archive_requests_check.py") set_tests_properties(startup_archive_requests PROPERTIES TIMEOUT 120) + add_test(NAME startup_archive_requests_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_archive_requests_cli_check.py") # Two integer operations whose refusal was never reached: v_cvt_i32_f32 with an output # modifier, and v_readfirstlane_b32 without a proven uniform source. add_test(NAME startup_gfx2hlsl_op_refusals COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/startup_archive_requests_cli_check.py b/tests/startup_archive_requests_cli_check.py new file mode 100644 index 000000000..f24f57370 --- /dev/null +++ b/tests/startup_archive_requests_cli_check.py @@ -0,0 +1,410 @@ +"""CLI, path-collision, error-guard, and mutation control suite for tools/startup/archive_requests.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "startup" / "archive_requests.py" +sys.path.insert(0, str(ROOT / "tools" / "startup")) + +import archive_requests # noqa: E402 +import gfx2hlsl # noqa: E402 + +PREFETCH = bytes.fromhex("0300a0bf") +CODE_END = bytes.fromhex("00009fbf") +ENDPGM = struct.pack(" bytes: + target = {"vs": 12, "ps": 0}[stage] + header = b"\x00\x00\x80\xd5" + struct.pack(" bytes: + buf = bytearray(length) + for at, blob in layout: + buf[at:at + len(blob)] = blob + return bytes(buf) + + +def _synthetic_pair_archive() -> tuple[bytes, bytes, bytes]: + ps_blob = _program("ps", 1) + vs_blob = _program("vs", 2, blocks=2) + payload = _stream([(0x2C, ps_blob), (0x12C, vs_blob)]) + return zlib.compress(payload, 9), ps_blob, vs_blob + + +def _parse_stats(line: str) -> dict[str, int]: + tokens = line.strip().split() + return {key: int(value) for key, value in (tok.split("=", 1) for tok in tokens)} + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = archive_requests.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class ArchiveRequestsCliPositiveTests(unittest.TestCase): + def test_main_writes_requests_returns_zero_and_preserves_stdout_stats(self) -> None: + archive_bytes, ps_blob, vs_blob = _synthetic_pair_archive() + root_bytes = b"DXBC-synthetic-root-one" + expected_key = gfx2hlsl.pipeline_key(ps_blob, vs_blob, root_bytes) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + roots_dir = root / "roots" + roots_dir.mkdir() + (roots_dir / "req_0000000000000001.root").write_bytes(root_bytes) + cache = root / "cache" + + argv = [str(archive), str(cache), "--roots", str(roots_dir)] + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + + stats = _parse_stats(out) + self.assertEqual( + list(stats), + [ + "streams", "oversized", "programs", "incomplete", "ps", "vs", + "other", "undecodable", "pairs", "written", "existing", "failed", "roots", + ], + ) + self.assertEqual( + (stats["streams"], stats["pairs"], stats["written"], stats["existing"], stats["failed"], stats["roots"]), + (1, 1, 1, 0, 0, 1), + ) + stem = cache / f"req_{expected_key:016x}" + self.assertEqual(stem.with_suffix(".a").read_bytes(), ps_blob) + self.assertEqual(stem.with_suffix(".b").read_bytes(), vs_blob) + self.assertEqual(stem.with_suffix(".root").read_bytes(), root_bytes) + self.assertEqual(list(cache.glob("*.tmp")), []) + + # Second run via subprocess reports existing=1, written=0, exit 0. + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + again_stats = _parse_stats(proc.stdout) + self.assertEqual((again_stats["written"], again_stats["existing"], again_stats["roots"]), (0, 1, 1)) + + def test_main_forwards_sys_argv_default_cache_roots_and_script_entrypoint(self) -> None: + archive_bytes, ps_blob, vs_blob = _synthetic_pair_archive() + root_bytes = b"DXBC-default-cache-root" + expected_key = gfx2hlsl.pipeline_key(ps_blob, vs_blob, root_bytes) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + cache = root / "cache_with_root" + cache.mkdir() + (cache / "req_0000000000000000.root").write_bytes(root_bytes) + + cli_argv = [str(TOOL), str(archive), str(cache)] + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(_parse_stats(out)["written"], 1) + self.assertTrue((cache / f"req_{expected_key:016x}.a").is_file()) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(_parse_stats(stdout.getvalue())["existing"], 1) + + +class ArchiveRequestsCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + expect_stdout_stats: bool = False, + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + if expect_stdout_stats: + self.assertTrue(out.strip()) + else: + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected non-empty stderr for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + if expect_stdout_stats: + self.assertTrue(proc.stdout.strip()) + else: + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected non-empty subprocess stderr for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + + def test_missing_and_directory_archive_rejected_upfront_without_reading_roots(self) -> None: + # Kills removal of upfront archive.is_dir() and not archive.is_file() guards. + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.rpf" + cache = root / "cache_missing" + with mock.patch.object(archive_requests, "read_roots") as read_roots_mock: + self._assert_clean_failure( + [str(missing), str(cache)], + expected_fragments=("Archive path is not a regular file",), + check_subprocess=False, + ) + read_roots_mock.assert_not_called() + self.assertFalse(cache.exists()) + self._assert_clean_failure( + [str(missing), str(cache)], + expected_fragments=("Archive path is not a regular file",), + ) + + dir_archive = root / "dir_archive" + dir_archive.mkdir() + with mock.patch.object(archive_requests, "read_roots") as read_roots_mock: + self._assert_clean_failure( + [str(dir_archive), str(cache)], + expected_fragments=("Archive path is a directory",), + check_subprocess=False, + ) + read_roots_mock.assert_not_called() + self._assert_clean_failure( + [str(dir_archive), str(cache)], + expected_fragments=("Archive path is a directory",), + ) + + # Direct streams() API checks. + with self.assertRaisesRegex(ValueError, "directory"): + list(archive_requests.streams(dir_archive, {})) + with self.assertRaisesRegex(ValueError, "Missing archive"): + list(archive_requests.streams(missing, {})) + + def test_cache_regular_file_and_collisions_rejected_upfront(self) -> None: + # Kills removal of cache.is_dir() and _same_path() resolve()/samefile() checks. + archive_bytes, _, _ = _synthetic_pair_archive() + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + sub = root / "sub" + sub.mkdir() + roots_dir = root / "roots" + roots_dir.mkdir() + root_file = roots_dir / "req_0000000000000001.root" + root_file.write_bytes(b"DXBC-root") + + file_cache = root / "regular_file.bin" + file_cache.write_bytes(b"keep-me") + with mock.patch.object(archive_requests, "read_roots") as read_roots_mock: + self._assert_clean_failure( + [str(archive), str(file_cache), "--roots", str(roots_dir)], + expected_fragments=("Cache path is not a directory",), + check_subprocess=False, + ) + read_roots_mock.assert_not_called() + self.assertEqual(file_cache.read_bytes(), b"keep-me") + self._assert_clean_failure( + [str(archive), str(file_cache), "--roots", str(roots_dir)], + expected_fragments=("Cache path is not a directory",), + ) + + # 1) Cache colliding with archive via relative alias (resolve()) and hardlink (samefile()). + archive_alias = sub / ".." / "shaders.rpf" + hardlink_archive = root / "shaders_hardlink.rpf" + os.link(archive, hardlink_archive) + self.assertNotEqual(archive.resolve(), hardlink_archive.resolve()) + self.assertTrue(archive.samefile(hardlink_archive)) + + for bad_cache in (archive_alias, hardlink_archive): + with self.subTest(bad_cache=str(bad_cache)): + with mock.patch.object(archive_requests, "read_roots") as read_roots_mock: + self._assert_clean_failure( + [str(archive), str(bad_cache), "--roots", str(roots_dir)], + expected_fragments=("Cache directory collides with archive",), + check_subprocess=False, + ) + read_roots_mock.assert_not_called() + self._assert_clean_failure( + [str(archive), str(bad_cache), "--roots", str(roots_dir)], + expected_fragments=("Cache directory collides with archive",), + ) + + # 2) Cache colliding with --roots directory or file (including non-existent resolve() alias & hardlink). + roots_alias = sub / ".." / "roots" + ghost_roots = root / "ghost_roots" + ghost_cache = sub / ".." / "ghost_roots" + hardlink_root = root / "root_hardlink.root" + os.link(root_file, hardlink_root) + for cache_arg, roots_arg in ( + (roots_alias, roots_dir), + (ghost_cache, ghost_roots), + (hardlink_root, root_file), + ): + with self.subTest(cache=str(cache_arg), roots=str(roots_arg)): + with mock.patch.object(archive_requests, "read_roots") as read_roots_mock: + self._assert_clean_failure( + [str(archive), str(cache_arg), "--roots", str(roots_arg)], + expected_fragments=("Cache directory collides with --roots",), + check_subprocess=False, + ) + read_roots_mock.assert_not_called() + self._assert_clean_failure( + [str(archive), str(cache_arg), "--roots", str(roots_arg)], + expected_fragments=("Cache directory collides with --roots",), + ) + + def test_roots_validation_and_write_failure_atomic_cleanup(self) -> None: + archive_bytes, ps_blob, vs_blob = _synthetic_pair_archive() + root_bytes = b"DXBC-root" + key = gfx2hlsl.pipeline_key(ps_blob, vs_blob, root_bytes) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + absent_roots = root / "absent_roots" + cache = root / "cache" + + with self.assertRaisesRegex(ValueError, "root signature path not found"): + archive_requests.read_roots([str(absent_roots)]) + + self._assert_clean_failure( + [str(archive), str(cache), "--roots", str(absent_roots)], + expected_fragments=("root signature path not found",), + ) + self.assertFalse(cache.exists()) + + # Empty roots directory -> "no root signature found", cache untouched. + empty_roots = root / "empty_roots" + empty_roots.mkdir() + self._assert_clean_failure( + [str(archive), str(cache), "--roots", str(empty_roots)], + expected_fragments=("no root signature found",), + ) + self.assertFalse(cache.exists()) + + # Directory matching req_*.root inside --roots -> clean ValueError, exit 1. + bad_roots = root / "bad_roots" + (bad_roots / "req_0000000000000000.root").mkdir(parents=True) + with self.assertRaisesRegex(ValueError, "directory"): + archive_requests.read_roots([str(bad_roots)]) + self._assert_clean_failure( + [str(archive), str(cache), "--roots", str(bad_roots)], + expected_fragments=("root signature path is a directory",), + ) + + # Blocked .root destination leaves 0 *.tmp and 0 .a, prints stats, exits 1. + valid_roots = root / "valid_roots" + valid_roots.mkdir() + (valid_roots / "req_0000000000000001.root").write_bytes(root_bytes) + blocked_cache = root / "blocked_cache" + blocked_cache.mkdir() + (blocked_cache / f"req_{key:016x}.root").mkdir() + self._assert_clean_failure( + [str(archive), str(blocked_cache), "--roots", str(valid_roots)], + expected_fragments=("could not be written",), + expect_stdout_stats=True, + ) + self.assertFalse((blocked_cache / f"req_{key:016x}.a").exists()) + self.assertEqual(list(blocked_cache.glob("*.tmp")), []) + + # Archive without any pair -> prints stats, exits 1. + nopair = root / "nopair.rpf" + nopair.write_bytes(zlib.compress(_stream([(0x2C, ps_blob)]), 9)) + self._assert_clean_failure( + [str(nopair), str(root / "nopair_cache"), "--roots", str(valid_roots)], + expected_fragments=("no program pair found",), + expect_stdout_stats=True, + ) + + def test_oserror_struct_error_and_zlib_error_guards_in_main(self) -> None: + # Kills removal of OSError, struct.error, and zlib.error from except tuple in main(). + archive_bytes, _, _ = _synthetic_pair_archive() + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + roots_dir = root / "roots" + roots_dir.mkdir() + (roots_dir / "req_0000000000000001.root").write_bytes(b"DXBC-root") + cache = root / "cache" + argv = [str(archive), str(cache), "--roots", str(roots_dir)] + + with mock.patch.object(archive_requests.os, "makedirs", side_effect=OSError("simulated mkdir failure")): + self._assert_clean_failure( + argv, + expected_fragments=("simulated mkdir failure",), + check_subprocess=False, + ) + + for exc_obj, fragment in ( + (struct.error("unpack_from requires a buffer of at least 4 bytes"), "unpack_from requires a buffer"), + (zlib.error("Error -3 while decompressing data: incorrect header check"), "Error -3 while decompressing data"), + ): + with self.subTest(exc=type(exc_obj).__name__): + with mock.patch.object(archive_requests, "streams", side_effect=exc_obj): + self._assert_clean_failure( + argv, + expected_fragments=(fragment,), + check_subprocess=False, + ) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "empty.rpf" + archive.write_bytes(b"") + for bad_argv in ([], [str(archive)], [str(archive), str(Path(tmp) / "cache"), "--unknown-flag"]): + with self.subTest(argv=bad_argv): + self._assert_clean_failure(bad_argv, expected_code=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup/archive_requests.py b/tools/startup/archive_requests.py index 34bfa01c6..2ced6ac87 100644 --- a/tools/startup/archive_requests.py +++ b/tools/startup/archive_requests.py @@ -13,9 +13,12 @@ Translate the result with gfx2hlsl.py --pending . """ import argparse +from collections.abc import Sequence import glob import mmap import os +from pathlib import Path +import struct import sys import zlib @@ -108,10 +111,21 @@ def chunks(view, counts): at += 64 +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + def streams(archive, counts): """Yield (archive offset, inflated bytes); a zlib stream that starts on the 64-byte boundary right after the previous one continues it, so a program split between the two is carved whole.""" - with open(archive, 'rb') as file: + path = Path(archive) + if path.is_dir(): + raise ValueError(f"Archive path is a directory: {archive}") + if not path.is_file(): + raise ValueError(f"Missing archive file: {archive}") + with open(path, 'rb') as file: if os.fstat(file.fileno()).st_size == 0: return with mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as view: @@ -133,9 +147,14 @@ def read_roots(paths): roots = [] for path in paths: if not os.path.exists(path): - sys.exit('root signature path not found: %s' % path) - files = sorted(glob.glob(os.path.join(path, 'req_*.root'))) if os.path.isdir(path) else [path] + raise ValueError('root signature path not found: %s' % path) + if os.path.isdir(path): + files = sorted(glob.glob(os.path.join(glob.escape(os.fspath(path)), 'req_*.root'))) + else: + files = [path] for name in files: + if os.path.isdir(name): + raise ValueError('root signature path is a directory: %s' % name) with open(name, 'rb') as file: blob = file.read() if blob and blob not in roots: @@ -163,46 +182,63 @@ def write_request(cache, key, a, b, root): return 'written' -def main(): +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument('archive') parser.add_argument('cache') parser.add_argument('--roots', nargs='+', help='req_*.root files or directories (default: the cache)') - args = parser.parse_args() - roots = read_roots(args.roots or [args.cache]) - if not roots: - sys.exit('no root signature found: run the title once with a shader cache, or pass --roots') - os.makedirs(args.cache, exist_ok=True) + args = parser.parse_args(argv) # streams counts joined runs of consecutive zlib streams counts = dict(streams=0, oversized=0, programs=0, incomplete=0, ps=0, vs=0, other=0, undecodable=0, pairs=0, written=0, existing=0, failed=0) - for _, data in streams(args.archive, counts): - counts['streams'] += 1 - previous = None # (stage, offset, program) of the program carved just before - for at, program in carve(data): - counts['programs'] += 1 - if not complete(program): - counts['incomplete'] += 1 - previous = None - continue - stage = stage_of(program) - counts[stage] += 1 - # directly following: the vertex program starts on the 256-byte step after the pixel program - if stage == 'vs' and previous and previous[0] == 'ps' and at == next_step(previous[1], previous[2]): - counts['pairs'] += 1 - for root in roots: - # The runtime hashes its first recorded blob (the pixel program here) first. - # pipeline_key names its parameters vs_code, ps_code; only the order matters. - key = gfx2hlsl.pipeline_key(previous[2], program, root) - counts[write_request(args.cache, key, previous[2], program, root)] += 1 - previous = (stage, at, program) + try: + archive = Path(args.archive) + cache = Path(args.cache) + if archive.is_dir(): + raise ValueError(f'Archive path is a directory: {args.archive}') + if not archive.is_file(): + raise ValueError(f'Archive path is not a regular file: {args.archive}') + if _same_path(cache, archive): + raise ValueError(f'Cache directory collides with archive: {args.cache}') + for root_path in args.roots or (): + if _same_path(cache, Path(root_path)): + raise ValueError(f'Cache directory collides with --roots path: {args.cache}') + if cache.exists() and not cache.is_dir(): + raise ValueError(f'Cache path is not a directory: {args.cache}') + roots = read_roots(args.roots or [args.cache]) + if not roots: + raise ValueError('no root signature found: run the title once with a shader cache, or pass --roots') + os.makedirs(args.cache, exist_ok=True) + for _, data in streams(args.archive, counts): + counts['streams'] += 1 + previous = None # (stage, offset, program) of the program carved just before + for at, program in carve(data): + counts['programs'] += 1 + if not complete(program): + counts['incomplete'] += 1 + previous = None + continue + stage = stage_of(program) + counts[stage] += 1 + # directly following: the vertex program starts on the 256-byte step after the pixel program + if stage == 'vs' and previous and previous[0] == 'ps' and at == next_step(previous[1], previous[2]): + counts['pairs'] += 1 + for root in roots: + # The runtime hashes its first recorded blob (the pixel program here) first. + # pipeline_key names its parameters vs_code, ps_code; only the order matters. + key = gfx2hlsl.pipeline_key(previous[2], program, root) + counts[write_request(args.cache, key, previous[2], program, root)] += 1 + previous = (stage, at, program) + except (OSError, ValueError, struct.error, zlib.error) as error: + parser.exit(1, f'{error}\n') counts['roots'] = len(roots) print(' '.join('%s=%d' % item for item in counts.items())) if counts['failed']: - sys.exit('%d request(s) could not be written' % counts['failed']) + parser.exit(1, '%d request(s) could not be written\n' % counts['failed']) if not counts['pairs']: - sys.exit('no program pair found in %s' % args.archive) + parser.exit(1, 'no program pair found in %s\n' % args.archive) + return 0 if __name__ == '__main__': - main() + raise SystemExit(main()) From d38d2247b1e6be0c1c0171b32c0c3b8daaa5045e Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 22:59:06 +0200 Subject: [PATCH 170/232] textures: extract main(argv), atomic manifest writes, and path/JSON/bounds guards in ttpf_batch_export with CLI suite (#2558) --- CMakeLists.txt | 2 + tests/ttpf_batch_export_cli_check.py | 414 +++++++++++++++++++++++++++ tools/ttpf_batch_export.py | 88 +++++- 3 files changed, 489 insertions(+), 15 deletions(-) create mode 100644 tests/ttpf_batch_export_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d9e869f2d..6e3254094 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8591,6 +8591,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/resource_ranges_check.py") add_test(NAME ttpf_batch_export COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/ttpf_batch_export_check.py") + add_test(NAME ttpf_batch_export_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/ttpf_batch_export_cli_check.py") add_test(NAME audio_awc_metadata COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/awc_metadata_check.py") add_test(NAME audio_awc_metadata_cli_check COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/ttpf_batch_export_cli_check.py b/tests/ttpf_batch_export_cli_check.py new file mode 100644 index 000000000..c703ef5e0 --- /dev/null +++ b/tests/ttpf_batch_export_cli_check.py @@ -0,0 +1,414 @@ +"""CLI, atomic manifest, path/JSON/bounds guard, and mutation suite for tools/ttpf_batch_export.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "ttpf_batch_export.py" +sys.path.insert(0, str(ROOT / "tools")) + +import ttpf_batch_export as batch # noqa: E402 + + +SYNTHETIC_TTPF_MIPS = '''\ +from pathlib import Path +import struct + +BC_FORMATS = {71, 98} + + +class Pool: + def __init__(self, path): + raw = Path(path).read_bytes() + if raw.startswith(b"BADSTRUCT"): + struct.unpack(" Path: + tools_dir.mkdir(parents=True, exist_ok=True) + (tools_dir / "ttpf_mips.py").write_text(SYNTHETIC_TTPF_MIPS, encoding="ascii") + return tools_dir + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = batch.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class TtpfBatchExportCliPositiveTests(unittest.TestCase): + def test_atomic_nested_manifest_summary_schema_and_count_zero(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + tools_dir = _write_fake_tools(root / "fake_tools") + pool = root / "sample.ttpf" + pool.write_bytes(b"RDS5_SYNTHETIC") + out_dir = root / "out" / "dds" + manifest_path = root / "manifests" / "nested" / "manifest.json" + self.assertFalse(out_dir.exists()) + self.assertFalse(manifest_path.parent.exists()) + + replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + replaces.append((src_path, dst_path)) + if dst_path == manifest_path: + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with mock.patch.object(batch.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([ + str(pool), + "-o", str(out_dir), + "--start", "1", + "--count", "2", + "--threads", "1", + "--manifest", str(manifest_path), + "--tools-path", str(tools_dir), + ]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + summary = json.loads(out) + self.assertEqual( + set(summary), + {"pool", "total_textures", "processed", "manifest", "entries", "elapsed_seconds", "stats"}, + ) + self.assertEqual(summary["total_textures"], 3) + self.assertEqual(summary["processed"], 2) + self.assertEqual(summary["entries"], 2) + self.assertEqual(summary["stats"], {"strict": 2, "provisional": 0, "failed": 0, "skipped": 0}) + self.assertTrue(any(dst == manifest_path for _, dst in replaces)) + self.assertEqual([p.name for p in manifest_path.parent.iterdir()], ["manifest.json"]) + entries = json.loads(manifest_path.read_text(encoding="utf-8")) + self.assertEqual([e["index"] for e in entries], [1, 2]) + + # --count 0 is valid and produces an empty manifest cleanly. + proc_zero = _run_subprocess( + str(pool), + "-o", str(out_dir), + "--count", "0", + "--manifest", str(manifest_path), + "--tools-path", str(tools_dir), + ) + self.assertEqual(proc_zero.returncode, 0, proc_zero.stderr) + summary_zero = json.loads(proc_zero.stdout) + self.assertEqual(summary_zero["processed"], 0) + self.assertEqual(json.loads(manifest_path.read_text(encoding="utf-8")), []) + + def test_main_sys_argv_forwarding_and_script_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + tools_dir = _write_fake_tools(root / "fake_tools") + pool = root / "entry.ttpf" + pool.write_bytes(b"RDS5_ENTRY") + out_dir = root / "entry_out" + cli_argv = [ + str(TOOL), + str(pool), + "-o", str(out_dir), + "--count", "1", + "--tools-path", str(tools_dir), + ] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(out)["processed"], 1) + self.assertTrue((out_dir / "manifest.json").is_file()) + + (out_dir / "manifest.json").unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue())["processed"], 1) + self.assertTrue((out_dir / "manifest.json").is_file()) + + +class TtpfBatchExportCliNegativeAndMutationTests(unittest.TestCase): + def _assert_exit_2_clean(self, argv, *, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_pool_missing_or_directory_and_out_file_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"RDS5") + pool_dir = root / "pool_dir" + pool_dir.mkdir() + existing_file = root / "not_a_dir.txt" + existing_file.write_text("keep", encoding="utf-8") + + with mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean([str(root / "missing.ttpf")], expected_fragment="Pool not found") + self._assert_exit_2_clean([str(pool_dir)], expected_fragment="regular file") + self._assert_exit_2_clean([str(pool), "-o", str(existing_file)], expected_fragment="not a directory") + load_mock.assert_not_called() + self.assertEqual(existing_file.read_text(encoding="utf-8"), "keep") + + def test_bounds_threads_start_count_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"RDS5") + out_dir = root / "never_created" + + for flag, bad_val, frag in ( + ("--threads", "0", "--threads must be >= 1"), + ("--threads", "-2", "--threads must be >= 1"), + ("--start", "-1", "--start must be >= 0"), + ("--count", "-1", "--count must be >= 0"), + ): + with self.subTest(flag=flag, val=bad_val): + with mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), flag, bad_val], + expected_fragment=frag, + ) + load_mock.assert_not_called() + self.assertFalse(out_dir.exists()) + + def test_manifest_dir_and_pool_or_out_collisions_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + pool = root / "pool.ttpf" + pool_bytes = b"RDS5_POOL" + pool.write_bytes(pool_bytes) + existing_dir = root / "manifest_dir" + existing_dir.mkdir() + out_dir = root / "never_out" + + # 1) --manifest is an existing directory. + with mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--manifest", str(existing_dir)], + expected_fragment="existing directory", + ) + load_mock.assert_not_called() + self.assertFalse(out_dir.exists()) + + # 2) --manifest collides with pool via resolve() (kills resolve() check). + alias_manifest = root / "sub" / ".." / "pool.ttpf" + with mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--manifest", str(alias_manifest)], + expected_fragment="collides with pool", + ) + load_mock.assert_not_called() + + # 3) --manifest collides with pool via hardlink samefile() (kills samefile() check). + hardlink_manifest = sub / "pool_link.json" + os.link(pool, hardlink_manifest) + self.assertNotEqual(pool.resolve(), hardlink_manifest.resolve()) + self.assertTrue(pool.samefile(hardlink_manifest)) + with mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--manifest", str(hardlink_manifest)], + expected_fragment="collides with pool", + ) + load_mock.assert_not_called() + self.assertEqual(pool.read_bytes(), pool_bytes) + + # 4) --manifest collides with --out or is an ancestor of --out. + with mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--manifest", str(out_dir)], + expected_fragment="collides with --out", + ) + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir / "child"), "--manifest", str(out_dir)], + expected_fragment="ancestor of --out", + ) + load_mock.assert_not_called() + self.assertFalse(out_dir.exists()) + + def test_history_calibration_and_tools_path_guards(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pool = root / "pool.ttpf" + pool.write_bytes(b"RDS5") + out_dir = root / "never_out" + a_dir = root / "a_dir" + a_dir.mkdir() + bad_json = root / "bad.json" + bad_json.write_text("{broken", encoding="utf-8") + list_json = root / "list.json" + list_json.write_text("[]", encoding="utf-8") + bad_ver = root / "bad_ver.json" + bad_ver.write_text('{"version": 2}', encoding="utf-8") + regular_file = root / "not_tools.txt" + regular_file.write_text("x", encoding="utf-8") + + # --history: directory, bad JSON, non-dict JSON, missing file (even without --allow-provisional) + for h_path, frag in ( + (a_dir, "directory"), + (bad_json, "--history"), + (list_json, "JSON object"), + (root / "missing_hist.json", "--history"), + ): + with self.subTest(history=h_path), mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--allow-provisional", "--history", str(h_path)], + expected_fragment=frag, + ) + load_mock.assert_not_called() + + # --calibration: directory, bad JSON, wrong version, missing file + for c_path, frag in ( + (a_dir, "directory"), + (bad_json, "--calibration"), + (bad_ver, "Unsupported calibration version"), + (root / "missing_cal.json", "--calibration"), + ): + with self.subTest(calibration=c_path), mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--calibration", str(c_path)], + expected_fragment=frag, + ) + load_mock.assert_not_called() + + # --tools-path: missing or regular file + for t_path, frag in ( + (root / "missing_tools", "--tools-path not found"), + (regular_file, "--tools-path must be a directory"), + ): + with self.subTest(tools_path=t_path), mock.patch.object(batch, "load_tools") as load_mock: + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--tools-path", str(t_path)], + expected_fragment=frag, + ) + load_mock.assert_not_called() + self.assertFalse(out_dir.exists()) + + def test_struct_error_from_pool_caught_cleanly_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + tools_dir = _write_fake_tools(root / "fake_tools") + bad_pool = root / "bad_struct.ttpf" + bad_pool.write_bytes(b"BADSTRUCT") + out_dir = root / "out_bad_struct" + + self._assert_exit_2_clean( + [str(bad_pool), "-o", str(out_dir), "--tools-path", str(tools_dir)], + expected_fragment="unpack requires", + ) + self.assertFalse(out_dir.exists()) + + def test_manifest_os_replace_failure_leaves_zero_temp_dirs_and_preserves_prior(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + tools_dir = _write_fake_tools(root / "fake_tools") + pool = root / "pool.ttpf" + pool.write_bytes(b"RDS5") + out_dir = root / "out" + manifest_dir = root / "manifest_out" + manifest_path = manifest_dir / "manifest.json" + real_replace = os.replace + + def fail_manifest_replace(src, dst): + if Path(dst) == manifest_path: + self.assertTrue(Path(src).is_file()) + raise OSError("simulated manifest replace failure") + return real_replace(src, dst) + + # 1) Fresh manifest: os.replace fails -> exit 2, zero temp dirs, zero manifest files. + with mock.patch.object(batch.os, "replace", side_effect=fail_manifest_replace): + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--count", "1", "--threads", "1", + "--manifest", str(manifest_path), "--tools-path", str(tools_dir)], + expected_fragment="simulated manifest replace failure", + check_subprocess=False, + ) + self.assertEqual(list(manifest_dir.iterdir()), []) + + # 2) Pre-existing manifest: os.replace fails -> prior file intact, zero temp dirs. + manifest_path.write_text("prior-manifest\n", encoding="utf-8") + with mock.patch.object(batch.os, "replace", side_effect=fail_manifest_replace): + self._assert_exit_2_clean( + [str(pool), "-o", str(out_dir), "--count", "1", "--threads", "1", + "--manifest", str(manifest_path), "--tools-path", str(tools_dir)], + expected_fragment="simulated manifest replace failure", + check_subprocess=False, + ) + self.assertEqual(manifest_path.read_text(encoding="utf-8"), "prior-manifest\n") + self.assertEqual([p.name for p in manifest_dir.iterdir()], ["manifest.json"]) + + def test_argparse_missing_required_pool_exit_2_without_traceback(self): + proc = _run_subprocess() + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("usage:", proc.stderr.lower()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ttpf_batch_export.py b/tools/ttpf_batch_export.py index 28d2267cb..77b565ddb 100644 --- a/tools/ttpf_batch_export.py +++ b/tools/ttpf_batch_export.py @@ -15,7 +15,9 @@ import json import os from pathlib import Path +import struct import sys +import tempfile import time FORMAT_NAMES = { @@ -235,6 +237,20 @@ def export_texture_entry(pool, index: int, out_dir: Path, pass +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _atomic_write_text(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=path.parent) as staging_dir: + staged = Path(staging_dir) / path.name + staged.write_text(text, encoding="utf-8") + os.replace(staged, path) + + def batch_export(pool_path: Path, out_dir: Path, indices: list[int] | None = None, start: int = 0, count: int | None = None, @@ -246,17 +262,62 @@ def batch_export(pool_path: Path, out_dir: Path, require_rust: bool = False, calibration_path: Path | None = None) -> dict: """Run batch export over a range of texture pool indices and write manifest.json.""" + if threads < 1: + raise ValueError(f"--threads must be >= 1, got {threads}") + if start < 0: + raise ValueError(f"--start must be >= 0, got {start}") + if count is not None and count < 0: + raise ValueError(f"--count must be >= 0, got {count}") + + if pool_path.exists() and (pool_path.is_dir() or not pool_path.is_file()): + raise ValueError(f"Pool path must be a regular file: {pool_path}") + if out_dir.exists() and not out_dir.is_dir(): + raise ValueError(f"--out path is not a directory: {out_dir}") + if _same_path(out_dir, pool_path): + raise ValueError(f"--out path collides with pool: {out_dir}") + + resolved_manifest = manifest_path if manifest_path is not None else out_dir / "manifest.json" + if resolved_manifest.exists() and resolved_manifest.is_dir(): + raise ValueError(f"--manifest path is an existing directory: {resolved_manifest}") + if _same_path(resolved_manifest, pool_path): + raise ValueError(f"--manifest path collides with pool: {resolved_manifest}") + if _same_path(resolved_manifest, out_dir): + raise ValueError(f"--manifest path collides with --out: {resolved_manifest}") + if resolved_manifest.resolve() in out_dir.resolve().parents: + raise ValueError(f"--manifest path cannot be an ancestor of --out: {resolved_manifest}") + if calibration_path is not None and (allow_provisional or history_path is not None): raise ValueError("--calibration cannot be combined with --allow-provisional or --history") history_dict = None - if allow_provisional and history_path is not None: + if history_path is not None: + if history_path.exists() and history_path.is_dir(): + raise ValueError(f"Cannot read --history {history_path}: path is a directory") try: history_dict = json.loads(history_path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: + except (OSError, json.JSONDecodeError, ValueError) as exc: raise ValueError(f"Cannot read --history {history_path}: {exc}") from exc if not isinstance(history_dict, dict): raise ValueError(f"Expected a JSON object in --history {history_path}") + if not allow_provisional: + history_dict = None + + calibration = None + if calibration_path is not None: + if calibration_path.exists() and calibration_path.is_dir(): + raise ValueError(f"Cannot read --calibration {calibration_path}: path is a directory") + try: + calibration = json.loads(calibration_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError, ValueError) as exc: + raise ValueError(f"Cannot read --calibration {calibration_path}: {exc}") from exc + if not isinstance(calibration, dict) or calibration.get("version") != 1: + raise ValueError("Unsupported calibration version (expected version 1)") + + if tools_path is not None: + if not tools_path.exists(): + raise FileNotFoundError(f"--tools-path not found: {tools_path}") + if not tools_path.is_dir(): + raise ValueError(f"--tools-path must be a directory: {tools_path}") ttpf = load_tools(tools_path) if ttpf is None: @@ -265,7 +326,7 @@ def batch_export(pool_path: Path, out_dir: Path, require_rust_backend(ttpf) fitted_decoder = None - if calibration_path is not None: + if calibration is not None: try: calibrated = importlib.import_module("calibrated_texture") if (calibrated.ttpf is not ttpf @@ -277,17 +338,10 @@ def batch_export(pool_path: Path, out_dir: Path, f"Cannot load the fitted decoder from the selected Leonida tools: {exc}. " "Install NumPy and build tools/bcpack_calibration in release mode." ) from exc - calibration = json.loads(calibration_path.read_text(encoding="utf-8")) - if not isinstance(calibration, dict) or calibration.get("version") != 1: - raise ValueError("Unsupported calibration version (expected version 1)") def fitted_decoder(pool): return calibrated.LocalDecoder(pool, calibration) - out_dir.mkdir(parents=True, exist_ok=True) - if manifest_path is None: - manifest_path = out_dir / "manifest.json" - start_time = time.perf_counter() pool = ttpf.Pool(str(pool_path)) try: @@ -295,6 +349,9 @@ def fitted_decoder(pool): finally: pool.close() + out_dir.mkdir(parents=True, exist_ok=True) + manifest_path = resolved_manifest + if indices is None: start_idx = max(0, start) end_idx = total_textures if count is None else min(total_textures, start_idx + count) @@ -333,7 +390,7 @@ def _worker(idx: int) -> dict: stats["failed"] += 1 manifest_entries.sort(key=lambda x: x.get("index", 0)) - manifest_path.write_text(json.dumps(manifest_entries, indent=2), encoding="utf-8") + _atomic_write_text(manifest_path, json.dumps(manifest_entries, indent=2)) elapsed = time.perf_counter() - start_time return { @@ -347,7 +404,7 @@ def _worker(idx: int) -> dict: } -def main(): +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("pool", type=Path, help="Path to .ttpf texture pool archive") parser.add_argument("-o", "--out", type=Path, default=Path("extracted_dds"), @@ -370,7 +427,7 @@ def main(): help="Require the optional Rust BCPack library to load before exporting") parser.add_argument("--calibration", type=Path, help="Retry strict failures with a local version-1 Leonida calibration profile") - args = parser.parse_args() + args = parser.parse_args(argv) if not args.pool.exists(): parser.error(f"Pool not found: {args.pool}") @@ -395,11 +452,12 @@ def main(): require_rust=args.require_rust, calibration_path=args.calibration, ) - except (RuntimeError, OSError, ValueError) as exc: + except (RuntimeError, OSError, ValueError, struct.error, json.JSONDecodeError) as exc: parser.error(str(exc)) print(json.dumps(summary, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 2072562252da8899bd7e40c4d18726915bd0f5d5 Mon Sep 17 00:00:00 2001 From: thepatrickworld Date: Wed, 25 Nov 2026 22:01:25 +0100 Subject: [PATCH 171/232] startup: cap v_fract_f32 at 0x3f7fffff like pixel_aot already does (#2010) * startup: cap v_fract_f32 at 0x3f7fffff like pixel_aot already does The gfx2hlsl table emitted a bare D3D frac for v_fract_f32, while tools/pixel_aot.py has always lowered the same instruction through fract32, which caps x - floor(x) at 0x3f7fffff because D3D frac has no upper bound and differs between adapters. Two NVIDIA reports fail the draw on the input 0xb0800000 (-2^-30) with 3f800000 where the instruction returns 3f7fffff: an RTX 3070 Ti on 32.0.16.2101 and a Quadro M1000M on 32.0.15.7371. The same draw passes on WARP, on Intel HD Graphics 530 and on the RDNA 4 card used here. The helper is the comparison form, not min, so a NaN stays a NaN. A new check pins the emitted statement of the e32 and e64 forms, the cap in the preamble, and rejects an uncapped frac and a min-form cap. No NVIDIA adapter is available here: the Maxwell and Turing results are not reproduced. What is verified is the emitted text, the pixel_aot rule it now matches, and the adapters that already returned 0x3f7fffff. * startup: compare the bits in fract32 so FXC keeps the cap, and bump the cache revision FXC treats frac as strictly below 1, so frac(value) >= 1.0f folds to false and the helper compiled to a bare frc: on the Quadro M1000M and the RTX 3070 Ti the cap was gone and v_fract_f32 still read 3f800000 for 0xb0800000. Comparing the encoding survives FXC (frc, ieq, movc), and frac can only reach the cap by rounding to exactly +1.0, so the equality covers the same case. The cap therefore changes translated shaders that are already cached: the revision seed goes to x2w-startup-shader-8 in gfx2hlsl.py and d3d12_draw.inl, and a control asserts both spellings agree and that the -7 seed keys differently. --------- Co-authored-by: Panam Co-authored-by: root Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 15 ++ docs/experiments.md | 22 ++ docs/startup-runtime.md | 7 +- src/startup_stubs/d3d12_draw.inl | 6 +- .../startup_compute_request_offline_check.py | 4 +- tests/startup_gfx2hlsl_buffer_store_check.py | 4 +- tests/startup_gfx2hlsl_fract_check.py | 195 +++++++++++++++++ tests/startup_gfx2hlsl_fract_draw_check.py | 205 ++++++++++++++++++ tests/startup_indirect_draw_indexed.cpp | 2 +- tests/startup_resource_retire_title.cpp | 2 +- tools/startup/gfx2hlsl.py | 17 +- 11 files changed, 464 insertions(+), 15 deletions(-) create mode 100644 tests/startup_gfx2hlsl_fract_check.py create mode 100644 tests/startup_gfx2hlsl_fract_draw_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e3254094..eaabfc868 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3587,6 +3587,21 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_shift64_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_fract_f32 goes through the clamped fract32 helper, never a bare D3D frac (#1741). + add_test(NAME startup_gfx2hlsl_fract COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fract_check.py") + set_tests_properties(startup_gfx2hlsl_fract PROPERTIES TIMEOUT 60) + # The same cap drawn on one pixel with FXC 5_1 (where the float comparison it used to be written with + # folded away) and DXC 6_0; the uncapped pair must read 0x3f800000 on the -2^-30 lane. + add_test(NAME startup_gfx2hlsl_fract_draw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fract_draw_check.py") + set_tests_properties(startup_gfx2hlsl_fract_draw_controls PROPERTIES TIMEOUT 60) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_fract_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fract_draw_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_fract_draw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl signed 24-bit multiply/multiply-add (v_mul_i32_i24, v_mad_i32_i24): evaluator, refusals and draws. add_test(NAME startup_gfx2hlsl_mul_mad_i24_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul_mad_i24_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 7e5b84ea3..4fdcb6cf7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15200,6 +15200,28 @@ On an AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`) and on in-bo ```powershell cmake --build --preset dev --target offscreen_check ctest --preset dev --no-tests=error -R '^startup_range_provenance' -V + +## Startup v_fract_f32 upper bound + +`v_fract_f32` in `tools/startup/gfx2hlsl.py` now lowers through a `fract32` helper in the common preamble +instead of a bare D3D `frac`. The helper is `frac(value)` capped at `0x3f7fffff` by a comparison, +`f >= 1.0f ? asfloat(0x3f7fffffu) : f`, which is the form and the rule `tools/pixel_aot.py` has always used: +for an input such as -2^-30 (`0xb0800000`) the unclamped `x - floor(x)` rounds up to 1.0 in binary32, while the +instruction returns at most `0x3f7fffff`. The cap is not written with `min`, because D3D `min` returns its other +operand for a NaN and a NaN input has to stay a NaN. Two NVIDIA reports fail `startup_gfx2hlsl_float_round_hardware` +on that very input with `expected=...3f7fffff... actual=...3f800000...`: an RTX 3070 Ti on driver 32.0.16.2101 and +a Quadro M1000M (Maxwell) on driver 32.0.15.7371, both in #1741, while the same draw passes on WARP, on Intel HD +Graphics 530 and on the RDNA 4 card used here. That agreement is the reason the D3D `frac` was the deviating side, +not the fixture. No NVIDIA adapter is available on this machine, so the Maxwell and Turing results are **not** +reproduced here: what the change is verified against is the emitted text, the pixel_aot rule it now matches, and +the adapters that already returned `0x3f7fffff`. `tests/startup_gfx2hlsl_fract_check.py` asserts that the statement +of the `_e32` and `_e64` forms is `U(fract32(...))`, that no bare `frac(` reaches it, that the preamble clamps at +`0x3f7fffff` with the comparison form, and that the table entry is used by `v_fract_f32` alone. Two controls +rewrite the lowering to the uncapped `frac` and to a `min`-form cap and require the checks to reject both. Only +`v_fract_f32` changes in this patch. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_fract$' -V ``` ## Vulkan subnormal preservation in a pixel shader diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 18a7e87e5..193f627ed 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -204,10 +204,13 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-15`. Older translations evaluate `s_brev_b32` of a -constant at run time instead of folding it into a known word, which changes the emitted HLSL. +The shader cache revision is `x2w-startup-shader-16`. Earlier translations lower `v_fract_f32` +through a bare `frac` instead of the clamped `fract32` helper. The matching compute +(`x2w-startup-shader-16cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance +because those stages use the shared lowering. Revisions before 15 lower `v_cvt_pk_u8_f32` with a float clamp and accept `s_setreg_imm32_b32` writes of the rounding mode. +Revisions before 14 evaluate constant `s_brev_b32` at run time instead of folding it into a known word. Revisions before 12 can overwrite the source mask when a save-EXEC instruction uses the same source and destination register. Earlier revisions can also carry a stale scalar symbol across a join, read a stale SCC after diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 57cef5130..2eefa8e18 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -244,7 +244,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-15"; + constexpr char revision[] = "x2w-startup-shader-16"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -364,7 +364,7 @@ void publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-15cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-16cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); @@ -427,7 +427,7 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo return copy_title_bytes(out.data(), pointer, out.size()); }; if (!copy_stage(13, true, mesh) || !copy_stage(5, false, pixel)) return; - constexpr char revision[] = "x2w-startup-mesh-57-1"; + constexpr char revision[] = "x2w-startup-mesh-57-2"; const u64 key = fnv_part(root_blob, fnv_part(pixel, fnv_part(mesh, fnv_bytes(revision, sizeof(revision) - 1)))); static SRWLOCK request_lock = SRWLOCK_INIT; static std::unordered_set written; diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index 9d75bc94a..30e6e3c37 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x9f56f9821d4b83e0 # compute_key of the parts above +KEY = 0x4db2818cb07558bf # framed key at revision 16cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-15cs': + for b in b'x2w-startup-shader-16cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack('= 1.0f ? ... : f`, did not survive FXC: it treats `frac` as strictly +below 1, folds that comparison to false and compiles the helper to a bare `frc`, so the cap disappeared on +exactly the adapters the fix was for. DXC keeps the compare and the select, which is why the pixel_aot +lowering, compiled by DXC only, never showed this. The cap is now a comparison on the BITS, +`asuint(f) == 0x3f800000u`, which FXC emits as `frc`, `ieq`, `movc`. `frac` can only reach the cap by +rounding to exactly +1.0, so the equality covers the case a `>=` comparison covered, and a NaN word misses +it and passes through. + +This check reads the emitted text only. It cannot reproduce the NVIDIA result: that needs one of those +adapters, and no such GPU is available here. What it pins is the lowering the adapters disagreed on, and +the shader cache revision that keeps the pre-fix entries out of the cache. +""" +import os +import re +import struct +import sys +from pathlib import Path + +here = os.path.dirname(os.path.abspath(__file__)) +root = Path(here).resolve().parent +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +sys.path.insert(0, here) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe # noqa: E402 + +BITS_FORM = 'asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f' +FLOAT_FORM = 'f >= 1.0f ? asfloat(0x3f7fffffu) : f' +ONE = 0x3f800000 +CAP = 0x3f7fffff +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def lower(line): + """The translated statement of one assembly line, as the caller sees it.""" + stage = Probe() + stage.one(line.split(' ', 1)[0], line) + return ' '.join(stage.lines) + + +HELPER = re.compile(r'float fract32\(float value\) \{.*?\}') +BARE_FRAC = re.compile(r'(?': word > ONE, '>=': word >= ONE}[test] + return CAP if fire else word + + +preamble = common() +match = HELPER.search(preamble) +check('the fract32 helper is emitted in the common preamble', match is not None, preamble[:240]) +helper = match.group(0) if match else '' +check('the helper is defined once', preamble.count('float fract32(') == 1, preamble[:240]) +source = Path(G.__file__).read_text(encoding='utf-8') +check('the helper carries the pixel_aot comment', + '# Match pixel_aot: x - floor(x) capped at 0x3f7fffff' in source) +check('the helper comment names FXC folding the float comparison', + 'FXC folds `frac(value) >= 1.0f` to false' in source) + +# 1. The table entry itself: one source, through the helper. +check('the VEC_F entry goes through fract32', G.VEC_F.get('v_fract_f32') == (1, 'fract32({0})'), + repr(G.VEC_F.get('v_fract_f32'))) +users = sorted(op for op, (_arity, text) in G.VEC_F.items() if 'fract32(' in text) +check('fract32 is used by v_fract_f32 alone and no other entry', users == ['v_fract_f32'], repr(users)) + +# 2. The emitted statement of each spelling, with the source modifiers the form accepts. +for line, expected in ( + ('v_fract_f32 v12, v0', 'v12 = U(fract32(F(v0)));'), + ('v_fract_f32 v0, v0', 'v0 = U(fract32(F(v0)));'), + ('v_fract_f32_e64 v13, |v1|', 'v13 = U(fract32(abs(F(v1))));'), + ('v_fract_f32_e64 v14, -|v2|', 'v14 = U(fract32((-abs(F(v2)))));'), +): + statement = lower(line) + found = problems(statement, helper) + check(f'{line} lowers through the clamp', not found, '%r: %s' % (statement, '; '.join(found))) + check(f'{line} emits the expected statement', statement == expected, statement) + +# 3. Negative controls: the checks above must reject the lowerings that caused the report and the ones that +# would let it come back. The same problem list is used, so the controls cannot drift from it. +uncapped = problems(lower('v_fract_f32 v12, v0').replace('fract32(', 'frac('), helper) +check('control: a bare frac is rejected', any('bare frac' in text for text in uncapped), repr(uncapped)) +capped_with_min = problems(lower('v_fract_f32 v12, v0'), helper.replace(BITS_FORM, + 'min(frac(value), asfloat(0x3f7fffffu))')) +check('control: a min-form clamp is rejected', bool(capped_with_min), repr(capped_with_min)) +raised_cap = problems(lower('v_fract_f32 v12, v0'), helper.replace('0x3f7fffffu', '0x3f800000u')) +check('control: a cap other than 0x3f7fffff is rejected', bool(raised_cap), repr(raised_cap)) +float_compare = problems(lower('v_fract_f32 v12, v0'), helper.replace(BITS_FORM, FLOAT_FORM)) +check('control: the float comparison FXC folds away is rejected', any('FXC folds' in text for text in float_compare), + repr(float_compare)) +strict = problems(lower('v_fract_f32 v12, v0'), helper.replace(BITS_FORM, BITS_FORM.replace('==', '>'))) +check('control: a strict > on the bits is rejected', bool(strict), repr(strict)) + +# What a strict > would do, evaluated on the words the helper can see. It misses the one case that occurs, +# because 1.0 is the value the cap is for, and it caps any NaN whose sign-and-exponent bits sort above 1.0. +check('the strict > misses 0x3f800000 and leaves 1.0, the word the report measured', + capped(ONE, '>') == ONE and capped(ONE, '==') == CAP, + '> reads %08x, == reads %08x' % (capped(ONE, '>'), capped(ONE, '=='))) +check('the strict > turns a NaN word above 1.0 into the cap, and the == form passes it', + capped(0x7fc00000, '>') == CAP and capped(0x7fc00000, '==') == 0x7fc00000, + '> reads %08x, == reads %08x' % (capped(0x7fc00000, '>'), capped(0x7fc00000, '=='))) +check('both comparisons leave a word below 1.0 alone', all(capped(w, t) == w for w in (0, CAP, 0x3f000000) + for t in ('==', '>'))) +def float_capped(word): + """The word the float comparison `frac(value) >= 1.0f` caps, read as a float: the rule the bits form keeps.""" + value = struct.unpack('= 1.0 else word + + +check('the bits equality caps the same words the float comparison does over the range frac returns', + all(capped(w, '==') == float_capped(w) for w in (0, 0x80000000, 0x3f000000, CAP, ONE, 0x7fc00000)), + repr([(hex(w), hex(capped(w, '==')), hex(float_capped(w))) + for w in (0, CAP, ONE, 0x7fc00000)])) +# Outside that range the bits form is narrower: it leaves 2.0 alone where the float form caps it. frac cannot +# return such a word, so this is the one place the two rules differ, and the narrower one hides nothing. +check('the bits form is narrower than the float form above 1.0, which frac cannot return', + capped(0x40000000, '==') == 0x40000000 and float_capped(0x40000000) == CAP, + 'bits %08x, float %08x' % (capped(0x40000000, '=='), float_capped(0x40000000))) + +# 4. The shader cache revision: both literals are the same word, and the old seed cannot produce the new key. +gfx_source = Path(G.__file__).read_text(encoding='utf-8') +seed = re.search(r"fnv\(b'(x2w-startup-shader-\d+)'\)", gfx_source) +stub_source = (root / 'src' / 'startup_stubs' / 'd3d12_draw.inl').read_text(encoding='utf-8') +literal = re.search(r'constexpr char revision\[\] = "(x2w-startup-shader-\d+)";', stub_source) +check('both files spell a x2w-startup-shader revision', seed is not None and literal is not None, + repr((seed and seed.group(1), literal and literal.group(1)))) +check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1), + repr((seed and seed.group(1), literal and literal.group(1)))) +check('the revision is x2w-startup-shader-16, after the fix to the cap', + bool(seed and seed.group(1) == 'x2w-startup-shader-16'), repr(seed and seed.group(1))) + + +def key_from_seed(word): + """pipeline_key's hash chain with one seed, over the same three blobs, without the layout.""" + return G.fnv(b'root', G.fnv(b'ps', G.fnv(b'vs', G.fnv(word.encode())))) + + +if seed: + check('pipeline_key hashes the seed the source spells', + G.pipeline_key(b'vs', b'ps', b'root') == key_from_seed(seed.group(1)), + '%016x vs %016x' % (G.pipeline_key(b'vs', b'ps', b'root'), key_from_seed(seed.group(1)))) + old, new = key_from_seed('x2w-startup-shader-15'), key_from_seed('x2w-startup-shader-16') + check('the -15 seed produces a different key, so the pre-fix entries are out of the cache', old != new, + '%016x vs %016x' % (old, new)) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tests/startup_gfx2hlsl_fract_draw_check.py b/tests/startup_gfx2hlsl_fract_draw_check.py new file mode 100644 index 000000000..363a59df2 --- /dev/null +++ b/tests/startup_gfx2hlsl_fract_draw_check.py @@ -0,0 +1,205 @@ +"""`v_fract_f32` capped at 0x3f7fffff in a drawn pixel, with FXC and DXC (#1741). + + (no arguments) translation and arithmetic controls, pure Python + draw [fxc] + translate the fixture, compile with FXC vs_5_1/ps_5_1 (the --pending + path) when given and with DXC vs_6_0/ps_6_0, draw one pixel and compare + the four words + +The fixture is a source-built gfx1013 vertex and pixel pair. The vertex stage places a full-screen triangle +from the vertex index (v0) and exports four words to param0; the pixel stage reads them flat with +v_interp_mov_f32 p0, applies v_fract_f32 to each and exports them to mrt0. The words are 0xb0800000 +(-2^-30, the input the two NVIDIA reports fail on), 0x3fc00000 (1.5), 0x00000000 and 0xc0200000 (-2.5), +so the capped reading of the four lanes is 0x3f7fffff, 0x3f000000, 0x00000000 and 0x3f000000. Nothing here +reads game data: the words come from the vertex stage, so no compiler can fold them. + +The control that counts: the same pair with the lowering left uncapped, `U(frac(F(v)))`, must read a +different word in the first lane. For -2^-30 the unclamped x - floor(x) rounds up to exactly 1.0 in +binary32, `0x3f800000`, while the instruction returns at most `0x3f7fffff`. An adapter whose bare `frc` +already caps reads the capped word there: the test records that as a finding on that adapter instead of +failing, because on it the two forms cannot be separated by this draw. The other three lanes must read the +same word with and without the cap, which is what says the cap adds no rounding of its own. +""" +import math +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' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import mov_literal # noqa: E402 +from startup_flat_param_check import VS_WORDS, compile_hlsl, draw, root_blob # noqa: E402 + +CAP = 0x3f7fffff +ONE = 0x3f800000 +INPUTS = (0xb0800000, 0x3fc00000, 0x00000000, 0xc0200000) +VS_EXPECTED = ('v_mov_b32_e32 v3, 0x40400000', 'v_mov_b32_e32 v10, 0xc0400000', + 'v_cmp_eq_u32_e32 vcc_lo, 1, v0', 'v_cndmask_b32_e32 v1, -1.0, v3, vcc_lo', + 'v_cmp_eq_u32_e32 vcc_lo, 2, v0', 'v_cndmask_b32_e32 v2, 1.0, v10, vcc_lo', + 'v_mov_b32_e32 v4, 1.0', 'v_mov_b32_e32 v5, 0', + 'v_mov_b32_e32 v6, 0xb0800000', 'v_mov_b32_e32 v7, 0x3fc00000', + 'v_mov_b32_e32 v8, 0', 'v_mov_b32_e32 v9, 0xc0200000', + 'exp pos0 v1, v2, v5, v4 done', 'exp param0 v6, v7, v8, v9', 's_endpgm') +PS_EXPECTED = ('s_mov_b32 m0, s2', + 'v_interp_mov_f32_e32 v0, p0, attr0.x', 'v_interp_mov_f32_e32 v1, p0, attr0.y', + 'v_interp_mov_f32_e32 v2, p0, attr0.z', 'v_interp_mov_f32_e32 v3, p0, attr0.w', + 'v_fract_f32_e32 v0, v0', 'v_fract_f32_e32 v1, v1', + 'v_fract_f32_e32 v2, v2', 'v_fract_f32_e32 v3, v3', + 'exp mrt0 v0, v1, v2, v3 done vm', 's_endpgm') +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +# The recorded words are built here rather than assembled: llvm-mc is not needed, and the controls read the +# decoded text back through gfx2hlsl.decode, which is the decoder the translator itself uses. +VS = (VS_WORDS[:40] # full-screen triangle, v3..v5 + + b''.join(mov_literal(6 + lane, word) for lane, word in enumerate(INPUTS)) + + bytes.fromhex('cf0800f801020504') # exp pos0 v1, v2, v5, v4 done + + struct.pack('<2I', 0xf800000f | 32 << 4, 0x09080706) # exp param0 v6, v7, v8, v9 + + bytes.fromhex('000081bf')) # s_endpgm + + +def vop1_e32(op, vdst, src0): + """VOP1 in the e32 encoding: src0 0..127 is an SGPR, 256+n is a VGPR (VGPR 0 is 0x100, not 0).""" + return struct.pack(' the cap: this adapter's own frac already stays below 1.0, so the draw cannot + # separate the two forms here. Recorded, not failed. + print(' recorded: %s %s uncapped pair reads the capped word %s, so this adapter clamps a bare ' + 'frc itself and the control cannot separate the two forms on it' % (kind, adapter, + EXPECTED_TEXT)) + else: + check('%s %s: the uncapped pair reads %s, not %s' % (kind, adapter, UNCAPPED_TEXT, EXPECTED_TEXT), + read == UNCAPPED, run.stdout + run.stderr) + + +def main(): + if len(sys.argv) == 1: + controls() + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + return + mode, *args = sys.argv[1:] + if mode != 'draw': + raise SystemExit(__doc__) + controls() + check_draw(*args) + if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) + print('PASS') + + +if __name__ == '__main__': + main() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index c0d23090c..9fcfa7fb1 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -295,7 +295,7 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-15"; + constexpr char revision[] = "x2w-startup-shader-16"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 5270131e8..0850645f7 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -371,7 +371,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-15"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-16"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3024ca8a4..68fbf037d 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -5604,7 +5604,7 @@ def declarations(self): 'v_madmk_f32': (3, 'mad32({0}, {1}, {2}, false)'), 'v_madak_f32': (3, 'mad32({0}, {1}, {2}, false)'), 'v_rcp_f32': (1, '1.0 / {0}'), 'v_rcp_iflag_f32': (1, '1.0 / {0}'), 'v_rsq_f32': (1, 'rsqrt({0})'), 'v_sqrt_f32': (1, 'sqrt({0})'), 'v_exp_f32': (1, 'exp2({0})'), 'v_log_f32': (1, 'log2({0})'), 'v_floor_f32': (1, 'floor({0})'), 'v_ceil_f32': (1, 'ceil({0})'), - 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'frac({0})'), 'v_rndne_f32': (1, 'round({0})'), + 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'fract32({0})'), 'v_rndne_f32': (1, 'round({0})'), 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), 'v_med3_f32': (3, 'med3({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), } @@ -5959,6 +5959,15 @@ def common(self): ' precise float sum = product + ftz32(c);', ' return ftz32(sum);', '}', + # Match pixel_aot: x - floor(x) capped at 0x3f7fffff, so a tiny negative input cannot round up to + # 1.0. The cap is a comparison, not min: min returns its other operand for a NaN. + # The comparison is on the bits because FXC folds `frac(value) >= 1.0f` to false and emits a bare + # frc for it, which loses the cap on an adapter whose frac returns 1.0. frac can only reach the cap + # by rounding to exactly +1.0, so the equality covers the same case, and a NaN misses it and passes. + 'float fract32(float value) {', + ' float f = frac(value);', + ' return asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f;', + '}', 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' @@ -6312,7 +6321,7 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-15')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-16')))) return fnv(layout, key) if layout else key @@ -6321,7 +6330,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-15cs') + key = fnv(b'x2w-startup-shader-16cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack(' Date: Wed, 25 Nov 2026 13:01:55 -0800 Subject: [PATCH 172/232] shader: lower gfx1013 array and 3D float image stores (#1649) Full-mask R32G32B32A32_FLOAT image_store at mip zero into a 2D array or 3D view, declared with --image-uav-dimension 2d-array or 3d, lowers to RWTexture2DArray or RWTexture3D at u0, indexed by three consecutive address VGPRs. A 2D image_load_mip from a separate SRV followed by an array store translates to the two views. Wrong view dimensions, sparse masks and gfx1030 array or volume views are refused. Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 31 ++++ tests/compute_check.cpp | 152 ++++++++++------ tests/compute_mimg_float_store_layers.s | 13 ++ .../compute_mimg_float_store_layers_check.py | 163 ++++++++++++++++++ tools/compute_store_aot.py | 39 ++++- 8 files changed, 345 insertions(+), 60 deletions(-) create mode 100644 tests/compute_mimg_float_store_layers.s create mode 100644 tests/compute_mimg_float_store_layers_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6045f6964..924cd1483 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -70,6 +70,7 @@ jobs: (["tests/compute_mimg_msaa_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "libLLVM-15.so.1"], {}), (["tests/compute_mimg_float_store_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_mimg_image_uav_load_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), + (["tests/compute_mimg_float_store_layers_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_mimg_float_store_d16_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_image_atomics_gfx1013_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_gather4_l_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), diff --git a/CMakeLists.txt b/CMakeLists.txt index eaabfc868..ef2ef512d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9065,6 +9065,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_gfx1013_image_uav_load_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_image_uav_load_${adapter}.txt") + add_test(NAME compute_store_aot_gfx1013_image_store_layers_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_mimg_float_store_layers_check.py" --draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_gfx1013_image_store_layers_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_image_store_layers_${adapter}.txt") add_test(NAME compute_store_aot_gfx1013_image_store_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_mimg_float_store_d16_check.py" --draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 8ee064816..3b0ccf646 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | | gfx1013 float image stores | Lower [full-mask 2D RGBA32 FLOAT stores and explicit-mip SRV reads](docs/experiments.md#gfx1013-2d-float-image-stores-and-mip-loads) [D16 stores to RGBA16 FLOAT](docs/experiments.md#gfx1013-2d-d16-float-image-stores) and [same-texel UAV loads](docs/experiments.md#gfx1013-same-texel-uav-loads). Compare all three destination mips, including untouched texels. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_(store\|uav_load)_'` | +| gfx1013 array and 3D image stores | Lower [full-mask RGBA32 FLOAT array and volume stores](docs/experiments.md#gfx1013-2d-array-and-3d-float-image-stores) and compare all slices and mips. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_store_layers_'` | | gfx1013 image atomics | Lower [2D `R32_UINT` `image_atomic_add`, `umax` and `cmpswap`](docs/experiments.md#gfx1013-2d-image-atomics) with the gfx1030 lowering and compare every texel of a three-mip texture, including contended adds. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_atomics_'` | | gfx1013 image gathers | Lower [one 2D `image_gather4_l` with a constant sampler and a known integer LOD](docs/experiments.md#gfx1013-2d-explicit-lod-image-gathers) on an RGBA32 FLOAT view. Compare all four taps at three mips and on a view that starts at mip 1. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_gather4_l_'` | | Startup compute mip-zero gather | Dispatch a [gfx1013 `image_gather4_lz`](docs/experiments.md#compute-mip-zero-gather) and compare four texels from the first visible mip against a CPU reference. | `ctest --preset dev --no-tests=error -R '^startup_compute_gather_lz'` | diff --git a/docs/experiments.md b/docs/experiments.md index 4fdcb6cf7..4a5261311 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4428,6 +4428,37 @@ python3 -B tests/compute_mimg_image_uav_load_check.py python3 -B tests/compute_mimg_image_uav_load_check.py --binary llvm-mc-15 llvm-objcopy-15 --llvm libLLVM-15.so.1 ``` +### gfx1013 2D array and 3D float image stores + +For full-mask `R32G32B32A32_FLOAT` stores at mip zero, declare +`--image-uav-dimension 2d-array` or `3d`. The dimension must match the native +`image_store` form. The translator binds `RWTexture2DArray` or +`RWTexture3D` at `u0` and indexes it with three consecutive +full-width address VGPRs in X, Y and slice or depth order. Bind the matching +UAV view and supply a unique destination texel for each invocation. The +opt-in covers stores with DMASK `0xf` and no explicit mip operand. + +Each source-built case writes 64 texels across two slices or depth planes at +mip zero, with distinct data derived from X, Y and the third coordinate. +The comparator checks every word of every slice and mip. The array check +covers 5,376 words across four layers at each mip. The volume check covers +4,672 words across mips with depths 4, 2 and 1. The swapped-coordinate control +exchanges Y with the last coordinate while keeping the values the same. +The translation controls refuse an incorrect view dimension, a sparse mask and an array or +volume view on gfx1030. A 2D `image_load_mip` from the separate SRV followed by a 2D array +store translates to the two views. The translator does not clamp the slice or depth +coordinate. A D3D12 UAV store outside the view is dropped, and the console's behaviour for +an out-of-range layer has not been measured. + +```powershell +cmake --build --preset dev --target offscreen_check -j 2 +ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_gfx1013_image_store_layers_(warp|hardware)$' -V +``` + +```bash +python3 -B tests/compute_mimg_float_store_layers_check.py --binary llvm-mc-15 llvm-objcopy-15 --llvm libLLVM-15.so.1 +``` + ### gfx1013 2D D16 float image stores Declare `--image-format R16G16B16A16_FLOAT` and `--image-uav-mip 0` diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index 5d4da8ae0..be0b6a422 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -40,10 +40,18 @@ constexpr UINT texture_view_mip1_flag = 1u << 31; // free below the format and view selectors. constexpr UINT texture_uav_load_flag = 1u << 21; constexpr UINT texture_rgba16_float_flag = 1u << 22; -constexpr UINT texture_format_mask = texture_rgba8_flag | texture_atomic_mask | texture_rgba32_float_flag | +constexpr UINT texture_array_flag = 1u << 31; +constexpr UINT texture_volume_flag = texture_array_flag | texture_rgba32_float_flag; +constexpr UINT texture_format_mask = texture_rgba8_flag | texture_atomic_mask | texture_volume_flag | texture_rgba16_float_flag | texture_uav_load_flag; constexpr UINT texture_width = 32, texture_height = 8, texture_channels = 4; -constexpr UINT texture_mip_levels = 3; +constexpr UINT texture_mip_levels = 3, texture_layers = 4; + +UINT texture_subresources(const D3D12_RESOURCE_DESC& desc) +{ + // A volume mip contains all of its depth slices in one subresource. + return desc.MipLevels * (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? 1u : desc.DepthOrArraySize); +} UINT texture_words_per_texel(DXGI_FORMAT format) { @@ -82,36 +90,43 @@ static void fill_upload(ID3D12Resource* upload, const std::array // buffer alive until the command list has executed. static ComPtr upload_texture(ID3D12Device* device, ID3D12GraphicsCommandList* list, const std::vector& texels, - DXGI_FORMAT format, ComPtr& staging, bool writable = false) + DXGI_FORMAT format, ComPtr& staging, bool writable = false, + D3D12_UAV_DIMENSION dimension = D3D12_UAV_DIMENSION_TEXTURE2D) { const UINT words_per_texel = texture_words_per_texel(format); const UINT base_words = texture_width * texture_height * words_per_texel; const UINT mips = texels.size() == base_words ? 1 : texture_mip_levels; D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Dimension = dimension == D3D12_UAV_DIMENSION_TEXTURE3D + ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Width = texture_width; desc.Height = texture_height; - desc.DepthOrArraySize = desc.SampleDesc.Count = 1; + desc.DepthOrArraySize = dimension == D3D12_UAV_DIMENSION_TEXTURE2D ? 1 : texture_layers; + desc.SampleDesc.Count = 1; desc.MipLevels = static_cast(mips); desc.Format = format; if (writable) desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; auto texture = resource(device, desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); - std::array layouts{}; + std::vector layouts(texture_subresources(desc)); UINT64 upload_bytes = 0; - device->GetCopyableFootprints(&desc, 0, mips, 0, layouts.data(), nullptr, nullptr, &upload_bytes); + device->GetCopyableFootprints(&desc, 0, static_cast(layouts.size()), 0, + layouts.data(), nullptr, nullptr, &upload_bytes); staging = make_buffer(device, upload_bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); void* mapped = nullptr; const D3D12_RANGE no_reads{}; check(staging->Map(0, &no_reads, &mapped), "Map texture upload"); std::memset(mapped, 0, static_cast(upload_bytes)); std::size_t word = 0; - for (UINT level = 0; level < mips; ++level) { - const auto& layout = layouts[level]; - const UINT row_words = (texture_width >> level) * words_per_texel; - for (UINT y = 0; y < (texture_height >> level); ++y) { - auto* row = static_cast(mapped) + layout.Offset + y * layout.Footprint.RowPitch; - std::memcpy(row, texels.data() + word, row_words * sizeof(UINT)); - word += row_words; + for (const auto& layout : layouts) { + const auto& footprint = layout.Footprint; + const UINT row_words = footprint.Width * words_per_texel; + for (UINT z = 0; z < footprint.Depth; ++z) { + for (UINT y = 0; y < footprint.Height; ++y) { + auto* row = static_cast(mapped) + layout.Offset + + (z * footprint.Height + y) * footprint.RowPitch; + std::memcpy(row, texels.data() + word, row_words * sizeof(UINT)); + word += row_words; + } } } staging->Unmap(0, nullptr); @@ -120,9 +135,9 @@ static ComPtr upload_texture(ID3D12Device* device, ID3D12Graphic dest.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; src.pResource = staging.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - for (UINT level = 0; level < mips; ++level) { - dest.SubresourceIndex = level; - src.PlacedFootprint = layouts[level]; + for (UINT subresource = 0; subresource < layouts.size(); ++subresource) { + dest.SubresourceIndex = subresource; + src.PlacedFootprint = layouts[subresource]; list->CopyTextureRegion(&dest, 0, 0, 0, &src, nullptr); } transition(list, texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, @@ -149,12 +164,21 @@ static ComPtr bind_tables(ID3D12Device* device, ID3D12Grap uav.Buffer.NumElements = capacity; uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; if (output_register >= uavs) throw std::runtime_error("Invalid output register"); + const auto output_desc = output->GetDesc(); for (UINT i = 0; i < uavs; ++i, cpu.ptr += stride) { - if (i == output_register && output->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D) { + if (i == output_register && output_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { D3D12_UNORDERED_ACCESS_VIEW_DESC image{}; - image.Format = output->GetDesc().Format; - image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - image.Texture2D.MipSlice = output_mip; + image.Format = output_desc.Format; + if (output_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { + image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + image.Texture3D = {output_mip, 0, ~0u}; + } else if (output_desc.DepthOrArraySize > 1) { + image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + image.Texture2DArray = {output_mip, 0, output_desc.DepthOrArraySize, 0}; + } else { + image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + image.Texture2D.MipSlice = output_mip; + } device->CreateUnorderedAccessView(output, nullptr, &image, cpu); } else { device->CreateUnorderedAccessView(i == output_register ? output : nullptr, nullptr, &uav, cpu); @@ -512,6 +536,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co const UINT selector = groups & texture_format_mask; groups &= ~texture_format_mask; DXGI_FORMAT format = DXGI_FORMAT_R32G32B32A32_UINT; + D3D12_UAV_DIMENSION dimension = D3D12_UAV_DIMENSION_TEXTURE2D; UINT required = D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE; switch (selector) { case 0: break; @@ -520,6 +545,14 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co format = DXGI_FORMAT_R32G32B32A32_FLOAT; required |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; break; + case texture_array_flag: + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + dimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + break; + case texture_volume_flag: + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + dimension = D3D12_UAV_DIMENSION_TEXTURE3D; + break; case texture_rgba16_float_flag: format = DXGI_FORMAT_R16G16B16A16_FLOAT; break; case texture_rgba8_flag: format = DXGI_FORMAT_R8G8B8A8_UINT; break; case texture_atomic_uint_flag: @@ -548,10 +581,16 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co } const bool float_image = selector == texture_rgba32_float_flag; const bool uav_load = selector == texture_uav_load_flag; + const bool layered = dimension != D3D12_UAV_DIMENSION_TEXTURE2D; const bool half_image = selector == texture_rgba16_float_flag; const UINT words_per_texel = texture_words_per_texel(format); const UINT base_words = texture_width * texture_height * words_per_texel; - const UINT all_words = base_words + base_words / 4 + base_words / 16; + UINT all_words = 0; + for (UINT level = 0; level < texture_mip_levels; ++level) { + UINT depth = layered ? texture_layers : 1; + if (dimension == D3D12_UAV_DIMENSION_TEXTURE3D) depth >>= level; + all_words += (base_words >> (2 * level)) * depth; + } std::vector initial(all_words), expected(all_words); source.read(reinterpret_cast(initial.data()), all_words * sizeof(UINT)); source.read(reinterpret_cast(expected.data()), all_words * sizeof(UINT)); @@ -573,9 +612,12 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co return false; } } - if ((support.Support2 & required) != required) { - std::printf("format=%u required_support2=0x%x support1=0x%x support2=0x%x\n", - static_cast(format), required, static_cast(support.Support1), + const UINT required_shape = dimension == D3D12_UAV_DIMENSION_TEXTURE3D ? D3D12_FORMAT_SUPPORT1_TEXTURE3D + : layered ? D3D12_FORMAT_SUPPORT1_TEXTURE2D : 0; + if ((support.Support2 & required) != required || (support.Support1 & required_shape) != required_shape) { + std::printf("format=%u dimension=%u required_support1=0x%x required_support2=0x%x support1=0x%x support2=0x%x\n", + static_cast(format), static_cast(dimension), required_shape, required, + static_cast(support.Support1), static_cast(support.Support2)); return false; } @@ -592,7 +634,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co ComputeCommands commands(device, pipeline.Get()); auto* list = commands.list.Get(); ComPtr staging, input_staging, input_image; - auto texture = upload_texture(device, list, initial, format, staging, true); + auto texture = upload_texture(device, list, initial, format, staging, true, dimension); if (float_image) input_image = upload_texture(device, list, input_texels, format, input_staging); auto constants_buffer = make_buffer(device, constants_offset + 4 * alignment, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); @@ -602,19 +644,20 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co list->Dispatch(groups, 1, 1); transition(list, texture.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); - std::array layouts{}; - UINT64 readback_bytes = 0; const auto desc = texture->GetDesc(); - device->GetCopyableFootprints(&desc, 0, texture_mip_levels, 0, layouts.data(), nullptr, nullptr, &readback_bytes); + const UINT subresources = texture_subresources(desc); + std::vector layouts(subresources); + UINT64 readback_bytes = 0; + device->GetCopyableFootprints(&desc, 0, subresources, 0, layouts.data(), nullptr, nullptr, &readback_bytes); auto readback = make_buffer(device, readback_bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); D3D12_TEXTURE_COPY_LOCATION src{}, dest{}; src.pResource = texture.Get(); src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dest.pResource = readback.Get(); dest.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - for (UINT level = 0; level < texture_mip_levels; ++level) { - src.SubresourceIndex = level; - dest.PlacedFootprint = layouts[level]; + for (UINT subresource = 0; subresource < subresources; ++subresource) { + src.SubresourceIndex = subresource; + dest.PlacedFootprint = layouts[subresource]; list->CopyTextureRegion(&dest, 0, 0, 0, &src, nullptr); } commands.submit_and_wait(device); @@ -623,29 +666,34 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co const D3D12_RANGE read{0, static_cast(readback_bytes)}, no_writes{}; check(readback->Map(0, &read, &mapped), "Map image store readback"); UINT word = 0, mismatches = 0; - for (UINT level = 0; level < texture_mip_levels; ++level) { - const auto& layout = layouts[level]; - const UINT row_words = (texture_width >> level) * words_per_texel; - for (UINT y = 0; y < (texture_height >> level); ++y) { - const auto* row = reinterpret_cast(static_cast(mapped) + - layout.Offset + y * layout.Footprint.RowPitch); - for (UINT x = 0; x < row_words; ++x, ++word) { - if (row[x] == expected[word]) continue; - if (half_image) { - for (UINT half = 0; half < 2; ++half) { - const UINT shift = 16u * half; - const UINT want = (expected[word] >> shift) & 0xffffu; - const UINT got = (row[x] >> shift) & 0xffffu; - if (want == got) continue; + for (UINT subresource = 0; subresource < subresources; ++subresource) { + const auto& layout = layouts[subresource]; + const auto& footprint = layout.Footprint; + const UINT level = subresource % desc.MipLevels; + const UINT row_words = footprint.Width * words_per_texel; + for (UINT z = 0; z < footprint.Depth; ++z) { + for (UINT y = 0; y < footprint.Height; ++y) { + const auto* row = reinterpret_cast(static_cast(mapped) + + layout.Offset + (z * footprint.Height + y) * footprint.RowPitch); + for (UINT x = 0; x < row_words; ++x, ++word) { + if (row[x] == expected[word]) continue; + if (half_image) { + for (UINT half = 0; half < 2; ++half) { + const UINT shift = 16u * half; + const UINT want = (expected[word] >> shift) & 0xffffu; + const UINT got = (row[x] >> shift) & 0xffffu; + if (want == got) continue; + if (!mismatches) + std::fprintf(stderr, "mip=%u half=%u expected=%04x actual=%04x\n", + level, 2 * word + half, want, got); + ++mismatches; + } + } else { if (!mismatches) - std::fprintf(stderr, "mip=%u half=%u expected=%04x actual=%04x\n", - level, 2 * word + half, want, got); + std::fprintf(stderr, "mip=%u word=%u expected=%08x actual=%08x\n", + level, word, expected[word], row[x]); ++mismatches; } - } else { - if (!mismatches) - std::fprintf(stderr, "mip=%u word=%u expected=%08x actual=%08x\n", level, word, expected[word], row[x]); - ++mismatches; } } } diff --git a/tests/compute_mimg_float_store_layers.s b/tests/compute_mimg_float_store_layers.s new file mode 100644 index 000000000..380534329 --- /dev/null +++ b/tests/compute_mimg_float_store_layers.s @@ -0,0 +1,13 @@ +s_mov_b32 s20, s7 +s_mov_b32 s21, 0 +s_load_dwordx8 s[24:31], s[20:21], 0x40 +v_lshl_add_u32 v8, s10, 2, v0 +v_lshl_add_u32 v9, s11, 2, v1 +v_lshl_add_u32 v10, s12, 1, v2 +v_or_b32_e32 v14, 0x3f810000, v8 +v_or_b32_e32 v15, 0x40110000, v9 +v_or_b32_e32 v16, 0x40410000, v10 +v_mov_b32_e32 v17, 0xbf810001 +s_waitcnt lgkmcnt(0) +image_store v[14:17], v[8:10], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY +s_endpgm diff --git a/tests/compute_mimg_float_store_layers_check.py b/tests/compute_mimg_float_store_layers_check.py new file mode 100644 index 000000000..76695fb25 --- /dev/null +++ b/tests/compute_mimg_float_store_layers_check.py @@ -0,0 +1,163 @@ +"""Check full-mask gfx1013 RGBA32 FLOAT stores to a 2D array and a 3D texture.""" +import argparse +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import aot, assemble, disassemble, rejects, store_container, variant +import compute_mimg_float_store_check as flat + +HERE = Path(__file__).resolve().parent +ARRAY_LINES = (HERE / "compute_mimg_float_store_layers.s").read_text(encoding="ascii").splitlines() +ARRAY_STORE = next(line for line in ARRAY_LINES if line.startswith("image_store")) +VOLUME_STORE = ARRAY_STORE.replace("IMG_2D_ARRAY", "IMG_3D") +VOLUME_LINES = variant(ARRAY_LINES, (ARRAY_STORE, VOLUME_STORE)) +ARRAY_WORDS = bytes.fromhex( + "070394be 800395be 0a060cf4 400000fa 080046d7 0a040104 090046d7 0b040504" + " 0a0046d7 0c020904 ff101c38 0000813f ff121e38 00001140 ff142038 00004140" + " ff02227e 010081bf 7fc08cbf 280f20f0 080e0600 000081bf" +) +VOLUME_WORDS = ARRAY_WORDS.replace(bytes.fromhex("280f20f0"), bytes.fromhex("100f20f0")) +GROUP = (4, 4, 2) +GROUPS = 2 +BINDING = dict(table_reg=7, group_reg=10, group_reg_y=11, group_reg_z=12, image_descriptor=0x40, + image_format="R32G32B32A32_FLOAT", image_uav_mip=0) +# Selectors in tests/compute_check.cpp. Both views cover four slices at mip zero. +CASES = ( + ("2d-array", ARRAY_LINES, ARRAY_STORE, ARRAY_WORDS, "RWTexture2DArray", 1 << 31, 5376), + ("3d", VOLUME_LINES, VOLUME_STORE, VOLUME_WORDS, "RWTexture3D", (1 << 31) | (1 << 30), 4672), +) +ADDRESS = "outputData[uint3(tid.x, tid.y, tid.z)]" + + +def controls(dimension, lines, store, texel_type): + binding = BINDING | {"image_uav_dimension": dimension} + source = aot.lower(lines, GROUP, **binding) + assert f"{texel_type} outputData : register(u0);" in source, source + assert ADDRESS in source, source + wrong_dimension = "3d" if dimension == "2d-array" else "2d-array" + for view in (wrong_dimension, "2d"): + rejects(f"image_store dimension {dimension} does not match the {view} UAV view", + aot.lower, lines, GROUP, **(binding | {"image_uav_dimension": view})) + sparse = store.replace("v[14:17]", "v[14:15]").replace("dmask:0xf", "dmask:0x5") + for changed, message in ( + (sparse, "image_store requires full DMASK 0xf"), + (store.replace("v[8:10]", "v[8:9]"), "Unsupported image store target"), + (store + " d16", "Unsupported compute instruction"), + (store + " a16", "Unsupported compute instruction"), + (store.replace("image_store", "image_store_mip"), "Unsupported compute instruction"), + (store.replace("image_store", "image_load_mip"), "Unsupported compute instruction"), + ): + rejects(message, aot.lower, variant(lines, (store, changed)), GROUP, **binding) + rejects("Image store mip does not match the UAV view", aot.lower, lines, GROUP, + **(binding | {"image_uav_mip": 1})) + print(f"{dimension}: translation controls passed", flush=True) + return source + + +def combined_controls(): + # A 2D mip load from the separate SRV followed by a 2D array store binds both views. + store = flat.STORE.replace("v[8:9]", "v[8:10]").replace("IMG_2D", "IMG_2D_ARRAY") + source = aot.lower(variant(flat.LINES, (flat.STORE, store)), flat.GROUP, + **(flat.BINDING | {"image_uav_dimension": "2d-array"})) + assert "Texture2D imageData : register(t0);" in source, source + assert "RWTexture2DArray outputData : register(u0);" in source, source + assert "outputData[uint3(tid.x, tid.y, 0x00000001u)] = " in source, source + # Array and volume views are gfx1013-only. + for dimension in ("2d-array", "3d"): + rejects("Array and 3D image UAVs require a gfx1013 RGBA32 FLOAT store binding", aot.lower, + ARRAY_LINES, GROUP, **(BINDING | {"image_uav_dimension": dimension, "cpu": "gfx1030"})) + print("combined SRV load and array store, and gfx1030 refusal: controls passed", flush=True) + + +def binary(directory, assembler, objcopy, library, dimension, lines, store, words, source): + code = assemble(directory, assembler, objcopy, lines) + assert code == words, f"{dimension}: assembled {code.hex()} != recorded {words.hex()}" + print(f"{dimension}: gfx1013 machine words match llvm-mc", flush=True) + if not library: + return + binding = BINDING | {"image_uav_dimension": dimension} + decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=b"gfx1013")) + assert [line for line in decoded if line.startswith("image_")] == [store] + assert aot.lower(decoded, GROUP, **binding) == source + container, output = directory / "layers.dxbc", directory / "layers.hlsl" + container.write_bytes(store_container(code, GROUP)) + options = [arg for key, value in binding.items() for arg in ("--" + key.replace("_", "-"), str(value))] + subprocess.run([sys.executable, "-B", aot.__file__, container, "--output", output, "--llvm", library, + *options], check=True) + assert output.read_text() == source + + +def reference(dimension): + initial, expected = [], [] + # D3D12 array subresources are ordered by layer, then mip. A volume has one + # subresource per mip and stores all depth slices with a shrinking depth. + array = dimension == "2d-array" + for layer in range(4 if array else 1): + for mip in range(3): + for depth in range(1 if array else 4 >> mip): + z = layer if array else depth + for y in range(8 >> mip): + for x in range(32 >> mip): + tag = mip << 16 | z << 12 | y << 7 | x << 2 + sentinels = [0xBF000000 | tag | c for c in range(4)] + initial.extend(sentinels) + if mip == 0 and x < 8 and y < 4 and z < 2: + expected.extend((0x3F810000 + x, 0x40110000 + y, 0x40410000 + z, 0xBF810001)) + else: + expected.extend(sentinels) + return initial, expected + + +def draw(directory, dxc, renderer, adapter, dimension, selector, count, source): + hlsl, cso, case = (directory / f"layers.{ext}" for ext in ("hlsl", "cso", "case")) + initial, expected = reference(dimension) + assert len(initial) == len(expected) == count + assert sum(before != after for before, after in zip(initial, expected, strict=True)) == 256 + case.write_bytes(struct.pack(f"<2I{2 * count}I", GROUPS | selector, 0, *initial, *expected)) + swapped = source.replace(ADDRESS, "outputData[uint3(tid.x, tid.z, tid.y)]") + assert swapped != source + for label, code, mismatches in (("translated", source, 0), ("swap y and slice/depth", swapped, 288)): + hlsl.write_text(code, encoding="ascii") + subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) + result = subprocess.run([renderer, adapter, "--compute-texture-store-case", cso, case], + capture_output=True, text=True, timeout=15) + print(f"{dimension} {label}:\n{result.stdout}{result.stderr}", end="", flush=True) + if result.returncode == 77: + return 77 + if "debug_layer=enabled" in result.stdout: + assert "debug_errors=0 debug_warnings=0" in result.stdout, label + assert f"compared_words={count} mismatches={mismatches}" in result.stdout, label + if mismatches: + assert result.returncode == 1 and "mip=0 word=129 expected=40110001 actual=40110000" in result.stderr + else: + assert result.returncode == 0, label + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--binary", nargs=2, metavar=("LLVM_MC", "LLVM_OBJCOPY")) + modes.add_argument("--draw", nargs=3, metavar=("DXC", "RENDERER", "ADAPTER")) + parser.add_argument("--llvm", metavar="LIBLLVM", help="Also check disassembly and the container CLI") + args = parser.parse_args() + combined_controls() + out = HERE.parent / "out" + out.mkdir(exist_ok=True) + status = 0 + with tempfile.TemporaryDirectory(prefix="compute_mimg_layers_", dir=out) as tmp: + directory = Path(tmp) + for dimension, lines, store, words, texel_type, selector, count in CASES: + source = controls(dimension, lines, store, texel_type) + if args.binary: + binary(directory, *args.binary, args.llvm, dimension, lines, store, words, source) + elif args.draw and draw(directory, *args.draw, dimension, selector, count, source) == 77: + status = 77 + return status + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index d58135549..d2a2e57f5 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -198,13 +198,14 @@ ALU_SOURCE = r"(s\d+|v\d+|-?\d+|0x[0-9a-f]+)" # Results are inline HLSL expressions; a longer one is rejected instead of growing without bound. ALU_EXPRESSION_LIMIT = 1024 -# Caller guarantees for a MIMG image descriptor: an 8-dword resource descriptor that names a 2D, -# linear (non-swizzled) image of the listed format. The translator checks where the eight words were +# Caller guarantees for a MIMG image descriptor: an 8-dword resource descriptor that names a +# linear (non-swizzled) image of the declared type and format. The translator checks where the eight words were # loaded from, not the 9-bit GFX10 format, type, swizzle, level or size fields inside them; the two # 16-byte descriptor slots are bound to t0 for reads or u0 for writes. # Value: (HLSL texel type, channel count). IMAGE_FORMATS = {"R32G32B32A32_UINT": ("uint4", 4), "R8G8B8A8_UINT": ("uint4", 4)} RGBA32_FLOAT = "R32G32B32A32_FLOAT" +IMAGE_UAV_TYPES = {"2d": "RWTexture2D", "2d-array": "RWTexture2DArray", "3d": "RWTexture3D"} RGBA16_FLOAT = "R16G16B16A16_FLOAT" # image_gather4_l on the gfx1013 RGBA32 FLOAT SRV, with the sampler profile of pixel_aot.check_gather_sampler # (normalized coordinates, clamp to the last texel, point mip, no LOD bias). RDNA 2 MIMG gathers return one DMASK @@ -769,6 +770,7 @@ def heap_store_view_hlsl(table_offset, view_count, output_bytes, *, components=4 def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=None, stride=None, + image_uav_dimension="2d", image_srv_descriptor=None, constant_descriptor=None, group_reg_y=None, group_reg_z=None, source_descriptor=None, source_stride=None, source_format=None, output_format=None, image_descriptor=None, image_format=None, image_uav_mip=None, image_float_domain=None, buffer_float_domain=None, cpu="gfx1013", lds_bytes=0, @@ -807,6 +809,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for writes, where image_uav_mip selects the writable subresource and replaces descriptor_offset. + image_uav_dimension declares the view for a store. Array and volume + stores require three address VGPRs and are available for gfx1013 RGBA32 FLOAT. R32_UINT selects the 4-sample Texture2DMS profile for an SRV or the non-returning 2D integer atomic profile for a UAV. R32_SINT is UAV-only and selects signed min/max. R32_FLOAT declares a native atomic image carried as raw words @@ -848,6 +852,10 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N float_image = rgba32_float_image or rgba16_float_image if image_format == RGBA16_FLOAT and not rgba16_float_image: raise ValueError("RGBA16 FLOAT requires a gfx1013 D16 image store UAV") + if image_uav_dimension not in IMAGE_UAV_TYPES: + raise ValueError("Unknown image UAV dimension") + if image_uav_dimension != "2d" and not (image_output and rgba32_float_image): + raise ValueError("Array and 3D image UAVs require a gfx1013 RGBA32 FLOAT store binding") # gfx1013 takes the shared image atomic lowering on an R32_UINT UAV only (add, umax, cmpswap; see lower()). gfx1013_image_atomic = cpu == "gfx1013" and image_atomic_type is not None and image_format == "R32_UINT" if image_output: @@ -2561,14 +2569,24 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N elif m := re.fullmatch(r"image_(?Pload|store|get_resinfo)(?P_mip)?(?P_pck(?:_sgn)?)? " r"(?Pv\d+|v\[\d+:\d+\]), (?Pv\d+|v\[\d+:\d+\]), " r"s\[(?P\d+):(?P\d+)\] dmask:0x(?P[0-9a-f]+) " - r"dim:SQ_RSRC_IMG_2D(?: unorm)?(?P a16)?(?P d16)?", line): + r"dim:SQ_RSRC_IMG_(?P2D_ARRAY|2D|3D)(?: unorm)?(?P a16)?(?P d16)?", line): # A16 packs x/y into one dword and takes the mip from the low half of the next dword. mip, a16 = bool(m["mip"]), bool(m["a16"]) d16 = bool(m["d16"]) write = m["kind"] == "store" resinfo = m["kind"] == "get_resinfo" + dimension = m["dimension"].lower().replace("_", "-") + layered = dimension != "2d" + if m["d16"] and layered: + # D16 stores are 2D only; refuse array and volume forms as an unmatched instruction. + raise ValueError(f"Unsupported compute instruction: {line}") + if write and dimension != image_uav_dimension: + raise ValueError(f"Unsupported compute instruction: image_store dimension {dimension} " + f"does not match the {image_uav_dimension} UAV view") + if layered and (not write or not rgba32_float_image or a16 or mip or m["packed"]): + raise ValueError(f"Unsupported compute instruction: {line}") vaddr = [int(n) for n in re.findall(r"\d+", m["addr"])] - address_words = 1 if resinfo else (1 if a16 else 2) + int(mip) + address_words = 1 if resinfo else (1 if a16 else 2) + int(mip) + int(layered) base, high = int(m["base"]), int(m["high"]) dmask = int(m["mask"], 16) # DMASK selects components in XYZW order and packs them into consecutive VGPRs. @@ -2604,7 +2622,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N elif cpu == "gfx1013" and (not rgba32_float_image or a16 or m["packed"] or (m["kind"], mip) not in (("store", False), ("load", True))): raise ValueError(f"Unsupported image {m['kind']} target: " - "gfx1013 requires full-width 2D RGBA32 FLOAT image_store or image_load_mip") + "gfx1013 requires full-width RGBA32 FLOAT image_store or 2D image_load_mip") if rgba32_float_image and write and dmask != 0xf: raise ValueError("gfx1013 RGBA32 FLOAT image_store requires full DMASK 0xf") separate_srv = not write and not uav_load and image_srv_descriptor is not None @@ -2639,7 +2657,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N else: x, y = map(hlsl_word, coordinates[:2]) if write: - # A D3D12 Texture2D UAV names one mip. Verify native and desktop mip selection agree. + # A D3D12 image UAV names one mip. Verify native and desktop mip selection agree. level = coordinates[-1] if mip else 0 if not isinstance(level, int) or (level & 0xffff if a16 else level) != image_uav_mip: raise ValueError("Image store mip does not match the UAV view") @@ -2667,7 +2685,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N selected = dict(zip(channels, words)) texel = ", ".join(selected.get(channel, "0u") for channel in "xyzw") value = f"uint4({texel})" - stores.append(f" outputData[uint2({x}, {y})] = {value};") + address = (f"uint3({x}, {y}, {hlsl_word(coordinates[2])})" if layered + else f"uint2({x}, {y})") + stores.append(f" outputData[{address}] = {value};") continue if resinfo: name = f"image_resinfo_{image_step_count}" @@ -3014,7 +3034,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N cbuffer += CVT_U32_F32_HELPER cbuffer += "".join(text for name, text in DOT_U_HELPERS.items() if f"{name}(" in body) uav_texel_type = image_atomic_type or ("float4" if float_image else "uint4") - uav = f"RWTexture2D<{uav_texel_type}>" if image_output else "RWByteAddressBuffer" + uav = f"{IMAGE_UAV_TYPES[image_uav_dimension]}<{uav_texel_type}>" if image_output else "RWByteAddressBuffer" # The helper reads outputData, so it follows the UAV declaration. descriptor_hlsl = descriptor_store_hlsl() if "store_descriptor_format(" in body else "" if "load_descriptor_format(" in body or "load_heap_view_format(" in body: @@ -3079,6 +3099,8 @@ def main(): help="Table byte offset of the 8-dword image descriptor bound to t0 or u0") parser.add_argument("--image-uav-mip", type=int, help="Bind the image to u0 at this mip instead of binding a raw output descriptor") + parser.add_argument("--image-uav-dimension", choices=IMAGE_UAV_TYPES, default="2d", + help="Declare the u0 view dimension for an image store") parser.add_argument("--image-srv-descriptor", type=lambda n: int(n, 0), help="Separate image descriptor at t0 when u0 is a gfx1013 RGBA32 FLOAT image") parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS.keys() | IMAGE_ATOMIC_TYPES.keys() @@ -3114,6 +3136,7 @@ def main(): output_format=args.output_format, image_descriptor=args.image_descriptor, image_format=args.image_format, buffer_float_domain=args.buffer_float_domain, + image_uav_dimension=args.image_uav_dimension, image_uav_mip=args.image_uav_mip, image_float_domain=args.image_float_domain, cpu=args.cpu, lds_bytes=args.lds_bytes, lds_f32_mode=args.lds_f32_mode, lds_f64_mode=args.lds_f64_mode, From e66405a6e1bf94b367f3baed1fd30a40040c8367 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:02:32 +0100 Subject: [PATCH 173/232] startup: accept the structured-to-raw descriptor conversion for compute buffer stores (Part of #2274) (#2546) * startup: accept the structured-to-raw descriptor conversion for compute buffer stores #2320 accepts a compute buffer store through a descriptor whose stride field was cleared. Captured programs convert a structured descriptor to a raw one before the store: the stride field DW1[29:16] is extracted (s_bfe_u32 0xe0010), optionally clamped to at least 1 (s_max_u32 with 1), NUM_RECORDS (DW2) is multiplied by it, OOB_SELECT (DW3[29:28]) is set to 3 and the stride is cleared. Accept exactly that conversion of the four words of one table descriptor, with the field positions from docs/pixel_mubuf_contract.md, and translate the store as #2320 does. Anything else stays refused with "buffer store through a modified descriptor": another OOB_SELECT, NUM_RECORDS not scaled or scaled by another value, the stride of another descriptor, another bit field, a clamp other than 1, the stride not cleared, or a conversion split across a branch. Derived words are not kept at joins. A second load of the same table words names the same descriptor value. Tests: startup_gfx2hlsl_compute_check.py adds case I-raw (same HLSL and manifest as the plain store, and in dispatch mode on WARP and hardware), the clamped form, and the refusals above. Part of #2274. AI-assisted. * startup: tell compute descriptor loads apart when the pointer may differ The pointer symbol records neither an addend (s_add_u32 on the low word) nor a rewritten high word, so two s_load_dwordx8 through such a pointer got the same ('desc', source, offset, dword) symbols while reading different words: the raw conversion could then take NUM_RECORDS from one descriptor and the stride from another. In a compute stage, a load through an untouched root pointer pair keeps the plain symbol, a load through an untouched 32-bit table pointer whose high word is a known constant is tagged with that constant, and any other load is tagged with its own offset. Loads of the same words through the same pointer still share one value, so equal loads on both arms of a branch are kept at the join as before. Controls: a second load after s_add_u32 on the pointer and after a new high word are refused for the raw conversion; a second load through the same pointer is accepted. AI-assisted. --- docs/experiments.md | 12 ++- tests/startup_gfx2hlsl_compute_check.py | 63 +++++++++++++- tools/startup/gfx2hlsl.py | 109 ++++++++++++++++++------ 3 files changed, 154 insertions(+), 30 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 4a5261311..d022a6c75 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14497,14 +14497,20 @@ allows the read, including at a branch target. The compute controls exercise con As in #2059, the run-time part of the address is rounded down to a multiple of 4. That rounding, and the handling of out-of-range stores, are assumptions, not measurements. -One descriptor modification is accepted for a raw buffer store: clearing the stride field of dword 1. That is +The stride-only exception for raw buffer stores clears the stride field of dword 1. That is `s_and_b32` of dword 1 with `0xc000ffff`, which keeps the base address bits 15:0 and bits 31:30. The result is -the raw descriptor such a store already assumes. Any other mask, any other dword, a repeated modification, and -the same clear on an image store stay refused. Loads through the descriptor still treat it as modified. +the raw descriptor such a store already assumes. Repeated clears and the same clear on an image store stay +refused. Loads through the descriptor still treat it as modified. Case I is case A with the clear before its store. The runner binds a root UAV and reads no descriptor, so the GPU run checks the translation, not the stride; the negative controls are the pure-Python refusals. +Compute buffer stores also accept a structured-to-raw conversion from one descriptor load. The shader +clears the stride in DW1[29:16], multiplies the original DW2 record count by the stride extracted from DW1 +(optionally clamped to at least 1 with `s_max_u32`), and sets DW3[29:28] (OOB_SELECT) to 3. Every other bit must match the load. Case I-raw uses the same +byte-address store and read-back as case I. As with the stride-only case, matching out-of-range behavior +requires the runtime to bind a UAV view sized to the resulting byte count. + The runtime has no slot-67 path yet, so no translated compute program runs in the stand-in. `startup_gfx2hlsl_compute_check.py` translates three source-built programs: diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index b88fe0d48..5cc703fd8 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -464,6 +464,24 @@ def saveexec_fixture(): 's_and_b32 s18, s18, 0xc000ffff': '12ff1287ffff00c0', 's_and_b32 s17, 0xc000ffff, s17': 'ff111187ffff00c0', 's_and_b32 s21, s21, 0xc000ffff': '15ff1587ffff00c0', + 's_bfe_u32 s21, s17, 0xe0010': '11ff959310000e00', + 's_bfe_u32 s21, s29, 0xe0010': '1dff959310000e00', + 's_max_u32 s21, s21, 1': '15819584', + 's_max_u32 s21, s21, 2': '15829584', + 's_bfe_u32 s21, s17, 0xe0011': '11ff959311000e00', + 's_mul_i32 s18, s18, s21': '12151293', + 's_mul_i32 s18, s18, 4': '12841293', + 's_and_b32 s19, s19, 0xcfffffff': '13ff1387ffffffcf', + 's_or_b32 s19, s19, 0x30000000': '13ff138800000030', + 's_or_b32 s19, s19, 0x20000000': '13ff138800000020', + 's_load_dwordx8 s[24:31], s[10:11], 0x0': '05060cf4000000fa', + 's_load_dwordx8 s[24:31], s[10:11], 0x20': '05060cf4200000fa', + 's_add_u32 s10, s10, 32': '0aa00a80', + 's_mov_b32 s11, 1': '81038bbe', + 's_waitcnt lgkmcnt(0)': '7fc08cbf', + 's_mov_b32 s19, s31': '1f0393be', + 's_mov_b32 s17, s29': '1d0391be', + 's_cbranch_scc1 2': '020085bf', } @@ -476,6 +494,15 @@ def splice(*lines, at=STORE_A): CASES['I'] = (SOURCE_A.replace('buffer_store_dword', STRIDE_CLEAR + '\nbuffer_store_dword'), splice(STRIDE_CLEAR), *CASES['A'][2:]) +# Case I-raw converts the structured UAV descriptor to the same byte range before the store. +STRIDE_EXTRACT = 's_bfe_u32 s21, s17, 0xe0010' +SCALE_RECORDS = 's_mul_i32 s18, s18, s21' +OOB_CLEAR = 's_and_b32 s19, s19, 0xcfffffff' +OOB_RAW = 's_or_b32 s19, s19, 0x30000000' +RAW_CONVERSION = (STRIDE_EXTRACT, STRIDE_CLEAR, SCALE_RECORDS, OOB_CLEAR, OOB_RAW) +CASES['I-raw'] = (SOURCE_A.replace('buffer_store_dword', '\n'.join((*RAW_CONVERSION, 'buffer_store_dword'))), + splice(*RAW_CONVERSION), *CASES['A'][2:]) + # Replace the nonzero stride constant in s5 with the first active lane of a # fresh 24-thread group. Ignoring FF1 leaves a different word at every i > 0. CASES['A-ff1'] = ('s_ff1_i32_b32 s5, exec_lo\n' + SOURCE_A, @@ -514,7 +541,7 @@ def formatted_input(): def expected(name): - if name == 'I': + if name in ('I', 'I-raw'): return expected('A') out = [SENTINEL] * WORDS _, _, _, local, groups = CASES[name] @@ -947,6 +974,40 @@ def check_controls(): 'v_mov_b32 v5, s20')).hlsl_cs() for lines in ((clear, clear), (clear, 's_or_b32 s17, s17, 0x40000'), ('s_or_b32 s17, s17, 0x40000', clear)): refused('buffer store through a modified descriptor', lambda lines=lines: translate('A', code=splice(*lines)).hlsl_cs()) + raw = translate('I-raw') + plain = translate('A') + assert raw.hlsl_cs() == plain.hlsl_cs() + assert raw.manifest() == plain.manifest() + assert translate('A', code=splice(STRIDE_EXTRACT, clear, SCALE_RECORDS, OOB_RAW)).hlsl_cs() == raw.hlsl_cs() + # Captured programs clamp the extracted stride to at least 1 before scaling NUM_RECORDS. + clamped = (STRIDE_EXTRACT, 's_max_u32 s21, s21, 1', *RAW_CONVERSION[1:]) + assert translate('A', code=splice(*clamped)).hlsl_cs() == raw.hlsl_cs() + refused('buffer store through a modified descriptor', lambda: translate( + 'A', code=splice(STRIDE_EXTRACT, 's_max_u32 s21, s21, 2', *RAW_CONVERSION[1:])).hlsl_cs()) + reload = ('s_load_dwordx8 s[24:31], s[10:11], 0x0', 's_waitcnt lgkmcnt(0)') + other = ('s_load_dwordx8 s[24:31], s[10:11], 0x20', 's_waitcnt lgkmcnt(0)') # the next two descriptors + # A second load through the same untouched pointer pair reads the same words, so a word taken from it is the + # same value. After s_add_u32 s10, s10, 32 the pointer symbol hides the addend, so that load is told apart. + for lines in ((*reload, 's_mov_b32 s19, s31', *RAW_CONVERSION), + (*reload, STRIDE_EXTRACT, 's_mov_b32 s17, s29', clear, SCALE_RECORDS, OOB_RAW)): + assert translate('A', code=splice(*lines)).hlsl_cs() == raw.hlsl_cs() + moved = ('s_add_u32 s10, s10, 32', *reload) + rehigh = ('s_mov_b32 s11, 1', *reload) # another high address word: another descriptor + for lines in ( + (*rehigh, 's_bfe_u32 s21, s29, 0xe0010', clear, SCALE_RECORDS, OOB_RAW), + (*moved, 's_mov_b32 s19, s31', *RAW_CONVERSION), + (*moved, 's_bfe_u32 s21, s29, 0xe0010', clear, SCALE_RECORDS, OOB_RAW), + (*RAW_CONVERSION[:-1], 's_or_b32 s19, s19, 0x20000000'), + (STRIDE_EXTRACT, clear, OOB_RAW), + (STRIDE_EXTRACT, SCALE_RECORDS, OOB_RAW), + (clear, 's_mul_i32 s18, s18, 4', OOB_RAW), + (*other, 's_mov_b32 s19, s31', *RAW_CONVERSION), + (*other, STRIDE_EXTRACT, 's_mov_b32 s17, s29', clear, SCALE_RECORDS, OOB_RAW), + (*other, 's_bfe_u32 s21, s29, 0xe0010', clear, SCALE_RECORDS, OOB_RAW), # another descriptor's stride + ('s_bfe_u32 s21, s17, 0xe0011', clear, SCALE_RECORDS, OOB_RAW), # not the stride field (bits 30:17) + (*RAW_CONVERSION[:-1], 's_cmp_lt_u32 s7, 4', 's_cbranch_scc1 2', OOB_RAW), + ): + refused('buffer store through a modified descriptor', lambda lines=lines: translate('A', code=splice(*lines)).hlsl_cs()) # The modification is recorded for the descriptor the word belongs to (byte 16 of the x8 load), not for the # load's first descriptor: loads through the read descriptor at byte 0 are unaffected. refusals = [] diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 68fbf037d..91eff8cbf 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -658,7 +658,9 @@ def names_one_value(sym): if sym is None: return False if sym[0] == 'desc': - return len(sym) == 4 # ('desc', source, load offset, dword); the 'modified' mark drops the written value + # ('desc', source, load offset, dword) and, in a compute stage, the offset of the s_load that read it: the + # source does not record an addend on the pointer, so only the same load proves the same words. + return len(sym) == 4 or (len(sym) == 5 and isinstance(sym[4], int)) # An add on a pointer keeps its symbol and marks it 'added' (the offset is not in the tuple), so only an # untouched pointer, exactly (kind, source), names one value. return sym[0] in ('const', 'ud', 'execcopy') or (sym[0] in ('ptr', 'ptrhi') and len(sym) == 2) @@ -687,6 +689,44 @@ def desc_key(sym): return sym[1], None if sym[2] is None else sym[2] + 4 * (sym[3] & ~3) +def desc_word(sym, dword): + return sym[:3] + (dword,) + sym[4:] + + +def raw_descriptor_alu(base, syms, constants): + """Recognize only the word expressions needed for a structured-to-raw buffer store.""" + # gfx10 V# layout in docs/pixel_mubuf_contract.md: stride is DW1[29:16], + # NUM_RECORDS is DW2 and OOB_SELECT is DW3[29:28]. + # The extracted stride may be clamped to at least 1 (s_max_u32 with 1), so that a descriptor that is + # already raw (stride 0) keeps NUM_RECORDS bytes. + if base == 's_max_u32': + for i, word in enumerate(syms): + if word and word[:2] == ('descnum', 'stride') and constants[1 - i] == 1: + return ('descnum', 'stride_min1', word[2]) + return None + for i, word in enumerate(syms): + if not word or word[0] != 'desc' or len(word) < 4: + continue + other = 1 - i + field = word[3] % 4 + loaded = 5 if len(word) > 4 and isinstance(word[4], int) else 4 # with the compute load tag + plain = len(word) == loaded # a loaded word of one s_load + if plain and field == 1: + if base == 's_and_b32' and constants[other] == 0xc000ffff: + return word + ('stride0',) + if base == 's_bfe_u32' and i == 0 and constants[1] == 0xe0010: + return ('descnum', 'stride', word) + if plain and field == 2 and base == 's_mul_i32': + if syms[other] in (('descnum', kind, desc_word(word, word[3] - 1)) for kind in ('stride', 'stride_min1')): + return word + ('byte_count',) + if field == 3: + if plain and base == 's_and_b32' and constants[other] == 0xcfffffff: + return word + ('oob0',) + if (plain or word[loaded:] == ('oob0',)) and base == 's_or_b32' and constants[other] == 0x30000000: + return word[:loaded] + ('oob3',) + return None + + def smem_offset(tok): """The SMEM offset operand as a token: 'off' (no offset operand) is the literal 0, anything else unchanged.""" return '0' if tok == 'off' else tok @@ -2963,6 +3003,8 @@ def src_sym(t): raise Unsupported('mask from descriptor data') d = reg_range(dname)[1] own = self.sym.get(d) + raw = (raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) + if getattr(self, 'kind', None) == 'cs' and len(syms) == 2 else None) if base in ('s_mov_b32', 's_mov_b64'): self.sym[d] = syms[0] if pair: @@ -2978,17 +3020,16 @@ def src_sym(t): self.sym[d + 1] = hi elif self.tracks_uniformity(): self.varying_s.add(d + 1) + elif raw is not None: + self.sym[d] = raw + if raw[0] == 'desc': + self.pipe.modified.add(desc_key(raw)) elif own and own[0] in ('desc', 'ptr', 'ptrhi') and any(s == own for s in syms): if own[0] == 'desc': self.pipe.modified.add(desc_key(own)) - # The word keeps its descriptor identity for loads; the store check (store_descriptor) sees the - # mark. In a compute stage, clearing the stride field of dword 1 (bits 29:16, keeping the base - # address bits 15:0 and bits 31:30) is marked on its own: a raw byte-address store accepts it. - stride0 = (getattr(self, 'kind', None) == 'cs' and base == 's_and_b32' and len(own) == 4 - and own[3] % 4 == 1 and sorted(srcs) == sorted([dname, '0xc000ffff'])) - self.sym[d] = own[:4] + ('stride0' if stride0 else 'modified',) - if not stride0: - getattr(self.pipe, 'other_modified', set()).add(desc_key(own)) + # Keep the resource identity for loads; stores refuse the unproved value. + self.sym[d] = own[:4] + ('modified',) + getattr(self.pipe, 'other_modified', set()).add(desc_key(own)) else: self.sym[d] = own if len(own) > 2 else own + ('added',) # the added offset is not tracked else: @@ -3340,8 +3381,20 @@ def op_s_load_dwordx4(self, ops, mods, count=4): for i in range(count): self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) return + # The pointer symbol does not record an addend or a rewritten high word, so two loads through such a + # pointer may read different words under the same (source, offset). In a compute stage those loads + # are told apart by the offset of the s_load; loads through the untouched pair keep one identity. + # A 32-bit table pointer carries a high word the program sets to a constant: loads through the same + # untouched low word and the same constant read the same words (tag -1 - constant). + hi = self.sym.get(base[1] + 1) + if getattr(self, 'kind', None) != 'cs' or (p == ('ptr', p[1]) and hi == ('ptrhi', p[1])): + load = () + elif p == ('ptr', p[1]) and hi and hi[0] == 'const' and len(hi) == 2: + load = (-1 - hi[1],) + else: + load = (self.pc,) for i in range(count): - self.sym[dst[1] + i] = ('desc', p[1], off, i) + self.sym[dst[1] + i] = ('desc', p[1], off, i) + load return if p[1] == ('smpheap',): if self.pipe.sampler_heap and count == 4: @@ -3656,25 +3709,28 @@ def op_buffer_store_vs(self, ops, mods, count): self.emit('a = (%s%d) & 0xfffffffcu;' % (soffset, offset) if soffset else 'a = %d;' % offset) self.emit(store if self.exec_known else 'if (exec & 1) %s' % store) - def store_descriptor(self, tok, words, what, stride0_ok=False): - """Resource key of a store's descriptor operand: all its words must still be the loaded words of one - descriptor at a fixed table offset. A moved, overwritten or modified word (stride, num_records, format) - would change what the store does. With stride0_ok (a raw byte-address store), dword 1 may carry a cleared - stride field: that is the raw descriptor such a store already assumes.""" + def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok=False): + """Resource key for a single loaded descriptor or a proven raw transformation of it.""" rsrc = reg_range(tok) first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == words - 1 else None if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 4: raise Unsupported('%s through %s holding %s' % (what, tok, first)) key = desc_key(first) - def word_ok(k): - sym, want = self.sym.get(rsrc[1] + k), first[:3] + (first[3] + k,) - return sym == want or (stride0_ok and k == 1 and sym == want + ('stride0',)) - if (not all(word_ok(k) for k in range(words)) or key in getattr(self.pipe, 'other_modified', ()) + loaded = tuple(desc_word(first, first[3] + k) for k in range(words)) + actual = tuple(self.sym.get(rsrc[1] + k) for k in range(words)) + valid = names_one_value(first) and actual == loaded + if names_one_value(first) and stride0_ok and words == 4: + cleared = loaded[1] + ('stride0',) + valid = valid or actual == (loaded[0], cleared, *loaded[2:]) + if not valid and raw_conversion_ok: + valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + if (not valid or key in getattr(self.pipe, 'other_modified', ()) or (key in self.pipe.modified and not stride0_ok)): raise Unsupported('%s through a modified descriptor' % what) return key - def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False): + def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=False, allow_scalar_address=False, + raw_conversion_ok=False): """Validate a fixed-table raw UAV descriptor, data range, byte address, and 4-byte alignment.""" offset = 0 glc = False @@ -3695,7 +3751,7 @@ def raw_table_uav_store(self, kind_label, ops, mods, data_count, *, allow_glc=Fa vaddr = reg_range(ops[1]) if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: raise Unsupported('%s vaddr %s for offen' % (kind_label, ops[1])) - key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True) + key = self.store_descriptor(ops[2], 4, kind_label, stride0_ok=True, raw_conversion_ok=raw_conversion_ok) terms = [self.u(ops[1])] if offen else [] if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): if not offen: @@ -3720,7 +3776,7 @@ def op_buffer_store_dword(self, ops, mods, count=1): return self.op_buffer_store_vs(ops, mods, count) if self.kind != 'cs': raise Unsupported('buffer_store_dword' + ('x%d' % count if count > 1 else '')) # the unknown-op refusal - src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count) + src, uav, address, _ = self.raw_table_uav_store('buffer store', ops, mods, count, raw_conversion_ok=True) words = [self.u('v%d' % n) for n in range(src[1], src[2] + 1)] data = words[0] if count == 1 else 'uint%d(%s)' % (count, ', '.join(words)) # Store* needs a multiple of four. As in #2059, the run-time part (VGPR and register soffset) is rounded down: @@ -3936,8 +3992,9 @@ def mubuf_format(self, ops, mods, count): # FORMAT and DST_SEL are read from the table word, so word 3 must still be the loaded one. r = reg_range(ops[2]) first = self.sym.get(r[1]) if r else None - if not r or r[0] != 's' or r[2] - r[1] != 3 or not first or first[0] != 'desc' or any( - self.sym.get(r[1] + i) != ('desc', first[1], first[2], first[3] + i) for i in range(4)): + if (not r or r[0] != 's' or r[2] - r[1] != 3 or not first or first[0] != 'desc' + or not names_one_value(first) or any( + self.sym.get(r[1] + i) != desc_word(first, first[3] + i) for i in range(4))): raise Unsupported('formatted buffer load through a descriptor whose words were rewritten') if first[1][0] != 'table': raise Unsupported('formatted buffer load requires a hardware table descriptor') @@ -4309,7 +4366,7 @@ def fixed_table_image(self, operand, name): if not first or first[0] != 'desc' or first[1][0] != 'table' or first[2] is None or first[3] % 8: raise Unsupported('%s requires a fixed table image descriptor' % name) for i in range(8): - word = first[:3] + (first[3] + i,) + word = desc_word(first, first[3] + i) # A write through a second load of this descriptor can leave these SGPR symbols intact. if self.sym.get(image[1] + i) != word or desc_key(word) in self.pipe.modified: raise Unsupported('%s through a modified image descriptor' % name) @@ -6228,7 +6285,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.uses_gather_2d_lod = False self.uses_sad = set() self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] - self.notes, self.modified, self.other_modified = set(), set(), set() # other: anything but a stride clear + self.notes, self.modified, self.other_modified = set(), set(), set() # other: unproved descriptor writes self.lod_unvalidated = set() # LLVM AMDGPUUsage, COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE on gfx10: 128 dwords per unit. self.lds_words = ((rsrc2 >> 15) & 0x1ff) * 128 From 9bef64ee0e25f90130840cc1445b6450f053f48e Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:03:27 +0100 Subject: [PATCH 174/232] startup: accept forward branches outside the slot 57 group-memory exchanges (Part of #2413) (#2548) * startup: accept forward branches outside the slot 57 group-memory exchanges The slot 57 mesh skeleton of #2447 refused any branch outside the two exchanges of the program. Accept forward s_branch, wave-uniform s_cbranch_scc0/scc1 and s_cbranch_execz in the code before the first exchange and after the second, emitted through Stage's existing block dispatch; the group barrier and allocation block stays outside the pc dispatch so every path runs it. mesh_skeleton walks the code with its straight-line proofs made path-aware: at a join, a VGPR stale or pending on any incoming path is stale, a narrowed EXEC mask is kept only when every path has the same one, and the wave index, thread index and SCC facts are kept only when all paths agree. An s_cbranch_execz may skip only predicated lane writes (and an s_branch that lands at or past its target over s_nop/s_waitcnt/s_clause), because the model skips per lane where the guest skips per wave; an if/else is accepted through s_and_saveexec_b64 of a fresh VCC and its s_andn2_b64 complement. Still refused: loops, branches entering or crossing an exchange, s_cbranch_vccz/vccnz, s_setpc/s_call/s_swappc, a branch bypassing an export, an early s_endpgm, other uses of a saved EXEC mask, and an SCC branch on a value not proven wave-uniform. Tests: startup_mesh57_skeleton_check.py adds taken and not-taken SCC branches and a lane-masked if/else, drawn on WARP and hardware against the CPU model, and refusals for a loop, a branch into the count exchange, a branch over the group-index exchange, s_setpc, a VGPR defined on one path, different EXEC masks before an export, a skipped scalar write under s_cbranch_execz (also past the target), and a uniform branch over the primitive export. Part of #2413. AI-assisted. * tests: cover the remaining slot 57 branch refusals Controls for s_cbranch_vccz and s_cbranch_vccnz on a wave-wide condition, an early s_endpgm, a read of the saved EXEC pair after the masked if/else, and code left unreachable by an unconditional forward branch. Each is derived from an accepted fixture and checked to reach its own refusal. AI-assisted. --- docs/experiments.md | 14 ++- tests/startup_mesh57_skeleton_check.py | 130 ++++++++++++++++++++- tools/startup/gfx2hlsl.py | 155 +++++++++++++++++++++---- 3 files changed, 271 insertions(+), 28 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index d022a6c75..c3604295f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9328,8 +9328,8 @@ and compiles them as `ms_6_5` and `ps_6_0` (without a pixel program, to `.ms57.hlsl` alone; see below). In that shape lane 0 of wave 0 stores the primitive and vertex counts, every wave passes a barrier, wave 0 sends one allocation request and the other wave reads the counts back; the -code around it is straight-line and exports vertex and primitive `thread` -under `count > thread`. `mesh_skeleton` in `tools/startup/gfx2hlsl.py` states +code around it exports vertex and primitive `thread` under +`count > thread`. `mesh_skeleton` in `tools/startup/gfx2hlsl.py` states the shape and refuses every other program with the first difference. The lowering clamps both counts to the 128 threads of a group and each index to the last vertex. It reads 9-bit indices, ignores the edge flags, and gives a @@ -9360,6 +9360,16 @@ required slot 57 bytecode artifact. A `ps none` result needs the mesh artifact only. A missing or truncated required artifact leaves the request pending even if its manifest exists. In manifest-only mode the manifest completes it. +The code outside the exchanges accepts forward `s_branch` and wave-uniform +SCC branches. A forward `s_cbranch_execz` can skip guarded lane writes, including +the masked arm of an if/else formed with `s_and_saveexec_b64` and a proven +complement. The proof checks register definitions and output masks at joins. +Loops, indirect jumps and calls, branches entering or crossing either exchange, +and unproven wave masks remain unsupported. Use +`python -B tests/startup_mesh57_skeleton_check.py` for translations and refusals. +Append `draw ` for CPU-reference readback +of the SCC paths and lane-masked if/else. + Set `X2W_REFUSE_FIXED_MESH=1` to report unavailable fixed mesh pipelines at slot 57 creation. The descriptor must name a registered root, have an empty VS slot and have a readable 16-byte to 64-KiB MS span. The PS span must be diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index ba0c10bcc..9e5dcca73 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -56,10 +56,58 @@ def root(): return b'DXBC' + bytes(16) + struct.pack('<4I', 1, 44 + len(rts0), 1, 36) + b'RTS0' + struct.pack('; s_cbranch_scc1 .join; v_mov v7, 1.0 + ('SCC branch taken', vertex_red('7e0e0280 bf008080 bf850001 7e0e02f2'), lambda lane: 0), + ('SCC branch not taken', vertex_red('7e0e0280 bf008180 bf850001 7e0e02f2'), lambda lane: 255), + # v7 starts at 0.5. The then arm writes 1.0 for tid < 6, the else arm writes 0.0 for the remaining lanes. + # v_cmp_gt_u32 vcc, 6, v0; s_and_saveexec_b64 s[20:21], vcc; s_cbranch_execz .empty + # v_mov v7, 1.0; s_branch .else; .empty: s_nop; .else: s_andn2_b64 exec, s[20:21], exec + # v_mov v7, 0; s_mov_b64 exec, -1 + ('lane-masked if/else', masked_vertex_red(), lambda lane: 255 if lane < 6 else 0), +) + +COUNT = [i for i, word in enumerate(MESH) if word == 'bf8a0000'][2] +POST_COUNT = MESH.index('7d28000e') +GROUP_END = MESH.index('05000006') + 1 +PRIMITIVE_EXPORT = MESH.index('f8000941') + + +def joined_vertex_masks(): + pos = MESH.index('f80008cf') + # Move the vertex narrowing after the loads so the join cannot make any export operands stale. + return MESH[:POST_COUNT] + MESH[POST_COUNT + 1:pos] + [ + '7d28000e', # v_cmpx_gt_i32 s14, v0 + 'bf008080', # s_cmp_eq_i32 0, 0 + 'bf850001', # s_cbranch_scc1 .pos (first incoming mask is the vertex count) + 'befe04c1', # s_mov_b64 exec, -1 (fallthrough reaches .pos with all lanes) + ] + MESH[pos:] def request(directory, mesh, pixel=PIXEL): @@ -93,8 +141,51 @@ def expect(what, got, want): 'slot 57 mesh count exchange: a branch leaves the accepted shape'), ('a barrier after the count exchange', mutate('bf8c3f70', 'bf8a0000'), 'slot 57 mesh: s_barrier outside the group-memory exchanges'), - ('a branch after the count exchange', mutate('bf8c3f70', 'bf820000'), - 'slot 57 mesh: a branch outside the group-memory exchanges is not covered'), + ('a loop after the count exchange', + mutate('bf8c3f70', branch(0xbf82, MESH.index('bf8c3f70'), POST_COUNT)), + 'slot 57 mesh: a loop outside the group-memory exchanges is not covered'), + ('a branch into the count exchange', + MESH[:COUNT] + [branch(0xbf82, COUNT, COUNT + 2)] + MESH[COUNT:], + 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), + ('a branch over the group-index exchange', MESH[:1] + [branch(0xbf82, 1, GROUP_END + 1)] + MESH[1:], + 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), + ('an indirect branch', mutate('bf8c3f70', 'be802014'), + 'slot 57 mesh: indirect control flow (s_setpc_b64) is not covered'), + # s_cbranch_vccz .join replaces the post-count SCC branch and keeps its forward target. + ('a forward VCC-zero branch', mutate('bf850001', 'bf860001', mesh=BRANCH_CASES[0][1]), + 'slot 57 mesh: s_cbranch_vccz on a wave-wide condition is not covered'), + # s_cbranch_vccnz .join replaces the post-count SCC branch and keeps its forward target. + ('a forward VCC-nonzero branch', mutate('bf850001', 'bf870001', mesh=BRANCH_CASES[0][1]), + 'slot 57 mesh: s_cbranch_vccnz on a wave-wide condition is not covered'), + # s_endpgm before the vertex count compare, with the original final s_endpgm still present. + ('an early program end', MESH[:POST_COUNT] + ['bf810000'] + MESH[POST_COUNT:], + 'slot 57 mesh: an early s_endpgm is not covered'), + # s_or_b64 exec, exec, s[20:21] replaces the full EXEC reset after the else arm. + ('a saved EXEC read after the masked if/else', mutate('befe04c1', '89fe7e14', 3, mesh=masked_vertex_red()), + 'slot 57 mesh: an unproven use of a saved EXEC mask is not covered'), + # s_branch .join leaves the fallthrough v_mov without an incoming edge. + ('untargeted code after an unconditional forward branch', + mutate('bf850001', 'bf820001', mesh=BRANCH_CASES[0][1]), + 'slot 57 mesh: unreachable code after a branch is not covered'), + ('a VGPR defined on only one incoming path', vertex_red('bf008080 bf850001 7e0e02f2'), + 'slot 57 mesh: v7 is read where it is not defined for every lane (an entry value, or left different per wave ' + 'by an exchange)'), + ('a branch that skips the position EXEC narrowing', + MESH[:POST_COUNT] + 'bf008080 bf850001'.split() + MESH[POST_COUNT:], + 'slot 57 mesh: export pos0 is not under exec = -1 narrowed by its output count > thread index'), + ('a position export after joining different EXEC masks', joined_vertex_masks(), + 'slot 57 mesh: export pos0 is not under exec = -1 narrowed by its output count > thread index'), + # s_mov_b32 s40, 1 replaces the then-arm v_mov inside the s_cbranch_execz range. + ('an EXEC-zero branch that skips a scalar write', mutate('7e0e02f2', 'bea80381', mesh=masked_vertex_red()), + 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), + # s_cmp_eq_i32 0, 0; s_cbranch_scc1 .end (over the two-dword primitive export). + ('a uniform branch that skips the primitive export', + MESH[:PRIMITIVE_EXPORT] + ['bf008080', 'bf850002'] + MESH[PRIMITIVE_EXPORT:], + 'slot 57 mesh: a branch bypasses an export'), + # .empty: s_mov_b32 s40, 1 replaces the s_nop between the EXEC-zero target and .else. + ('a branch in an EXEC-zero range that jumps past a scalar write at the target', + mutate('bf800000', 'bea80381', mesh=masked_vertex_red()), + 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), ('a position export under the primitive count', mutate('7d28000e', '7d28000d'), 'slot 57 mesh: export pos0 is not under exec = -1 narrowed by its output count > thread index'), # v_mov_b32 v7, v1: v1 holds the stored count in wave 0 and the read one elsewhere. @@ -142,6 +233,16 @@ def controls(): expect('group memory is the two count words', re.findall(r'groupshared[^;]*;', text), ['groupshared uint lds[2];']) expect('outputs follow the allocation', all(body.index(line) > body.index(want[-1]) for line in body if 'verts[tid]' in line or 'tris[tid]' in line), True) + prefix = MESH[:1] + 'bf008080 bf850001 bf800000 bf800000'.split() + MESH[1:] + for what, mesh, _ in BRANCH_CASES + (('SCC branch before the group-index exchange', prefix, None),): + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, mesh) + expect(what + ' translates', result, 'ok') + if result == 'ok': + text = (Path(tmp) / ('%016x.ms57.hlsl' % key)).read_text() + expect(what + ' uses forward block dispatch', ('if (pc ==' in text, '[loop]' in text), (True, False)) + expect(what + ' guards the position export', bool(re.search( + r'if \(exec & 1\) \{[^\n]*o\.pos = [^\n]*mesh_vertex = true;', text)), True) for what, mesh, reason in REFUSALS: with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, mesh) @@ -358,6 +459,25 @@ def draw(dxc, renderer, adapter, publisher=None): expect('a reference with one wrong pixel fails', (r.returncode, 'pixels=1024 mismatches=1' in r.stdout, 'Draw reference mismatch' in r.stderr), (1, True, True)) + for what, mesh, red in BRANCH_CASES: + key, result = request(tmp, mesh) + expect(what + ' translates and compiles', result, 'ok') + if result != 'ok': + continue + name = str(Path(tmp) / ('%016x' % key)) + words = [a | b << 10 | c << 20 for a, b, c in indices] + struct.pack_into('> 7 at byte 8, waits and passes a barrier; every other wave passes a barrier and reads byte 8 to v5. - - Straight-line code up to the next barrier. Its only read of v5 may be one v_readfirstlane_b32 under exec = -1. + - Code up to the next barrier. Its only read of v5 may be one v_readfirstlane_b32 under exec = -1. - Counts: one barrier; the wave whose index (s_bfe_u32 of s3, 4 bits at 24) is zero stores SGPR P at byte 0 and SGPR V at byte 4 under the saved lane-0 mask, waits, passes a barrier and sends one allocation request with m0 = P << 12 | V; every other wave passes a barrier and reads both words back into the same P and V. - - Straight-line code to s_endpgm. Exports only here: pos0 and param under exec = -1 narrowed by one + - Code to s_endpgm. Exports only here: pos0 and param under exec = -1 narrowed by one v_cmpx_gt_i32 V, thread; the primitive export likewise with P. thread is the v_mbcnt pair over wave << 6. Each path therefore passes three barriers, each store has one writer (one lane of one wave), and a wait and a barrier separate it from every read. The lowering keeps one writer and one barrier: thread 0 stores, all read. @@ -1262,7 +1262,8 @@ def mesh_skeleton(ins): op_x2w_mesh_* handlers), SCC and m0 after the counts. Of s3 only the wave index is modelled. """ env = {} - start = 1 if ins and ins[0][2] == 's_inst_prefetch' else 0 + first = 1 if ins and ins[0][2] == 's_inst_prefetch' else 0 + start = next((i for i in range(first, len(ins)) if ins[i][3] == 's_mov_b64 exec, 1'), first) a_end = mesh_run(ins, start, 'group-index exchange', MESH_EXCHANGE, env) count_at = next((i for i in range(a_end, len(ins)) if ins[i][2] == 's_barrier'), len(ins)) b_end = mesh_run(ins, count_at, 'count exchange', MESH_COUNTS, env) @@ -1277,30 +1278,106 @@ def lands(key, index, what): lands('b_join', b_end, 'count exchange') lands('b_rskip', count_at + 27, 'count exchange') lane = set(range(*(lambda r: (r[1], r[2] + 1))(reg_range(env['lane'])))) + a_bits = int(env['a_bits'][1:]) sreg = {key: int(env[key][1:]) for key in ('wave', 'prims', 'verts', 'b_tmp')} vreg = {key: int(env[key][1:]) for key in ('a_zero', 'a_zero2', 'b_p', 'b_zero', 'b_v', 'b_zero2', 'b_r0', 'b_r1')} if (len({vreg['b_p'], vreg['b_zero'], vreg['b_v']}) != 3 or len({vreg['b_r0'], vreg['b_r1']}) != 2 or vreg['b_r0'] == vreg['b_zero2'] or 5 in (vreg['a_zero'], vreg['a_zero2']) or len({sreg['prims'], sreg['verts'], sreg['b_tmp']}) != 3 or {sreg['prims'], sreg['verts']} & lane - or sreg['wave'] in lane | {3, sreg['prims'], sreg['verts']} or int(env['a_bits'][1:]) in lane): + or sreg['wave'] in lane | {3, sreg['prims'], sreg['verts']} or a_bits in lane | {3} or 3 in lane): raise Unsupported('slot 57 mesh count exchange: registers of the accepted shape overlap') if not ins or ins[-1][2] != 's_endpgm': raise Unsupported('slot 57 mesh program does not end with s_endpgm') - out = list(ins[:start]) + offsets = {item[0]: i for i, item in enumerate(ins)} + edges = {} + for lo, hi in ((0, start), (a_end, count_at), (b_end, len(ins))): + for i in range(lo, hi): + off, _, name, asm = ins[i] + if name.startswith(('s_setpc', 's_call', 's_swappc')): + raise Unsupported('slot 57 mesh: indirect control flow (%s) is not covered' % name) + if name == 's_endpgm' and i != len(ins) - 1: + raise Unsupported('slot 57 mesh: an early s_endpgm is not covered') + if not name.startswith(('s_cbranch', 's_branch')): + continue + target = int(parse(asm)[1][0].split('_')[1], 16) + dest = offsets.get(target) + if dest is None: + raise Unsupported('slot 57 mesh: a branch target is not an instruction boundary') + # The first instruction of an exchange is also the preceding region's join. + # Branches must reconverge before that instruction. + if not lo <= dest < hi: + raise Unsupported('slot 57 mesh: a branch enters or crosses a group-memory exchange') + if target <= off: + raise Unsupported('slot 57 mesh: a loop outside the group-memory exchanges is not covered') + if name not in ('s_branch', 's_cbranch_scc0', 's_cbranch_scc1', 's_cbranch_execz'): + raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) + edges[i] = dest + + targets = set(edges.values()) + no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) + for source, target in edges.items(): + if ins[source][2] == 's_cbranch_execz': + # The model skips per lane, while the guest skips per wave. The difference is invisible when + # lanes with clear EXEC can only bypass predicated writes before the paths meet. A skipped + # s_branch may land at the execz target or past it over instructions without effect (the + # `s_branch .else` over `.empty: s_nop` of an if/else), so both paths meet with the same state. + for i in range(source + 1, target): + _, _, name, asm = ins[i] + if not (no_effect(i) or name == 'exp' + or (name == 's_branch' and edges[i] >= target + and all(no_effect(k) for k in range(target, edges[i]))) + or (name.startswith(('v_', 'buffer_load')) and not name.startswith(EXECZ_REFUSED) + and not scalar_effects(name, asm)[2])): + raise Unsupported('slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes') + elif any(ins[i][2] == 'exp' for i in range(source + 1, target)): + raise Unsupported('slot 57 mesh: a branch bypasses an export') + + saved_masks = set().union(*(scalar_registers(parse(asm)[1][0]) for _, _, name, asm in ins + if name == 's_and_saveexec_b64')) + out = list(ins[:first]) span = lambda first, last: (ins[first][0], ins[last][0] + ins[last][1] - ins[first][0]) - out.append(span(start, start + 1) + ('x2w_mesh_lane0', 'x2w_mesh_lane0 ' + env['lane'])) - out.append(ins[start + 2]) - out.append(span(start + 3, a_end - 1) + ('s_nop', 's_nop 0')) # State of the walk over the code outside the two exchanges. stale = set(range(256)) # VGPRs the model does not hold for every lane; no entry VGPR is modelled pending = set() # of those, the ones written only for the lanes of a narrowed exec - mask = 'lane0' # 'lane0', None (all lanes), 'verts' or 'prims' (all lanes narrowed by one compare) + mask = None # None (all lanes), an output count, or another narrowed mask wave_known = False # sreg['wave'] holds s_bfe_u32(s3, 4 bits at 24) thread = base = None # VGPR of the thread index, SGPR holding wave << 6 + thread_high = None # second instruction of a proven adjacent v_mbcnt pair scc_stale = False exports = [] - for index in list(range(a_end, count_at)) + [None] + list(range(b_end, len(ins) - 1)): + incoming = {} + falls = True + for index in (list(range(first, start)) + [start] + list(range(a_end, count_at)) + [None] + + list(range(b_end, len(ins)))): + if index in targets: + paths = incoming[index] + if falls: + paths.append((stale, pending, mask, wave_known, thread, base, scc_stale)) + stale = set().union(*(p[0] for p in paths)) + pending = set().union(*(p[1] for p in paths)) + mask = paths[0][2] + if any(p[2] != mask for p in paths): + stale |= pending + pending.clear() + mask = 'unknown' + wave_known = all(p[3] for p in paths) + thread, base = (paths[0][k] if all(p[k] == paths[0][k] for p in paths) else None for k in (4, 5)) + scc_stale = any(p[6] for p in paths) + falls = True + if not falls: + raise Unsupported('slot 57 mesh: unreachable code after a branch is not covered') + if index == start: + out.append(span(start, start + 1) + ('x2w_mesh_lane0', 'x2w_mesh_lane0 ' + env['lane'])) + out.append(ins[start + 2]) + out.append(span(start + 3, a_end - 1) + ('s_nop', 's_nop 0')) + stale |= pending | {5, vreg['a_zero'], vreg['a_zero2']} + pending.clear() + mask, thread = 'lane0', None + wave_known = wave_known and sreg['wave'] != a_bits + if base == a_bits or base in lane: + base = None + continue if index is None: if not wave_known: raise Unsupported('slot 57 mesh count exchange: the compared register is not the wave index') @@ -1310,20 +1387,34 @@ def lands(key, index, what): stale |= pending | {vreg[k] for k in ('b_p', 'b_zero', 'b_v', 'b_zero2', 'b_r0', 'b_r1')} pending.clear() mask, scc_stale = None, True + wave_known = wave_known and sreg['wave'] != sreg['b_tmp'] + if base in {sreg['prims'], sreg['verts'], sreg['b_tmp']}: + base = None continue off, size, name, asm = ins[index] after = index >= b_end _, ops, _ = parse(asm) base_name = re.sub(r'_e(32|64)$', '', name) - if name.startswith(('s_cbranch', 's_branch', 's_setpc', 's_call', 's_swappc')): - raise Unsupported('slot 57 mesh: a branch outside the group-memory exchanges is not covered') + complement = (name == 's_andn2_b64' and type(mask) is int and len(ops) == 3 + and ops == ['exec', parse(ins[mask][3])[1][0], 'exec']) + if name != 's_and_saveexec_b64' and not complement and scalar_registers(asm) & saved_masks: + raise Unsupported('slot 57 mesh: an unproven use of a saved EXEC mask is not covered') + if index in edges: + if scc_stale and reads_scc(name, asm): + raise Unsupported('slot 57 mesh: an unmodelled SCC is read by a branch') + incoming.setdefault(edges[index], []).append( + (stale.copy(), pending.copy(), mask, wave_known, thread, base, scc_stale)) + out.append(ins[index]) + falls = name != 's_branch' + continue if name.startswith('ds_') or name in ('s_barrier', 's_sendmsg', 's_sendmsghalt'): raise Unsupported('slot 57 mesh: %s outside the group-memory exchanges' % name) if name.startswith(('v_readlane', 'v_writelane')): raise Unsupported('slot 57 mesh: lane spills are not covered') keep = ins[index] if base_name == 'v_readfirstlane_b32': - if after or asm != 'v_readfirstlane_b32 %s, v5' % ops[0] or mask is not None or 5 not in stale: + if (not a_end <= index < count_at or asm != 'v_readfirstlane_b32 %s, v5' % ops[0] + or mask is not None or 5 not in stale): raise Unsupported('slot 57 mesh: v_readfirstlane_b32 outside the group-index read is not covered') keep = (off, size, 'x2w_mesh_group', 'x2w_mesh_group ' + ops[0]) ops = ops[:1] @@ -1349,11 +1440,21 @@ def lands(key, index, what): raise Unsupported('slot 57 mesh: SCC of the count exchange is read') if name.startswith(('s_cmp', 's_bitcmp')): scc_stale = False - # EXEC and VCC as wave-wide masks are outside the per-thread model here: only the two forms below touch EXEC. + # Saveexec uses a fresh VCC from an adjacent compare. Only the matching complement can read the + # saved mask. Hardware SCC (whether any bit is set) is not represented by a per-lane boolean. if asm == 's_mov_b64 exec, -1': mask = None stale |= pending pending.clear() + elif (name == 's_and_saveexec_b64' and mask is None and index > 0 and index not in targets + and re.fullmatch(r's_and_saveexec_b64 s\[\d+:\d+\], vcc', asm) + and ins[index - 1][2].startswith('v_cmp_') + and parse(ins[index - 1][3])[1][:1] in (['vcc'], ['vcc_lo'])): + mask, scc_stale = index, True + elif complement: + stale |= pending + pending.clear() + mask, scc_stale = ('else', mask), True elif base_name.startswith('v_cmpx'): count = {env['verts']: 'verts', env['prims']: 'prims'}.get(ops[0] if ops else None) if (base_name != 'v_cmpx_gt_i32' or not after or mask is not None or count is None @@ -1361,7 +1462,7 @@ def lands(key, index, what): raise Unsupported('slot 57 mesh: an EXEC compare other than output count > thread index under ' 'exec = -1 is not covered') mask = count - elif writes_exec(name, ops) or re.search(r'\bexec(_lo|_hi)?\b', asm) or ( + elif writes_exec(name, ops) or re.search(r'\b(?:exec(?:_lo|_hi)?|src_execz|src_vccz)\b', asm) or ( name.startswith('s_') and re.search(r'\bvcc(_lo|_hi)?\b', asm)): raise Unsupported('slot 57 mesh: %s on a wave mask is not covered' % base_name) # The thread index: v_mbcnt_lo(-1, wave << 6) then v_mbcnt_hi(-1, that) under exec = -1. @@ -1377,9 +1478,11 @@ def lands(key, index, what): dest = reg_range(ops[0]) if ops and not base_name.startswith(('v_cmp', 'exp', 'buffer_store')) else None writes_v = set(range(dest[1], dest[2] + 1)) if dest and dest[0] == 'v' else set() if base_name == 'v_mbcnt_lo_u32_b32' and base is not None and ops[1:] == ['-1', 's%d' % base] and mask is None \ + and index + 1 not in targets \ and index + 1 < len(ins) and ins[index + 1][3] == 'v_mbcnt_hi_u32_b32 %s, -1, %s' % (ops[0], ops[0]): thread = dest[1] - elif thread in writes_v and not (base_name == 'v_mbcnt_hi_u32_b32' and ins[index - 1][2].startswith('v_mbcnt_lo')): + thread_high = index + 1 + elif thread in writes_v and index != thread_high: raise Unsupported('slot 57 mesh: the thread index register is rewritten') if keep[2] != 'x2w_mesh_group' and reads_v & stale: raise Unsupported('slot 57 mesh: v%d is read where it is not defined for every lane (an entry value, or ' @@ -1401,7 +1504,6 @@ def lands(key, index, what): out.append(keep) if exports.count('pos0') != 1 or exports.count('target_20') != 1: raise Unsupported('slot 57 mesh: one pos0 and one primitive export are required') - out.append(ins[-1]) return out @@ -2118,6 +2220,14 @@ def translate(self): names = {off: name for off, _n, name, _asm in self.ins} execz_targets = set() if getattr(self, 'kind', None) == 'cs' else { t for t in targets if all(pc < t and names[pc] == 's_cbranch_execz' for pc, to in branches if to == t)} + self.mesh_allocation_block = None + splits = set(targets) + if getattr(self, 'kind', None) == 'ms' and targets: + at = next(i for i, item in enumerate(self.ins) if item[2] == 'x2w_mesh_counts') + self.mesh_allocation_block = self.ins[at][0] + # The exchange and its EXEC restore always run. Keep the group barrier and allocation outside + # the pc dispatch even when the preceding region took different paths. + 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__ joined, forward_splits, div_targets = self.joined_registers(with_cfg=True) @@ -2191,7 +2301,7 @@ def translate(self): raised_unsupported = None for instruction_index, (off, n, name, asm) in enumerate(self.ins): - if off in targets and off != start: + if off in splits and off != start: self.pinned_low16_v.update(self.low16_only_v) self.blocks.append((start, self.lines, None)) self.lines, start = [], off @@ -2620,6 +2730,8 @@ def lower(self, base, asm, ops, mods): if base == 's_branch': return ('jump', int(ops[0].split('_')[1], 16)) if base.startswith('s_cbranch_'): + if getattr(self, 'kind', None) == 'ms' and base in ('s_cbranch_scc0', 's_cbranch_scc1') and not self.scc_uniform: + 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:]] return ('branch', cond, int(ops[0].split('_')[1], 16)) @@ -5597,7 +5709,10 @@ def goto(off): if loops: out.append(' [loop] for (uint guard = 0; guard < 65536 && pc != 0xffffu; ++guard) {') for i, (off, lines, term) in enumerate(self.blocks): - out.append(' %sif (pc == %d) {' % ('else ' if loops and i else '', i)) + if off == getattr(self, 'mesh_allocation_block', None): + out.append(' {') + else: + out.append(' %sif (pc == %d) {' % ('else ' if loops and i else '', i)) out += [' ' + line for line in lines] nxt = i + 1 if i + 1 < len(self.blocks) else 0xffff if not term: @@ -6351,8 +6466,6 @@ class MeshPipeline(Pipeline): def hlsl_ms(self): s = self.vs - if len(s.blocks) != 1: - raise Unsupported('slot 57 mesh: a branch outside the group-memory exchanges is not covered') lines = [re.sub(r' o\.fparam(\d+) = [^;]*;', lambda m: m[0] if int(m[1]) in self.flat else '', re.sub(r' o\.hparam(\d+)_(?:lo|hi) = [^;]*;', lambda m: m[0] if int(m[1]) in self.f16_plain else '', line)) From 1e79cb4bb8d5d3527fd7ca0fa897b185096a93a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= <113895866+Asimmimx@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:05:50 +0300 Subject: [PATCH 175/232] textures: refuse a block-compressed copy box that does not end on a block (#2553) * textures: measure block-compressed copy bounds in whole blocks list_copy_texture.h compared the copy region of a block-compressed CopyTextureRegion against the subresource size in texels. A 2x2 or 1x1 BC mip (and any mip whose size is not a multiple of 4, such as 6x6) has a 4x4-block-aligned footprint from GetCopyableFootprints, so the canonical whole-footprint upload with a null box was refused as dest_overflow and never forwarded, although D3D12 accepts it. Round each side's extent up to the block before the bounds checks, as D3D12 does (its debug layer reports a 1x1 BC1 mip as 4x4). A second block or an 8x8 footprint into a 1x1 mip is still refused. * textures: refuse a block-compressed copy box that does not end on a block D3D12 requires an explicit block-compressed source box to end on a whole block too, even where it ends at the edge of a smaller mip. Forwarded, a {0,0,2,2} box on a 2x2 mip or {0,0,6,6} on a 6x6 mip makes the desktop list's Close return E_INVALIDARG (measured without the debug layer on WARP and an RX 6600), so every command recorded in that list is lost. The check now reports bad_alignment for such a box, and slot 16 drops only that copy. --------- Co-authored-by: Royoo <3230853833@qq.com> --- docs/startup-runtime.md | 7 ++++-- src/startup_stubs/list_copy_texture.h | 6 ++++- tests/startup_list_copy_texture_check.cpp | 10 +++++++++ tests/startup_list_copy_texture_warp.cpp | 27 +++++++++++++++++++++++ 4 files changed, 47 insertions(+), 3 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 193f627ed..c70bbe8e6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2985,6 +2985,8 @@ check only: the buffer (includes the destination origin, the source box origin and the footprint-height slice stride), block alignment, every multiply and add in the footprint arithmetic checked for wrapping. Block-compressed bounds are whole 4x4 blocks, as in D3D12: a 2x2 or 1x1 mip takes the 4x4 footprint GetCopyableFootprints gives it. + An explicit box must also end on a block (`{0,0,2,2}` on a 2x2 mip is `bad_alignment`): forwarded, it makes the + desktop list's Close fail with E_INVALIDARG. - Subresource index: `mip + slice * mips + plane * mips * array_size` must lie inside the resource's `mips * array_size * planes`; a mip-only modulo would read an out-of-range slice as mip 0 (`bad_subresource`). A planar format (more than one plane) is refused (`planar_unsupported`). @@ -3002,6 +3004,7 @@ check only: Wrapped-list readback (`tests/startup_list_copy_texture_warp.cpp`): two images round-trip through array slices 1 and 2 of a 2-mip, 3-slice texture (upload buffer, texture, readback buffer, byte-for-byte), and a list with an out-of-range subresource, an index of `0xffffffff` and a footprint format mismatch is refused -before any desktop copy, leaving a sentinel-filled readback buffer unchanged. Reproduce the portable check -with its negative controls and the WARP and hardware runs with +before any desktop copy, leaving a sentinel-filled readback buffer unchanged. On a BC1 2x2 mip, the same +list refuses boxes with an unaligned right or bottom edge, copies the aligned 4x4 block, and reads back +all eight block bytes with the next byte unchanged. Reproduce the portable and wrapped-list checks with `ctest --preset dev --no-tests=error -R '^startup_list_copy_texture' -V`. diff --git a/src/startup_stubs/list_copy_texture.h b/src/startup_stubs/list_copy_texture.h index 4ca6f57a3..6a2fe981c 100644 --- a/src/startup_stubs/list_copy_texture.h +++ b/src/startup_stubs/list_copy_texture.h @@ -61,7 +61,7 @@ enum class Verdict { bad_offset, // a footprint offset that is not a multiple of 512 footprint_overflow, // the footprint reaches past the end of its buffer sample_mismatch, // the two sides differ in sample count - bad_alignment, // a block-compressed copy that does not start on a block + bad_alignment, // a block-compressed copy that does not start on a block, or a box that does not end on one bad_subresource, // an index outside the resource's mips * array slices * planes format_mismatch, // the two sides name different formats partial_multisample, // a multisampled copy that is not the whole subresource at the origin @@ -154,6 +154,10 @@ inline Verdict check(const Side& dst, std::uint32_t x, std::uint32_t y, std::uin if (use.left >= use.right || use.top >= use.bottom || use.front >= use.back) return Verdict::bad_box; if (use.right > src_w || use.bottom > src_h || use.back > src.depth) return Verdict::source_overflow; if (x % tex.block_w || use.left % tex.block_w || y % tex.block_h || use.top % tex.block_h) return Verdict::bad_alignment; + // The box must also end on a block, even where it ends at the edge of a smaller mip: a {0,0,2,2} box on a 2x2 or + // a {0,0,6,6} box on a 6x6 block-compressed mip makes the desktop list's Close fail with E_INVALIDARG, so every + // command recorded in it is lost (measured without the debug layer on WARP and on an RX 6600). + if (use.right % tex.block_w || use.bottom % tex.block_h) return Verdict::bad_alignment; const std::uint32_t w = use.right - use.left, h = use.bottom - use.top, d = use.back - use.front; // D3D12 requires a null source box even if an explicit box would cover the whole subresource. const bool depth_stencil = src.depth_stencil || dst.depth_stencil; diff --git a/tests/startup_list_copy_texture_check.cpp b/tests/startup_list_copy_texture_check.cpp index 22a5d948e..38ade4ed0 100644 --- a/tests/startup_list_copy_texture_check.cpp +++ b/tests/startup_list_copy_texture_check.cpp @@ -70,6 +70,16 @@ int main(int argc, char** argv) expect(check(texture(2, 2, 4), 4, 0, 0, footprint(4, 4, 512, 256, 8, 1032, 4), nullptr), Verdict::dest_overflow, "bc 2x2 mip, second block"); expect(check(texture(1, 1, 4), 0, 0, 0, footprint(8, 8, 0, 256, 8, 272, 4), nullptr), Verdict::dest_overflow, "bc 1x1 mip, 8x8 footprint"); expect(check(texture(2, 2, 4), 0, 0, 0, texture(4, 4, 4), &(const Box&)Box{0, 0, 0, 8, 4, 1}), Verdict::source_overflow, "bc 4x4 source, 8-wide box"); + // An explicit box must also end on a block, even at the edge of a smaller mip. Without the debug layer, on WARP + // and on an RX 6600, each of these three makes the list's Close return E_INVALIDARG; the 8x8 box on the 6x6 mip + // (it ends on a block) closes and executes. + expect(check(texture(2, 2, 4), 0, 0, 0, footprint(4, 4, 512, 256, 8, 1032, 4), &(const Box&)Box{0, 0, 0, 2, 2, 1}), + Verdict::bad_alignment, "bc 2x2 mip, 2x2 box"); + expect(check(texture(6, 6, 4), 0, 0, 0, texture(6, 6, 4), &(const Box&)Box{0, 0, 0, 6, 6, 1}), Verdict::bad_alignment, "bc 6x6 mip, 6x6 box"); + expect(check(texture(6, 6, 4), 0, 0, 0, texture(6, 6, 4), &(const Box&)Box{0, 0, 0, 6, 8, 1}), Verdict::bad_alignment, "bc 6x6 mip, 6x8 box"); + expect(check(texture(6, 6, 4), 0, 0, 0, texture(6, 6, 4), &(const Box&)Box{0, 0, 0, 8, 6, 1}), Verdict::bad_alignment, "bc 6x6 mip, 8x6 box"); + expect(check(texture(6, 6, 4), 0, 0, 0, texture(6, 6, 4), &(const Box&)Box{0, 0, 0, 8, 8, 1}), Verdict::ok, "bc 6x6 mip, 8x8 box"); + expect(check(texture(64, 64, 4), 0, 0, 0, texture(64, 64, 4), &(const Box&)Box{4, 8, 0, 12, 16, 1}), Verdict::ok, "bc inner whole-block box"); // The destination origin counts: a 1x1 RGBA8 copy at Y=63 of a 64x64, 256-pitch footprint ends at byte 16132. expect(check(footprint(64, 64, 0, 256, 4, 256), 0, 63, 0, texture(1, 1), nullptr), Verdict::footprint_overflow, "dest origin counts"); diff --git a/tests/startup_list_copy_texture_warp.cpp b/tests/startup_list_copy_texture_warp.cpp index 46e6e033a..4acdd6a4c 100644 --- a/tests/startup_list_copy_texture_warp.cpp +++ b/tests/startup_list_copy_texture_warp.cpp @@ -211,6 +211,33 @@ int main(int argc, char** argv) std::puts("2 the readback buffer changed"); return 17; } + // 3. Refuse either unaligned edge without losing the valid copy and readback on the same list. + const D3D12_RESOURCE_DESC bc_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, 8, 8, 1, 3, + DXGI_FORMAT_BC1_UNORM, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN}; + void* bc = make_resource(device, D3D12_HEAP_TYPE_DEFAULT, bc_desc, D3D12_RESOURCE_STATE_COMMON); + if (!bc || !ok(invoke(list, 139, arg(allocator), 0))) return 18; + const auto bc_mip = subresource(bc, 2); + const auto bc_up = footprint(upload, 0, DXGI_FORMAT_BC1_UNORM); + const auto bc_out = footprint(readback, 0, DXGI_FORMAT_BC1_UNORM); + const D3D12_BOX bad_right{0, 0, 0, 2, 4, 1}; + const D3D12_BOX bad_bottom{0, 0, 0, 4, 2, 1}; + const D3D12_BOX whole_block{0, 0, 0, 4, 4, 1}; + invoke(list, 16, arg(&bc_mip), 0, 0, 0, arg(&bc_up), arg(&bad_right)); + invoke(list, 16, arg(&bc_mip), 0, 0, 0, arg(&bc_up), arg(&bad_bottom)); + invoke(list, 16, arg(&bc_mip), 0, 0, 0, arg(&bc_up), arg(&whole_block)); + copy(bc_out, bc_mip); + if (!ok(invoke(list, 9)) || !submit()) return 19; + LONG forwarded3 = 0, refused3 = 0; + x2w_d3d12_list_copy_texture_stats(&forwarded3, &refused3); + std::printf("3 BC1 mip: forwarded +%ld refused +%ld (expected +2, +2)\n", forwarded3 - forwarded2, refused3 - refused2); + if (forwarded3 - forwarded2 != 2 || refused3 - refused2 != 2) return 20; + if (!ok(invoke(readback, 8, 0, 0, arg(&memory))) || !memory) return 21; + const auto* block = static_cast(memory); + bool block_ok = block[8] == sentinel; + for (UINT i = 0; i < 8; ++i) block_ok = block_ok && block[i] == image_byte(0, 0, i); + invoke(readback, 9, 0, 0); + if (!block_ok) return 22; + std::puts("ok"); return 0; } From 7962b1a51718f200878e90e8a40195a576cd3418 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg Date: Thu, 26 Nov 2026 05:07:41 +0800 Subject: [PATCH 176/232] docs: show how to prime the Windows pixel core fixture cache (#2561) AI-assisted with Codex (GPT-6.2 Astra, xhigh). Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- docs/experiments.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index c3604295f..4bc816298 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -7586,6 +7586,24 @@ hashes and per-case outcomes. The union of the two new coverage records matched the original 710 forms. This establishes equivalent selected work on WARP, not physical-adapter timeout headroom. +If `pixel_aot_hardware` approaches its 60 s timeout on Windows, you can prime +the Python bytecode cache once before measuring. CTest starts the fixture with +`-B`, so Python can read cached modules but does not write them during the test. +From the repository root, use the same interpreter configured as `INTAKE_PYTHON` +(the default path is shown here) and run CTest in the same PowerShell session. + +```powershell +$env:PYTHONPYCACHEPREFIX = Join-Path $PWD 'out/pycache' +& .\out\pe-env\Scripts\python.exe -c "import sys; sys.path.insert(0, 'tests'); import pixel_aot_check" +ctest --preset dev --no-tests=error -R '^pixel_aot_hardware$' -V +``` + +On Windows 11 build 26100.9711 at `82bb67ef`, six of eight runs on an Intel UHD +770 and RTX 4060 reached the timeout before priming. The import took 5.75 s +once. With the cache, three runs per adapter took 25.68–27.77 s and produced +the same 1,010-line form record as the two earlier completed runs. +[Commands, drivers and individual times in #448](https://github.com/R0Y00/Xbox2Windows/issues/448#issuecomment-7174505456). + The first raw buffer_load_dword path remains a proposal while [issue #319](https://github.com/R0Y00/Xbox2Windows/issues/319) is open. The [binding contract](pixel_mubuf_contract.md) records the separate DW0/DW1 From 0104f76302ddbf66af55dd0bcffda4decebfe940 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 23:08:20 +0200 Subject: [PATCH 177/232] shader: extract main(argv), atomic HLSL writes, and directory/struct/zlib guards in shader_profile_audit with CLI suite (#2554) * shader: extract main(argv), atomic HLSL writes, and directory/struct/zlib guards in shader_profile_audit with CLI suite * tests: sort iterdir() listing in shader_profile_audit_cli_check --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/shader_profile_audit_cli_check.py | 362 ++++++++++++++++++++++++ tools/shader_profile_audit.py | 84 ++++-- 3 files changed, 428 insertions(+), 20 deletions(-) create mode 100644 tests/shader_profile_audit_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ef2ef512d..1157febcf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9805,6 +9805,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/shader_census_check.py") add_test(NAME shader_profile_audit_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/shader_profile_audit_check.py") + add_test(NAME shader_profile_audit_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/shader_profile_audit_cli_check.py") add_test(NAME shader_metadata_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/probe_roots_cli_check.py") # Keep both shader-model profiles in the retarget probe even though the draw fixture uses SM 6.0. diff --git a/tests/shader_profile_audit_cli_check.py b/tests/shader_profile_audit_cli_check.py new file mode 100644 index 000000000..82418d731 --- /dev/null +++ b/tests/shader_profile_audit_cli_check.py @@ -0,0 +1,362 @@ +"""CLI, atomic HLSL write, path-collision, error-guard, and mutation suite for tools/shader_profile_audit.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "shader_profile_audit.py" +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) + +import shader_profile_audit # noqa: E402 +import shader_profile_audit_check as fixture # noqa: E402 + + +def _synthetic_archive() -> tuple[bytes, dict[str, bytes]]: + ps_ok = fixture.make_shader_blob(0, fixture.PS_GENERAL_TAG, marker=1) + ps_cb = fixture.make_shader_blob(0, fixture.PS_CB_TAG, marker=2) + ps_bad = fixture.make_shader_blob(0, fixture.PS_BAD_TAG, marker=3) + cs_ok = fixture.make_shader_blob(5, fixture.CS_STORE_TAG, psv_group=(4, 1, 8), marker=4) + ms_ok = fixture.make_shader_blob(13, fixture.MS_POINT_TAG, code_bytes=832, psv_group=(128, 1, 1), marker=5) + vs_skip = fixture.make_shader_blob(1, fixture.PS_GENERAL_TAG, marker=6) + archive = ( + fixture.rpf_record(ps_ok, "ps_ok") + + fixture.rpf_record(ps_cb, "ps_cb") + + fixture.rpf_record(ps_bad, "ps_bad") + + fixture.rpf_record(cs_ok, "cs_ok") + + fixture.rpf_record(ms_ok, "ms_ok") + + fixture.rpf_record(vs_skip, "vs_skip") + ) + blobs = {"ps_ok": ps_ok, "cs_ok": cs_ok, "ms_ok": ms_ok} + return archive, blobs + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = shader_profile_audit.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class ShaderProfileAuditCliPositiveTests(unittest.TestCase): + def test_main_writes_hlsl_and_probe_atomically_and_returns_zero_json(self) -> None: + archive_bytes, blobs = _synthetic_archive() + expected_hashes = {name: hashlib.sha256(blob).hexdigest() for name, blob in blobs.items()} + + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + source_dir = root / "nested" / "hlsl_out" + self.assertFalse(source_dir.exists()) + + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with ( + mock.patch.object(shader_profile_audit.pixel_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.mesh_entry_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main([str(archive), "--llvm", "stub", "--source-dir", str(source_dir), "--cb-reads"]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + payload = json.loads(out) + self.assertEqual(set(payload), {"records", "hlsl_records", "profiles", "first_stops", "cb_reads"}) + self.assertEqual(payload["records"], {"PS": 3, "CS": 1, "MS": 1, "VS": 1}) + self.assertEqual(payload["hlsl_records"], {"PS": 1, "CS": 1, "MS": 1}) + self.assertEqual(payload["profiles"], {"PS": {"general": 1}, "CS": {"store": 1}, "MS": {"point mesh": 1}}) + self.assertEqual(payload["cb_reads"]["first_descriptor"], [["entry s9 + 0x0", 1]]) + + expected_files = { + source_dir / "general" / f"{expected_hashes['ps_ok']}.hlsl", + source_dir / "store" / f"{expected_hashes['cs_ok']}.hlsl", + source_dir / "point-mesh" / f"{expected_hashes['ms_ok']}.hlsl", + source_dir / "s9-slot0-read-probe.hlsl", + } + self.assertEqual(len(seen_replaces), len(expected_files)) + self.assertEqual({dst.resolve() for _, dst in seen_replaces}, {p.resolve() for p in expected_files}) + for path in expected_files: + self.assertTrue(path.is_file(), f"missing emitted file: {path}") + self.assertEqual(sorted(p.name for p in path.parent.iterdir()), [path.name] if path.parent != source_dir else sorted(["general", "store", "point-mesh", "s9-slot0-read-probe.hlsl"])) + + # Second run atomically overwrites stale contents with zero leftover temp dirs. + for path in expected_files: + path.write_text("STALE_CONTENT", encoding="utf-8") + with ( + mock.patch.object(shader_profile_audit.pixel_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.mesh_entry_aot, "disassemble", side_effect=fixture.stub_disassemble), + ): + code, _, err = _run_main([str(archive), "--llvm", "stub", "--source-dir", str(source_dir), "--cb-reads"]) + self.assertEqual(code, 0, err) + for path in expected_files: + self.assertNotEqual(path.read_text(encoding="utf-8"), "STALE_CONTENT") + if path.parent != source_dir: + self.assertEqual([p.name for p in path.parent.iterdir()], [path.name]) + self.assertEqual(sorted(p.name for p in source_dir.iterdir()), ["general", "point-mesh", "s9-slot0-read-probe.hlsl", "store"]) + + def test_main_forwards_default_sys_argv_and_script_entrypoint_returns_zero(self) -> None: + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "empty.rpf" + archive.write_bytes(b"") + cli_argv = [str(TOOL), str(archive), "--llvm", "stub"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(json.loads(out), {"records": {}, "hlsl_records": {}, "profiles": {}, "first_stops": {}}) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue()), {"records": {}, "hlsl_records": {}, "profiles": {}, "first_stops": {}}) + + proc = _run_subprocess(str(archive), "--llvm", "stub", "--cb-reads") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("cb_reads", json.loads(proc.stdout)) + + +class ShaderProfileAuditCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + + def test_missing_and_directory_archive_rejected_cleanly(self) -> None: + # Kills removal of OSError/ValueError handling and args.archive.is_dir() guard. + with TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.rpf" + self._assert_clean_failure( + [str(missing), "--llvm", "stub"], + expected_fragments=("Shader profile audit:", "Missing archive file"), + ) + + dir_archive = root / "archive_dir" + dir_archive.mkdir() + argv = [str(dir_archive), "--llvm", "stub"] + with mock.patch.object(shader_profile_audit, "scan") as scan_mock: + self._assert_clean_failure( + argv, + expected_fragments=("Shader profile audit:", "Archive path is a directory"), + check_subprocess=False, + ) + scan_mock.assert_not_called() + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("Shader profile audit: Archive path is a directory", proc.stderr) + + def test_source_dir_regular_file_and_archive_collisions_rejected_upfront(self) -> None: + # Kills removal of upfront --source-dir regular-file and resolve()/samefile() collision guards. + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "empty.rpf" + archive.write_bytes(b"") + sub = root / "sub" + sub.mkdir() + + existing_file = root / "not_a_dir.txt" + existing_file.write_bytes(b"preserve-me") + with mock.patch.object(shader_profile_audit, "scan") as scan_mock: + self._assert_clean_failure( + [str(archive), "--llvm", "stub", "--source-dir", str(existing_file)], + expected_fragments=("Shader profile audit:", "Source directory is not a directory"), + ) + scan_mock.assert_not_called() + self.assertEqual(existing_file.read_bytes(), b"preserve-me") + + # 1) Relative alias to existing archive. + alias = sub / ".." / "empty.rpf" + with mock.patch.object(shader_profile_audit, "scan") as scan_mock: + self._assert_clean_failure( + [str(archive), "--llvm", "stub", "--source-dir", str(alias)], + expected_fragments=("Shader profile audit:", "collides with archive"), + ) + scan_mock.assert_not_called() + + # 2) Non-existent archive alias (kills mutating resolve() == resolve()). + ghost = root / "ghost.rpf" + ghost_alias = sub / ".." / "ghost.rpf" + with mock.patch.object(shader_profile_audit, "scan") as scan_mock: + self._assert_clean_failure( + [str(ghost), "--llvm", "stub", "--source-dir", str(ghost_alias)], + expected_fragments=("Shader profile audit:", "collides with archive"), + ) + scan_mock.assert_not_called() + + # 3) Hardlink alias where resolve() differs (kills mutating samefile()). + hardlink = root / "empty_hardlink.rpf" + os.link(archive, hardlink) + self.assertNotEqual(archive.resolve(), hardlink.resolve()) + self.assertTrue(archive.samefile(hardlink)) + with mock.patch.object(shader_profile_audit, "scan") as scan_mock: + self._assert_clean_failure( + [str(archive), "--llvm", "stub", "--source-dir", str(hardlink)], + expected_fragments=("Shader profile audit:", "collides with archive"), + ) + scan_mock.assert_not_called() + + def test_output_file_colliding_with_archive_rejected_without_overwrite(self) -> None: + # Kills removal of per-destination archive collision guard. + archive_bytes, _ = _synthetic_archive() + with TemporaryDirectory() as tmp: + source_dir = Path(tmp) + archive = source_dir / "s9-slot0-read-probe.hlsl" + archive.write_bytes(archive_bytes) + with ( + mock.patch.object(shader_profile_audit.pixel_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.mesh_entry_aot, "disassemble", side_effect=fixture.stub_disassemble), + ): + self._assert_clean_failure( + [str(archive), "--llvm", "stub", "--source-dir", str(source_dir), "--cb-reads"], + expected_fragments=("Shader profile audit:", "Output file collides with archive"), + check_subprocess=False, + ) + self.assertEqual(archive.read_bytes(), archive_bytes) + + def test_os_replace_failure_leaves_zero_partial_files_or_temp_dirs(self) -> None: + archive_bytes, _ = _synthetic_archive() + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + source_dir = root / "atomic_fail" + replace_calls = [] + + def failing_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), Path(dst).parent.resolve()) + raise OSError("simulated replace failure") + + with ( + mock.patch.object(shader_profile_audit.pixel_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.mesh_entry_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.os, "replace", side_effect=failing_replace), + ): + self._assert_clean_failure( + [str(archive), "--llvm", "stub", "--source-dir", str(source_dir), "--cb-reads"], + expected_fragments=("Shader profile audit:", "simulated replace failure"), + check_subprocess=False, + ) + + self.assertEqual(len(replace_calls), 1) + # Only the parent directory of the first target exists; 0 .hlsl files and 0 temp dirs remain. + self.assertEqual(list(source_dir.rglob("*.hlsl")), []) + for directory in [source_dir, *(p for p in source_dir.rglob("*") if p.is_dir())]: + self.assertFalse(any(p.name.startswith("tmp") for p in directory.iterdir()), list(directory.iterdir())) + + def test_mid_scan_struct_and_zlib_errors_caught_without_partial_hlsl_or_traceback(self) -> None: + # Kills removal of struct.error and zlib.error from except (OSError, ValueError, struct.error, zlib.error). + archive_bytes, _ = _synthetic_archive() + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "shaders.rpf" + archive.write_bytes(archive_bytes) + + for exc_obj, fragment in ( + (struct.error("unpack_from requires a buffer of at least 4 bytes"), "unpack_from requires a buffer"), + (zlib.error("Error -3 while decompressing data: incorrect header check"), "Error -3 while decompressing data"), + ): + source_dir = root / f"fail_{type(exc_obj).__name__}" + with self.subTest(exc=type(exc_obj).__name__): + with ( + mock.patch.object(shader_profile_audit.pixel_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit.mesh_entry_aot, "disassemble", side_effect=fixture.stub_disassemble), + mock.patch.object(shader_profile_audit, "cb_diagnostic", side_effect=exc_obj), + ): + self._assert_clean_failure( + [str(archive), "--llvm", "stub", "--source-dir", str(source_dir), "--cb-reads"], + expected_fragments=("Shader profile audit:", fragment), + check_subprocess=False, + ) + self.assertFalse(source_dir.exists()) + + # Subprocess OSError check (zero traceback). + missing = root / "missing_sub.rpf" + proc = _run_subprocess(str(missing), "--llvm", "stub") + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("Shader profile audit:", proc.stderr) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "empty.rpf" + archive.write_bytes(b"") + for bad_argv in ([], [str(archive)], [str(archive), "--llvm", "stub", "--unknown-flag"]): + with self.subTest(argv=bad_argv): + self._assert_clean_failure(bad_argv, expected_code=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/shader_profile_audit.py b/tools/shader_profile_audit.py index ce57fa7e4..4221f811f 100644 --- a/tools/shader_profile_audit.py +++ b/tools/shader_profile_audit.py @@ -2,13 +2,16 @@ import argparse from collections import Counter, defaultdict -from collections.abc import Mapping +from collections.abc import Mapping, Sequence import hashlib import itertools import json import mmap +import os from pathlib import Path import struct +import tempfile +import zlib import compute_store_aot import depth_mask_aot @@ -213,25 +216,40 @@ def cb_diagnostic(program, llvm): return group, read, method, stop, probe -def scan(archive, llvm, source_dir=None, *, cb_reads=False): - if isinstance(archive, (str, Path)): - path = Path(archive) - if not path.is_file(): - raise ValueError(f"Missing archive file: {path}") - with path.open("rb") as f: - if f.seek(0, 2): - with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as data: - return scan(data, llvm, source_dir, cb_reads=cb_reads) - return scan(b"", llvm, source_dir, cb_reads=cb_reads) +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _write_text_atomic(destination: Path, content: str, *, encoding: str) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=destination.parent) as staging_dir: + staged = Path(staging_dir) / destination.name + staged.write_text(content, encoding=encoding) + os.replace(staged, destination) + + +def _validate_source_dir(source_dir: Path, archive_path: Path | None = None) -> None: + if archive_path is not None and _same_path(source_dir, archive_path): + raise ValueError(f"Source directory collides with archive: {source_dir}") + if source_dir.exists() and not source_dir.is_dir(): + raise ValueError(f"Source directory is not a directory: {source_dir}") + + +def _scan_bytes(archive, llvm, source_dir=None, *, cb_reads=False, archive_path: Path | None = None): if not isinstance(archive, (bytes, bytearray, memoryview, mmap.mmap)): raise ValueError("Archive payload must be bytes-like or a path") source_dir = Path(source_dir) if source_dir is not None else None + if source_dir is not None: + _validate_source_dir(source_dir, archive_path) cache = {} records, accepted = Counter(), Counter() profiles, first_stops = defaultdict(Counter), defaultdict(Counter) cb_cache = {} groups, modes, consumers, after_binding = Counter(), Counter(), Counter(), Counter() probe_source = None + pending_writes: dict[Path, tuple[str, str]] = {} def observe(stage, blob, sections): nonlocal probe_source @@ -241,9 +259,7 @@ def observe(stage, blob, sections): def emit(profile, source): if source_dir is not None: - directory = source_dir / profile - directory.mkdir(exist_ok=True, parents=True) - (directory / (digest.hex() + ".hlsl")).write_text(source, encoding="utf-8") + pending_writes[source_dir / profile / f"{digest.hex()}.hlsl"] = (source, "utf-8") if digest not in cache: try: @@ -276,24 +292,52 @@ def emit(profile, source): s9_zero_reads=consumers.most_common(), s9_zero_full_shader_stops=after_binding.most_common()) if probe_source is not None and source_dir is not None: - source_dir.mkdir(parents=True, exist_ok=True) - (source_dir / "s9-slot0-read-probe.hlsl").write_text(probe_source, encoding="ascii") + pending_writes[source_dir / "s9-slot0-read-probe.hlsl"] = (probe_source, "ascii") + for destination, _ in pending_writes.items(): + if archive_path is not None and _same_path(destination, archive_path): + raise ValueError(f"Output file collides with archive: {destination}") + if destination.exists() and destination.is_dir(): + raise ValueError(f"Output path is a directory: {destination}") + for destination, (content, encoding) in pending_writes.items(): + _write_text_atomic(destination, content, encoding=encoding) return result -def main(): +def scan(archive, llvm, source_dir=None, *, cb_reads=False): + if isinstance(archive, (str, Path)): + path = Path(archive) + if path.is_dir(): + raise ValueError(f"Archive path is a directory: {path}") + if not path.is_file(): + raise ValueError(f"Missing archive file: {path}") + if source_dir is not None: + _validate_source_dir(Path(source_dir), path) + with path.open("rb") as f: + if f.seek(0, 2): + with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as data: + return _scan_bytes(data, llvm, source_dir, cb_reads=cb_reads, archive_path=path) + return _scan_bytes(b"", llvm, source_dir, cb_reads=cb_reads, archive_path=path) + return _scan_bytes(archive, llvm, source_dir, cb_reads=cb_reads) + + +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path) parser.add_argument("--llvm", required=True, help="Path or loader name for the LLVM 15 library") parser.add_argument("--source-dir", type=Path, help="Optional local directory for accepted HLSL by profile and container hash") parser.add_argument("--cb-reads", action="store_true", help="Trace first-profile unresolved constant buffer reads") - args = parser.parse_args() + args = parser.parse_args(argv) try: + if args.archive.is_dir(): + raise ValueError(f"Archive path is a directory: {args.archive}") + if args.source_dir is not None: + _validate_source_dir(args.source_dir, args.archive) result = scan(args.archive, args.llvm, args.source_dir, cb_reads=args.cb_reads) - except (OSError, ValueError) as error: + except (OSError, ValueError, struct.error, zlib.error) as error: parser.exit(1, f"Shader profile audit: {error}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 1c902063f9223091d02d09069747bcde872c7d96 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 23:12:29 +0200 Subject: [PATCH 178/232] shader: return exit code from main(argv), handle empty archives, and add path/error guards in compute_container_index with CLI suite (#2562) --- CMakeLists.txt | 2 + tests/compute_container_index_cli_check.py | 312 +++++++++++++++++++++ tools/compute_container_index.py | 47 +++- 3 files changed, 354 insertions(+), 7 deletions(-) create mode 100644 tests/compute_container_index_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1157febcf..671409c90 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3944,6 +3944,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_request_offline_check.py") add_test(NAME compute_container_index COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/compute_container_index_check.py") + add_test(NAME compute_container_index_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/compute_container_index_cli_check.py") # Offline re-key of saved shader requests under the current cache revision (pure Python). add_test(NAME startup_shader_cache_rekey COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_check.py") diff --git a/tests/compute_container_index_cli_check.py b/tests/compute_container_index_cli_check.py new file mode 100644 index 000000000..2e7a28a5f --- /dev/null +++ b/tests/compute_container_index_cli_check.py @@ -0,0 +1,312 @@ +"""CLI, empty-archive, path/collision, error-guard, and mutation suite for tools/compute_container_index.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "compute_container_index.py" +sys.path.insert(0, str(ROOT / "tools")) + +import compute_container_index # noqa: E402 + + +def _build_compute_container(hash_part: bytes | None, *, stage: int = 5) -> bytes: + program = struct.pack(" bytes: + compressor = zlib.compressobj(wbits=-15) + compressed = compressor.compress(blob) + compressor.flush() + size = len(compressed) + return f"fixture-{index}".encode("ascii") + b"\x00\x00" + struct.pack("<4I", size, 0, size, len(blob)) + compressed + + +def _slot_data(digest: bytes) -> bytes: + return struct.pack(" tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = compute_container_index.main(argv) + except SystemExit as exc: + return exc.code, stdout.getvalue(), stderr.getvalue() + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class ComputeContainerIndexCliPositiveTests(unittest.TestCase): + def _assert_schema(self, doc: dict, *, selection: str) -> None: + self.assertEqual(set(doc), {"selection", "summary", "requests"}) + self.assertEqual(doc["selection"], selection) + self.assertEqual( + set(doc["summary"]), + { + "cache_requests", + "selected_keys", + "request_statuses", + "archive_records", + "archive_framing_rejections", + }, + ) + + def test_empty_archive_and_nonempty_cache_modes_return_zero_json(self) -> None: + digest = b"\x11" * 16 + blob = _build_compute_container(bytes(4) + digest) + expected_sha = hashlib.sha256(blob).hexdigest() + key_hex = f"{1:016x}" + + with TemporaryDirectory() as tmp: + root = Path(tmp) + cache = root / "cache" + cache.mkdir() + (cache / f"req_{key_hex}.c67").write_bytes(b"slot67") + (cache / f"req_{key_hex}.data").write_bytes(_slot_data(digest)) + + # 1) 0-byte archive must not crash mmap.mmap(..., 0); passes b"" to scene_records. + empty_archive = root / "empty.bin" + empty_archive.write_bytes(b"") + code, out, err = _run_main([str(empty_archive), str(cache)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + empty_doc = json.loads(out) + self._assert_schema(empty_doc, selection="cache") + self.assertEqual(empty_doc["summary"]["cache_requests"], 1) + self.assertEqual(empty_doc["summary"]["selected_keys"], 1) + self.assertEqual(empty_doc["summary"]["archive_records"], {}) + self.assertEqual(empty_doc["requests"][key_hex], {"status": "unmatched", "candidates": []}) + + proc = _run_subprocess(str(empty_archive), str(cache)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), empty_doc) + + # 2) Non-empty archive with --trace returns matched unique candidate and dispatch_rows. + archive = root / "shaders.bin" + archive.write_bytes(_archive_record(0, blob)) + trace = root / "dispatch.log" + trace.write_text(f"x2w-mesh-compute mode=direct key={key_hex} frame=1\n", encoding="utf-8") + + code, out, err = _run_main([str(archive), str(cache), "--trace", str(trace)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + traced_doc = json.loads(out) + self._assert_schema(traced_doc, selection="dispatch-trace") + self.assertEqual( + traced_doc["requests"][key_hex], + { + "status": "unique", + "dispatch_rows": {"direct": 1}, + "candidates": [{"sha256": expected_sha, "hash_flags": 0, "records": 1}], + }, + ) + self.assertEqual(sorted(p.name for p in cache.iterdir()), [f"req_{key_hex}.c67", f"req_{key_hex}.data"]) + + def test_main_forwards_sys_argv_and_script_entrypoint_returns_zero(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "empty.bin" + archive.write_bytes(b"") + cache = root / "cache" + cache.mkdir() + cli_argv = [str(TOOL), str(archive), str(cache)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self._assert_schema(json.loads(out), selection="cache") + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self._assert_schema(json.loads(stdout.getvalue()), selection="cache") + + +class ComputeContainerIndexCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected non-empty stderr for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected non-empty subprocess stderr for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + + def test_invalid_archive_cache_and_trace_paths_rejected_upfront(self) -> None: + # Kills removal of _validate_inputs() archive/cache/trace and _same_path() guards. + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + archive = root / "archive.bin" + archive.write_bytes(b"") + cache = root / "cache" + cache.mkdir() + regular_file = root / "regular.txt" + regular_file.write_bytes(b"not-a-dir") + missing = root / "missing" + dir_path = root / "some_dir" + dir_path.mkdir() + + cases = ( + ("dir_archive", [str(dir_path), str(cache)], "Archive path is a directory"), + ("missing_archive", [str(missing), str(cache)], "Archive path is not a regular file"), + ("missing_cache", [str(archive), str(missing)], "Cache directory does not exist"), + ("file_cache", [str(archive), str(regular_file)], "Cache path is not a directory"), + ("dir_trace", [str(archive), str(cache), "--trace", str(dir_path)], "Trace path is a directory"), + ("missing_trace", [str(archive), str(cache), "--trace", str(missing)], "Trace path is not a regular file"), + ( + "trace_relative_alias_archive", + [str(archive), str(cache), "--trace", str(sub / ".." / "archive.bin")], + "Trace path collides with archive", + ), + ( + "trace_nonexistent_alias_archive", + [str(root / "ghost.bin"), str(cache), "--trace", str(sub / ".." / "ghost.bin")], + "Trace path collides with archive", + ), + ) + for label, argv, fragment in cases: + with self.subTest(label=label): + with mock.patch.object(compute_container_index, "build_index") as build_mock: + self._assert_clean_failure( + argv, + expected_fragments=("ValueError:", fragment), + check_subprocess=False, + ) + build_mock.assert_not_called() + self._assert_clean_failure(argv, expected_fragments=("ValueError:", fragment)) + + # Hardlink --trace colliding with archive where resolve() differs (kills samefile()). + hardlink_trace = root / "archive_hardlink.log" + os.link(archive, hardlink_trace) + self.assertNotEqual(archive.resolve(), hardlink_trace.resolve()) + self.assertTrue(archive.samefile(hardlink_trace)) + with mock.patch.object(compute_container_index, "build_index") as build_mock: + self._assert_clean_failure( + [str(archive), str(cache), "--trace", str(hardlink_trace)], + expected_fragments=("ValueError:", "Trace path collides with archive"), + check_subprocess=False, + ) + build_mock.assert_not_called() + self._assert_clean_failure( + [str(archive), str(cache), "--trace", str(hardlink_trace)], + expected_fragments=("ValueError:", "Trace path collides with archive"), + ) + + # Direct build_index() call validates inputs too. + with self.assertRaisesRegex(ValueError, "Trace path collides with archive"): + compute_container_index.build_index(archive, cache, hardlink_trace) + + def test_oserror_struct_error_and_zlib_error_guards_in_main(self) -> None: + # Kills removal of OSError, ValueError, struct.error, and zlib.error from except tuple in main(). + with TemporaryDirectory() as tmp: + root = Path(tmp) + archive = root / "empty.bin" + archive.write_bytes(b"") + cache = root / "cache" + cache.mkdir() + argv = [str(archive), str(cache)] + + for exc_obj, expected_type, fragment in ( + (OSError("simulated I/O failure"), "OSError", "simulated I/O failure"), + (ValueError("simulated validation failure"), "ValueError", "simulated validation failure"), + (struct.error("unpack_from requires a buffer of at least 4 bytes"), "error", "unpack_from requires a buffer"), + (zlib.error("Error -3 while decompressing data: incorrect header check"), "error", "Error -3 while decompressing data"), + ): + with self.subTest(exc=expected_type): + with mock.patch.object(compute_container_index, "build_index", side_effect=exc_obj): + self._assert_clean_failure( + argv, + expected_fragments=(f"{expected_type}:", fragment), + check_subprocess=False, + ) + + # Real subprocess OSError when req_.data is a directory. + key_hex = f"{2:016x}" + (cache / f"req_{key_hex}.c67").write_bytes(b"slot67") + (cache / f"req_{key_hex}.data").mkdir() + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip()) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + with TemporaryDirectory() as tmp: + archive = Path(tmp) / "empty.bin" + archive.write_bytes(b"") + for bad_argv in ([], [str(archive)], [str(archive), str(tmp), "--unknown-flag"]): + with self.subTest(argv=bad_argv): + self._assert_clean_failure(bad_argv, expected_code=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/compute_container_index.py b/tools/compute_container_index.py index 882e025de..67c675e54 100644 --- a/tools/compute_container_index.py +++ b/tools/compute_container_index.py @@ -2,12 +2,14 @@ import argparse from collections import Counter, defaultdict +from collections.abc import Sequence import hashlib import json import mmap from pathlib import Path import re import struct +import zlib from resource_inventory import scene_records @@ -36,9 +38,34 @@ def dispatch_counts(trace): return counts +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _validate_inputs(archive: Path, cache: Path, trace: Path | None) -> None: + if archive.is_dir(): + raise ValueError(f"Archive path is a directory: {archive}") + if trace is not None and _same_path(trace, archive): + raise ValueError(f"Trace path collides with archive: {trace}") + if not archive.is_file(): + raise ValueError(f"Archive path is not a regular file: {archive}") + if not cache.exists(): + raise ValueError(f"Cache directory does not exist: {cache}") + if not cache.is_dir(): + raise ValueError(f"Cache path is not a directory: {cache}") + if trace is not None: + if trace.is_dir(): + raise ValueError(f"Trace path is a directory: {trace}") + if not trace.is_file(): + raise ValueError(f"Trace path is not a regular file: {trace}") + + def build_index(archive, cache, trace): + _validate_inputs(archive, cache, trace) observed = dispatch_counts(trace) if trace is not None else None - request_paths = {match[1]: path for path in cache.iterdir() + request_paths = {match[1]: path for path in sorted(cache.iterdir()) if path.is_file() and (match := REQUEST.fullmatch(path.name))} keys = sorted(observed if observed is not None else request_paths) rows = {} @@ -85,8 +112,12 @@ def observe(kind, blob, sections): candidate = candidates[digest].setdefault(sha, {"sha256": sha, "hash_flags": flags, "records": 0}) candidate["records"] += 1 - with archive.open("rb") as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: - inventory = scene_records(data, observe=observe) + with archive.open("rb") as stream: + if stream.seek(0, 2): + with mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: + inventory = scene_records(data, observe=observe) + else: + inventory = scene_records(b"", observe=observe) for key, digest in digests.items(): matches = sorted(candidates[digest].values(), key=lambda candidate: candidate["sha256"]) if not matches: @@ -108,18 +139,20 @@ def observe(kind, blob, sections): } -def main(argv=None): +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archive", type=Path, help="local archive with named shader records") parser.add_argument("cache", type=Path, help="local runtime cache containing req_.c67 and .data files") parser.add_argument("--trace", type=Path, help="select keys from direct and indirect dispatch trace rows") args = parser.parse_args(argv) try: + _validate_inputs(args.archive, args.cache, args.trace) report = build_index(args.archive, args.cache, args.trace) - except (OSError, ValueError) as exc: - parser.error(str(exc)) + except (OSError, ValueError, struct.error, zlib.error) as exc: + parser.exit(1, f"{type(exc).__name__}: {exc}\n") print(json.dumps(report, indent=2, sort_keys=True)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From b13fa36346ebf59303abd4bbdadb783bc54cb086 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro?= <36482489+alvaroolt@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:16:34 +0100 Subject: [PATCH 179/232] gpu: keep one readback queue in the hardware lease fixtures (#2565) The XMem lease fixtures hold a writer queue with pending work behind a CPU-signalled fence while run() clears and reads back the targets. run() created and released a DIRECT queue for each clear and readback copy. On the RTX 5080 (driver 32.0.16.2124), when several of these fixtures run at once, a queue release can block in NtGdiDdDDIDestroyAllocation2 until the test stops at the 60 s timeout. A plain D3D12 program without the runtime shows the same stall, but only when two processes each release a queue during such a hold. Record those clears and copies on one DIRECT queue per device that lives until the process exits. ComputeCommands gains a constructor that uses an existing queue. --- docs/experiments.md | 19 +++++++++++++++++++ tests/desktop_gpu.cpp | 9 +++++++++ tests/desktop_gpu.h | 3 +++ tests/startup_indirect_draw_indexed.cpp | 22 ++++++++++++++++++++-- 4 files changed, 51 insertions(+), 2 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 4bc816298..67556e6de 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9291,6 +9291,25 @@ Both pages are reusable afterward. ctest --preset release --no-tests=error -j1 -R '^startup_indirect_mesh_lease_(warp|hardware)_dual' -V ``` +These fixtures hold a writer queue with pending work behind a CPU-signalled +fence while `run()` clears and reads back the targets. They used to create and +release a DIRECT queue for each clear and readback copy. On Windows 11 build +26300.9974 with an RTX 5080 (32.0.16.2124), running the ten +`startup_indirect_mesh_xmem_arguments*_hardware` and +`startup_indirect_mesh_lease_hardware_*` cases together with `-j 8` left five +of them at the 60 s timeout. The main thread was inside +`NtGdiDdDDIDestroyAllocation2` while it released one of those queues. The +other five passed in under 5 s. A plain D3D12 program reproduced the stall +without the runtime. It needed two processes that both release a queue while +another of their queues waits behind a CPU-signalled fence with a copy pending. +It did not stall when only one process did this, when the held queue had no +pending work, or when the program released a buffer instead of a queue. It also +did not stall on WARP or on the AMD Radeon iGPU (32.0.11034.2). The clears and +copies now share one DIRECT queue per device that lives until the process +exits. With that change, the ten cases passed five consecutive `-j 8` runs. +Whether the stall comes from the NVIDIA driver or from the Windows graphics +kernel was not established. + For a matched local replay, set `X2W_MESH86_WRITER_TRACE=` to select the one-based index of a slot 61 DispatchMesh attempt with a slot 86 cache key on the bound pipeline. Use `X2W_MESH86_XMEM_SRV=1` and diff --git a/tests/desktop_gpu.cpp b/tests/desktop_gpu.cpp index 825253dc5..96b932559 100644 --- a/tests/desktop_gpu.cpp +++ b/tests/desktop_gpu.cpp @@ -69,6 +69,15 @@ ComputeCommands::ComputeCommands(ID3D12Device* device, ID3D12PipelineState* pipe "Create compute command list"); } +ComputeCommands::ComputeCommands(ID3D12Device* device, ID3D12CommandQueue* existing, ID3D12PipelineState* pipeline) + : queue(existing) +{ + const auto type = queue->GetDesc().Type; + check(device->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator)), "Create compute allocator"); + check(device->CreateCommandList(0, type, allocator.Get(), pipeline, IID_PPV_ARGS(&list)), + "Create compute command list"); +} + void ComputeCommands::submit_and_wait(ID3D12Device* device) { check(list->Close(), "Close compute command list"); diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index e01c44fd7..21b325fd0 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -133,6 +133,9 @@ void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* buffer, struct ComputeCommands { ComputeCommands(ID3D12Device* device, ID3D12PipelineState* pipeline, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_COMPUTE); + // Records on a new list for an existing queue of the list's type. Releasing the commands then + // leaves that queue alive. + ComputeCommands(ID3D12Device* device, ID3D12CommandQueue* existing, ID3D12PipelineState* pipeline); void submit_and_wait(ID3D12Device* device); Microsoft::WRL::ComPtr queue; Microsoft::WRL::ComPtr allocator; diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 9fcfa7fb1..c4b91f264 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -497,6 +497,24 @@ void submit(ID3D12Device* device, ID3D12GraphicsCommandList* list) check(device->GetDeviceRemovedReason(), "GPU completion"); } +// The lease fixtures hold a writer queue behind a CPU-signalled gate while run() clears and reads back +// its targets. With NVIDIA driver 32.0.16.2124, releasing a queue during that hold blocks until the test +// times out when another process releases a queue during its own hold. Those clears and copies therefore +// share one DIRECT queue per device that lives until the process exits. +ID3D12CommandQueue* kept_direct_queue(ID3D12Device* device) +{ + static std::mutex lock; + static std::vector>> queues; + const std::lock_guard guard(lock); + for (const auto& [owner, queue] : queues) + if (owner == device) return queue.Get(); + const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + ComPtr queue; + check(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)), "create kept readback queue"); + queues.emplace_back(device, queue); + return queue.Get(); +} + struct MeshLeaseDraw { UINT64 address; IUnknown* queue; @@ -900,7 +918,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ if (leased && leased->before_submit) { // A submission-level refusal skips the entire wrapped list, // including its clear. Initialize the readback target separately. - ComputeCommands clear_targets(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + ComputeCommands clear_targets(device, kept_direct_queue(device), nullptr); for (std::size_t i = 0; i < targets.size(); ++i) { auto* target = targets[i].Get(); transition(clear_targets.list.Get(), target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); @@ -1147,7 +1165,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer_ device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); for (const auto& target : targets) { const auto pixel_readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); - ComputeCommands copy(device, nullptr, D3D12_COMMAND_LIST_TYPE_DIRECT); + ComputeCommands copy(device, kept_direct_queue(device), nullptr); transition(copy.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); D3D12_TEXTURE_COPY_LOCATION source{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; D3D12_TEXTURE_COPY_LOCATION destination{pixel_readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; From 84c271cf67a900ae1516d68f2ee2aa0277f16272 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 23:17:56 +0200 Subject: [PATCH 180/232] runtime: harden atomic JSON writes, path/collision guards, and IO/decode error handling in ps_input_scan with CLI suite (#2564) --- CMakeLists.txt | 2 + tests/startup_ps_input_scan_cli_check.py | 336 +++++++++++++++++++++++ tools/startup/ps_input_scan.py | 57 +++- 3 files changed, 389 insertions(+), 6 deletions(-) create mode 100644 tests/startup_ps_input_scan_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 671409c90..b5451cccc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3396,6 +3396,8 @@ if(EXISTS "${INTAKE_PYTHON}") # The pixel input mask scan finds where a pipeline stores the two masks, from shader register use (#1629). add_test(NAME startup_ps_input_scan COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_check.py") + add_test(NAME startup_ps_input_scan_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_ps_input_scan_cli_check.py") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_packed_screen_position_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_packed_position_check.py" "${DXC_EXECUTABLE}" diff --git a/tests/startup_ps_input_scan_cli_check.py b/tests/startup_ps_input_scan_cli_check.py new file mode 100644 index 000000000..909712570 --- /dev/null +++ b/tests/startup_ps_input_scan_cli_check.py @@ -0,0 +1,336 @@ +"""CLI, atomic JSON output, path/collision guard, error handling, and mutation suite for tools/startup/ps_input_scan.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "startup" / "ps_input_scan.py" +sys.path.insert(0, str(ROOT / "tools" / "startup")) + +import gfx2hlsl as G # noqa: E402 +import ps_input_scan as scanner # noqa: E402 + + +END = 0xBF810000 + + +def _w(*words): + return struct.pack("<%dI" % len(words), *words) + + +def _ps_blob(mask: int) -> bytes: + # Minimal synthetic gfx1013 PS: v_mov_b32 v4, v1; exp mrt0 v4, v4, v4, v4 done vm; s_endpgm + code = _w(0x7E000000 | (4 << 17) | (1 << 9) | (256 + 1), 0xF800180F, 0x04040404, END) + header = _w(2, 1, mask, mask) + return header + G.PREFETCH + code + + +def _populate_pixel_dir(pixel_dir: Path) -> None: + pixel_dir.mkdir(parents=True, exist_ok=True) + for idx, mask in enumerate((0x0002, 0x0003)): + (pixel_dir / f"shader_{idx:02d}.bin").write_bytes(_ps_blob(mask)) + + +def _populate_request_dir(req_dir: Path) -> None: + req_dir.mkdir(parents=True, exist_ok=True) + # Minimal VS blob (prefetch + s_endpgm) + PS blob + vs_blob = G.PREFETCH + _w(END) + ps_blob = _ps_blob(0x0002) + key = "0000000000001000" + (req_dir / f"req_{key}.a").write_bytes(vs_blob) + (req_dir / f"req_{key}.b").write_bytes(ps_blob) + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = scanner.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class PsInputScanCliPositiveTests(unittest.TestCase): + def test_nested_atomic_json_write_list_and_schema(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pixel_dir = root / "pixels" + _populate_pixel_dir(pixel_dir) + json_out = root / "nested" / "reports" / "scan.json" + self.assertFalse(json_out.parent.exists()) + + replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with mock.patch.object(scanner.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([ + "--pixel-dir", str(pixel_dir), + "--json", str(json_out), + "--list", + ]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("pipelines: 2 scanned, 0 skipped", out) + self.assertIn("p000001", out) + self.assertEqual(len(replaces), 1) + self.assertEqual(sorted(p.name for p in json_out.parent.iterdir()), ["scan.json"]) + + payload = json.loads(json_out.read_text(encoding="utf-8")) + self.assertEqual( + set(payload), + { + "pipelines", "skipped", "informative", "distinct_contracts", + "excluded_unsatisfiable", "ambiguous_pipelines", "contracts", + "candidates", "detail_truncated", "verdict", + "top_candidate_pipelines", "footer", + }, + ) + self.assertEqual(payload["pipelines"], 2) + self.assertEqual([c["id"] for c in payload["contracts"]], ["p000001", "p000002"]) + + def test_main_sys_argv_forwarding_and_script_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pixel_dir = root / "pixels" + _populate_pixel_dir(pixel_dir) + json_out = root / "out.json" + cli_argv = [str(TOOL), "--pixel-dir", str(pixel_dir), "--json", str(json_out)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertIn("pipelines: 2 scanned", out) + self.assertTrue(json_out.is_file()) + + json_out.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertIn("pipelines: 2 scanned", stdout.getvalue()) + self.assertTrue(json_out.is_file()) + + +class PsInputScanCliNegativeAndMutationTests(unittest.TestCase): + def _assert_exit_2_clean(self, argv, *, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_json_directory_and_input_collisions_rejected_upfront(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + req_dir = root / "requests" + pixel_dir = root / "pixels" + _populate_request_dir(req_dir) + _populate_pixel_dir(pixel_dir) + cap_file = root / "capture.bin" + cap_bytes = b"CAP_PLACEHOLDER" + cap_file.write_bytes(cap_bytes) + existing_dir = root / "existing_dir" + existing_dir.mkdir() + + # 1) --json is an existing directory (including ""). + for bad_json in (str(existing_dir), ""): + with mock.patch.object(scanner, "run") as run_mock: + self._assert_exit_2_clean( + ["--pixel-dir", str(pixel_dir), "--json", bad_json], + expected_fragment="existing directory", + check_subprocess=bool(bad_json), + ) + run_mock.assert_not_called() + + # 2) --json collides with --capture via resolve() and hardlink samefile(). + self.assertTrue( + scanner._same_path(root / "ghost.json", root / "no_such_dir" / ".." / "ghost.json") + ) + cap_alias = root / "no_such_dir" / ".." / "capture.bin" + cap_link = sub / "cap_link.json" + os.link(cap_file, cap_link) + self.assertNotEqual(cap_file.resolve(), cap_link.resolve()) + self.assertTrue(cap_file.samefile(cap_link)) + for bad_json in (cap_alias, cap_link): + with mock.patch.object(scanner, "run") as run_mock: + self._assert_exit_2_clean( + ["--capture", str(cap_file), "--json", str(bad_json)], + expected_fragment="collides with --capture", + ) + run_mock.assert_not_called() + self.assertEqual(cap_file.read_bytes(), cap_bytes) + + # 3) --json collides with request_dir or --pixel-dir, inside them, or hardlink to file inside them. + req_alias = root / "sub" / ".." / "requests" + pix_alias = root / "sub" / ".." / "pixels" + req_inside = req_dir / "nested" / "out.json" + pix_inside = pixel_dir / "out.json" + req_link = sub / "req_file_link.json" + pix_link = sub / "pix_file_link.json" + os.link(req_dir / "req_0000000000001000.a", req_link) + os.link(pixel_dir / "shader_00.bin", pix_link) + + cases = [ + ([str(req_dir), "--json", str(req_alias)], "collides with request directory"), + ([str(req_dir), "--json", str(req_inside)], "inside request directory"), + ([str(req_dir), "--json", str(req_link)], "collides with file in request directory"), + (["--pixel-dir", str(pixel_dir), "--json", str(pix_alias)], "collides with --pixel-dir"), + (["--pixel-dir", str(pixel_dir), "--json", str(pix_inside)], "inside --pixel-dir"), + (["--pixel-dir", str(pixel_dir), "--json", str(pix_link)], "collides with file in --pixel-dir"), + ] + for argv, frag in cases: + with self.subTest(argv=argv), mock.patch.object(scanner, "run") as run_mock: + self._assert_exit_2_clean(argv, expected_fragment=frag) + run_mock.assert_not_called() + self.assertFalse((req_dir / "nested").exists()) + + def test_os_value_struct_and_zlib_errors_caught_cleanly_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pixel_dir = root / "pixels" + _populate_pixel_dir(pixel_dir) + json_out = root / "never" / "out.json" + + # Corrupt capture file hits ValueError cleanly. + bad_cap = root / "corrupt_capture.bin" + bad_cap.write_bytes(b"TRUNCATED") + self._assert_exit_2_clean( + ["--capture", str(bad_cap), "--json", str(json_out)], + expected_fragment="truncated chunk header", + ) + self.assertFalse(json_out.parent.exists()) + + # Explicit OSError, ValueError, struct.error, zlib.error during run() all exit 2 cleanly. + for exc in ( + OSError("simulated read error"), + ValueError("simulated value error"), + struct.error("simulated struct error"), + zlib.error("simulated zlib error"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(scanner, "run", side_effect=exc): + self._assert_exit_2_clean( + ["--pixel-dir", str(pixel_dir), "--json", str(json_out)], + expected_fragment=str(exc), + check_subprocess=False, + ) + self.assertFalse(json_out.parent.exists()) + + def test_os_replace_and_staging_failures_leave_zero_temp_dirs_and_preserve_prior(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pixel_dir = root / "pixels" + _populate_pixel_dir(pixel_dir) + out_dir = root / "out" + json_out = out_dir / "scan.json" + + def failing_replace(src, dst): + src_path = Path(src) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), Path(dst).parent.resolve()) + raise OSError("simulated replace failure") + + # 1) Fresh --json: os.replace OSError -> exit 2, zero files & zero temp dirs. + with mock.patch.object(scanner.os, "replace", side_effect=failing_replace): + self._assert_exit_2_clean( + ["--pixel-dir", str(pixel_dir), "--json", str(json_out)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), []) + + # 2) Pre-existing --json: os.replace OSError -> prior file intact, zero temp dirs. + json_out.write_text("prior-scan\n", encoding="utf-8") + with mock.patch.object(scanner.os, "replace", side_effect=failing_replace): + self._assert_exit_2_clean( + ["--pixel-dir", str(pixel_dir), "--json", str(json_out)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(json_out.read_text(encoding="utf-8"), "prior-scan\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["scan.json"]) + + # 3) Staging write failure -> os.replace never called, prior file intact, zero temp dirs. + with ( + mock.patch.object(scanner.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated stage failure")), + ): + self._assert_exit_2_clean( + ["--pixel-dir", str(pixel_dir), "--json", str(json_out)], + expected_fragment="simulated stage failure", + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(json_out.read_text(encoding="utf-8"), "prior-scan\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["scan.json"]) + + def test_argparse_and_input_validation_exit_2_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + a_file = root / "not_a_dir.bin" + a_file.write_bytes(b"x") + a_dir = root / "not_a_file" + a_dir.mkdir() + + for bad_argv in ( + [], + [str(a_file)], + ["--pixel-dir", str(a_file)], + ["--capture", str(a_dir)], + ["--pixel-dir", str(a_dir), "--top", "0"], + ["--pixel-dir", str(a_dir), "--region-limit", "4"], + ): + proc = _run_subprocess(*bad_argv) + self.assertEqual(proc.returncode, 2) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("usage:", proc.stderr.lower()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup/ps_input_scan.py b/tools/startup/ps_input_scan.py index d2ff96a44..e788b2ba0 100644 --- a/tools/startup/ps_input_scan.py +++ b/tools/startup/ps_input_scan.py @@ -40,7 +40,10 @@ import re import struct import sys +import tempfile +import zlib from collections import Counter, namedtuple +from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import gfx2hlsl as G # noqa: E402 (also puts tools/ on sys.path) @@ -1004,7 +1007,45 @@ def run(directory, capture_path, pixel_dir, top, limit, listing): return lines, result -def main(argv=None): +def _same_path(left, right): + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _validate_json_path(json_path, request_dir, pixel_dir, capture_path): + json_resolved = json_path.resolve() + if capture_path: + cap_path = Path(capture_path) + if _same_path(json_path, cap_path): + raise ValueError('--json path collides with --capture: %s' % json_path) + if cap_path.resolve() in json_resolved.parents: + raise ValueError('--json path cannot be inside --capture: %s' % json_path) + for label, dir_arg in (('request directory', request_dir), ('--pixel-dir', pixel_dir)): + if dir_arg and _same_path(json_path, Path(dir_arg)): + raise ValueError('--json path collides with %s: %s' % (label, json_path)) + if json_path.exists() and json_path.is_dir(): + raise ValueError('--json path is an existing directory: %s' % json_path) + for label, dir_arg in (('request directory', request_dir), ('--pixel-dir', pixel_dir)): + if not dir_arg: + continue + dir_path = Path(dir_arg) + if dir_path.resolve() in json_resolved.parents: + raise ValueError('--json path cannot be inside %s: %s' % (label, json_path)) + if json_path.exists() and any(_same_path(json_path, child) for child in dir_path.iterdir()): + raise ValueError('--json path collides with file in %s: %s' % (label, json_path)) + + +def _atomic_write_text(path, text): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=path.parent) as staging_dir: + staged = Path(staging_dir) / path.name + staged.write_text(text, encoding='utf-8') + os.replace(staged, path) + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.split('\n')[0]) parser.add_argument('request_dir', nargs='?', help='directory with req_.a/.b/.root files') parser.add_argument('--capture', help='capture.bin whose path-57 PSOs are scanned') @@ -1024,13 +1065,17 @@ def main(argv=None): parser.error('--capture is not a file') if args.top < 1 or args.region_limit < 8: parser.error('--top must be positive and --region-limit at least 8') - lines, result = run(args.request_dir, args.capture, args.pixel_dir, args.top, args.region_limit, args.list) + try: + if args.json is not None: + _validate_json_path(Path(args.json), args.request_dir, args.pixel_dir, args.capture) + lines, result = run(args.request_dir, args.capture, args.pixel_dir, args.top, args.region_limit, args.list) + if args.json is not None: + _atomic_write_text(args.json, json.dumps(result, indent=1)) + except (OSError, ValueError, struct.error, zlib.error) as exc: + parser.error(str(exc)) print('\n'.join(lines)) - if args.json: - with open(args.json, 'w', encoding='utf-8') as file: - json.dump(result, file, indent=1) return 0 if __name__ == '__main__': - sys.exit(main()) + raise SystemExit(main()) From 25054241413e9db4a1335b1cf05a5ab1f7d10d00 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:19:35 +0100 Subject: [PATCH 181/232] tests: start the slowest ctest cases first (#2486) * tests: start the slowest ctest cases first with COST * tests: assert descending order of ctest COST list and note its source --- CMakeLists.txt | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index b5451cccc..7cd534585 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9989,3 +9989,57 @@ if(EXISTS "${INTAKE_PYTHON}") --host $ --backend warp --case ${control}) endforeach() endif() + +# Start the slowest tests first so the ctest worker pool has no long tail at the end. +# COST only changes scheduling order under `ctest --parallel`; no test, argument or assertion changes. +# Costs are measured seconds (approx.) from the Windows CI ctest log taken when this list was added +# (2026-11-25, main at a6c8d80dc); re-measure when the order looks wrong. Keep the list in descending cost order: +# the loop below stops the configure if it is not. Names absent in a configuration are skipped. +set(X2W_SLOW_TEST_COSTS + startup_debug 56 + compute_store_aot_heap_view_store_warp 51 + compute_store_aot_descriptor_load_format_warp 51 + cpu_aot_sse_fp_pd 44 + cpu_aot_x87_fprem 41 + compute_store_aot_heap_view_load_warp 37 + startup_run_ps1 37 + pixel_aot_warp 36 + pixel_aot_bits_warp 36 + startup_gamesave_read_publish_locked 33 + pixel_aot_core_vector_warp 33 + pixel_aot_three_way_warp 33 + form_coverage 33 + startup_vertex_fetch_formats_warp 32 + pixel_aot_buffer_color_warp 31 + sampled_coverage_warp 31 + startup_storage_worker_start 30 + cpu_aot_x87_scale 30 + startup_mrt_fxc_warp 30 + startup_heartbeat_commit 30 + pixel_aot_predicate_rounding_warp 30 + startup_mrt_dxc_warp 28 + cpu_aot_xchg 27 + depth_mask_unary_draw_warp 26 + pixel_aot_comparisons_warp 26) +list(LENGTH X2W_SLOW_TEST_COSTS X2W_SLOW_TEST_COSTS_LEN) +math(EXPR X2W_SLOW_TEST_COSTS_LAST "${X2W_SLOW_TEST_COSTS_LEN} - 1") +math(EXPR X2W_SLOW_TEST_COSTS_ODD "${X2W_SLOW_TEST_COSTS_LEN} % 2") +if(X2W_SLOW_TEST_COSTS_ODD) + message(FATAL_ERROR "X2W_SLOW_TEST_COSTS must hold name/cost pairs") +endif() +set(X2W_SLOW_TEST_PREV_COST "") +foreach(i RANGE 0 ${X2W_SLOW_TEST_COSTS_LAST} 2) + math(EXPR j "${i} + 1") + list(GET X2W_SLOW_TEST_COSTS ${i} slow_name) + list(GET X2W_SLOW_TEST_COSTS ${j} slow_cost) + if(NOT slow_cost MATCHES "^[0-9]+$") + message(FATAL_ERROR "X2W_SLOW_TEST_COSTS: cost of ${slow_name} is not an integer: ${slow_cost}") + endif() + if(NOT X2W_SLOW_TEST_PREV_COST STREQUAL "" AND slow_cost GREATER X2W_SLOW_TEST_PREV_COST) + message(FATAL_ERROR "X2W_SLOW_TEST_COSTS must be in descending cost order: ${slow_name} (${slow_cost}) follows ${X2W_SLOW_TEST_PREV_COST}") + endif() + set(X2W_SLOW_TEST_PREV_COST ${slow_cost}) + if(TEST ${slow_name}) + set_tests_properties(${slow_name} PROPERTIES COST ${slow_cost}) + endif() +endforeach() From 6c7a59a28896263896e873bab997c6977aa96eb7 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:23:20 +0100 Subject: [PATCH 182/232] startup: translate VOP3 NEG on an inline-integer or literal float source (follow-up to #2529) (#2563) * startup: translate VOP3 NEG on an inline-integer or literal float source The refusal added for NEG on an inline-integer or literal VOP3 source (Part of #1723) covered every slot. For a float-typed source slot of the f32 ALU table (VEC_F) and of v_cmp(x)_*_f32 (src0 only for the class compares), translate NEG with the model LLVM's assembler uses when it folds neg into an immediate: bit 31 of the 32-bit source word flipped (inline 1 -> 0x80000001, literal 0x5 -> 0x80000005, inline 0 -> 0x80000000). The word is taken from the encoding, not from the printed text, and emitted as an exact bit pattern. RDNA hardware behaviour for these sources is not measured; the WARP and NVIDIA readback only checks the HLSL against this model. Integer-typed slots, the class mask slot, NEG with ABS on the same source, and everything refused for another reason stay refused. Tests: startup_gfx2hlsl_neg_check.py checks the emitted words for v_fma_f32, v_mul_f32 and v_med3_f32 with NEG on inline 0, 1 and 64 and a literal, and in dispatch mode reads them back on WARP and hardware against a CPU reference (the two subnormal v_mul results may flush to signed zero). startup_gfx2hlsl_refusals_check.py now expects float slots to translate and integer slots, the class mask slot and NEG with ABS to refuse. AI-assisted. # Conflicts: # CMakeLists.txt # Please enter the commit message for your changes. Lines starting # with '#' will be kept; you may remove them yourself if you want to. # An empty message aborts the commit. # # interactive rebase in progress; onto 9bef64ee # Last command done (1 command done): # pick 19a8c3aa # startup: translate VOP3 NEG on an inline-integer or literal float source # No commands remaining. # You are currently rebasing branch 'vop3-neg-inline' on '9bef64ee'. # # Changes to be committed: # modified: .github/workflows/windows.yml # modified: AGENTS.md # modified: CMakeLists.txt # modified: docs/experiments.md # new file: tests/startup_gfx2hlsl_neg_check.py # modified: tests/startup_gfx2hlsl_refusals_check.py # modified: tools/startup/gfx2hlsl.py # * build: restore the endforeach of the v_fma_mix dispatch tests Resolving the rebase onto main dropped the endforeach() that closes the startup_gfx2hlsl_fma_mix_dispatch loop, so the CMake configure failed. The neg tests now follow the closed loop. AI-assisted. --- .github/workflows/windows.yml | 1 + AGENTS.md | 1 + CMakeLists.txt | 8 ++ docs/experiments.md | 4 +- tests/startup_gfx2hlsl_neg_check.py | 114 +++++++++++++++++++++++ tests/startup_gfx2hlsl_refusals_check.py | 83 ++++++++++++----- tools/startup/gfx2hlsl.py | 40 ++++++-- 7 files changed, 222 insertions(+), 29 deletions(-) create mode 100644 tests/startup_gfx2hlsl_neg_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 924cd1483..6c465262b 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -271,6 +271,7 @@ jobs: tests/startup_gfx2hlsl_interp_f16_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ tests/startup_gfx2hlsl_mad_check.py \ + tests/startup_gfx2hlsl_neg_check.py \ tests/startup_gfx2hlsl_compute_check.py \ tests/startup_compute_lds_b64_check.py \ tests/startup_compute_lds_b128_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 28e2f1cb5..c2cea0b61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -165,6 +165,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_table_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_neg_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7cd534585..6d65b2536 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3527,6 +3527,14 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_fma_mix_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + add_test(NAME startup_gfx2hlsl_neg_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_neg_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_neg_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_neg_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_neg_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 67556e6de..8ecdccb2a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -13977,7 +13977,9 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_cmp16_' -V python -B tests/startup_gfx2hlsl_cmp16_check.py binary ``` -`tools/startup/gfx2hlsl.py` also refuses the NEG bit of a VOP3 source that is a non-negative inline integer (0 to 64) or a literal. The disassembler prints inline 1 with NEG as `-1`, the same text as inline -1, so the text cannot tell the two encodings apart. The exception is the two data operands of `v_cndmask_b32_e64`, which model NEG as a flip of bit 31. The hardware behavior of NEG on integer sources is not measured. Check: `tests/startup_gfx2hlsl_refusals_check.py`. +`tools/startup/gfx2hlsl.py` refuses VOP3 NEG on a non-negative inline integer (0 to 64) or a literal in integer and unclassified source slots. The disassembler prints inline 1 with NEG as `-1`, the same text as inline -1, so the text cannot tell the two encodings apart. The two data operands of `v_cndmask_b32_e64` model NEG as a flip of bit 31. `tests/startup_gfx2hlsl_refusals_check.py` covers these rules. + +For binary32 arithmetic and compare sources, the translator reads the inline integer (0 to 64) or literal dword from the VOP3 encoding, flips bit 31, and emits `F(0x........u)` using the existing `asfloat` macro. This follows LLVM AMDGPUAsmParser's immediate sign XOR and the RDNA 2 ISA's description of NEG as a float input modifier. The class mask and immediate ABS combined with NEG still refuse. RDNA hardware behavior for these immediate sources has not been measured. The D3D12 readback in `tests/startup_gfx2hlsl_neg_check.py` checks normal FMA and MED3 results, signed zero and normal MUL results, and allows signed flush-to-zero for subnormal MUL results. ## Startup translator: explicit-LOD image sampling diff --git a/tests/startup_gfx2hlsl_neg_check.py b/tests/startup_gfx2hlsl_neg_check.py new file mode 100644 index 000000000..8ef9e4408 --- /dev/null +++ b/tests/startup_gfx2hlsl_neg_check.py @@ -0,0 +1,114 @@ +"""Translate encoded binary32 VOP3 NEG fixtures and optionally dispatch them on D3D12.""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +from startup_flat_param_check import root_blob +from startup_gfx2hlsl_bit_alu_check import G, POST_WORDS, PRE_WORDS, vs_words +from startup_gfx2hlsl_refusals_check import vop3 + +SIGN = 0x80000000 +ONE = 0x3f800000 +MIN_NORMAL = 0x00800000 +# (encoded selector, optional literal dword) +IMMEDIATES = ((128, None), (129, None), (192, None), (255, 0x40a00000)) +# (encoded opcode, arity, runtime src1, runtime src2, scalar reference) +OPS = { + 'v_fma_f32': (0x14b, 3, ONE, SIGN | ONE, lambda a, b, c: a * b + c), + 'v_mul_f32': (0x108, 2, ONE, 0, lambda a, b, c: a * b), + 'v_med3_f32': (0x157, 3, SIGN | ONE, 0xc0000000, lambda a, b, c: sorted((a, b, c))[1]), +} + + +def float_value(word): + return struct.unpack(' ]') diff --git a/tests/startup_gfx2hlsl_refusals_check.py b/tests/startup_gfx2hlsl_refusals_check.py index f2f22d966..a596aa4a3 100644 --- a/tests/startup_gfx2hlsl_refusals_check.py +++ b/tests/startup_gfx2hlsl_refusals_check.py @@ -114,30 +114,45 @@ def check_neg_integer_sources(): cndmask = 0x101 accepted = [op for op in range(0x400) if not isinstance(translate_one(vop3(op, sentinels)), str)] check('the sweep reaches the accepted VOP3 opcodes', len(accepted) > 100 and cndmask in accepted) - loose = [] + mismatches = [] for op in accepted: for slot in range(3): - srcs = list(sentinels) - srcs[slot] = inline(1) - plain = translate_one(vop3(op, srcs)) - result = translate_one(vop3(op, srcs, neg=1 << slot)) - modeled = op == cndmask and slot < 2 - if isinstance(plain, str) or modeled: - continue - # Ops with their own, earlier refusal of NEG and ABS (the 16-bit compares, v_sad_*) keep it. - if not (isinstance(result, str) and ('NEG on an integer or literal source %d' % slot in result - or ' with neg/abs' in result)): - loose.append((hex(op), slot, result)) - check('NEG on inline 1 is refused for every accepted opcode and slot except v_cndmask_b32_e64 data sources', - not loose) - if loose: - print(' first misses: %s' % loose[:4]) + for source, literal, expected in ((inline(1), None, '0x80000001'), (255, 5, '0x80000005')): + srcs = list(sentinels) + srcs[slot] = source + code = vop3(op, srcs, literal=literal) + if literal is not None and G.D.decode_instruction(code, 0)[0] != len(code): + # An unused source field does not consume a literal dword. + continue + plain = translate_one(code) + if isinstance(plain, str) or (op == cndmask and slot < 2): + continue + result = translate_one(vop3(op, srcs, neg=1 << slot, literal=literal)) + name = plain[0].split()[0].removesuffix('_e64') + compare = name.startswith(('v_cmp_', 'v_cmpx_')) and name.endswith('_f32') + float_slot = (name in G.VEC_F and slot < G.VEC_F[name][0] + or compare and slot < (1 if '_class_' in name else 2)) + if float_slot: + # Always/never compares consume no source in the emitted predicate. + constant_compare = name.split('_')[-2] in ('t', 'f') + ok = (not isinstance(result, str) and expected in result[0] + and (constant_compare or expected + 'u' in ' '.join(result[1]))) + else: + # Dedicated encoding refusals run before the general NEG check. + ok = (isinstance(result, str) and ('NEG on an integer or literal source %d' % slot in result + or ' with neg/abs' in result)) + if not ok: + mismatches.append((hex(op), slot, expected, result)) + check('VOP3 NEG on inline 1 and a literal follows the source type in every lowerable slot', not mismatches) + if mismatches: + print(' first misses: %s' % mismatches[:4]) def refused(code, slot): text = translate_one(code) return isinstance(text, str) and 'NEG on an integer or literal source %d' % slot in text - iadd, fadd, cmp_lt, add_co, shl64 = names['v_mad_u32_u24'], 0x103, 0x81, names['v_add_co_u32'], names['v_lshlrev_b64'] + iadd, fadd, add_co, shl64 = names['v_mad_u32_u24'], 0x103, names['v_add_co_u32'], names['v_lshlrev_b64'] + cmp_lt = next(op for op, entry in G.D.VOPC_OPS.items() if entry[0] == 'v_cmp_lt_f32_e32') for slot in range(3): srcs = list(sentinels) srcs[slot] = inline(1) @@ -150,10 +165,36 @@ def refused(code, slot): check('literal with NEG refused', refused(vop3(iadd, [255, sentinels[1], sentinels[2]], neg=1, literal=5), 0)) check('literal without NEG translates', not isinstance( translate_one(vop3(iadd, [255, sentinels[1], sentinels[2]], literal=5)), str)) - check('v_add_f32_e64 with an integer inline and NEG refused', refused(vop3(fadd, [inline(1), v(12), 0], neg=1), 0)) - check('compare with inline 1 and NEG refused', refused(vop3(cmp_lt, [inline(1), v(12), 0], sdst=4, neg=1), 0)) - check('compare slot 1 with literal and NEG refused', refused( - vop3(cmp_lt, [v(10), 255, 0], sdst=4, neg=2, literal=7), 1)) + def exact(code, word): + result = translate_one(code) + return not isinstance(result, str) and 'F(0x%08xu)' % word in ' '.join(result[1]) + + check('v_add_f32_e64 inline 0 with NEG is negative zero', + exact(vop3(fadd, [inline(0), v(12), 0], neg=1), 0x80000000)) + check('v_add_f32_e64 inline 64 with NEG stays subnormal', + exact(vop3(fadd, [inline(64), v(12), 0], neg=1), 0x80000040)) + check('v_add_f32_e64 NEG flips the sign of an encoded NaN payload', + exact(vop3(fadd, [255, v(12), 0], neg=1, literal=0xffc12345), 0x7fc12345)) + check('v_add_f32_e64 immediate ABS with NEG is refused', + refused(vop3(fadd, [inline(1), v(12), 0], absolute=1, neg=1), 0)) + word0, word1 = struct.unpack('<2I', vop3(fadd, [v(10), inline(1), 0], neg=2)) + # The rewritten final operand must keep both supported and refused output modifiers. + clamp = translate_one(struct.pack('<2I', word0 | (1 << 15), word1)) + check('rewriting the last source preserves clamp', + not isinstance(clamp, str) and 'saturate(F(v10) + F(0x80000001u))' in ' '.join(clamp[1])) + op_sel = translate_one(struct.pack('<2I', word0 | (1 << 11), word1)) + check('rewriting the last source preserves the op_sel refusal', + isinstance(op_sel, str) and 'modifier op_sel' in op_sel) + check('float compare slot 0 with inline 1 and NEG reads its word', + exact(vop3(cmp_lt, [inline(1), v(12), 0], neg=1), 0x80000001)) + check('float compare slot 1 with literal and NEG reads its word', + exact(vop3(cmp_lt, [v(10), 255, 0], neg=2, literal=7), 0x80000007)) + check('class compare slot 0 with literal and NEG reads its word', + exact(vop3(0x88, [255, inline(1), 0], neg=1, literal=7), 0x80000007)) + check('class compare slot 1 with literal and NEG is refused', + refused(vop3(0x88, [v(10), 255, 0], neg=2, literal=7), 1)) + check('integer compare slot 0 with inline and NEG is refused', + refused(vop3(0x81, [inline(1), v(12), 0], neg=1), 0)) check('v_add_co_u32 (carry out) with inline 1 and NEG refused', refused(vop3(add_co, [inline(1), v(12), 0], sdst=4, neg=1), 0)) check('v_lshlrev_b64 with NEG on the shift inline refused', refused(vop3(shl64, [inline(1), v(12), 0], neg=1), 0)) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 17126c7ff..3359788bc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -411,19 +411,45 @@ def check_encoding(code, off, n, name, asm): fields[i + 1] = operand[:len(operand) - len(operand.lstrip())] + '0x%08x' % (bits ^ 0x80000000) asm = ','.join(fields) if n >= 8 and struct.unpack_from('> 26 == 0b110101: - # VOP3 NEG (w1[31:29], bit 29 + i for source i) on a non-negative inline integer (128..192) or a literal (255). - # The decoder prints inline 1 with NEG as `-1`, the text of the plain inline -1 (193), so both would translate to - # 0xffffffff, and a literal 5 would become 0xfffffffb. Only v_cndmask_b32_e64 models NEG on its two data - # sources (above, as the sign bit flipped). Inline floats, registers and negative inlines are not affected. - # ABS is not tested: on the VOP3b forms w0[10:8] is SDST, not a modifier. - word1, = struct.unpack_from('> (9 * i)) & 0x1ff - if 128 <= source <= 192 or source == 255: + if not (128 <= source <= 192 or source == 255): + continue + # The selected float forms are VOP3A, where w0[10:8] holds ABS. Keep the + # refusal for NEG combined with ABS on this source. + if i >= float_sources or word0 & (1 << (8 + i)): raise Unsupported('%s with NEG on an integer or literal source %d: the printed sign would read as inline -N' % (name, i)) + if source == 255: + if n != 12 or off + n > len(code): + raise Unsupported('%s missing literal dword' % name) + bits, = struct.unpack_from(' Date: Wed, 25 Nov 2026 21:25:08 +0000 Subject: [PATCH 183/232] gfx2hlsl: accept float neg/abs sources on pixel-stage DPP quad swaps (Part of #1723) (#2559) * gfx2hlsl: accept float neg/abs sources on pixel-stage DPP quad swaps (Part of #1723) * tests: verify DPP float source modifiers by exact pixel readback --------- Co-authored-by: Royoo <3230853833@qq.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 1 + docs/experiments.md | 2 +- tests/startup_gfx2hlsl_dpp_quad_swap_check.py | 56 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 32 +++++++++-- 4 files changed, 85 insertions(+), 6 deletions(-) diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6c465262b..857039d2b 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -117,6 +117,7 @@ jobs: (["tests/startup_gfx2hlsl_calculated_target_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_join_symbols_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_swap_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_dpp_quad_swap_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_shift64_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mul_mad_i24_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cube_check.py", "binary", "llvm-mc-15"], {}), diff --git a/docs/experiments.md b/docs/experiments.md index 8ecdccb2a..aaab16458 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14367,7 +14367,7 @@ lane masks and the discard destination. Run `tools/startup/gfx2hlsl.py` lowers the gfx1013 binary16 interpolation pair `v_interp_p1ll_f16` / `v_interp_p2_f16` (#1996, item C). The attribute channel holds two binary16 values that the vertex stage exports with `compr`; half `h` of channel `c` is float channel `2 * c + h` of the parameter, and the pair becomes `(vD & 0xffff0000u) | f32tof16(i.paramN.)`, with the upper half of the destination kept. Only the plain form and `high` are lowered: `clamp`, an output modifier, a source modifier, a `p2` whose third source is not the matching `p1ll` result, and an attribute that the vertex stage does not export are refused. A vertex stage that packs the halves into a plain 32-bit export (no `compr`, e.g. with `v_cvt_pkrtz_f16_f32`) is lowered too, for all four channels: half `h` of channel `c` is `f16tof32(word_c >> 16 * h)`, carried by the extra interpolated outputs `hparamN_lo` and `hparamN_hi` that exist only when the pixel stage reads the attribute this way. An attribute exported both with `compr` and plain, and a read of a channel the plain export leaves `off`, are refused; the compr export still fills only `x` and `y`. `tests/startup_gfx2hlsl_interp_f16_check.py` evaluates the translated text on the CPU against a reference from the ISA layout and fails when the lowering is removed or the `high` bit is inverted; `binary ` reassembles the fixtures and `draw` is the desktop readback (tests `startup_gfx2hlsl_interp_f16_controls`, `_warp` and `_hardware`). The `op_sel` bits (word 0 bits 11 to 14, each refused on its own) and any read of the upper 16 bits of a `p2` destination stay refused because no source states them for gfx10. Either of two kinds of evidence would lift the refusals: a source that states the gfx10 behaviour of the high 16 bits of the `v_interp_p2_f16` destination and of `op_sel` (kept, cleared or written), or a hardware draw on RDNA that reads back both halves of a `p2` result for each `op_sel` value and compares them with the lowering. -The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands; vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks, source modifiers and operations without a table entry are refused. `fi:1` (fetch inactive) is accepted under the same whole-quad proof, where no source lane is disabled, and gives the same translation. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. +The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands. A binary32 source may carry the `neg`/`abs` modifier (`-vN`, `|vN|`, `-|vN|`): the permuted word is read from the neighbour first and the modifier applies to that value (RDNA 2 ISA 12.19, LLVM 15 prints them on the `_dpp` spelling), while integer sources, SGPR sources and every other modifier stay refused. Vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks and operations without a table entry are refused. `fi:1` (fetch inactive) is accepted under the same whole-quad proof, where no source lane is disabled, and gives the same translation. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. `startup_gfx2hlsl_dpp_quad_swap_controls` checks `-v0` and `|v0|` against the emitted `QuadReadAcrossX` text and keeps an integer `-v0` refused; the draw mode also checks all 256 pixels of a binary32 multiply-by-one fixture. Its three channels use NEG, ABS and NEG+ABS on different neighbours, and each dropped modifier produces a mismatch. The binary mode reassembles the modified DPP source words. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) The startup pixel stage lowers constant-lane SGPR spills (#2125 item E): `v_writelane_b32 vN, sM, k` followed by `v_readlane_b32 sD, vN, k` with an inline constant lane `k` (0..31) becomes one scalar slot per (VGPR, lane), written and read back as plain assignments. Both instructions ignore EXEC and touch only lane `k`, so with a constant `k` and a VGPR that no other instruction names, no cross-lane read exists to model. Refused, each with a reason: a lane chosen by an SGPR, lanes outside 0..31, a VGPR that any other instruction also names (vector use or register range), a read of a slot nothing wrote, branches (write-before-read needs straight-line order), a lane mask, `m0` or modifier on the value, a destination that is not a plain SGPR, and vertex stages. A constant value reloads as a constant. `tests/startup_gfx2hlsl_sgpr_spill_check.py` builds a pixel program with four slots in three VGPRs, clobbers the source SGPRs, reloads them (one slot after a second write) and ORs each word into the packed screen position; it draws 16 x 16 pixels and compares every word with an integer reference computed from the slot rule. Four wrong lowerings (overwrite ignored, lane 31 read as lane 0, a second VGPR read as the first, no reload) must read a different image. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_sgpr_spill_' -V`. The Python controls and the `binary` assembler check run on Linux; the draws need DXC and `offscreen_check` on Windows. diff --git a/tests/startup_gfx2hlsl_dpp_quad_swap_check.py b/tests/startup_gfx2hlsl_dpp_quad_swap_check.py index a156b757c..8a58318c5 100644 --- a/tests/startup_gfx2hlsl_dpp_quad_swap_check.py +++ b/tests/startup_gfx2hlsl_dpp_quad_swap_check.py @@ -119,6 +119,33 @@ def fixture(name, wqm=True): return text + EXPORT_TEXT, words + EXPORT +def modified_fixture(modifiers=(1 << 20, 1 << 21, 3 << 20)): + """Read a different negative normal in each lane, then multiply the modified source by 1.""" + text = WQM_TEXT + 'v_mov_b32_e32 v9, -2.0\nv_mov_b32_e32 v11, 1.0\nv_or_b32_e32 v10, v0, v9\n' + words = WQM + struct.pack('<2I', 0x7e000000 | 9 << 17 | 1 << 9 | 245, + 0x7e000000 | 11 << 17 | 1 << 9 | 242) + words += vop2_plain(V_OR, 10, 0, 9) + for i, (perm, mode) in enumerate(zip(SWAPS, modifiers), 1): + source = {0: 'v10', 1 << 20: '-v10', 1 << 21: '|v10|', 3 << 20: '-|v10|'}[mode] + text += dpp_text('v_mul_f32_dpp', 'v%d, %s, v11' % (i, source), perm) + '\n' + low, high = struct.unpack('<2I', vop2_dpp(0x08, i, 10, 11, perm)) + words += struct.pack('<2I', low, high | mode) + text += 'v_mov_b32_e32 v4, v10\n' + words += struct.pack(' Date: Thu, 26 Nov 2026 00:27:49 +0300 Subject: [PATCH 184/232] shader: lower RDNA2 dual/st64 LDS ops and 32-bit LDS atomics in gfx2hlsl (#2556) * gfx2hlsl: lower dual-offset/st64 32-bit LDS ops and 32-bit LDS atomics (#1541, #2274) * tests: match merged lds_byte_offsets 16-bit offset refusal (#2404) --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 17 + docs/experiments.md | 20 + .../startup_compute_lds_dual_atomics_check.py | 794 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 158 ++++ 5 files changed, 991 insertions(+) create mode 100644 tests/startup_compute_lds_dual_atomics_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 857039d2b..73c7fbadc 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -137,6 +137,7 @@ jobs: (["tests/compute_entry_layout_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_ngg_slice_check.py", "binary", "llvm-mc-15"], {}), (["tests/compute_dpp_row_shr_check.py", *COMMON_LLVM], {}), + (["tests/startup_compute_lds_dual_atomics_check.py", "binary", "llvm-mc-15"], {}), ] sys.exit(runpy.run_path("tools/run_checks_parallel.py", run_name="run_checks_parallel")["run_checks"](CHECKS)) @@ -314,6 +315,7 @@ jobs: tests/startup_gfx2hlsl_handler_arity_check.py \ tests/startup_gfx2hlsl_getpc_refusal_check.py \ tests/startup_gfx2hlsl_image_arity_check.py \ + tests/startup_compute_lds_dual_atomics_check.py \ tests/run_checks_parallel_check.py build-and-test: name: Build and test on Windows diff --git a/CMakeLists.txt b/CMakeLists.txt index 6d65b2536..3392bd50f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3621,6 +3621,23 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_mul_mad_i24_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl dual-offset/stride-64 32-bit LDS ops and 32-bit LDS atomics (Refs #1541, #2274). + add_test(NAME startup_compute_lds_dual_atomics_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_dual_atomics_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_lds_dual_atomics_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_dual_atomics_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_lds_dual_atomics_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS d-wrong-st64-stride d-drop-oob-zero d-drop-align d-drop-exec d-alias-overwrite + a-swap-minmax a-drop-exec a-drop-wrxchg-rtn a-oob-nonzero r-drop-add-rtn) + add_test(NAME startup_compute_lds_dual_atomics_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_dual_atomics_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_lds_dual_atomics_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # XG slots 2 and 8 for a texture given the 4 KiB allocation answer (src/startup_stubs/small_texture_4k.h): # the copy must stay in front of a guard page; the mutated run is not limited and must fail. add_test(NAME startup_small_texture_4k_xg COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index aaab16458..fd009c4d2 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15385,6 +15385,26 @@ is 0, so bit 0 of the result is 0 (1 for `s_orn2_b64`) whatever S holds. This re a lane whose exec bit is 0 takes the branch; it is pure Python only, not run on a GPU, and its words are built from the field layouts rather than assembled. +## Startup compute dual-offset/stride-64 LDS ops and 32-bit LDS atomics + +[`tools/startup/gfx2hlsl.py`](../tools/startup/gfx2hlsl.py) (`lds_dual`, `lds_atomic`, `_lds_general_barrier_ok`, refs `#1541`, `#2274`) lowers the remaining 32-bit RDNA 2 DS dual-offset/stride-64 and unsigned/bitwise atomic instructions onto `groupshared uint lds[N]` (`COMPUTE_PGM_RSRC2.GRANULATED_LDS_SIZE`, nonzero and `<= 32 KiB` / 8192 dwords): + +- **Dual-offset & stride-64 32-bit LDS ops**: `ds_write2_b32` (`0x0e`, `offset0 * 4`, `offset1 * 4`), `ds_write2st64_b32` (`0x0f`, `offset0 * 256`, `offset1 * 256`), and `ds_read2st64_b32` (`0x38`, `offset0 * 256`, `offset1 * 256`). Validation reuses `_lds_single`, `_lds_pair`, and `lds_byte_offsets('ds_read2_b32', mods)` (8-bit unsigned offsets `0..255`, distinct `offset0 != offset1` refusing dual aliasing, and rejecting `gds`/unknown modifiers). +- **32-bit unsigned/bitwise LDS atomics**: non-returning `ds_add_u32` (`0x00`), `ds_min_u32` (`0x07`), `ds_max_u32` (`0x08`), `ds_and_b32` (`0x09`), `ds_or_b32` (`0x0a`), and pre-op returning `ds_add_rtn_u32` (`0x20`), `ds_min_rtn_u32` (`0x27`), `ds_max_rtn_u32` (`0x28`), `ds_and_rtn_b32` (`0x29`), `ds_or_rtn_b32` (`0x2a`), and `ds_wrxchg_rtn_b32` (`0x2d`), lowered via HLSL `InterlockedAdd`/`Min`/`Max`/`And`/`Or`/`Exchange`. Single-offset validation reuses `lds_byte_offsets('ds_write_b32', mods)` with `0 <= offset <= 0xffff` and 4-byte immediate alignment. +- **Runtime bounds, alignment, aliasing, EXEC and encoding guards**: `check_encoding` refuses reserved DS `w0` bit 16 and nonzero unused `w1` operand fields (`vdst`/`data0`/`data1`); every access snapshots `a = ;`, enforces `((a & 3u) == 0u) && a < lds_bytes - off_bytes` (no 32-bit wraparound; OOB/misaligned writes and atomics are no-ops while reads and `_rtn` destinations yield `0u`), guards writes, reads, and atomics under `(exec & 1)` when `EXEC` is not entry-full (preserving inactive lanes' `vdst`), and emits `GroupMemoryBarrierWithGroupSync()` for straight-line `s_barrier` in dual/atomic compute shaders while keeping legacy `check_lds_exchange` programs and non-compute stages unchanged. + +[`tests/startup_compute_lds_dual_atomics_check.py`](../tests/startup_compute_lds_dual_atomics_check.py) verifies decoding and HLSL lowering for all 14 opcodes, `LDS_SIZE` boundaries (`0`, `1`, `64`, `65`), aliasing/GDS/reserved-bit/unused-field/alignment/branch-barrier/arity/stage refusals, and dispatches three source-built `gfx1013` compute programs on D3D12 (`cs_6_0`, `-Gis -WX`, `debug_layer=enabled`): `D` (`[numthreads(64,1,1)]`, `groups=(1,1,1)`, `LDS_SIZE=4`, exercising `ds_write2_b32`, `ds_write2st64_b32`, `ds_read2st64_b32`, `v[14:15], v14` aliasing, EXEC-masked write + static OOB `offset1:8`, misaligned write no-op, and dynamic OOB read returning `0`), `A` (`[numthreads(64,1,1)]`, `groups=(2,1,1)`, `LDS_SIZE=1`, 128 contended threads exercising `ds_add_u32`, `ds_add_rtn_u32`, `ds_min_u32`, `ds_max_u32`, `ds_or_b32`, `ds_and_b32`, `ds_wrxchg_rtn_b32`, bijective 64/64 ticket proof, deterministic `wrxchg` conservation sum, EXEC-masked atomics + inactive `vdst` preservation, and runtime OOB/misaligned `_rtn -> 0`), and `R` (`[numthreads(32,1,1)]`, `groups=(1,1,1)`, `LDS_SIZE=2`, deterministic pre/post verification of all six `_rtn` atomics including `vdst == vaddr`, `vdst == vdata`, and triple aliasing). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`), all three dispatches matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`) and all ten shader mutant controls (`d-wrong-st64-stride`, `d-drop-oob-zero`, `d-drop-align`, `d-drop-exec`, `d-alias-overwrite`, `a-swap-minmax`, `a-drop-exec`, `a-drop-wrxchg-rtn`, `a-oob-nonzero`, `r-drop-add-rtn`) rejected cleanly with `debug_errors=0 debug_warnings=0`. + +```powershell +. .\tools\dev.ps1 +cmake -S . -B build-lds-atomics -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=cl +cmake --build build-lds-atomics --target offscreen_check +ctest --test-dir build-lds-atomics --no-tests=error -j 1 -R '^startup_compute_lds_dual_atomics' -V +python -B tests/startup_compute_lds_dual_atomics_check.py binary llvm-mc-15 +``` + +Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), signed 32-bit (`ds_min_i32`/`ds_max_i32`), `ds_xor_b32`, `ds_sub_u32`/`ds_rsub_u32`, float LDS atomics, and 64-bit LDS dual/atomic forms. + ## Startup translator: a short operand list is refused, never a translator crash The batch translator records any non-`Unsupported` exception from a handler as diff --git a/tests/startup_compute_lds_dual_atomics_check.py b/tests/startup_compute_lds_dual_atomics_check.py new file mode 100644 index 000000000..17b4fdd1f --- /dev/null +++ b/tests/startup_compute_lds_dual_atomics_check.py @@ -0,0 +1,794 @@ +#!/usr/bin/env python3 +"""Verify dual-offset/stride-64 32-bit LDS ops and 32-bit LDS atomics in tools/startup/gfx2hlsl.py (Refs #1541, #2274). + +Covers: + - Dual-offset & stride-64 32-bit LDS ops: ds_write2_b32 (* 4), ds_write2st64_b32 (* 256), ds_read2st64_b32 (* 256) + - 32-bit unsigned/bitwise LDS atomics (non-rtn & _rtn): ds_add_u32, ds_add_rtn_u32, ds_min_u32, ds_min_rtn_u32, + ds_max_u32, ds_max_rtn_u32, ds_and_b32, ds_and_rtn_b32, ds_or_b32, ds_or_rtn_b32, ds_wrxchg_rtn_b32 + +Modes: + (no arguments) pure-Python unit, encoding, HLSL and refusal controls + binary reassemble every fixture and snippet with llvm-mc (gfx1013) + dispatch compile DXC cs_6_0, dispatch and verify GPU readback + control verify mutated shader/reference control rejects at pinned word +""" + +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_compute_check import MASK, SENTINEL, TGID_X, USER7, WORDS, patch, refused, root_blob # noqa: E402 + + +def le32(w): + return (w & MASK).to_bytes(4, 'little') + + +def sop2(op, sdst, ssrc0, ssrc1): + return le32(0x80000000 | ((op & 0x7f) << 23) | ((sdst & 0x7f) << 16) | ((ssrc1 & 0xff) << 8) | (ssrc0 & 0xff)) + + +def sop1(op, sdst, ssrc0): + return le32(0xbe800000 | ((sdst & 0x7f) << 16) | ((op & 0xff) << 8) | (ssrc0 & 0xff)) + + +def sopp(op, simm=0): + return le32(0xbf800000 | ((op & 0x7f) << 16) | (simm & 0xffff)) + + +def vop1(op, vdst, src0, lit=None): + b = le32(0x7e000000 | ((vdst & 0xff) << 17) | ((op & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def v_mov_imm(vdst, val): + if 0 <= val <= 64: + return vop1(0x01, vdst, 0x80 + val) + if -16 <= val <= -1: + return vop1(0x01, vdst, 0xc0 - val) + return vop1(0x01, vdst, 0xff, val) + + +def vop2(op, vdst, src0, vsrc1, lit=None): + b = le32(((op & 0x3f) << 25) | ((vdst & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def vopc(op, src0, vsrc1, lit=None): + b = le32(0x7c000000 | ((op & 0xff) << 17) | ((vsrc1 & 0xff) << 9) | (src0 & 0x1ff)) + return b if lit is None else b + le32(lit) + + +def mubuf_store(op, vdata, vaddr, srsrc=16, soffset_enc=0x80, offset=0): + w0 = 0xe0001000 | ((op & 0x7f) << 18) | (offset & 0xfff) + w1 = ((soffset_enc & 0xff) << 24) | (((srsrc // 4) & 0x1f) << 16) | ((vdata & 0xff) << 8) | (vaddr & 0xff) + return le32(w0) + le32(w1) + + +def ds_single(op, addr, data0=0, vdst=0, offset=0, gds=0, bit16=0, data1=0): + w0 = 0xd8000000 | ((op & 0xff) << 18) | ((gds & 1) << 17) | ((bit16 & 1) << 16) | (offset & 0xffff) + w1 = ((vdst & 0xff) << 24) | ((data1 & 0xff) << 16) | ((data0 & 0xff) << 8) | (addr & 0xff) + return le32(w0) + le32(w1) + + +def ds_dual(op, addr, data0=0, data1=0, vdst=0, offset0=0, offset1=0, gds=0, bit16=0): + off16 = ((offset1 & 0xff) << 8) | (offset0 & 0xff) + return ds_single(op, addr, data0=data0, vdst=vdst, offset=off16, gds=gds, bit16=bit16, data1=data1) + + +PREAMBLE_LINES = [ + ('s_mov_b32 s10, s6', bytes.fromhex('06038abe')), + ('s_mov_b32 s11, 0', bytes.fromhex('80038bbe')), + ('s_load_dwordx8 s[12:19], s[10:11], 0x0', bytes.fromhex('05030cf4000000fa')), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), +] + + +def build_program(items): + return '\n'.join(asm for asm, _ in items) + '\n', b''.join(raw for _, raw in items) + + +# --------------------------------------------------------------------------- +# Case D: [numthreads(64, 1, 1)], groups=(1, 1, 1), LDS_SIZE=4 (2048 B = 8 st64 banks). +# Exercises ds_write2_b32, ds_write2st64_b32, ds_read2st64_b32, omitted offset0=0, +# vdst[0]==vaddr aliasing, EXEC-guarded dual write + static OOB offset1:8, +# runtime misaligned write no-op, and runtime dynamic OOB read returning 0. +# --------------------------------------------------------------------------- +def make_case_d(): + p = list(PREAMBLE_LINES) + p += [ + ('v_lshlrev_b32 v4, 2, v0', vop2(0x1a, 4, 0x82, 0)), + ('v_xor_b32 v5, 0x11000000, v0', vop2(0x1d, 5, 0xff, 0, 0x11000000)), + ('v_lshlrev_b32 v6, 8, v0', vop2(0x1a, 6, 0x88, 0)), + ('v_xor_b32 v6, 0x22000000, v6', vop2(0x1d, 6, 0xff, 6, 0x22000000)), + # Bank 0 (+0) and Bank 2 (+512) via ds_write2st64_b32 (omitted offset0 defaults to 0). + ('ds_write2st64_b32 v4, v5, v6 offset1:2', ds_dual(0x0f, 4, 5, 6, offset0=0, offset1=2)), + # Bank 6 (+1536) and Bank 7 (+1792) via ds_write2st64_b32. + ('ds_write2st64_b32 v4, v5, v6 offset0:6 offset1:7', ds_dual(0x0f, 4, 5, 6, offset0=6, offset1=7)), + # Bank 4..5 (+1024..1535) via ds_write2_b32 (8 bytes per lane: offset0=0, offset1=1 -> +4B). + ('v_lshlrev_b32 v7, 3, v0', vop2(0x1a, 7, 0x83, 0)), + ('v_add_nc_u32 v7, 1024, v7', vop2(0x25, 7, 0xff, 7, 1024)), + ('v_xor_b32 v8, 0x33000000, v0', vop2(0x1d, 8, 0xff, 0, 0x33000000)), + ('v_xor_b32 v9, 0x44000000, v0', vop2(0x1d, 9, 0xff, 0, 0x44000000)), + ('ds_write2_b32 v7, v8, v9 offset1:1', ds_dual(0x0e, 7, 8, 9, offset0=0, offset1=1)), + # EXEC-guarded dual st64 write: only lanes 0..31 overwrite Bank 6; offset1:8 (2048 B) is static OOB no-op. + ('v_or_b32 v10, 0x55000000, v0', vop2(0x1c, 10, 0xff, 0, 0x55000000)), + ('v_mov_b32 v11, 0xdead0001', v_mov_imm(11, 0xdead0001)), + ('v_cmp_gt_u32 vcc_lo, 32, v0', vopc(0xc4, 0x80 + 32, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('ds_write2st64_b32 v4, v10, v11 offset0:6 offset1:8', ds_dual(0x0f, 4, 10, 11, offset0=6, offset1=8)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + # Runtime misaligned address (4*l + 2): ds_write2_b32 must be a no-op and leave Bank 0 intact. + ('v_add_nc_u32 v12, 2, v4', vop2(0x25, 12, 0x82, 4)), + ('ds_write2_b32 v12, v11, v11 offset1:1', ds_dual(0x0e, 12, 11, 11, offset0=0, offset1=1)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('s_barrier', bytes.fromhex('00008abf')), + # Cross-wave peer read with vdst[0] == vaddr aliasing (v[14:15], v14): Bank 2 and EXEC-masked Bank 6. + ('v_xor_b32 v14, 0x80, v4', vop2(0x1d, 14, 0xff, 4, 0x80)), + ('ds_read2st64_b32 v[14:15], v14 offset0:2 offset1:6', ds_dual(0x38, 14, vdst=14, offset0=2, offset1=6)), + # Bank 4 (even dwords from ds_write2_b32) + Bank 7 (lanes 0..31 in-bounds, lanes 32..63 dynamic OOB -> 0). + ('v_lshlrev_b32 v16, 3, v0', vop2(0x1a, 16, 0x83, 0)), + ('ds_read2st64_b32 v[16:17], v16 offset0:4 offset1:7', ds_dual(0x38, 16, vdst=16, offset0=4, offset1=7)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('v_lshlrev_b32 v13, 4, v0', vop2(0x1a, 13, 0x84, 0)), + ('buffer_store_dwordx4 v[14:17], v13, s[16:19], 0 offen', mubuf_store(0x1e, 14, 13)), + # Lanes 0..23 also read Bank 0 (proving misaligned write did not clobber it) and Bank 4 odd dwords (+4). + ('v_lshlrev_b32 v18, 3, v0', vop2(0x1a, 18, 0x83, 0)), + ('v_add_nc_u32 v18, 4, v18', vop2(0x25, 18, 0x84, 18)), + ('ds_read2st64_b32 v[18:19], v18 offset1:4', ds_dual(0x38, 18, vdst=18, offset0=0, offset1=4)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('v_cmp_gt_u32 vcc_lo, 24, v0', vopc(0xc4, 0x80 + 24, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('v_lshlrev_b32 v20, 3, v0', vop2(0x1a, 20, 0x83, 0)), + ('buffer_store_dwordx2 v[18:19], v20, s[16:19], 0 offen offset:1024', mubuf_store(0x1d, 18, 20, offset=1024)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + ('s_endpgm', bytes.fromhex('000081bf')), + ] + return build_program(p) + + +# --------------------------------------------------------------------------- +# Case A: [numthreads(64, 1, 1)], groups=(2, 1, 1), LDS_SIZE=1 (512 B = 128 dwords). +# 2 groups x 64 threads contending on shared LDS slots with ds_add_u32, ds_add_rtn_u32, +# ds_min_u32, ds_max_u32, ds_or_b32, ds_and_b32, ds_wrxchg_rtn_b32, plus bijective ticket +# histogram proof, wrxchg conservation sum, EXEC-masked atomics + inactive vdst preservation, +# runtime OOB _rtn -> 0, and runtime misaligned _rtn -> 0. +# --------------------------------------------------------------------------- +def make_case_a(): + p = list(PREAMBLE_LINES) + p += [ + ('v_mov_b32 v1, 0', v_mov_imm(1, 0)), + ('v_mov_b32 v2, 1', v_mov_imm(2, 1)), + # Lanes 0..31 zero lds[64..127] (bytes 256..508) via ds_write2_b32. + ('v_lshlrev_b32 v3, 3, v0', vop2(0x1a, 3, 0x83, 0)), + ('v_add_nc_u32 v3, 256, v3', vop2(0x25, 3, 0xff, 3, 256)), + ('v_cmp_gt_u32 vcc_lo, 32, v0', vopc(0xc4, 0x80 + 32, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('ds_write2_b32 v3, v1, v1 offset1:1', ds_dual(0x0e, 3, 1, 1, offset0=0, offset1=1)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + # Lane 0 initializes lds[0..11] via ds_write2_b32. + ('v_cmp_gt_u32 vcc_lo, 1, v0', vopc(0xc4, 0x81, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('v_mov_b32 v4, 0x10000000', v_mov_imm(4, 0x10000000)), + ('v_mov_b32 v5, 0x20000000', v_mov_imm(5, 0x20000000)), + ('ds_write2_b32 v1, v4, v5 offset1:1', ds_dual(0x0e, 1, 4, 5, offset0=0, offset1=1)), + ('v_mov_b32 v4, -2', v_mov_imm(4, -2)), + ('v_mov_b32 v5, 1', v_mov_imm(5, 1)), + ('ds_write2_b32 v1, v4, v5 offset0:2 offset1:3', ds_dual(0x0e, 1, 4, 5, offset0=2, offset1=3)), + ('v_mov_b32 v4, 0', v_mov_imm(4, 0)), + ('v_mov_b32 v5, -1', v_mov_imm(5, -1)), + ('ds_write2_b32 v1, v4, v5 offset0:4 offset1:5', ds_dual(0x0e, 1, 4, 5, offset0=4, offset1=5)), + ('v_mov_b32 v4, 0', v_mov_imm(4, 0)), + ('v_mov_b32 v5, 0xdeadbeef', v_mov_imm(5, 0xdeadbeef)), + ('ds_write2_b32 v1, v4, v5 offset0:6 offset1:7', ds_dual(0x0e, 1, 4, 5, offset0=6, offset1=7)), + ('v_mov_b32 v4, 0', v_mov_imm(4, 0)), + ('v_mov_b32 v5, 0x77770000', v_mov_imm(5, 0x77770000)), + ('ds_write2_b32 v1, v4, v5 offset0:8 offset1:9', ds_dual(0x0e, 1, 4, 5, offset0=8, offset1=9)), + ('v_mov_b32 v4, 0x100', v_mov_imm(4, 0x100)), + ('v_mov_b32 v5, 0', v_mov_imm(5, 0)), + ('ds_write2_b32 v1, v4, v5 offset0:10 offset1:11', ds_dual(0x0e, 1, 4, 5, offset0=10, offset1=11)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('s_barrier', bytes.fromhex('00008abf')), + # All 64 lanes execute contended 32-bit LDS atomics. + ('s_lshl_b32 s20, s7, 8', sop2(0x1e, 20, 7, 0x88)), + ('s_lshl_b32 s22, s7, 16', sop2(0x1e, 22, 7, 0x90)), + ('v_add_nc_u32 v6, s20, v0', vop2(0x25, 6, 20, 0)), + ('v_add_nc_u32 v6, 1, v6', vop2(0x25, 6, 0x81, 6)), + ('ds_add_u32 v1, v6', ds_single(0x00, 1, 6, offset=0)), + ('ds_add_rtn_u32 v7, v1, v6 offset:4', ds_single(0x20, 1, 6, vdst=7, offset=4)), + # Unsigned min/max values crossing 0x7fffffff / 0x80000000 signed boundary. + ('v_add_nc_u32 v8, 0x7ffffff0, v0', vop2(0x25, 8, 0xff, 0, 0x7ffffff0)), + ('v_add_nc_u32 v8, s22, v8', vop2(0x25, 8, 22, 8)), + ('v_and_b32 v9, 3, v0', vop2(0x1b, 9, 0x83, 0)), + ('v_lshlrev_b32 v9, 30, v9', vop2(0x1a, 9, 0x80 + 30, 9)), + ('v_xor_b32 v8, v9, v8', vop2(0x1d, 8, 0x109, 8)), + ('ds_min_u32 v1, v8 offset:8', ds_single(0x07, 1, 8, offset=8)), + ('ds_max_u32 v1, v8 offset:12', ds_single(0x08, 1, 8, offset=12)), + # Bitwise OR and AND reductions. + ('v_and_b32 v10, 15, v0', vop2(0x1b, 10, 0x80 + 15, 0)), + ('v_lshlrev_b32 v10, v10, v2', vop2(0x1a, 10, 0x10a, 2)), + ('v_or_b32 v11, s22, v10', vop2(0x1c, 11, 22, 10)), + ('ds_or_b32 v1, v11 offset:16', ds_single(0x0a, 1, 11, offset=16)), + ('v_not_b32 v12, v10', vop1(0x37, 12, 0x10a)), + ('ds_and_b32 v1, v12 offset:20', ds_single(0x09, 1, 12, offset=20)), + # Bijective ticket proof: 64 threads fetch unique 0..63 tickets and mark lds[64 + ticket]. + ('ds_add_rtn_u32 v13, v1, v2 offset:24', ds_single(0x20, 1, 2, vdst=13, offset=24)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('v_lshlrev_b32 v14, 2, v13', vop2(0x1a, 14, 0x82, 13)), + ('v_add_nc_u32 v14, 256, v14', vop2(0x25, 14, 0xff, 14, 256)), + ('ds_add_u32 v14, v2', ds_single(0x00, 14, 2, offset=0)), + # wrxchg conservation proof: sum(returned_old) + final_lds7 == init + sum(v15). + ('v_or_b32 v15, 0xaa000000, v6', vop2(0x1c, 15, 0xff, 6, 0xaa000000)), + ('ds_wrxchg_rtn_b32 v16, v1, v15 offset:28', ds_single(0x2d, 1, 15, vdst=16, offset=28)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('ds_add_u32 v1, v16 offset:32', ds_single(0x00, 1, 16, offset=32)), + # EXEC-guarded atomics (lanes 0..15) + inactive-lane vdst preservation (v17 stays 0x12345678 for l>=16). + ('v_mov_b32 v17, 0x12345678', v_mov_imm(17, 0x12345678)), + ('v_cmp_gt_u32 vcc_lo, 16, v0', vopc(0xc4, 0x80 + 16, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('ds_add_u32 v1, v2 offset:36', ds_single(0x00, 1, 2, offset=36)), + ('ds_add_rtn_u32 v17, v1, v2 offset:40', ds_single(0x20, 1, 2, vdst=17, offset=40)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('ds_add_u32 v1, v17 offset:44', ds_single(0x00, 1, 17, offset=44)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + # Runtime OOB and misaligned _rtn atomics: LDS untouched, destination receives 0. + ('v_mov_b32 v18, 512', v_mov_imm(18, 512)), + ('v_mov_b32 v19, 0xbad00001', v_mov_imm(19, 0xbad00001)), + ('ds_add_rtn_u32 v19, v18, v2', ds_single(0x20, 18, 2, vdst=19, offset=0)), + ('v_mov_b32 v20, 2', v_mov_imm(20, 2)), + ('v_mov_b32 v21, 0xbad00002', v_mov_imm(21, 0xbad00002)), + ('ds_wrxchg_rtn_b32 v21, v20, v2', ds_single(0x2d, 20, 2, vdst=21, offset=0)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('s_barrier', bytes.fromhex('00008abf')), + # Read back lds[l] and lds[64 + l] in one ds_read2st64_b32, store 64 ticket words per group. + ('v_lshlrev_b32 v22, 2, v0', vop2(0x1a, 22, 0x82, 0)), + ('ds_read2st64_b32 v[22:23], v22 offset1:1', ds_dual(0x38, 22, vdst=22, offset0=0, offset1=1)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + # Per-group output byte base s21 = gid * 320 (80 dwords per group). + ('s_mul_i32 s21, s7, 320', sop2(0x26, 21, 7, 0xff) + le32(320)), + ('v_lshlrev_b32 v24, 2, v0', vop2(0x1a, 24, 0x82, 0)), + ('v_add_nc_u32 v24, s21, v24', vop2(0x25, 24, 21, 24)), + ('buffer_store_dword v23, v24, s[16:19], 0 offen offset:64', mubuf_store(0x1c, 23, 24, offset=64)), + # Lanes 0..6 store lds[0..6] to words 0..6 of the group's 80-word slice. + ('v_cmp_gt_u32 vcc_lo, 7, v0', vopc(0xc4, 0x87, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('buffer_store_dword v22, v24, s[16:19], 0 offen', mubuf_store(0x1c, 22, 24, offset=0)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + # Lane 0 computes wrxchg conservation sum (lds[7] + lds[8]) and stores words 7..12. + ('v_cmp_gt_u32 vcc_lo, 1, v0', vopc(0xc4, 0x81, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('ds_add_rtn_u32 v25, v1, v1 offset:28', ds_single(0x20, 1, 1, vdst=25, offset=28)), + ('ds_add_rtn_u32 v26, v1, v1 offset:32', ds_single(0x20, 1, 1, vdst=26, offset=32)), + ('ds_add_rtn_u32 v27, v1, v1 offset:36', ds_single(0x20, 1, 1, vdst=27, offset=36)), + ('ds_add_rtn_u32 v28, v1, v1 offset:40', ds_single(0x20, 1, 1, vdst=28, offset=40)), + ('ds_add_rtn_u32 v29, v1, v1 offset:44', ds_single(0x20, 1, 1, vdst=29, offset=44)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + ('v_add_nc_u32 v25, v25, v26', vop2(0x25, 25, 0x119, 26)), + ('v_mov_b32 v26, v27', vop1(0x01, 26, 0x11b)), + ('v_mov_b32 v27, v28', vop1(0x01, 27, 0x11c)), + ('v_mov_b32 v28, v29', vop1(0x01, 28, 0x11d)), + ('buffer_store_dwordx4 v[25:28], v24, s[16:19], 0 offen offset:28', mubuf_store(0x1e, 25, 24, offset=28)), + ('v_mov_b32 v29, v19', vop1(0x01, 29, 0x113)), + ('v_mov_b32 v30, v21', vop1(0x01, 30, 0x115)), + ('buffer_store_dwordx2 v[29:30], v24, s[16:19], 0 offen offset:44', mubuf_store(0x1d, 29, 24, offset=44)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + # Lane 16 stores v17 (0x12345678, preserved while inactive during l < 16 guard) at word 13 (offset 52). + ('v_cmp_eq_u32 vcc_lo, 16, v0', vopc(0xc2, 0x80 + 16, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('v_mov_b32 v31, s21', vop1(0x01, 31, 21)), + ('buffer_store_dword v17, v31, s[16:19], 0 offen offset:52', mubuf_store(0x1c, 17, 31, offset=52)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + ('s_endpgm', bytes.fromhex('000081bf')), + ] + return build_program(p) + + +# --------------------------------------------------------------------------- +# Case R: [numthreads(32, 1, 1)], groups=(1, 1, 1), LDS_SIZE=2 (1024 B = 256 dwords). +# Per-lane private slots exercising all 6 _rtn 32-bit LDS atomics (ds_add_rtn_u32, +# ds_min_rtn_u32, ds_max_rtn_u32, ds_or_rtn_b32, ds_and_rtn_b32, ds_wrxchg_rtn_b32) +# with vdst==vaddr, vdst==vdata, and vdst==vaddr==vdata aliasing, verifying both +# pre-op return values and post-op LDS words deterministically. +# --------------------------------------------------------------------------- +def make_case_r(): + p = list(PREAMBLE_LINES) + p += [ + ('v_lshlrev_b32 v4, 2, v0', vop2(0x1a, 4, 0x82, 0)), # 0..124 (slot per lane in each 128B region) + # Initialize 6 regions of 32 dwords (offsets 0, 128, 256, 384, 512, 640) via ds_write2st64_b32. + ('v_add_nc_u32 v5, 0x7ffffff0, v0', vop2(0x25, 5, 0xff, 0, 0x7ffffff0)), + ('v_xor_b32 v6, 0x80000010, v0', vop2(0x1d, 6, 0xff, 0, 0x80000010)), + ('ds_write2st64_b32 v4, v5, v6 offset1:1', ds_dual(0x0f, 4, 5, 6, offset0=0, offset1=1)), # +0 and +256 + ('v_add_nc_u32 v7, 128, v4', vop2(0x25, 7, 0xff, 4, 128)), + ('ds_write2st64_b32 v7, v6, v5 offset1:1', ds_dual(0x0f, 7, 6, 5, offset0=0, offset1=1)), # +128 and +384 + ('v_xor_b32 v8, 0x0f0f0000, v0', vop2(0x1d, 8, 0xff, 0, 0x0f0f0000)), + ('v_xor_b32 v9, 0xf0f000ff, v0', vop2(0x1d, 9, 0xff, 0, 0xf0f000ff)), + ('ds_write2st64_b32 v4, v8, v9 offset0:2 offset1:3', ds_dual(0x0f, 4, 8, 9, offset0=2, offset1=3)), # +512 and +768 + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + # 1. ds_add_rtn_u32 at +0 with vdst == vaddr aliasing (v10 holds addr, receives old). + ('v_mov_b32 v10, v4', vop1(0x01, 10, 0x104)), + ('v_add_nc_u32 v11, 0x100, v0', vop2(0x25, 11, 0xff, 0, 0x100)), + ('ds_add_rtn_u32 v10, v10, v11', ds_single(0x20, 10, 11, vdst=10, offset=0)), + # 2. ds_min_rtn_u32 at +128 with vdst == vdata aliasing (v11 holds data, receives old). + ('v_add_nc_u32 v11, 0x7ffffff8, v0', vop2(0x25, 11, 0xff, 0, 0x7ffffff8)), + ('ds_min_rtn_u32 v11, v4, v11 offset:128', ds_single(0x27, 4, 11, vdst=11, offset=128)), + # 3. ds_max_rtn_u32 at +256. + ('v_add_nc_u32 v12, 0x7ffffff8, v0', vop2(0x25, 12, 0xff, 0, 0x7ffffff8)), + ('ds_max_rtn_u32 v12, v4, v12 offset:256', ds_single(0x28, 4, 12, vdst=12, offset=256)), + # 4. ds_or_rtn_b32 at +512. + ('v_mov_b32 v13, 0x00f000aa', v_mov_imm(13, 0x00f000aa)), + ('ds_or_rtn_b32 v13, v4, v13 offset:512', ds_single(0x2a, 4, 13, vdst=13, offset=512)), + # 5. ds_and_rtn_b32 at +768. + ('v_mov_b32 v14, 0xff0000f0', v_mov_imm(14, 0xff0000f0)), + ('ds_and_rtn_b32 v14, v4, v14 offset:768', ds_single(0x29, 4, 14, vdst=14, offset=768)), + # 6. ds_wrxchg_rtn_b32 at +384 with triple aliasing vdst == vaddr == vdata (v15 = 4*l + 384). + ('v_add_nc_u32 v15, 384, v4', vop2(0x25, 15, 0xff, 4, 384)), + ('ds_wrxchg_rtn_b32 v15, v15, v15', ds_single(0x2d, 15, 15, vdst=15, offset=0)), + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + # Read back post-op values of all 6 slots using ds_read2st64_b32. + ('ds_read2st64_b32 v[16:17], v4 offset1:1', ds_dual(0x38, 4, vdst=16, offset0=0, offset1=1)), # post +0, +256 + ('ds_read2st64_b32 v[18:19], v7 offset1:1', ds_dual(0x38, 7, vdst=18, offset0=0, offset1=1)), # post +128, +384 + ('ds_read2st64_b32 v[20:21], v4 offset0:2 offset1:3', ds_dual(0x38, 4, vdst=20, offset0=2, offset1=3)), # post +512, +768 + ('s_waitcnt lgkmcnt(0)', bytes.fromhex('7fc08cbf')), + # Pack 8 words per lane (256 words total; words 256..319 remain SENTINEL): + # [old_add^post_add, old_min, post_min, old_max, post_max, old_or^post_or, old_and^post_and, old_xchg^post_xchg] + # Store exact distinct words for lanes 0..31 by folding old/post with rotations or storing 8 words: + # word 0: old_add (v10), word 1: post_add (v16), word 2: old_min^post_min, word 3: old_max^post_max + # Wait: storing 8 direct words (with old+post verified cleanly): + # [old_add, post_add, post_min, post_max, post_or, post_and, old_xchg, post_xchg] + + # XOR old_min/old_max/old_or/old_and into a second pass? Better: just mix old_min/max/or/and into lanes 0..31 + # without losing any bit: 10 words per lane = 320? No, keep 32 sentinel words! 9 words * 32 = 288 (32 sentinels)! + # Even cleaner: 8 words per lane using exact non-symmetric checksums? No, direct words are cleaner for mutants! + # With 24 lanes? No, 32 lanes x 8 words = 256 words: + # [old_add, post_add, old_min, post_min, old_max, post_max, post_or ^ (old_or << 1), post_and ^ (old_and << 1)] + # Wait: we still have words 256..319 (64 words)! Lanes 0..15 can store [old_xchg, post_xchg, old_or, old_and] + # at words 256..319? Keep 16 sentinel words: lanes 0..11 store [old_xchg, post_xchg, old_or, old_and] = 48 words (256..303), + # leaving words 304..319 as 16 untouched SENTINEL words! + ('v_lshlrev_b32 v22, 5, v0', vop2(0x1a, 22, 0x85, 0)), # 32 * l (8 dwords per lane) + ('v_mov_b32 v24, v10', vop1(0x01, 24, 0x10a)), # old_add + ('v_mov_b32 v25, v16', vop1(0x01, 25, 0x110)), # post_add + ('v_mov_b32 v26, v11', vop1(0x01, 26, 0x10b)), # old_min + ('v_mov_b32 v27, v18', vop1(0x01, 27, 0x112)), # post_min + ('buffer_store_dwordx4 v[24:27], v22, s[16:19], 0 offen', mubuf_store(0x1e, 24, 22, offset=0)), + ('v_mov_b32 v24, v12', vop1(0x01, 24, 0x10c)), # old_max + ('v_mov_b32 v25, v17', vop1(0x01, 25, 0x111)), # post_max + ('v_mov_b32 v26, v20', vop1(0x01, 26, 0x114)), # post_or + ('v_mov_b32 v27, v21', vop1(0x01, 27, 0x115)), # post_and + ('buffer_store_dwordx4 v[24:27], v22, s[16:19], 0 offen offset:16', mubuf_store(0x1e, 24, 22, offset=16)), + # Lanes 0..11 store [old_xchg, post_xchg, old_or, old_and] at byte offset 1024 + 16*l (words 256..303). + ('v_cmp_gt_u32 vcc_lo, 12, v0', vopc(0xc4, 0x80 + 12, 0)), + ('s_and_saveexec_b32 s0, vcc_lo', bytes.fromhex('6a3c80be')), + ('v_lshlrev_b32 v23, 4, v0', vop2(0x1a, 23, 0x84, 0)), + ('v_mov_b32 v24, v15', vop1(0x01, 24, 0x10f)), # old_xchg + ('v_mov_b32 v25, v19', vop1(0x01, 25, 0x113)), # post_xchg + ('v_mov_b32 v26, v13', vop1(0x01, 26, 0x10d)), # old_or + ('v_mov_b32 v27, v14', vop1(0x01, 27, 0x10e)), # old_and + ('buffer_store_dwordx4 v[24:27], v23, s[16:19], 0 offen offset:1024', mubuf_store(0x1e, 24, 23, offset=1024)), + ('s_or_b32 exec_lo, exec_lo, s0', bytes.fromhex('7e007e88')), + ('s_endpgm', bytes.fromhex('000081bf')), + ] + return build_program(p) + + +SOURCE_D, WORDS_D = make_case_d() +SOURCE_A, WORDS_A = make_case_a() +SOURCE_R, WORDS_R = make_case_r() + +CASES = { + 'D': (SOURCE_D, WORDS_D, USER7 | TGID_X | (4 << 15), (64, 1, 1), (1, 1, 1)), + 'A': (SOURCE_A, WORDS_A, USER7 | TGID_X | (1 << 15), (64, 1, 1), (2, 1, 1)), + 'R': (SOURCE_R, WORDS_R, USER7 | TGID_X | (2 << 15), (32, 1, 1), (1, 1, 1)), +} + +# Verified single-instruction gfx1013 DS snippets for all 14 lowered opcodes. +VERIFIED_SNIPPETS = { + 'ds_write2_b32 v2, v8, v16 offset0:4 offset1:8': ds_dual(0x0e, 2, 8, 16, offset0=4, offset1=8).hex(), + 'ds_write2st64_b32 v4, v5, v6 offset0:2 offset1:3': ds_dual(0x0f, 4, 5, 6, offset0=2, offset1=3).hex(), + 'ds_read2st64_b32 v[10:11], v5 offset0:3 offset1:2': ds_dual(0x38, 5, vdst=10, offset0=3, offset1=2).hex(), + 'ds_add_u32 v2, v8 offset:8': ds_single(0x00, 2, 8, offset=8).hex(), + 'ds_min_u32 v2, v8 offset:12': ds_single(0x07, 2, 8, offset=12).hex(), + 'ds_max_u32 v2, v8 offset:16': ds_single(0x08, 2, 8, offset=16).hex(), + 'ds_and_b32 v2, v8 offset:20': ds_single(0x09, 2, 8, offset=20).hex(), + 'ds_or_b32 v2, v8 offset:24': ds_single(0x0a, 2, 8, offset=24).hex(), + 'ds_add_rtn_u32 v24, v2, v8 offset:8': ds_single(0x20, 2, 8, vdst=24, offset=8).hex(), + 'ds_min_rtn_u32 v24, v2, v8 offset:12': ds_single(0x27, 2, 8, vdst=24, offset=12).hex(), + 'ds_max_rtn_u32 v24, v2, v8 offset:16': ds_single(0x28, 2, 8, vdst=24, offset=16).hex(), + 'ds_and_rtn_b32 v24, v2, v8 offset:20': ds_single(0x29, 2, 8, vdst=24, offset=20).hex(), + 'ds_or_rtn_b32 v24, v2, v8 offset:24': ds_single(0x2a, 2, 8, vdst=24, offset=24).hex(), + 'ds_wrxchg_rtn_b32 v24, v2, v8 offset:28': ds_single(0x2d, 2, 8, vdst=24, offset=28).hex(), +} + + +def expected_words(name): + out = [SENTINEL] * WORDS + if name == 'D': + for l in range(64): + peer = l ^ 32 + bank2_peer = 0x22000000 ^ (peer << 8) + bank6_peer = (0x55000000 | peer) if peer < 32 else (0x11000000 ^ peer) + bank4_even = 0x33000000 ^ l + bank7_word = (0x22000000 ^ ((2 * l) << 8)) if l < 32 else 0 + out[4 * l:4 * l + 4] = [bank2_peer, bank6_peer, bank4_even, bank7_word] + for l in range(24): + bank0_odd = 0x11000000 ^ (2 * l + 1) + bank4_odd = 0x44000000 ^ l + out[256 + 2 * l:256 + 2 * l + 2] = [bank0_odd, bank4_odd] + elif name == 'A': + for g in range(2): + base = g * 80 + adds = [((g << 8) + l + 1) & MASK for l in range(64)] + minmax = [(((0x7ffffff0 + l + (g << 16)) & MASK) ^ ((l & 3) << 30)) for l in range(64)] + ors = [(g << 16) | (1 << (l & 15)) for l in range(64)] + ands = [(~(1 << (l & 15))) & MASK for l in range(64)] + xvals = [0xaa000000 | v for v in adds] + or_acc = 0 + for v in ors: + or_acc |= v + and_acc = MASK + for v in ands: + and_acc &= v + out[base + 0] = (0x10000000 + sum(adds)) & MASK + out[base + 1] = (0x20000000 + sum(adds)) & MASK + out[base + 2] = min([0xfffffffe] + minmax) + out[base + 3] = max([1] + minmax) + out[base + 4] = or_acc + out[base + 5] = and_acc + out[base + 6] = 64 + out[base + 7] = (0xdeadbeef + sum(xvals)) & MASK + out[base + 8] = 0x77770010 + out[base + 9] = 0x110 + out[base + 10] = sum(0x100 + i for i in range(16)) & MASK + out[base + 11] = 0 + out[base + 12] = 0 + out[base + 13] = 0x12345678 + for l in range(64): + out[base + 16 + l] = 1 + elif name == 'R': + for l in range(32): + v5 = (0x7ffffff0 + l) & MASK + v6 = (0x80000010 ^ l) & MASK + v8 = (0x0f0f0000 ^ l) & MASK + v9 = (0xf0f000ff ^ l) & MASK + old_add = v5 + post_add = (old_add + 0x100 + l) & MASK + old_min = v6 + post_min = min(old_min, (0x7ffffff8 + l) & MASK) + old_max = v6 + post_max = max(old_max, (0x7ffffff8 + l) & MASK) + old_or = v8 + post_or = old_or | 0x00f000aa + old_and = v9 + post_and = old_and & 0xff0000f0 + old_xchg = v5 + post_xchg = (384 + 4 * l) & MASK + out[8 * l:8 * l + 8] = [old_add, post_add, old_min, post_min, old_max, post_max, post_or, post_and] + if l < 12: + out[256 + 4 * l:256 + 4 * l + 4] = [old_xchg, post_xchg, old_or, old_and] + else: + raise KeyError(name) + return out + + +def translate_case(name, code=None, rsrc2=None, group=None): + _, words, default_rsrc2, local, _groups = CASES[name] + return G.ComputePipeline(words if code is None else code, root_blob(), + default_rsrc2 if rsrc2 is None else rsrc2, local if group is None else group) + + +def single_ds_code(ds_bytes, *, with_exec=False, with_barrier=False, with_branch=False): + code = bytearray(b''.join(raw for _, raw in PREAMBLE_LINES)) + code += v_mov_imm(1, 0) + v_mov_imm(2, 7) + v_mov_imm(3, 11) + if with_branch: + code += sopp(0x04, 2) # s_cbranch_scc0 +2 (skip 8-byte DS instruction cleanly) + if with_exec: + code += vopc(0xc4, 0x81, 0) + bytes.fromhex('6a3c80be') # v_cmp_gt_u32 vcc_lo, 1, v0; s_and_saveexec_b32 s0, vcc_lo + code += ds_bytes + if with_exec: + code += bytes.fromhex('7e007e88') + if with_barrier: + code += bytes.fromhex('7fc08cbf00008abf') + code += bytes.fromhex('000081bf') + return bytes(code) + + +def check_controls(): + # 1. Decode every fixture and single-instruction snippet through disasm_rdna2 / G.decode. + for line, hex_words in VERIFIED_SNIPPETS.items(): + (_, size, op, asm), = G.decode(bytes.fromhex(hex_words)) + assert size == 8 and op == line.split()[0] and asm == line, (line, op, asm) + for name, (source, words, *_rest) in CASES.items(): + lines = source.splitlines() + decoded = G.decode(words) + assert len(decoded) == len(lines), (name, len(decoded), len(lines)) + for src_line, (_, _, dec_op, _dec_asm) in zip(lines, decoded): + assert dec_op.removesuffix('_e32').removesuffix('_e64') == src_line.split()[0], (name, src_line, dec_op) + + # 2. Verify HLSL lowering for Case D (dual-offset & stride-64 ops, EXEC guard, alignment & bounds). + hlsl_d = translate_case('D').hlsl_cs() + assert 'groupshared uint lds[512];' in hlsl_d, hlsl_d + assert hlsl_d.count('GroupMemoryBarrierWithGroupSync();') == 1, hlsl_d + assert 'if (((a & 3u) == 0u) && a < 2048u) lds[(a + 0u) >> 2] = v5;' in hlsl_d, hlsl_d + assert 'if (((a & 3u) == 0u) && a < 1536u) lds[(a + 512u) >> 2] = v6;' in hlsl_d, hlsl_d + assert 'if (((a & 3u) == 0u) && a < 2044u) lds[(a + 4u) >> 2] = v9;' in hlsl_d, hlsl_d + assert 'if ((exec & 1) && ((a & 3u) == 0u) && a < 512u) lds[(a + 1536u) >> 2] = v10;' in hlsl_d, hlsl_d + assert 'lds[(a + 2048u) >> 2]' not in hlsl_d, hlsl_d # static OOB offset1:8 omitted + assert 'if ((exec & 1) && ((a & 3u) == 0u) && a < 256u) w = lds[(a + 1792u) >> 2];' in hlsl_d, hlsl_d + + # 3. Verify HLSL lowering for Case A (all 7 atomic ops, Interlocked*, EXEC guard, dual barriers). + hlsl_a = translate_case('A').hlsl_cs() + assert 'groupshared uint lds[128];' in hlsl_a, hlsl_a + assert 'uint ao = 0;' in hlsl_a, hlsl_a + assert hlsl_a.count('GroupMemoryBarrierWithGroupSync();') == 2, hlsl_a + for snippet in ( + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 512u) InterlockedAdd(lds[(a + 0u) >> 2], v6);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 508u) InterlockedAdd(lds[(a + 4u) >> 2], v6, ao);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 504u) InterlockedMin(lds[(a + 8u) >> 2], v8);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 500u) InterlockedMax(lds[(a + 12u) >> 2], v8);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 496u) InterlockedOr(lds[(a + 16u) >> 2], v11);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 492u) InterlockedAnd(lds[(a + 20u) >> 2], v12);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 484u) InterlockedExchange(lds[(a + 28u) >> 2], v15, ao);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 476u) InterlockedAdd(lds[(a + 36u) >> 2], v2);', + 'if ((exec & 1) && ((a & 3u) == 0u) && a < 472u) InterlockedAdd(lds[(a + 40u) >> 2], v2, ao);', + 'if (exec & 1) v17 = ao;', + ): + assert snippet in hlsl_a, (snippet, hlsl_a) + + # 4. Verify HLSL lowering for Case R (all 6 _rtn atomics + aliasing, entry-full EXEC without exec guard). + hlsl_r = translate_case('R').hlsl_cs() + assert 'groupshared uint lds[256];' in hlsl_r, hlsl_r + for snippet in ( + 'if (((a & 3u) == 0u) && a < 1024u) InterlockedAdd(lds[(a + 0u) >> 2], v11, ao);', + 'if (((a & 3u) == 0u) && a < 896u) InterlockedMin(lds[(a + 128u) >> 2], v11, ao);', + 'if (((a & 3u) == 0u) && a < 768u) InterlockedMax(lds[(a + 256u) >> 2], v12, ao);', + 'if (((a & 3u) == 0u) && a < 512u) InterlockedOr(lds[(a + 512u) >> 2], v13, ao);', + 'if (((a & 3u) == 0u) && a < 256u) InterlockedAnd(lds[(a + 768u) >> 2], v14, ao);', + 'if (((a & 3u) == 0u) && a < 1024u) InterlockedExchange(lds[(a + 0u) >> 2], v15, ao);', + ): + assert snippet in hlsl_r, (snippet, hlsl_r) + + # 5. Non-rtn atomic shader must NOT declare unused `uint ao = 0;`. + non_rtn_only = G.ComputePipeline(single_ds_code(ds_single(0x00, 1, 2, offset=4)), root_blob(), + USER7 | (1 << 15), (32, 1, 1)).hlsl_cs() + assert 'InterlockedAdd(lds[(a + 4u) >> 2], v2);' in non_rtn_only + assert 'uint ao = 0;' not in non_rtn_only, non_rtn_only + + # 6. LDS_SIZE boundaries: 0 refused, 65 (>32 KiB) refused, 1 (512 B) and 64 (32 KiB) accepted, 2D/3D groups accepted. + base = USER7 | TGID_X + for name in ('D', 'A', 'R'): + refused('at most 32 KiB', lambda n=name: translate_case(n, rsrc2=base | (0 << 15))) + refused('at most 32 KiB', lambda n=name: translate_case(n, rsrc2=base | (65 << 15))) + assert 'groupshared uint lds[8192];' in translate_case('D', rsrc2=base | (64 << 15)).hlsl_cs() + assert 'groupshared uint lds[8192];' in translate_case('A', rsrc2=base | (64 << 15)).hlsl_cs() + assert '[numthreads(8, 8, 1)]' in translate_case('D', group=(8, 8, 1)).hlsl_cs() + + # 7. Static OOB immediate offset on _rtn atomic sets dst = 0u without emitting OOB Interlocked*. + oob_rtn = G.ComputePipeline(single_ds_code(ds_single(0x20, 1, 2, vdst=3, offset=512)), root_blob(), + USER7 | (1 << 15), (32, 1, 1)).hlsl_cs() + assert 'Interlocked' not in oob_rtn and 'v3 = 0u;' in oob_rtn, oob_rtn + oob_rtn_exec = G.ComputePipeline(single_ds_code(ds_single(0x20, 1, 2, vdst=3, offset=512), with_exec=True), + root_blob(), USER7 | (1 << 15), (32, 1, 1)).hlsl_cs() + assert 'if (exec & 1) v3 = 0u;' in oob_rtn_exec, oob_rtn_exec + + # 8. Dual aliasing refusals: offset0 == offset1 (both equal nonzero and both omitted = 0) on write2/write2st64/read2st64. + for op, kw in ((0x0e, {'data0': 2, 'data1': 3}), (0x0f, {'data0': 2, 'data1': 3}), (0x38, {'vdst': 2})): + for off in (0, 5): + raw = ds_dual(op, 1, offset0=off, offset1=off, **kw) + refused('distinct offsets', lambda r=raw: G.ComputePipeline( + single_ds_code(r), root_blob(), USER7 | (4 << 15), (32, 1, 1))) + + # 9. GDS refusal on all 14 opcodes. + for line, hex_words in VERIFIED_SNIPPETS.items(): + w0, w1 = struct.unpack('<2I', bytes.fromhex(hex_words)) + gds_raw = struct.pack('<2I', w0 | (1 << 17), w1) + refused('offset', lambda r=gds_raw: G.ComputePipeline( + single_ds_code(r), root_blob(), USER7 | (4 << 15), (32, 1, 1))) + + # 10. Binary encoding anomalies (reserved bit 16 and unused w1 operand fields) refused at decode/check_encoding. + for line, hex_words in VERIFIED_SNIPPETS.items(): + op_name = line.split()[0] + w0, w1 = struct.unpack('<2I', bytes.fromhex(hex_words)) + bit16_raw = struct.pack('<2I', w0 | (1 << 16), w1) + refused('reserved bit 16', lambda r=bit16_raw: G.ComputePipeline( + single_ds_code(r), root_blob(), USER7 | (4 << 15), (32, 1, 1))) + unused_mask = G.LDS_UNUSED_W1_MASK[op_name] + # Set the lowest bit in the unused w1 field mask. + bad_bit = unused_mask & -unused_mask + unused_raw = struct.pack('<2I', w0, w1 | bad_bit) + refused('unused operand field', lambda r=unused_raw: G.ComputePipeline( + single_ds_code(r), root_blob(), USER7 | (4 << 15), (32, 1, 1))) + + # 11. Unaligned immediate offsets (1, 2, 3) refused on single-offset LDS atomics. + for op_code in (0x00, 0x07, 0x08, 0x09, 0x0a, 0x20, 0x27, 0x28, 0x29, 0x2a, 0x2d): + vdst = 3 if op_code >= 0x20 else 0 + for bad_off in (1, 2, 3, 6): + raw = ds_single(op_code, 1, 2, vdst=vdst, offset=bad_off) + refused('4-byte aligned immediate offset', lambda r=raw: G.ComputePipeline( + single_ds_code(r), root_blob(), USER7 | (1 << 15), (32, 1, 1))) + + # 12. Branched shader + s_barrier refused (while branched shader WITHOUT s_barrier translates!). + branch_no_bar = single_ds_code(ds_single(0x00, 1, 2, offset=4), with_branch=True, with_barrier=False) + assert 'InterlockedAdd(' in G.ComputePipeline(branch_no_bar, root_blob(), USER7 | (1 << 15), (32, 1, 1)).hlsl_cs() + branch_with_bar = single_ds_code(ds_single(0x00, 1, 2, offset=4), with_branch=True, with_barrier=True) + refused('straight-line', lambda: G.ComputePipeline(branch_with_bar, root_blob(), USER7 | (1 << 15), (32, 1, 1))) + # Nonzero reserved immediate on s_barrier in a dual/atomic shader is refused. + bad_bar = patch(WORDS_A, '00008abf', '01008abf') if WORDS_A.count(bytes.fromhex('00008abf')) == 1 else ( + WORDS_A.replace(bytes.fromhex('00008abf'), bytes.fromhex('01008abf'), 1)) + refused('s_barrier with unexpected', lambda: translate_case('A', code=bad_bar)) + + # 13. Direct Stage operand, modifier, non-compute stage, and missing-metadata refusals. + stage = translate_case('D').cs + for bad_ops in ([], ['v1', 'v2'], ['v1', 'v2', 'v3', 'v4'], ['v[1:2]', 'v2', 'v3'], ['s1', 'v2', 'v3'], ['v1', 'v256', 'v3']): + refused('three single VGPRs', lambda o=bad_ops: stage.lds_dual('ds_write2_b32', o, ['offset1:1'])) + refused('three single VGPRs', lambda o=bad_ops: stage.lds_dual('ds_write2st64_b32', o, ['offset1:1'])) + for bad_ops in ([], ['v[1:2]'], ['v1', 'v2'], ['v[1:3]', 'v2'], ['v[255:256]', 'v2'], ['v[1:2]', 's2']): + refused('2-VGPR pair', lambda o=bad_ops: stage.lds_dual('ds_read2st64_b32', o, ['offset1:1'])) + refused('ordinary dword offsets', lambda: stage.lds_dual('ds_write2_b32', ['v1', 'v2', 'v3'], ['offset0:256', 'offset1:1'])) + refused('ordinary dword offsets', lambda: stage.lds_dual('ds_write2_b32', ['v1', 'v2', 'v3'], ['offset0:1', 'offset0:2'])) + refused('ordinary dword offsets', lambda: stage.lds_dual('ds_read2st64_b32', ['v[1:2]', 'v3'], ['offset:4'])) + refused('two single VGPRs', lambda: stage.lds_atomic('ds_add_u32', ['v1', 'v2', 'v3'], [])) + refused('two single VGPRs', lambda: stage.lds_atomic('ds_min_u32', ['v[1:2]', 'v3'], [])) + refused('three single VGPRs', lambda: stage.lds_atomic('ds_add_rtn_u32', ['v1', 'v2'], [])) + refused('three single VGPRs', lambda: stage.lds_atomic('ds_wrxchg_rtn_b32', ['v[1:2]', 'v2', 'v3'], [])) + refused('optional byte offset', lambda: stage.lds_atomic('ds_add_u32', ['v1', 'v2'], ['offset:65536'])) + refused('optional byte offset', lambda: stage.lds_atomic('ds_or_b32', ['v1', 'v2'], ['slc'])) + + for stage_kind in ('vs', 'ps'): + s = G.Stage.__new__(G.Stage) + s.kind = stage_kind + for op in G.LDS_DUAL_OPS: + refused(op, lambda st=s, o=op: st.lower(o, o, ['v1', 'v2', 'v3'], ['offset1:1'])) + for op in G.LDS_ATOMIC_OPS: + refused(op, lambda st=s, o=op: st.lower(o, o, ['v1', 'v2'], [])) + + bare = G.Stage.__new__(G.Stage) + bare.kind = 'cs' + bare.pipe = None + refused('metadata', lambda: bare.lds_dual('ds_write2_b32', ['v1', 'v2', 'v3'], ['offset1:1'])) + refused('metadata', lambda: bare.lds_atomic('ds_add_u32', ['v1', 'v2'], [])) + + # 14. Out-of-scope DS ops stay refused by name. + for op_code, op_name in ((0x05, 'ds_min_i32'), (0x06, 'ds_max_i32'), (0x0b, 'ds_xor_b32'), + (0x15, 'ds_add_f32'), (0x2e, 'ds_wrxchg2_rtn_b32'), (0x4e, 'ds_write2_b64'), + (0x78, 'ds_read2st64_b64')): + raw = ds_dual(op_code, 1, 2, 4, vdst=8, offset0=1, offset1=2) + refused(op_name, lambda r=raw: G.ComputePipeline( + single_ds_code(r), root_blob(), USER7 | (4 << 15), (32, 1, 1))) + + # 15. D3D12 debug_layer status handling: enabled clean, enabled nonzero/missing, unavailable, missing status. + assert check_debug_layer('D', 'backend=warp debug_layer=enabled\ndebug_errors=0 debug_warnings=0\n') == 'enabled' + assert check_debug_layer('D', 'backend=hardware debug_layer=unavailable\ngroups=1x1x1 compared_words=320 mismatches=0\n') == 'unavailable' + for bad_out, expected_msg in ( + ('backend=warp debug_layer=enabled\ndebug_errors=1 debug_warnings=0\n', 'missing zero debug errors/warnings'), + ('backend=warp debug_layer=enabled\ndebug_errors=0 debug_warnings=2\n', 'missing zero debug errors/warnings'), + ('backend=warp debug_layer=enabled\ndebug_errors=0 debug_warnings=01\n', 'missing zero debug errors/warnings'), + ('backend=warp debug_layer=enabled\ngroups=1x1x1 compared_words=320 mismatches=0\n', 'missing zero debug errors/warnings'), + ('backend=hardware\ngroups=1x1x1 compared_words=320 mismatches=0\n', 'missing debug_layer status'), + ): + try: + check_debug_layer('D', bad_out) + except AssertionError as err: + assert expected_msg in str(err), (bad_out, str(err)) + else: + raise AssertionError('expected debug_layer rejection for %r' % (bad_out,)) + + print('dual-offset/st64 LDS and 32-bit LDS atomic controls (14 ops, encodings, bounds, aliasing, EXEC, debug_layer, refusals) pass') + + +def assemble(llvm_mc, source): + from startup_flat_param_check import assemble as run + return run(llvm_mc, source) + + +def check_binary(llvm_mc): + for name, (source, words, *_rest) in CASES.items(): + built = assemble(llvm_mc, source) + assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, hex_words in VERIFIED_SNIPPETS.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == hex_words, '%s: assembled %s, recorded %s' % (line, built, hex_words) + print('LDS dual/atomic fixture words match llvm-mc (%d programs, %d snippets)' + % (len(CASES), len(VERIFIED_SNIPPETS))) + + +# Shader mutant controls: each must fail on WARP and hardware at the expected word with debug_errors=0. +CONTROLS = { + 'd-wrong-st64-stride': ('D', 'if (((a & 3u) == 0u) && a < 1536u) lds[(a + 512u) >> 2] = v6;\n', + 'if (((a & 3u) == 0u) && a < 2040u) lds[(a + 8u) >> 2] = v6;\n'), + 'd-drop-oob-zero': ('D', ' w = 0u;\n if ((exec & 1) && ((a & 3u) == 0u) && a < 256u) w = lds[(a + 1792u) >> 2];\n', + ' w = 1u;\n if ((exec & 1) && ((a & 3u) == 0u) && a < 256u) w = lds[(a + 1792u) >> 2];\n'), + 'd-drop-align': ('D', 'if ((exec & 1) && ((a & 3u) == 0u) && a < 2048u) lds[(a + 0u) >> 2] = v11;\n', + 'if ((exec & 1) && a < 2048u) lds[(a + 0u) >> 2] = v11;\n'), + 'd-drop-exec': ('D', 'if ((exec & 1) && ((a & 3u) == 0u) && a < 512u) lds[(a + 1536u) >> 2] = v10;\n', + 'if (((a & 3u) == 0u) && a < 512u) lds[(a + 1536u) >> 2] = v10;\n'), + 'd-alias-overwrite': ('D', ' if ((exec & 1) && ((a & 3u) == 0u) && a < 512u) w = lds[(a + 1536u) >> 2];\n', + ' if ((exec & 1) && ((v14 & 3u) == 0u) && v14 < 512u) w = lds[(v14 + 1536u) >> 2];\n'), + 'a-swap-minmax': ('A', 'InterlockedMin(lds[(a + 8u) >> 2], v8);', + 'InterlockedMax(lds[(a + 8u) >> 2], v8);'), + 'a-drop-exec': ('A', 'if ((exec & 1) && ((a & 3u) == 0u) && a < 476u) InterlockedAdd(lds[(a + 36u) >> 2], v2);', + 'if (((a & 3u) == 0u) && a < 476u) InterlockedAdd(lds[(a + 36u) >> 2], v2);'), + 'a-drop-wrxchg-rtn': ('A', 'InterlockedExchange(lds[(a + 28u) >> 2], v15, ao);\n if (exec & 1) v16 = ao;', + 'InterlockedExchange(lds[(a + 28u) >> 2], v15, ao);\n if (exec & 1) v16 = 0u;'), + 'a-oob-nonzero': ('A', ' a = v18;\n ao = 0u;\n if ((exec & 1) && ((a & 3u) == 0u) && a < 512u) InterlockedAdd(lds[(a + 0u) >> 2], v2, ao);', + ' a = v18;\n ao = 1u;\n if ((exec & 1) && ((a & 3u) == 0u) && a < 512u) InterlockedAdd(lds[(a + 0u) >> 2], v2, ao);'), + 'r-drop-add-rtn': ('R', 'InterlockedAdd(lds[(a + 0u) >> 2], v11, ao);\n v10 = ao;', + 'InterlockedAdd(lds[(a + 0u) >> 2], v11, ao);\n v10 = v11;'), +} + + +def mutate(hlsl, control): + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def run_case(name, dxc, runner, adapter, directory, control=None): + hlsl = translate_case(name).hlsl_cs() + if control: + hlsl = mutate(hlsl, control) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-Gis', '-WX', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = CASES[name][4] + constants = [0] * 16 + case.write_bytes( + struct.pack(' len(code): + raise Unsupported('%s encoding length %d at +0x%x' % (name, n, off)) + word0, word1 = struct.unpack_from('<2I', code, off) + if word0 & (1 << 16): + raise Unsupported('%s reserved bit 16 set at +0x%x' % (name, off)) + if word1 & LDS_UNUSED_W1_MASK[name]: + raise Unsupported('%s unused operand field set at +0x%x' % (name, off)) if re.fullmatch(r'v_cmpx?_(lt|eq|le|gt|ne|ge)_[iu]16_e64', name): # The decoder prints NEG on an inline integer as a sign (inline 1 with NEG reads `-1`, the same text as # inline -1), and LLVM 15 rejects `-v1` and `|v1|` on these sources: refuse either bit (VOP3 w0[10:8] ABS, @@ -2755,6 +2763,12 @@ def lower(self, base, asm, ops, mods): return ('end',) if base == 's_branch': return ('jump', int(ops[0].split('_')[1], 16)) + if base == 's_barrier' and getattr(self, 'kind', None) == 'cs' and self._lds_general_barrier_ok(): + if mods or ops not in ([], ['0'], ['0x0']): + raise Unsupported('s_barrier with unexpected operands or modifiers') + self._lds_require_alloc(base) + self.emit('GroupMemoryBarrierWithGroupSync();') + return None if base.startswith('s_cbranch_'): if getattr(self, 'kind', None) == 'ms' and base in ('s_cbranch_scc0', 's_cbranch_scc1') and not self.scc_uniform: raise Unsupported('slot 57 mesh: a branch reads SCC that is not proven wave-uniform') @@ -2815,6 +2829,10 @@ def lower(self, base, asm, ops, mods): return handler(ops, mods) if base in MUBUF_ATOMIC_OPS: return self.buffer_atomic(base, ops, mods) + if base in LDS_DUAL_OPS: + return self.lds_dual(base, ops, mods) + if base in LDS_ATOMIC_OPS: + return self.lds_atomic(base, ops, mods) if base.endswith('_dpp'): return self.dpp(base[:-len('_dpp')], ops, mods) if base.startswith('v_cmp'): @@ -3981,6 +3999,108 @@ def buffer_atomic(self, name, ops, mods): if glc: self.set_v(data[1], 'asuint(ai)' if signed else 'ao') + def _lds_general_barrier_ok(self): + """True when a compute stage uses dual/atomic LDS ops in straight-line code without legacy exchange ops.""" + ins = getattr(self, 'ins', None) + if not ins: + return False + has_general = False + for i, (_, _, name, _) in enumerate(ins): + op = re.sub(r'_e(32|64)$', '', name) + if op in LEGACY_LDS_EXCHANGE_OPS: + return False + if op in LDS_DUAL_ATOMIC_OPS: + has_general = True + if op.startswith(('s_branch', 's_cbranch', 's_setpc', 's_swappc')) or (op == 's_endpgm' and i + 1 < len(ins)): + return False + return has_general + + def _lds_require_alloc(self, base): + if getattr(self, 'pipe', None) is None: + raise Unsupported('%s needs pipeline metadata' % base) + words = self.pipe.lds_words + if not 0 < words <= 8192: + raise Unsupported('%s needs a nonzero LDS allocation of at most 32 KiB' % base) + self.uses_lds = True + return words * 4 + + def lds_dual(self, name, ops, mods): + """Lower 32-bit dual-offset and stride-64 LDS ops (ds_write2_b32, ds_write2st64_b32, ds_read2st64_b32).""" + if getattr(self, 'kind', None) != 'cs': + raise Unsupported(name) + is_write, stride = LDS_DUAL_OPS[name] + if is_write: + if (len(ops) != 3 or _lds_single(ops[0]) is None + or _lds_single(ops[1]) is None or _lds_single(ops[2]) is None): + raise Unsupported('%s needs three single VGPRs (addr, data0, data1)' % name) + else: + if len(ops) != 2 or _lds_pair(ops[0]) is None or _lds_single(ops[1]) is None: + raise Unsupported('%s needs a 2-VGPR pair and a byte address VGPR' % name) + # Reuse ds_read2_b32 modifier/aliasing validation (offset0/offset1 in 0..255, distinct, no gds/unknown mods). + off0, off1 = lds_byte_offsets('ds_read2_b32', mods) + scale = stride // 4 + off0, off1 = off0 * scale, off1 * scale + lds_bytes = self._lds_require_alloc(name) + exec_prefix = '' if self.exec_known else '(exec & 1) && ' + if is_write: + addr = self.u(ops[0]) + d0, d1 = self.u(ops[1]), self.u(ops[2]) + self.emit('a = %s;' % addr) + for off, val in ((off0, d0), (off1, d1)): + if off < lds_bytes: + self.emit('if (%s((a & 3u) == 0u) && a < %du) lds[(a + %du) >> 2] = %s;' + % (exec_prefix, lds_bytes - off, off, val)) + else: + dst = _lds_pair(ops[0]) + addr = self.u(ops[1]) + self.emit('a = %s;' % addr) + for idx, off in enumerate((off0, off1)): + if off < lds_bytes: + self.emit('w = 0u;') + self.emit('if (%s((a & 3u) == 0u) && a < %du) w = lds[(a + %du) >> 2];' + % (exec_prefix, lds_bytes - off, off)) + self.set_v(dst + idx, 'w') + else: + self.set_v(dst + idx, '0u') + + def lds_atomic(self, name, ops, mods): + """Lower 32-bit unsigned/bitwise compute LDS atomics (non-rtn and _rtn forms) onto groupshared uint lds[N].""" + if getattr(self, 'kind', None) != 'cs': + raise Unsupported(name) + method, has_rtn = LDS_ATOMIC_OPS[name] + if has_rtn: + if (len(ops) != 3 or _lds_single(ops[0]) is None + or _lds_single(ops[1]) is None or _lds_single(ops[2]) is None): + raise Unsupported('%s needs three single VGPRs (dst, addr, data)' % name) + dst, addr_op, data_op = _lds_single(ops[0]), ops[1], ops[2] + else: + if len(ops) != 2 or _lds_single(ops[0]) is None or _lds_single(ops[1]) is None: + raise Unsupported('%s needs two single VGPRs (addr, data)' % name) + dst, addr_op, data_op = None, ops[0], ops[1] + # Reuse ds_write_b32 single-offset validation (optional 16-bit byte offset, no gds/unknown mods). + off, = lds_byte_offsets('ds_write_b32', mods) + if off % 4: + raise Unsupported('%s requires 4-byte aligned immediate offset, got %d' % (name, off)) + lds_bytes = self._lds_require_alloc(name) + addr = self.u(addr_op) + data = self.u(data_op) + self.emit('a = %s;' % addr) + exec_prefix = '' if self.exec_known else '(exec & 1) && ' + if off < lds_bytes: + if has_rtn: + if not isinstance(getattr(self, 'used_atomic', None), set): + self.used_atomic = set() + self.used_atomic.add('uint') + self.emit('ao = 0u;') + self.emit('if (%s((a & 3u) == 0u) && a < %du) Interlocked%s(lds[(a + %du) >> 2], %s, ao);' + % (exec_prefix, lds_bytes - off, method, off, data)) + self.set_v(dst, 'ao') + else: + self.emit('if (%s((a & 3u) == 0u) && a < %du) Interlocked%s(lds[(a + %du) >> 2], %s);' + % (exec_prefix, lds_bytes - off, method, off, data)) + elif has_rtn: + self.set_v(dst, '0u') + def op_buffer_store_dwordx2(self, ops, mods): self.op_buffer_store_dword(ops, mods, 2) @@ -5814,6 +5934,44 @@ def declarations(self): 'buffer_atomic_xor': ('Xor', False, False, 1), } +# Legacy straight-line LDS exchange ops checked by check_lds_exchange(). +LEGACY_LDS_EXCHANGE_OPS = frozenset(( + 'ds_write_b32', 'ds_read_b32', 'ds_read2_b32', 'ds_write_b64', 'ds_read_b64', 'ds_write_b128', 'ds_read_b128', +)) + +# Dual-offset & stride-64 32-bit LDS ops: name -> (is_write, offset_stride_bytes) +LDS_DUAL_OPS = { + 'ds_write2_b32': (True, 4), + 'ds_write2st64_b32': (True, 256), + 'ds_read2st64_b32': (False, 256), +} + +# 32-bit unsigned/bitwise LDS atomics: name -> (HLSL Interlocked* suffix, has_rtn) +LDS_ATOMIC_OPS = { + 'ds_add_u32': ('Add', False), + 'ds_min_u32': ('Min', False), + 'ds_max_u32': ('Max', False), + 'ds_and_b32': ('And', False), + 'ds_or_b32': ('Or', False), + 'ds_add_rtn_u32': ('Add', True), + 'ds_min_rtn_u32': ('Min', True), + 'ds_max_rtn_u32': ('Max', True), + 'ds_and_rtn_b32': ('And', True), + 'ds_or_rtn_b32': ('Or', True), + 'ds_wrxchg_rtn_b32': ('Exchange', True), +} + +LDS_DUAL_ATOMIC_OPS = frozenset((*LDS_DUAL_OPS, *LDS_ATOMIC_OPS)) + +# Unused w1 register field masks in RDNA 2 DS encoding (must be zero): +# w1[7:0]=ADDR, w1[15:8]=DATA0, w1[23:16]=DATA1, w1[31:24]=VDST. +LDS_UNUSED_W1_MASK = { + 'ds_write2_b32': 0xff000000, + 'ds_write2st64_b32': 0xff000000, + 'ds_read2st64_b32': 0x00ffff00, + **{op: (0x00ff0000 if has_rtn else 0xffff0000) for op, (_, has_rtn) in LDS_ATOMIC_OPS.items()}, +} + # name -> (source operand count, expression); operands are floats VEC_F = { 'v_add_f32': (2, '{0} + {1}'), 'v_sub_f32': (2, '{0} - {1}'), 'v_subrev_f32': (2, '{1} - {0}'), From 34e1637ed2dad953361c7b1348fa673d16be1d59 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 23:34:06 +0200 Subject: [PATCH 185/232] gpu: harden atomic report writes and path/collision guards in mesh_od_pipeline with CLI suite (#2569) --- CMakeLists.txt | 3 + tests/mesh_od_pipeline_cli_check.py | 479 ++++++++++++++++++++++++++++ tools/mesh_od_pipeline.py | 76 ++++- 3 files changed, 543 insertions(+), 15 deletions(-) create mode 100644 tests/mesh_od_pipeline_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3392bd50f..4517671cb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8771,6 +8771,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME mesh_od_pipeline_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_od_pipeline_check.py") set_tests_properties(mesh_od_pipeline_check PROPERTIES TIMEOUT 30) + add_test(NAME mesh_od_pipeline_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_od_pipeline_cli_check.py") + set_tests_properties(mesh_od_pipeline_cli_check PROPERTIES TIMEOUT 30) endif() add_test(NAME mesh_depth_pair_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_depth_pair_check.py" "${DXC_EXECUTABLE}" diff --git a/tests/mesh_od_pipeline_cli_check.py b/tests/mesh_od_pipeline_cli_check.py new file mode 100644 index 000000000..799617c61 --- /dev/null +++ b/tests/mesh_od_pipeline_cli_check.py @@ -0,0 +1,479 @@ +"""CLI, atomic report write, path/collision guard, and mutation suite for tools/mesh_od_pipeline.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import csv +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "mesh_od_pipeline.py" +sys.path.insert(0, str(ROOT / "tools")) + +import mesh_od_pipeline as tool # noqa: E402 + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = tool.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _fake_run_once(_dxc, _hlsl, cso, _flags, _timeout): + cso.write_bytes(b"DXBC" + b"\x00" * 32) + return { + "args": ["dxc", "-Fo", str(cso)], + "wall_s": 0.01, + "peak_bytes": 1024 * 1024, + "exit_code": 0, + "outcome": "dxil", + "cso_bytes": 36, + "first_diagnostic": "", + "output": "", + } + + +def _fake_run_draw(_renderer, _adapter, _mesh, _pixel, data_path, _timeout): + is_ref = data_path.name == "reference.bin" + return { + "outcome": "pass" if is_ref else "mismatch", + "detail": "" if is_ref else "1024 pixels", + "exit_code": 0 if is_ref else 1, + "wall_s": 0.02, + "peak_mib": 8.0, + "pipeline_ms": 0.75 if is_ref else None, + "output": "adapter=mock\nmesh_pipeline_ms=0.75\n", + } + + +def _fake_unsupported(*_args, **_kwargs): + return { + "outcome": "unsupported", + "detail": "mesh shader tier", + "exit_code": 77, + "wall_s": 0.01, + "peak_mib": 4.0, + "pipeline_ms": None, + "output": "mesh_shader_tier=unsupported\n", + } + + +def _make_fake_tools(root: Path) -> tuple[Path, Path]: + dxc = root / "dxc.exe" + renderer = root / "offscreen_check.exe" + dxc.write_bytes(b"DXC_SENTINEL") + renderer.write_bytes(b"RENDERER_SENTINEL") + return dxc, renderer + + +def _base_argv(dxc: Path, renderer: Path, *extra: str) -> list[str]: + return [ + "--dxc", str(dxc), + "--renderer", str(renderer), + "--adapter", "warp", + "--variants", "control", + "--compile-timeout", "10", + "--pipeline-timeout", "10", + *extra, + ] + + +class MeshOdPipelineCliPositiveTests(unittest.TestCase): + def test_main_writes_nested_json_and_csv_atomically_and_overwrites_stale(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + json_out = root / "nested" / "json" / "report.json" + csv_out = root / "nested" / "csv" / "report.csv" + self.assertFalse(json_out.parent.exists()) + self.assertFalse(csv_out.parent.exists()) + + seen_replaces: list[tuple[Path, Path]] = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + return real_replace(src, dst) + + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "run_draw", side_effect=_fake_run_draw), + mock.patch.object(tool, "dxc_version", return_value="dxcompiler 1.8"), + mock.patch.object(tool.os, "replace", side_effect=tracking_replace), + ): + code_json, out_json, err_json = _run_main( + _base_argv(dxc, renderer, "--check", "--out", str(json_out)) + ) + code_csv, out_csv, err_csv = _run_main( + _base_argv(dxc, renderer, "--check", "--out", str(csv_out)) + ) + + self.assertIs(type(code_json), int) + self.assertEqual(code_json, 0, err_json) + self.assertEqual(err_json, "") + self.assertIn(f"wrote {json_out}", out_json) + + self.assertIs(type(code_csv), int) + self.assertEqual(code_csv, 0, err_csv) + self.assertEqual(err_csv, "") + self.assertIn(f"wrote {csv_out}", out_csv) + + self.assertEqual(len(seen_replaces), 2) + self.assertEqual(seen_replaces[0][1].resolve(), json_out.resolve()) + self.assertEqual(seen_replaces[1][1].resolve(), csv_out.resolve()) + self.assertEqual(sorted(p.name for p in json_out.parent.iterdir()), ["report.json"]) + self.assertEqual(sorted(p.name for p in csv_out.parent.iterdir()), ["report.csv"]) + + loaded_json = json.loads(json_out.read_text(encoding="utf-8")) + self.assertEqual(loaded_json["dxc_version"], "dxcompiler 1.8") + self.assertEqual(loaded_json["adapter"], "warp") + self.assertEqual(len(loaded_json["variants"]), 2) + + with csv_out.open("r", encoding="utf-8", newline="") as handle: + rows = list(csv.DictReader(handle)) + self.assertEqual(len(rows), 2) + self.assertEqual(list(rows[0].keys()), list(tool.CSV_FIELDS)) + self.assertEqual(rows[0]["variant"], "control") + self.assertEqual(rows[0]["draw_outcome"], "pass") + + # Second run atomically overwrites stale contents with zero leftover temp dirs. + json_out.write_text("STALE_JSON", encoding="utf-8") + csv_out.write_text("STALE_CSV", encoding="utf-8") + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "run_draw", side_effect=_fake_run_draw), + mock.patch.object(tool, "dxc_version", return_value="dxcompiler 1.8"), + ): + self.assertEqual(_run_main(_base_argv(dxc, renderer, "--out", str(json_out)))[0], 0) + self.assertEqual(_run_main(_base_argv(dxc, renderer, "--out", str(csv_out)))[0], 0) + + self.assertNotEqual(json_out.read_text(encoding="utf-8"), "STALE_JSON") + self.assertNotEqual(csv_out.read_text(encoding="utf-8"), "STALE_CSV") + self.assertEqual(sorted(p.name for p in json_out.parent.iterdir()), ["report.json"]) + self.assertEqual(sorted(p.name for p in csv_out.parent.iterdir()), ["report.csv"]) + + def test_work_dir_creation_and_capability_skip_exit_77(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + work_dir = root / "work" / "nested" + self.assertFalse(work_dir.exists()) + + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "run_draw", side_effect=_fake_unsupported), + ): + code, out, err = _run_main( + _base_argv(dxc, renderer, "--check", "--work-dir", str(work_dir)) + ) + + self.assertIs(type(code), int) + self.assertEqual(code, 77, err) + self.assertEqual(err, "") + self.assertIn("capability skip", out) + self.assertTrue(work_dir.is_dir()) + self.assertIn("pixel.hlsl", sorted(p.name for p in work_dir.iterdir())) + + def test_main_forwards_sys_argv_and_script_entrypoint_exits_zero(self) -> None: + cli_argv = [str(TOOL), "--list-variants", "--variants", "control,chain_1", "--seed", "0x5eed0001"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + lines = out.splitlines() + self.assertEqual(len(lines), 2) + self.assertIn("control", lines[0]) + self.assertIn("chain_1", lines[1]) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(stdout.getvalue(), out) + + proc = _run_subprocess(*cli_argv[1:]) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(proc.stdout, out) + + +class MeshOdPipelineCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + if expected_code == 1 and check_subprocess: + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + + def test_os_replace_failure_preserves_existing_reports_and_leaves_zero_temp_artifacts(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + + for suffix, sentinel in ((".json", '{"preserved": true}\n'), (".csv", "preserved,csv\n")): + report_path = root / f"dir_{suffix[1:]}" / f"report{suffix}" + report_path.parent.mkdir() + report_path.write_text(sentinel, encoding="utf-8") + replace_calls = [] + + def failing_replace(src, dst): + src_path = Path(src) + replace_calls.append((src_path, Path(dst))) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), Path(dst).parent.resolve()) + raise OSError("simulated replace failure") + + with self.subTest(suffix=suffix): + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "run_draw", side_effect=_fake_run_draw), + mock.patch.object(tool, "dxc_version", return_value="dxcompiler 1.8"), + mock.patch.object(tool.os, "replace", side_effect=failing_replace), + ): + self._assert_clean_failure( + _base_argv(dxc, renderer, "--out", str(report_path)), + expected_fragments=("error: failed to write", "simulated replace failure"), + check_subprocess=False, + ) + self.assertEqual(len(replace_calls), 1) + self.assertEqual(report_path.read_text(encoding="utf-8"), sentinel) + self.assertEqual( + sorted(p.name for p in report_path.parent.iterdir()), + [report_path.name], + ) + + # Non-existent nested target also leaves zero temp artifacts when os.replace fails. + fresh_target = root / "fresh" / "nested" / "out.json" + with mock.patch.object(tool.os, "replace", side_effect=OSError("replace boom")): + with self.assertRaises(OSError): + tool.write_report(fresh_target, {"seed": "0x1"}, []) + self.assertFalse(fresh_target.exists()) + self.assertEqual(sorted(p.name for p in fresh_target.parent.iterdir()), []) + + def test_out_existing_directory_rejected_upfront_in_main_and_write_report(self) -> None: + # Kills removal of --out directory guard in _validate_paths() and write_report(). + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + out_dir = root / "report_dir" + out_dir.mkdir() + sentinel = out_dir / "keep.txt" + sentinel.write_text("KEEP", encoding="utf-8") + + argv = _base_argv(dxc, renderer, "--out", str(out_dir)) + with mock.patch.object(tool, "measure") as measure_mock: + self._assert_clean_failure( + argv, + expected_fragments=("error:", "directory"), + check_subprocess=False, + ) + measure_mock.assert_not_called() + + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("error:", proc.stderr) + self.assertIn("directory", proc.stderr) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["keep.txt"]) + self.assertEqual(sentinel.read_text(encoding="utf-8"), "KEEP") + + with self.assertRaises(ValueError): + tool.write_report(out_dir, {}, []) + + def test_out_collisions_with_dxc_and_renderer_rejected_via_resolve_and_samefile(self) -> None: + # Kills removal of resolve() and samefile() collision guards against --dxc and --renderer. + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + sub = root / "sub" + sub.mkdir() + + # 1) Non-existent relative alias check directly on _same_path (kills mutating resolve()). + ghost = root / "ghost_report.json" + ghost_alias = sub / ".." / "ghost_report.json" + self.assertTrue(tool._same_path(ghost, ghost_alias)) + + # 2) Relative alias collisions with --dxc and --renderer. + dxc_alias = sub / ".." / "dxc.exe" + renderer_alias = sub / ".." / "offscreen_check.exe" + for flag_name, alias in (("--dxc", dxc_alias), ("--renderer", renderer_alias)): + argv = _base_argv(dxc, renderer, "--out", str(alias)) + with self.subTest(kind="alias", target=flag_name): + with mock.patch.object(tool, "measure") as measure_mock: + self._assert_clean_failure( + argv, + expected_fragments=("error:", "collides", flag_name), + ) + measure_mock.assert_not_called() + + # 3) Hardlink aliases where resolve() differs (kills mutating samefile()). + dxc_hardlink = root / "dxc_hardlink.exe" + renderer_hardlink = root / "renderer_hardlink.exe" + os.link(dxc, dxc_hardlink) + os.link(renderer, renderer_hardlink) + self.assertNotEqual(dxc.resolve(), dxc_hardlink.resolve()) + self.assertNotEqual(renderer.resolve(), renderer_hardlink.resolve()) + self.assertTrue(dxc.samefile(dxc_hardlink)) + self.assertTrue(renderer.samefile(renderer_hardlink)) + + for flag_name, link_path in (("--dxc", dxc_hardlink), ("--renderer", renderer_hardlink)): + argv = _base_argv(dxc, renderer, "--out", str(link_path)) + with self.subTest(kind="hardlink", target=flag_name): + with mock.patch.object(tool, "measure") as measure_mock: + self._assert_clean_failure( + argv, + expected_fragments=("error:", "collides", flag_name), + ) + measure_mock.assert_not_called() + + self.assertEqual(dxc.read_bytes(), b"DXC_SENTINEL") + self.assertEqual(renderer.read_bytes(), b"RENDERER_SENTINEL") + + def test_work_dir_regular_file_and_out_file_parent_rejected_cleanly(self) -> None: + # Kills removal of --work-dir existing regular file guard and --out parent file guard. + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + regular_file = root / "existing_file.txt" + regular_file.write_bytes(b"PRESERVE_FILE") + + with mock.patch.object(tool, "measure") as measure_mock: + self._assert_clean_failure( + _base_argv(dxc, renderer, "--work-dir", str(regular_file)), + expected_fragments=("error:", "--work-dir", "not a directory"), + ) + measure_mock.assert_not_called() + + with mock.patch.object(tool, "measure") as measure_mock: + self._assert_clean_failure( + _base_argv(dxc, renderer, "--out", str(regular_file / "report.json")), + expected_fragments=("error:", "not a directory"), + ) + measure_mock.assert_not_called() + self.assertEqual(regular_file.read_bytes(), b"PRESERVE_FILE") + + def test_dxc_version_and_write_report_errors_return_exit_1_without_traceback(self) -> None: + # Kills removal of (OSError, ValueError) handlers around dxc_version() and write_report(). + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + out_json = root / "out.json" + argv = _base_argv(dxc, renderer, "--out", str(out_json)) + + for exc_obj in (OSError("dxc version io failure"), ValueError("dxc version parse error")): + with self.subTest(stage="dxc_version", exc=type(exc_obj).__name__): + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "run_draw", side_effect=_fake_run_draw), + mock.patch.object(tool, "dxc_version", side_effect=exc_obj), + ): + self._assert_clean_failure( + argv, + expected_fragments=("error:", str(exc_obj)), + check_subprocess=False, + ) + self.assertFalse(out_json.exists()) + + for exc_obj in (OSError("disk full"), ValueError("invalid payload")): + with self.subTest(stage="write_report", exc=type(exc_obj).__name__): + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "run_draw", side_effect=_fake_run_draw), + mock.patch.object(tool, "dxc_version", return_value="dxcompiler 1.8"), + mock.patch.object(tool, "write_report", side_effect=exc_obj), + ): + self._assert_clean_failure( + argv, + expected_fragments=("error: failed to write", str(exc_obj)), + check_subprocess=False, + ) + self.assertFalse(out_json.exists()) + + def test_argparse_errors_py314_compatible_non_zero_exit_and_semantic_stderr(self) -> None: + with TemporaryDirectory() as tmp: + root = Path(tmp) + dxc, renderer = _make_fake_tools(root) + missing_dxc = root / "missing_dxc.exe" + + cases = ( + ([], "required"), + (["--unknown-flag"], "unrecognized"), + (_base_argv(dxc, renderer, "--variants", ""), "selects nothing"), + (_base_argv(dxc, renderer, "--repeat", "0"), "--repeat"), + (_base_argv(missing_dxc, renderer), "--dxc not found"), + ) + for bad_argv, expected_substr in cases: + with self.subTest(argv=bad_argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + with self.assertRaises(SystemExit) as exited: + tool.main(bad_argv) + self.assertIsInstance(exited.exception.code, int) + self.assertNotEqual(exited.exception.code, 0) + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertIn(expected_substr, stderr.getvalue()) + + proc = _run_subprocess(*bad_argv) + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_substr, proc.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mesh_od_pipeline.py b/tools/mesh_od_pipeline.py index b77e3aee3..9c4535c37 100644 --- a/tools/mesh_od_pipeline.py +++ b/tools/mesh_od_pipeline.py @@ -41,10 +41,12 @@ """ import argparse +from collections.abc import Sequence import csv from datetime import datetime, timezone import json import math +import os from pathlib import Path import re import statistics @@ -393,20 +395,53 @@ def print_table(records): f" {summary['draw_outcome']} {summary['draw_detail']} {summary['controls']}") +def _same_path(left: Path, right: Path) -> bool: + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _validate_paths( + dxc: Path, + renderer: Path, + out: Path | None, + work_dir: Path | None, +) -> None: + if work_dir is not None and work_dir.exists() and not work_dir.is_dir(): + raise ValueError(f"--work-dir path is not a directory: {work_dir}") + if out is not None: + if out.exists() and out.is_dir(): + raise ValueError(f"--out path is a directory: {out}") + if out.parent.exists() and not out.parent.is_dir(): + raise ValueError(f"--out parent is not a directory: {out.parent}") + if _same_path(out, dxc): + raise ValueError(f"--out path collides with --dxc: {out}") + if _same_path(out, renderer): + raise ValueError(f"--out path collides with --renderer: {out}") + + def write_report(path, payload, records): + path = Path(path) + if path.exists() and path.is_dir(): + raise ValueError(f"--out path is a directory: {path}") path.parent.mkdir(parents=True, exist_ok=True) - if path.suffix.lower() == ".json": - path.write_text(json.dumps({**payload, "variants": records}, indent=1) + "\n", - encoding="utf-8") - return - with path.open("w", encoding="utf-8", newline="") as handle: - writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS, extrasaction="ignore") - writer.writeheader() - for record in records: - writer.writerow({**record, **summarize(record)}) - - -def main(argv=None): + with tempfile.TemporaryDirectory(dir=path.parent) as staging_dir: + staged = Path(staging_dir) / path.name + if path.suffix.lower() == ".json": + staged.write_text( + json.dumps({**payload, "variants": records}, indent=1) + "\n", + encoding="utf-8", + ) + else: + with staged.open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS, extrasaction="ignore") + writer.writeheader() + for record in records: + writer.writerow({**record, **summarize(record)}) + os.replace(staged, path) + + +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--dxc", type=Path, help="DXC executable") @@ -457,6 +492,12 @@ def main(argv=None): if not getattr(args, option).is_file(): parser.error(f"--{option} not found: {getattr(args, option)}") + try: + _validate_paths(args.dxc, args.renderer, args.out, args.work_dir) + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + temporary = None try: if args.work_dir: @@ -468,7 +509,7 @@ def main(argv=None): identity, records = measure(names, args.dxc, args.renderer, args.adapter, work, args.repeat, args.compile_timeout, args.pipeline_timeout, args.seed) - except (RuntimeError, OSError) as exc: + except (RuntimeError, OSError, ValueError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 finally: @@ -479,9 +520,14 @@ def main(argv=None): print(line) print_table(records) if args.out: + try: + version = dxc_version(args.dxc) + except (OSError, ValueError) as exc: + print(f"error: failed to query dxc version: {exc}", file=sys.stderr) + return 1 payload = { "recorded_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), - "dxc": str(args.dxc), "dxc_version": dxc_version(args.dxc), + "dxc": str(args.dxc), "dxc_version": version, "target": TARGET, "adapter": args.adapter, "identity": identity, "seed": f"0x{args.seed:08x}", "repeat": args.repeat, "compile_timeout_s": args.compile_timeout, @@ -489,7 +535,7 @@ def main(argv=None): } try: write_report(args.out, payload, records) - except OSError as exc: + except (OSError, ValueError) as exc: print(f"error: failed to write {args.out}: {exc}", file=sys.stderr) return 1 print(f"\nwrote {args.out}") From b0eb6faadf0b8a4fe1073406e0fc68e85f629ba1 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 22:34:57 +0100 Subject: [PATCH 186/232] startup: accept the structured-to-raw descriptor conversion for vertex buffer stores (#2570) A vertex-stage buffer store through a descriptor modified before the store was refused outright. Captured vertex programs apply the conversion that compute stores already accept (#2546): the stride field DW1[29:16] is extracted (s_bfe_u32 0xe0010), clamped to at least 1 (s_max_u32 with 1), NUM_RECORDS (DW2) is multiplied by it, OOB_SELECT (DW3[29:28]) is set to 3 and the stride is cleared. The vertex stage now recognizes the same word expressions and, when the store descriptor is marked modified, checks it with the compute helper: all four words must be the words of one descriptor load, either unchanged except for the stride clear (#2320) or the full raw conversion. The store and manifest are those of the unmodified descriptor. Stores through an unmodified descriptor take the existing path unchanged. As in compute, a vertex-stage descriptor load through a pointer other than the untouched pair is tagged with the constant high word of a 32-bit table pointer, or otherwise with its own load, so the conversion cannot take NUM_RECORDS from one load and the stride from another. Graphics pipelines now keep the other_modified set too. Tests: startup_gfx2hlsl_buffer_store_check.py adds the captured clamped sequence, the unclamped one and the stride clear (same HLSL and manifest as the plain store), a stride taken from a second load through the same pointer (accepted), and refusals for a clamp of 2, NUM_RECORDS not scaled or scaled by a constant, OOB_SELECT 2, the stride not cleared, another bit field, and the stride or NUM_RECORDS of a second load after a pointer add. Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 2 + tests/startup_gfx2hlsl_buffer_store_check.py | 64 ++++++++++++++++++++ tools/startup/gfx2hlsl.py | 14 +++-- 3 files changed, 74 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index fd009c4d2..fb1b82f96 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -264,6 +264,8 @@ to check RGBA8 texel and alpha values, rebinding, and a mismatched 2D view on ha `tools/startup/gfx2hlsl.py` lowers vertex-stage `buffer_store_dword`, `dwordx2`, `dwordx3` and `dwordx4` in the `off` form to `RWByteAddressBuffer.Store*`. The descriptor must come from a root-table slot, and the manifest becomes version 2 with a `uav table ` line. This is offline only: the shipped runtime refuses version 2 manifests, so no store runs in a game. Refused forms: `glc`, `slc`, `offen`, `idxen`, pixel stage, a descriptor also used for a load, a descriptor whose base was changed, and an immediate or inline offset that is not a multiple of four. A register offset is rounded down to a multiple of four. +The descriptor modifications that compute buffer stores accept are accepted here too, with the same checks: the stride clear of DW1 and the structured-to-raw conversion (stride DW1[29:16] extracted, optionally clamped to at least 1, DW2 NUM_RECORDS scaled by it, DW3 OOB_SELECT set to 3, stride cleared), all four words from one descriptor load. The store and manifest are those of the unmodified descriptor. In the vertex stage, as in compute, a descriptor load through a pointer other than the untouched pair is tagged with the constant high word of a 32-bit table pointer, or otherwise with its own load, so the conversion cannot mix words of two loads. Any other modification stays refused. As for compute, matching out-of-range behavior would need a UAV view sized to the converted byte count; the runtime binds no vertex-stage UAV yet. + ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_buffer_store$' --output-on-failure ``` diff --git a/tests/startup_gfx2hlsl_buffer_store_check.py b/tests/startup_gfx2hlsl_buffer_store_check.py index c689fc5cc..38c427ceb 100644 --- a/tests/startup_gfx2hlsl_buffer_store_check.py +++ b/tests/startup_gfx2hlsl_buffer_store_check.py @@ -46,6 +46,15 @@ def v_mov(vdst, inline): return struct.pack(' Date: Thu, 26 Nov 2026 00:36:10 +0300 Subject: [PATCH 187/232] shader: lower compute buffer_store_format_d16_x in gfx2hlsl (#2478) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * shader: lower compute buffer_store_format_d16_x in gfx2hlsl Refs #2274. Adds compute-stage MUBUF buffer_store_format_d16_x (opcode 0x84) lowering to tools/startup/gfx2hlsl.py: - Validates four untouched descriptor words from a fixed native table entry (refusing modified descriptors including stride clears, shared load/store descriptors, missing local table provenance after branches, non-compute stages, lane-mask soffset, illegal binary lds/reserved MUBUF bits, bad operand shapes, and unsupported modifiers glc/slc/dlc/tfe/lds). - Emits uav table plus udsrc entries uav_descword3, uav_stride (unmasked DW1 >> 16, so stride > 0x3fffu rejects DW1[31:30] CACHE_SWIZZLE/SWIZZLE_ENABLE) and uav_numrecords, under an if (exec & 1) guard when EXEC is not proven entry-full. - Supports 1-channel formats BUF_FMT_32_FLOAT (22), BUF_FMT_16_FLOAT (13), BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8), BUF_FMT_16_UINT (11) and BUF_FMT_16_SINT (12) in both GFX10 unified and legacy DFMT/NFMT encodings, checking DST_SEL_X == 4, zero reserved/swizzle/ADD_TID_ENABLE/TYPE flags, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: OOB_SELECT 0 (structured, stride != 0, rec_off = voff + imm_off checked against stride while soffset adds to base) and OOB_SELECT 3 (raw, stride == 0, soffset + rec_off + elem_bytes <= num_records). OOB_SELECT 1/2, mismatched stride/OOB_SELECT, 32-bit overflow, misaligned addresses, unsupported formats/flags and OOB lanes are no-ops. - Uses 4-byte aligned Store for BUF_FMT_32_FLOAT and a lock-free InterlockedCompareExchange CAS loop for 2-byte aligned 16-bit formats. Adds tests/startup_compute_store_d16_x_check.py wired in CMakeLists.txt, .github/workflows/windows.yml and docs/experiments.md. AI-assisted: implementation and tests drafted and verified with an AI coding assistant. * shader: guard buffer_store_format_d16_x against host UAV bounds * tests: allow unavailable D3D12 debug layer in startup_compute_store_d16_x_check When the optional Windows Graphics Tools debug layer is absent, keep word comparisons and mutant mismatch checks active while reporting `debug_layer=unavailable`; continue requiring zero errors/warnings whenever `debug_layer=enabled` is reported. --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 16 + docs/experiments.md | 18 + tests/compute_check.cpp | 40 +- tests/desktop_gpu.h | 2 +- tests/offscreen_check.cpp | 16 +- tests/startup_compute_store_d16_x_check.py | 752 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 227 ++++++- 8 files changed, 1053 insertions(+), 20 deletions(-) create mode 100644 tests/startup_compute_store_d16_x_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 73c7fbadc..25e5ceefd 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -97,6 +97,7 @@ jobs: (["tests/startup_compute_readfirstlane_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), + (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), @@ -220,6 +221,7 @@ jobs: tests/startup_compute_image_store_d16_check.py \ tests/startup_compute_gather_l_check.py \ tests/startup_compute_buffer_atomics_check.py \ + tests/startup_compute_store_d16_x_check.py \ tests/startup_image_gather_c_lz_check.py \ tests/startup_image_sample_c_check.py \ tests/startup_image_3d_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index 4517671cb..a117853fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3535,6 +3535,22 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_gfx2hlsl_neg_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl compute buffer_store_format_d16_x: multi-format, bounds/OOB, atomic CAS RMW and EXEC guard (Refs #2274). + add_test(NAME startup_compute_store_d16_x_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_store_d16_x_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_store_d16_x_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS f32-drop-store f32-wrong-half f32-drop-oob unorm16-trunc p-drop-soffset p-drop-keep s-fold-soff-stride e-drop-exec b-short-binding b-tight-host-guard) + add_test(NAME startup_compute_store_d16_x_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_d16_x_check.py" control ${control} "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_compute_store_d16_x_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index fb1b82f96..240a0ab98 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14644,6 +14644,24 @@ case. The three mutations mismatched 32, 8 and 16 words respectively on both ada ctest --preset dev --no-tests=error -j 1 -R '^startup_gfx2hlsl_compute_(controls|warp|hardware)$' -V ``` +### Startup compute formatted 16-bit single-channel buffer stores + +[The startup translator](../tools/startup/gfx2hlsl.py) (`op_buffer_store_format_d16_x`, refs `#2274`) lowers compute MUBUF `buffer_store_format_d16_x` (`0x84`) through four untouched words of a fixed native table descriptor (`uav table `), requesting `udsrc` entries `uav_descword3`, `uav_stride` (unmasked `DW1 >> 16`, so `stride > 0x3fffu` rejects nonzero `CACHE_SWIZZLE`/`SWIZZLE_ENABLE` bits 31:30) and `uav_numrecords` for that UAV slot. After a branch, the descriptor must come from a local table load with a proven entry root pointer; non-compute stages, modified descriptors (including stride clears), shared load/store descriptors, lane-mask `soffset`, illegal binary `lds`/reserved MUBUF bits, and unsupported modifiers (`glc`, `slc`, `dlc`, `tfe`, `lds`) are refused with `Unsupported`. + +Supported 1-channel formats (`BUF_FMT_32_FLOAT` 22, `BUF_FMT_16_FLOAT` 13, `BUF_FMT_16_UNORM` 7, `BUF_FMT_16_SNORM` 8, `BUF_FMT_16_UINT` 11, `BUF_FMT_16_SINT` 12, in both GFX10 unified and legacy `DFMT`/`NFMT` encodings) extract the low 16 bits of `vdata`, enforce `DST_SEL_X == 4`, zero reserved/swizzle/`ADD_TID_ENABLE`/`TYPE` bits, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: `OOB_SELECT == 0` (`SQ_OOB_INDEX_AND_OFFSET`, requires `stride != 0`, checks `idx < num_records` and `rec_off + elem_bytes <= stride` where `rec_off = voff + imm_off`, while `soffset` adds to base address) and `OOB_SELECT == 3` (`SQ_OOB_COMPLETE` raw mode, requires `stride == 0`, checks `soffset + rec_off + elem_bytes <= num_records`). `OOB_SELECT` `1` (`INDEX_ONLY`) and `2` (`NUM_RECORDS_0` / disabled bounds), mismatched `stride`/`OOB_SELECT`, 32-bit address overflow, misaligned addresses, and OOB lanes are no-ops. Separately from guest `num_records`/`stride`, `store_format_d16_x` queries `buf.GetDimensions(uav_bytes)` on the bound raw UAV and exits before `buf.Store` (`uav_bytes < 4u || addr > uav_bytes - 4u`) or before `buf.Load(base)` and `buf.InterlockedCompareExchange(base, ...)` (`uav_bytes < 4u || base > uav_bytes - 4u`) whenever the enclosing aligned DWORD `[base, base + 4)` exceeds the host view. Stores use 4-byte aligned `Store` for `32_FLOAT` and a lock-free `InterlockedCompareExchange` CAS loop for 2-byte aligned 16-bit formats, under an `if (exec & 1)` lane guard when `EXEC` is not proven entry-full. + +[The `buffer_store_format_d16_x` check](../tests/startup_compute_store_d16_x_check.py) covers pure-Python unit/manifest/encoding/provenance/refusal checks (including static ordering of `GetDimensions` and host-backing guards before `Store`, `Load`, and `InterlockedCompareExchange`) and dispatches six source-built `gfx1013` compute programs through descriptor-table raw views (`offscreen_check --compute-store-sized-case` with optional `uav_words`): `F` (all six formats + legacy encodings + 7 no-op descriptor/OOB/swizzle checks), `P` (`OOB_SELECT=3` raw bounds + `stride=0` + `offen` + SGPR `soffset` + concurrent adjacent halves), `S` (`OOB_SELECT=0` structured with `soffset=16 > stride=8`), `E` (`idxen offen` + local descriptor reload after `s_cbranch_execz` + inner `s_and_saveexec_b32` EXEC guard), `B`/`B-short` (`OOB_SELECT=3, stride=0, num_records=6` writing `addr = 0, 2, 4` against padded `uav_words=2` and short `uav_words=1` host bindings), and `C` (256 concurrent threads hammering the same low/high 16-bit halfwords to verify atomic CAS without bitwise-OR or torn corruption). On both WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.9818`) and `NVIDIA GeForce RTX 4070 SUPER` (`10de:2783`, driver `32.0.16.2114`) with the D3D12 debug layer enabled, all 18 deterministic dispatch cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), Case `C` produced valid atomic halfword values with 319 untouched sentinels (`debug_errors=0 debug_warnings=0`), and all ten controls rejected cleanly on both adapters (`f32-drop-store`, `f32-wrong-half`, `f32-drop-oob`, `unorm16-trunc`, `p-drop-soffset`, `p-drop-keep`, `s-fold-soff-stride`, `e-drop-exec`, plus `b-short-binding` and `b-tight-host-guard` at `word=1` with `debug_errors=0 debug_warnings=0`). + +```powershell +. .\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -j 1 -R "^startup_compute_store_d16_x" -V +python -B tests/startup_compute_store_d16_x_check.py binary llvm-mc-15 +``` + +Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), `OOB_SELECT=3` with nonzero stride, multi-channel `buffer_store_format_d16_{xy,xyz,xyzw}`, `buffer_store_format_d16_hi_x`, and live runtime slot-67 dispatch binding of `uav_descword3`/`uav_stride`/`uav_numrecords`. + ### First active lane at compute entry The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index be0b6a422..aaddced65 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -66,10 +66,11 @@ UINT texture_words_per_texel(DXGI_FORMAT format) static UINT input_word(UINT i) { return 0x8b02a7f1u + i * 0x413b1u; } -// source replaces the generated t0 words when a store case supplies its own, and initial -// replaces the sentinel words that seed the output buffer. +// source replaces the generated t0 words when a store case supplies its own, initial replaces the +// sentinel words that seed the output buffer, and root_constants replaces the b0 CBV constants. static void fill_upload(ID3D12Resource* upload, const std::array* source = nullptr, - const std::array* initial = nullptr) + const std::array* initial = nullptr, + const std::array* root_constants = nullptr) { void* mapped = nullptr; const D3D12_RANGE no_reads{}; @@ -81,7 +82,8 @@ static void fill_upload(ID3D12Resource* upload, const std::array } auto* cb = static_cast(mapped) + constants_offset; std::memset(cb, 0, 4 * alignment); - std::memcpy(cb, constants.data(), sizeof(constants)); + const auto& cb0 = root_constants ? *root_constants : constants; + std::memcpy(cb, cb0.data(), sizeof(cb0)); for (UINT i = 1; i < 4; ++i) std::memcpy(cb + i * alignment, &constants[12 + i], sizeof(UINT)); upload->Unmap(0, nullptr); } @@ -148,8 +150,11 @@ static ComPtr upload_texture(ID3D12Device* device, ID3D12Graphic static ComPtr bind_tables(ID3D12Device* device, ID3D12GraphicsCommandList* list, ID3D12Resource* input, ID3D12Resource* output, ID3D12Resource* texture = nullptr, UINT output_register = uavs - 1, UINT output_mip = 0, - UINT input_register = srvs - 1, UINT texture_first_mip = 0) + UINT input_register = srvs - 1, UINT texture_first_mip = 0, + UINT output_words = capacity) { + if (output_words == 0 || output_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); D3D12_DESCRIPTOR_HEAP_DESC desc{}; desc.NumDescriptors = uavs + srvs; desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; @@ -161,7 +166,7 @@ static ComPtr bind_tables(ID3D12Device* device, ID3D12Grap D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; uav.Format = DXGI_FORMAT_R32_TYPELESS; uav.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - uav.Buffer.NumElements = capacity; + uav.Buffer.NumElements = output_words; uav.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; if (output_register >= uavs) throw std::runtime_error("Invalid output register"); const auto output_desc = output->GetDesc(); @@ -241,9 +246,11 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE D3D12_SHADER_BYTECODE rootBytes, bool conversion_pair = false, const StoreCase* store = nullptr, const std::vector* texels = nullptr, DXGI_FORMAT texture_format = DXGI_FORMAT_UNKNOWN, ID3D12Resource* rendered_texture = nullptr, - bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0) + bool dpp_case = false, bool sized_views = false, UINT texture_first_mip = 0, + UINT uav_words = capacity) { if ((texels || rendered_texture) && !tables) throw std::runtime_error("An image load needs the descriptor-table signature"); + if (uav_words == 0 || uav_words > capacity) throw std::runtime_error("Invalid compute UAV word count"); ComPtr signature; check(device->CreateRootSignature(0, rootBytes.pShaderBytecode, rootBytes.BytecodeLength, IID_PPV_ARGS(&signature)), "Create compute root signature"); @@ -258,7 +265,8 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); fill_upload(input.Get(), store && store->has_source ? &store->source : nullptr, - store && store->has_initial ? &store->initial : nullptr); + store && store->has_initial ? &store->initial : nullptr, + store ? &store->root_constants : nullptr); ComputeCommands commands(device, pipeline.Get()); auto& list = commands.list; ComPtr texture_upload, texture; @@ -273,7 +281,7 @@ static void run_compute(ID3D12Device* device, bool tables, D3D12_SHADER_BYTECODE // signature's UAV range starts at u0, while the root-descriptor path keeps u12. auto* image = rendered_texture ? rendered_texture : texture.Get(); // A sized-view case binds both raw buffers at u0 and t0, so GetDimensions reports the view's byte size. - heap = sized_views ? bind_tables(device, list.Get(), input.Get(), output.Get(), nullptr, 0, 0, 0) + heap = sized_views ? bind_tables(device, list.Get(), input.Get(), output.Get(), nullptr, 0, 0, 0, 0, uav_words) : bind_tables(device, list.Get(), input.Get(), output.Get(), image, image ? 0 : uavs - 1, 0, srvs - 1, texture_first_mip); } else { @@ -341,8 +349,10 @@ void check_compute(ID3D12Device* device, bool tables) } void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference, - bool dpp_case, bool sized_views) + bool dpp_case, bool sized_views, UINT uav_words) { + if (sized_views && uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error(std::string("Could not open compute shader: ") + path); const auto size = file.tellg(); @@ -383,12 +393,16 @@ void check_compute_file(ID3D12Device* device, const char* path, bool conversion_ store.has_source = true; } } - if (sized_views) + if (sized_views) { + const UINT effective_uav_words = uav_words ? uav_words : capacity; + if (effective_uav_words > capacity) + throw std::runtime_error("Invalid compute UAV word count"); run_compute(device, true, shader, {compute_tables, sizeof(compute_tables)}, false, &store, nullptr, - DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true); - else + DXGI_FORMAT_UNKNOWN, nullptr, dpp_case, true, 0, effective_uav_words); + } else { run_compute(device, false, shader, {compute_root, sizeof(compute_root)}, false, &store, nullptr, DXGI_FORMAT_UNKNOWN, nullptr, dpp_case); + } } else { run_compute(device, false, shader, shader, conversion_pair); } diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 21b325fd0..63b23b2ce 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -42,7 +42,7 @@ void check_spirv_compaction(ID3D12Device* device, const char* shader_path); void check_spirv_compare_sampler(ID3D12Device* device, const char* shader_path, const char* ordinary_register, const char* reference_path, const char* descriptors = nullptr); void check_compute_file(ID3D12Device* device, const char* path, bool conversion_pair, const char* reference = nullptr, - bool dpp_case = false, bool sized_views = false); + bool dpp_case = false, bool sized_views = false, UINT uav_words = 0); void check_compute_texture_file(ID3D12Device* device, const char* path, const char* reference); bool check_compute_texture_msaa_file(ID3D12Device* device, const char* path, const char* reference, const char* vs_path, const char* ps_path); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 8b8a9f675..e056d23dd 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -546,11 +546,19 @@ OperationResult run_compute_store_case(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// The store case with both raw buffers bound as descriptor-table views of the full 1280 bytes, so a -// shader reading a descriptor's size sees the view size (root descriptors carry none). +// The store case with both raw buffers bound as descriptor-table views (defaulting to the full 1280 +// bytes, or an explicit uav_words count in [1, 320]), so a shader reading a descriptor's size sees +// the view size (root descriptors carry none). OperationResult run_compute_store_sized_case(const OperationContext& ctx) { - check_compute_file(ctx.device, ctx.argv[3], false, ctx.argv[4], false, true); + UINT uav_words = 0; + if (ctx.argc == 6) { + const std::string_view text = ctx.argv[5]; + const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), uav_words); + if (error != std::errc{} || end != text.data() + text.size() || uav_words == 0) + throw std::runtime_error("Invalid compute UAV word count"); + } + check_compute_file(ctx.device, ctx.argv[3], false, ctx.argv[4], false, true, uav_words); return {OutcomeKind::pass, nullptr}; } @@ -1578,7 +1586,7 @@ const OperationSpec kOperations[] = { {"--compute-root-file", 4, 4, nullptr, kNoGate, run_compute_root_file}, {"--ffx-immediate-conversion", 4, 4, nullptr, kNoGate, run_ffx_immediate_conversion}, {"--compute-store-case", 5, 5, nullptr, kNoGate, run_compute_store_case}, - {"--compute-store-sized-case", 5, 5, nullptr, kNoGate, run_compute_store_sized_case}, + {"--compute-store-sized-case", 5, 6, nullptr, kNoGate, run_compute_store_sized_case}, {"--compute-store-dpp-case", 5, 5, nullptr, kGateShaderWave, run_compute_store_dpp_case}, {"--compute-store-case-atomic64", 5, 5, nullptr, kGateComputeAtomic64, run_compute_store_case}, {"--compute-texture-case", 5, 5, nullptr, kNoGate, run_compute_texture_case}, diff --git a/tests/startup_compute_store_d16_x_check.py b/tests/startup_compute_store_d16_x_check.py new file mode 100644 index 000000000..8dab1979b --- /dev/null +++ b/tests/startup_compute_store_d16_x_check.py @@ -0,0 +1,752 @@ +#!/usr/bin/env python3 +"""Verify compute buffer_store_format_d16_x lowering in tools/startup/gfx2hlsl.py (Refs #2274). + + (no arguments) pure-Python unit, format, bounds and refusal checks + binary reassemble fixture sources and verify machine words + dispatch translate, compile DXC cs_6_0, dispatch and verify readback + control dispatch a mutated translation that must mismatch + +The fixtures are source-built gfx1013 compute programs: +- Case F: 16 lanes read poisoned-high-half inputs from t0 and store via `buffer_store_format_d16_x ... idxen offset:4`. + Dispatched across all six supported formats (32_FLOAT, 16_FLOAT, 16_UNORM, 16_SNORM legacy, 16_UINT, 16_SINT legacy) + with OOB_SELECT=0, stride=8, num_records=12 (so lanes 12..15 are OOB no-ops preserving sentinel), plus no-op checks + for unsupported FORMAT, OOB_SELECT=1/2, OOB_SELECT=0 with stride=0, OOB_SELECT=3 with stride=8, and DW1 swizzle bits. +- Case P: 32 lanes concurrently write adjacent low/high 16-bit halves of the same dwords using `offen`, SGPR `soffset` + (`s4`), `offset:2`, OOB_SELECT=3, `stride=0` and `num_records=50` (raw byte bounds; lanes 23..31 are OOB no-ops). +- Case S: 16 lanes store via structured OOB_SELECT=0 with SGPR `soffset` (`s4=16 > stride=8`) and `offset:4`, proving + RDNA 2 ISA separation of `soffset` from the record offset checked against `stride`. +- Case E: 16 lanes narrow EXEC to tid.x < 10, branch with `s_cbranch_execz`, locally reload the UAV descriptor, narrow + EXEC again to tid.x < 6 via `s_and_saveexec_b32`, and store via `idxen offen` to `BUF_FMT_16_FLOAT` (OOB_SELECT=0); + inactive lanes 6..15 must preserve sentinel. +- Case C: 256 concurrent threads (4 groups x 64 lanes) repeatedly write competing values ({0x1111, 0x2222} to byte 0, + {0x4444, 0x8888} to byte 2) to the same 16-bit halfwords, verifying atomic CAS prevents bitwise-OR or torn corruption. +- Case B / B-short: 4 lanes write 3 in-bounds 16-bit halves at addr = 0, 2, 4 under guest OOB_SELECT=3, stride=0, + num_records=6. Case B binds a padded host raw UAV (uav_words=2, 8 bytes) so DWORD 0 updates and DWORD 1 updates only + its low half while preserving the high-half sentinel; Case B-short binds the same shader/inputs to a short host raw + UAV (uav_words=1, 4 bytes) proving the host backing guard exits before Load/InterlockedCompareExchange on DWORD 1. +""" + +import math +import re +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_compute_check import SENTINEL, USER7, WORDS, patch, refused, root_blob # noqa: E402 + +MUBUF_STORE_FORMAT_D16_X = 0x84 + + +def encode_mubuf(op, vdata, vaddr, srsrc, soffset_enc, *, idxen=False, offen=False, offset=0, + glc=False, slc=False, dlc=False, tfe=False, lds=False, w0_rsvd=False, w1_rsvd=False): + w0 = (0xe0000000 | ((op & 0xff) << 18) | (int(w0_rsvd) << 17) | (int(lds) << 16) + | (int(dlc) << 15) | (int(glc) << 14) | (int(idxen) << 13) | (int(offen) << 12) | (offset & 0xfff)) + w1 = (((soffset_enc & 0xff) << 24) | (int(tfe) << 23) | (int(slc) << 22) | (int(w1_rsvd) << 21) + | (((srsrc // 4) & 0x1f) << 16) | ((vdata & 0xff) << 8) | (vaddr & 0xff)) + return struct.pack('> 16, num_records). +F_VARIANTS = { + 'F-f32': (desc_word3(22, oob_select=0, dst_sel=0x204), 8, 12, 'fp16', True), + 'F-f16': (desc_word3(13, oob_select=0, dst_sel=0xFAC), 8, 12, 'fp16', True), + 'F-unorm16': (desc_word3(7, oob_select=0, dst_sel=0x204), 8, 12, 'fp16', True), + 'F-snorm16': (desc_word3(8, legacy=True, oob_select=0), 8, 12, 'fp16', True), + 'F-uint16': (desc_word3(11, oob_select=0, dst_sel=0xFAC), 8, 12, 'int16', True), + 'F-sint16': (desc_word3(12, legacy=True, oob_select=0), 8, 12, 'int16', True), + # Refused / no-op descriptor configurations (must preserve all 320 sentinel words): + 'F-unsupported': (desc_word3(29, oob_select=0, dst_sel=0xFAC), 8, 12, 'fp16', False), # 16_16_FLOAT + 'F-oob1': (desc_word3(22, oob_select=1, dst_sel=0x204), 8, 12, 'fp16', False), # INDEX_ONLY + 'F-oob2': (desc_word3(22, oob_select=2, dst_sel=0x204), 8, 12, 'fp16', False), # DISABLED + 'F-oob0-stride0': (desc_word3(22, oob_select=0, dst_sel=0x204), 0, 64, 'fp16', False), # structured + stride=0 + 'F-oob3-stride8': (desc_word3(22, oob_select=3, dst_sel=0x204), 8, 64, 'fp16', False), # raw + stride!=0 + 'F-swizzle-en': (desc_word3(22, oob_select=0, dst_sel=0x204), 8 | 0x8000, 12, 'fp16', False), # DW1 bit 31 + 'F-cache-swizzle': (desc_word3(22, oob_select=0, dst_sel=0x204), 8 | 0x4000, 12, 'fp16', False), # DW1 bit 30 +} + +PROGRAMS = { + 'F': (SOURCE_F, WORDS_F, USER7, (16, 1, 1), (1, 1, 1)), + 'P': (SOURCE_P, WORDS_P, USER7, (32, 1, 1), (1, 1, 1)), + 'S': (SOURCE_S, WORDS_S, USER7, (16, 1, 1), (1, 1, 1)), + 'E': (SOURCE_E, WORDS_E, USER7, (16, 1, 1), (1, 1, 1)), + 'C': (SOURCE_C, WORDS_C, USER7, (64, 1, 1), (4, 1, 1)), + 'B': (SOURCE_B, WORDS_B, USER7, (4, 1, 1), (1, 1, 1)), +} + +DISPATCH_CASES = (*F_VARIANTS.keys(), 'P', 'S', 'E', 'B', 'B-short') +CONTENTION_VALID_LO = (0x1111, 0x2222) +CONTENTION_VALID_HI = (0x4444, 0x8888) + + +def f16_to_f32_bits(h): + val = struct.unpack('= 0.0 + else math.ceil(struct.unpack(' base byte offset 4; lane i writes at 4 + 2*i. + # OOB_SELECT=3 (raw), stride = 0, num_records = 50 -> lanes 0..22 write bytes 4..49, + # lanes 23..31 are OOB no-ops preserving sentinel (including high half of dword 12). + halves = tuple(((0x1000 + i * 0x0137) & 0xffff) for i in range(32)) + source = poisoned_source(halves) + word3 = desc_word3(11, oob_select=3, dst_sel=0xFAC) # BUF_FMT_16_UINT, OOB_SELECT=3 (RAW) + constants = [2, 0, word3, 0, 50] + [0] * 11 + for lane in range(32): + addr = 4 + 2 * lane + if addr + 2 <= 50: + put_half(buf, addr, halves[lane]) + return 'P', source, constants, list(struct.unpack('<%dI' % WORDS, buf)), None + + if name == 'S': + # Structured OOB_SELECT=0 with soffset (s4=16) > stride (8) and imm_off=4. + # RDNA 2 ISA: rec_off=4 <= stride-4 (in-bounds), addr = 16 + idx*8 + 4 for idx < 12. + halves = tuple(0x7c00 if i == 11 else h for i, h in enumerate(FP16_VALUES)) + source = poisoned_source(halves) + word3 = desc_word3(22, oob_select=0, dst_sel=0x204) # BUF_FMT_32_FLOAT, OOB_SELECT=0 + constants = [16, 0, word3, 8, 12] + [0] * 11 + for lane in range(12): + struct.pack_into(' word 0 updated, word 1 low half updated (high half sentinel). + # Case B-short binds a short 1-word (4-byte) raw UAV -> word 0 updated, word 1 untouched sentinel. + halves = (0x1234, 0x5678, 0x9abc, 0xdef0) + source = poisoned_source(halves) + word3 = desc_word3(11, oob_select=3, dst_sel=0xFAC) # BUF_FMT_16_UINT, OOB_SELECT=3 (RAW) + constants = [0, 0, word3, 0, 6] + [0] * 11 + uav_words = 2 if name == 'B' else 1 + uav_bytes = uav_words * 4 + for lane in range(4): + addr = 2 * lane + if addr + 2 <= 6 and (addr & ~3) + 4 <= uav_bytes: + put_half(buf, addr, halves[lane]) + return 'B', source, constants, list(struct.unpack('<%dI' % WORDS, buf)), uav_words + + if name == 'C': + # Even lanes read t0[0]=0x1111, t0[2]=0x4444; odd lanes read t0[1]=0x2222, t0[3]=0x8888. + source = poisoned_source((0x1111, 0x2222, 0x4444, 0x8888)) + word3 = desc_word3(11, oob_select=3, dst_sel=0xFAC) # BUF_FMT_16_UINT, OOB_SELECT=3 (RAW) + constants = [0, 0, word3, 0, 4] + [0] * 11 + # Sentinel 0xdeadbeef at word 0 forces offscreen_check to report actual word 0 while asserting words 1..319 == SENTINEL. + exp = [SENTINEL] * WORDS + exp[0] = 0xdeadbeef + return 'C', source, constants, exp, None + + raise KeyError(name) + + +def translate(prog_key, code=None, rsrc2=None, group=None): + _, words, default_rsrc2, local, _ = PROGRAMS[prog_key] + return G.ComputePipeline(words if code is None else code, root_blob(), + default_rsrc2 if rsrc2 is None else rsrc2, local if group is None else group) + + +def check_controls(): + # 1. Verify decoder round-trip for every verified snippet. + for line, hex_words in VERIFIED_SNIPPETS.items(): + (_, size, op, asm), = G.decode(bytes.fromhex(hex_words)) + assert (size, op, asm) == (8, 'buffer_store_format_d16_x', line), (line, size, op, asm) + + # 2. Verify validate_store_d16_x_word3 accepts all 6 unified + 6 legacy formats, OOB 0/3, 0xFAC and 0x204. + for code, (fmt_name, elem_bytes) in G.STORE_D16_X_FORMATS.items(): + for legacy in (False, True): + for oob in (0, 3): + for sel in (0xFAC, 0x204): + w3 = desc_word3(code, legacy=legacy, oob_select=oob, dst_sel=sel) + assert G.validate_store_d16_x_word3(w3) == (code, fmt_name, elem_bytes), hex(w3) + + # 3. Verify validate_store_d16_x_word3 refuses unsupported formats, flags, DST_SEL_X and OOB_SELECT 1/2. + for bad_w3, frag in ( + (desc_word3(0), 'unsupported descriptor FORMAT'), + (desc_word3(1), 'unsupported descriptor FORMAT'), + (desc_word3(5), 'unsupported descriptor FORMAT'), + (desc_word3(20), 'unsupported descriptor FORMAT'), + (desc_word3(23), 'unsupported descriptor FORMAT'), + (desc_word3(29), 'unsupported descriptor FORMAT'), + (desc_word3(56), 'unsupported descriptor FORMAT'), + (desc_word3(77), 'unsupported descriptor FORMAT'), + ((0 << 24) | (1 << 12) | 0xFAC, 'unsupported descriptor FORMAT'), + (desc_word3(22, dst_sel=0xFA0), 'non-identity DST_SEL_X'), + (desc_word3(22, dst_sel=0xFA5), 'non-identity DST_SEL_X'), + (desc_word3(22, oob_select=1), 'OOB_SELECT 1'), + (desc_word3(22, oob_select=2), 'OOB_SELECT 2'), + (desc_word3(22) | (1 << 23), 'flags'), + (desc_word3(22) | (1 << 21), 'flags'), + (desc_word3(22) | (1 << 30), 'flags'), + (desc_word3(22) | (1 << 19), 'flags'), + (desc_word3(22) | (1 << 25), 'flags'), + (-1, 'invalid descriptor word 3'), + (True, 'invalid descriptor word 3'), + (1 << 32, 'invalid descriptor word 3'), + ): + refused(frag, lambda w=bad_w3: G.validate_store_d16_x_word3(w)) + + # 4. Verify manifests, CAS atomic helper (not InterlockedAnd/Or), and soffset/imm_offset separation. + pipe_f = translate('F') + mf_f = pipe_f.manifest() + hlsl_f = pipe_f.hlsl_cs() + assert mf_f == ( + 'x2w-manifest 2\nstage cs\ngroup 16 1 1\nud 5\n' + 'udsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\n' + 'udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n' + 'srv 0 buf table 1 0\nuav 0 table 1 16\n' + ), mf_f + assert 'void store_format_d16_x(' in hlsl_f + assert 'buf.InterlockedCompareExchange(' in hlsl_f + assert 'InterlockedAnd' not in hlsl_f and 'InterlockedOr' not in hlsl_f + assert ' store_format_d16_x(u0, ud2, ud3, ud4, v0, 0u, 0u, 4u, v5);' in hlsl_f, hlsl_f + dim_pos = hlsl_f.index('buf.GetDimensions(uav_bytes);') + store_guard_pos = hlsl_f.index('if ((addr & 3u) != 0u || uav_bytes < 4u || addr > uav_bytes - 4u) return;') + store_pos = hlsl_f.index('buf.Store(addr, asuint(f16tof32(h)));') + cas_guard_pos = hlsl_f.index('if (uav_bytes < 4u || base > uav_bytes - 4u) return;') + load_pos = hlsl_f.index('buf.Load(base)') + cas_pos = hlsl_f.index('buf.InterlockedCompareExchange(') + assert dim_pos < store_guard_pos < store_pos < cas_guard_pos < load_pos < cas_pos, ( + dim_pos, store_guard_pos, store_pos, cas_guard_pos, load_pos, cas_pos) + + hlsl_p = translate('P').hlsl_cs() + assert ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, ud0, 2u, v5);' in hlsl_p, hlsl_p + + hlsl_s = translate('S').hlsl_cs() + assert ' store_format_d16_x(u0, ud2, ud3, ud4, v0, 0u, ud0, 4u, v5);' in hlsl_s, hlsl_s + + hlsl_e = translate('E').hlsl_cs() + assert 'if (exec & 1) store_format_d16_x(u0, ud2, ud3, ud4, v2, v3, 0u, 0u, v5);' in hlsl_e, hlsl_e + + hlsl_b = translate('B').hlsl_cs() + assert ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, 0u, 0u, v5);' in hlsl_b, hlsl_b + + # 'off' addressing mode with inline soffset=8 and offset:4 must keep soff=8u and imm_off=4u SEPARATE! + store_f = '042010e200050480' + off_store = encode_mubuf(MUBUF_STORE_FORMAT_D16_X, 5, 0, 16, 0x80 + 8, offset=4) + hlsl_off = translate('F', code=patch(WORDS_F, store_f, off_store.hex())).hlsl_cs() + assert 'store_format_d16_x(u0, ud2, ud3, ud4, 0u, 0u, 8u, 4u, v5);' in hlsl_off, hlsl_off + + # Shaders without buffer_store_format_d16_x must NOT emit the helper. + plain = G.ComputePipeline(bytes.fromhex('000081bf'), root_blob(), USER7, (1, 1, 1)).hlsl_cs() + assert 'store_format_d16_x' not in plain + + # 5. Refusal checks: unsupported modifiers (glc, slc, dlc, tfe) AND binary lds=1 / reserved bits. + for mod_name, hex_word in ( + ('modifier glc', VERIFIED_SNIPPETS['buffer_store_format_d16_x v5, v0, s[16:19], 0 idxen glc']), + ('modifier slc', VERIFIED_SNIPPETS['buffer_store_format_d16_x v5, v0, s[16:19], 0 idxen slc']), + ('modifier dlc', VERIFIED_SNIPPETS['buffer_store_format_d16_x v5, v0, s[16:19], 0 idxen dlc']), + ('modifier tfe', VERIFIED_SNIPPETS['buffer_store_format_d16_x v5, v0, s[16:19], 0 idxen tfe']), + ('illegal MUBUF encoding bits', encode_mubuf(MUBUF_STORE_FORMAT_D16_X, 5, 0, 16, 0x80, idxen=True, offset=4, lds=True).hex()), + ('illegal MUBUF encoding bits', encode_mubuf(MUBUF_STORE_FORMAT_D16_X, 5, 0, 16, 0x80, idxen=True, offset=4, w0_rsvd=True).hex()), + ('illegal MUBUF encoding bits', encode_mubuf(MUBUF_STORE_FORMAT_D16_X, 5, 0, 16, 0x80, idxen=True, offset=4, w1_rsvd=True).hex()), + ): + refused(mod_name, lambda hw=hex_word: translate('F', code=patch(WORDS_F, store_f, hw)).hlsl_cs()) + + # Lane mask in soffset: patching Case E store soffset from 0 (0x80) to s0 (0x00, written by s_and_saveexec_b32 s0, vcc_lo). + refused('is a lane mask', + lambda: translate('E', code=patch(WORDS_E, '003010e202050480', '003010e202050400')).hlsl_cs()) + + # Direct Stage handler checks for non-compute stages, operand arity, lds/duplicate/out-of-range modifiers, + # bad vdata/vaddr/soffset/descriptor forms. + for stage_kind in ('ps', 'vs'): + st = G.Stage.__new__(G.Stage) + st.kind = stage_kind + try: + st.op_buffer_store_format_d16_x(['v5', 'v0', 's[16:19]', '0'], ['idxen']) + except G.Unsupported as reason: + assert str(reason) == 'buffer_store_format_d16_x', str(reason) + else: + raise AssertionError(f'{stage_kind} stage accepted buffer_store_format_d16_x') + + cs = pipe_f.cs + cs.raw_code = b'' # unit probe calls with synthetic operand lists + for bad_ops, bad_mods, frag in ( + ([], [], 'with 0 operands, expected 4'), + (['v5'], [], 'with 1 operands, expected 4'), + (['v5', 'v0', 's[16:19]'], ['idxen'], 'with 3 operands, expected 4'), + (['v5', 'v0', 's[16:19]', '0', '0'], ['idxen'], 'with 5 operands, expected 4'), + (['v5', 'v0', 's[16:19]', '0'], ['lds'], 'modifier lds'), + (['v5', 'v0', 's[16:19]', '0'], ['idxen', 'idxen'], 'modifier idxen'), + (['v5', 'v0', 's[16:19]', '0'], ['offen', 'offen'], 'modifier offen'), + (['v5', 'v0', 's[16:19]', '0'], ['offset:4', 'offset:8'], 'modifier offset:8'), + (['v5', 'v0', 's[16:19]', '0'], ['offset:4096'], 'modifier offset:4096'), + (['v[5:6]', 'v0', 's[16:19]', '0'], ['idxen'], 'data v[5:6]'), + (['s4', 'v0', 's[16:19]', '0'], ['idxen'], 'data s4'), + (['v256', 'v0', 's[16:19]', '0'], ['idxen'], 'data v256'), + (['v5', 'v0', 's[16:19]', '0'], ['idxen', 'offen'], 'vaddr v0 for idxen offen'), + (['v5', 'v[0:1]', 's[16:19]', '0'], ['idxen'], 'vaddr v[0:1] for idxen'), + (['v5', 'off', 's[16:19]', '0'], ['offen'], 'vaddr off for offen'), + (['v5', 'v0', 's[16:19]', '0'], [], 'vaddr v0 without idxen or offen'), + (['v5', 'v0', 's[16:19]', '-1'], ['idxen'], 'soffset -1'), + (['v5', 'v0', 's[16:19]', 'v1'], ['idxen'], 'soffset v1'), + (['v5', 'v0', 's[16:19]', 'exec_lo'], ['idxen'], 'is a lane mask'), + (['v5', 'v0', 's[16:19]', 's106'], ['idxen'], 'soffset s106'), + (['v5', 'v0', 's[16:17]', '0'], ['idxen'], 'descriptor s[16:17]'), + (['v5', 'v0', 's[104:107]', '0'], ['idxen'], 'descriptor s[104:107]'), + ): + refused(frag, lambda o=bad_ops, m=bad_mods: cs.op_buffer_store_format_d16_x(o, m)) + + # 6. Modified descriptor refusals (including stride clear), load+store reuse, missing local reload. + for inserted, frag in ( + ('800392be', 'modified descriptor'), # s_mov_b32 s18, 0 + ('800393be', 'modified descriptor'), # s_mov_b32 s19, 0 + ('11ff1187ffff00c0', 'modified descriptor'), # s_and_b32 s17, s17, 0xc000ffff (stride clear) + ('10841080', 'modified descriptor'), # s_add_u32 s16, s16, 4 + ('000082bf', 'local table load'), # s_branch +0 without local reload + ): + refused(frag, lambda ins=inserted: translate('F', code=patch(WORDS_F, store_f, ins + store_f)).hlsl_cs()) + + store_on_read = encode_mubuf(MUBUF_STORE_FORMAT_D16_X, 5, 0, 12, 0x80, idxen=True, offset=4).hex() + refused('used for a load and a store', + lambda: translate('F', code=patch(WORDS_F, store_f, store_on_read)).hlsl_cs()) + + # Negative self-check: disabling the handler refuses Case F cleanly. + saved = G.Stage.op_buffer_store_format_d16_x + try: + delattr(G.Stage, 'op_buffer_store_format_d16_x') + refused('buffer_store_format_d16_x', lambda: translate('F').hlsl_cs()) + finally: + G.Stage.op_buffer_store_format_d16_x = saved + + # 7. Debug-layer status handling (with and without Windows Graphics Tools). + assert _check_debug_layer('backend=hardware debug_layer=enabled\ndebug_errors=0 debug_warnings=0\n', 'unit-ok') == 'debug_errors=0 debug_warnings=0' + assert _check_debug_layer('backend=hardware debug_layer=unavailable\n', 'unit-unavail') == 'debug_layer=unavailable' + for bad_out in ( + 'backend=hardware debug_layer=enabled\ndebug_errors=1 debug_warnings=0\n', + 'backend=hardware debug_layer=enabled\n', + 'backend=hardware\ndebug_errors=0 debug_warnings=0\n', + ): + try: + _check_debug_layer(bad_out, 'unit-fail') + except AssertionError: + pass + else: + raise AssertionError('unexpectedly accepted debug output: %r' % (bad_out,)) + + print('buffer_store_format_d16_x unit, format, bounds, CAS, provenance and refusal checks pass') + + +def assemble(llvm_mc, source): + from startup_flat_param_check import assemble as run + return run(llvm_mc, source) + + +def check_binary(llvm_mc): + for name, (source, words, *_rest) in PROGRAMS.items(): + built = assemble(llvm_mc, source) + assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, hex_words in VERIFIED_SNIPPETS.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == hex_words, '%s: assembled %s, recorded %s' % (line, built, hex_words) + print('buffer_store_format_d16_x fixture words match llvm-mc (%d programs, %d snippets)' + % (len(PROGRAMS), len(VERIFIED_SNIPPETS))) + + +CONTROLS = { + 'f32-drop-store': ( + 'F-f32', + ' store_format_d16_x(u0, ud2, ud3, ud4, v0, 0u, 0u, 4u, v5);\n', + '', + None, + ), + 'f32-wrong-half': ( + 'F-f32', + ' uint h = val & 0xffffu;\n', + ' uint h = (val >> 16u) & 0xffffu;\n', + None, + ), + 'f32-drop-oob': ( + 'F-f32', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + ' if (elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + None, + ), + 'unorm16-trunc': ( + 'F-unorm16', + ' return (uint)floor(scaled + 0.5f);\n', + ' return (uint)floor(scaled);\n', + None, + ), + 'p-drop-soffset': ( + 'P', + ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, ud0, 2u, v5);\n', + ' store_format_d16_x(u0, ud2, ud3, ud4, 0u, v1, 0u, 2u, v5);\n', + None, + ), + 'p-drop-keep': ( + 'P', + ' uint next = (cur & keep) | ins;\n', + ' uint next = ins;\n', + None, + ), + 's-fold-soff-stride': ( + 'S', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;\n', + ' if (idx >= num_records || elem_bytes > stride || (rec_off + soff) > stride - elem_bytes) return;\n', + None, + ), + 'e-drop-exec': ( + 'E', + 'if (exec & 1) store_format_d16_x(', + 'store_format_d16_x(', + None, + ), + 'b-short-binding': ( + 'B', + None, + None, + 1, + ), + 'b-tight-host-guard': ( + 'B', + ' if (uav_bytes < 4u || base > uav_bytes - 4u) return;\n', + ' if (uav_bytes < 4u || base > uav_bytes - 8u) return;\n', + None, + ), +} + + +def mutate(hlsl, control): + _, old, new, _ = CONTROLS[control] + if old is None: + return hlsl + assert hlsl.count(old) == 1, (control, hlsl) + return hlsl.replace(old, new) + + +def run_case(name, dxc, runner, adapter, directory, control=None, uav_words=None): + prog_key, source, constants, exp, case_uav_words = case_inputs(name) + hlsl = translate(prog_key).hlsl_cs() + if control: + hlsl = mutate(hlsl, control) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = PROGRAMS[prog_key][4] + case.write_bytes( + struct.pack('> 16) & 0xffff + assert lo in CONTENTION_VALID_LO and hi in CONTENTION_VALID_HI, ( + 'case C: atomic CAS contention corrupted word 0: 0x%08x (lo=0x%04x hi=0x%04x)' % (actual, lo, hi)) + print('case C: atomic CAS contention ok (word0=0x%08x, 319 sentinels untouched, %s)' % (actual, debug_note)) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 1: + check_controls() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + check_binary(sys.argv[2]) + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + sys.exit(check_dispatch(*sys.argv[2:])) + elif len(sys.argv) == 6 and sys.argv[1] == 'control': + sys.exit(check_dispatch(*sys.argv[3:], control=sys.argv[2])) + else: + sys.exit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 4e18d69cd..ec4a478c2 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -169,6 +169,52 @@ def strip_header(code): # Integer formats read a DST_SEL constant 1 as the integer 1, every other format as 1.0. DESC_ONE_INTEGER = ('BUF_FMT_8_UINT', 'BUF_FMT_16_16_UINT', 'BUF_FMT_8_8_8_8_UINT') +# Supported 1-channel formats for compute buffer_store_format_d16_x (RDNA 2 MUBUF 0x84): +# V# word 3 bits 18:12 carry the 7-bit GFX10 unified FORMAT when RESOURCE_LEVEL (bit 24) is 1, +# or legacy (DFMT << 3) | NFMT when bit 24 is 0. Bits checked zero: TYPE[31:30], reserved[27:25], +# ADD_TID_ENABLE[23], INDEX_STRIDE[22:21], reserved[20:19]. DST_SEL_X[2:0] must be 4 (SQ_SEL_X); +# OOB_SELECT[29:28] must be 0 (SQ_OOB_INDEX_AND_OFFSET, structured with stride != 0) or +# 3 (SQ_OOB_COMPLETE, raw byte bounds with stride == 0). Modes 1 (INDEX_ONLY) and 2 +# (NUM_RECORDS_0 / disabled bounds check) are refused. Entry constant uav_stride carries the +# unmasked upper 16 bits of V# word 1 (DW1 >> 16), so stride > 0x3fffu rejects CACHE_SWIZZLE +# (bit 30) and SWIZZLE_ENABLE (bit 31). +STORE_D16_X_FORMATS = { + 7: ('BUF_FMT_16_UNORM', 2), + 8: ('BUF_FMT_16_SNORM', 2), + 11: ('BUF_FMT_16_UINT', 2), + 12: ('BUF_FMT_16_SINT', 2), + 13: ('BUF_FMT_16_FLOAT', 2), + 22: ('BUF_FMT_32_FLOAT', 4), +} +STORE_D16_X_LEGACY_FORMATS = { + (2 << 3) | 0: 7, # DFMT_16 + NFMT_UNORM + (2 << 3) | 1: 8, # DFMT_16 + NFMT_SNORM + (2 << 3) | 4: 11, # DFMT_16 + NFMT_UINT + (2 << 3) | 5: 12, # DFMT_16 + NFMT_SINT + (2 << 3) | 7: 13, # DFMT_16 + NFMT_FLOAT + (4 << 3) | 7: 22, # DFMT_32 + NFMT_FLOAT +} +STORE_D16_X_WORD3_ZERO_MASK = 0xcef80000 # bits 31:30 TYPE | 27:25 reserved | 23 ADD_TID_ENABLE | 22:21 INDEX_STRIDE | 20:19 reserved + + +def validate_store_d16_x_word3(word3): + """Validate V# word 3 for compute buffer_store_format_d16_x and return (code, name, elem_bytes).""" + if not isinstance(word3, int) or isinstance(word3, bool) or not 0 <= word3 <= 0xffffffff: + raise Unsupported('buffer_store_format_d16_x invalid descriptor word 3 %r' % (word3,)) + if word3 & STORE_D16_X_WORD3_ZERO_MASK: + raise Unsupported('buffer_store_format_d16_x unsupported descriptor word 3 flags 0x%08x' % word3) + if (word3 & 7) != 4: + raise Unsupported('buffer_store_format_d16_x non-identity DST_SEL_X %d' % (word3 & 7)) + oob_select = (word3 >> 28) & 3 + if oob_select not in (0, 3): + raise Unsupported('buffer_store_format_d16_x unsupported OOB_SELECT %d' % oob_select) + field = (word3 >> DESC_FORMAT_SHIFT) & DESC_FORMAT_MASK + code = field if ((word3 >> 24) & 1) else STORE_D16_X_LEGACY_FORMATS.get(field) + info = STORE_D16_X_FORMATS.get(code) + if info is None: + raise Unsupported('buffer_store_format_d16_x unsupported descriptor FORMAT %d' % field) + return code, info[0], info[1] + def starts_with_fetch_call(code): return len(code) >= 4 and struct.unpack_from(' binary32, 4-byte aligned Store. + - BUF_FMT_16_FLOAT (13), BUF_FMT_16_UINT (11), BUF_FMT_16_SINT (12): low 16 bits stored at a + 2-byte aligned offset via a lock-free InterlockedCompareExchange CAS loop on the enclosing dword. + - BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8): binary16 -> binary32 -> D3D half-away-from-zero + 16-bit UNORM/SNORM (NaN -> 0), stored via the same 2-byte atomic CAS loop. + Per RDNA 2 ISA §8.1.5 Table 35, OOB_SELECT 0 (structured, stride != 0) checks index < num_records + and (voff + imm_off) + elem_bytes <= stride while soffset adds to the base address; OOB_SELECT 3 + (raw, stride == 0) checks (soffset + voff + imm_off) + elem_bytes <= num_records. OOB_SELECT 1/2, + mismatched stride/OOB_SELECT, nonzero DW1[31:30] swizzle flags (uav_stride carries DW1 >> 16), + unsupported formats/flags, misaligned addresses and out-of-bounds lanes are no-ops. + """ + name = 'buffer_store_format_d16_x' + if self.kind != 'cs': + raise Unsupported(name) + raw = getattr(self, 'raw_code', b'') + pc = getattr(self, 'pc', None) + if raw and pc is not None and pc + 8 <= len(raw): + w0, w1 = struct.unpack_from(' 0xfff: + raise Unsupported('%s modifier %s' % (name, m)) + imm_offset = val + else: + raise Unsupported('%s modifier %s' % (name, m)) + imm_offset = 0 if imm_offset is None else imm_offset + src = reg_range(ops[0]) + if not src or src[0] != 'v' or src[1] != src[2] or src[1] > 255: + raise Unsupported('%s data %s' % (name, ops[0])) + if idxen and offen: + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[2] - vaddr[1] != 1 or vaddr[2] > 255: + raise Unsupported('%s vaddr %s for idxen offen' % (name, ops[1])) + idx_expr, voff_expr = self.u('v%d' % vaddr[1]), self.u('v%d' % vaddr[2]) + elif idxen: + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('%s vaddr %s for idxen' % (name, ops[1])) + idx_expr, voff_expr = self.u(ops[1]), '0u' + elif offen: + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('%s vaddr %s for offen' % (name, ops[1])) + idx_expr, voff_expr = '0u', self.u(ops[1]) + else: + if ops[1] != 'off': + raise Unsupported('%s vaddr %s without idxen or offen' % (name, ops[1])) + idx_expr, voff_expr = '0u', '0u' + if re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + soff_imm = int(ops[3], 0) + if soff_imm > 0xffffffff: + raise Unsupported('%s soffset %s' % (name, ops[3])) + soff_expr = '%du' % soff_imm + else: + if self.is_lane_mask(ops[3]): + raise Unsupported('%s soffset %s is a lane mask' % (name, ops[3])) + sreg = reg_range(ops[3]) + if not sreg or sreg[0] != 's' or sreg[1] != sreg[2] or sreg[1] > 105: + raise Unsupported('%s soffset %s' % (name, ops[3])) + soff_expr = self.S(sreg[1]) + rsrc = reg_range(ops[2]) + if not rsrc or rsrc[0] != 's' or rsrc[2] - rsrc[1] != 3 or rsrc[2] > 105: + raise Unsupported('%s descriptor %s' % (name, ops[2])) + key = self.store_descriptor(ops[2], 4, name, stride0_ok=False) + first = self.sym.get(rsrc[1]) + if getattr(self, 'past_entry', False) and not self.formatted_descriptor_from_block(rsrc, first): + raise Unsupported('%s requires descriptor words proven in the entry block or a local table load' % name) + uav = self.pipe.uav(key, 'raw') + uav_index = self.pipe.uavs[key]['index'] + word3 = 'ud%d' % self.pipe.ud(('uav_descword3', uav_index)) + stride = 'ud%d' % self.pipe.ud(('uav_stride', uav_index)) + num_records = 'ud%d' % self.pipe.ud(('uav_numrecords', uav_index)) + val_expr = self.u(ops[0], low16_only=True) + self.pipe.uses_store_d16_x = True + call = 'store_format_d16_x(%s, %s, %s, %s, %s, %s, %s, %du, %s);' % ( + uav, word3, stride, num_records, idx_expr, voff_expr, soff_expr, imm_offset, val_expr) + self.emit(call if self.exec_known else 'if (exec & 1) ' + call) + def op_tbuffer_load_format_x(self, ops, mods): self.tbuffer(ops, mods, 1) @@ -6197,6 +6338,7 @@ class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False uses_gather_2d_lod = False + uses_store_d16_x = False uses_sad = () srv_formats = () uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -6226,6 +6368,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uses_sampler_heap = False self.uses_pack16_rne = False self.uses_gather_2d_lod = False + self.uses_store_d16_x = False self.uses_sad = set() self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index @@ -6461,6 +6604,85 @@ def common(self): ' return result;', '}', )) + if self.uses_store_d16_x: + out.extend(( + 'uint d16_to_unorm16(uint h) {', + ' float x = f16tof32(h);', + ' if (isnan(x)) return 0u;', + ' precise float saturated = saturate(x);', + ' precise float scaled = saturated * 65535.0f;', + ' return (uint)floor(scaled + 0.5f);', + '}', + 'uint d16_to_snorm16(uint h) {', + ' float x = f16tof32(h);', + ' if (isnan(x)) return 0u;', + ' precise float saturated = clamp(x, -1.0f, 1.0f);', + ' precise float scaled = saturated * 32767.0f;', + ' precise float rounded = scaled >= 0.0f ? floor(scaled + 0.5f) : ceil(scaled - 0.5f);', + ' return ((uint)(int)rounded) & 0xffffu;', + '}', + 'void store_format_d16_x(RWByteAddressBuffer buf, uint word3, uint stride, uint num_records, ' + 'uint idx, uint voff, uint soff, uint imm_off, uint val) {', + ' if ((word3 & 0xcef80000u) != 0u || (word3 & 7u) != 4u) return;', + ' uint oob_sel = (word3 >> 28u) & 3u;', + ' if ((oob_sel != 0u && oob_sel != 3u) || stride > 0x3fffu) return;', + ' uint field = (word3 >> 12u) & 127u;', + ' uint fmt = 0u;', + ' if (((word3 >> 24u) & 1u) != 0u) {', + ' fmt = field;', + ' } else {', + ' if (field == 16u) fmt = 7u;', + ' else if (field == 17u) fmt = 8u;', + ' else if (field == 20u) fmt = 11u;', + ' else if (field == 21u) fmt = 12u;', + ' else if (field == 23u) fmt = 13u;', + ' else if (field == 39u) fmt = 22u;', + ' }', + ' uint elem_bytes = fmt == 22u ? 4u : (fmt == 7u || fmt == 8u || fmt == 11u || fmt == 12u || fmt == 13u ? 2u : 0u);', + ' if (elem_bytes == 0u) return;', + ' if (voff > 0xffffffffu - imm_off) return;', + ' uint rec_off = voff + imm_off;', + ' uint addr = 0u;', + ' if (oob_sel == 3u) {', + ' if (stride != 0u) return;', + ' if (soff > 0xffffffffu - rec_off) return;', + ' addr = soff + rec_off;', + ' if (elem_bytes > num_records || addr > num_records - elem_bytes) return;', + ' } else {', + ' if (stride == 0u) return;', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;', + ' if (idx > (0xffffffffu - rec_off) / stride) return;', + ' uint elem_addr = idx * stride + rec_off;', + ' if (soff > 0xffffffffu - elem_addr) return;', + ' addr = elem_addr + soff;', + ' }', + ' uint uav_bytes = 0u;', + ' buf.GetDimensions(uav_bytes);', + ' uint h = val & 0xffffu;', + ' if (fmt == 22u) {', + ' if ((addr & 3u) != 0u || uav_bytes < 4u || addr > uav_bytes - 4u) return;', + ' buf.Store(addr, asuint(f16tof32(h)));', + ' return;', + ' }', + ' if ((addr & 1u) != 0u) return;', + ' uint out16 = h;', + ' if (fmt == 7u) out16 = d16_to_unorm16(h);', + ' else if (fmt == 8u) out16 = d16_to_snorm16(h);', + ' uint base = addr & 0xfffffffcu;', + ' if (uav_bytes < 4u || base > uav_bytes - 4u) return;', + ' uint shift = (addr & 2u) << 3u;', + ' uint keep = ~(0xffffu << shift);', + ' uint ins = (out16 & 0xffffu) << shift;', + ' uint cur = buf.Load(base);', + ' for (;;) {', + ' uint next = (cur & keep) | ins;', + ' uint prev = 0u;', + ' buf.InterlockedCompareExchange(base, cur, next, prev);', + ' if (prev == cur) break;', + ' cur = prev;', + ' }', + '}', + )) if 'v_sad_u8' in self.uses_sad: out.append( 'uint sad_u8(uint a, uint b, uint c) {' @@ -6608,6 +6830,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_gather_2d_lod = False + self.uses_store_d16_x = False self.uses_sad = set() self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: unproved descriptor writes From 2f7fd286e44c96a13830acb050466f7d81ecc92d Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah Date: Wed, 25 Nov 2026 23:36:47 +0200 Subject: [PATCH 188/232] shader: validate input paths and add OSError/struct guards in mesh_loop_census with CLI suite (#2574) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/mesh_loop_census_cli_check.py | 372 ++++++++++++++++++++++++++++ tools/mesh_loop_census.py | 83 +++++-- 3 files changed, 431 insertions(+), 26 deletions(-) create mode 100644 tests/mesh_loop_census_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index a117853fa..54b590bd6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8696,6 +8696,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/mesh_scc_any_lane_check.py") add_test(NAME mesh_loop_census COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_loop_census_check.py") + add_test(NAME mesh_loop_census_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh_loop_census_cli_check.py") add_test(NAME mesh_entry_exec_restore_cpu COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/mesh_entry_check.py" exec-restore) add_test(NAME mesh_amplification_refusal COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/mesh_loop_census_cli_check.py b/tests/mesh_loop_census_cli_check.py new file mode 100644 index 000000000..36ac0864a --- /dev/null +++ b/tests/mesh_loop_census_cli_check.py @@ -0,0 +1,372 @@ +"""Pure-Python CLI, path-validation, error-guard, and mutation suite for tools/mesh_loop_census.py.""" + +from collections import Counter +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "mesh_loop_census.py" +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tests")) + +import mesh_loop_census # noqa: E402 +from mesh_two_exits_check import mesh_container # noqa: E402 + +LIMITS = (4, 2) +LOOP_FREE_PROGRAM = [ + (0, "s_mov_b32 s10, 0"), + (4, "s_endpgm"), +] +COUNTED_LOOP_PROGRAM = [ + (0, "s_mov_b32 s10, 0"), + (4, "s_add_u32 s10, s10, 1"), + (8, "s_cmp_lt_u32 s10, 4"), + (12, "s_cbranch_scc1 65533"), + (16, "s_endpgm"), +] + + +def _synthetic_dxbc(tag: bytes) -> bytes: + return b"DXBC" + tag.ljust(28, b"\x00") + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = mesh_loop_census.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class MeshLoopCensusCliPositiveTests(unittest.TestCase): + def test_main_classifies_loop_free_counted_duplicate_non_dxbc_and_malformed(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + nested = root / "nested" + nested.mkdir() + + loop_free_blob = _synthetic_dxbc(b"loop-free") + counted_blob = _synthetic_dxbc(b"counted-a") + duplicate_blob = _synthetic_dxbc(b"counted-b") + bad_blob = _synthetic_dxbc(b"bad-stage") + + (root / "a_loop_free.dxbc").write_bytes(loop_free_blob) + (nested / "b_counted.dxbc").write_bytes(counted_blob) + (nested / "c_duplicate.dxbc").write_bytes(duplicate_blob) + (root / "d_bad.dxbc").write_bytes(bad_blob) + (root / "e_notes.txt").write_bytes(b"not a dxbc container") + + seen_calls: list[tuple[bytes, object]] = [] + + def fake_decode_mesh(blob: bytes, library: object): + seen_calls.append((blob, library)) + if blob == loop_free_blob: + return list(LOOP_FREE_PROGRAM), LIMITS + if blob in (counted_blob, duplicate_blob): + return list(COUNTED_LOOP_PROGRAM), LIMITS + if blob == bad_blob: + raise ValueError("Unsupported shader stage 5") + raise AssertionError(f"unexpected blob: {blob!r}") + + with mock.patch.object(mesh_loop_census.mesh_entry_aot, "decode_mesh", side_effect=fake_decode_mesh): + code, out, err = _run_main([str(root), "--llvm", "mock-llvm.dll"]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(seen_calls), 4) + self.assertTrue(all(lib == "mock-llvm.dll" for _, lib in seen_calls)) + self.assertEqual( + sorted(p.name for p in root.iterdir()), + ["a_loop_free.dxbc", "d_bad.dxbc", "e_notes.txt", "nested"], + ) + self.assertEqual( + sorted(p.name for p in nested.iterdir()), + ["b_counted.dxbc", "c_duplicate.dxbc"], + ) + + expected_fragments = ( + "| Population | Programs |", + "| containers not decoded: Unsupported shader stage N | 1 |", + "| duplicate mesh programs | 1 |", + "| files without a DXBC container | 1 |", + "| loop-free | 1 |", + "| with loops | 1 |", + "| back-edges | 1 |", + "| outermost back-edges | 1 |", + "| programs with 1 loop | 1 |", + "| s_cbranch_scc1 | 1 |", + "| no | no | no | no | yes | constant pattern | 1 | 3 / 3 / 3 |", + "| First refusal (entry lowerer, as decoded) | With loops | Loop-free |", + "| at a latch | 1 | 0 |", + "| Expected a forward mesh branch | 1 | 0 |", + ) + for fragment in expected_fragments: + self.assertIn(fragment, out, out) + for leak in ("a_loop_free", "b_counted", "c_duplicate", "d_bad", "e_notes", "s10"): + self.assertNotIn(leak, out, leak) + + def test_main_llvm_mc_backend_wires_disassembler_and_forwards_sys_argv(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + blob = _synthetic_dxbc(b"mc-counted") + (root / "mesh.dxbc").write_bytes(blob) + + saved_pixel_disasm = mesh_loop_census.pixel_aot.disassemble + saved_mesh_disasm = mesh_loop_census.mesh_entry_aot.disassemble + seen_mc_cmds: list[list[str]] = [] + + def fake_decode_mesh(container: bytes, library: object): + self.assertEqual(container, blob) + self.assertEqual(library, "mock-llvm-mc") + decoded = mesh_loop_census.mesh_entry_aot.disassemble( + b"\x00" * 20, + library, + offsets=True, + ) + return decoded, LIMITS + + def fake_subprocess_run(cmd, *, input, capture_output, text, check): + seen_mc_cmds.append(list(cmd)) + stdout = "\n".join( + [ + "s_mov_b32 s10, 0 ; encoding: [0x80,0x03,0x8a,0xbe]", + "s_add_u32 s10, s10, 1 ; encoding: [0x0a,0x81,0x0a,0x80]", + "s_cmp_lt_u32 s10, 4 ; encoding: [0x0a,0x84,0x0a,0xbf]", + "s_cbranch_scc1 65533 ; encoding: [0xfd,0xff,0x85,0xbf]", + "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", + ] + ) + return subprocess.CompletedProcess(cmd, 0, stdout=stdout, stderr="") + + try: + with ( + mock.patch.object(mesh_loop_census.mesh_entry_aot, "decode_mesh", side_effect=fake_decode_mesh), + mock.patch.object(mesh_loop_census.subprocess, "run", side_effect=fake_subprocess_run), + ): + code, out, err = _run_main([str(root), "--llvm-mc", "mock-llvm-mc"]) + finally: + mesh_loop_census.pixel_aot.disassemble = saved_pixel_disasm + mesh_loop_census.mesh_entry_aot.disassemble = saved_mesh_disasm + + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(len(seen_mc_cmds), 1) + self.assertEqual(seen_mc_cmds[0][0], "mock-llvm-mc") + self.assertIn("--disassemble", seen_mc_cmds[0]) + self.assertIn("| with loops | 1 |", out) + self.assertIn("| s_cbranch_scc1 | 1 |", out) + + with tempfile.TemporaryDirectory() as tmp: + empty_dir = Path(tmp) + cli_argv = [str(TOOL), str(empty_dir), "--llvm", "stub"] + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("| Population | Programs |", out) + + stdout = io.StringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertIn("| Population | Programs |", stdout.getvalue()) + + proc = _run_subprocess(str(empty_dir), "--llvm", "stub") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("| Population | Programs |", proc.stdout) + + +class MeshLoopCensusCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int = 1, + expected_fragments: tuple[str, ...] = (), + check_subprocess: bool = True, + ) -> None: + code, out, err = _run_main(argv) + self.assertIs(type(code), int) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.strip(), f"expected subprocess stderr output for {argv!r}") + for fragment in expected_fragments: + self.assertIn(fragment, proc.stderr) + + def test_missing_directory_and_regular_file_rejected_cleanly(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing_dir" + regular_file = root / "shader.dxbc" + regular_file.write_bytes(_synthetic_dxbc(b"single")) + + for target, fragment in ( + (missing, "does not exist"), + (regular_file, "not a directory"), + ): + with self.subTest(target=target.name): + with self.assertRaises(ValueError) as direct_err: + mesh_loop_census.read_programs(target, Counter(), "stub") + self.assertIn(fragment, str(direct_err.exception)) + + with mock.patch.object(mesh_loop_census, "use_llvm_mc") as mc_mock: + self._assert_clean_failure( + [str(target), "--llvm-mc", "mock-llvm-mc"], + expected_fragments=("mesh_loop_census:", fragment), + check_subprocess=False, + ) + mc_mock.assert_not_called() + + self._assert_clean_failure( + [str(target), "--llvm", "stub"], + expected_fragments=("mesh_loop_census:", fragment), + ) + + def test_llvm_and_llvm_mc_directory_and_empty_paths_rejected_upfront(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + input_dir = root / "inputs" + input_dir.mkdir() + backend_dir = root / "backend_dir" + backend_dir.mkdir() + + for flag in ("--llvm", "--llvm-mc"): + for bad_value, fragment in ( + (str(backend_dir), "existing directory"), + ("", "non-empty"), + (" ", "non-empty"), + ): + with self.subTest(flag=flag, bad_value=bad_value): + with ( + mock.patch.object(mesh_loop_census, "use_llvm_mc") as mc_mock, + mock.patch.object(mesh_loop_census, "read_programs") as read_mock, + ): + self._assert_clean_failure( + [str(input_dir), flag, bad_value], + expected_fragments=("mesh_loop_census:", fragment), + ) + mc_mock.assert_not_called() + read_mock.assert_not_called() + + def test_oserror_valueerror_struct_error_guards_without_traceback(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + valid_mesh_blob = mesh_container(bytes.fromhex("80038abe000081bf")) + (root / "sample.dxbc").write_bytes(valid_mesh_blob) + + # Subprocess OSError via nonexistent --llvm-mc executable and nonexistent --llvm library (no mocking). + missing_mc = root / "nonexistent_llvm_mc" + saved_pixel_disasm = mesh_loop_census.pixel_aot.disassemble + saved_mesh_disasm = mesh_loop_census.mesh_entry_aot.disassemble + try: + self._assert_clean_failure( + [str(root), "--llvm-mc", str(missing_mc)], + expected_fragments=("mesh_loop_census:",), + ) + finally: + mesh_loop_census.pixel_aot.disassemble = saved_pixel_disasm + mesh_loop_census.mesh_entry_aot.disassemble = saved_mesh_disasm + missing_llvm = root / "nonexistent_llvm.dll" + self._assert_clean_failure( + [str(root), "--llvm", str(missing_llvm)], + expected_fragments=("mesh_loop_census:",), + ) + + # In-process OSError from decode_mesh propagates cleanly to parser.exit(1, ...). + with mock.patch.object( + mesh_loop_census.mesh_entry_aot, + "decode_mesh", + side_effect=OSError("cannot open library"), + ): + self._assert_clean_failure( + [str(root), "--llvm", "stub"], + expected_fragments=("mesh_loop_census:", "cannot open library"), + check_subprocess=False, + ) + + # In-process ValueError and struct.error from census/read_programs caught cleanly. + for exc_obj, fragment in ( + (ValueError("synthetic census failure"), "synthetic census failure"), + (struct.error("unpack requires a buffer of 4 bytes"), "unpack requires a buffer of 4 bytes"), + ): + with self.subTest(exc=type(exc_obj).__name__): + with mock.patch.object(mesh_loop_census, "census", side_effect=exc_obj): + self._assert_clean_failure( + [str(root), "--llvm", "stub"], + expected_fragments=("mesh_loop_census:", fragment), + check_subprocess=False, + ) + + # Negative control: per-container ValueError / KeyError / struct.error in decode_mesh + # stays tallied in Population and exits 0. + for exc_obj, expected_row in ( + (KeyError("DXIL"), "| containers not decoded: 'DXIL' | 1 |"), + (struct.error("unpack_from requires 8 bytes"), "| containers not decoded: unpack_from requires N bytes | 1 |"), + ): + with self.subTest(container_exc=type(exc_obj).__name__): + with mock.patch.object(mesh_loop_census.mesh_entry_aot, "decode_mesh", side_effect=exc_obj): + code, out, err = _run_main([str(root), "--llvm", "stub"]) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn(expected_row, out) + + def test_argparse_usage_errors_compatible_with_py314(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for bad_argv, expected_fragment in ( + ([], "required"), + ([str(root)], "required"), + ([str(root), "--llvm", "a", "--llvm-mc", "b"], "not allowed"), + ([str(root), "--llvm", "a", "--unknown-flag"], "unrecognized"), + ): + with self.subTest(argv=bad_argv): + self._assert_clean_failure( + bad_argv, + expected_code=2, + expected_fragments=(expected_fragment,), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/mesh_loop_census.py b/tools/mesh_loop_census.py index 3384eaa39..4f919bf9f 100644 --- a/tools/mesh_loop_census.py +++ b/tools/mesh_loop_census.py @@ -37,13 +37,14 @@ mesh_loop_census.py DIR --llvm-mc LLVM_MC decode with llvm-mc (the same instruction printer) """ import argparse +from collections import Counter +from collections.abc import Sequence import hashlib +from pathlib import Path import re import struct import subprocess import sys -from collections import Counter -from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import mesh_dynamic_aot # noqa: E402 @@ -251,24 +252,47 @@ def census(programs): return c +def _validate_directory(root): + path = Path(root) + if not path.exists(): + raise ValueError(f"Input directory does not exist: {root}") + if not path.is_dir(): + raise ValueError(f"Input path is not a directory: {root}") + return path + + +def _validate_backend(flag, value): + if value is None: + return + if not value.strip(): + raise ValueError(f"Expected a non-empty {flag} path") + if Path(value).is_dir(): + raise ValueError(f"{flag} path is an existing directory: {value}") + + def read_programs(root, population, library): - seen = set() - for path in sorted(p for p in Path(root).rglob("*") if p.is_file()): - blob = path.read_bytes() - if blob[:4] != b"DXBC": - population["files without a DXBC container"] += 1 - continue - try: - decoded, limits = mesh_entry_aot.decode_mesh(blob, library) - except (ValueError, KeyError, struct.error) as error: - population["containers not decoded: " + normalise(str(error))] += 1 - continue - key = hashlib.sha256(repr((limits, [line for _, line in decoded])).encode()).digest() - if key in seen: - population["duplicate mesh programs"] += 1 - continue - seen.add(key) - yield signed_branches(decoded), limits + root_path = _validate_directory(root) + + def _iter_programs(): + seen = set() + for path in sorted(p for p in root_path.rglob("*") if p.is_file()): + blob = path.read_bytes() + if blob[:4] != b"DXBC": + population["files without a DXBC container"] += 1 + continue + try: + decoded, limits = mesh_entry_aot.decode_mesh(blob, library) + except (ValueError, KeyError, struct.error) as error: + population["containers not decoded: " + normalise(str(error))] += 1 + continue + key = hashlib.sha256(repr((limits, [line for _, line in decoded])).encode()).digest() + if key in seen: + population["duplicate mesh programs"] += 1 + continue + seen.add(key) + yield signed_branches(decoded), limits + + return _iter_programs() def table(title, rows, header="Programs"): @@ -307,20 +331,27 @@ def render(c, population): return "\n".join(out[1:]) + "\n" -def main(argv=None): +def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("directory", type=Path) backend = parser.add_mutually_exclusive_group(required=True) backend.add_argument("--llvm", help="LLVM C library with the AMDGPU disassembler") backend.add_argument("--llvm-mc", help="llvm-mc with the AMDGPU target") args = parser.parse_args(argv) - if args.llvm_mc: - use_llvm_mc(args.llvm_mc) - population = Counter() - counters = census(read_programs(args.directory, population, args.llvm or args.llvm_mc)) - sys.stdout.write(render(counters, population)) + try: + _validate_directory(args.directory) + _validate_backend("--llvm", args.llvm) + _validate_backend("--llvm-mc", args.llvm_mc) + if args.llvm_mc is not None: + use_llvm_mc(args.llvm_mc) + population = Counter() + counters = census(read_programs(args.directory, population, args.llvm or args.llvm_mc)) + report = render(counters, population) + except (OSError, ValueError, struct.error) as error: + parser.exit(1, f"mesh_loop_census: {error}\n") + sys.stdout.write(report) return 0 if __name__ == "__main__": - sys.exit(main()) + raise SystemExit(main()) From 8f045aee62143bbfca2e3ba67b60b88b40eba7ef Mon Sep 17 00:00:00 2001 From: Jess Doit <86271385+Jess-Doit@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:37:54 -0800 Subject: [PATCH 189/232] shader: lower gfx1013 DWORD buffer atomics (#1684) Lowers 32-bit MUBUF buffer_atomic_add, umax and cmpswap in the gfx1013 compute translator to InterlockedAdd, InterlockedMax and InterlockedCompareExchange on the raw UAV, one atomic per program, and refuses every other 32-bit MUBUF atomic. The LLVM 15 words are recorded for the fixtures, and the width gate is pinned with defined 64-bit data. Co-authored-by: Claude Opus 5.5 Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 5 + README.md | 1 + docs/experiments.md | 41 +++++ tests/compute_buffer_atomic_add.s | 11 ++ tests/compute_buffer_atomic_cmpswap.s | 17 ++ tests/compute_buffer_atomics_check.py | 244 ++++++++++++++++++++++++++ tools/compute_store_aot.py | 106 ++++++++--- 9 files changed, 403 insertions(+), 25 deletions(-) create mode 100644 tests/compute_buffer_atomic_add.s create mode 100644 tests/compute_buffer_atomic_cmpswap.s create mode 100644 tests/compute_buffer_atomics_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 25e5ceefd..1837fd411 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -41,6 +41,7 @@ jobs: SPIRV = ["spirv-as", "spirv-val", "spirv-cross"] CHECKS = [ (["tests/compute_store_check.py", *COMMON_LLVM], {}), + (["tests/compute_buffer_atomics_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_load_format_check.py", *COMMON_LLVM], {}), (["tests/compute_heap_view_check.py", *COMMON_LLVM], {}), (["tests/compute_heap_store_check.py", *COMMON_LLVM], {}), @@ -307,6 +308,7 @@ jobs: tests/startup_stream_interface_check.py \ tests/compute_alu_cmp_ne_check.py \ tests/compute_entry_layout_check.py \ + tests/compute_buffer_atomics_check.py \ tests/compute_alu_bcnt64_check.py \ tests/compute_load_format_check.py \ tests/compute_heap_view_check.py \ diff --git a/AGENTS.md b/AGENTS.md index c2cea0b61..6bcd9cd28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -216,6 +216,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_stream_interface_check.py ./out/pe-env/bin/python -B tests/compute_alu_cmp_ne_check.py ./out/pe-env/bin/python -B tests/compute_entry_layout_check.py +./out/pe-env/bin/python -B tests/compute_buffer_atomics_check.py ./out/pe-env/bin/python -B tests/compute_alu_bcnt64_check.py ./out/pe-env/bin/python -B tests/compute_load_format_check.py ./out/pe-env/bin/python -B tests/compute_heap_view_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 54b590bd6..ab6f8d14c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8979,6 +8979,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(compute_store_aot_mubuf_reduction_${adapter} PROPERTIES TIMEOUT 45 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_mubuf_reduction_${adapter}.txt") + add_test(NAME compute_store_aot_gfx1013_buffer_atomics_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_buffer_atomics_check.py" --draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(compute_store_aot_gfx1013_buffer_atomics_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_buffer_atomics_${adapter}.txt") add_test(NAME compute_store_aot_alu_minmax3_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_alu_minmax3_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter}) diff --git a/README.md b/README.md index 3b0ccf646..cfa6e4579 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 conditional atomic subtract | Lower [fixed-address `buffer_atomic_csub`](docs/experiments.md#gfx1030-fixed-address-mubuf-conditional-subtract) when the program discards the old value. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_csub_'` | | gfx1030 atomic buffer float min/max | Lower [fixed-address `buffer_atomic_fmin`/`fmax`](docs/experiments.md#gfx1030-fixed-address-mubuf-float-minmax) under the caller's finite-normal domain and verify the folded word against a CPU float reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_float_'` | | gfx1030 atomic buffer counters | Lower [fixed-address MUBUF bounded increment and decrement](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-counters) for 32 and 64 bits. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_counter'` | +| gfx1013 32-bit buffer atomics | Lower [raw UAV add, unsigned max and compare-swap](docs/experiments.md#gfx1013-32-bit-mubuf-buffer-atomics) and check old-value returns and contended add serialization. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_buffer_atomics_'` | | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | | gfx1013 float image stores | Lower [full-mask 2D RGBA32 FLOAT stores and explicit-mip SRV reads](docs/experiments.md#gfx1013-2d-float-image-stores-and-mip-loads) [D16 stores to RGBA16 FLOAT](docs/experiments.md#gfx1013-2d-d16-float-image-stores) and [same-texel UAV loads](docs/experiments.md#gfx1013-same-texel-uav-loads). Compare all three destination mips, including untouched texels. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_(store\|uav_load)_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 240a0ab98..174fbe767 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -5593,6 +5593,47 @@ ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_subword_' -V python3 -B tests/compute_store_check.py binary llvm-mc-15 llvm-objcopy-15 libLLVM-15.so.1 ``` +### gfx1013 32-bit MUBUF buffer atomics + +The raw UAV profile lowers one unguarded `buffer_atomic_add`, +`buffer_atomic_umax` or `buffer_atomic_cmpswap` through `u0` on gfx1013. +Use `off` for a shared DWORD, `offen` with a verified shifted dispatch ID, +or `idxen` with a verified dispatch ID and the declared byte stride. +The descriptor must be ready at `lgkmcnt(0)`. Supply a linear, aligned raw +UAV without thread-ID addition. The caller guarantees in-range addresses +without wrap and a dispatch of one group on unused axes. + +`glc` places the old DWORD into the first data VGPR, available after +`s_waitcnt vmcnt(0)`. Compare-swap reads replacement from VDATA and +compare from VDATA+1, then passes compare before replacement to HLSL. +VDATA+1 still holds the comparison word after the wait. +[AMD RDNA 2 Shader ISA, MUBUF opcode 49](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) + +The result can be written by a later plain DWORD store. Use disjoint +fields of the same per-lane address layout, or put every return record +above the fixed shared word. Without `glc`, the profile accepts an +unused data VGPR and requires an explicit rewrite before consuming +that register. It refuses `_x2`, other atomic operations, a source +SRV used as an atomic destination, and indexed plus offset addressing. + +The fixtures compare all 320 UAV words per dispatch. They cover separate +add and unsigned max destinations, max without `glc`, compare-swap hits +and misses, and 32 lanes adding different operands into one shared DWORD. +The shared trace pairs each lane's returned DWORD with its operand and +reconstructs every transition from the initial value to the exact total. +Untouched words retain their patterned sentinels. Replacing add with OR +and replacing the old-value record with the addend each change the readback. + +```powershell +cmake --build --preset dev --target offscreen_check -j 2 +ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_gfx1013_buffer_atomics_(warp|hardware)$' -V +``` + +```sh +python3 -B tests/compute_buffer_atomics_check.py +python3 -B tests/compute_buffer_atomics_check.py --binary llvm-mc-15 llvm-objcopy-15 --llvm libLLVM-15.so.1 +``` + ### gfx1030 fixed-address MUBUF atomic reductions The compute store profile lowers one non-returning 32-bit MUBUF atomic diff --git a/tests/compute_buffer_atomic_add.s b/tests/compute_buffer_atomic_add.s new file mode 100644 index 000000000..7e2a519af --- /dev/null +++ b/tests/compute_buffer_atomic_add.s @@ -0,0 +1,11 @@ +s_mov_b32 s20, s7 +s_mov_b32 s21, 0 +s_load_dwordx4 s[24:27], s[20:21], 0x30 +v_lshl_add_u32 v0, s10, 5, v0 +v_lshlrev_b32_e32 v2, 3, v0 +v_add_nc_u32_e32 v4, 1, v0 +s_waitcnt lgkmcnt(0) +buffer_atomic_add v4, v2, s[24:27], 0 offen glc +s_waitcnt vmcnt(0) +buffer_store_dword v4, v2, s[24:27], 0 offen offset:4 +s_endpgm diff --git a/tests/compute_buffer_atomic_cmpswap.s b/tests/compute_buffer_atomic_cmpswap.s new file mode 100644 index 000000000..c49bcc810 --- /dev/null +++ b/tests/compute_buffer_atomic_cmpswap.s @@ -0,0 +1,17 @@ +s_mov_b32 s20, s7 +s_mov_b32 s21, 0 +s_load_dwordx4 s[24:27], s[20:21], 0x30 +v_lshl_add_u32 v0, s10, 5, v0 +v_or_b32_e32 v4, 0x12340000, v0 +v_mul_lo_u32 v5, v0, 4 +v_add_nc_u32_e32 v5, 1, v5 +v_mul_lo_u32 v5, v5, 0x9e3779b1 +v_or_b32_e32 v5, 1, v5 +v_and_b32_e32 v6, 1, v0 +v_xor_b32_e32 v5, v6, v5 +s_waitcnt lgkmcnt(0) +buffer_atomic_cmpswap v[4:5], v0, s[24:27], 0 idxen glc +s_waitcnt vmcnt(0) +buffer_store_dword v4, v0, s[24:27], 0 idxen offset:4 +buffer_store_dword v5, v0, s[24:27], 0 idxen offset:8 +s_endpgm diff --git a/tests/compute_buffer_atomics_check.py b/tests/compute_buffer_atomics_check.py new file mode 100644 index 000000000..861210495 --- /dev/null +++ b/tests/compute_buffer_atomics_check.py @@ -0,0 +1,244 @@ +"""Check gfx1013 DWORD buffer atomics against a raw UAV readback.""" +import argparse +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import aot, assemble, disassemble, rejects, store_container, variant + +HERE = Path(__file__).resolve().parent +ADD = (HERE / "compute_buffer_atomic_add.s").read_text(encoding="ascii").splitlines() +CAS = (HERE / "compute_buffer_atomic_cmpswap.s").read_text(encoding="ascii").splitlines() +ADD_ATOMIC = next(line for line in ADD if line.startswith("buffer_atomic_add")) +ADD_RECORD = next(line for line in ADD if line.startswith("buffer_store_dword")) +SHIFT = "v_lshlrev_b32_e32 v2, 3, v0" +WAIT = "s_waitcnt vmcnt(0)" +INDEX_RECORD = ADD_RECORD.replace("v2,", "v0,").replace("offen", "idxen") +MAX_ATOMIC = "buffer_atomic_umax v4, v0, s[24:27], 0 idxen glc" +MAX = variant(ADD, (SHIFT, ""), ("v_add_nc_u32_e32 v4, 1, v0", "v_mov_b32_e32 v4, 0x80012345"), + (ADD_ATOMIC, MAX_ATOMIC), (ADD_RECORD, INDEX_RECORD)) +MAX_NO_GLC = variant(MAX, (MAX_ATOMIC, MAX_ATOMIC.removesuffix(" glc")), (WAIT, ""), (INDEX_RECORD, "")) +SHARED = variant(ADD, (SHIFT, ""), (ADD_ATOMIC, "buffer_atomic_add v4, off, s[24:27], 0 glc"), + (ADD_RECORD, INDEX_RECORD)) +PREFIX = "070394be 800395be 0a0608f4300000fa 000046d70a0a0104 " +CASES = { + "add_offen": (ADD, 8, "83000434 8100084a 7fc08cbf 0050c8e002040680 703f8cbf 041070e002040680"), + "umax_idxen": (MAX, 8, "ff02087e45230180 7fc08cbf 0060e0e000040680 703f8cbf 042070e000040680"), + "umax_no_glc": (MAX_NO_GLC, 8, "ff02087e45230180 7fc08cbf 0020e0e000040680"), + "shared_add": (SHARED, 8, "8100084a 7fc08cbf 0040c8e000040680 703f8cbf 042070e000040680"), + "cmpswap": (CAS, 16, "ff00083800003412 050069d500090100 810a0a4a 050069d505ff0100b179379e " + "810a0a38 81000c36 060b0a3a 7fc08cbf 0060c4e000040680 703f8cbf 042070e000040680 082070e000050680"), +} +GROUP = (32, 1, 1) +LANES = GROUP[0] +DWORDS = 320 +WORD_MASK = 0xFFFFFFFF +BINDING = dict(table_reg=7, group_reg=10, descriptor_offset=0x30) + + +def controls(): + rejected = ( + (ADD_ATOMIC, ADD_ATOMIC.removesuffix(" glc"), "Store data is not a known word"), + (WAIT, "", "before s_waitcnt vmcnt(0)"), + (WAIT, "s_waitcnt lgkmcnt(0)", "before s_waitcnt vmcnt(0)"), + (WAIT, "v_mov_b32_e32 v8, v4\n" + WAIT, "before s_waitcnt vmcnt(0)"), + (ADD_RECORD, ADD_RECORD.removesuffix(" offset:4"), "Overlapping raw UAV stores"), + (ADD_ATOMIC, ADD_ATOMIC.replace("v2,", "v0,"), "Unverified per-thread atomic address"), + (SHIFT, SHIFT.replace(", 3,", ", 31,"), "Unverified per-thread atomic address"), + ) + for old, new, message in rejected: + rejects(message, aot.lower, variant(ADD, (old, new)), GROUP, **BINDING, stride=8) + # Every other 32-bit MUBUF atomic the gfx1030 profile knows stays refused on gfx1013. + refused_ops = sorted(set(aot.MUBUF_ATOMIC_METHODS) - {"add", "umax", "cmpswap"}) + assert {"sub", "smin", "umin", "smax", "and", "or", "xor", "swap", "inc", "dec", "csub"} <= set(refused_ops) + for op in refused_ops: + rejects("require 32-bit add, umax or cmpswap", aot.lower, + variant(ADD, (ADD_ATOMIC, ADD_ATOMIC.replace("atomic_add", f"atomic_{op}"))), + GROUP, **BINDING, stride=8) + # The 64-bit forms of the accepted ops, with every data VGPR defined, so only the width gate can refuse them. + defined = "v_add_nc_u32_e32 v4, 1, v0\n" + "\n".join(f"v_mov_b32_e32 v{r}, {r}" for r in (5, 6, 7)) + for op, data in (("add", "v[4:5]"), ("umax", "v[4:5]"), ("cmpswap", "v[4:7]")): + rejects("require 32-bit add, umax or cmpswap", aot.lower, + variant(ADD, ("v_add_nc_u32_e32 v4, 1, v0", defined), + (ADD_ATOMIC, ADD_ATOMIC.replace("buffer_atomic_add v4", f"buffer_atomic_{op}_x2 {data}"))), + GROUP, **BINDING, stride=8) + srv_atomic =variant(ADD, (ADD_ATOMIC, ADD_ATOMIC.replace("s[24:27]", "s[28:31]")), + ("s_waitcnt lgkmcnt(0)", "s_load_dwordx4 s[28:31], s[20:21], 0x40\ns_waitcnt lgkmcnt(0)")) + rejects("Unverified atomic reduction descriptor", aot.lower, srv_atomic, GROUP, + **BINDING, stride=8, source_descriptor=0x40) + rejects("Return record can overlap the fixed atomic address", aot.lower, + variant(SHARED, (INDEX_RECORD, INDEX_RECORD.removesuffix(" offset:4"))), GROUP, **BINDING, stride=8) + # The emitted text pins what only the Windows draw would otherwise show. + lowered = {name: aot.lower(lines, GROUP, **BINDING, stride=stride) for name, (lines, stride, _) in CASES.items()} + # cmpswap: VDATA (v4) is the replacement and VDATA+1 (v5) the compare; HLSL takes the compare first. + compare = "((0x00000001u & tid.x) ^ (0x00000001u | ((0x00000001u + (tid.x * 0x00000004u)) * 0x9e3779b1u)))" + assert (f"outputData.InterlockedCompareExchange(tid.x * 16u + 0u, {compare}, (0x12340000u | tid.x), atomicOld);" + in lowered["cmpswap"]), lowered["cmpswap"] + # glc returns the old value, and that value is what the record stores. + assert "outputData.InterlockedAdd((tid.x << 3u) + 0u, (0x00000001u + tid.x), atomicOld);" in lowered["add_offen"] + assert "outputData.Store((tid.x << 3u) + 4u, atomicOld);" in lowered["add_offen"] + # umax is the unsigned InterlockedMax, with and without glc. + assert (" uint atomicOld;\n outputData.InterlockedMax(tid.x * 8u + 0u, 0x80012345u, atomicOld);" + in lowered["umax_idxen"]), lowered["umax_idxen"] + assert (" uint ignoredAtomic;\n outputData.InterlockedMax(tid.x * 8u + 0u, 0x80012345u, ignoredAtomic);" + in lowered["umax_no_glc"]), lowered["umax_no_glc"] + # Without glc nothing is returned. + assert "atomicOld" not in lowered["umax_no_glc"] + # A nonzero per-thread offset reaches the address, here with the record moved to offset 0. + offset = aot.lower(variant(ADD, (ADD_ATOMIC, ADD_ATOMIC.replace("0 offen glc", "0 offen offset:4 glc")), + (ADD_RECORD, ADD_RECORD.replace(" offset:4", ""))), GROUP, **BINDING, stride=8) + assert "outputData.InterlockedAdd((tid.x << 3u) + 4u, (0x00000001u + tid.x), atomicOld);" in offset, offset + assert "outputData.Store((tid.x << 3u) + 0u, atomicOld);" in offset, offset + # A lane guard before or after the atomic is refused. + guard = "v_cmp_gt_u32_e32 vcc_lo, 16, v0\ns_and_saveexec_b32 s30, vcc_lo" + rejects("gfx1013 requires an unguarded raw-buffer program", aot.lower, + variant(ADD, (ADD_ATOMIC, guard + "\n" + ADD_ATOMIC)), GROUP, **BINDING, stride=8) + rejects("gfx1013 buffer atomics require an unguarded program", aot.lower, + variant(ADD, (ADD_ATOMIC, ADD_ATOMIC + "\n" + guard)), GROUP, **BINDING, stride=8) + check_serialization_control() + print("gfx1013 atomic translation and serialization controls passed", flush=True) + + +def binary(directory, assembler, objcopy, library, name, lines, stride, recorded, source): + code = assemble(directory, assembler, objcopy, lines) + assert code == bytes.fromhex(PREFIX + recorded + " 000081bf"), f"{name}: machine words differ ({code.hex()})" + print(f"{name}: gfx1013 machine words match llvm-mc", flush=True) + if not library: + return + decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=b"gfx1013")) + assert aot.lower(decoded, GROUP, **BINDING, stride=stride) == source + container, output = directory / f"{name}.dxbc", directory / f"{name}-cli.hlsl" + container.write_bytes(store_container(code, GROUP)) + options = [arg for key, value in (BINDING | {"stride": stride}).items() + for arg in ("--" + key.replace("_", "-"), str(value))] + subprocess.run([sys.executable, "-B", aot.__file__, container, "--output", output, "--llvm", library, + *options], check=True) + assert output.read_text() == source + + +def fill_word(index): + # The raw UAV dump harness starts with a distinct deterministic sentinel per word. + return (((index + 1) * 0x9E3779B1) | 1) & WORD_MASK + + +def reference(name): + words = [fill_word(index) for index in range(DWORDS)] + if name == "shared_add": + words[0] += sum(range(1, LANES + 1)) + words[1:2 * LANES:2] = [None] * LANES # checked by the serialization oracle + return words + for lane in range(LANES): + index = lane * (4 if name == "cmpswap" else 2) + old = words[index] + if name == "cmpswap": + compare = old ^ (lane & 1) + words[index] = (0x12340000 | lane) if compare == old else old + words[index + 2] = compare # VDATA+1 retains its input after the GLC result. + elif name == "add_offen": + words[index] = (old + lane + 1) & WORD_MASK + else: + words[index] = max(old, 0x80012345) + if name != "umax_no_glc": + words[index + 1] = old + return words + + +def check_serialization(old_values, final): + # Each lane adds a different strictly positive value and the total cannot wrap. + # Sorting the (old value, lane operand) pairs therefore gives the only possible + # order of this observed trace. Reconstruct each edge rather than assuming lane order. + current = fill_word(0) + for old, operand in sorted((old, lane + 1) for lane, old in enumerate(old_values)): + assert old == current, f"shared add trace breaks at operand {operand}: {old:08x} != {current:08x}" + current += operand + assert current == final, f"shared add trace ends at {current:08x}, UAV has {final:08x}" + + +def check_serialization_control(): + old_values, current = [0] * LANES, fill_word(0) + for lane in reversed(range(LANES)): + old_values[lane] = current + current += lane + 1 + check_serialization(old_values, current) + # The sorted old values still look the same, but two now belong to the wrong lanes. + old_values[0], old_values[1] = old_values[1], old_values[0] + try: + check_serialization(old_values, current) + except AssertionError: + return + raise AssertionError("The serialization oracle accepted a scrambled lane/operand pair") + + +def draw(directory, dxc, renderer, adapter, name, source): + expected = reference(name) + variants = [("translated", source, None)] + if name == "add_offen": + variants += [ + ("add lowered as OR", source.replace("InterlockedAdd", "InterlockedOr"), + (0, 0x9E3779B2, 0x9E3779B1)), + ("record contains the addend", source.replace("+ 4u, atomicOld);", "+ 4u, tid.x + 1u);"), + (1, 0x9E3779B1, 1)), + ] + hlsl, cso, dump = (directory / f"{name}.{ext}" for ext in ("hlsl", "cso", "bin")) + for label, code, predicted in variants: + assert (code == source) == (predicted is None), label + hlsl.write_text(code, encoding="ascii") + subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) + result = subprocess.run([renderer, adapter, "--raw-uav-dump", cso, "1", str(4 * DWORDS), dump], + capture_output=True, text=True, timeout=15) + print(f"{name} {label}:\n{result.stdout}{result.stderr}", end="", flush=True) + if result.returncode == 77: + return 77 + result.check_returncode() + if "debug_layer=enabled" in result.stdout: + assert "debug_errors=0 debug_warnings=0" in result.stdout, name + actual = struct.unpack(f"<{DWORDS}I", dump.read_bytes()) + first = next(((i, want, got) for i, (want, got) in enumerate(zip(expected, actual, strict=True)) + if want is not None and want != got), None) + assert first == predicted, f"{name} {label}: first mismatch {first}, expected {predicted}" + if predicted is not None: + index, want, got = first + print(f"control caught at word {index}: expected={want:08x} actual={got:08x}", flush=True) + continue + if name == "shared_add": + check_serialization(actual[1:2 * LANES:2], actual[0]) + print(f"shared add: 32 old values serialize from {fill_word(0):08x} to {actual[0]:08x}", flush=True) + print(f"{name}: compared all {DWORDS} words", flush=True) + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--binary", nargs=2, metavar=("LLVM_MC", "LLVM_OBJCOPY")) + modes.add_argument("--draw", nargs=3, metavar=("DXC", "RENDERER", "ADAPTER")) + parser.add_argument("--llvm", metavar="LIBLLVM", help="Also check disassembly and the container CLI") + args = parser.parse_args() + controls() + if not (args.binary or args.draw): + for lines, stride, _ in CASES.values(): + aot.lower(lines, GROUP, **BINDING, stride=stride) + return 0 + out = HERE.parent / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compute_buffer_atomics_", dir=out) as tmp: + directory = Path(tmp) + for name, (lines, stride, words) in CASES.items(): + source = aot.lower(lines, GROUP, **BINDING, stride=stride) + if args.binary: + binary(directory, *args.binary, args.llvm, name, lines, stride, words, source) + elif draw(directory, *args.draw, name, source) == 77: + return 77 + if args.draw and (record := os.environ.get("FORM_COVERAGE_RECORD")): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + accepted = {line.split()[0] for lines, _, _ in CASES.values() for line in lines} + path.write_text("".join(f"{op}\n" for op in sorted(accepted)), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index d2a2e57f5..ed5140888 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -592,6 +592,20 @@ def descriptor_store_hlsl(): ) +def linear_uav_address(tag, dims, idxen, offen, stride, offset, size): + """Address one lane's field within an indexed or shifted dispatch element.""" + if not isinstance(tag, tuple): + return None + if idxen and not offen and tag[0] == "thread" and stride is not None and offset + size <= stride: + axis = tag[1] + return ("index", axis), axis, f"tid.{AXES[axis]} * {stride}u + {offset}u" + if offen and not idxen and tag[0] == "thread_bytes": + _, axis, shift = tag + if 2 <= shift <= 31 and offset + size <= 1 << shift and dims[axis] << shift <= 1 << 32: + return ("byte_offset", axis, shift), axis, f"(tid.{AXES[axis]} << {shift}u) + {offset}u" + return None + + def descriptor_load_hlsl(): """One load function shared by every descriptor-format buffer_load_format opcode. @@ -978,7 +992,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N scalar[reg] = ("group", axis) vector = {axis: ("local", axis) for axis in range(local_axes) if axis == 0 or dims[axis] > 1} pending = set() - # VGPRs a buffer read still writes, with the word they receive (None when unknown); + # Pending VMEM results, with the word they receive (None when unknown); # they enter vector only at s_waitcnt vmcnt(0). loading = {} stores = [] @@ -986,6 +1000,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N format_store_index = 0 atomic_update = False buffer_float_update = False + shared_atomic_offset = None # DS operations and image loads can consume each other's temporaries. Keep them in instruction order. staged_steps = [] ds_step_count = 0 @@ -1124,6 +1139,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N else: scalar[sdst_reg] = ("cond", cond_expr) elif m := re.fullmatch(r"s_and_saveexec_b32 s(\d+), vcc_lo", line): + if cpu == "gfx1013" and atomic_update: + raise ValueError("gfx1013 buffer atomics require an unguarded program") saved = int(m[1]) if vcc == ("invalid",) and guard_span is None and saved <= 105 and saved not in pending: raise ValueError("Unverified lane guard compare") @@ -2719,28 +2736,58 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N reg = first + index vector.pop(reg, None) loading[reg] = ("alu", f"{name}.{component}") - elif m := re.fullmatch(rf"buffer_atomic_({'|'.join(MUBUF_ATOMIC_METHODS)})(_x2)? " - r"(v\d+|v\[\d+:\d+\]), off, s\[(\d+):(\d+)\], 0(?: offset:(\d+))?( glc)?", line): - if cpu != "gfx1030" or stride is not None or output_format is not None or image_output: + elif m := re.fullmatch(rf"buffer_atomic_(?P{'|'.join(MUBUF_ATOMIC_METHODS)})(?P_x2)? " + r"(?Pv\d+|v\[\d+:\d+\]), (?Poff|v\d+|v\[\d+:\d+\]), " + r"s\[(?P\d+):(?P\d+)\], 0" + r"(?P idxen)?(?P offen)?(?: offset:(?P\d+))?(?P glc)?", line): + op, wide, glc = m["op"], bool(m["wide"]), bool(m["glc"]) + fixed = m["addr"] == "off" and not (m["idxen"] or m["offen"]) + if cpu == "gfx1030" and not fixed: + raise ValueError(f"Unsupported compute instruction: {line}") + if output_format is not None or image_output or (cpu == "gfx1030" and stride is not None): raise ValueError("Unsupported atomic reduction target or binding") + # One atomic per program, and no UAV write before it. The atomic itself is appended to + # stores, so a second atomic is refused here too. That keeps the single atomicOld or + # ignoredAtomic declaration below unique. On gfx1013, plain DWORD stores of the + # returned value may follow it. if stores: raise ValueError("An atomic reduction must be the only UAV operation") - op, wide = m[1], bool(m[2]) - if op in ("fmin", "fmax") and (buffer_float_domain != "finite-normal" or wide or m[7]): - raise ValueError("buffer_atomic fmin/fmax require a finite-normal domain, " - "a single 32-bit operand and no glc") - if op == "csub" and (wide or not m[7]): - raise ValueError("Conditional subtract requires 32-bit glc") - if op != "csub" and m[7]: - raise ValueError(f"Unsupported compute instruction: {line}") - base, high = int(m[4]), int(m[5]) - offset = int(m[6] or 0) + if cpu == "gfx1013": + if wide or op not in ("add", "umax", "cmpswap"): + raise ValueError("Unsupported atomic reduction target or binding: " + "gfx1013 buffer atomics require 32-bit add, umax or cmpswap") + if guard_span is not None or image_descriptor is not None: + raise ValueError("Unsupported atomic reduction target or binding: " + "gfx1013 requires an unguarded raw-buffer program") + else: + if op in ("fmin", "fmax") and (buffer_float_domain != "finite-normal" or wide or glc): + raise ValueError("buffer_atomic fmin/fmax require a finite-normal domain, " + "a single 32-bit operand and no glc") + if op == "csub" and (wide or not glc): + raise ValueError("Conditional subtract requires 32-bit glc") + if op != "csub" and glc: + raise ValueError(f"Unsupported compute instruction: {line}") + base, high = int(m["base"]), int(m["high"]) + offset = int(m["offset"] or 0) if (high != base + 3 or base % 4 or pending.intersection(range(base, high + 1)) or any(scalar.get(base + i) != ("uav", i) for i in range(4))): raise ValueError("Unverified atomic reduction descriptor") if offset > 4095 or offset % (8 if wide else 4): raise ValueError("Unverified atomic reduction address") - src, *last = map(int, re.findall(r"\d+", m[3])) + address = f"{offset}u" + if cpu == "gfx1013": + if fixed: + shared_atomic_offset = offset + else: + tag = vector.get(int(m["addr"][1:])) if re.fullmatch(r"v\d+", m["addr"]) else None + access = linear_uav_address(tag, dims, m["idxen"], m["offen"], stride, offset, 4) + if access is None: + raise ValueError("Unverified per-thread atomic address") + layout, axis, address = access + if any(dims[other] > 1 for other in range(3) if other != axis): + raise ValueError("Atomic address does not separate every invocation of the group") + written_spans.append((offset, offset + 4)) + src, *last = map(int, re.findall(r"\d+", m["data"])) width = 2 if wide else 1 count = 2 * width if op == "cmpswap" else width if last != ([src + count - 1] if count > 1 else []) or src + count > 256: @@ -2757,11 +2804,12 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N word = f"int64_t({word})" if wide else f"asint({word})" elif op == "sub": word = f"({'0ull' if wide else '0u'} - {word})" - # Both overloads discard the old value. Raw UAV atomics on pairs require SM 6.6. + # Raw UAV atomics on pairs require SM 6.6. kind = ("int64_t" if signed else "uint64_t") if wide else ("int" if signed else "uint") method = MUBUF_ATOMIC_METHODS[op] + ("64" if wide else "") if op == "cmpswap": - # The ISA places replacement before compare, unlike the HLSL argument order. + # RDNA 2 MUBUF opcode 49 takes replacement in VDATA and compare in VDATA+1. + # HLSL takes compare first. word = f"{operands[1]}, {word}" if op in ("fmin", "fmax"): # Raw-word finite-normal binary32 min/max on the raw UAV, under the caller's @@ -2786,8 +2834,15 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N f" outputData.Interlocked{method}({offset}u, expected, next, observed);", " } while (observed != expected);")) else: - stores.extend((f" {kind} ignoredAtomic;", - f" outputData.Interlocked{method}({offset}u, {word}, ignoredAtomic);")) + result = "atomicOld" if glc else "ignoredAtomic" + stores.extend((f" {kind} {result};", + f" outputData.Interlocked{method}({address}, {word}, {result});")) + if cpu == "gfx1013": + # Without GLC the source is unchanged. This profile refuses consumers of + # that register until an explicit rewrite instead of supplying an old value. + vector.pop(src, None) + if glc: + loading[src] = ("alu", result) atomic_update = True if op in ("fmin", "fmax"): buffer_float_update = True @@ -2797,7 +2852,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N r"s\[(?P\d+):(?P\d+)\], 0" r"(?(typed) format:\[(?PBUF_FMT_(?:(?:32_){1,4}|(?:16_){1,4})UINT)\])" r"(?P idxen)?(?P offen)?(?: offset:(?P\d+))?", line): - if atomic_update: + if atomic_update and (cpu == "gfx1030" or not line.startswith("buffer_store_dword ")): raise ValueError("An atomic reduction must be the only UAV operation") if image_output: raise ValueError("Buffer stores require a raw UAV binding") @@ -2872,6 +2927,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N addr = m["addr"] addr_regs = list(map(int, re.findall(r"\d+", addr))) tags = [vector.get(reg) for reg in addr_regs] + linear = (linear_uav_address(tags[0], dims, idxen, offen, stride, offset, span) + if heap_store_view is None and len(tags) == 1 and (idxen or atomic_update) else None) if heap_store_view is not None: if not formatted or len(tags) != 1 or not isinstance(tags[0], tuple) or tags[0][0] != "thread": raise ValueError("Heap store view needs a formatted store indexed by dispatch thread ID") @@ -2881,14 +2938,11 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N elif addr == "off" and not idxen and not offen and dims == (1, 1, 1) and stride is None: store_layout = ("fixed",) covered = set() - elif (stride is not None and idxen and not offen and len(addr_regs) == 1 - and isinstance(tags[0], tuple) and tags[0][0] == "thread" and offset + span <= stride): + elif linear is not None: # One index axis: every other group dimension must be one, so no two # invocations of a group share an address. - index = tags[0][1] - store_layout = ("index", index) + store_layout, index, address = linear covered = {index} - address = f"tid.{AXES[index]} * {stride}u + {offset}u" elif (stride is not None and idxen and offen and len(addr_regs) == 2 and addr_regs[1] == addr_regs[0] + 1 and all(isinstance(tag, tuple) for tag in tags) and tags[0][0] == "thread" and tags[1][0] == "thread_bytes" and tags[0][1] != tags[1][1]): @@ -2929,6 +2983,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N raise ValueError("Unsupported store address") if any(dims[axis] > 1 for axis in range(3) if axis not in covered): raise ValueError("Store address does not separate every invocation of the group") + if shared_atomic_offset is not None and (linear is None or offset <= shared_atomic_offset): + raise ValueError("Return record can overlap the fixed atomic address") if layout not in (None, store_layout): raise ValueError("Stores use different address layouts") layout = store_layout From bd53c9b68c7c85db3998c2ba5b44078272c4da94 Mon Sep 17 00:00:00 2001 From: thepatrickworld Date: Wed, 25 Nov 2026 22:48:52 +0100 Subject: [PATCH 190/232] startup: return the minimum of the three on v_med3_f32 with a NaN source (#2095) * startup: return the minimum of the three on v_med3_f32 with a NaN source * tests: supply the eight entry words the med3 draw fixture declares * Bump the startup shader cache revision to 16 for the med3 lowering * Update the readfirstlane uniformity fixture for the med3_32 helper rename * Bump the startup shader cache revision to 17 for the med3 lowering main moved to 16 through #2010, so this branch takes 17 and moves the compute key with it (17cs), as MasterDomino asked in #2095. --------- Co-authored-by: Panam Co-authored-by: root Co-authored-by: thepatrickworld Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: panam --- CMakeLists.txt | 13 + docs/experiments.md | 62 +++ docs/startup-runtime.md | 7 +- src/startup_stubs/d3d12_draw.inl | 4 +- tests/desktop_gpu.h | 3 + tests/offscreen_check.cpp | 42 ++ .../startup_compute_request_offline_check.py | 4 +- tests/startup_entry_words.cpp | 123 ++++++ tests/startup_gfx2hlsl_buffer_store_check.py | 4 +- tests/startup_gfx2hlsl_f32_med3_check.py | 379 ++++++++++++++++++ tests/startup_gfx2hlsl_fract_check.py | 8 +- ..._gfx2hlsl_readfirstlane_recompute_check.py | 2 +- ...up_gfx2hlsl_readfirstlane_uniform_check.py | 4 +- tests/startup_indirect_draw_indexed.cpp | 2 +- tests/startup_resource_retire_title.cpp | 2 +- tools/startup/gfx2hlsl.py | 15 +- 16 files changed, 652 insertions(+), 22 deletions(-) create mode 100644 tests/startup_entry_words.cpp create mode 100644 tests/startup_gfx2hlsl_f32_med3_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ab6f8d14c..f516c33ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1834,6 +1834,7 @@ endforeach() target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) +target_sources(offscreen_check PRIVATE tests/startup_entry_words.cpp) # The storage root handed to the executable ends in a separator and is never cut off # (src/startup_stubs/storage_root.h); the mutated run is the negative control. add_executable(startup_storage_root_check tests/startup_storage_root_check.cpp) @@ -3206,6 +3207,18 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: signed and unsigned three-source integer min, max and median. add_test(NAME startup_gfx2hlsl_int_med3_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_int_med3_check.py") + # v_med3_f32 with a NaN source is the minimum of the three (ISA p. 343): the preamble's med3_32 tests the + # encoding, the integer medians are unchanged, and the old branchless helper must be rejected. + add_test(NAME startup_gfx2hlsl_f32_med3_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f32_med3_check.py") + # The same four words drawn on WARP and the card, the NaN among them from the entry constants; the + # branchless lowering must mismatch on that lane. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_f32_med3_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f32_med3_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_f32_med3_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # Startup shader translator: s_cselect_b32 into the wave32 lane masks vcc_lo and exec_lo. add_test(NAME startup_gfx2hlsl_cselect_mask_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cselect_mask_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 174fbe767..c5519a4e4 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15381,6 +15381,68 @@ On Intel UHD Graphics (TGL GT1) with Mesa 26.2.7, DXC 1.10.2605.37 and SPIRV-Too python3 -B tests/pixel_denorm_vulkan_check.py /path/to/dxc tests/vk_pixel_draw.c --device Intel VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.json \ python3 -B tests/pixel_denorm_vulkan_check.py /path/to/dxc tests/vk_pixel_draw.c --device llvmpipe +## v_med3_f32 with a NaN source + +The RDNA 2 ISA defines `V_MED3_F32` (p. "343 V_MED3_F32") as a NaN branch first: + +``` +if (isNan(S0.f) || isNan(S1.f) || isNan(S2.f)) + D.f = V_MIN3_F32(S0.f, S1.f, S2.f); +else if (V_MAX3_F32(S0.f, S1.f, S2.f) == S0.f) + D.f = V_MAX_F32(S1.f, S2.f); +... +``` + +A NaN source therefore makes the result the smallest of the three. `tools/startup/gfx2hlsl.py` lowered +`v_med3_f32` to `max(min(a, b), min(max(a, b), c))`, which returns the larger of the non-NaN sources instead. +Drawn with `med3(a, 2.0, 1.0)` on a Radeon RX 9070 XT (driver `32.0.32029.2010`): + +| `a` | emitted form | ISA rule | +|---|---|---| +| NaN (`0x7fc00000`) | 2.0 | **1.0** | +| 3.0 | 2.0 | 2.0 | +| 1.5 | 1.5 | 1.5 | +| 0.5 | 1.0 | 1.0 | + +The only divergence is the NaN source. The table now points `v_med3_f32` at `med3_32`, whose body is the one +`tools/pixel_aot.py` already uses: + +```hlsl +float med3_32(float a, float b, float c) { + uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu); + return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c)); +} +``` + +The NaN test is on the encoding rather than on `isnan()`, because some desktop compilers fold float NaN +tests, and `min(min(a, b), c)` over operands whose sources D3D's `min()` keeps gives the smallest non-NaN +source. The integer medians (`v_med3_u32`, `v_med3_i32`) are untouched: they compare words and have no NaN. + +What the measurement establishes and what it does not: the emitted form rendered 2.0 on the card for a NaN +operand, and the ISA rule is the lower of the non-NaN sources. That the hardware instruction itself computes +`V_MIN3_F32` on a NaN source is **not** established here: HLSL cannot emit `v_med3_f32` (the compiler does not +select it from the median pattern), so the fixture compares the translated text against the ISA rule, not +against the instruction. Reading the instruction directly needs a captured shader or the ISA simulator. + +`tests/startup_gfx2hlsl_f32_med3_check.py` holds the controls and the draw. The controls read the emitted +HLSL: the preamble carries `med3_32` with the `0x7f800000u` threshold and the `asuint(x) & 0x7fffffffu` test, +the binary32 table points at it, both the bare and the `_e64` spellings lower to it, and the integer medians +keep their own lowering. Four mutations are rejected: the branchless helper, a `>=` threshold, an `isnan(` +test and a table pointing back at a helper without the branch. The `decode` mode builds +`v_med3_f32 v12, v1, v2, v3` as `0c0057d501050e04` and proves it with `tools/disasm_rdna2.py`. + +The draw is a source-built gfx1013 pair whose pixel stage moves the four entry constants s8..s11 into +s44..s47 and applies `v_med3_f32 v(12+lane), v1, v2, v3` with `v2 = 2.0` and `v3 = 1.0`. The inputs arrive as +root 32-bit constants written per draw by `offscreen_check --startup-entry-words`, not as literals: a literal +would be folded at compile time and the lowering under test would never run. The four inputs are +`0x7fc00000`, `0x40400000`, `0x3fc00000` and `0x3f000000`; the expected words are `0x3f800000`, +`0x40000000`, `0x3fc00000` and `0x3f800000`. The control that counts restores the branchless helper in the +same pair and requires a mismatch on the NaN lane alone: `0x40000000` where the ISA asks `0x3f800000`, the +other three lanes unchanged. A negative control that passes is reported as a failure, not accepted. + +```powershell +cmake --build --preset dev --target offscreen_check +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_f32_med3' -V ``` ## Vulkan draw of the core translated pixel shaders diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c70bbe8e6..473b5c8c9 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -204,10 +204,11 @@ The translation is refused when: - either header has another size; - the code reads an attribute the table does not list. -The shader cache revision is `x2w-startup-shader-16`. Earlier translations lower `v_fract_f32` -through a bare `frac` instead of the clamped `fract32` helper. The matching compute -(`x2w-startup-shader-16cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance +The shader cache revision is `x2w-startup-shader-17`. Earlier translations lower `v_med3_f32` through a +branchless median, which returns the smaller of the other two operands when a source is NaN. The matching +compute (`x2w-startup-shader-17cs`) and fixed slot 57 mesh (`x2w-startup-mesh-57-2`) keys advance because those stages use the shared lowering. +Revisions before 16 lower `v_fract_f32` through a bare `frac` instead of the clamped `fract32` helper. Revisions before 15 lower `v_cvt_pk_u8_f32` with a float clamp and accept `s_setreg_imm32_b32` writes of the rounding mode. Revisions before 14 evaluate constant `s_brev_b32` at run time instead of folding it into a known word. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2eefa8e18..1cf860745 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -244,7 +244,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* { // Keep pre-fix desktop bytecode and manifests out of this ABI's cache. // tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL. - constexpr char revision[] = "x2w-startup-shader-16"; + constexpr char revision[] = "x2w-startup-shader-17"; const u64 seed = fnv_bytes(revision, sizeof(revision) - 1); u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed))); // A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key. @@ -364,7 +364,7 @@ void publish_compute_request(const void* desc) std::vector fields(sizeof(words)); words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0; std::memcpy(fields.data(), words, sizeof(words)); - constexpr char compute_revision[] = "x2w-startup-shader-16cs"; // tools/startup/gfx2hlsl.py compute_key + constexpr char compute_revision[] = "x2w-startup-shader-17cs"; // tools/startup/gfx2hlsl.py compute_key u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1); const std::vector* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b}; for (const auto* part : order) key = fnv_part(*part, key); diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 63b23b2ce..75dc3e27b 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -35,6 +35,9 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con std::uint32_t* words, UINT width = 1, UINT height = 1, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE, UINT vertices = 3); +void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + const std::uint32_t* entry, UINT entry_count, std::uint32_t* words, + UINT width = 1, UINT height = 1); void dump_raw_uav(ID3D12Device* device, const char* shader_path, const char* groups, const char* bytes, const char* out_path); void check_spirv_window(ID3D12Device* device, const char* shader_path); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index e056d23dd..a62bf1872 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1488,6 +1488,47 @@ OperationResult run_startup_flat_param(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +// Comma-separated 8-digit hex words, in order. An empty list or any other shape returns nothing. +static std::vector parse_hex_words(std::string_view text) +{ + std::vector words; + while (!text.empty()) { + std::uint32_t value = 0; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value, 16); + if (parsed.ec != std::errc{} || parsed.ptr == text.data()) return {}; + words.push_back(value); + text.remove_prefix(std::size_t(parsed.ptr - text.data())); + if (text.empty()) break; + if (text.front() != ',') return {}; + text.remove_prefix(1); + } + return words; +} + +// --startup-entry-words : draws one pixel with a gfx2hlsl +// vertex and pixel pair that reads its operands from the entry constant buffer (tests/startup_entry_words.cpp). +// is 1..32 comma-separated 8-digit hex words, ud0 first; the translated vertex stage reads ud0 +// as its rectangle-list switch, so a plain triangle fixture keeps it 0. is the four words the +// target must hold, compared bit for bit. +OperationResult run_startup_entry_words(const OperationContext& ctx) +{ + const auto entry = parse_hex_words(ctx.argv[5]); + const auto expected = parse_hex_words(ctx.argv[6]); + if (entry.empty() || entry.size() > 32) + return {OutcomeKind::fail, "entry constants are not 1..32 hex words"}; + if (expected.size() != 4) + return {OutcomeKind::fail, "expected value is not four hex words"}; + std::uint32_t words[4]{}; + check_startup_entry_words(ctx.device, ctx.argv[3], ctx.argv[4], entry.data(), UINT(entry.size()), words); + if (std::memcmp(words, expected.data(), sizeof(words)) != 0) { + std::fprintf(stderr, "startup_entry_words mismatch expected=%08x,%08x,%08x,%08x " + "actual=%08x,%08x,%08x,%08x\n", + expected[0], expected[1], expected[2], expected[3], words[0], words[1], words[2], words[3]); + return {OutcomeKind::fail, "entry constant readback differs"}; + } + return {OutcomeKind::pass, nullptr}; +} + constexpr CapabilityGate kNoGate{}; constexpr CapabilityGate kGateSm60BufferOps{ D3D_SHADER_MODEL_6_0, false, false, 0, @@ -1609,6 +1650,7 @@ const OperationSpec kOperations[] = { {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, {"--startup-flat-param", 6, 6, nullptr, kNoGate, run_startup_flat_param}, + {"--startup-entry-words", 7, 7, nullptr, kNoGate, run_startup_entry_words}, {"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words}, {"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words}, // : whole raw UAV after one dispatch (#775 GVN parity). diff --git a/tests/startup_compute_request_offline_check.py b/tests/startup_compute_request_offline_check.py index 30e6e3c37..f57f4b28c 100644 --- a/tests/startup_compute_request_offline_check.py +++ b/tests/startup_compute_request_offline_check.py @@ -25,12 +25,12 @@ DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11) STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003) STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0) -KEY = 0x4db2818cb07558bf # framed key at revision 16cs +KEY = 0x8421b8080fd0a5e6 # framed key at revision 17cs def framed_key(): h = 1469598103934665603 - for b in b'x2w-startup-shader-16cs': + for b in b'x2w-startup-shader-17cs': h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B): for b in struct.pack(' +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { + +std::vector read_blob(const char* path) +{ + std::ifstream file(path, std::ios::binary); + std::vector bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + if (!file.good() && !file.eof()) throw std::runtime_error(std::string("Cannot read ") + path); + if (bytes.empty()) throw std::runtime_error(std::string("Empty shader ") + path); + return bytes; +} +} // namespace + +void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + const std::uint32_t* entry, UINT entry_count, std::uint32_t* words, + UINT width, UINT height) +{ + const auto vs = read_blob(vertex_path); + const auto ps = read_blob(pixel_path); + + D3D12_ROOT_PARAMETER param{}; + param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + param.Constants = {0, 0, entry_count}; + param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + D3D12_ROOT_SIGNATURE_DESC rs{}; + rs.NumParameters = 1; + rs.pParameters = ¶m; + ComPtr signature, errors; + if (FAILED(D3D12SerializeRootSignature(&rs, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &errors))) + throw std::runtime_error(errors ? static_cast(errors->GetBufferPointer()) + : "Serialize flat parameter root signature"); + ComPtr root; + check(device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&root)), + "Create flat parameter root signature"); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pd.SampleMask = UINT_MAX; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pd.SampleDesc.Count = 1; + ComPtr pipeline; + check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "Create flat parameter PSO"); + + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rd.Width = width; + rd.Height = height; + rd.DepthOrArraySize = 1; + rd.MipLevels = 1; + rd.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rd.SampleDesc.Count = 1; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {-1.0f, -1.0f, -1.0f, -1.0f}}; + const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 readback_size = 0; + device->GetCopyableFootprints(&rd, 0, 1, 0, &footprint, nullptr, nullptr, &readback_size); + const auto readback = make_buffer(device, readback_size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + ComPtr rtvs; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create flat parameter RTV heap"); + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv); + + ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto* list = commands.list.Get(); + list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); + list->SetGraphicsRootSignature(root.Get()); + list->SetGraphicsRoot32BitConstants(0, entry_count, entry, 0); + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, static_cast(width), static_cast(height)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION out{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + out.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION in{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr); + commands.submit_and_wait(device); + + void* mapped = nullptr; + const D3D12_RANGE read{0, static_cast(readback_size)}; + const D3D12_RANGE none{0, 0}; + check(readback->Map(0, &read, &mapped), "Map flat parameter readback"); + const auto* first = static_cast(mapped) + footprint.Offset; + for (UINT y = 0; y < height; ++y) { + std::memcpy(words + size_t(y) * width * 4, first + size_t(y) * footprint.Footprint.RowPitch, + size_t(width) * 4 * sizeof(*words)); + } + readback->Unmap(0, &none); + std::printf("startup_entry_words words=%08x,%08x,%08x,%08x\n", words[0], words[1], words[2], words[3]); +} diff --git a/tests/startup_gfx2hlsl_buffer_store_check.py b/tests/startup_gfx2hlsl_buffer_store_check.py index 38c427ceb..dd4e6a179 100644 --- a/tests/startup_gfx2hlsl_buffer_store_check.py +++ b/tests/startup_gfx2hlsl_buffer_store_check.py @@ -212,8 +212,8 @@ def main(): '%s %s' % (result, fail_reason(name))) # 8. The cache revision moved, so a translation from before the store lowering is never loaded. - check('cache key uses revision 16', G.pipeline_key(b'a', b'b', ROOT) == - G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-16'))))) + check('cache key uses revision 17', G.pipeline_key(b'a', b'b', ROOT) == + G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-17'))))) if failures: print('FAILED: ' + ', '.join(failures)) diff --git a/tests/startup_gfx2hlsl_f32_med3_check.py b/tests/startup_gfx2hlsl_f32_med3_check.py new file mode 100644 index 000000000..25fc58b0b --- /dev/null +++ b/tests/startup_gfx2hlsl_f32_med3_check.py @@ -0,0 +1,379 @@ +"""v_med3_f32 in tools/startup/gfx2hlsl.py: a NaN source is the minimum of the three (#2044). + + (no arguments) translation controls, pure Python + decode decode the fixture words with tools/disasm_rdna2.py and compare the text + binary reassemble the fixture sources and compare them with the words below + draw [fxc] + compile the translated pair with FXC vs_5_1/ps_5_1 when given and with DXC + vs_6_0/ps_6_0, draw one pixel and compare the four exported words; then the + branchless lowering must disagree on the NaN lane + (needs tests/offscreen_check.cpp built as offscreen_check) + +The RDNA 2 ISA defines V_MED3_F32 (\"343 V_MED3_F32\") as: + + if (isNan(S0.f) || isNan(S1.f) || isNan(S2.f)) D.f = V_MIN3_F32(S0.f, S1.f, S2.f); + else if (V_MAX3_F32(S0.f, S1.f, S2.f) == S0.f) D.f = V_MAX_F32(S1.f, S2.f); + ... + +A NaN source therefore makes the result the smallest of the three. The lowering used to emit +`max(min(a, b), min(max(a, b), c))`, which on a NaN source returns 2.0 for med3(NaN, 2.0, 1.0) where the ISA +returns 1.0: measured on an RX 9070 XT (driver 32.0.32029.2010) with a = NaN, 3.0, 1.5 and 0.5, the old form +gave 2.0, 2.0, 1.5, 1.0 and the ISA demands 1.0, 2.0, 1.5, 1.0. + +The table now points at `med3_32`, whose body is that of `tools/pixel_aot.py`: a NaN source is recognised on +the encoding (`asuint(x) & 0x7fffffffu > 0x7f800000u`) because a float `isnan()` may be folded away by the +compiler, and the result is `min(min(a, b), c)`, which D3D's min() reduces to the smallest non-NaN source. +The integer medians (`v_med3_u32`, `v_med3_i32`) are untouched: they have no NaN. + +What the measurement establishes and what it does not: the emitted text renders 2.0 on the card for a NaN +operand, and the ISA's rule is the lower of the non-NaN sources. That the hardware instruction itself +computes V_MIN3_F32 on a NaN source is **not** established by this fixture: HLSL has no way to emit +`v_med3_f32` (the compiler does not select it from the median pattern), so the draw compares the translated +text against the ISA rule, not against the instruction. This limit is recorded in docs/experiments.md. + +Controls, all on the emitted HLSL text (no compiler, no GPU): + - the preamble defines `med3_32` with the encoding test on all three sources, the `>` of `0x7f800000u` and + `min(min(a, b), c)` for the NaN branch; no line calls a `med3(` helper; + - the binary32 table points `v_med3_f32` at `med3_32` and the integer forms are unchanged; + - every lane of the fixture lowers to `U(med3_32(F(v1), F(v2), F(v3)))` reading s44..s47, which the entry + constant buffer fills at draw time; + - four mutations must be rejected: the old branchless helper, the threshold `>=`, an `isnan(` test, and a + table that points back at a helper without the branch. + +The draw fixture is a source-built pair. The vertex stage places a full-screen triangle and exports the +position only. The pixel stage moves the four entry constants s8..s11 into s44..s47, then for each lane +`v_mov_b32 v1, s44+lane`, `v_mov_b32 v2, 2.0`, `v_mov_b32 v3, 1.0` and `v_med3_f32 v(12+lane), v1, v2, v3`, +exporting the four words to mrt0. The constants are root 32-bit constants (the form +tools/startup/gfx2hlsl.py lowers a constant buffer to), written by the renderer per draw: a literal would be +folded at compile time and the lowering under test would never run. The four inputs are 0x7fc00000 (quiet +NaN), 0x40400000 (3.0), 0x3fc00000 (1.5) and 0x3f000000 (0.5); the expected words are 0x3f800000 (1.0), +0x40000000 (2.0), 0x3fc00000 (1.5) and 0x3f800000 (1.0). + +The control that counts: the branchless helper restored in the same pair must MISMATCH on the NaN lane, with +0x40000000 where the ISA asks 0x3f800000, and match the other three lanes. A draw whose negative control +passes proves nothing; this check reports that as a failure rather than accepting it. + +The instruction words are constructed here from the field layout the checked-in decoder reads +(`tools/disasm_rdna2.py`): VOP3A w0 = 0b110101 << 26 | opcode << 16 | vdst, w1 = src0 | src1 << 9 | src2 << 18, +with the VGPR codes 256+n; v_med3_f32 is opcode 0x157, so `v_med3_f32 v12, v1, v2, v3` is +0c0057d501050e04. The decode mode proves that with the repository decoder. +""" +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 +import disasm_rdna2 # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl # noqa: E402 + +SOP1_MOV_B32 = 0xbe800300 +VOP1_E32 = 0x7e000000 +VOP1_MOV_B32 = 0x01 +VGPR, LITERAL = 256, 255 +INLINE = {0x40000000: 0xf4, 0x3f800000: 0xf2} # 2.0 and 1.0, the coding llvm-mc picks for a float literal + +# The four inputs, then the four words the ISA rule gives for med3(a, 2.0, 1.0). +INPUTS = (0x7fc00000, 0x40400000, 0x3fc00000, 0x3f000000) +EXPECTED = (0x3f800000, 0x40000000, 0x3fc00000, 0x3f800000) +# The branchless lowering's NaN lane: max(min(a, b), min(max(a, b), c)) with a = NaN is 2.0. +BRANCHLESS_NAN = 0x40000000 + +MED3_32 = ('float med3_32(float a, float b, float c) {\n' + ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);\n' + ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));\n' + '}') +BRANCHLESS = 'float med3_32(float a, float b, float c) {\n return max(min(a, b), min(max(a, b), c));\n}' +OLD_ISNAN = ('float med3_32(float a, float b, float c) {\n' + ' return isnan(a) || isnan(b) || isnan(c) ? min(min(a, b), c)' + ' : max(min(a, b), min(max(a, b), c));\n}') + +failures = [] + + +def check(label, ok, detail=''): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH'), flush=True) + if not ok: + failures.append(label) + if detail: + print(' ' + detail) + + +# ---- the fixture ----------------------------------------------------------------------------------------------- +VS_SOURCE = ('v_mov_b32 v3, 0x40400000\n' + 'v_mov_b32 v10, 0xc0400000\n' + 'v_cmp_eq_u32 vcc_lo, 1, v0\n' + 'v_cndmask_b32 v1, -1.0, v3, vcc_lo\n' + 'v_cmp_eq_u32 vcc_lo, 2, v0\n' + 'v_cndmask_b32 v2, 1.0, v10, vcc_lo\n' + 'v_mov_b32 v4, 1.0\n' + 'v_mov_b32 v5, 0\n' + 'exp pos0 v1, v2, v5, v4 done\n' + 's_endpgm\n') +VS_WORDS = (bytes.fromhex('ff02067e00004040' 'ff02147e000040c0' '8100847d' 'f3060202' '8200847d' 'f2140402' + 'f202087e' '80020a7e') + + bytes.fromhex('cf0800f801020504' '000081bf')) +PS_EXPORT = bytes.fromhex('0f1800f80c0d0e0f000081bf') # exp mrt0 v12..v15 done vm ; s_endpgm + + +def sop1_mov_b32(sdst, ssrc0): + return struct.pack('=', lambda t: t.replace('top > 0x7f800000u', 'top >= 0x7f800000u')), + ('an isnan() test instead of the encoding test', lambda t: t.replace(MED3_32, OLD_ISNAN)), + ('the table pointing back at a helper without the branch', + lambda t: t.replace(STATEMENT % 12, 'v12 = U(med3(F(v1), F(v2), F(v3)));')), + ] + + +def check_mutations(): + hlsl = pipeline().hlsl_ps() + for label, mutate in mutations(hlsl): + changed = mutate(hlsl) + rejected = changed != hlsl + if rejected: + try: + check_text(changed) + except AssertionError: + pass + else: + rejected = False + check('%s is rejected' % label, rejected) + + +# ---- the words ------------------------------------------------------------------------------------------------ +def check_decode(): + decoded = disasm_rdna2.disassemble_binary(PS_WORDS) + assembly = [ins['assembly'] for ins in decoded] + assert assembly[0:4] == ['s_mov_b32 s%d, s%d' % (44 + lane, 8 + lane) for lane in range(4)], assembly[0:4] + for lane in range(4): + block = assembly[4 + 4 * lane:8 + 4 * lane] + assert block == ['v_mov_b32_e32 v1, s%d' % (44 + lane), 'v_mov_b32_e32 v2, 2.0', + 'v_mov_b32_e32 v3, 1.0', 'v_med3_f32 v%d, v1, v2, v3' % (12 + lane)], block + assert assembly[-2:] == ['exp mrt0 v12, v13, v14, v15 done vm', 's_endpgm'], assembly[-2:] + assert PS_WORDS[28:36].hex() == '0c0057d501050e04', PS_WORDS[28:36].hex() + print('the fixture decodes to s44..s47, v_med3_f32 on each lane and the mrt0 export') + + +def check_binary(llvm_mc): + for name, source, words in (('vertex', VS_SOURCE, VS_WORDS), ('pixel', PS_SOURCE, PS_WORDS)): + built = assemble(llvm_mc, source) + if built != words: + raise AssertionError('%s fixture: assembled %s, recorded %s' % (name, built.hex(), words.hex())) + print('fixture words match llvm-mc') + + +# ---- the draw ------------------------------------------------------------------------------------------------- +def draw(renderer, adapter, vs, ps, constants, expected): + """One pixel through offscreen_check --startup-entry-words; exit 77 (skip) propagates.""" + run = subprocess.run([renderer, adapter, '--startup-entry-words', str(vs), str(ps), constants, expected], + capture_output=True, text=True) + sys.stdout.write(run.stdout) + if run.returncode == 77: + print(run.stdout + run.stderr) + sys.exit(77) + return run + + +def actual_words(run): + """The four words the renderer reports as `actual=` in its mismatch line.""" + m = re.search(r'actual=([0-9a-f]{8}),([0-9a-f]{8}),([0-9a-f]{8}),([0-9a-f]{8})', run.stderr) + return [int(word, 16) for word in m.groups()] if m else None + + +def naive(hlsl): + """The branchless helper restored, the table still calling med3_32.""" + return hlsl.replace(MED3_32, BRANCHLESS) + + +def check_draw(dxc, renderer, adapter, fxc=None): + check_controls() + check_mutations() + check_decode() + if failures: + sys.exit(1) + # ud0 is the vertex stage's rectangle-list switch; the four inputs follow it and are what the pixel + # stage moves into s44..s47. The list is as long as the constant buffer both shaders declare. + translated = pipeline() + entry = [0] * entry_counts(translated.hlsl_vs(), translated.hlsl_ps()) + entry[1:1 + len(INPUTS)] = INPUTS + constants = words_text(entry) + expected = words_text(EXPECTED) + print('constants %s expected %s' % (constants, expected)) + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, pipeline().hlsl_vs(), 'vs_med3_%s' % kind, vs_profile, directory) + good = compile_hlsl(compiler, kind, pipeline().hlsl_ps(), 'ps_med3_%s' % kind, ps_profile, directory) + run = draw(renderer, adapter, vs, good, constants, expected) + if run.returncode: + raise AssertionError('%s translated pair, constants %s\n%s\n%s' + % (kind, constants, run.stdout, run.stderr)) + print('%s %s: %s' % (kind, adapter, expected), flush=True) + bad = compile_hlsl(compiler, kind, naive(pipeline().hlsl_ps()), 'ps_med3_bad_%s' % kind, + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, constants, expected) + actual = actual_words(run) + label = '%s branchless lowering on %s' % (kind, adapter) + if run.returncode == 0: + check('%s was accepted: the draw does not catch the defect' % label, False) + elif actual is None: + check('%s failed without an actual= line: %s' % (label, run.stderr.strip()), False) + else: + nan_lane = actual[0] == BRANCHLESS_NAN and EXPECTED[0] != BRANCHLESS_NAN + others = actual[1:] == list(EXPECTED[1:]) + check('%s mismatched on the NaN lane (%s) and matched the other three' + % (label, words_text(actual)), nan_lane and others) + if failures: + sys.exit(1) + + +def main(): + if len(sys.argv) == 1: + check_controls() + check_mutations() + check_decode() + if failures: + sys.exit(1) + return + mode, *args = sys.argv[1:] + if mode == 'decode': + check_decode() + elif mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tests/startup_gfx2hlsl_fract_check.py b/tests/startup_gfx2hlsl_fract_check.py index f5a1b7af0..de05a5e1f 100644 --- a/tests/startup_gfx2hlsl_fract_check.py +++ b/tests/startup_gfx2hlsl_fract_check.py @@ -170,8 +170,8 @@ def float_capped(word): repr((seed and seed.group(1), literal and literal.group(1)))) check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1), repr((seed and seed.group(1), literal and literal.group(1)))) -check('the revision is x2w-startup-shader-16, after the fix to the cap', - bool(seed and seed.group(1) == 'x2w-startup-shader-16'), repr(seed and seed.group(1))) +check('the revision is x2w-startup-shader-17, after the fix to the cap', + bool(seed and seed.group(1) == 'x2w-startup-shader-17'), repr(seed and seed.group(1))) def key_from_seed(word): @@ -183,8 +183,8 @@ def key_from_seed(word): check('pipeline_key hashes the seed the source spells', G.pipeline_key(b'vs', b'ps', b'root') == key_from_seed(seed.group(1)), '%016x vs %016x' % (G.pipeline_key(b'vs', b'ps', b'root'), key_from_seed(seed.group(1)))) - old, new = key_from_seed('x2w-startup-shader-15'), key_from_seed('x2w-startup-shader-16') - check('the -15 seed produces a different key, so the pre-fix entries are out of the cache', old != new, + old, new = key_from_seed('x2w-startup-shader-16'), key_from_seed('x2w-startup-shader-17') + check('the -16 seed produces a different key, so the pre-fix entries are out of the cache', old != new, '%016x vs %016x' % (old, new)) if failures: diff --git a/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py b/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py index 9e4f0c2f5..538adf789 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_recompute_check.py @@ -81,7 +81,7 @@ def read_line(lines): 's_cbranch_scc1 label_0018', DEFINE, READ, 's_endpgm')), ] EXPECTED = {'chain through a second VGPR': 's9 = U(F((s3)) * 2.0);', - 'median of three after a join': 's9 = U(med3(F(s3), F(0x00000000u), 0.5));'} + 'median of three after a join': 's9 = U(med3_32(F(s3), F(0x00000000u), 0.5));'} for label, instructions in ACCEPTED: got = run(*instructions) want = EXPECTED.get(label, RECOMPUTED) diff --git a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py index eef935483..b1fb5ee6f 100644 --- a/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py +++ b/tests/startup_gfx2hlsl_readfirstlane_uniform_check.py @@ -81,9 +81,9 @@ def run(*instructions, exec_known=True): ['v7 = U(1.0 / F(s2));']), # The clamp to [0, 0.5] of a scalar, as compiled shaders write it. ('median of three', ('v_med3_f32 v7, s2, 0, 0.5',), - ['v7 = U(med3(F(s2), F(0x00000000u), 0.5));']), + ['v7 = U(med3_32(F(s2), F(0x00000000u), 0.5));']), ('median of three scalar sources', ('v_med3_f32 v7, s2, -s3, |s2| clamp',), - ['v7 = U(saturate(med3(F(s2), (-F(s3)), abs(F(s2)))));']), + ['v7 = U(saturate(med3_32(F(s2), (-F(s3)), abs(F(s2)))));']), ('move', ('v_mov_b32_e32 v7, s2',), ['v7 = s2;']), ('literal move', ('v_mov_b32_e32 v7, 0x1234',), ['v7 = 0x00001234u;']), ('chain with an in-place write', ('v_mul_f32_e64 v7, s2, 2.0', 'v_cvt_u32_f32_e32 v7, v7'), diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index c4b91f264..234eb8c3b 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -295,7 +295,7 @@ ComPtr translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false) { // The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC. - constexpr char revision[] = "x2w-startup-shader-16"; + constexpr char revision[] = "x2w-startup-shader-17"; static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103}; static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204}; auto& vertex_id = vertex_ids[indexed ? 2 : needs_start]; diff --git a/tests/startup_resource_retire_title.cpp b/tests/startup_resource_retire_title.cpp index 0850645f7..fa6fbaf4c 100644 --- a/tests/startup_resource_retire_title.cpp +++ b/tests/startup_resource_retire_title.cpp @@ -371,7 +371,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel constexpr int draw_seed = 77; constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM -constexpr char draw_revision[] = "x2w-startup-shader-16"; // d3d12_draw.inl cached_translation +constexpr char draw_revision[] = "x2w-startup-shader-17"; // d3d12_draw.inl cached_translation constexpr char draw_vertex_shader[] = R"( struct Varying { float4 position : SV_Position; }; diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ec4a478c2..00fa3c759 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6129,7 +6129,7 @@ def declarations(self): 'v_exp_f32': (1, 'exp2({0})'), 'v_log_f32': (1, 'log2({0})'), 'v_floor_f32': (1, 'floor({0})'), 'v_ceil_f32': (1, 'ceil({0})'), 'v_trunc_f32': (1, 'trunc({0})'), 'v_fract_f32': (1, 'fract32({0})'), 'v_rndne_f32': (1, 'round({0})'), 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), - 'v_med3_f32': (3, 'med3({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), + 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), } # Conversions whose result is binary32. The expression is the float value, so an output modifier # (clamp, mul:2, mul:4, div:2) can wrap it the way it wraps any other float result. The uint-result @@ -6493,7 +6493,14 @@ def common(self): ' float f = frac(value);', ' return asuint(f) == 0x3f800000u ? asfloat(0x3f7fffffu) : f;', '}', - 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', + # v_med3_f32 with a NaN source is the minimum of the three (ISA "343 V_MED3_F32"), so the test is + # on the encoding: a float isnan() may be folded away by the compiler. D3D min() returns the + # other operand, so min(min(a, b), c) over a NaN source is the smallest of the non-NaN ones. + # Same body as med3_32 in tools/pixel_aot.py. + 'float med3_32(float a, float b, float c) {', + ' uint top = max(max(asuint(a) & 0x7fffffffu, asuint(b) & 0x7fffffffu), asuint(c) & 0x7fffffffu);', + ' return top > 0x7f800000u ? min(min(a, b), c) : max(min(a, b), min(max(a, b), c));', + '}', # High half of an unsigned 32x32 product, by halfword products so it fits 32-bit HLSL. 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' @@ -6924,7 +6931,7 @@ def fnv(data, h=1469598103934665603): def pipeline_key(vs_code, ps_code, root_blob, layout=b''): """Hash the startup translation revision and the three blobs in runtime order, then a stream's input layout.""" - key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-16')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-17')))) return fnv(layout, key) if layout else key @@ -6933,7 +6940,7 @@ def compute_key(cs_code, data, root_blob, desc, state_a=b'', state_b=b''): graphics revision followed by "cs", then each part preceded by its length as a little-endian u64: the code, the words 7-8 blob, the root signature, the 12 description words with their pointers zeroed and the two state blocks.""" - key = fnv(b'x2w-startup-shader-16cs') + key = fnv(b'x2w-startup-shader-17cs') for part in (cs_code, data, root_blob, desc, state_a, state_b): key = fnv(part, fnv(struct.pack(' Date: Wed, 25 Nov 2026 22:48:57 +0100 Subject: [PATCH 191/232] startup: accept slot 57 VCC branches on a wave-uniform compare (Part of #2413) (#2566) * startup: accept slot 57 VCC branches on a wave-uniform compare s_cbranch_vccz and s_cbranch_vccnz were refused outside the exchanges as a wave-wide condition. Accept them when every path reaching the branch last wrote VCC with a v_cmp under the full EXEC mask, no other VCC write follows, EXEC is still the full mask at the branch, and Stage proves the compare's sources wave-uniform (no VGPR, uniform SGPRs or constants). VCC is then all ones or all zeros, so the per-lane test equals the wave-wide one. Anything else stays refused. Tests: taken and not-taken vccz and vccnz branches, drawn on WARP and hardware against the CPU model; refusals for a VGPR compare, a narrowed EXEC at the branch, a VCC write between the compare and the branch, and a join where one path has no VCC definition. Part of #2413. AI-assisted. * tests: cover calls, s_cbranch_execnz and a jump over the count exchange Refusal controls for the slot 57 branch walk: s_call_b64 and s_swappc_b64 after the count exchange (indirect control flow), a forward s_cbranch_execnz (wave-wide condition), and an s_branch from between the exchanges to after the count exchange. Each is derived from an accepted fixture and checked to reach its own refusal. AI-assisted. * tests: refuse a VCC branch whose compare ran under a narrowed EXEC A uniform compare that writes VCC under a narrowed mask leaves the other lanes at 0, so restoring EXEC before the branch does not make VCC uniform. The control narrows EXEC with s_and_saveexec_b64, compares, restores EXEC to -1 and branches on vccz; it must stay refused. AI-assisted. * tests: refuse a VCC branch on a compare of an SGPR written before a join Stage proves each compare source with uniform_source. The VGPR control is also caught by mesh_vregs, so nothing pinned uniform_source itself: an SGPR written before the last join is not proven uniform and the VCC branch must stay refused. Reported in review of the pull request. AI-assisted. --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 7 +++ tests/startup_mesh57_skeleton_check.py | 66 ++++++++++++++++++++++++-- tools/startup/gfx2hlsl.py | 41 ++++++++++++++-- 3 files changed, 105 insertions(+), 9 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index c5519a4e4..eeae050ce 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9450,6 +9450,13 @@ and unproven wave masks remain unsupported. Use Append `draw ` for CPU-reference readback of the SCC paths and lane-masked if/else. +A forward `s_cbranch_vccz` or `s_cbranch_vccnz` can also branch on the +lane's VCC bit when EXEC is full and every incoming path last wrote VCC with +a full-EXEC `v_cmp_*` from wave-uniform SGPRs or constants. A compare with a +VGPR source, a different VCC write, or a narrowed EXEC at the branch +invalidates the proof. The CPU-reference draws cover both outcomes for each +branch polarity and a VCC-zero branch after a join. + Set `X2W_REFUSE_FIXED_MESH=1` to report unavailable fixed mesh pipelines at slot 57 creation. The descriptor must name a registered root, have an empty VS slot and have a readable 16-byte to 64-KiB MS span. The PS span must be diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 9e5dcca73..14c661f44 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -82,10 +82,30 @@ def masked_vertex_red(): return mesh[:at] + ['bf880004'] + mesh[at:] # s_cbranch_execz skips both vertex exports +# s_mov_b32 s40, 0.5; v_cmp_ge_f32_e64 vcc_lo, s40, 1.0 +VCC_COMPARE = 'bea803f0 d406006a 0001e428' + + BRANCH_CASES = ( # v_mov v7, 0; s_cmp_eq_i32 0, ; s_cbranch_scc1 .join; v_mov v7, 1.0 ('SCC branch taken', vertex_red('7e0e0280 bf008080 bf850001 7e0e02f2'), lambda lane: 0), ('SCC branch not taken', vertex_red('7e0e0280 bf008180 bf850001 7e0e02f2'), lambda lane: 255), + # v_mov v7, 0; set s40 and VCC as above; s_cbranch_vccz .join; v_mov v7, 1.0 + ('VCC-zero branch taken', vertex_red('7e0e0280 ' + VCC_COMPARE + ' bf860001 7e0e02f2'), lambda lane: 0), + # s_mov_b32 s40, 1.0 changes the compare result to true. + ('VCC-zero branch not taken', vertex_red('7e0e0280 bea803f2 d406006a 0001e428 bf860001 7e0e02f2'), + lambda lane: 255), + # The same false compare falls through for s_cbranch_vccnz. + ('VCC-nonzero branch not taken', vertex_red('7e0e0280 ' + VCC_COMPARE + ' bf870001 7e0e02f2'), + lambda lane: 255), + # s_mov_b32 s40, 1.0 makes s_cbranch_vccnz take .join. + ('VCC-nonzero branch taken', vertex_red('7e0e0280 bea803f2 d406006a 0001e428 bf870001 7e0e02f2'), + lambda lane: 0), + # s_cmp_eq_i32 0, 0; s_cbranch_scc1 .join skips a second uniform compare. + # .join: s_cbranch_vccz .done skips v_mov v7, 1.0 using the earlier compare. + ('VCC-zero branch after a join', + vertex_red('7e0e0280 ' + VCC_COMPARE + ' bf008080 bf850002 d406006a 0001e028 bf860001 7e0e02f2'), + lambda lane: 0), # v7 starts at 0.5. The then arm writes 1.0 for tid < 6, the else arm writes 0.0 for the remaining lanes. # v_cmp_gt_u32 vcc, 6, v0; s_and_saveexec_b64 s[20:21], vcc; s_cbranch_execz .empty # v_mov v7, 1.0; s_branch .else; .empty: s_nop; .else: s_andn2_b64 exec, s[20:21], exec @@ -149,14 +169,52 @@ def expect(what, got, want): 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), ('a branch over the group-index exchange', MESH[:1] + [branch(0xbf82, 1, GROUP_END + 1)] + MESH[1:], 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), + # s_branch .post_count replaces s_waitcnt lgkmcnt(0) between the exchanges. + ('a branch over the count exchange', + mutate('bf8cc07f', branch(0xbf82, MESH.index('bf8cc07f'), POST_COUNT)), + 'slot 57 mesh: a branch enters or crosses a group-memory exchange'), ('an indirect branch', mutate('bf8c3f70', 'be802014'), 'slot 57 mesh: indirect control flow (s_setpc_b64) is not covered'), - # s_cbranch_vccz .join replaces the post-count SCC branch and keeps its forward target. - ('a forward VCC-zero branch', mutate('bf850001', 'bf860001', mesh=BRANCH_CASES[0][1]), + # s_call_b64 s[20:21], 2 replaces s_waitcnt vmcnt(0) and targets the parameter export. + ('a call after the count exchange', mutate('bf8c3f70', 'bb140002'), + 'slot 57 mesh: indirect control flow (s_call_b64) is not covered'), + # s_swappc_b64 s[20:21], s[22:23] replaces s_waitcnt vmcnt(0). + ('a PC swap after the count exchange', mutate('bf8c3f70', 'be942116'), + 'slot 57 mesh: indirect control flow (s_swappc_b64) is not covered'), + # s_cbranch_execnz .join replaces s_cbranch_scc1 .join and keeps its forward target. + ('an EXEC-nonzero branch after the count exchange', mutate('bf850001', 'bf890001', mesh=BRANCH_CASES[0][1]), + 'slot 57 mesh: s_cbranch_execnz on a wave-wide condition is not covered'), + # v_cmp_ge_f32_e64 vcc_lo, v0, 1.0; s_cbranch_vccz .join; v_mov v7, 1.0 + ('a VCC-zero branch after a VGPR compare', + vertex_red('7e0e0280 d406006a 0001e500 bf860001 7e0e02f2'), + 'slot 57 mesh: s_cbranch_vccz on a wave-wide condition is not covered'), + # v_cmp_gt_u32_e32 vcc_lo, 6, v0 replaces VCC before s_cbranch_vccnz .join. + ('a VCC-nonzero branch after an intervening VCC write', + vertex_red('7e0e0280 ' + VCC_COMPARE + ' 7d880086 bf870001 7e0e02f2'), + 'slot 57 mesh: s_cbranch_vccnz on a wave-wide condition is not covered'), + # s_mov_b32 s40, 0.5; s_cmp_eq_i32 0, 0; s_cbranch_scc1 .join skips s_mov_b32 s40, 1.0; .join: the compare + # reads s40, written before the join, which Stage's uniform_source does not prove; s_cbranch_vccz skips s_nop. + ('a VCC compare on an SGPR written before a join', + MESH[:POST_COUNT] + ['bea803f0', 'bf008080', 'bf850001', 'bea803f2'] + VCC_COMPARE.split()[1:] + + ['bf860001', 'bf800000'] + MESH[POST_COUNT:], + 'slot 57 mesh: s_cbranch_vccz on a wave-wide condition is not covered'), + # v_cmp_gt_u32 vcc, 6, v0; s_and_saveexec_b64 s[20:21], vcc narrows EXEC; the uniform compare then writes VCC + # only for the narrowed lanes; s_mov_b64 exec, -1 restores the full mask before s_cbranch_vccz skips s_nop. + ('a VCC compare under a narrowed EXEC before the branch', + MESH[:POST_COUNT] + ['7d880086', 'be94246a'] + VCC_COMPARE.split() + ['befe04c1', 'bf860001', 'bf800000'] + + MESH[POST_COUNT:], 'slot 57 mesh: s_cbranch_vccz on a wave-wide condition is not covered'), - # s_cbranch_vccnz .join replaces the post-count SCC branch and keeps its forward target. - ('a forward VCC-nonzero branch', mutate('bf850001', 'bf870001', mesh=BRANCH_CASES[0][1]), + # Set uniform VCC, then keep the v_cmpx_gt_i32 that narrows EXEC before s_cbranch_vccz skips s_nop. + ('a VCC-zero branch under narrowed EXEC', + MESH[:POST_COUNT] + VCC_COMPARE.split() + [MESH[POST_COUNT], 'bf860001', 'bf800000'] + MESH[POST_COUNT + 1:], + 'slot 57 mesh: s_cbranch_vccz on a wave-wide condition is not covered'), + # s_cbranch_vccnz .join replaces the SCC branch without defining VCC. + ('a VCC-nonzero branch without a compare', mutate('bf850001', 'bf870001', mesh=BRANCH_CASES[0][1]), 'slot 57 mesh: s_cbranch_vccnz on a wave-wide condition is not covered'), + # s_cbranch_scc1 .join can skip all three dwords that set s40 and VCC. + ('a VCC-zero branch after a join missing a VCC definition on one path', + vertex_red('7e0e0280 bf008080 bf850003 ' + VCC_COMPARE + ' bf860001 7e0e02f2'), + 'slot 57 mesh: s_cbranch_vccz on a wave-wide condition is not covered'), # s_endpgm before the vertex count compare, with the original final s_endpgm still present. ('an early program end', MESH[:POST_COUNT] + ['bf810000'] + MESH[POST_COUNT:], 'slot 57 mesh: an early s_endpgm is not covered'), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 00fa3c759..666d0442b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1322,7 +1322,11 @@ def mesh_run(ins, at, what, patterns, env): return at + len(patterns) -def mesh_skeleton(ins): +MESH_VCC_BRANCHES = ('s_cbranch_vccz', 's_cbranch_vccnz') +VCC_KEYS = {'vcc', 'vcc_hi'} + + +def mesh_skeleton(ins, vcc_branches): """Prove the one accepted group-memory shape of a slot 57 mesh program and replace it by per-thread instructions. Accepted shape, in program order (anything else is refused with its own message): @@ -1390,7 +1394,7 @@ def lands(key, index, what): raise Unsupported('slot 57 mesh: a branch enters or crosses a group-memory exchange') if target <= off: raise Unsupported('slot 57 mesh: a loop outside the group-memory exchanges is not covered') - if name not in ('s_branch', 's_cbranch_scc0', 's_cbranch_scc1', 's_cbranch_execz'): + if name not in ('s_branch', 's_cbranch_scc0', 's_cbranch_scc1', 's_cbranch_execz') + MESH_VCC_BRANCHES: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) edges[i] = dest @@ -1425,6 +1429,9 @@ def lands(key, index, what): thread = base = None # VGPR of the thread index, SGPR holding wave << 6 thread_high = None # second instruction of a proven adjacent v_mbcnt pair scc_stale = False + # Possible last full-EXEC compare offsets. An empty set means some path lacks such a definition. + # The exchanges preserve VCC. Stage.translate checks the sources against its SGPR facts at each definition. + vcc_compares = frozenset() exports = [] incoming = {} falls = True @@ -1433,7 +1440,7 @@ def lands(key, index, what): if index in targets: paths = incoming[index] if falls: - paths.append((stale, pending, mask, wave_known, thread, base, scc_stale)) + paths.append((stale, pending, mask, wave_known, thread, base, scc_stale, vcc_compares)) stale = set().union(*(p[0] for p in paths)) pending = set().union(*(p[1] for p in paths)) mask = paths[0][2] @@ -1444,6 +1451,8 @@ def lands(key, index, what): wave_known = all(p[3] for p in paths) thread, base = (paths[0][k] if all(p[k] == paths[0][k] for p in paths) else None for k in (4, 5)) scc_stale = any(p[6] for p in paths) + definitions = [p[7] for p in paths] + vcc_compares = frozenset().union(*definitions) if all(definitions) else frozenset() falls = True if not falls: raise Unsupported('slot 57 mesh: unreachable code after a branch is not covered') @@ -1482,8 +1491,12 @@ def lands(key, index, what): if index in edges: if scc_stale and reads_scc(name, asm): raise Unsupported('slot 57 mesh: an unmodelled SCC is read by a branch') + if name in MESH_VCC_BRANCHES: + if mask is not None or not vcc_compares: + raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) + vcc_branches[off] = vcc_compares incoming.setdefault(edges[index], []).append( - (stale.copy(), pending.copy(), mask, wave_known, thread, base, scc_stale)) + (stale.copy(), pending.copy(), mask, wave_known, thread, base, scc_stale, vcc_compares)) out.append(ins[index]) falls = name != 's_branch' continue @@ -1520,6 +1533,11 @@ def lands(key, index, what): raise Unsupported('slot 57 mesh: SCC of the count exchange is read') if name.startswith(('s_cmp', 's_bitcmp')): scc_stale = False + if scalar_effects(name, asm)[2] & VCC_KEYS: + vcc_compares = frozenset({off}) if ( + mask is None and base_name.startswith('v_cmp_') and name.endswith(('_e32', '_e64')) + and len(ops) == 3 and ops[0] in ('vcc', 'vcc_lo') + ) else frozenset() # Saveexec uses a fresh VCC from an adjacent compare. Only the matching complement can read the # saved mask. Hardware SCC (whether any bit is set) is not represented by a per-lane boolean. if asm == 's_mov_b64 exec, -1': @@ -1618,7 +1636,8 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): else: self.ins = decode(self.raw_code, refusals) if decoded is None else decoded if kind == 'ms': - self.ins = mesh_skeleton(self.ins) + self.mesh_vcc_branches = {} + self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches) # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept # there is known only afterwards: translate again with that register read at run time or refused there. A # register only moves from kept to 'run' to 'refuse', so this ends. @@ -2281,6 +2300,8 @@ def after(block): # blocks reached from block over at least one edge def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ + vcc_branches = getattr(self, 'mesh_vcc_branches', {}) + vcc_compares = set().union(*vcc_branches.values()) try: self.calculated_pc = calculated_pc_proof(self.ins, getattr(self, 'kind', None)) except Unsupported as reason: @@ -2337,6 +2358,7 @@ def translate(self): for _ in range(max(4, len(self.ins) + 2)): scc_effects = {} + uniform_vcc_compares = set() self.lines = [] self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) @@ -2485,9 +2507,18 @@ def translate(self): if off in refused: raise Unsupported(refused[off]) base = re.sub(r'_e(32|64)$', '', name) + if off in vcc_compares and all( + not mesh_vregs([tok]) and self.uniform_source(tok) + for tok in parse(asm)[1][1:] + ): + uniform_vcc_compares.add(off) if base.startswith('s_cbranch_'): cond = base[10:] cond_uniform = cond in ('scc0', 'scc1') and self.scc_uniform + if off in vcc_branches: + if not vcc_branches[off] <= uniform_vcc_compares: + raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) + cond_uniform = True if not cond_uniform: b_target = int(parse(asm)[1][0].split('_')[1], 16) regs, affected = div_targets.get(off, (set(), set())) From 9befe6cd7d9dc6c71a6c8a5d29f7f1b5fc4f3d6f Mon Sep 17 00:00:00 2001 From: SuperCraft3M <69873238+SuperCraft3M@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:51:09 +0100 Subject: [PATCH 192/232] tooling: stage an isolated startup executable directory (#1549) --- CMakeLists.txt | 4 ++ docs/experiments.md | 14 ++++ docs/startup-runtime.md | 9 ++- tests/startup_stage_package_check.py | 99 ++++++++++++++++++++++++++++ tools/startup/stage_package.ps1 | 65 ++++++++++++++++++ 5 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 tests/startup_stage_package_check.py create mode 100644 tools/startup/stage_package.ps1 diff --git a/CMakeLists.txt b/CMakeLists.txt index f516c33ac..dbc45262c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3733,6 +3733,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_launch_cli_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_launch_cli_check.py") set_tests_properties(startup_launch_cli_check PROPERTIES TIMEOUT 30) + find_program(STARTUP_POWERSHELL NAMES powershell pwsh REQUIRED) + add_test(NAME startup_stage_package COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stage_package_check.py" "${STARTUP_POWERSHELL}") + set_tests_properties(startup_stage_package PROPERTIES TIMEOUT 120) add_test(NAME startup_debug COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_debug_check.py" "$" "$") diff --git a/docs/experiments.md b/docs/experiments.md index eeae050ce..56913942f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -315,6 +315,20 @@ cmake --build --preset dev --target startup_storage_root_check startup_stub_game ctest --preset dev --no-tests=error -R '^startup_storage_root' -V ``` +## Startup package staging + +`tools/startup/stage_package.ps1` copies one executable and its adjacent DLLs into a fresh +run directory. Package archives and subdirectories stay at the data root. The tool refuses +destinations in the package, ancestors of the package, nonempty destinations and destination +paths through reparse points. It does not resolve dependencies or establish executable compatibility. +`startup_stage_package` checks staging from a changed PowerShell location, exact DLL extensions +and DLL selection beside a nested executable. It also checks preservation of package data and +refusal of overwrites, overlapping paths, junctions and invalid executable inputs. + +```powershell +ctest --preset dev --no-tests=error -R '^startup_stage_package$' -V +``` + ## Typed startup colour exports The [startup draw fixture](startup-runtime.md) uses a source-built gfx1013 pixel shader diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 473b5c8c9..717fd922e 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -659,7 +659,14 @@ code that names the export (see `src/startup_stubs/trap.h`). ## Run Prepare a folder with the executable and its package DLLs yourself. Never commit or upload it. -Then: +Alternatively, stage one executable and its adjacent DLLs with: + +```powershell +.\tools\startup\stage_package.ps1 -PackageDir -Exe .exe -RunDir <fresh run folder> +``` + +The destination must be absent or empty and separate from the package. Archives and subdirectories +are not copied. Keep using the package root as `-DataDir`, then run the staged executable: ```powershell .\tools\startup\run.ps1 -Exe <folder>\<title>.exe -DataDir <package root> -LogDir out\startup\run1 ` diff --git a/tests/startup_stage_package_check.py b/tests/startup_stage_package_check.py new file mode 100644 index 000000000..fdc7cfeae --- /dev/null +++ b/tests/startup_stage_package_check.py @@ -0,0 +1,99 @@ +"""Exercise safe startup staging using synthetic files; no game package is needed.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +SCRIPT = Path(__file__).resolve().parents[1] / "tools/startup/stage_package.ps1" + + +def call(powershell, package, exe, run): + return subprocess.run( + [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), + "-PackageDir", str(package), "-Exe", str(exe), "-RunDir", str(run)], + capture_output=True, text=True, timeout=30, + ) + + +def stage_from_changed_location(powershell, root, package, location): + return subprocess.run( + [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", + r"$ErrorActionPreference = 'Stop'; Set-Location -LiteralPath $env:X2W_TEST_LOCATION; " + r"& $env:X2W_TEST_SCRIPT -PackageDir $env:X2W_TEST_PACKAGE -Exe 'bin\child.exe' -RunDir 'package-run'"], + cwd=root, env=dict(os.environ, X2W_TEST_LOCATION=str(location), X2W_TEST_SCRIPT=str(SCRIPT), + X2W_TEST_PACKAGE=str(package)), capture_output=True, text=True, timeout=30, + ) + + +def main(): + powershell = sys.argv[1] + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + package = root / "package" + package.mkdir() + exe = package / "title.exe" + dll = package / "runtime.dll" + asset = package / "large.rpf" + exe.write_bytes(b"synthetic executable") + dll.write_bytes(b"synthetic runtime") + asset.write_bytes(b"package data must not be staged") + (package / "backup.dll_").write_bytes(b"not a DLL") + (package / "backup.dllold").write_bytes(b"not a DLL either") + original = {path.name: path.read_bytes() for path in (exe, dll, asset)} + + run = root / "scratch" / "run" + result = call(powershell, package, exe.name, run) + assert result.returncode == 0, result.stdout + result.stderr + assert (run / exe.name).read_bytes() == original[exe.name] + assert (run / dll.name).read_bytes() == original[dll.name] + assert {entry.name for entry in run.iterdir()} == {exe.name, dll.name} + assert {path.name: path.read_bytes() for path in (exe, dll, asset)} == original + + # A reused run must never overwrite the previous copy or its stand-ins. + (run / dll.name).write_bytes(b"stand-in installed for this run") + result = call(powershell, package, exe.name, run) + assert result.returncode != 0 and "absent or empty" in result.stderr + assert (run / dll.name).read_bytes() == b"stand-in installed for this run" + + for destination in (package, package / "nested-run", root): + result = call(powershell, package, exe.name, destination) + assert result.returncode != 0 and "separate from PackageDir" in result.stderr + result = call(powershell, package, asset.name, root / "bad") + assert result.returncode != 0 and "executable file" in result.stderr + outside = root / "outside.exe" + outside.write_bytes(b"outside") + result = call(powershell, package, outside, root / "bad") + assert result.returncode != 0 and "inside PackageDir" in result.stderr + result = call(powershell, package, exe.name, outside) + assert result.returncode != 0 and "absent or empty" in result.stderr + assert outside.read_bytes() == b"outside" + + bin_dir = package / "bin" + bin_dir.mkdir() + (bin_dir / "child.exe").write_bytes(b"child") + (bin_dir / "side.DLL").write_bytes(b"beside child") + location = root / "changed-location" + location.mkdir() + result = stage_from_changed_location(powershell, run.parent, package, root) + assert result.returncode == 0, result.stdout + result.stderr + sibling = root / "package-run" + assert {entry.name for entry in sibling.iterdir()} == {"child.exe", "side.DLL"} + assert (sibling / "side.DLL").read_bytes() == b"beside child" + assert not (run.parent / "package-run").exists() + + junction = root / "link" + result = subprocess.run(["cmd.exe", "/c", "mklink", "/J", str(junction), str(location)], + capture_output=True, text=True, timeout=30) + assert result.returncode == 0, result.stdout + result.stderr + try: + result = call(powershell, package, exe.name, junction / "new-run") + assert result.returncode != 0 and "reparse point" in result.stderr + assert not (location / "new-run").exists() + finally: + junction.rmdir() + print("safe startup staging: isolated executable/DLL copy, package preservation and overwrite/path guards passed") + + +if __name__ == "__main__": + main() diff --git a/tools/startup/stage_package.ps1 b/tools/startup/stage_package.ps1 new file mode 100644 index 000000000..422b6e7db --- /dev/null +++ b/tools/startup/stage_package.ps1 @@ -0,0 +1,65 @@ +<# +.SYNOPSIS +Stages a small, disposable executable directory for an offline startup run. + +.DESCRIPTION +Copies one executable and the DLLs beside it into a separate run directory. Package assets +remain in PackageDir and are supplied as run.ps1's -DataDir. No recursive copy is performed. +#> +param( + [Parameter(Mandatory)] [string]$PackageDir, + [Parameter(Mandatory)] [string]$Exe, + [Parameter(Mandatory)] [string]$RunDir +) +$ErrorActionPreference = "Stop" + +$package = (Resolve-Path -LiteralPath $PackageDir).Path.TrimEnd('\') +$source = if ([IO.Path]::IsPathRooted($Exe)) { + (Resolve-Path -LiteralPath $Exe).Path +} else { + (Resolve-Path -LiteralPath (Join-Path $package $Exe)).Path +} +$sourceDir = Split-Path -Parent $source +$provider = $null +$drive = $null +$run = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath( + $RunDir, [ref]$provider, [ref]$drive).TrimEnd('\') +if ($provider.Name -ne 'FileSystem') { throw "RunDir must be a filesystem path." } +if (-not (Test-Path -LiteralPath $source -PathType Leaf) -or [IO.Path]::GetExtension($source) -ine '.exe') { + throw "Exe must name an executable file." +} + +function Test-PathInside([string]$Path, [string]$Parent) { + $prefix = $Parent.TrimEnd('\') + '\' + return $Path.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase) +} + +if (-not (Test-PathInside $source $package)) { + throw "Exe must be inside PackageDir." +} +if ($run.Equals($package, [StringComparison]::OrdinalIgnoreCase) -or + (Test-PathInside $run $package) -or (Test-PathInside $package $run)) { + throw "RunDir must be separate from PackageDir and its parent directories." +} + +# Do not write through an existing junction/symlink or overwrite a previous package. +for ($ancestor = $run; $ancestor; $ancestor = Split-Path -Parent $ancestor) { + if ((Test-Path -LiteralPath $ancestor) -and + ((Get-Item -LiteralPath $ancestor -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { + throw "RunDir must not pass through a reparse point." + } +} +if ((Test-Path -LiteralPath $run) -and + (-not (Test-Path -LiteralPath $run -PathType Container) -or + @(Get-ChildItem -LiteralPath $run -Force).Count)) { + throw "RunDir must be absent or empty. Use a fresh directory for staging." +} + +New-Item -ItemType Directory -Force -Path $run | Out-Null +Copy-Item -LiteralPath $source -Destination $run -Force +$dlls = @(Get-ChildItem -LiteralPath $sourceDir -File -Filter '*.dll' | + Where-Object { $_.Extension -ieq '.dll' }) +foreach ($dll in $dlls) { + Copy-Item -LiteralPath $dll.FullName -Destination $run -Force +} +Write-Output "Staged executable and $($dlls.Count) adjacent DLLs in $run; package assets remain in $package." From 380116c17ef8181f767297619bdf6507533a2bfb Mon Sep 17 00:00:00 2001 From: Matheus Sergio <matheusolovics@gmail.com> Date: Wed, 25 Nov 2026 18:52:33 -0300 Subject: [PATCH 193/232] startup: lower D16 image_load_mip in gfx2hlsl (#2575) Extend the D16 MIMG load lowering in `tools/startup/gfx2hlsl.py` (`#2139`) from level-zero `image_load` to explicit-mip `image_load_mip` on 2D, 3D and 2D-array resources: - Accept `d16` alongside cache-policy and `unorm` modifiers on `image_load_mip` (`Texture2D.Load(int3(x, y, mip))` and `Texture2DArray`/`Texture3D.Load(int4(x, y, slice_or_z, mip))`), including non-sequential address (`NSA`) register lists and both vertex and pixel stages. - Reuse the exact IEEE binary32-to-binary16 RNE (`pack16_rne`) and exact `UNORM16` (`pack16_unorm16`) helpers, `udsrc <ud> d16unorm16 <index>` selection, `d16srv <index> exact` manifest validation against the 14 GPU-verified exact DXGI formats, and odd-`dmask` low-16-bit provenance tracking (`low16_only_v`). - Keep `a16`, `tfe`, `lwe`, `r128`, set reserved MIMG bits, `dmask:0x0`, 1D and cube dimensions, compute `d16` image loads, and mismatched destination or address register widths refused. - Extend `offscreen_check --startup-image-load-d16` (`tests/startup_image_3d.cpp`) and `tests/startup_image_load_d16_check.py` (plus the explicit-mip layout checks in `tests/startup_image_load_mip_check.py` and `tests/startup_image_2d_array_check.py`) to two-mip (`8x2` + `4x1`) 2D and two-slice 2D-array `R16_UNORM` and `R32G32B32A32_FLOAT` textures, covering explicit-mip fixtures C and D, odd-`dmask` upper-half poison checks, and six additional HLSL mutations (`mip_zero`, `mip_drop_nsa`, `mip_rtz`, `mip_double_round`, `swap_slice_mip`, and `array_drop_nsa`). Part of #2023 AI-assisted. Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- docs/experiments.md | 4 +- tests/desktop_gpu.h | 2 +- tests/offscreen_check.cpp | 16 +- tests/startup_image_2d_array_check.py | 14 +- tests/startup_image_3d.cpp | 68 +++- tests/startup_image_load_d16_check.py | 509 ++++++++++++++++++++------ tests/startup_image_load_mip_check.py | 16 +- tools/startup/gfx2hlsl.py | 13 +- 8 files changed, 480 insertions(+), 162 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 56913942f..7c81370a7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14114,9 +14114,9 @@ cmake --build --preset dev --target offscreen_check d3d12_xs_shim ctest --preset dev --no-tests=error -R '^startup_image_sample_a16_(controls|warp|hardware)$' -V ``` -## Startup translator: level-zero D16 image loads +## Startup translator: D16 image loads -For level-zero `image_load` with `d16` on 2D (including `a16` and NSA), 3D and 2D-array resources, `tools/startup/gfx2hlsl.py` narrows each enabled `dmask` component of the `Load` result to IEEE binary16 and packs the halves pairwise into `ceil(popcount(dmask) / 2)` consecutive VGPRs (low half first, high half second). HLSL `f32tof16` truncates toward zero on WARP (lowering 31,740 of the 65,536 `DXGI_FORMAT_R16_UNORM` depth values by 1 ULP relative to RDNA hardware), while narrowing an intermediate binary32 `Load` value still double-rounds `R16_UNORM` at `0xffaf` (`0x3bfe` instead of `0x3bfd`) and `0xffef` (`0x3c00` instead of `0x3bff`). `gfx2hlsl.py` therefore emits both an integer binary32-to-binary16 round-to-nearest-even helper (`pack16_rne`, quieting NaNs while preserving sign) and an exact `UNORM16` helper (`pack16_unorm16`, recovering `u = uint(saturate(v) * 65535.0 + 0.5)` and rounding `u / 65535` directly to binary16), selected per SRV via `udsrc <ud> d16unorm16 <index>`, and writes `d16srv <index> exact` to `<key>.txt`. Before drawing, `src/startup_stubs/d3d12_draw.inl` (`src/startup_stubs/d16_image_format.h`) validates the bound view's effective `DXGI_FORMAT` against the 14 independently GPU-verified exact formats (five 32-bit float views, six 8-bit `UNORM` views, and three 16-bit `UNORM` views), setting `d16unorm16` to `1` for `R16*_UNORM` and `0` for the exact binary32/`UNORM8` formats while refusing integer (`UINT`/`SINT`), typeless, depth-stencil-only, `SNORM16`, `R24_UNORM`, `SRGB`, block-compressed, packed-target stand-in, console extension, null-resource and unbound views. When `popcount(dmask)` is odd (`1` or `3`), bits `31:16` of the final destination VGPR are hardware-undefined on RDNA 2; `gfx2hlsl.py` tracks those registers across expressions and basic blocks and refuses whole-word reads unless consumed through a low-16-bit operation (`v_cvt_f32_f16`, `v_cvt_f32_ubyte0`/`1`, `SDWA` `BYTE_0`/`BYTE_1`/`WORD_0`, `v_and_b32` with constant mask `<= 0xffff`, `v_cmp_class_f16`/`v_cmpx_class_f16`, or `v_fma_mix*` half operands). Pipelines without `image_load` `d16` omit all helpers and `d16srv` lines; `image_load_mip` with `d16`, sampler MIMG forms with `d16`, 1D and cube dimensions, 3D or 2D-array `a16`, `tfe`, `lwe`, `r128`, set reserved MIMG bits, an empty `dmask`, and mismatched register counts remain refused. +For `image_load` and `image_load_mip` with `d16` on 2D (including NSA, and `a16` on level-zero `image_load`), 3D and 2D-array resources, `tools/startup/gfx2hlsl.py` narrows each enabled `dmask` component of the `Load` result to IEEE binary16 and packs the halves pairwise into `ceil(popcount(dmask) / 2)` consecutive VGPRs (low half first, high half second). HLSL `f32tof16` truncates toward zero on WARP (lowering 31,740 of the 65,536 `DXGI_FORMAT_R16_UNORM` depth values by 1 ULP relative to RDNA hardware), while narrowing an intermediate binary32 `Load` value still double-rounds `R16_UNORM` at `0xffaf` (`0x3bfe` instead of `0x3bfd`) and `0xffef` (`0x3c00` instead of `0x3bff`). `gfx2hlsl.py` therefore emits both an integer binary32-to-binary16 round-to-nearest-even helper (`pack16_rne`, quieting NaNs while preserving sign) and an exact `UNORM16` helper (`pack16_unorm16`, recovering `u = uint(saturate(v) * 65535.0 + 0.5)` and rounding `u / 65535` directly to binary16), selected per SRV via `udsrc <ud> d16unorm16 <index>`, and writes `d16srv <index> exact` to `<key>.txt`. Before drawing, `src/startup_stubs/d3d12_draw.inl` (`src/startup_stubs/d16_image_format.h`) validates the bound view's effective `DXGI_FORMAT` against the 14 independently GPU-verified exact formats (five 32-bit float views, six 8-bit `UNORM` views, and three 16-bit `UNORM` views), setting `d16unorm16` to `1` for `R16*_UNORM` and `0` for the exact binary32/`UNORM8` formats while refusing integer (`UINT`/`SINT`), typeless, depth-stencil-only, `SNORM16`, `R24_UNORM`, `SRGB`, block-compressed, packed-target stand-in, console extension, null-resource and unbound views. When `popcount(dmask)` is odd (`1` or `3`), bits `31:16` of the final destination VGPR are hardware-undefined on RDNA 2; `gfx2hlsl.py` tracks those registers across expressions and basic blocks and refuses whole-word reads unless consumed through a low-16-bit operation (`v_cvt_f32_f16`, `v_cvt_f32_ubyte0`/`1`, `SDWA` `BYTE_0`/`BYTE_1`/`WORD_0`, `v_and_b32` with constant mask `<= 0xffff`, `v_cmp_class_f16`/`v_cmpx_class_f16`, or `v_fma_mix*` half operands). Pipelines without D16 image loads omit all helpers and `d16srv` lines; sampler MIMG forms with `d16`, 1D and cube dimensions, `image_load_mip` or 3D / 2D-array `a16`, `tfe`, `lwe`, `r128`, set reserved MIMG bits, an empty `dmask`, and mismatched register counts remain refused. Verified on commit base `009153b7` on Windows 11 26H2 (build `26300.9974`) across Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.9818`) and AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`), D3D12 debug layer enabled (`debug_errors=0 debug_warnings=0`): exhaustive GPU probes across all 65,536 `DXGI_FORMAT_R16_UNORM` texels (DXC `cs_6_2` and FXC `cs_5_0`) and all 256 `DXGI_FORMAT_R8_UNORM` texels match RDNA 2 hardware `d16` loads with 0 mismatches (`65,536 / 65,536` and `256 / 256`, including `0xffaf -> 0x3bfd` and `0xffef -> 0x3bff`). In `offscreen_check --startup-image-load-d16` (DXC `ps_6_0` and FXC `ps_5_1`), fixtures A and B match all 128 output words (32 pixels) on `8x2` `R16_UNORM` and `8x2` `R32G32B32A32_FLOAT` textures, remain invariant when `0xdead0000` is injected into bits `31:16` of the odd-`dmask` registers, and reject eight mutated HLSL controls (truncation toward zero, binary32 `double_round` on `0xffaf`/`0xffef`, unpacked 32-bit `U(t.x)`, swapped low/high halves, dropped `<< 16` shift, dropped `a16` coordinate unpack, ignored NSA register list, and unmasked odd-`dmask` upper half). Through `d3d12_xs.dll` (`startup_d16_srv_{warp,hardware}`), `R16_UNORM` (`0xffef -> 0x3bff`), `R32_FLOAT` (`0x3f7ff000 -> 0x3c00`) and `R16_TYPELESS` viewed as `R16_UNORM` (`0xaaaa -> 0x3955`) dispatch the exact per-SRV mode on one PSO while `R16_UINT`, `R16_SNORM`, null-resource and unwritten views are refused and malformed `d16srv` manifests are rejected. diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index 75dc3e27b..84ff8c3f5 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -28,7 +28,7 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const bool one_dimensional = false, bool two_dimensional = false, UINT first_mip = 0, UINT view_levels = 0); void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, - bool depth16, std::uint32_t words[64]); + bool depth16, std::uint32_t words[64], bool array = false); int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, const std::uint32_t expected[4]); void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index a62bf1872..d3973cdd1 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1331,21 +1331,23 @@ OperationResult run_startup_image_2d_view(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } -// --startup-image-load-d16 <r16_unorm|rgba32f> <vs.cso> <ps.cso> <expected.bin>: draws an 8x2 full-screen -// pair to an R32G32B32A32_UINT target against an 8x2 R16_UNORM or R32G32B32A32_FLOAT source texture and -// compares all 64 little-endian words with expected.bin. +// --startup-image-load-d16 <r16_unorm|rgba32f|r16_unorm_array|rgba32f_array> <vs.cso> <ps.cso> <expected.bin>: +// draws an 8x2 full-screen pair to an R32G32B32A32_UINT target against a two-mip (8x2 + 4x1) 2D or two-slice +// 2D-array R16_UNORM / R32G32B32A32_FLOAT source texture and compares all 64 little-endian words with expected.bin. OperationResult run_startup_image_load_d16(const OperationContext& ctx) { - const bool depth16 = std::strcmp(ctx.argv[3], "r16_unorm") == 0; - if (!depth16 && std::strcmp(ctx.argv[3], "rgba32f") != 0) - return {OutcomeKind::fail, "image_load d16 source mode must be r16_unorm or rgba32f"}; + const bool depth16 = std::strcmp(ctx.argv[3], "r16_unorm") == 0 || std::strcmp(ctx.argv[3], "r16_unorm_array") == 0; + const bool rgba32f = std::strcmp(ctx.argv[3], "rgba32f") == 0 || std::strcmp(ctx.argv[3], "rgba32f_array") == 0; + const bool array = std::strcmp(ctx.argv[3], "r16_unorm_array") == 0 || std::strcmp(ctx.argv[3], "rgba32f_array") == 0; + if (!depth16 && !rgba32f) + return {OutcomeKind::fail, "image_load d16 source mode must be r16_unorm[_array] or rgba32f[_array]"}; std::uint32_t expected[64]{}; std::ifstream file(ctx.argv[6], std::ios::binary); file.read(reinterpret_cast<char*>(expected), sizeof(expected)); if (!file || file.peek() != std::char_traits<char>::eof()) return {OutcomeKind::fail, "expected file does not hold 64 words"}; std::uint32_t actual[64]{}; - check_startup_image_load_d16(ctx.device, ctx.argv[4], ctx.argv[5], depth16, actual); + check_startup_image_load_d16(ctx.device, ctx.argv[4], ctx.argv[5], depth16, actual, array); unsigned differing = 0; for (unsigned i = 0; i < 16; ++i) { const std::uint32_t* want = &expected[i * 4]; diff --git a/tests/startup_image_2d_array_check.py b/tests/startup_image_2d_array_check.py index caede750f..4aaf0edc8 100644 --- a/tests/startup_image_2d_array_check.py +++ b/tests/startup_image_2d_array_check.py @@ -226,8 +226,18 @@ def mip_controls(): accepted[1] |= 0x10 # unorm assert 't = %s;' % MIP_CALL in translate(mip_words(1, 0, bytes(accepted))).hlsl_ps() - # Refused: packed 16-bit data or addresses and fault-status returns need their own lowering. - for flag, byte, mask in (('d16', 7, 0x80), ('a16', 7, 0x40), ('tfe', 2, 0x01)): + # Packed 16-bit data narrows the four channels into v[0:1] and marks SRV 0 for exact D16 validation. + d16 = bytearray(MIP_IMAGE) + d16[7] |= 0x80 + d16_pipe = translate(mip_words(1, 0, bytes(d16))) + d16_ps = d16_pipe.hlsl_ps() + assert 't = %s;' % MIP_CALL in d16_ps, d16_ps + assert 'v0 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in d16_ps, d16_ps + assert 'v1 = pack16_d16(t.z, ud4) | (pack16_d16(t.w, ud4) << 16);' in d16_ps, d16_ps + assert 'd16srv 0 exact' in d16_pipe.manifest().splitlines(), d16_pipe.manifest() + + # Refused: packed addresses and fault-status returns need their own lowering. + for flag, byte, mask in (('a16', 7, 0x40), ('tfe', 2, 0x01)): refused = bytearray(MIP_IMAGE) refused[byte] |= mask try: diff --git a/tests/startup_image_3d.cpp b/tests/startup_image_3d.cpp index 64f0a5e67..6c0070de6 100644 --- a/tests/startup_image_3d.cpp +++ b/tests/startup_image_3d.cpp @@ -215,19 +215,24 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const z, color[0], color[1], color[2], color[3]); } -// Draws an 8x2 R32G32B32A32_UINT target against an 8x2 2D source texture with no static samplers: +// Draws an 8x2 R32G32B32A32_UINT target against a two-mip (8x2 mip 0, 4x1 mip 1) 2D or two-slice 2D-array +// source texture with no static samplers: // depth16 == true: DXGI_FORMAT_R16_UNORM (16-bit depth SRV format) covering zero, binary16 subnormals, -// exact fractions and values where IEEE round-to-nearest-even differs from RTZ; +// exact fractions, double-rounding discriminators (0xffaf, 0xffef) and RNE-vs-RTZ codes; // depth16 == false: DXGI_FORMAT_R32G32B32A32_FLOAT covering four distinct channels per texel, halfway ties // to even, 1-ULP midpoint neighbours, subnormals, signed zero, overflow and quiet NaNs. void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, - bool depth16, std::uint32_t words[64]) + bool depth16, std::uint32_t words[64], bool array) { - constexpr UINT width = 8, height = 2; + constexpr UINT width = 8, height = 2, d16_mips = 2; static constexpr std::uint16_t kDepthTexels[width * height] = { 0x0000, 0x0001, 0x0003, 0x1234, 0x2aad, 0x4008, 0x5555, 0x8000, 0x8010, 0xa018, 0xc018, 0xe00c, 0xffaf, 0xffef, 0xfffe, 0xffff, }; + static constexpr std::uint16_t kDepthMip1[2][width / 2] = { + {0xffaf, 0xffef, 0x0003, 0x8010}, + {0xffef, 0xffaf, 0x5555, 0xa018}, + }; static constexpr std::uint32_t kFloatTexels[width * height][4] = { {0x3f801000u, 0x3f803000u, 0x3f801001u, 0x3f7fffffu}, {0x387fe000u, 0x387fdfffu, 0x33800000u, 0x33000000u}, @@ -246,6 +251,12 @@ void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, {0x3fc00000u, 0xc0000000u, 0x40200000u, 0xc0400000u}, {0x477fe000u, 0xc77fe000u, 0x38800000u, 0xb8800000u}, }; + static constexpr std::uint32_t kFloatMip1[width / 2][4] = { + {0x3f803000u, 0x387fe000u, 0xbf803000u, 0x477fefffu}, + {0x33800000u, 0x33000001u, 0x80000000u, 0x7fc00001u}, + {0x44006000u, 0xc4006000u, 0x39003000u, 0xb9003000u}, + {0x477ff000u, 0xc77ff000u, 0x3e200000u, 0xbe200000u}, + }; const auto vs = read_blob(vertex_path); const auto ps = read_blob(pixel_path); @@ -271,29 +282,46 @@ void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, ComPtr<ID3D12PipelineState> pipeline; check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "Create image_load d16 PSO"); + const UINT slices = array ? 2u : 1u; + const UINT subresources = slices * d16_mips; D3D12_RESOURCE_DESC td{}; td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; td.Width = width; td.Height = height; - td.DepthOrArraySize = 1; - td.MipLevels = 1; + td.DepthOrArraySize = static_cast<UINT16>(slices); + td.MipLevels = d16_mips; td.Format = depth16 ? DXGI_FORMAT_R16_UNORM : DXGI_FORMAT_R32G32B32A32_FLOAT; td.SampleDesc.Count = 1; const auto texture = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); - D3D12_PLACED_SUBRESOURCE_FOOTPRINT src_footprint{}; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT src_footprints[4]{}; UINT64 upload_size = 0; - device->GetCopyableFootprints(&td, 0, 1, 0, &src_footprint, nullptr, nullptr, &upload_size); + device->GetCopyableFootprints(&td, 0, subresources, 0, src_footprints, nullptr, nullptr, &upload_size); const auto upload = make_buffer(device, upload_size, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); void* mapped = nullptr; const D3D12_RANGE none{0, 0}; check(upload->Map(0, &none, &mapped), "Map image_load d16 texels"); - auto* const dst_bytes = static_cast<std::uint8_t*>(mapped) + src_footprint.Offset; - const UINT row_bytes = depth16 ? width * sizeof(std::uint16_t) : width * 4 * sizeof(std::uint32_t); - for (UINT y = 0; y < height; ++y) { - const void* row_src = depth16 ? static_cast<const void*>(&kDepthTexels[y * width]) - : static_cast<const void*>(&kFloatTexels[y * width][0]); - std::memcpy(dst_bytes + y * src_footprint.Footprint.RowPitch, row_src, row_bytes); + const UINT texel_bytes = depth16 ? sizeof(std::uint16_t) : 4 * sizeof(std::uint32_t); + for (UINT s = 0; s < slices; ++s) { + for (UINT m = 0; m < d16_mips; ++m) { + const UINT sub = m + s * d16_mips; + const UINT mw = width >> m, mh = height >> m; + auto* const sub_bytes = static_cast<std::uint8_t*>(mapped) + src_footprints[sub].Offset; + for (UINT y = 0; y < mh; ++y) { + for (UINT x = 0; x < mw; ++x) { + auto* const cell = sub_bytes + y * src_footprints[sub].Footprint.RowPitch + x * texel_bytes; + if (m == 0) { + const UINT idx = s == 0 ? (y * width + x) : (width * height - 1u - (y * width + x)); + if (depth16) std::memcpy(cell, &kDepthTexels[idx], texel_bytes); + else std::memcpy(cell, &kFloatTexels[idx][0], texel_bytes); + } else { + const UINT idx = s == 0 ? x : ((width / 2 - 1u) - x); + if (depth16) std::memcpy(cell, &kDepthMip1[s][x], texel_bytes); + else std::memcpy(cell, &kFloatMip1[idx][0], texel_bytes); + } + } + } + } } upload->Unmap(0, nullptr); @@ -323,11 +351,13 @@ void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); auto* list = commands.list.Get(); - D3D12_TEXTURE_COPY_LOCATION to{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; - to.SubresourceIndex = 0; - D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; - from.PlacedFootprint = src_footprint; - list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + for (UINT sub = 0; sub < subresources; ++sub) { + D3D12_TEXTURE_COPY_LOCATION to{texture.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + to.SubresourceIndex = sub; + D3D12_TEXTURE_COPY_LOCATION from{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + from.PlacedFootprint = src_footprints[sub]; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + } transition(list, texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); list->SetGraphicsRootSignature(root.Get()); ID3D12DescriptorHeap* heaps[]{views.Get()}; diff --git a/tests/startup_image_load_d16_check.py b/tests/startup_image_load_d16_check.py index f5bc99cb6..6dfe63292 100644 --- a/tests/startup_image_load_d16_check.py +++ b/tests/startup_image_load_d16_check.py @@ -1,15 +1,18 @@ -"""Level-zero D16 image_load lowering in tools/startup/gfx2hlsl.py (Part of #2023, item D). +"""D16 image_load and image_load_mip lowering in tools/startup/gfx2hlsl.py (Part of #2023, item D). (no arguments) emitted-HLSL rounding, decoder, SRV format and odd-dmask controls binary <llvm-mc> reassemble every fixture source and compare it with the recorded words decode <libLLVM> disassemble the MIMG words with LLVM's C API and compare with disasm_rdna2.py draw <dxc> <offscreen_check> <warp|hardware> [fxc] - translate, compile (DXC ps_6_0, and FXC ps_5_1 when given) and draw two - pixel fixtures against 8x2 R16_UNORM (including 0xffaf and 0xffef) and 8x2 - R32G32B32A32_FLOAT textures into an R32G32B32A32_UINT target, checking all - 64 output words per draw, high-half odd-dmask isolation and eight mutations - -On RDNA 2 (gfx1013), image_load with d16 narrows the enabled dmask channels to IEEE binary16 (round to nearest even) + translate, compile (DXC ps_6_0, and FXC ps_5_1 when given) and draw four + pixel fixtures (level-zero 2D A/B, explicit-mip 2D C and explicit-mip + 2D-array D) against two-mip (8x2 + 4x1) R16_UNORM (including 0xffaf and + 0xffef) and R32G32B32A32_FLOAT 2D / two-slice 2D-array textures into an + R32G32B32A32_UINT target, checking all 64 output words per draw, high-half + odd-dmask isolation and fourteen mutations + +On RDNA 2 (gfx1013), image_load and image_load_mip with d16 narrow the enabled dmask channels to IEEE binary16 (round to +nearest even) and packs them pairwise into ceil(popcount(dmask) / 2) consecutive VGPRs (low half first, high half second; when popcount(dmask) is odd, bits 31:16 of the final destination VGPR are hardware-undefined). HLSL f32tof16 truncates toward zero on WARP (lowering 31,740 of the 65,536 R16_UNORM values by 1 ULP), while narrowing a binary32 intermediate @@ -55,6 +58,11 @@ 0x8010, 0xa018, 0xc018, 0xe00c, 0xffaf, 0xffef, 0xfffe, 0xffff, ) +DEPTH_MIP1 = ( + (0xffaf, 0xffef, 0x0003, 0x8010), + (0xffef, 0xffaf, 0x5555, 0xa018), +) + FLOAT_TEXELS = ( (0x3f801000, 0x3f803000, 0x3f801001, 0x3f7fffff), (0x387fe000, 0x387fdfff, 0x33800000, 0x33000000), @@ -74,6 +82,13 @@ (0x477fe000, 0xc77fe000, 0x38800000, 0xb8800000), ) +FLOAT_MIP1 = ( + (0x3f803000, 0x387fe000, 0xbf803000, 0x477fefff), + (0x33800000, 0x33000001, 0x80000000, 0x7fc00001), + (0x44006000, 0xc4006000, 0x39003000, 0xb9003000), + (0x477ff000, 0xc77ff000, 0x3e200000, 0xbe200000), +) + # DXGI_FORMAT enum values referenced in src/startup_stubs/d16_image_format.h. DXGI_FORMAT_VALUES = { 'DXGI_FORMAT_R32G32B32A32_FLOAT': 2, @@ -190,21 +205,84 @@ def encode_v_and_low16(reg): 'image_load v[4:5], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY d16', encode_mimg(IMG_LOAD, dmask=0xf, dim=DIM_2D_ARRAY, vaddr=0, vdata=4, d16=1), ), - 'mip_d16_refused': ( + 'mip_d16_2d': ( 'image_load_mip v[4:5], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D d16', encode_mimg(IMG_LOAD_MIP, dmask=0xf, vaddr=0, vdata=4, d16=1), ), + 'mip_d16_x': ( + 'image_load_mip v4, v[8:10], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D d16', + encode_mimg(IMG_LOAD_MIP, dmask=0x1, vaddr=8, vdata=4, d16=1), + ), + 'mip_d16_xz': ( + 'image_load_mip v5, v[8:10], s[16:23] dmask:0x5 dim:SQ_RSRC_IMG_2D unorm d16', + encode_mimg(IMG_LOAD_MIP, dmask=0x5, vaddr=8, vdata=5, unorm=1, d16=1), + ), + 'mip_d16_xyz_nsa': ( + 'image_load_mip v[6:7], [v2, v9, v10], s[16:23] dmask:0x7 dim:SQ_RSRC_IMG_2D glc slc dlc d16', + encode_mimg(IMG_LOAD_MIP, dmask=0x7, vaddr=2, vdata=6, nsa=1, extra_addrs=(9, 10), glc=1, slc=1, dlc=1, d16=1), + ), + 'mip_d16_3d': ( + 'image_load_mip v[4:5], v[0:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_3D d16', + encode_mimg(IMG_LOAD_MIP, dmask=0xf, dim=DIM_3D, vaddr=0, vdata=4, d16=1), + ), + 'mip_d16_2da_xyzw': ( + 'image_load_mip v[4:5], v[8:11], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY d16', + encode_mimg(IMG_LOAD_MIP, dmask=0xf, dim=DIM_2D_ARRAY, vaddr=8, vdata=4, d16=1), + ), + 'mip_d16_2da_x_nsa': ( + 'image_load_mip v6, [v12, v9, v10, v11], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY d16', + encode_mimg(IMG_LOAD_MIP, dmask=0x1, dim=DIM_2D_ARRAY, vaddr=12, vdata=6, nsa=1, extra_addrs=(9, 10, 11), d16=1), + ), + 'mip_d16_2da_zw_nsa': ( + 'image_load_mip v7, [v12, v9, v10, v11], s[16:23] dmask:0xc dim:SQ_RSRC_IMG_2D_ARRAY d16', + encode_mimg(IMG_LOAD_MIP, dmask=0xc, dim=DIM_2D_ARRAY, vaddr=12, vdata=7, nsa=1, extra_addrs=(9, 10, 11), d16=1), + ), '1d_d16_refused': ( 'image_load v4, v0, s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_1D d16', encode_mimg(IMG_LOAD, dmask=0x1, dim=DIM_1D, vaddr=0, vdata=4, d16=1), ), + 'mip_1d_d16_refused': ( + 'image_load_mip v4, v[0:1], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_1D d16', + encode_mimg(IMG_LOAD_MIP, dmask=0x1, dim=DIM_1D, vaddr=0, vdata=4, d16=1), + ), 'cube_d16_refused': ( 'image_load v[4:5], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE d16', encode_mimg(IMG_LOAD, dmask=0xf, dim=DIM_CUBE, vaddr=0, vdata=4, d16=1), ), + 'mip_cube_d16_refused': ( + 'image_load_mip v[4:5], v[0:3], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_CUBE d16', + encode_mimg(IMG_LOAD_MIP, dmask=0xf, dim=DIM_CUBE, vaddr=0, vdata=4, d16=1), + ), } DECODE_KEYS = tuple(MIMG_LLVM_MC) +# Prefix for 2D image_load_mip (Fixture C): v10 = y (mip 0 or 1), v8 = v2 = x >> y, v9 = 0, v3 = 63 (NSA sentinel). +PRE_C = """\ +s_load_dwordx8 s[16:23], s[8:9], 0x0 +v_and_b32_e32 v1, 7, v0 +v_lshrrev_b32_e32 v10, 16, v0 +v_lshrrev_b32_e32 v8, v10, v1 +v_mov_b32_e32 v9, 0 +v_lshrrev_b32_e32 v2, v10, v1 +v_mov_b32_e32 v3, 63 +s_waitcnt lgkmcnt(0) +""" +PRE_WORDS_C = bytes.fromhex('04040cf4000000fa' '87000236' '9000142c' '0a03102c' '8002127e' '0a03042c' 'bf02067e' '7fc08cbf') + +# Prefix for 2D-array image_load_mip (Fixture D): v8 = v12 = x >> 1, v9 = 0, v10 = x & 1 (slice), v11 = y (mip), v13 = 63. +PRE_D = """\ +s_load_dwordx8 s[16:23], s[8:9], 0x0 +v_and_b32_e32 v1, 7, v0 +v_lshrrev_b32_e32 v11, 16, v0 +v_lshrrev_b32_e32 v8, 1, v1 +v_mov_b32_e32 v9, 0 +v_and_b32_e32 v10, 1, v1 +v_lshrrev_b32_e32 v12, 1, v1 +v_mov_b32_e32 v13, 63 +s_waitcnt lgkmcnt(0) +""" +PRE_WORDS_D = bytes.fromhex('04040cf4000000fa' '87000236' '9000162c' '8102102c' '8002127e' '81021436' '8102182c' 'bf021a7e' '7fc08cbf') + # Fixture A exercises 1-channel depth d16 (dmask:0x1 -> v_cvt_f32_f16), 2-channel non-contiguous a16+d16 (dmask:0x5) # and 3-channel NSA d16 (dmask:0x7 -> SDWA WORD_0 low-half consumer on v7). PS_SOURCE_A = PRE + '\n'.join(MIMG_LLVM_MC[k][0] for k in ('d16_x', 'd16_xz_a16', 'd16_xyz_nsa')) + '\n' + POST_A @@ -214,6 +292,16 @@ def encode_v_and_low16(reg): PS_SOURCE_B = PRE + '\n'.join(MIMG_LLVM_MC[k][0] for k in ('d16_xyzw', 'd16_y', 'd16_zw')) + '\n' + POST_B PS_WORDS_B = PRE_WORDS + b''.join(MIMG_LLVM_MC[k][1] for k in ('d16_xyzw', 'd16_y', 'd16_zw')) + POST_WORDS_B +# Fixture C exercises 2D image_load_mip with d16 across mip 0 (y=0) and mip 1 (y=1): odd dmask:0x1 -> v_cvt_f32_f16, +# 2-channel non-contiguous dmask:0x5 with unorm, and 3-channel NSA [v2, v9, v10] dmask:0x7 -> SDWA WORD_0 on v7. +PS_SOURCE_C = PRE_C + '\n'.join(MIMG_LLVM_MC[k][0] for k in ('mip_d16_x', 'mip_d16_xz', 'mip_d16_xyz_nsa')) + '\n' + POST_A +PS_WORDS_C = PRE_WORDS_C + b''.join(MIMG_LLVM_MC[k][1] for k in ('mip_d16_x', 'mip_d16_xz', 'mip_d16_xyz_nsa')) + POST_WORDS_A + +# Fixture D exercises 2D-array image_load_mip with d16 across slices (x & 1) and mips (y): full dmask:0xf on v[8:11], +# NSA [v12, v9, v10, v11] odd dmask:0x1 -> v_and_b32 0xffff on v6, and NSA dmask:0xc on v7. +PS_SOURCE_D = PRE_D + '\n'.join(MIMG_LLVM_MC[k][0] for k in ('mip_d16_2da_xyzw', 'mip_d16_2da_x_nsa', 'mip_d16_2da_zw_nsa')) + '\n' + POST_B +PS_WORDS_D = PRE_WORDS_D + b''.join(MIMG_LLVM_MC[k][1] for k in ('mip_d16_2da_xyzw', 'mip_d16_2da_x_nsa', 'mip_d16_2da_zw_nsa')) + POST_WORDS_B + PACK16_RNE_HLSL = """\ uint pack16_rne(float value) { @@ -336,28 +424,49 @@ def pack16_rtz_ref(bits): return sign | (sig >> shift) -def texel_f32_words(tex_mode, x, y): - if not (0 <= x < WIDTH and 0 <= y < HEIGHT): - return (0, 0, 0, 0) - idx = y * WIDTH + x - if tex_mode == 'r16_unorm': - return (f32_bits_from_unorm16(DEPTH_TEXELS[idx]), 0, 0, 0x3f800000) - return FLOAT_TEXELS[idx] - - -def texel_halves(tex_mode, x, y, mutant=None): - if not (0 <= x < WIDTH and 0 <= y < HEIGHT): - return (0, 0, 0, 0) - idx = y * WIDTH + x - if tex_mode == 'r16_unorm': - rgba = texel_f32_words(tex_mode, x, y) - if mutant == 'rtz': +def texel_f32_words(tex_mode, x, y, *, mip=0, slice_=0): + is_depth = tex_mode.startswith('r16_unorm') + oob = (0, 0, 0, 0x3f800000) if is_depth else (0, 0, 0, 0) + max_slices = 2 if tex_mode.endswith('_array') else 1 + if not (0 <= mip < 2 and 0 <= slice_ < max_slices): + return oob + mw, mh = WIDTH >> mip, HEIGHT >> mip + if not (0 <= x < mw and 0 <= y < mh): + return oob + if mip == 0: + idx = (y * WIDTH + x) if slice_ == 0 else (WIDTH * HEIGHT - 1 - (y * WIDTH + x)) + if is_depth: + return (f32_bits_from_unorm16(DEPTH_TEXELS[idx]), 0, 0, 0x3f800000) + return FLOAT_TEXELS[idx] + if is_depth: + return (f32_bits_from_unorm16(DEPTH_MIP1[slice_][x]), 0, 0, 0x3f800000) + idx = x if slice_ == 0 else ((WIDTH // 2 - 1) - x) + return FLOAT_MIP1[idx] + + +def texel_halves(tex_mode, x, y, mutant=None, *, mip=0, slice_=0): + is_depth = tex_mode.startswith('r16_unorm') + oob = (0, 0, 0, 0x3c00) if is_depth else (0, 0, 0, 0) + max_slices = 2 if tex_mode.endswith('_array') else 1 + if not (0 <= mip < 2 and 0 <= slice_ < max_slices): + return oob + mw, mh = WIDTH >> mip, HEIGHT >> mip + if not (0 <= x < mw and 0 <= y < mh): + return oob + rgba = texel_f32_words(tex_mode, x, y, mip=mip, slice_=slice_) + if is_depth: + if mutant in ('rtz', 'mip_rtz'): return tuple(pack16_rtz_ref(c) for c in rgba) - if mutant == 'double_round': + if mutant in ('double_round', 'mip_double_round'): return tuple(pack16_rne_ref(c) for c in rgba) - return (exact_unorm16_f16_ref(DEPTH_TEXELS[idx]), 0, 0, 0x3c00) - narrow = pack16_rtz_ref if mutant == 'rtz' else pack16_rne_ref - return tuple(narrow(c) for c in FLOAT_TEXELS[idx]) + u16 = ( + DEPTH_TEXELS[(y * WIDTH + x) if slice_ == 0 else (WIDTH * HEIGHT - 1 - (y * WIDTH + x))] + if mip == 0 + else DEPTH_MIP1[slice_][x] + ) + return (exact_unorm16_f16_ref(u16), 0, 0, 0x3c00) + narrow = pack16_rtz_ref if mutant in ('rtz', 'mip_rtz') else pack16_rne_ref + return tuple(narrow(c) for c in rgba) def pack_pair(lo, hi): @@ -368,9 +477,9 @@ def expected_words(fixture, tex_mode, mutant=None): out = [] for y in range(HEIGHT): for x in range(WIDTH): - rgba = texel_f32_words(tex_mode, x, y) - hx, hy, hz, hw = texel_halves(tex_mode, x, y, mutant) if fixture == 'A': + rgba = texel_f32_words(tex_mode, x, y) + hx, hy, hz, hw = texel_halves(tex_mode, x, y, mutant) w0 = rgba[0] if mutant == 'unpacked_x' else f32_bits_from_f16_bits(hx) ax, ay = (x | (y << 16), 63) if mutant == 'drop_a16' else (x, y) hax, _, haz, _ = texel_halves(tex_mode, ax, ay, mutant) @@ -385,8 +494,29 @@ def expected_words(fixture, tex_mode, mutant=None): w2 = pack_pair(hnx, hny) w3 = (0xdead0000 | hnz) if mutant == 'unmasked_odd_hi' else hnz out.extend((w0, w1, w2, w3)) - else: + elif fixture == 'B': + hx, hy, hz, hw = texel_halves(tex_mode, x, y, mutant) out.extend((pack_pair(hx, hy), pack_pair(hz, hw), hy, pack_pair(hz, hw))) + elif fixture == 'C': + mip = 0 if mutant == 'mip_zero' else y + tx = x >> y + hx, _, hz, _ = texel_halves(tex_mode, tx, 0, mutant, mip=mip) + w0 = f32_bits_from_f16_bits(hx) + w1 = pack_pair(hx, hz) + nty = 63 if mutant == 'mip_drop_nsa' else 0 + hnx, hny, hnz, _ = texel_halves(tex_mode, tx, nty, mutant, mip=mip) + w2 = pack_pair(hnx, hny) + w3 = (0xdead0000 | hnz) if mutant == 'mip_unmasked_odd_hi' else hnz + out.extend((w0, w1, w2, w3)) + elif fixture == 'D': + tx = x >> 1 + s, m = (y, x & 1) if mutant == 'swap_slice_mip' else (x & 1, y) + hx, hy, hz, hw = texel_halves(tex_mode, tx, 0, mutant, mip=m, slice_=s) + nty = 63 if mutant == 'array_drop_nsa' else 0 + hnx, _, hnz, hnw = texel_halves(tex_mode, tx, nty, mutant, mip=m, slice_=s) + out.extend((pack_pair(hx, hy), pack_pair(hz, hw), hnx, pack_pair(hnz, hnw))) + else: + raise ValueError(fixture) return out @@ -504,7 +634,8 @@ def check_rounding_formula(): def check_decoder_and_masks(): - for blob, expected_text in ((PRE_WORDS, PRE), (POST_WORDS_A, POST_A), (POST_WORDS_B, POST_B)): + for blob, expected_text in ((PRE_WORDS, PRE), (PRE_WORDS_C, PRE_C), (PRE_WORDS_D, PRE_D), + (POST_WORDS_A, POST_A), (POST_WORDS_B, POST_B)): off = 0 decoded = [] while off < len(blob): @@ -518,65 +649,78 @@ def check_decoder_and_masks(): length, _, asm, _ = D.decode_instruction(raw, 0) assert length == len(raw) and asm == text, (key, length, asm, text) - # Check all 15 non-zero dmasks for destination register width, pairwise component order and odd-dmask gating. - for dmask in range(1, 16): - comps = [c for bit, c in enumerate('xyzw') if dmask & (1 << bit)] - expected_regs = (len(comps) + 1) // 2 - raw = encode_mimg(IMG_LOAD, dmask=dmask, vaddr=8, vdata=4, d16=1) - _, _, asm, _ = D.decode_instruction(raw, 0) - expected_dst = 'v4' if expected_regs == 1 else 'v[4:5]' - assert asm.startswith(f'image_load {expected_dst}, '), (dmask, asm) - if len(comps) % 2 == 1: - odd_reg = 4 + (len(comps) - 1) // 2 - expect_refused( - lambda r=raw: G.Pipeline(VS_WORDS, PRE_WORDS + r + POST_WORDS, root_blob(), - ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV), - f'whole-word read of v{odd_reg} after odd d16 image_load', - f'odd dmask 0x{dmask:x} direct export', - ) - ps_blob = PRE_WORDS + raw + encode_v_and_low16(odd_reg) + POST_WORDS - else: - ps_blob = PRE_WORDS + raw + POST_WORDS - pipe = G.Pipeline(VS_WORDS, ps_blob, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) - ps = pipe.hlsl_ps() - manifest = pipe.manifest() - assert PACK16_HELPERS_HLSL in ps - assert 'udsrc 4 d16unorm16 0' in manifest.splitlines(), manifest - assert 'd16srv 0 exact' in manifest.splitlines(), manifest - assert 'SamplerState' not in ps and 'smp ' not in manifest - for i in range(0, len(comps), 2): - reg = 4 + i // 2 - if i + 1 == len(comps): - want = f'v{reg} = pack16_d16(t.{comps[i]}, ud4);' + # Check all 15 non-zero dmasks on both image_load and image_load_mip for destination width, + # pairwise component order, explicit mip Load coordinates and odd-dmask gating. + for op_name, op_code, pre_words, want_load in ( + ('image_load', IMG_LOAD, PRE_WORDS, 'r0.Load(int3(v8, v9, 0))'), + ('image_load_mip', IMG_LOAD_MIP, PRE_WORDS_C, 'r0.Load(int3(v8, v9, v10))'), + ): + for dmask in range(1, 16): + comps = [c for bit, c in enumerate('xyzw') if dmask & (1 << bit)] + expected_regs = (len(comps) + 1) // 2 + raw = encode_mimg(op_code, dmask=dmask, vaddr=8, vdata=4, d16=1) + _, _, asm, _ = D.decode_instruction(raw, 0) + expected_dst = 'v4' if expected_regs == 1 else 'v[4:5]' + assert asm.startswith(f'{op_name} {expected_dst}, '), (op_name, dmask, asm) + if len(comps) % 2 == 1: + odd_reg = 4 + (len(comps) - 1) // 2 + expect_refused( + lambda r=raw, pw=pre_words: G.Pipeline( + VS_WORDS, pw + r + POST_WORDS, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV + ), + f'whole-word read of v{odd_reg} after odd d16 image_load', + f'{op_name} odd dmask 0x{dmask:x} direct export', + ) + ps_blob = pre_words + raw + encode_v_and_low16(odd_reg) + POST_WORDS else: - want = f'v{reg} = pack16_d16(t.{comps[i]}, ud4) | (pack16_d16(t.{comps[i + 1]}, ud4) << 16);' - assert want in ps, (dmask, want, ps) - - # Verify 3D and 2D-array level-zero D16 loads, plus vertex-stage emission. - for key, hlsl_type, srv_kind in (('d16_3d', 'Texture3D<float4>', 'tex3d'), - ('d16_2da', 'Texture2DArray<float4>', 'tex2da')): - ps_3 = PRE_WORDS + MIMG_LLVM_MC[key][1] + POST_WORDS + ps_blob = pre_words + raw + POST_WORDS + pipe = G.Pipeline(VS_WORDS, ps_blob, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) + ps = pipe.hlsl_ps() + manifest = pipe.manifest() + assert PACK16_HELPERS_HLSL in ps + assert want_load in ps, (op_name, dmask, ps) + assert 'udsrc 4 d16unorm16 0' in manifest.splitlines(), manifest + assert 'd16srv 0 exact' in manifest.splitlines(), manifest + assert 'SamplerState' not in ps and 'smp ' not in manifest + for i in range(0, len(comps), 2): + reg = 4 + i // 2 + if i + 1 == len(comps): + want = f'v{reg} = pack16_d16(t.{comps[i]}, ud4);' + else: + want = f'v{reg} = pack16_d16(t.{comps[i]}, ud4) | (pack16_d16(t.{comps[i + 1]}, ud4) << 16);' + assert want in ps, (op_name, dmask, want, ps) + + # Verify 3D and 2D-array level-zero and explicit-mip D16 loads, plus vertex-stage emission. + for key, hlsl_type, srv_kind, want_call, pre_words in ( + ('d16_3d', 'Texture3D<float4>', 'tex3d', 'r0.Load(int4(v0, v1, v2, 0))', PRE_WORDS), + ('d16_2da', 'Texture2DArray<float4>', 'tex2da', 'r0.Load(int4(v0, v1, v2, 0))', PRE_WORDS), + ('mip_d16_3d', 'Texture3D<float4>', 'tex3d', 'r0.Load(int4(v0, v1, v2, v3))', PRE_WORDS), + ('mip_d16_2da_xyzw', 'Texture2DArray<float4>', 'tex2da', 'r0.Load(int4(v8, v9, v10, v11))', PRE_WORDS_D), + ): + ps_3 = pre_words + MIMG_LLVM_MC[key][1] + POST_WORDS pipe = G.Pipeline(VS_WORDS, ps_3, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) hlsl = pipe.hlsl_ps() manifest = pipe.manifest().splitlines() - assert hlsl_type in hlsl and 'r0.Load(int4(v0, v1, v2, 0))' in hlsl, hlsl + assert hlsl_type in hlsl and want_call in hlsl, (key, hlsl) assert f'srv 0 {srv_kind} table 0 0' in manifest and 'd16srv 0 exact' in manifest - # Vertex stage using image_load ... d16 emits helpers and d16srv, while a pipeline without d16 omits both. - vs_d16 = ( - bytes.fromhex('04040cf4000000fa' '8002027e' '7fc08cbf') - + encode_mimg(IMG_LOAD, dmask=0x3, vaddr=0, vdata=4, d16=1) - + bytes.fromhex('703f8cbf' 'cf0800f804040404' '000081bf') - ) + # Vertex stage using image_load / image_load_mip ... d16 emits helpers and d16srv, while a pipeline without d16 omits both. ps_plain = bytes.fromhex('8002007e' '0f1800f800000000' '000081bf') - vs_pipe = G.Pipeline(vs_d16, ps_plain, root_blob()) - assert PACK16_HELPERS_HLSL in vs_pipe.hlsl_vs() - assert 'v4 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in vs_pipe.hlsl_vs() - assert 'd16srv 0 exact' in vs_pipe.manifest().splitlines() + for op_code, want_call in ((IMG_LOAD, 'r0.Load(int3(v0, v1, 0))'), (IMG_LOAD_MIP, 'r0.Load(int3(v0, v1, v2))')): + vs_d16 = ( + bytes.fromhex('04040cf4000000fa' '8002027e' '8002047e' '7fc08cbf') + + encode_mimg(op_code, dmask=0x3, vaddr=0, vdata=4, d16=1) + + bytes.fromhex('703f8cbf' 'cf0800f804040404' '000081bf') + ) + vs_pipe = G.Pipeline(vs_d16, ps_plain, root_blob()) + assert PACK16_HELPERS_HLSL in vs_pipe.hlsl_vs() + assert want_call in vs_pipe.hlsl_vs(), vs_pipe.hlsl_vs() + assert 'v4 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in vs_pipe.hlsl_vs() + assert 'd16srv 0 exact' in vs_pipe.manifest().splitlines() plain_pipe = G.Pipeline(VS_WORDS, ps_plain, root_blob()) assert 'pack16_' not in plain_pipe.hlsl_vs() and 'pack16_' not in plain_pipe.hlsl_ps() assert 'd16srv' not in plain_pipe.manifest() and 'd16unorm16' not in plain_pipe.manifest() - print('decoder & masks: all 15 non-zero dmasks, 2D/a16/NSA/3D/2D_ARRAY, d16srv manifest and VS/PS paths verified') + print('decoder & masks: all 15 non-zero dmasks (load & load_mip), 2D/a16/NSA/3D/2D_ARRAY, d16srv and VS/PS paths verified') def check_srv_format_controls(): @@ -589,10 +733,12 @@ def check_srv_format_controls(): assert {DXGI_FORMAT_VALUES[n] for n in unorm16_names} == G.D16_UNORM16_SRV_FORMATS ps_even = PRE_WORDS + MIMG_LLVM_MC['d16_xyzw'][1] + POST_WORDS + ps_mip_even = PRE_WORDS_C + MIMG_LLVM_MC['mip_d16_xz'][1] + POST_WORDS for fmt in sorted(G.D16_EXACT_SRV_FORMATS): - pipe = G.Pipeline(VS_WORDS, ps_even, root_blob(), ps_hw_inputs=PACKED_INPUT, - rtv_formats=UINT_RTV, srv_formats=(fmt,)) - assert 'd16srv 0 exact' in pipe.manifest().splitlines() + for blob in (ps_even, ps_mip_even): + pipe = G.Pipeline(VS_WORDS, blob, root_blob(), ps_hw_inputs=PACKED_INPUT, + rtv_formats=UINT_RTV, srv_formats=(fmt,)) + assert 'd16srv 0 exact' in pipe.manifest().splitlines() # Integer (UINT/SINT), typeless, depth-stencil-only, SNORM16, R24_UNORM, SRGB, BCn and console formats are refused. refused_srv_formats = ( @@ -630,13 +776,14 @@ def check_srv_format_controls(): (119, 'console R16_UNORM_X8_TYPELESS'), ) for fmt, label in refused_srv_formats: - expect_refused( - lambda f=fmt: G.Pipeline(VS_WORDS, ps_even, root_blob(), ps_hw_inputs=PACKED_INPUT, - rtv_formats=UINT_RTV, srv_formats={0: f}), - f'image_load d16 unsupported SRV format {fmt}', - f'srv_formats {label}', - ) - print(f'srv formats: 14 exact formats match d16_image_format.h; {len(refused_srv_formats)} non-exact formats refused') + for op_name, blob in (('image_load', ps_even), ('image_load_mip', ps_mip_even)): + expect_refused( + lambda f=fmt, b=blob: G.Pipeline(VS_WORDS, b, root_blob(), ps_hw_inputs=PACKED_INPUT, + rtv_formats=UINT_RTV, srv_formats={0: f}), + f'{op_name} d16 unsupported SRV format {fmt}', + f'{op_name} srv_formats {label}', + ) + print(f'srv formats: 14 exact formats match d16_image_format.h; {len(refused_srv_formats)} non-exact formats refused on load & load_mip') def check_odd_dmask_consumers(): @@ -678,6 +825,8 @@ def stage_with(lines, *, has_branches=False): odd_1 = 'image_load v4, v[0:1], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D d16' odd_3 = 'image_load v[6:7], v[0:1], s[16:23] dmask:0x7 dim:SQ_RSRC_IMG_2D d16' + odd_mip_1 = 'image_load_mip v4, v[0:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D d16' + odd_mip_3 = 'image_load_mip v[6:7], v[0:2], s[16:23] dmask:0x7 dim:SQ_RSRC_IMG_2D d16' accepted_sequences = ( (odd_1, 'v_cvt_f32_f16_e32 v4, v4', 'v_add_f32_e32 v4, 1.0, v4'), @@ -694,6 +843,8 @@ def stage_with(lines, *, has_branches=False): (odd_1, 'v_fma_mixlo_f16 v8, v4, 1.0, 0 op_sel_hi:[1,0,0]', 'v_add_nc_u32_e32 v8, 1, v8'), (odd_1, 'v_fma_mixhi_f16 v4, 1.0, 1.0, 0', 'v_add_nc_u32_e32 v4, 1, v4'), (odd_3, 'v_add_nc_u32_e32 v6, 1, v6', 'v_cvt_f32_f16_e32 v7, v7', 'v_add_f32_e32 v7, 1.0, v7'), + (odd_mip_1, 'v_cvt_f32_f16_e32 v4, v4', 'v_add_f32_e32 v4, 1.0, v4'), + (odd_mip_3, 'v_add_nc_u32_e32 v6, 1, v6', 'v_and_b32_e32 v7, 0xffff, v7', 'v_add_nc_u32_e32 v7, 1, v7'), ) for seq in accepted_sequences: stage_with(seq) @@ -735,6 +886,15 @@ def stage_with(lines, *, has_branches=False): ('v7 dmask 0x7 tail', (odd_3, 'v_add_nc_u32_e32 v5, 1, v7'), 'whole-word read of v7'), + ('mip v4 add', + (odd_mip_1, 'v_add_nc_u32_e32 v5, 1, v4'), + 'whole-word read of v4'), + ('mip v7 dmask 0x7 tail', + (odd_mip_3, 'v_add_nc_u32_e32 v5, 1, v7'), + 'whole-word read of v7'), + ('mip coord odd v4', + (odd_1, 'image_load_mip v[6:7], [v0, v1, v4], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D d16'), + 'whole-word read of v4'), ) for label, seq, msg in refused_sequences: expect_refused(lambda s=seq: stage_with(s), msg, label) @@ -779,16 +939,21 @@ def check_refusals(): def build_ps(mimg_bytes): return G.Pipeline(VS_WORDS, PRE_WORDS + mimg_bytes + POST_WORDS, root_blob(), ps_hw_inputs=PACKED_INPUT) - expect_refused(lambda: build_ps(MIMG_LLVM_MC['mip_d16_refused'][1]), 'image_load_mip', 'image_load_mip d16') expect_refused(lambda: build_ps(MIMG_LLVM_MC['1d_d16_refused'][1]), '1D', '1D image_load d16') + expect_refused(lambda: build_ps(MIMG_LLVM_MC['mip_1d_d16_refused'][1]), '1D', '1D image_load_mip d16') expect_refused(lambda: build_ps(MIMG_LLVM_MC['cube_d16_refused'][1]), 'SQ_RSRC_IMG_CUBE', 'cube image_load d16') + expect_refused(lambda: build_ps(MIMG_LLVM_MC['mip_cube_d16_refused'][1]), 'SQ_RSRC_IMG_CUBE', 'cube image_load_mip d16') expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, dim=DIM_3D, a16=1, d16=1)), 'image_load', '3D a16+d16') expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, dim=DIM_2D_ARRAY, a16=1, d16=1)), 'image_load', '2D_ARRAY a16+d16') - expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, dmask=0, d16=1)), 'dmask:0x0', 'dmask 0 d16') - expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, tfe=1, d16=1)), 'tfe', 'tfe d16') - expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, lwe=1, d16=1)), 'lwe', 'lwe d16') - expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, r128=1, d16=1)), 'r128', 'r128 d16') - expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, w0_reserved=0x40, d16=1)), 'reserved', 'w0 reserved d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD_MIP, dim=DIM_2D, a16=1, d16=1)), 'image_load_mip a16', 'mip 2D a16+d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD_MIP, dim=DIM_3D, a16=1, d16=1)), 'image_load_mip a16', 'mip 3D a16+d16') + expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD_MIP, dim=DIM_2D_ARRAY, a16=1, d16=1)), 'image_load_mip a16', 'mip 2D_ARRAY a16+d16') + for op_name, op_code in (('image_load', IMG_LOAD), ('image_load_mip', IMG_LOAD_MIP)): + expect_refused(lambda o=op_code: build_ps(encode_mimg(o, dmask=0, d16=1)), 'dmask:0x0', f'{op_name} dmask 0 d16') + expect_refused(lambda o=op_code: build_ps(encode_mimg(o, tfe=1, d16=1)), 'tfe', f'{op_name} tfe d16') + expect_refused(lambda o=op_code: build_ps(encode_mimg(o, lwe=1, d16=1)), 'lwe', f'{op_name} lwe d16') + expect_refused(lambda o=op_code: build_ps(encode_mimg(o, r128=1, d16=1)), 'r128', f'{op_name} r128 d16') + expect_refused(lambda o=op_code: build_ps(encode_mimg(o, w0_reserved=0x40, d16=1)), 'reserved', f'{op_name} w0 reserved d16') expect_refused(lambda: build_ps(encode_mimg(IMG_LOAD, a16=1, d16=1, nsa=1, extra_addrs=(1,))), 'invalid_nsa', 'a16+d16 fake NSA') sample_pre = PRE_WORDS + bytes.fromhex('800398be800399be80039abe80039bbe') @@ -816,7 +981,35 @@ def build_ps(mimg_bytes): 'image_load address or modifiers', '1-VGPR addr without a16', ) - print('refusals: image_load_mip, sample/sample_lz, 1D/cube, 3D/array a16, tfe/lwe/r128/reserved and bad tuple widths refused') + expect_refused( + lambda: pipe.ps.image(['v[4:7]', 'v[8:10]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0xf', 'd16'], 'load_mip'), + 'image_load_mip d16 destination v[4:7] for dmask 0xf', + 'mip 4-VGPR dst on dmask 0xf d16', + ) + expect_refused( + lambda: pipe.ps.image(['v[4:5]', 'v[8:10]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0x3', 'd16'], 'load_mip'), + 'image_load_mip d16 destination v[4:5] for dmask 0x3', + 'mip 2-VGPR dst on dmask 0x3 d16', + ) + expect_refused( + lambda: pipe.ps.image(['v[4:5]', 'v[8:9]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0xf', 'd16'], 'load_mip'), + 'image_load_mip address or modifiers', + 'mip 2-VGPR addr on 2D d16', + ) + pipe_d = G.Pipeline(VS_WORDS, PS_WORDS_D, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV) + expect_refused( + lambda: pipe_d.ps.image(['v[4:5]', 'v[8:10]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D_ARRAY', 'dmask:0xf', 'd16'], 'load_mip'), + 'image_load_mip address or modifiers', + 'mip 3-VGPR addr on 2D_ARRAY d16', + ) + cs_stage = G.Stage.__new__(G.Stage) + cs_stage.kind = 'cs' + expect_refused( + lambda: cs_stage.image(['v[4:5]', 'v[0:2]', 's[16:23]'], ['dim:SQ_RSRC_IMG_2D', 'dmask:0xf', 'd16'], 'load_mip'), + 'compute d16 image load', + 'compute image_load_mip d16', + ) + print('refusals: sample/sample_lz, 1D/cube, mip/3D/array a16, compute d16, tfe/lwe/r128/reserved and bad tuple widths refused') def controls(): @@ -830,11 +1023,13 @@ def controls(): def check_binary(llvm_mc): assert assemble(llvm_mc, PS_SOURCE_A) == PS_WORDS_A, 'PS_SOURCE_A encoding mismatch' assert assemble(llvm_mc, PS_SOURCE_B) == PS_WORDS_B, 'PS_SOURCE_B encoding mismatch' + assert assemble(llvm_mc, PS_SOURCE_C) == PS_WORDS_C, 'PS_SOURCE_C encoding mismatch' + assert assemble(llvm_mc, PS_SOURCE_D) == PS_WORDS_D, 'PS_SOURCE_D encoding mismatch' for key, (inst, expected) in sorted(MIMG_LLVM_MC.items()): built = assemble(llvm_mc, inst + '\n') if built != expected: raise AssertionError(f'{key}: assembled {built.hex()}, recorded {expected.hex()}') - print(f'llvm-mc: {len(MIMG_LLVM_MC)} MIMG encodings and both pixel fixtures match recorded words') + print(f'llvm-mc: {len(MIMG_LLVM_MC)} MIMG encodings and all four pixel fixtures match recorded words') def check_decode(library): @@ -895,6 +1090,59 @@ def mutate_hlsl_a(source, mutant): return mutated +def mutate_hlsl_c(source, mutant): + if mutant == 'mip_zero': + t_contig = 't = r0.Load(int3(v8, v9, v10));' + t_nsa = 't = r0.Load(int3(v2, v9, v10));' + assert source.count(t_contig) == 2 and source.count(t_nsa) == 1, source + mutated = (source.replace(t_contig, 't = r0.Load(int3(v8, v9, 0));') + .replace(t_nsa, 't = r0.Load(int3(v2, v9, 0));')) + elif mutant == 'mip_drop_nsa': + target = 't = r0.Load(int3(v2, v9, v10));' + assert source.count(target) == 1, source + mutated = source.replace(target, 't = r0.Load(int3(v2, v3, v10));', 1) + elif mutant == 'mip_rtz': + assert source.count(PACK16_RNE_HLSL) == 1 and source.count(PACK16_D16_HLSL) == 1, source + mutated = (source.replace(PACK16_RNE_HLSL, PACK16_RTZ_HLSL, 1) + .replace('return unorm16 != 0u ? pack16_unorm16(value) : pack16_rne(value);', + 'return pack16_rne(value);', 1)) + elif mutant == 'mip_double_round': + target = 'return unorm16 != 0u ? pack16_unorm16(value) : pack16_rne(value);' + assert source.count(target) == 1, source + mutated = source.replace(target, 'return pack16_rne(value);', 1) + elif mutant == 'poison_odd_hi': + t4 = 'v4 = pack16_d16(t.x, ud4);' + t7 = 'v7 = pack16_d16(t.z, ud4);' + assert source.count(t4) == 1 and source.count(t7) == 1, source + mutated = (source.replace(t4, 'v4 = 0xdead0000u | pack16_d16(t.x, ud4);', 1) + .replace(t7, 'v7 = 0xdead0000u | pack16_d16(t.z, ud4);', 1)) + else: + raise ValueError(mutant) + assert mutated != source, mutant + return mutated + + +def mutate_hlsl_d(source, mutant): + if mutant == 'swap_slice_mip': + t_contig = 't = r0.Load(int4(v8, v9, v10, v11));' + t_nsa = 't = r0.Load(int4(v12, v9, v10, v11));' + assert source.count(t_contig) == 1 and source.count(t_nsa) == 2, source + mutated = (source.replace(t_contig, 't = r0.Load(int4(v8, v9, v11, v10));') + .replace(t_nsa, 't = r0.Load(int4(v12, v9, v11, v10));')) + elif mutant == 'array_drop_nsa': + t_nsa = 't = r0.Load(int4(v12, v9, v10, v11));' + assert source.count(t_nsa) == 2, source + mutated = source.replace(t_nsa, 't = r0.Load(int4(v12, v13, v10, v11));') + elif mutant == 'poison_odd_hi': + t6 = 'v6 = pack16_d16(t.x, ud4);' + assert source.count(t6) == 1, source + mutated = source.replace(t6, 'v6 = 0xdead0000u | pack16_d16(t.x, ud4);', 1) + else: + raise ValueError(mutant) + assert mutated != source, mutant + return mutated + + def run_d16_draw(renderer, adapter, tex_mode, vs, ps, words, directory, tag): expected_path = directory / f'{tag}.bin' expected_path.write_bytes(struct.pack('<64I', *words)) @@ -914,7 +1162,11 @@ def run_d16_draw(renderer, adapter, tex_mode, vs, ps, words, directory, tag): def check_draw(dxc, renderer, adapter, fxc=None): hlsl_a = G.Pipeline(VS_WORDS, PS_WORDS_A, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV).hlsl_ps() hlsl_b = G.Pipeline(VS_WORDS, PS_WORDS_B, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV).hlsl_ps() - mutants = ('rtz', 'double_round', 'unpacked_x', 'swap_halves', 'drop_shift', 'drop_a16', 'drop_nsa', 'unmasked_odd_hi') + hlsl_c = G.Pipeline(VS_WORDS, PS_WORDS_C, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV).hlsl_ps() + hlsl_d = G.Pipeline(VS_WORDS, PS_WORDS_D, root_blob(), ps_hw_inputs=PACKED_INPUT, rtv_formats=UINT_RTV).hlsl_ps() + mutants_a = ('rtz', 'double_round', 'unpacked_x', 'swap_halves', 'drop_shift', 'drop_a16', 'drop_nsa', 'unmasked_odd_hi') + mutants_c = ('mip_zero', 'mip_drop_nsa', 'mip_rtz', 'mip_double_round') + mutants_d = ('swap_slice_mip', 'array_drop_nsa') compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) out_dir = HERE.parent / 'out' @@ -925,40 +1177,63 @@ def check_draw(dxc, renderer, adapter, fxc=None): vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, f'vs_{kind}', vs_profile, directory) ps_a = compile_hlsl(compiler, kind, hlsl_a, f'ps_a_{kind}', ps_profile, directory) ps_b = compile_hlsl(compiler, kind, hlsl_b, f'ps_b_{kind}', ps_profile, directory) - ps_poison = compile_hlsl(compiler, kind, mutate_hlsl_a(hlsl_a, 'poison_odd_hi'), - f'ps_poison_{kind}', ps_profile, directory) + ps_c = compile_hlsl(compiler, kind, hlsl_c, f'ps_c_{kind}', ps_profile, directory) + ps_d = compile_hlsl(compiler, kind, hlsl_d, f'ps_d_{kind}', ps_profile, directory) + ps_poison_a = compile_hlsl(compiler, kind, mutate_hlsl_a(hlsl_a, 'poison_odd_hi'), + f'ps_poison_a_{kind}', ps_profile, directory) + ps_poison_c = compile_hlsl(compiler, kind, mutate_hlsl_c(hlsl_c, 'poison_odd_hi'), + f'ps_poison_c_{kind}', ps_profile, directory) + ps_poison_d = compile_hlsl(compiler, kind, mutate_hlsl_d(hlsl_d, 'poison_odd_hi'), + f'ps_poison_d_{kind}', ps_profile, directory) for tex_mode in ('r16_unorm', 'rgba32f'): ref_a = expected_words('A', tex_mode) ref_b = expected_words('B', tex_mode) + ref_c = expected_words('C', tex_mode) run_a = run_d16_draw(renderer, adapter, tex_mode, vs, ps_a, ref_a, directory, f'ref_a_{tex_mode}_{kind}') assert run_a.returncode == 0, f'{kind} A {tex_mode} failed:\n{run_a.stdout}{run_a.stderr}' run_b = run_d16_draw(renderer, adapter, tex_mode, vs, ps_b, ref_b, directory, f'ref_b_{tex_mode}_{kind}') assert run_b.returncode == 0, f'{kind} B {tex_mode} failed:\n{run_b.stdout}{run_b.stderr}' - run_p = run_d16_draw(renderer, adapter, tex_mode, vs, ps_poison, ref_a, - directory, f'poison_{tex_mode}_{kind}') - assert run_p.returncode == 0, f'{kind} poison_odd_hi {tex_mode} leaked:\n{run_p.stdout}{run_p.stderr}' - print(f'{kind} {tex_mode}: fixtures A/B and odd-dmask upper-half poison check matched all words', flush=True) + run_c = run_d16_draw(renderer, adapter, tex_mode, vs, ps_c, ref_c, directory, f'ref_c_{tex_mode}_{kind}') + assert run_c.returncode == 0, f'{kind} C {tex_mode} failed:\n{run_c.stdout}{run_c.stderr}' + run_pa = run_d16_draw(renderer, adapter, tex_mode, vs, ps_poison_a, ref_a, + directory, f'poison_a_{tex_mode}_{kind}') + assert run_pa.returncode == 0, f'{kind} poison_a {tex_mode} leaked:\n{run_pa.stdout}{run_pa.stderr}' + run_pc = run_d16_draw(renderer, adapter, tex_mode, vs, ps_poison_c, ref_c, + directory, f'poison_c_{tex_mode}_{kind}') + assert run_pc.returncode == 0, f'{kind} poison_c {tex_mode} leaked:\n{run_pc.stdout}{run_pc.stderr}' + arr_mode = f'{tex_mode}_array' + ref_d = expected_words('D', arr_mode) + run_d = run_d16_draw(renderer, adapter, arr_mode, vs, ps_d, ref_d, directory, f'ref_d_{arr_mode}_{kind}') + assert run_d.returncode == 0, f'{kind} D {arr_mode} failed:\n{run_d.stdout}{run_d.stderr}' + run_pd = run_d16_draw(renderer, adapter, arr_mode, vs, ps_poison_d, ref_d, + directory, f'poison_d_{arr_mode}_{kind}') + assert run_pd.returncode == 0, f'{kind} poison_d {arr_mode} leaked:\n{run_pd.stdout}{run_pd.stderr}' + print(f'{kind} {tex_mode}[/_array]: fixtures A/B/C/D and odd-dmask poison checks matched all words', flush=True) # Every mutation must fail against the reference and match its mutated model across every # applicable texture mode (drop_shift uses rgba32f because t.z is 0.0 on R16_UNORM; double_round - # uses r16_unorm to exercise 0xffaf -> 0x3bfe vs 0x3bfd and 0xffef -> 0x3c00 vs 0x3bff). - for mut in mutants: - ps_mut = compile_hlsl(compiler, kind, mutate_hlsl_a(hlsl_a, mut), f'mut_{mut}_{kind}', ps_profile, directory) - if mut == 'drop_shift': - modes = ('rgba32f',) - elif mut == 'double_round': - modes = ('r16_unorm',) - else: - modes = ('r16_unorm', 'rgba32f') + # and mip_double_round use r16_unorm to exercise 0xffaf -> 0x3bfe vs 0x3bfd and 0xffef -> 0x3c00 vs 0x3bff). + mutant_cases = ( + [('A', mut, mutate_hlsl_a(hlsl_a, mut), + ('rgba32f',) if mut == 'drop_shift' else ('r16_unorm',) if mut == 'double_round' else ('r16_unorm', 'rgba32f')) + for mut in mutants_a] + + [('C', mut, mutate_hlsl_c(hlsl_c, mut), + ('r16_unorm',) if mut == 'mip_double_round' else ('r16_unorm', 'rgba32f')) + for mut in mutants_c] + + [('D', mut, mutate_hlsl_d(hlsl_d, mut), ('r16_unorm_array', 'rgba32f_array')) + for mut in mutants_d] + ) + for fixture, mut, mutated_hlsl, modes in mutant_cases: + ps_mut = compile_hlsl(compiler, kind, mutated_hlsl, f'mut_{mut}_{kind}', ps_profile, directory) for tex_mode in modes: - ref_words = expected_words('A', tex_mode) + ref_words = expected_words(fixture, tex_mode) fail_run = run_d16_draw(renderer, adapter, tex_mode, vs, ps_mut, ref_words, directory, f'fail_{mut}_{tex_mode}_{kind}') assert fail_run.returncode == 1, ( f'{kind} mutant {mut} ({tex_mode}) unexpectedly passed:\n{fail_run.stdout}{fail_run.stderr}' ) - mut_words = expected_words('A', tex_mode, mutant=mut) + mut_words = expected_words(fixture, tex_mode, mutant=mut) match_run = run_d16_draw(renderer, adapter, tex_mode, vs, ps_mut, mut_words, directory, f'model_{mut}_{tex_mode}_{kind}') assert match_run.returncode == 0, ( diff --git a/tests/startup_image_load_mip_check.py b/tests/startup_image_load_mip_check.py index 0fb4bd69d..f635cf6dc 100644 --- a/tests/startup_image_load_mip_check.py +++ b/tests/startup_image_load_mip_check.py @@ -71,12 +71,12 @@ def check_plain_load_layouts(llvm_mc): d16_ps = shader(bytes.fromhex('080f00f000040480')).hlsl_ps() assert 'v4 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in d16_ps, d16_ps assert 'v5 = pack16_d16(t.z, ud4) | (pack16_d16(t.w, ud4) << 16);' in d16_ps, d16_ps - try: - shader(bytes.fromhex('080f04f000040480')) - except G.Unsupported as error: - assert 'image_load_mip' in str(error) and 'd16' in str(error), error - else: - raise AssertionError('d16 image_load_mip accepted') + d16_mip_pipe = shader(bytes.fromhex('080f04f000040480')) + d16_mip_ps = d16_mip_pipe.hlsl_ps() + assert 'r0.Load(int3(v0, v1, v2))' in d16_mip_ps, d16_mip_ps + assert 'v4 = pack16_d16(t.x, ud4) | (pack16_d16(t.y, ud4) << 16);' in d16_mip_ps, d16_mip_ps + assert 'v5 = pack16_d16(t.z, ud4) | (pack16_d16(t.w, ud4) << 16);' in d16_mip_ps, d16_mip_ps + assert 'd16srv 0 exact' in d16_mip_pipe.manifest().splitlines(), d16_mip_pipe.manifest() for flag, encoded in (('tfe', '080f01f000040400'), ('r128', '088f00f000040400'), ('lwe', '080f02f000040400'), @@ -108,8 +108,8 @@ def check(llvm_mc): assert f'srv 0 {kind} table 0 0' in pipe.manifest(), name assert 'SamplerState' not in pipe.hlsl_ps(), name print(f'{name}: {address}, {kind}, no sampler') - # Packed data, packed addresses and fault-status returns need separate lowering. - for flag, byte, mask in (('d16', 7, 0x80), ('a16', 7, 0x40), ('tfe', 2, 0x01)): + # Packed addresses and fault-status returns remain refused on image_load_mip. + for flag, byte, mask in (('a16', 7, 0x40), ('tfe', 2, 0x01)): unsupported = bytearray.fromhex(CASES[0][2]) unsupported[byte] |= mask try: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 666d0442b..f3844a9f7 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4573,7 +4573,7 @@ def image(self, ops, mods, how): # and Texture2DArray.Load takes int4(x, y, slice, mip) like a volume's int4(x, y, z, mip). axes = 3 if three else 2 packed_2d = how == 'load' and dim == 'SQ_RSRC_IMG_2D' and 'a16' in mods - packed_d16 = how == 'load' and 'd16' in mods + packed_d16 = how in ('load', 'load_mip') and 'd16' in mods allowed = ('unorm', 'glc', 'slc', 'dlc') if packed_2d: allowed += ('a16',) @@ -4585,14 +4585,15 @@ def image(self, ops, mods, how): if unsupported or wrong_address or not dmask: raise Unsupported('image_%s address or modifiers: %s' % (how, ' '.join(mods))) if packed_d16: + op_name = 'image_' + how expected_dst = (bin(dmask).count('1') + 1) // 2 if not dst or dst[0] != 'v' or dst[2] - dst[1] + 1 != expected_dst or dst[2] > 255: - raise Unsupported('image_load d16 destination %s for dmask %#x' % (ops[0], dmask)) + raise Unsupported('%s d16 destination %s for dmask %#x' % (op_name, ops[0], dmask)) res = self.pipe.resources[desc_key] if res['index'] in self.pipe.srv_formats: fmt = self.pipe.srv_formats[res['index']] if fmt not in D16_EXACT_SRV_FORMATS: - raise Unsupported('image_load d16 unsupported SRV format %d' % fmt) + raise Unsupported('%s d16 unsupported SRV format %d' % (op_name, fmt)) if packed_2d: packed = self.u(cs[0]) address = ['%s & 0xffffu' % packed, '%s >> 16' % packed] @@ -4671,7 +4672,7 @@ def image(self, ops, mods, how): else: call = '%s.Sample(%s, %s)' % (tex, smp, uv) self.emit('t = %s;' % call) - if how == 'load' and 'd16' in mods: + if how in ('load', 'load_mip') and 'd16' in mods: res = self.pipe.resources[desc_key] res['d16_exact'] = True mode_arg = 'ud%d' % self.pipe.ud(('d16unorm16', res['index'])) @@ -6353,8 +6354,8 @@ def read(fmt, data, offset): UINT_RTVS = frozenset((3, 7, 12, 17, 25, 30, 36, 42, 50, 57, 62)) SINT_RTVS = frozenset((4, 8, 14, 18, 32, 38, 43, 52, 59, 64)) FLOAT32_RTVS = frozenset((2, 6, 16, 41)) -# DXGI_FORMAT values independently verified exact for D16 image_load, matching d16_srv_mode() -# in src/startup_stubs/d16_image_format.h (#2023): 32-bit float and 8-bit UNORM views (exact via +# DXGI_FORMAT values independently verified exact for D16 image_load and image_load_mip, matching +# d16_srv_mode() in src/startup_stubs/d16_image_format.h (#2023): 32-bit float and 8-bit UNORM views (exact via # pack16_rne) plus 16-bit UNORM views (exact via pack16_unorm16). D16_FLOAT_EXACT_SRV_FORMATS = frozenset((2, 6, 16, 21, 28, 41, 49, 61, 65, 87, 88)) D16_UNORM16_SRV_FORMATS = frozenset((11, 35, 56)) From fc97ade7ed00bd7b70e6123ac4ab3c601d2ac732 Mon Sep 17 00:00:00 2001 From: JB2WIN <joshua2win@gmail.com> Date: Wed, 25 Nov 2026 22:53:40 +0100 Subject: [PATCH 194/232] d3d12: opt-in release of retired textures held only by never-overwritten descriptor slots (#2579) * d3d12: opt-in diagnostics for why released resources stay retained X2W_D3D12_RETIRE_REASONS=1 (with X2W_D3D12_RELEASE_RETIRED=1 and X2W_D3D12_BUDGET=1) adds one "x2w-retire held:" line to the heartbeat. It counts final-released resources whose desktop object is still alive, by reason (view-refs, list-hold, flight, queued-waiting-fence, left-class:*, never-class:*) with bytes from the budget ticket and the age in frames. The retire class decision now records why a resource is not a member, and the first use that took it out of the class. No behavior change; without the switches nothing is recorded and no line is built. Fixture startup_resource_retire_reasons creates one resource per main reason and compares the whole line; the off and no-retire modes are the negative controls. AI-assisted (Claude Code) Refs #2379 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * d3d12: opt-in X2W_D3D12_RELEASE_RETIRED_VIEWS frees released textures held only by descriptor slots With X2W_D3D12_RELEASE_RETIRED=1 a released class texture stayed retained for as long as any tracked slot-18 descriptor slot named it, which is forever when the title never overwrites the slot. With the new switch the drain replaces those slots by null SRVs once the release-time fences have passed: shadow entries and refs are dropped in every heap (copies included), the desktop descriptor is rewritten with CreateShaderResourceView(nullptr), the view records naming the resource are cleared and the view token in title descriptor memory is cleared. Lists and submissions keep the desktop object through the existing retire_hold/flight mechanism. Without the switch nothing changes. The fixture reads the desktop descriptors back with a compute probe and has keep/noretire negative controls. Four local mutants (null rewrite omitted, release-time fence ignored, token not cleared, copies skipped) fail it. AI-assisted (Claude Code). Refs #2379 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * d3d12: clear retired view slots under draw_lock A translated draw holds draw_lock from reading a view record until it records its hold on the sampled texture. Clearing the records without that lock let the drain drop a texture between those two steps, so the draw recorded a texture it no longer held. Take draw_lock (try, never blocking) before note_lock, in the draw path's order. AI-assisted (Claude Code). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 42 ++ docs/startup-runtime.md | 43 ++ src/startup_stubs/d3d12_capture.inl | 4 +- src/startup_stubs/d3d12_xs_device.cpp | 419 +++++++++++++- src/startup_stubs/resource_budget.h | 14 + tests/startup_resource_retire_reasons.cpp | 456 +++++++++++++++ tests/startup_resource_retire_views.cpp | 657 ++++++++++++++++++++++ 7 files changed, 1615 insertions(+), 20 deletions(-) create mode 100644 tests/startup_resource_retire_reasons.cpp create mode 100644 tests/startup_resource_retire_views.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index dbc45262c..eb977a69d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1346,6 +1346,26 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") endforeach() +# X2W_D3D12_RETIRE_REASONS=1 names why released resources still hold their desktop object (needs RELEASE_RETIRED and +# BUDGET). `off` (no RETIRE_REASONS) and `no-retire` (no RELEASE_RETIRED) are negative controls: the line must stay empty. +add_executable(startup_resource_retire_reasons tests/startup_resource_retire_reasons.cpp) +target_include_directories(startup_resource_retire_reasons PRIVATE src) +target_compile_features(startup_resource_retire_reasons PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire_reasons PRIVATE d3d12_xs_shim d3d12 dxgi) +foreach(backend IN ITEMS warp hardware) + set(reasons_base "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + add_test(NAME startup_resource_retire_reasons_${backend} COMMAND startup_resource_retire_reasons ${backend}) + set_tests_properties(startup_resource_retire_reasons_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${reasons_base};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_RETIRE_REASONS=1") + add_test(NAME startup_resource_retire_reasons_off_${backend} COMMAND startup_resource_retire_reasons ${backend} off) + set_tests_properties(startup_resource_retire_reasons_off_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${reasons_base};X2W_D3D12_RELEASE_RETIRED=1") + add_test(NAME startup_resource_retire_reasons_no_retire_${backend} COMMAND startup_resource_retire_reasons ${backend} no-retire) + set_tests_properties(startup_resource_retire_reasons_no_retire_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${reasons_base};X2W_D3D12_RETIRE_REASONS=1") +endforeach() + + add_executable(startup_resource_retire_title tests/startup_resource_retire_title.cpp) target_include_directories(startup_resource_retire_title PRIVATE src) target_compile_features(startup_resource_retire_title PRIVATE cxx_std_17) @@ -1362,6 +1382,28 @@ foreach(backend IN ITEMS warp hardware) ENVIRONMENT "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_RESOURCE_INDEX_CHECK=1;X2W_D3D12_DEBUG=0") endforeach() +# X2W_D3D12_RELEASE_RETIRED_VIEWS=1 frees a released class texture that only tracked slot-18 descriptor slots keep alive by +# replacing those slots with null descriptors. `keep` is the negative control (views switch off, or retire switch off). +add_executable(startup_resource_retire_views tests/startup_resource_retire_views.cpp) +target_include_directories(startup_resource_retire_views PRIVATE src) +target_compile_features(startup_resource_retire_views PRIVATE cxx_std_17) +target_link_libraries(startup_resource_retire_views PRIVATE d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(backend IN ITEMS warp hardware) + foreach(debug IN ITEMS 0 1) + set(retire_views_env "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=${debug}") + add_test(NAME startup_resource_retire_views_${backend}_debug${debug} COMMAND startup_resource_retire_views ${backend}) + set_tests_properties(startup_resource_retire_views_${backend}_debug${debug} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_views_env};X2W_D3D12_RELEASE_RETIRED=1;X2W_D3D12_RELEASE_RETIRED_VIEWS=1") + endforeach() + set(retire_views_keep "X2W_D3D12_BUDGET=1;X2W_D3D12_PERMISSIVE=1;X2W_D3D12_LIST_NOOP=1;X2W_D3D12_RENDER=1;X2W_D3D12_DEBUG=0") + add_test(NAME startup_resource_retire_views_keep_${backend} COMMAND startup_resource_retire_views ${backend} keep) + set_tests_properties(startup_resource_retire_views_keep_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_views_keep};X2W_D3D12_RELEASE_RETIRED=1") + add_test(NAME startup_resource_retire_views_noretire_${backend} COMMAND startup_resource_retire_views ${backend} keep) + set_tests_properties(startup_resource_retire_views_noretire_${backend} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "${retire_views_keep};X2W_D3D12_RELEASE_RETIRED_VIEWS=1") +endforeach() + # GPU writes the dispatch record that the desktop command processor consumes (Refs #1412). add_executable(startup_compute_binding_trace tests/startup_compute_binding_trace.cpp) target_compile_features(startup_compute_binding_trace PRIVATE cxx_std_20) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 717fd922e..673534dbf 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1346,6 +1346,8 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | opt-in, effective only together with `X2W_D3D12_RELEASE_RETIRED=1`: a released class texture that only tracked slot-18 descriptor slots keep alive (the title never overwrites them) is freed once those slots are replaced by null descriptors ([details](#d3d12-resource-budget)). Unset, nothing changes | +| `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | | `X2W_DEPTH_STATE=1` | translated draws of slot 57 pipelines take their depth-stencil state and stencil reference from state block A instead of the desktop default (depth and stencil off); a refused block keeps the default. Off by default, then nothing changes: see [Shortcuts that are known to be wrong](#shortcuts-that-are-known-to-be-wrong) | | `X2W_PRESENT_SIGNATURE_EVERY=<n>` | in render mode, samples a coarse signature of the presented picture every `n` presents from the start, without a script request (`0` off). Unset, sampling starts, every 4 presents, only once a script with a `wait` asks for it: see [Waiting for the presented picture](#waiting-for-the-presented-picture) | @@ -1421,6 +1423,47 @@ unordered-access flag, and live in a default heap without heap flags: reusing the same title address or desktop pointer does not skip uploads or resolve a retired wrapper. +`X2W_D3D12_RELEASE_RETIRED_VIEWS=1` (only with `X2W_D3D12_RELEASE_RETIRED=1`) ends the +`view-refs` retention. Once a released class texture's release-time fences have passed, +the drain (a try-lock, never blocking) replaces every tracked slot-18 descriptor slot +that names it, in every heap and so every `CopyDescriptors*` copy, by a null SRV of the +same dimension: the shadow entry and its ref are dropped, the desktop descriptor is +rewritten with `CreateShaderResourceView(nullptr, ...)`, the view records naming the +resource lose it, and the view token in title descriptor memory is cleared when it +still carries that id. A draw that reads the slot afterwards binds a null texture +(zeros). The texture is then freed by the normal rules: lists and submissions that hold +it through `retire_hold` keep the desktop object until the recording is dropped or the +submission's fence passes. No recorded list or submission reads a title heap's SRV +descriptor (translated draws build their own descriptors from the tokens at draw time +and hold what they sample), so the rewrite cannot reach GPU work. A slot that cannot be +rewritten keeps its ref and the texture stays retained. Not covered: a title thread +that writes the same slot at the moment of the drain, and a guest that uses the +resource after its final release (unsupported with the switch, as before). +`startup_resource_retire_views_*` reads the desktop descriptors back through a compute +probe; the `keep` and `noretire` cases are the negative controls. + +`X2W_D3D12_RETIRE_REASONS=1` (with `X2W_D3D12_RELEASE_RETIRED=1` and +`X2W_D3D12_BUDGET=1`) adds a diagnostic line to the heartbeat. It counts every +resource whose final guest Release happened and whose desktop object is still +alive, once, by the first cause that applies. Format: `reason=count/bytes(oldest Nf)`, +bytes from the budget ticket, `oldest` in frames since the final Release: +- `view-refs`: a tracked slot 18 descriptor still names it; + `view-refs-in-visible-heap` is the part with a descriptor in a shader-visible heap. +- `list-hold`, `flight`: a closed or recording list, or a submission, holds a + desktop reference. +- `queued-waiting-fence`: queued, the release-time fence of a queue has not passed; + `drain-pending`: ready, the drain has not run yet; `unqueued`: no queue could take its marker. +- `left-class:<view|view-copy|residency|present|hold-missed>`: it was in the class and the first use named left it. +- `never-class:<buffer|dimension|msaa|rt-ds-uav|heap-type|heap-flags|title-memory|aliased|reserved|slot>`: it was + never in the class (`slot`: created by a path that does not classify). +- `other`: none of the above. +`total` is the sum; `unattributed` is the budget's retained count and bytes minus +`total` (backing heaps, upload and readback objects, and anything created outside the wrappers). +Wrappers without a desktop object (tiled address textures) are not counted. A +released resource that only a list or submission keeps alive after its wrapper +let go is matched by its desktop pointer. Without the switches nothing is +recorded and no line is built. + Every other resource (buffers, placed buffers, reserved resources, render/depth/UAV targets, and slot 127 `__XMemAllocationHooks__` textures) keeps the lifetime described above. A resource leaves the class for good when a UAV/RTV/DSV view is diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 879f71f8e..6f92733f0 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -320,7 +320,7 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ retire_release_view_ref(reinterpret_cast<const void*>(view_records()[prev - 1].resource)); } } else if (slot == 18 && resource) { - retire_leave_class(reinterpret_cast<const void*>(resource)); + retire_leave_class(reinterpret_cast<const void*>(resource), RetireLeft::view); } ReleaseSRWLockExclusive(¬e_lock); const std::size_t token_bytes = slot == 22 ? x2w_startup::title_sampler_stride : 32u; @@ -367,7 +367,7 @@ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, const std::uint32_t src_id = from[i]; if (src_id && src_id - 1 < view_records().size() && view_records()[src_id - 1].slot == 18 && view_materialized()[src_id - 1]) - retire_leave_class(reinterpret_cast<const void*>(view_records()[src_id - 1].resource)); + retire_leave_class(reinterpret_cast<const void*>(view_records()[src_id - 1].resource), RetireLeft::view_copy); } } ReleaseSRWLockExclusive(¬e_lock); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index b5b79f444..06a1eb1c1 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -139,6 +139,13 @@ struct IndirectGraphicsPipeline { UINT cached_srv_root = UINT_MAX; }; +// Why a resource is outside the retire class (X2W_D3D12_RELEASE_RETIRED), decided at creation, and why it left it later. +// Both only feed the opt-in X2W_D3D12_RETIRE_REASONS diagnostics. never::slot is the zero value: created by a path that +// does not classify. +enum class RetireNever : std::uint8_t { slot, none, buffer, dimension, msaa, rt_ds_uav, heap_type, heap_flags, title_memory, + aliased, reserved, count }; +enum class RetireLeft : std::uint8_t { none, view, view_copy, residency, present, hold_missed, count }; + struct alignas(16) WrapperOwn { IUnknown* real; LONG refs; @@ -159,6 +166,10 @@ struct alignas(16) WrapperOwn { // accesses: a race needs the guest to use a resource across its own final Release. bool retire_hold_missed; // Resource: retire_hold could not record a use (no desktop object or no room), so the // drain must keep it for the process instead of dropping a list's desktop object. + bool retire_views_stuck; // Resource: X2W_D3D12_RELEASE_RETIRED_VIEWS could not clear every descriptor slot that + // names it, so it stays retained (and is not scanned again). + std::uint8_t retire_never; // RetireNever of this resource (set only with X2W_D3D12_RELEASE_RETIRED) + std::uint8_t retire_left; // RetireLeft: the first use that took it out of the class volatile LONG retire_view_refs; // Live tracked slot-18 SRV descriptor slots referencing this resource. bool retire_has_written_gen; // Whether written_textures()[title_memory].generation was snapshotted at Release. u64 retire_written_gen; // Snapshotted written_textures() generation for stale-entry cleanup. @@ -792,6 +803,14 @@ bool release_retired_enabled() return on; } +// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (needs X2W_D3D12_RELEASE_RETIRED=1): a released class member that only tracked slot-18 +// descriptor slots keep alive is freed once every such slot has been replaced by a null descriptor. +bool release_retired_views_enabled() +{ + static const bool on = release_retired_enabled() && x2w_local::env_on("X2W_D3D12_RELEASE_RETIRED_VIEWS"); + return on; +} + // The retire class of X2W_D3D12_RELEASE_RETIRED, decided once at creation from the desktop description: a committed // 2D texture with one sample, no render-target, depth-stencil or unordered-access use, in a default heap with no heap // flags. Slot 27 and non-hooked slot 127 have no title memory; slot 133 committed 2D textures with title memory are @@ -799,13 +818,27 @@ bool release_retired_enabled() // resources with __XMemAllocationHooks__ title memory remain excluded. Every use reaches the shim through handlers // that retire_hold or shadow-slot SRV ref-counting cover, or that clear the flag; see // docs/startup-runtime.md#d3d12-resource-budget. -bool retire_class(const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, - const void* title_memory, bool allow_title_memory = false) +RetireNever retire_classify(const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC& desc, + const void* title_memory, bool allow_title_memory) { - return release_retired_enabled() && props.Type == D3D12_HEAP_TYPE_DEFAULT && heap_flags == D3D12_HEAP_FLAG_NONE && - desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1 && - (desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) == D3D12_RESOURCE_FLAG_NONE && - (!title_memory || allow_title_memory); + if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return RetireNever::buffer; + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return RetireNever::dimension; + if (desc.SampleDesc.Count != 1) return RetireNever::msaa; + if ((desc.Flags & ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) != D3D12_RESOURCE_FLAG_NONE) return RetireNever::rt_ds_uav; + if (props.Type != D3D12_HEAP_TYPE_DEFAULT) return RetireNever::heap_type; + if (heap_flags != D3D12_HEAP_FLAG_NONE) return RetireNever::heap_flags; + if (title_memory && !allow_title_memory) return RetireNever::title_memory; + return RetireNever::none; +} + +// Decides the retire class of a new wrapper once, from the desktop description, and records the reason for the diagnostics. +void retire_set_class(Wrapper* w, const D3D12_HEAP_PROPERTIES& props, D3D12_HEAP_FLAGS heap_flags, + const D3D12_RESOURCE_DESC& desc, const void* title_memory, bool allow_title_memory = false) +{ + if (!release_retired_enabled()) return; + const RetireNever why = retire_classify(props, heap_flags, desc, title_memory, allow_title_memory); + w->own().retire_never = static_cast<std::uint8_t>(why); + w->own().retire_when_idle = why == RetireNever::none; } template <int K, int N, int R, int Desc = -1> @@ -838,8 +871,12 @@ __declspec(noinline) u64 create_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d, Wrapper* child = wrap(static_cast<IUnknown*>(*out), kind); if constexpr (K == device_kind && N == 27) { if (kind == resource_kind && args[0]) - child->own().retire_when_idle = retire_class(*reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(args[0]), - static_cast<D3D12_HEAP_FLAGS>(args[1]), desc_copy, nullptr); + retire_set_class(child, *reinterpret_cast<const D3D12_HEAP_PROPERTIES*>(args[0]), + static_cast<D3D12_HEAP_FLAGS>(args[1]), desc_copy, nullptr); + } + if constexpr (K == device_kind && (N == 29 || N == 30)) { + if (kind == resource_kind && release_retired_enabled()) + child->own().retire_never = static_cast<std::uint8_t>(N == 29 ? RetireNever::aliased : RetireNever::reserved); } if constexpr (K == device_kind && (N == 27 || N == 28 || N == 29)) { if (x2w_budget::enabled()) { @@ -931,7 +968,7 @@ ULONG __stdcall add_ref(Wrapper* self) { return static_cast<ULONG>(InterlockedIn void retire_placement(Wrapper* w); void register_retire_queue(Wrapper* queue); void retire_resource(Wrapper* w); -void retire_leave_class(const void* object); +void retire_leave_class(const void* object, RetireLeft why); void retire_add_view_ref(const void* object); void retire_release_view_ref(const void* object); void retire_drop_heap_views(Wrapper* heap); @@ -941,6 +978,8 @@ void retire_drop_recording(Wrapper* list); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists); void drain_retired_resources(); +bool retire_reasons_enabled(); +void retire_diag_note_release(Wrapper* w); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); void clear_unplaced_buffers(Wrapper* device); @@ -960,6 +999,7 @@ ULONG __stdcall release(Wrapper* self) discard_mesh_lease_recording(static_cast<ID3D12CommandList*>(self->own().real)); retire_drop_recording(self); } + if (self->own().kind == resource_kind && retire_reasons_enabled()) retire_diag_note_release(self); if (self->own().retire_when_idle) retire_resource(self); if (self->own().kind == device_kind) clear_unplaced_buffers(self); @@ -1243,7 +1283,7 @@ HRESULT __stdcall device_residency(Wrapper* self, UINT count, void* const* objec { std::vector<ID3D12Pageable*> real(count); for (UINT i = 0; i < count; ++i) { - retire_leave_class(objects[i]); // no hold tracks the residency of a desktop object + retire_leave_class(objects[i], RetireLeft::residency); // no hold tracks the residency of a desktop object real[i] = reinterpret_cast<ID3D12Pageable*>(unwrap(reinterpret_cast<u64>(objects[i]))); } return N == 34 ? device_of(self)->MakeResident(count, real.data()) : device_of(self)->Evict(count, real.data()); @@ -3968,13 +4008,13 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) Timed timed(time_view); // UAV, RTV and DSV views keep the resource's old lifetime; slot-18 SRVs stay in the retire class as long as // their descriptor slots are tracked by shadow_slot and translated draws hold bound resources with retire_hold. - if constexpr (N >= 19 && N <= 21) retire_leave_class(reinterpret_cast<const void*>(a)); - if constexpr (N == 19) retire_leave_class(reinterpret_cast<const void*>(b)); + if constexpr (N >= 19 && N <= 21) retire_leave_class(reinterpret_cast<const void*>(a), RetireLeft::view); + if constexpr (N == 19) retire_leave_class(reinterpret_cast<const void*>(b), RetireLeft::view); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; args[D] = desktop_cpu_handle(args[D]); if (!args[D]) { - if constexpr (N == 18) retire_leave_class(reinterpret_cast<const void*>(a)); + if constexpr (N == 18) retire_leave_class(reinterpret_cast<const void*>(a), RetireLeft::view); return 0; } const auto record_view = [&](bool materialized) { @@ -4313,7 +4353,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 w->own().budget = x2w_budget::committed(device_of(self), created, props.Type); w->own().title_memory = address; note_resource(w, desc, 0); - w->own().retire_when_idle = retire_class(props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); + retire_set_class(w, props, D3D12_HEAP_FLAG_NONE, texture, address, /*allow_title_memory=*/true); *out = w; return S_OK; } @@ -4391,6 +4431,7 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 clear, text, static_cast<unsigned long>(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); if (FAILED(hr)) return hr; Wrapper* w = wrap(resource, resource_kind); + if (release_retired_enabled()) w->own().retire_never = static_cast<std::uint8_t>(RetireNever::buffer); w->own().title_memory = address; const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; auto& group = placement_group(desc->Width); @@ -4469,10 +4510,13 @@ void register_retire_queue(Wrapper* queue) } // A use the holds do not cover (a view, residency, presentation) takes the resource out of the class for good. -void retire_leave_class(const void* object) +void retire_leave_class(const void* object, RetireLeft why) { if (!release_retired_enabled()) return; - if (Wrapper* w = as_wrapper(object)) w->own().retire_when_idle = false; + if (Wrapper* w = as_wrapper(object)) { + if (w->own().retire_when_idle) w->own().retire_left = static_cast<std::uint8_t>(why); // the first use counts + w->own().retire_when_idle = false; + } } void retire_add_view_ref(const void* object) @@ -4573,6 +4617,7 @@ void retire_hold(Wrapper* list, Wrapper* resource) // The use cannot be recorded: leave the class, and mark it so the drain keeps the desktop object for the // process (as it keeps a submission it could not fence) rather than dropping one a list still names. resource->own().retire_when_idle = false; + resource->own().retire_left = static_cast<std::uint8_t>(RetireLeft::hold_missed); resource->own().retire_hold_missed = true; } ReleaseSRWLockExclusive(&retire_lock); @@ -4673,10 +4718,143 @@ void retire_resource(Wrapper* w) if (!queued) InterlockedIncrement64(&retire_kept); // stays retained, as without the switch } +// A null SRV of the dimension the title's view had (the draw path binds the same R8G8B8A8_UNORM null for a view that +// resolves to nothing). A null resource reads no more of the description than its format and dimension. +D3D12_SHADER_RESOURCE_VIEW_DESC retire_null_srv_desc(const ViewRecord& record) +{ + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + if (record.desc_bytes >= 40) { + D3D12_SRV_DIMENSION dimension; + std::memcpy(&dimension, record.desc + 4, sizeof(dimension)); + if (dimension >= D3D12_SRV_DIMENSION_TEXTURE1D && dimension <= D3D12_SRV_DIMENSION_TEXTURECUBEARRAY) + desc.ViewDimension = dimension; + } + switch (desc.ViewDimension) { + case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipLevels = 1; desc.Texture1DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipLevels = 1; desc.Texture2DArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = 1; break; + case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.MipLevels = 1; desc.TextureCubeArray.NumCubes = 1; break; + case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; + default: desc.Texture2D.MipLevels = 1; break; + } + return desc; +} + +// True when the release-time fence of every queue has passed (retire_lock held). +bool retire_fences_reached(const RetiredResource& item) +{ + bool reached = item.targets.size() <= retire_queues.size(); + for (std::size_t q = 0; q < item.targets.size() && reached; ++q) + reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; + return reached; +} + +// X2W_D3D12_RELEASE_RETIRED_VIEWS=1: a released class member whose release-time fences have passed and that only +// tracked slot-18 descriptor slots still name gets those slots replaced by null descriptors, so the main drain loop can +// free it. Every slot of every heap that has a shadow is handled, copies included (they are counted the same way). For +// each slot, under note_lock: the shadow entry is cleared and its ref dropped, and the desktop descriptor is rewritten +// as a null SRV of the same dimension. The view records that name the resource then lose it (so a token that a raw +// title copy left behind resolves to nothing), and the token in title descriptor memory is cleared when it still +// carries the id. A slot that cannot be rewritten keeps its ref, and the resource stays retained. Nothing waits. +// Why this cannot reach GPU work: translated draws never bind a title heap. They build their own descriptors from the +// title's tokens at draw time and retire_hold what they sample, so a descriptor of a title heap is read by no recorded +// list or submission (ClearUnorderedAccessView binds a heap for UAV slots only, and those are not touched here). +void retire_null_ready_views() +{ + std::vector<Wrapper*> ready; + try { + ready.reserve(64); + } catch (const std::bad_alloc&) { + return; + } + if (!TryAcquireSRWLockShared(&retire_lock)) return; + for (const RetiredResource& item : retired_resources) { + Wrapper* w = item.wrapper; + if (ready.size() == ready.capacity()) break; + if (w->own().retire_hold_missed || w->own().retire_views_stuck || !retire_fences_reached(item)) continue; + if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) <= 0) continue; + if (InterlockedCompareExchange(&w->own().refs, 0, 0) != 0) continue; // referenced again: leave its views + ready.push_back(w); + } + ReleaseSRWLockShared(&retire_lock); + if (ready.empty()) return; + + struct Cleared { + u64 title_cpu; + std::uint32_t index, increment, id; + }; + std::vector<Cleared> cleared; + std::size_t stuck = 0; + // draw_lock first, in the order draw_translated takes them: a draw holds it from reading a view record until it + // retire_holds the texture, so clearing the records under it means a draw either recorded its hold already or + // resolves the token to nothing. + if (!TryAcquireSRWLockExclusive(&draw_lock)) return; + if (!TryAcquireSRWLockExclusive(¬e_lock)) { + ReleaseSRWLockExclusive(&draw_lock); + return; + } + try { + std::unordered_set<std::uint32_t> ids; // view ids that name a ready resource + for (std::uint32_t id = 0; id < view_records().size(); ++id) { + const ViewRecord& record = view_records()[id]; + if (record.slot != 18 || !view_materialized()[id]) continue; + if (std::find(ready.begin(), ready.end(), reinterpret_cast<Wrapper*>(record.resource)) != ready.end()) + ids.insert(id); + } + ID3D12Device* const device = the_device ? device_of(the_device) : nullptr; + for (const HeapInfo& h : heap_infos()) { + if (!h.shadow || ids.empty() || !device || !h.desktop_cpu) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t slot_id = h.shadow[i]; + if (!slot_id || !ids.count(slot_id - 1)) continue; + const ViewRecord& record = view_records()[slot_id - 1]; + const D3D12_SHADER_RESOURCE_VIEW_DESC null_view = retire_null_srv_desc(record); + device->CreateShaderResourceView(nullptr, &null_view, + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast<SIZE_T>(h.desktop_cpu + u64{i} * h.increment)}); + h.shadow[i] = 0; + retire_release_view_ref(reinterpret_cast<const void*>(record.resource)); + if (h.title_cpu && h.title_cpu != h.desktop_cpu) cleared.push_back({h.title_cpu, i, h.increment, slot_id - 1}); + } + } + for (Wrapper* w : ready) { + if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + w->own().retire_views_stuck = true; + ++stuck; + continue; + } + for (std::uint32_t id : ids) + if (view_records()[id].resource == reinterpret_cast<u64>(w)) view_records()[id].resource = 0; + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockExclusive(¬e_lock); + ReleaseSRWLockExclusive(&draw_lock); + for (const Cleared& slot : cleared) { + const u64 token = slot.title_cpu + u64{slot.index} * title_descriptor_stride(slot.title_cpu, slot.increment); + if (!title_backed(token, 32) || !x2w_local::writable(reinterpret_cast<void*>(token), 32)) continue; + std::uint32_t words[2]; + std::memcpy(words, reinterpret_cast<const void*>(token), sizeof(words)); + if (words[0] == view_token_magic && words[1] == slot.id) + InterlockedCompareExchange(reinterpret_cast<volatile LONG*>(token), 0, static_cast<LONG>(view_token_magic)); + } + if (stuck) { + static LONG reported; + if (first_calls(reported, 4)) log("x2w-d3d12 retire: %zu released textures keep an untracked descriptor; they stay retained", stuck); + } +} + + // Never blocks: a contended lock or an unfinished queue leaves the work for the next call. void drain_retired_resources() { if (!InterlockedCompareExchange(&retire_pending, 0, 0)) return; + if (release_retired_views_enabled()) retire_null_ready_views(); constexpr std::size_t batch = 256; struct RetiredDrop { Wrapper* wrapper; @@ -4768,6 +4946,207 @@ void drain_retired_resources() } } +// X2W_D3D12_RETIRE_REASONS=1 (with X2W_D3D12_RELEASE_RETIRED=1 and X2W_D3D12_BUDGET=1): why resources that the guest +// released for good still hold their desktop object. Every final guest Release of a resource with a desktop object is +// remembered here; the heartbeat classifies the ones whose object is still alive, once each, by the first cause that +// applies, in the order of the enum below. Counts and bytes come from the budget ticket. Without the switches nothing +// is recorded and no line is built. +bool retire_reasons_enabled() +{ + static const bool on = release_retired_enabled() && x2w_budget::enabled() && x2w_local::env_on("X2W_D3D12_RETIRE_REASONS"); + return on; +} + +struct ReleasedResource { + ID3D12Resource* real; // identity once the wrapper let go of it; dereferenced only while a hold keeps it alive + LONG frame; // frame_number at the final Release +}; +SRWLOCK retire_diag_lock = SRWLOCK_INIT; // a leaf, never held together with another lock +std::unordered_map<Wrapper*, ReleasedResource> retire_diag_released; + +void retire_diag_note_release(Wrapper* w) +{ + if (!w->own().real) return; + AcquireSRWLockExclusive(&retire_diag_lock); + try { + retire_diag_released[w] = {static_cast<ID3D12Resource*>(w->own().real), frame_number}; + } catch (const std::bad_alloc&) { // a diagnostic only: the resource is then missing from the counts + } + ReleaseSRWLockExclusive(&retire_diag_lock); +} + +enum class Held { view_refs, list_hold, flight, waiting_fence, drain_pending, unqueued, left_view, left_view_copy, + left_residency, left_present, left_hold_missed, never_slot, never_buffer, never_dimension, never_msaa, + never_rt_ds_uav, never_heap_type, never_heap_flags, never_title_memory, never_aliased, never_reserved, + other, count }; +constexpr const char* held_names[] = {"view-refs", "list-hold", "flight", "queued-waiting-fence", "drain-pending", + "unqueued", "left-class:view", "left-class:view-copy", "left-class:residency", "left-class:present", + "left-class:hold-missed", "never-class:slot", "never-class:buffer", "never-class:dimension", "never-class:msaa", + "never-class:rt-ds-uav", "never-class:heap-type", "never-class:heap-flags", "never-class:title-memory", + "never-class:aliased", "never-class:reserved", "other"}; +static_assert(std::size(held_names) == static_cast<std::size_t>(Held::count)); +constexpr Held held_left[] = {Held::other, Held::left_view, Held::left_view_copy, Held::left_residency, Held::left_present, + Held::left_hold_missed}; +constexpr Held held_never[] = {Held::never_slot, Held::other, Held::never_buffer, Held::never_dimension, Held::never_msaa, + Held::never_rt_ds_uav, Held::never_heap_type, Held::never_heap_flags, + Held::never_title_memory, Held::never_aliased, Held::never_reserved}; +static_assert(std::size(held_left) == static_cast<std::size_t>(RetireLeft::count)); +static_assert(std::size(held_never) == static_cast<std::size_t>(RetireNever::count)); + +struct RetireReasonReport { + u64 count[static_cast<int>(Held::count)]; + u64 bytes[static_cast<int>(Held::count)]; + LONG oldest[static_cast<int>(Held::count)]; // frames since the final Release of the oldest entry + u64 visible_count, visible_bytes; // view-refs entries with a descriptor in a shader-visible heap +}; + +void retire_reasons_collect(RetireReasonReport& report) +{ + // 1: which resources a tracked slot-18 descriptor names, and whether one of those lies in a shader-visible heap. + std::unordered_map<const Wrapper*, bool> viewed; + AcquireSRWLockShared(¬e_lock); + try { + for (const HeapInfo& h : heap_infos()) { + if (!h.shadow) continue; + for (std::uint32_t i = 0; i < h.count; ++i) { + const std::uint32_t id = h.shadow[i]; + if (!id || id - 1 >= view_records().size() || view_records()[id - 1].slot != 18 || !view_materialized()[id - 1]) + continue; + bool& visible = viewed[reinterpret_cast<const Wrapper*>(view_records()[id - 1].resource)]; + visible = visible || h.desktop_gpu != 0; + } + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockShared(¬e_lock); + + // 2: the remembered final Releases. + std::vector<std::pair<Wrapper*, ReleasedResource>> entries; + AcquireSRWLockShared(&retire_diag_lock); + try { + entries.assign(retire_diag_released.begin(), retire_diag_released.end()); + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockShared(&retire_diag_lock); + + // 3: the retire bookkeeping. own().real is cleared by the drain under this lock, so a non-null pointer read here + // names a desktop object that stays alive for as long as the lock is held. + std::vector<Wrapper*> gone; + AcquireSRWLockShared(&retire_lock); + try { + std::unordered_map<const Wrapper*, const RetiredResource*> queued; + std::unordered_set<const ID3D12Resource*> listed, flying; + for (const RetiredResource& item : retired_resources) queued.emplace(item.wrapper, &item); + for (const auto& list : retire_list_holds) listed.insert(list.second.begin(), list.second.end()); + for (const RetireFlight& flight : retire_flights) flying.insert(flight.resources.begin(), flight.resources.end()); + const LONG now = frame_number; + const auto add = [&](Held why, const x2w_budget::Ticket* ticket, LONG frame) { + const int i = static_cast<int>(why); + ++report.count[i]; + report.bytes[i] += ticket ? static_cast<u64>(ticket->bytes()) : 0; + report.oldest[i] = (std::max)(report.oldest[i], now - frame); + }; + for (const auto& [w, released] : entries) { + if (InterlockedCompareExchange(&w->own().refs, 0, 0) > 0) continue; // referenced again: not released for good + auto* real = static_cast<ID3D12Resource*>(w->own().real); + if (!real) { + // The drain let go of it; only a list hold or a submission can still keep the desktop object. + const bool by_list = listed.count(released.real) != 0; + if (!by_list && !flying.count(released.real)) { + gone.push_back(w); + continue; + } + x2w_budget::Ticket* ticket = x2w_budget::ticket_of(released.real); + add(by_list ? Held::list_hold : Held::flight, ticket, released.frame); + if (ticket) ticket->Release(); + continue; + } + const x2w_budget::Ticket* ticket = w->own().budget; + Held why = Held::other; + const auto found = queued.find(w); + if (!w->own().retire_when_idle) { + if (w->own().retire_left && w->own().retire_left < static_cast<std::uint8_t>(RetireLeft::count)) + why = held_left[w->own().retire_left]; + else if (w->own().retire_never < static_cast<std::uint8_t>(RetireNever::count)) + why = held_never[w->own().retire_never]; + } else if (found == queued.end()) { + why = Held::unqueued; + } else if (InterlockedCompareExchange(&w->own().retire_view_refs, 0, 0) > 0) { + why = Held::view_refs; + if (const auto view = viewed.find(w); view != viewed.end() && view->second) { + ++report.visible_count; + report.visible_bytes += ticket ? static_cast<u64>(ticket->bytes()) : 0; + } + } else if (listed.count(real)) { + why = Held::list_hold; + } else if (flying.count(real)) { + why = Held::flight; + } else { + const RetiredResource& item = *found->second; + bool reached = item.targets.size() <= retire_queues.size(); + for (std::size_t q = 0; q < item.targets.size() && reached; ++q) + reached = retire_queues[q].fence->GetCompletedValue() >= item.targets[q]; + why = reached ? Held::drain_pending : Held::waiting_fence; + } + add(why, ticket, released.frame); + } + } catch (const std::bad_alloc&) { + } + ReleaseSRWLockShared(&retire_lock); + + // 4: forget entries whose desktop object is gone. + if (!gone.empty()) { + AcquireSRWLockExclusive(&retire_diag_lock); + for (Wrapper* w : gone) + if (!w->own().real) retire_diag_released.erase(w); + ReleaseSRWLockExclusive(&retire_diag_lock); + } +} + +// The heartbeat line, or an empty string when the diagnostics are not switched on. unattributed: what the budget still +// counts as retained, less what this classification found (backing heaps, upload and readback objects, anything it cannot see). +std::size_t retire_reasons_line(char* out, std::size_t capacity) +{ + if (!out || !capacity) return 0; + out[0] = 0; + if (!retire_reasons_enabled()) return 0; + RetireReasonReport report{}; + retire_reasons_collect(report); + const x2w_budget::Snapshot budget = x2w_budget::snapshot(); + std::size_t used = 0; + const auto append = [&](const char* format, auto... args) { + if (used + 1 >= capacity) return; + const int n = std::snprintf(out + used, capacity - used, format, args...); + if (n > 0) used = (std::min)(used + static_cast<std::size_t>(n), capacity - 1); + }; + append("x2w-retire held:"); + u64 total_count = 0, total_bytes = 0; + for (int i = 0; i < static_cast<int>(Held::count); ++i) { + if (!report.count[i]) continue; + total_count += report.count[i]; + total_bytes += report.bytes[i]; + append(" %s=%llu/%llu(oldest %ldf)", held_names[i], report.count[i], report.bytes[i], report.oldest[i]); + } + if (!total_count) append(" none"); + if (report.visible_count) append(" view-refs-in-visible-heap=%llu/%llu", report.visible_count, report.visible_bytes); + u64 retained_count = 0, retained_bytes = 0; + for (const auto& retained : budget.retained) { + retained_count += retained.objects; + retained_bytes += retained.bytes; + } + append(" total=%llu/%llu unattributed=%lld/%lld", total_count, total_bytes, + static_cast<long long>(retained_count) - static_cast<long long>(total_count), + static_cast<long long>(retained_bytes) - static_cast<long long>(total_bytes)); + return used; +} + +// Fixture export (startup_resource_retire_reasons): the line the heartbeat logs, now. Returns its length; 0 and an +// empty string without the switches. +extern "C" __declspec(dllexport) std::size_t x2w_d3d12_retire_reasons_line(char* out, std::size_t capacity) +{ + return retire_reasons_line(out, capacity); +} + // Fixture probe (startup_resource_retire): what still names a resource of the class by its raw desktop pointer, how many // resources the open recording of a list moved out of COMMON, and how many it holds. Counts entries only. struct RetireProbe { @@ -5177,7 +5556,7 @@ HRESULT __stdcall device_create_committed_x(Wrapper* self, const D3D12_HEAP_PROP Wrapper* w = wrap(resource, resource_kind); w->own().budget = x2w_budget::committed(device_of(self), resource, props->Type); w->own().title_memory = title_memory; - w->own().retire_when_idle = retire_class(*props, flags, copy, title_memory); + retire_set_class(w, *props, flags, copy, title_memory); note_resource(w, desc, info.SizeInBytes != ~0ull ? info.SizeInBytes : 0); *out = w; return S_OK; @@ -5381,7 +5760,7 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa if (release_retired_enabled() && planes && plane_parameters) { const auto* words = static_cast<const u64*>(plane_parameters); if (x2w_local::readable(words, 0x18) && words[1] >= 1 && x2w_local::readable(reinterpret_cast<const void*>(words[2]), 8)) - retire_leave_class(*reinterpret_cast<void* const*>(words[2])); + retire_leave_class(*reinterpret_cast<void* const*>(words[2]), RetireLeft::present); } drain_retired_resources(); Timed timed(time_present); @@ -5539,6 +5918,10 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa "%lld ms slept", frame, (now - started) / 1000.0, frame * 1000.0 / (now - started ? now - started : 1), frame_waits[0], frame_waits[1], frame_waits[2], frame_waits[3], static_cast<long long>(frame_wait_ms)); if (x2w_budget::enabled()) report_budget(static_cast<ID3D12CommandQueue*>(self->own().real)); + if (retire_reasons_enabled()) { + char line[1536]; + if (retire_reasons_line(line, sizeof(line))) log("%s", line); + } } return S_OK; } diff --git a/src/startup_stubs/resource_budget.h b/src/startup_stubs/resource_budget.h index fc7d9e75e..6d6217b40 100644 --- a/src/startup_stubs/resource_budget.h +++ b/src/startup_stubs/resource_budget.h @@ -74,6 +74,10 @@ class Ticket final : public IUnknown { return refs; } + // Read-only identity for the opt-in retire diagnostics (X2W_D3D12_RETIRE_REASONS). + Category category() const { return category_; } + LONG64 bytes() const { return bytes_; } + void begin_use() { AcquireSRWLockExclusive(&lock); @@ -128,6 +132,16 @@ inline Ticket* attach(ID3D12Object* object, Category category, UINT64 bytes, UIN return nullptr; } +// The ticket stored on a live desktop object, with a reference the caller releases, or null. +inline Ticket* ticket_of(ID3D12Object* object) +{ + constexpr GUID key{0x28213cf4, 0x25cf, 0x42be, {0x80, 0xf1, 0xc5, 0x9e, 0x97, 0xf7, 0x20, 0xd1}}; + IUnknown* stored = nullptr; + UINT size = sizeof(stored); + if (FAILED(object->GetPrivateData(key, &size, &stored)) || !stored) return nullptr; + return static_cast<Ticket*>(stored); +} + inline Ticket* resource(ID3D12Device* device, ID3D12Resource* resource, Category category) { if (!enabled()) return nullptr; diff --git a/tests/startup_resource_retire_reasons.cpp b/tests/startup_resource_retire_reasons.cpp new file mode 100644 index 000000000..72524c519 --- /dev/null +++ b/tests/startup_resource_retire_reasons.cpp @@ -0,0 +1,456 @@ +// X2W_D3D12_RETIRE_REASONS=1 (docs/startup-runtime.md#d3d12-resource-budget): with X2W_D3D12_RELEASE_RETIRED=1 and +// X2W_D3D12_BUDGET=1 the heartbeat names why resources that the guest released for good still hold their desktop +// object. The fixture creates one resource per main reason, releases it, and compares the whole line the export builds +// (the same text the heartbeat logs) with the expected counts and bytes. Bytes come from the desktop allocation size, +// which is what the budget ticket records. +// +// startup_resource_retire_reasons <warp|hardware> [off|no-retire] +// (X2W_D3D12_BUDGET=1 X2W_D3D12_PERMISSIVE=1 X2W_D3D12_LIST_NOOP=1 X2W_D3D12_RENDER=1 and +// X2W_D3D12_RELEASE_RETIRED=1 X2W_D3D12_RETIRE_REASONS=1; "off" runs without RETIRE_REASONS, "no-retire" without +// RELEASE_RETIRED: the export must then report nothing) +// +// Expected reasons, each with its own resource: +// view-refs (two, one of them in a shader-visible heap), never-class:rt-ds-uav, never-class:msaa, never-class:buffer, +// left-class:view, left-class:residency, left-class:present, list-hold (an unsubmitted closed list), flight (a +// submission held behind a gate), queued-waiting-fence (a release behind the same gate). +// Then the gate opens, the flight and fence entries leave, and the list hold leaves with the Reset of its list. +#include "startup_stubs/resource_budget.h" + +#include <d3d12sdklayers.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <deque> +#include <map> +#include <string> + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) std::size_t x2w_d3d12_retire_reasons_line(char*, std::size_t); + +namespace { + +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; +constexpr UINT side = 64; + +template<class Result = HRESULT, class... Args> +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +template<class T> +ComPtr<T> desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr<T> output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr<IUnknown> reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast<IUnknown*>(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast<unsigned long>(hr)); + return SUCCEEDED(hr); +} + +ComPtr<IDXGIAdapter1> pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Res { + ComPtr<IUnknown> guest; + UINT64 bytes = 0; +}; +struct GuestQueue { + ComPtr<IUnknown> queue, done; + ComPtr<ID3D12Fence> done_real; + UINT64 value = 0; +}; +struct GuestList { + ComPtr<IUnknown> allocator, list; +}; +using Tokens = std::map<std::string, std::pair<long long, long long>>; + +Tokens parse(const char* line) +{ + Tokens tokens; + for (const char* p = line; *p;) { + while (*p == ' ') ++p; + const char* end = p; + while (*end && *end != ' ') ++end; + char word[128]{}; + std::memcpy(word, p, (std::min<std::size_t>)(static_cast<std::size_t>(end - p), sizeof(word) - 1)); + char name[96]{}; + long long count = 0, bytes = 0; + if (std::sscanf(word, "%95[^=]=%lld/%lld", name, &count, &bytes) == 3) tokens[name] = {count, bytes}; + p = end; + } + return tokens; +} + +struct Context { + IUnknown* guest; + ID3D12Device* device; + HANDLE event = nullptr; + std::deque<Res> pool; + GuestQueue direct, other, gated; + GuestList drain_list; + D3D12_RESOURCE_DESC desc{}; + std::array<GUID, 1> iid_resource{__uuidof(ID3D12Resource)}; + + bool wait(ID3D12Fence* fence, UINT64 value) + { + if (fence->GetCompletedValue() >= value) return true; + if (FAILED(fence->SetEventOnCompletion(value, event))) return false; + return WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0; + } + Res& make(const D3D12_RESOURCE_DESC& d, bool through_slot_27 = false) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + Res& r = pool.emplace_back(); + r.bytes = device->GetResourceAllocationInfo(0, 1, &d).SizeInBytes; + const HRESULT hr = through_slot_27 + ? invoke(guest, 27, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, &iid_resource[0], + r.guest.GetAddressOf()) + : invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, nullptr, + &iid_resource[0], r.guest.GetAddressOf()); + if (!require(hr, "create resource")) throw 4; + return r; + } + Res& texture(D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE, UINT samples = 1) + { + D3D12_RESOURCE_DESC d = desc; + d.Flags = flags; + d.SampleDesc = {samples, 0}; + return make(d); + } + Res& buffer() + { + const D3D12_RESOURCE_DESC d{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 65536, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + return make(d, true); + } + bool make_queue(GuestQueue& q) + { + const D3D12_COMMAND_QUEUE_DESC d{}; + return require(invoke(guest, 8, &d, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") && + require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "done fence") && + (q.done_real = desktop_object<ID3D12Fence>(guest, device, q.done.Get())) != nullptr; + } + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (wait(q.done_real.Get(), q.value)) return true; + std::puts("FAIL: a queue did not reach its completion fence"); + return false; + } + bool sync_all() { return sync(direct) && sync(other) && sync(gated); } + bool make_list(GuestList& l) + { + const unsigned list_desc[] = {static_cast<unsigned>(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + return require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), l.allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, l.allocator.Get(), nullptr, &__uuidof(ID3D12GraphicsCommandList), l.list.GetAddressOf()), "list") && + require(invoke(l.list.Get(), 139, l.allocator.Get(), nullptr), "list reset"); + } + bool reset_list(GuestList& l) + { + ComPtr<IUnknown> next; + if (!require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), next.GetAddressOf()), "allocator")) return false; + if (!require(invoke(l.list.Get(), 139, next.Get(), nullptr), "list reset")) return false; + l.allocator = next; + return true; + } + bool close(GuestList& l) { return require(invoke(l.list.Get(), 9), "list close"); } + void execute(GuestQueue& q, GuestList& l) + { + IUnknown* lists[] = {l.list.Get()}; + invoke<void>(q.queue.Get(), 10, 1u, lists); + } + void drain() { execute(other, drain_list); } + // A closed list that copies source into destination. + bool record_copy(GuestList& l, Res& destination, Res& source) + { + if (!make_list(l)) return false; + invoke<void>(l.list.Get(), 17, destination.guest.Get(), source.guest.Get()); + return close(l); + } + bool line(std::string& text) const + { + char buffer[2048]{}; + if (!x2w_d3d12_retire_reasons_line(buffer, sizeof(buffer))) return false; + text = buffer; + return true; + } +}; + +struct Want { + const char* name; + long long count, bytes; +}; + +// The line carries exactly the wanted tokens, plus total and unattributed. +bool expect(Context& c, const char* stage, std::initializer_list<Want> wants, long long unattributed_count = 0) +{ + std::string text; + if (!c.line(text)) { + std::printf("FAIL: %s: the diagnostics line is empty although the switches are on\n", stage); + return false; + } + Tokens want; + long long total_count = 0, total_bytes = 0; + for (const Want& w : wants) { + want[w.name] = {w.count, w.bytes}; + if (std::strcmp(w.name, "view-refs-in-visible-heap")) total_count += w.count, total_bytes += w.bytes; + } + want["total"] = {total_count, total_bytes}; + const Tokens got = parse(text.c_str()); + Tokens compare = got; + const auto un = compare.find("unattributed"); + const bool unattributed_ok = un != compare.end() && un->second.first == unattributed_count; + compare.erase("unattributed"); + if (compare == want && unattributed_ok) return true; + std::printf("FAIL: %s\n got: %s\n want:", stage, text.c_str()); + for (const auto& [name, value] : want) std::printf(" %s=%lld/%lld", name.c_str(), value.first, value.second); + std::printf(" unattributed=%lld/*\n", unattributed_count); + return false; +} + +// Drains until the line matches, without sleeping. +bool settle(Context& c, const char* stage, std::initializer_list<Want> wants, long long unattributed_count = 0) +{ + for (int i = 0; i < settle_limit; ++i) { + c.drain(); + std::string text; + Tokens want; + long long total_count = 0, total_bytes = 0; + for (const Want& w : wants) { + want[w.name] = {w.count, w.bytes}; + if (std::strcmp(w.name, "view-refs-in-visible-heap")) total_count += w.count, total_bytes += w.bytes; + } + want["total"] = {total_count, total_bytes}; + if (c.line(text)) { + Tokens got = parse(text.c_str()); + const auto un = got.find("unattributed"); + const bool unattributed_ok = un != got.end() && un->second.first == unattributed_count; + got.erase("unattributed"); + if (got == want && unattributed_ok) return true; + } + } + return expect(c, stage, wants, unattributed_count); +} + +bool scenario(Context& c) +{ + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } visible_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}, + hidden_heap{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}, 0, 0}; + ComPtr<IUnknown> visible, hidden; + if (!require(invoke(c.guest, 14, &visible_heap, &__uuidof(ID3D12DescriptorHeap), visible.GetAddressOf()), "visible heap") || + !require(invoke(c.guest, 14, &hidden_heap, &__uuidof(ID3D12DescriptorHeap), hidden.GetAddressOf()), "hidden heap")) + return false; + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + + if (!c.sync_all()) return false; // every queue has a completion point before anything is released + Res& A = c.texture(); + Res& B = c.texture(); + invoke<void>(c.guest, 18, A.guest.Get(), &srv, invoke<UINT64>(visible.Get(), 9)); + invoke<void>(c.guest, 18, B.guest.Get(), &srv, invoke<UINT64>(hidden.Get(), 9)); + const UINT64 tb = A.bytes; + A.guest.Reset(); + B.guest.Reset(); + + Res& rt = c.texture(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + Res& msaa = c.texture(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, 4); + Res& buf = c.buffer(); + const UINT64 rt_bytes = rt.bytes, msaa_bytes = msaa.bytes, buf_bytes = buf.bytes; + rt.guest.Reset(); + msaa.guest.Reset(); + buf.guest.Reset(); + + // A view whose descriptor handle the shim cannot translate takes the resource out of the class. + Res& viewed = c.texture(); + invoke<void>(c.guest, 18, viewed.guest.Get(), &srv, UINT64{0}); + viewed.guest.Reset(); + Res& resident = c.texture(); + IUnknown* residents[] = {resident.guest.Get()}; + if (!require(invoke(c.guest, 34, 1u, residents), "MakeResident")) return false; + resident.guest.Reset(); + Res& presented = c.texture(); + void* surface = presented.guest.Get(); + const UINT64 plane[10]{0, 1, reinterpret_cast<UINT64>(&surface)}; + const UINT64 present_parameters[8]{}; + if (!require(invoke(c.direct.queue.Get(), 32, 1u, plane, present_parameters), "Present")) return false; + presented.guest.Reset(); + + // A released source that a closed, unsubmitted list names. + GuestList listed; + Res& list_destination = c.texture(); + Res& list_source = c.texture(); + if (!c.record_copy(listed, list_destination, list_source)) return false; + list_source.guest.Reset(); + if (!c.sync_all()) return false; + for (int i = 0; i < 4; ++i) c.drain(); + + // A submission behind a gate, its list reset, then two releases behind the same gate. + ComPtr<IUnknown> gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate fence") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "queue wait")) + return false; + GuestList flying; + Res& fly_destination = c.texture(); + Res& fly_source = c.texture(); + if (!c.record_copy(flying, fly_destination, fly_source)) return false; + c.execute(c.gated, flying); + fly_source.guest.Reset(); + if (!c.reset_list(flying)) return false; + Res& waiting = c.texture(); + waiting.guest.Reset(); + if (!c.sync(c.direct) || !c.sync(c.other)) return false; + for (int i = 0; i < 4; ++i) c.drain(); + + if (!expect(c, "every reason once", + {{"view-refs", 2, static_cast<long long>(2 * tb)}, {"view-refs-in-visible-heap", 1, static_cast<long long>(tb)}, + {"never-class:rt-ds-uav", 1, static_cast<long long>(rt_bytes)}, + {"never-class:msaa", 1, static_cast<long long>(msaa_bytes)}, + {"never-class:buffer", 1, static_cast<long long>(buf_bytes)}, + {"left-class:view", 1, static_cast<long long>(tb)}, {"left-class:residency", 1, static_cast<long long>(tb)}, + {"left-class:present", 1, static_cast<long long>(tb)}, {"list-hold", 1, static_cast<long long>(tb)}, + {"flight", 1, static_cast<long long>(tb)}, {"queued-waiting-fence", 1, static_cast<long long>(tb)}})) + return false; + std::puts("1 one resource per reason: view-refs, rt-ds-uav, msaa, buffer, left view/residency/present, list-hold, flight, fence"); + + if (!require(invoke(gate.Get(), 10, UINT64{1}), "gate signal") || !c.sync_all()) return false; + if (!settle(c, "gate opened", + {{"view-refs", 2, static_cast<long long>(2 * tb)}, {"view-refs-in-visible-heap", 1, static_cast<long long>(tb)}, + {"never-class:rt-ds-uav", 1, static_cast<long long>(rt_bytes)}, + {"never-class:msaa", 1, static_cast<long long>(msaa_bytes)}, + {"never-class:buffer", 1, static_cast<long long>(buf_bytes)}, + {"left-class:view", 1, static_cast<long long>(tb)}, {"left-class:residency", 1, static_cast<long long>(tb)}, + {"left-class:present", 1, static_cast<long long>(tb)}, {"list-hold", 1, static_cast<long long>(tb)}})) + return false; + std::puts("2 gate opened: flight and queued-waiting-fence leave, the rest stays"); + + if (!c.reset_list(listed)) return false; + if (!settle(c, "list reset", + {{"view-refs", 2, static_cast<long long>(2 * tb)}, {"view-refs-in-visible-heap", 1, static_cast<long long>(tb)}, + {"never-class:rt-ds-uav", 1, static_cast<long long>(rt_bytes)}, + {"never-class:msaa", 1, static_cast<long long>(msaa_bytes)}, + {"never-class:buffer", 1, static_cast<long long>(buf_bytes)}, + {"left-class:view", 1, static_cast<long long>(tb)}, {"left-class:residency", 1, static_cast<long long>(tb)}, + {"left-class:present", 1, static_cast<long long>(tb)}})) + return false; + std::puts("3 list reset: the list hold leaves"); + + // Overwriting the shader-visible descriptor drops one view reference; the resource then retires. + Res& replacement = c.texture(); + invoke<void>(c.guest, 18, replacement.guest.Get(), &srv, invoke<UINT64>(visible.Get(), 9)); + if (!settle(c, "descriptor overwritten", + {{"view-refs", 1, static_cast<long long>(tb)}, + {"never-class:rt-ds-uav", 1, static_cast<long long>(rt_bytes)}, + {"never-class:msaa", 1, static_cast<long long>(msaa_bytes)}, + {"never-class:buffer", 1, static_cast<long long>(buf_bytes)}, + {"left-class:view", 1, static_cast<long long>(tb)}, {"left-class:residency", 1, static_cast<long long>(tb)}, + {"left-class:present", 1, static_cast<long long>(tb)}})) + return false; + std::puts("4 descriptor overwritten: the visible-heap view-refs entry retires, the hidden-heap one stays"); + return true; +} + +// Negative control: the same kind of release with the switches off reports nothing. +bool nothing_reported(Context& c) +{ + if (!c.sync_all()) return false; + Res& r = c.texture(); + r.guest.Reset(); + Res& g = c.texture(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + g.guest.Reset(); + for (int i = 0; i < 4; ++i) c.drain(); + char buffer[256]; + std::memset(buffer, 'x', sizeof(buffer)); + const std::size_t length = x2w_d3d12_retire_reasons_line(buffer, sizeof(buffer)); + if (length || buffer[0]) { + std::printf("FAIL: the diagnostics reported %zu bytes without their switches: %s\n", length, buffer); + return false; + } + return true; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "off") && std::strcmp(argv[2], "no-retire"))) + return 2; + const auto env_on = [](const char* name) { + char value[2]{}; + return GetEnvironmentVariableA(name, value, sizeof(value)) == 1 && value[0] == '1'; + }; + const bool off = argc == 3 && !std::strcmp(argv[2], "off"); + const bool no_retire = argc == 3 && !std::strcmp(argv[2], "no-retire"); + if (env_on("X2W_D3D12_RETIRE_REASONS") != !off || env_on("X2W_D3D12_RELEASE_RETIRED") != !no_retire || + !env_on("X2W_D3D12_BUDGET")) { + std::puts("FAIL: the environment does not match the requested mode"); + return 2; + } + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + ComPtr<IUnknown> guest; + ComPtr<ID3D12Device> device; + std::array<unsigned char, 64> parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + std::printf("mode=%s\n", off ? "off" : no_retire ? "no-retire" : "on"); + Context c{guest.Get(), device.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!c.event || !c.make_queue(c.direct) || !c.make_queue(c.other) || !c.make_queue(c.gated)) return 4; + if (!c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!(off || no_retire ? nothing_reported(c) : scenario(c))) return 5; + } catch (int code) { + return code; + } + if (FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(off || no_retire ? "retire-reasons off checks passed" : "retire-reasons checks passed"); + return 0; +} diff --git a/tests/startup_resource_retire_views.cpp b/tests/startup_resource_retire_views.cpp new file mode 100644 index 000000000..6db82d289 --- /dev/null +++ b/tests/startup_resource_retire_views.cpp @@ -0,0 +1,657 @@ +// X2W_D3D12_RELEASE_RETIRED_VIEWS=1 (with X2W_D3D12_RELEASE_RETIRED=1, Refs #2379): a released committed 2D texture that +// only tracked slot-18 descriptor slots keep alive is freed once those slots hold null descriptors. The title never has +// to overwrite them. +// +// startup_resource_retire_views <warp|hardware> [keep] +// +// `keep` is the negative control: the views switch is off (or the retire switch is, with the views switch set), so a +// released texture stays retained exactly as before and its descriptors keep naming it. +// +// The fixture reads the desktop descriptors the shim wrote: a compute shader on the fixture's own desktop queue loads +// texel (0,0) through a slot of a guest heap (bound directly when the heap is shader-visible, copied into a probe +// heap when it is not). A filled texture reads back non-zero, a null descriptor reads back zero. +// Cases: +// 1 single SRV in a shader-visible heap, never overwritten: freed after the release fences, descriptor null, view +// token in title descriptor memory cleared. +// 2 the same texture also copied into a second (non-shader-visible) heap, release behind a gated queue: nothing is +// touched until the gate opens, then both copies are null and the texture is freed (copies are handled). +// 3 a closed list recorded a CopyResource from the texture, submitted behind a gate: descriptors are nulled but the +// desktop object lives until the submission's fence, and the copy still reads the texels. +// 4 a closed, never submitted list names the texture: nulled, retained until the recording is discarded. +// 5 a live texture's descriptor is never touched. +#include "startup_stubs/resource_budget.h" + +#include <d3d12sdklayers.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <array> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <cwchar> +#include <deque> + +using Microsoft::WRL::ComPtr; + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); + +namespace { +using namespace x2w_budget; + +constexpr UINT side = 64, pitch = 256, image_bytes = side * pitch; +constexpr DWORD wait_ms = 10000; +constexpr int settle_limit = 200; +constexpr std::uint32_t view_token_magic = 0x56573258; // "X2WV", d3d12_capture.inl + +template<class Result = HRESULT, class... Args> +Result invoke(IUnknown* object, unsigned slot, Args... args) +{ + using Call = Result (WINAPI*)(IUnknown*, Args...); + return reinterpret_cast<Call>((*reinterpret_cast<void***>(object))[slot])(object, args...); +} + +template<class T> +ComPtr<T> desktop_object(IUnknown* guest, ID3D12Device* device, IUnknown* object) +{ + constexpr GUID key{0x0e34d52f, 0xd5a5, 0x4790, {0x91, 0xd4, 0x11, 0xa6, 0x7c, 0xbc, 0x2b, 0xc1}}; + ComPtr<T> output; + if (FAILED(invoke(guest, 5, &key, object))) return output; + ComPtr<IUnknown> reference; + UINT bytes = sizeof(IUnknown*); + const HRESULT hr = device->GetPrivateData(key, &bytes, reference.GetAddressOf()); + invoke(guest, 5, &key, static_cast<IUnknown*>(nullptr)); + if (SUCCEEDED(hr)) reference.As(&output); + return output; +} + +bool require(HRESULT hr, const char* stage) +{ + if (FAILED(hr)) std::printf("FAIL: %s hr=0x%08lx\n", stage, static_cast<unsigned long>(hr)); + return SUCCEEDED(hr); +} + +std::uint8_t pattern_byte(int seed, UINT i) { return static_cast<std::uint8_t>(i * 7 + seed * 13 + 1); } + +ComPtr<IDXGIAdapter1> pick_adapter(IDXGIFactory4* factory, bool warp) +{ + ComPtr<IDXGIAdapter1> adapter; + if (warp) { + factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + return adapter; + } + wchar_t name[128]{}; + GetEnvironmentVariableW(L"XBOX2WINDOWS_ADAPTER", name, static_cast<DWORD>(std::size(name))); + for (UINT i = 0; factory->EnumAdapters1(i, &adapter) == S_OK; ++i, adapter.Reset()) { + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(adapter->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) && + (!name[0] || std::wcsstr(desc.Description, name)) && + SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) + return adapter; + } + return nullptr; +} + +struct Res { + ComPtr<IUnknown> guest; + const char* name = ""; + UINT64 bytes = 0; + bool released = false; + bool freed = false; +}; + +struct GuestList { + ComPtr<IUnknown> allocator, list; +}; + +struct GuestQueue { + ComPtr<IUnknown> queue, done; + ComPtr<ID3D12Fence> done_real; + UINT64 value = 0; +}; + +struct GuestHeap { + ComPtr<IUnknown> guest; + ComPtr<ID3D12DescriptorHeap> real; + UINT64 cpu = 0, gpu = 0; + bool visible = false; +}; + +constexpr char probe_shader[] = R"( +Texture2D<float4> source : register(t0); +RWByteAddressBuffer result : register(u0); +[numthreads(1, 1, 1)] void main() +{ + result.Store4(0, asuint(source.Load(int3(0, 0, 0)))); +} +)"; + +struct Context { + IUnknown* guest; + ID3D12Device* device; + ComPtr<ID3D12CommandQueue> own_queue; + ComPtr<ID3D12CommandAllocator> own_allocator; + ComPtr<ID3D12GraphicsCommandList> own_list; + ComPtr<ID3D12Fence> own_fence; + UINT64 own_value = 0; + HANDLE event = nullptr; + ComPtr<ID3D12Resource> upload, readback, probe_out; + ComPtr<ID3D12RootSignature> probe_root; + ComPtr<ID3D12PipelineState> probe_pso; + ComPtr<ID3D12DescriptorHeap> probe_heap; + UINT increment = 0; + Snapshot base{}; + std::deque<Res> pool; + GuestQueue direct, gated; + GuestList drain_list; + D3D12_RESOURCE_DESC desc{}; + UINT64 texture_bytes = 0; + std::array<GUID, 1> iid_resource{__uuidof(ID3D12Resource)}; + + bool wait(ID3D12Fence* fence, UINT64 value) + { + if (fence->GetCompletedValue() >= value) return true; + if (FAILED(fence->SetEventOnCompletion(value, event))) return false; + return WaitForSingleObject(event, wait_ms) == WAIT_OBJECT_0; + } + bool own_run() + { + if (!require(own_list->Close(), "own list close")) return false; + ID3D12CommandList* lists[] = {own_list.Get()}; + own_queue->ExecuteCommandLists(1, lists); + if (!require(own_queue->Signal(own_fence.Get(), ++own_value), "own signal")) return false; + if (wait(own_fence.Get(), own_value)) return true; + std::puts("FAIL: own queue timed out"); + return false; + } + D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* buffer) const + { + D3D12_TEXTURE_COPY_LOCATION location{buffer, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + location.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, side, side, 1, pitch}; + return location; + } + static D3D12_TEXTURE_COPY_LOCATION footprint_tex(ID3D12Resource* tex) + { + return {tex, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {0}}; + } + bool make_queue(GuestQueue& q) + { + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + if (!require(invoke(guest, 8, &qd, &__uuidof(ID3D12CommandQueue), q.queue.GetAddressOf()), "queue") || + !require(invoke(guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), q.done.GetAddressOf()), "fence")) + return false; + q.done_real = desktop_object<ID3D12Fence>(guest, device, q.done.Get()); + return q.done_real != nullptr; + } + bool sync(GuestQueue& q) + { + if (!require(invoke(q.queue.Get(), 14, q.done.Get(), ++q.value), "queue signal")) return false; + if (wait(q.done_real.Get(), q.value)) return true; + std::puts("FAIL: guest queue timed out"); + return false; + } + bool make_list(GuestList& l) + { + const unsigned list_desc[] = {static_cast<unsigned>(D3D12_COMMAND_LIST_TYPE_DIRECT), 2, 1, 0}; + return require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + l.allocator.GetAddressOf()), "allocator") && + require(invoke(guest, 73, list_desc, l.allocator.Get(), nullptr, + &__uuidof(ID3D12GraphicsCommandList), l.list.GetAddressOf()), "command list") && + require(invoke(l.list.Get(), 139, l.allocator.Get(), nullptr), "list reset"); + } + bool close(GuestList& l) { return require(invoke(l.list.Get(), 9), "list close"); } + HRESULT reset_list(GuestList& l) + { + ComPtr<IUnknown> next; + if (!require(invoke(guest, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, &__uuidof(ID3D12CommandAllocator), + next.GetAddressOf()), "allocator")) + return E_FAIL; + const HRESULT hr = invoke(l.list.Get(), 139, next.Get(), nullptr); + if (SUCCEEDED(hr)) l.allocator = next; + return hr; + } + void execute(GuestQueue& q, GuestList& l) + { + IUnknown* lists[] = {l.list.Get()}; + invoke<void>(q.queue.Get(), 10, 1u, lists); + } + Res& make_committed(const char* name) + { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC d = desc; + Res& r = pool.emplace_back(); + r.name = name; + r.bytes = texture_bytes; + if (!require(invoke(guest, 127, &heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0u, + nullptr, &iid_resource[0], r.guest.GetAddressOf()), name)) + throw 4; + return r; + } + bool fill_desktop(IUnknown* resource, int seed) + { + const auto real = desktop_object<ID3D12Resource>(guest, device, resource); + if (!real) return false; + void* mapped = nullptr; + const D3D12_RANGE none{}; + if (!require(upload->Map(0, &none, &mapped), "upload map")) return false; + auto* dst = static_cast<std::uint8_t*>(mapped); + for (UINT i = 0; i < image_bytes; ++i) dst[i] = pattern_byte(seed, i); + upload->Unmap(0, nullptr); + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) + return false; + own_list->CopyTextureRegion(&footprint_tex(real.Get()), 0, 0, 0, &footprint(upload.Get()), nullptr); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COMMON}; + own_list->ResourceBarrier(1, &b); + return own_run(); + } + bool holds(IUnknown* resource, int seed, const char* what) + { + const auto real = desktop_object<ID3D12Resource>(guest, device, resource); + if (!real) return false; + if (!require(own_allocator->Reset(), "own allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "own list")) + return false; + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {real.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyTextureRegion(&footprint(readback.Get()), 0, 0, 0, &footprint_tex(real.Get()), nullptr); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_COMMON; + own_list->ResourceBarrier(1, &b); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, image_bytes}; + if (!require(readback->Map(0, &all, &mapped), "readback map")) return false; + const auto* src = static_cast<const std::uint8_t*>(mapped); + UINT mismatches = 0; + for (UINT y = 0; y < side; ++y) + for (UINT x = 0; x < side * 4; ++x) + if (src[y * pitch + x] != pattern_byte(seed, y * pitch + x)) ++mismatches; + readback->Unmap(0, nullptr); + if (mismatches) { + std::printf("FAIL: %s readback had %u mismatched bytes\n", what, mismatches); + return false; + } + return true; + } + void release(Res& r) + { + r.guest.Reset(); + r.released = true; + } + void drain_once() + { + IUnknown* lists[] = {drain_list.list.Get()}; + invoke<void>(direct.queue.Get(), 10, 1u, lists); + } + bool expect(const char* stage, const char* fail) const + { + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 live_n = base.live[texture].objects, ret_n = base.retained[texture].objects; + UINT64 live_b = base.live[texture].bytes, ret_b = base.retained[texture].bytes; + for (const Res& r : pool) { + if (!r.released) { + live_b += r.bytes; + ++live_n; + } else if (!r.freed) { + ret_b += r.bytes; + ++ret_n; + } + } + const auto& got_live = now.live[texture]; + const auto& got_ret = now.retained[texture]; + if (got_live.bytes == live_b && got_live.objects == live_n && got_ret.bytes == ret_b && got_ret.objects == ret_n) + return true; + std::printf("FAIL: %s\n stage '%s' live=%llu/%llu expected=%llu/%llu retained=%llu/%llu expected=%llu/%llu\n", + fail, stage, got_live.bytes, got_live.objects, live_b, live_n, + got_ret.bytes, got_ret.objects, ret_b, ret_n); + return false; + } + bool stays(const char* stage, const char* fail) + { + drain_once(); + return sync(direct) && expect(stage, fail); + } + bool settle(const char* stage, const char* fail) + { + for (int i = 0; i < settle_limit; ++i) { + drain_once(); + Snapshot now{}; + if (!x2w_d3d12_budget_snapshot(&now, sizeof(now))) return false; + UINT64 ret_n = base.retained[texture].objects; + for (const Res& r : pool) if (r.released && !r.freed) ++ret_n; + if (now.retained[texture].objects == ret_n) return expect(stage, fail); + } + return expect(stage, fail); + } + bool make_heap(GuestHeap& h, UINT count, bool visible) + { + const struct { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 backing, bytes; + } request{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, count, + visible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE}, 0, 0}; + if (!require(invoke(guest, 14, &request, &__uuidof(ID3D12DescriptorHeap), h.guest.GetAddressOf()), "guest heap")) + return false; + h.real = desktop_object<ID3D12DescriptorHeap>(guest, device, h.guest.Get()); + if (!h.real) { + std::puts("FAIL: guest heap has no desktop object"); + return false; + } + h.cpu = invoke<UINT64>(h.guest.Get(), 9); + h.gpu = visible ? invoke<UINT64>(h.guest.Get(), 10) : 0; + h.visible = visible; + return true; + } + // Loads texel (0,0) through the desktop descriptor behind slot `index` of the guest heap. + bool read_slot(const GuestHeap& h, UINT index, float (&texel)[4]) + { + if (!require(own_allocator->Reset(), "probe allocator") || !require(own_list->Reset(own_allocator.Get(), nullptr), "probe list")) + return false; + ID3D12DescriptorHeap* bound = probe_heap.Get(); + D3D12_GPU_DESCRIPTOR_HANDLE gpu = probe_heap->GetGPUDescriptorHandleForHeapStart(); + if (h.visible) { + bound = h.real.Get(); + gpu = h.real->GetGPUDescriptorHandleForHeapStart(); + gpu.ptr += std::uint64_t{index} * increment; + } else { + D3D12_CPU_DESCRIPTOR_HANDLE src = h.real->GetCPUDescriptorHandleForHeapStart(); + src.ptr += std::uint64_t{index} * increment; + device->CopyDescriptorsSimple(1, probe_heap->GetCPUDescriptorHandleForHeapStart(), src, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + own_list->SetDescriptorHeaps(1, &bound); + own_list->SetComputeRootSignature(probe_root.Get()); + own_list->SetPipelineState(probe_pso.Get()); + own_list->SetComputeRootDescriptorTable(0, gpu); + own_list->SetComputeRootUnorderedAccessView(1, probe_out->GetGPUVirtualAddress()); + own_list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER b{D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, {}}; + b.Transition = {probe_out.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE}; + own_list->ResourceBarrier(1, &b); + own_list->CopyBufferRegion(readback.Get(), 0, probe_out.Get(), 0, 16); + b.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + b.Transition.StateAfter = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + own_list->ResourceBarrier(1, &b); + if (!own_run()) return false; + void* mapped = nullptr; + const D3D12_RANGE all{0, 16}; + if (!require(readback->Map(0, &all, &mapped), "probe readback map")) return false; + std::memcpy(texel, mapped, sizeof(texel)); + readback->Unmap(0, nullptr); + return true; + } + // want_null: the slot must read as null (all zero); otherwise it must read the texture's texels (not all zero). + bool slot_is(const GuestHeap& h, UINT index, bool want_null, const char* what) + { + float texel[4]{}; + if (!read_slot(h, index, texel)) return false; + const bool zero = texel[0] == 0.0f && texel[1] == 0.0f && texel[2] == 0.0f && texel[3] == 0.0f; + if (zero == want_null) return true; + std::printf("FAIL: %s: descriptor reads %.3f %.3f %.3f %.3f, expected %s\n", what, texel[0], texel[1], texel[2], + texel[3], want_null ? "null (all zero)" : "texels of the texture"); + return false; + } + // The view token the shim wrote into title descriptor memory for a slot (first word). + static std::uint32_t token_word(const GuestHeap& h, UINT index, UINT stride) + { + std::uint32_t word = 0; + std::memcpy(&word, reinterpret_cast<const void*>(h.cpu + std::uint64_t{index} * stride), sizeof(word)); + return word; + } +}; + +D3D12_SHADER_RESOURCE_VIEW_DESC texture_view() +{ + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Texture2D.MipLevels = 1; + return srv; +} + +// 1: one SRV in a shader-visible heap, never overwritten. +bool case1_single_view(Context& c, bool on, GuestHeap& visible) +{ + Res& T = c.make_committed("T1"); + if (!c.fill_desktop(T.guest.Get(), 1)) return false; + const auto srv = texture_view(); + invoke<void>(c.guest, 18, T.guest.Get(), &srv, visible.cpu); + if (!c.slot_is(visible, 0, false, "case 1 control: live texture's descriptor") || + Context::token_word(visible, 0, c.increment) != view_token_magic) { + std::puts("FAIL: case 1 control: live texture's view token missing"); + return false; + } + c.release(T); + if (on) { + T.freed = true; + if (!c.settle("T1 freed with its descriptor never overwritten", "T1 kept although only a descriptor names it")) + return false; + if (!c.slot_is(visible, 0, true, "case 1: descriptor after the free")) return false; + if (Context::token_word(visible, 0, c.increment) == view_token_magic) { + std::puts("FAIL: case 1: view token still in title descriptor memory after the free"); + return false; + } + return true; + } + for (int i = 0; i < 8; ++i) + if (!c.stays("T1 released, views switch off", "T1 freed without the views switch")) return false; + return c.slot_is(visible, 0, false, "case 1 control: descriptor with the views switch off"); +} + +// 2: a copy in a second heap, release behind a gated queue. +bool case2_copy_and_gate(Context& c, bool on, GuestHeap& visible, GuestHeap& staging) +{ + Res& T = c.make_committed("T2"); + if (!c.fill_desktop(T.guest.Get(), 2)) return false; + const auto srv = texture_view(); + invoke<void>(c.guest, 18, T.guest.Get(), &srv, visible.cpu + c.increment); + invoke<void>(c.guest, 24, 1u, staging.cpu, visible.cpu + c.increment, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + ComPtr<IUnknown> gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait")) + return false; + c.release(T); + for (int i = 0; i < 8; ++i) + if (!c.stays("T2 released behind a closed gate", "T2 freed before the release fences passed")) return false; + if (!c.slot_is(visible, 1, false, "case 2: original descriptor before the gate opens") || + !c.slot_is(staging, 0, false, "case 2: copied descriptor before the gate opens")) + return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate") || !c.sync(c.gated)) return false; + if (!on) { + for (int i = 0; i < 8; ++i) + if (!c.stays("T2 released, views switch off", "T2 freed without the views switch")) return false; + return c.slot_is(staging, 0, false, "case 2 control: copied descriptor with the views switch off"); + } + T.freed = true; + if (!c.settle("T2 freed after the gate opened", "T2 kept after its fences passed")) return false; + return c.slot_is(visible, 1, true, "case 2: original descriptor after the free") && + c.slot_is(staging, 0, true, "case 2: copied descriptor after the free"); +} + +// 3 and 4: lists that name the texture. +bool case3_list_holds(Context& c, bool on, GuestHeap& visible) +{ + Res& T3 = c.make_committed("T3"); + Res& D3 = c.make_committed("D3"); + Res& T4 = c.make_committed("T4"); + Res& D4 = c.make_committed("D4"); + if (!c.fill_desktop(T3.guest.Get(), 3) || !c.fill_desktop(D3.guest.Get(), 99) || !c.fill_desktop(T4.guest.Get(), 4) || + !c.fill_desktop(D4.guest.Get(), 99)) + return false; + const auto srv = texture_view(); + invoke<void>(c.guest, 18, T3.guest.Get(), &srv, visible.cpu + 2 * c.increment); + invoke<void>(c.guest, 18, T4.guest.Get(), &srv, visible.cpu + 3 * c.increment); + GuestList submitted, discarded; + if (!c.make_list(submitted) || !c.make_list(discarded)) return false; + invoke<void>(submitted.list.Get(), 17, D3.guest.Get(), T3.guest.Get()); + invoke<void>(discarded.list.Get(), 17, D4.guest.Get(), T4.guest.Get()); + if (!c.close(submitted) || !c.close(discarded)) return false; + c.release(T3); + c.release(T4); + for (int i = 0; i < 8; ++i) + if (!c.stays("T3/T4 released behind closed lists", "a texture left the budget while a closed list names it")) + return false; + if (on && (!c.slot_is(visible, 2, true, "case 3: descriptor of the listed texture T3") || + !c.slot_is(visible, 3, true, "case 4: descriptor of the listed texture T4"))) + return false; + ComPtr<IUnknown> gate; + if (!require(invoke(c.guest, 36, UINT64{0}, D3D12_FENCE_FLAG_NONE, &__uuidof(ID3D12Fence), gate.GetAddressOf()), "gate3") || + !require(invoke(c.gated.queue.Get(), 17, gate.Get(), UINT64{1}), "wait3")) + return false; + c.execute(c.gated, submitted); + if (!SUCCEEDED(c.reset_list(submitted))) return false; + for (int i = 0; i < 8; ++i) + if (!c.stays("T3 held by a gated submission", "T3 left the budget while its submission is in flight")) return false; + if (!SUCCEEDED(c.reset_list(discarded))) return false; // discards the recording that was never submitted + if (on) T4.freed = true; + if (!c.settle("T4 freed after its recording was discarded", "T4 kept after its recording was discarded")) return false; + if (!require(invoke(gate.Get(), 10, UINT64{1}), "signal gate3") || !c.sync(c.gated)) return false; + if (on) T3.freed = true; + if (!c.settle("T3 freed after its submission's fence", "T3 kept after its submission's fence passed")) return false; + // The copy ran against the live texels, not against anything freed or nulled. + return c.holds(D3.guest.Get(), 3, "D3 copy of T3 recorded before the release"); +} + +// 5: a live texture is never touched. +bool case5_live_control(Context& c, GuestHeap& visible) +{ + Res& T = c.make_committed("T5"); + if (!c.fill_desktop(T.guest.Get(), 5)) return false; + const auto srv = texture_view(); + invoke<void>(c.guest, 18, T.guest.Get(), &srv, visible.cpu + 4 * c.increment); + for (int i = 0; i < 8; ++i) + if (!c.stays("T5 live", "a live texture left the budget")) return false; + return c.slot_is(visible, 4, false, "case 5: descriptor of a live texture"); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2 || argc > 3 || (std::strcmp(argv[1], "warp") && std::strcmp(argv[1], "hardware")) || + (argc == 3 && std::strcmp(argv[2], "keep"))) + return 2; + ComPtr<IDXGIFactory4> factory; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 3; + const auto adapter = pick_adapter(factory.Get(), std::strcmp(argv[1], "warp") == 0); + if (!adapter) return 77; + char debug_env[2]{}; + const bool debug_on = GetEnvironmentVariableA("X2W_D3D12_DEBUG", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_on) { + ComPtr<ID3D12Debug> debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) return 77; + debug->EnableDebugLayer(); + } + ComPtr<IUnknown> guest; + ComPtr<ID3D12Device> device; + std::array<unsigned char, 64> parameters{}; + if (!require(D3D12XboxCreateDevice(adapter.Get(), parameters.data(), __uuidof(ID3D12Device), + reinterpret_cast<void**>(guest.GetAddressOf())), "Xbox device") || + !require(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)), "desktop device")) + return 3; + ComPtr<ID3D12InfoQueue> debug; + if (debug_on && FAILED(device.As(&debug))) return 3; + if (debug) { + D3D12_MESSAGE_SEVERITY severities[] = { + D3D12_MESSAGE_SEVERITY_CORRUPTION, D3D12_MESSAGE_SEVERITY_ERROR, D3D12_MESSAGE_SEVERITY_WARNING}; + D3D12_INFO_QUEUE_FILTER filter{}; + filter.AllowList.NumSeverities = static_cast<UINT>(std::size(severities)); + filter.AllowList.pSeverityList = severities; + if (FAILED(debug->AddStorageFilterEntries(&filter))) return 3; + debug->ClearStoredMessages(); + } + char value[2]{}; + const bool retire_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED", value, sizeof(value)) == 1 && value[0] == '1'; + value[0] = 0; + const bool views_on = GetEnvironmentVariableA("X2W_D3D12_RELEASE_RETIRED_VIEWS", value, sizeof(value)) == 1 && value[0] == '1'; + const bool keep_mode = argc == 3; + // The effective switch needs both; `keep` runs with either one missing. + if ((retire_on && views_on) == keep_mode) return 2; + const bool on = !keep_mode; + DXGI_ADAPTER_DESC1 adapter_desc{}; + adapter->GetDesc1(&adapter_desc); + std::printf("adapter=%ls debug_layer=%s mode=%s\n", adapter_desc.Description, debug ? "enabled" : "off", keep_mode ? "keep" : "on"); + + Context c{guest.Get(), device.Get()}; + try { + c.desc = {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, 1, 1, DXGI_FORMAT_R8G8B8A8_UNORM, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_NONE}; + c.texture_bytes = device->GetResourceAllocationInfo(0, 1, &c.desc).SizeInBytes; + c.increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + c.event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const D3D12_COMMAND_QUEUE_DESC direct{}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}, readback_heap{D3D12_HEAP_TYPE_READBACK}, + default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC buffer{D3D12_RESOURCE_DIMENSION_BUFFER, 0, image_bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + D3D12_RESOURCE_DESC out_desc = buffer; + out_desc.Width = 256; + out_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_DESCRIPTOR_HEAP_DESC probe_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (!c.event || !require(device->CreateCommandQueue(&direct, IID_PPV_ARGS(&c.own_queue)), "own queue") || + !require(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&c.own_allocator)), "own allocator") || + !require(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, c.own_allocator.Get(), nullptr, IID_PPV_ARGS(&c.own_list)), "own list") || + !require(c.own_list->Close(), "own list close") || + !require(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&c.own_fence)), "own fence") || + !require(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&c.upload)), "upload") || + !require(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, + nullptr, IID_PPV_ARGS(&c.readback)), "readback") || + !require(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &out_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, IID_PPV_ARGS(&c.probe_out)), "probe output") || + !require(device->CreateDescriptorHeap(&probe_heap_desc, IID_PPV_ARGS(&c.probe_heap)), "probe heap")) + return 4; + + // The probe: a compute shader that loads texel (0,0) through descriptor table slot 0. + const D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameters_root[2]{}; + parameters_root[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters_root[0].DescriptorTable = {1, &range}; + parameters_root[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + parameters_root[1].Descriptor = {0, 0}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, parameters_root, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> root_blob, errors, code; + if (!require(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, root_blob.GetAddressOf(), + errors.GetAddressOf()), "probe root serialize") || + !require(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&c.probe_root)), "probe root signature") || + !require(D3DCompile(probe_shader, std::strlen(probe_shader), nullptr, nullptr, nullptr, "main", "cs_5_1", 0, 0, + code.GetAddressOf(), errors.ReleaseAndGetAddressOf()), "probe shader")) + return 4; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = c.probe_root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (!require(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&c.probe_pso)), "probe pipeline")) return 4; + + if (!c.make_queue(c.direct) || !c.make_queue(c.gated) || !c.make_list(c.drain_list) || !c.close(c.drain_list)) return 4; + if (!x2w_d3d12_budget_snapshot(&c.base, sizeof(c.base))) return 4; + + GuestHeap visible, staging; + if (!c.make_heap(visible, 8, true) || !c.make_heap(staging, 1, false)) return 4; + + if (!case1_single_view(c, on, visible)) return 5; + std::puts("1 single SRV in a shader-visible heap, never overwritten: freed with a null descriptor and a cleared token"); + if (!case2_copy_and_gate(c, on, visible, staging)) return 5; + std::puts("2 copied descriptor behind a closed gate: untouched until the fences pass, then both copies null"); + if (!case3_list_holds(c, on, visible)) return 5; + std::puts("3/4 listed texture: descriptors null, desktop object kept until the submission's fence or the discard"); + if (!case5_live_control(c, visible)) return 5; + std::puts("5 live texture: descriptor untouched"); + } catch (int code) { + return code; + } + const UINT64 errors = debug ? debug->GetNumStoredMessages() : 0; + std::printf("debug_errors_or_warnings=%llu\n", errors); + if (errors || FAILED(device->GetDeviceRemovedReason())) return 4; + std::puts(on ? "release-retired views checks passed" : "views-off control checks passed"); + return 0; +} From fb2f86ac53fb91b40fde6a78bd753961610752f1 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:02:34 +0200 Subject: [PATCH 195/232] pe: harden atomic report writes and path/XML/mmap error guards in resource_inventory with CLI suite (#2582) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/resource_inventory_cli_check.py | 432 ++++++++++++++++++++++++++ tools/resource_inventory.py | 138 +++++--- 3 files changed, 528 insertions(+), 44 deletions(-) create mode 100644 tests/resource_inventory_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index eb977a69d..2cc5fbcf7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10042,6 +10042,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/bink_descriptors_aot_check.py") add_test(NAME range_manifest_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/range_manifest_check.py") + add_test(NAME pe_resource_inventory_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/resource_inventory_cli_check.py") else() message(WARNING "Python-driven tests, including the CPU fixtures, are disabled because " diff --git a/tests/resource_inventory_cli_check.py b/tests/resource_inventory_cli_check.py new file mode 100644 index 000000000..4fc6eda0f --- /dev/null +++ b/tests/resource_inventory_cli_check.py @@ -0,0 +1,432 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-write, and error-guard suite for tools/resource_inventory.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import shutil +import stat +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +sys.path.insert(0, str(TOOLS_DIR)) +import resource_inventory # noqa: E402 + + +VALID_LAYOUT = """<?xml version="1.0" encoding="utf-8"?> +<Package> + <Chunk Id="1000" Marker="Launch"> + <FileGroup SourcePath=".\\" DestinationPath="\\" Include="sample.bin" /> + <FileGroup SourcePath=".\\" DestinationPath="\\" Include="shaders.rpf" /> + </Chunk> +</Package> +""" + + +def _dxbc_dxil_container() -> bytes: + """Build a minimal DXBC container with a framed DXIL program header.""" + program = struct.pack("<II4sIII", 0, 8, b"DXIL", 0, 16, 4) + b"BC\xc0\xde" + bytes(4) + dxil_part = b"DXIL" + struct.pack("<I", len(program)) + program + table_end = 32 + 4 + total_size = table_end + len(dxil_part) + return ( + b"DXBC" + + bytes(16) + + struct.pack("<IIII", 1, total_size, 1, table_end) + + dxil_part + ) + + +def _minimal_pe_bin() -> bytes: + """Build a minimal PE header recognized by resource_inventory.signature.""" + buf = bytearray(256) + buf[0:2] = b"MZ" + pe_offset = 64 + struct.pack_into("<I", buf, 60, pe_offset) + buf[pe_offset:pe_offset + 4] = b"PE\0\0" + struct.pack_into("<HH", buf, pe_offset + 4, 0x8664, 3) + struct.pack_into("<I", buf, pe_offset + 40, 0x1234) + return bytes(buf) + + +def _sample_rpf_bytes(container: bytes) -> bytes: + """Build synthetic RPF9-like bytes with one aligned zlib stream and one raw-DEFLATE scene record.""" + z_payload = zlib.compress(container) + pad_to_16 = (-len(z_payload)) % 16 + encoder = zlib.compressobj(wbits=-15) + raw_deflate = encoder.compress(container) + encoder.flush() + record_hdr = b"rec0\0\0" + struct.pack("<4I", len(raw_deflate), 0, len(raw_deflate), len(container)) + return b"9FPR" + bytes(12) + z_payload + bytes(pad_to_16) + record_hdr + raw_deflate + + +def _copy_isolated_tools(workspace: Path) -> Path: + """Copy only the tools modules needed to run resource_inventory in isolation.""" + tools_copy = workspace / "tools" + tools_copy.mkdir(parents=True, exist_ok=True) + for name in ("resource_inventory.py", "verify_build.py"): + shutil.copy2(TOOLS_DIR / name, tools_copy / name) + return tools_copy / "resource_inventory.py" + + +def _make_validator_command(directory: Path, name: str, script_body: str) -> Path: + """Create a directly invocable validator script for the current platform.""" + py_script = directory / f"{name}.py" + py_script.write_text(script_body, encoding="utf-8") + if os.name == "nt": + wrapper = directory / f"{name}.cmd" + wrapper.write_text(f'@echo off\r\n"{sys.executable}" -B "{py_script}" %*\r\n', encoding="utf-8") + return wrapper + wrapper = directory / f"{name}.sh" + wrapper.write_text(f'#!/bin/sh\nexec "{sys.executable}" -B "{py_script}" "$@"\n', encoding="utf-8") + wrapper.chmod(wrapper.stat().st_mode | stat.S_IXUSR) + return wrapper + + +def _run_in_process(argv: list[str], tool_path: Path | None = None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + patcher = mock.patch.object(resource_inventory, "__file__", str(tool_path)) if tool_path else None + try: + if patcher is not None: + patcher.start() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = resource_inventory.main(argv) + except SystemExit as exc: + code = exc.code + rc = 0 if code is None else (int(code) if isinstance(code, int) else 1) + if not isinstance(code, (type(None), int)): + stderr.write(f"{code}\n") + finally: + if patcher is not None: + patcher.stop() + return rc, stdout.getvalue(), stderr.getvalue() + + +class ResourceInventoryCliTests(unittest.TestCase): + def _create_valid_build(self, workspace: Path, *, with_rpf: bool = True) -> tuple[Path, bytes]: + build_dir = workspace / "sample_build" + build_dir.mkdir(parents=True, exist_ok=True) + (build_dir / "layout_test.xml").write_text(VALID_LAYOUT, encoding="utf-8") + (build_dir / "sample.bin").write_bytes(_minimal_pe_bin()) + (build_dir / "ignored.torrent").write_bytes(b"ignored") + (build_dir / "extra.txt").write_bytes(b"note") + container = _dxbc_dxil_container() + if with_rpf: + (build_dir / "shaders.rpf").write_bytes(_sample_rpf_bytes(container)) + return build_dir, container + + def test_positive_cli_and_subprocess_write_report(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + build_dir, container = self._create_valid_build(workspace) + control = workspace / "control.bin" + control.write_bytes(container) + validator = _make_validator_command( + workspace, + "ok_validator", + 'import json, sys\n' + 'sys.stdin.buffer.read()\n' + 'print(json.dumps({"call_hr": "0x00000000", "status": "0x00000000"}))\n', + ) + + rc, stdout, stderr = _run_in_process( + [ + str(build_dir), + "--shader-control", + str(control), + "--scene-records", + "--scene-validator", + str(validator), + ], + tool_path=tool_copy, + ) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn("1 chunks | 4 files |", stdout) + self.assertIn("shaders.rpf", stdout) + + out_dir = workspace / "out" / "resources" + report_path = out_dir / f"{build_dir.name}.json" + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), [report_path.name]) + report = json.loads(report_path.read_text(encoding="utf-8")) + self.assertEqual(report["build"], build_dir.name) + self.assertEqual(report["layout"], "layout_test.xml") + self.assertEqual(report["outside_layout"], ["extra.txt", "layout_test.xml"]) + self.assertEqual(report["positive_control"]["sha256"], hashlib.sha256(container).hexdigest()) + self.assertEqual(report["positive_control"]["markers"]["framed_dxil_programs"], 1) + self.assertEqual(report["archive_probes"]["shaders.rpf"]["raw_markers"]["framed_dxil_programs"], 0) + self.assertEqual(len(report["archive_probes"]["shaders.rpf"]["sample_streams"]), 1) + self.assertEqual( + report["archive_probes"]["shaders.rpf"]["sample_streams"][0]["decoded_markers"]["framed_dxil_programs"], + 1, + ) + self.assertEqual(report["scene_records"]["records"], 1) + self.assertEqual(report["scene_records"]["validator_samples"], 1) + pe_row = next(row for row in report["files"] if row["path"] == "sample.bin") + self.assertEqual(pe_row["pe_machine"], "0x8664") + self.assertEqual(pe_row["pe_sections"], 3) + self.assertEqual(pe_row["pe_entry_rva"], 0x1234) + + proc = subprocess.run( + [sys.executable, "-B", str(tool_copy), str(build_dir), "--scene-records"], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), [report_path.name]) + + def test_atomic_write_preserves_existing_report_and_leaves_zero_temp_artifacts(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + build_dir, _ = self._create_valid_build(workspace, with_rpf=False) + out_dir = workspace / "out" / "resources" + out_dir.mkdir(parents=True) + report_path = out_dir / f"{build_dir.name}.json" + sentinel = '{"preserved": true}\n' + report_path.write_text(sentinel, encoding="utf-8") + + for patch_target, exc in ( + ((resource_inventory.os, "replace"), OSError("disk full")), + ((resource_inventory.json, "dump"), OSError("write error")), + ((resource_inventory.json, "dump"), TypeError("unserializable")), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(patch_target[0], patch_target[1], side_effect=exc): + rc, stdout, stderr = _run_in_process([str(build_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertEqual(stdout, "") + self.assertTrue(stderr.startswith("resource_inventory: "), stderr) + self.assertIn(str(exc), stderr) + self.assertNotIn("Traceback", stderr) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), [report_path.name]) + self.assertEqual(report_path.read_text(encoding="utf-8"), sentinel) + + def test_output_directory_and_output_inside_input_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + build_dir, _ = self._create_valid_build(workspace, with_rpf=False) + out_dir = workspace / "out" / "resources" + bad_output_dir = out_dir / f"{build_dir.name}.json" + bad_output_dir.mkdir(parents=True) + + with mock.patch.object(resource_inventory.json, "dump", side_effect=AssertionError("unexpected dump")): + rc, _, stderr = _run_in_process([str(build_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr.startswith("resource_inventory: "), stderr) + self.assertIn("directory", stderr) + self.assertNotIn("Traceback", stderr) + self.assertTrue(bad_output_dir.is_dir()) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), [bad_output_dir.name]) + + # Input directory is the workspace root itself, so out/resources/<name>.json sits inside root. + (workspace / "layout_root.xml").write_text("<Package/>", encoding="utf-8") + rc, _, stderr = _run_in_process([str(workspace)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr.startswith("resource_inventory: "), stderr) + self.assertIn("outside", stderr) + self.assertNotIn("Traceback", stderr) + + def test_directory_and_layout_guards(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + + # Missing CLI args (Python 3.14-compatible argparse assertion). + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + with self.assertRaises(SystemExit) as cm: + resource_inventory.main([]) + self.assertNotEqual(cm.exception.code, 0) + self.assertIn("directory", stderr.getvalue().lower()) + self.assertNotIn("Traceback", stderr.getvalue()) + + # Missing input directory -> exit 1. + rc, _, stderr_text = _run_in_process([str(workspace / "missing_dir")], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # File passed instead of directory -> exit 1. + not_a_dir = workspace / "file.txt" + not_a_dir.write_text("hello", encoding="utf-8") + rc, _, stderr_text = _run_in_process([str(not_a_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # layout*.xml count != 1 preserves parser.error exit 2. + empty_dir = workspace / "no_layout" + empty_dir.mkdir() + rc, _, stderr_text = _run_in_process([str(empty_dir)], tool_path=tool_copy) + self.assertEqual(rc, 2) + self.assertIn("layout*.xml", stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # Malformed XML and missing attributes -> exit 1. + for label, content in ( + ("malformed_xml", "<Package>"), + ("missing_id", "<Package><Chunk/></Package>"), + ("missing_include", '<Package><Chunk Id="1"><FileGroup DestinationPath="\\"/></Chunk></Package>'), + ): + with self.subTest(case=label): + bad_dir = workspace / label + bad_dir.mkdir() + (bad_dir / "layout.xml").write_text(content, encoding="utf-8") + rc, _, stderr_text = _run_in_process([str(bad_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # Unreadable layout (OSError) -> exit 1. + valid_dir, _ = self._create_valid_build(workspace, with_rpf=False) + with mock.patch.object(resource_inventory, "read_layout", side_effect=OSError("layout read denied")): + rc, _, stderr_text = _run_in_process([str(valid_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertIn("layout read denied", stderr_text) + self.assertNotIn("Traceback", stderr_text) + + def test_shader_control_and_probe_archive_guards(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + build_dir, _ = self._create_valid_build(workspace, with_rpf=False) + + bad_control = workspace / "no_dxil.bin" + bad_control.write_bytes(b"not a dxil container") + control_dir = workspace / "control_dir" + control_dir.mkdir() + + for label, arg_path in ( + ("missing", workspace / "missing_control.bin"), + ("directory", control_dir), + ("no_dxil", bad_control), + ): + with self.subTest(shader_control=label): + rc, _, stderr_text = _run_in_process( + [str(build_dir), "--shader-control", str(arg_path)], + tool_path=tool_copy, + ) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # 0-byte RPF9 archive triggers ValueError in probe_archive -> exit 1. + (build_dir / "shaders.rpf").write_bytes(b"") + rc, _, stderr_text = _run_in_process([str(build_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertIn("Empty archive", stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # OSError from probe_archive -> exit 1. + (build_dir / "shaders.rpf").write_bytes(b"9FPR" + bytes(16)) + with mock.patch.object(resource_inventory, "probe_archive", side_effect=OSError("archive io error")): + rc, _, stderr_text = _run_in_process([str(build_dir)], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertIn("archive io error", stderr_text) + self.assertNotIn("Traceback", stderr_text) + + def test_scene_records_and_validator_guards(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + build_dir, _ = self._create_valid_build(workspace, with_rpf=False) + + # Missing shaders.rpf with --scene-records -> exit 1. + rc, _, stderr_text = _run_in_process([str(build_dir), "--scene-records"], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # shaders.rpf is a directory -> exit 1. + rpf_dir = build_dir / "shaders.rpf" + rpf_dir.mkdir() + rc, _, stderr_text = _run_in_process([str(build_dir), "--scene-records"], tool_path=tool_copy) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + rpf_dir.rmdir() + + # Restore valid shaders.rpf for validator guard tests. + build_dir, _ = self._create_valid_build(workspace, with_rpf=True) + val_dir = workspace / "val_dir" + val_dir.mkdir() + fail_val = _make_validator_command(workspace, "fail_val", "import sys\nsys.exit(3)\n") + bad_json_val = _make_validator_command(workspace, "bad_json", 'print("{not json")\n') + missing_key_val = _make_validator_command(workspace, "missing_key", 'print("{}")\n') + + for label, val_path in ( + ("missing_validator", workspace / "missing_validator.exe"), + ("dir_validator", val_dir), + ("failing_validator", fail_val), + ("bad_json_validator", bad_json_val), + ("missing_key_validator", missing_key_val), + ): + with self.subTest(validator=label): + rc, _, stderr_text = _run_in_process( + [str(build_dir), "--scene-validator", str(val_path)], + tool_path=tool_copy, + ) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + # Guarded exception types in scene_records -> exit 1 without traceback. + dummy_val = _make_validator_command(workspace, "dummy_val", "import sys\nsys.exit(0)\n") + for exc in ( + OSError("mmap failure"), + ValueError("bad value"), + struct.error("short unpack"), + subprocess.TimeoutExpired(cmd="val", timeout=15), + json.JSONDecodeError("bad", "doc", 0), + ): + with self.subTest(scene_exc=type(exc).__name__): + with mock.patch.object(resource_inventory, "scene_records", side_effect=exc): + rc, _, stderr_text = _run_in_process( + [str(build_dir), "--scene-records", "--scene-validator", str(dummy_val)], + tool_path=tool_copy, + ) + self.assertEqual(rc, 1) + self.assertTrue(stderr_text.startswith("resource_inventory: "), stderr_text) + self.assertNotIn("Traceback", stderr_text) + + def test_subprocess_negative_smoke(self): + with tempfile.TemporaryDirectory() as tmp: + workspace = Path(tmp) + tool_copy = _copy_isolated_tools(workspace) + build_dir, _ = self._create_valid_build(workspace, with_rpf=False) + (build_dir / "shaders.rpf").write_bytes(b"") + + proc = subprocess.run( + [sys.executable, "-B", str(tool_copy), str(build_dir)], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1) + self.assertTrue(proc.stderr.startswith("resource_inventory: "), proc.stderr) + self.assertIn("Empty archive", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/resource_inventory.py b/tools/resource_inventory.py index 2cde077b5..ecd97bd33 100644 --- a/tools/resource_inventory.py +++ b/tools/resource_inventory.py @@ -5,11 +5,13 @@ import hashlib import json import mmap +import os from pathlib import Path import re import struct import subprocess -from tempfile import NamedTemporaryFile +import tempfile +import xml.etree.ElementTree as ET import zlib from verify_build import read_layout @@ -198,36 +200,59 @@ def scene_records(data, validator=None, *, observe=None): "validator_samples": len(samples), "first_per_stage": samples} -def main(argv=None): +def _write_atomic_json(output: Path, report: dict) -> None: + if output.is_dir(): + raise IsADirectoryError(f"output path is a directory: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=output.parent, prefix=f".{output.name}.") as tmp_dir: + tmp_path = Path(tmp_dir) / output.name + with tmp_path.open("w", encoding="utf-8", newline="\n") as handle: + json.dump(report, handle, indent=2, ensure_ascii=False) + handle.write("\n") + os.replace(tmp_path, output) + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("directory", type=Path) parser.add_argument("--shader-control", type=Path) parser.add_argument("--scene-records", action="store_true", help="Inspect compressed records in shaders.rpf") parser.add_argument("--scene-validator", type=Path, help="Use the built root_probe.exe on one container per stage") args = parser.parse_args(argv) - root = args.directory.resolve(strict=True) - layouts = [path for path in root.glob("layout*.xml") if path.is_file()] + try: + root = args.directory.resolve(strict=True) + if not root.is_dir(): + raise NotADirectoryError(f"not a directory: {root}") + layouts = [path for path in sorted(root.glob("layout*.xml")) if path.is_file()] + except OSError as exc: + parser.exit(1, f"resource_inventory: {exc}\n") if len(layouts) != 1: parser.error(f"expected exactly one layout*.xml file in {root}, found {len(layouts)}") layout, = layouts - markers, targets = read_layout(layout) + try: + markers, targets = read_layout(layout) + except (OSError, ET.ParseError, KeyError) as exc: + parser.exit(1, f"resource_inventory: {exc}\n") rows = [] - for path in sorted(root.rglob("*")): - if not path.is_file() or path.suffix.lower() == ".torrent": - continue - with path.open("rb") as stream: - header = stream.read(1024) - name = path.relative_to(root).as_posix() - row = {"path": name, "bytes": path.stat().st_size, "chunks": targets.get(name, []), - "prefix_hex": header[:8].hex(), "signature": signature(header)} - if row["signature"] == "PE" and path.suffix.lower() == ".bin": - pe_offset, = struct.unpack_from("<I", header, 60) - if pe_offset + 44 <= len(header): - machine, sections = struct.unpack_from("<HH", header, pe_offset + 4) - row["pe_machine"] = hex(machine) - row["pe_sections"] = sections - row["pe_entry_rva"], = struct.unpack_from("<I", header, pe_offset + 40) - rows.append(row) + try: + for path in sorted(root.rglob("*")): + if not path.is_file() or path.suffix.lower() == ".torrent": + continue + with path.open("rb") as stream: + header = stream.read(1024) + name = path.relative_to(root).as_posix() + row = {"path": name, "bytes": path.stat().st_size, "chunks": targets.get(name, []), + "prefix_hex": header[:8].hex(), "signature": signature(header)} + if row["signature"] == "PE" and path.suffix.lower() == ".bin": + pe_offset, = struct.unpack_from("<I", header, 60) + if pe_offset + 44 <= len(header): + machine, sections = struct.unpack_from("<HH", header, pe_offset + 4) + row["pe_machine"] = hex(machine) + row["pe_sections"] = sections + row["pe_entry_rva"], = struct.unpack_from("<I", header, pe_offset + 40) + rows.append(row) + except (OSError, struct.error) as exc: + parser.exit(1, f"resource_inventory: {exc}\n") available = {r["path"] for r in rows} chunks = {} for chunk, marker in markers.items(): @@ -236,14 +261,25 @@ def main(argv=None): "present_bytes": sum(r["bytes"] for r in rows if chunk in r["chunks"]), "missing": sorted(set(files) - available)} control = None - if args.shader_control: - data = args.shader_control.read_bytes() - control = {"file": args.shader_control.name, "sha256": hashlib.sha256(data).hexdigest(), - "markers": shader_markers(data)} - if not control["markers"]["framed_dxil_programs"]: - raise ValueError("Positive control has no structurally recognizable DXIL program") - focus = {name: probe_archive(root / name) for name in ("appdata0.rpf", "common.rpf", "shaders.rpf") - if name in available} + if args.shader_control is not None: + control_path = args.shader_control + try: + if control_path.is_dir(): + raise IsADirectoryError(f"shader control is a directory: {control_path}") + if not control_path.is_file(): + raise FileNotFoundError(f"shader control not found: {control_path}") + data = control_path.read_bytes() + control = {"file": control_path.name, "sha256": hashlib.sha256(data).hexdigest(), + "markers": shader_markers(data)} + if not control["markers"]["framed_dxil_programs"]: + raise ValueError("Positive control has no structurally recognizable DXIL program") + except (OSError, ValueError) as exc: + parser.exit(1, f"resource_inventory: {exc}\n") + try: + focus = {name: probe_archive(root / name) for name in ("appdata0.rpf", "common.rpf", "shaders.rpf") + if name in available} + except (OSError, ValueError) as exc: + parser.exit(1, f"resource_inventory: {exc}\n") report = { "build": root.name, "layout": layout.name, "chunks": chunks, "signature_counts": dict(Counter(r["signature"] for r in rows)), "files": rows, @@ -252,25 +288,39 @@ def main(argv=None): "probe_scope": "Raw marker search covers the three entire archives. Sample up to 8 checksum-valid zlib streams at 16-byte aligned 78xx headers in first 4 MiB; limits 512 KiB input and 2 MiB output per candidate. No inference about remaining encoded content.", "positive_control": control, "archive_probes": focus, } - if args.scene_records or args.scene_validator: - with (root / "shaders.rpf").open("rb") as stream: - if stream.seek(0, 2): - with mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: - report["scene_records"] = scene_records(data, args.scene_validator) - else: - report["scene_records"] = scene_records(b"") + if args.scene_records or args.scene_validator is not None: + shaders_rpf = root / "shaders.rpf" + validator = args.scene_validator + try: + if validator is not None: + if validator.is_dir(): + raise IsADirectoryError(f"scene validator is a directory: {validator}") + if not validator.is_file(): + raise FileNotFoundError(f"scene validator not found: {validator}") + if shaders_rpf.is_dir(): + raise IsADirectoryError(f"shaders.rpf is a directory: {shaders_rpf}") + if not shaders_rpf.is_file(): + raise FileNotFoundError(f"missing shaders.rpf in {root}") + with shaders_rpf.open("rb") as stream: + if stream.seek(0, 2): + with mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: + report["scene_records"] = scene_records(data, validator) + else: + report["scene_records"] = scene_records(b"", validator) + except (OSError, ValueError, KeyError, struct.error, subprocess.SubprocessError, json.JSONDecodeError) as exc: + parser.exit(1, f"resource_inventory: {exc}\n") output = Path(__file__).resolve().parents[1] / "out" / "resources" / (root.name + ".json") - if output.resolve().is_relative_to(root): - raise ValueError("Resource report must be outside the game directory") - output.parent.mkdir(parents=True, exist_ok=True) - with NamedTemporaryFile(dir=output.parent, mode="w", encoding="utf-8", delete=False) as f: - json.dump(report, f, indent=2, ensure_ascii=False) - f.write("\n") - Path(f.name).replace(output) + try: + if output.resolve().is_relative_to(root): + raise ValueError("Resource report must be outside the game directory") + _write_atomic_json(output, report) + except (OSError, ValueError, TypeError) as exc: + parser.exit(1, f"resource_inventory: {exc}\n") print(f"{len(chunks)} chunks | {len(rows)} files | {output}") for name, probe in focus.items(): print(name, probe["raw_markers"], "sampled zlib streams", len(probe["sample_streams"])) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 10b2dafb58661015419552d7e8a4037bff495077 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:10:11 +0200 Subject: [PATCH 196/232] runtime: extract main(argv) and add path/key/timeout guards in mesh86_cache with CLI suite (#2584) --- CMakeLists.txt | 2 + tests/startup_mesh86_cache_cli_check.py | 353 ++++++++++++++++++++++++ tools/startup/mesh86_cache.py | 31 ++- 3 files changed, 379 insertions(+), 7 deletions(-) create mode 100644 tests/startup_mesh86_cache_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 2cc5fbcf7..7fb325fa6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1610,6 +1610,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh86_srv_proof_check.py" "${DXC_EXECUTABLE}" "${CMAKE_CURRENT_BINARY_DIR}") set_tests_properties(startup_mesh86_srv_proof PROPERTIES TIMEOUT 60) + add_test(NAME runtime_mesh86_cache_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh86_cache_cli_check.py") add_test(NAME startup_indirect_mesh_lease_warp_dual-trace-disabled COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_indirect_mesh_cache_check.py" "${DXC_EXECUTABLE}" "$<TARGET_FILE:startup_indirect_draw_indexed>" warp diff --git a/tests/startup_mesh86_cache_cli_check.py b/tests/startup_mesh86_cache_cli_check.py new file mode 100644 index 000000000..706b9987a --- /dev/null +++ b/tests/startup_mesh86_cache_cli_check.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, path/key/timeout-guard, and atomic-publish suite for tools/startup/mesh86_cache.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import stat +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_STARTUP = ROOT / "tools" / "startup" +TOOL = TOOLS_STARTUP / "mesh86_cache.py" +sys.path.insert(0, str(TOOLS_STARTUP)) +import mesh86_cache # noqa: E402 + + +VALID_MS_DUMP = """; Resource Bindings: +; +; Name Type Format Dim ID HLSL Bind Count +; --------------------------------------- +; source texture byte r/o T0 t0 1 + +%1 = call %dx.types.Handle @dx.op.createHandle(i32 57, i8 0, i32 0, i32 0, i1 false) +%2 = call %dx.types.ResRet.i32 @dx.op.rawBufferLoad.i32(i32 139, %dx.types.Handle %1, i32 0, i32 undef, i8 1, i32 4) +call void @dx.op.emitIndices(i32 169, i32 0, i32 0, i32 1, i32 2) +""" + +VALID_PS_DUMP = """%1 = call float @dx.op.loadInput.f32(i32 4, i32 0, i32 0, i8 0, i32 undef) +call void @dx.op.storeOutput.f32(i32 5, i32 0, i32 0, i8 0, float %1) +""" + + +def _source_envelope(stage: int) -> bytes: + """Build a synthetic Xbox shader envelope compatible with mesh86_cache.load_request.""" + image = b"FSSM" + bytes(192) + compressed = zlib.compress(image) + native = b"XBCH" + struct.pack("<IQQ", 3, len(compressed), len(image)) + compressed + program = ( + struct.pack("<I", (stage << 16) | 0x65) + + bytes(20) + + b"XDAT" + + struct.pack("<IIIII", 1, 36, 13, 48, len(native)) + + native + ) + part = b"DXIL" + struct.pack("<I", len(program)) + program + return b"DXBC" + bytes(16) + struct.pack("<IIII", 1, 36 + len(part), 1, 36) + part + + +def _desktop_dxbc(stage: int, marker_byte: int = 0) -> bytes: + """Build a valid desktop DXBC/DXIL container accepted by mesh86_cache.desktop_stage.""" + program = struct.pack("<II4sIII", (stage << 16) | 0x65, 7, b"DXIL", 0, 16, 4) + b"BC\xc0\xde" + if marker_byte: + program += struct.pack("<I", marker_byte) + program = program[:4] + struct.pack("<I", len(program) // 4) + program[8:] + part = b"DXIL" + struct.pack("<I", len(program)) + program + return b"DXBC" + bytes(16) + struct.pack("<IIII", 1, 36 + len(part), 1, 36) + part + + +def _write_request(cache_dir: Path, *, with_pixel: bool = True) -> int: + ms = _source_envelope(13) + ps = _source_envelope(0) if with_pixel else b"" + root = b"DXBC" + bytes(28) + stream = bytes(32) + key = mesh86_cache.request_key(ms, ps, root, stream) + stem = cache_dir / f"req_{key:016x}" + for suffix, data in zip((".m86", ".ps86", ".root", ".stream86"), (ms, ps, root, stream)): + stem.with_suffix(suffix).write_bytes(data) + return key + + +def _make_fake_dxc(directory: Path, name: str, script_body: str) -> Path: + py_script = directory / f"{name}.py" + py_script.write_text(script_body, encoding="utf-8") + if os.name == "nt": + wrapper = directory / f"{name}.cmd" + wrapper.write_text(f'@echo off\r\n"{sys.executable}" -B "{py_script}" %*\r\n', encoding="utf-8") + return wrapper + wrapper = directory / f"{name}.sh" + wrapper.write_text(f'#!/bin/sh\nexec "{sys.executable}" -B "{py_script}" "$@"\n', encoding="utf-8") + wrapper.chmod(wrapper.stat().st_mode | stat.S_IXUSR) + return wrapper + + +def _run_cli(argv: list[str]) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = mesh86_cache.main(argv) + except SystemExit as exc: + code = exc.code + rc = 0 if code is None else (int(code) if isinstance(code, int) else 1) + if not isinstance(code, (type(None), int)): + stderr.write(f"{code}\n") + return rc, stdout.getvalue(), stderr.getvalue() + + +class Mesh86CacheCliTests(unittest.TestCase): + def test_positive_inspect_publish_and_prove_root_srv(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + cache = root / "cache" + cache.mkdir() + key = _write_request(cache, with_pixel=True) + ms_cso = root / "desktop.ms.cso" + ps_cso = root / "desktop.ps.cso" + ms_cso.write_bytes(_desktop_dxbc(13)) + ps_cso.write_bytes(_desktop_dxbc(0)) + + # Inspect mode via main(argv) -> 0. + rc, stdout, stderr = _run_cli([str(cache), f"{key:016x}"]) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn(f"{key:016x}: MS", stdout) + + # Publish mode without --prove-root-srv. + rc, stdout, stderr = _run_cli([str(cache), f"{key:016x}", "--mesh", str(ms_cso), "--pixel", str(ps_cso)]) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn("published desktop stages", stdout) + ready = cache / f"{key:016x}.mesh86.txt" + self.assertTrue(ready.read_text(encoding="ascii").startswith("x2w-mesh86 1 ")) + self.assertEqual( + sorted(p.name for p in cache.iterdir()), + sorted([ + f"{key:016x}.mesh86.txt", + f"{key:016x}.ms.cso", + f"{key:016x}.ps.cso", + f"req_{key:016x}.m86", + f"req_{key:016x}.ps86", + f"req_{key:016x}.root", + f"req_{key:016x}.stream86", + ]), + ) + + # Publish mode with --prove-root-srv and timeout=30 verification. + fake_dxc = _make_fake_dxc( + root, + "fake_dxc", + "import sys\n" + "target = sys.argv[-1]\n" + f"print({VALID_MS_DUMP!r} if target.endswith('ms') else {VALID_PS_DUMP!r})\n", + ) + real_run = subprocess.run + observed_timeouts = [] + + def spy_run(*args, **kwargs): + observed_timeouts.append(kwargs.get("timeout")) + return real_run(*args, **kwargs) + + with mock.patch.object(mesh86_cache.subprocess, "run", side_effect=spy_run): + rc, stdout, stderr = _run_cli([ + str(cache), + f"{key:016x}", + "--mesh", + str(ms_cso), + "--pixel", + str(ps_cso), + "--prove-root-srv", + str(fake_dxc), + ]) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertEqual(observed_timeouts, [30, 30]) + marker_text = ready.read_text(encoding="ascii") + self.assertTrue(marker_text.startswith("x2w-mesh86 2 ")) + self.assertTrue(marker_text.endswith(" srv 0 0 4\n")) + + # Subprocess positive smoke test. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(cache), f"{key:016x}"], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn(f"{key:016x}: MS", proc.stdout) + + def test_key_range_and_argparse_guards(self): + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) / "cache" + cache.mkdir() + + # Missing args / invalid hex -> non-zero SystemExit without traceback. + for bad_argv, expected_substr in ( + ([], "required"), + ([str(cache), "not_hex"], "invalid"), + ): + with self.subTest(bad_argv=bad_argv): + rc, _, stderr = _run_cli(bad_argv) + self.assertNotEqual(rc, 0) + self.assertIn(expected_substr, stderr.lower()) + self.assertNotIn("Traceback", stderr) + + # Out-of-range 64-bit keys -> exit 1 without touching cache files. + for bad_key in ("-1", "10000000000000000", "1ffffffffffffffff"): + with self.subTest(bad_key=bad_key): + rc, _, stderr = _run_cli([str(cache), bad_key]) + self.assertEqual(rc, 1) + self.assertIn("64-bit", stderr) + self.assertNotIn("Traceback", stderr) + + # Boundary 64-bit keys (0 and 2^64-1) pass the range check and only fail on missing req files. + for boundary_key in ("0", "ffffffffffffffff"): + with self.subTest(boundary_key=boundary_key): + rc, _, stderr = _run_cli([str(cache), boundary_key]) + self.assertEqual(rc, 1) + self.assertNotIn("64-bit", stderr) + self.assertNotIn("Traceback", stderr) + + def test_cache_and_input_path_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + cache = root / "cache" + cache.mkdir() + key = _write_request(cache, with_pixel=True) + valid_ms = root / "ms.cso" + valid_ps = root / "ps.cso" + valid_ms.write_bytes(_desktop_dxbc(13)) + valid_ps.write_bytes(_desktop_dxbc(0)) + regular_file = root / "not_a_dir.bin" + regular_file.write_bytes(b"data") + dir_path = root / "a_dir" + dir_path.mkdir() + + # Cache missing or regular file -> exit 1. + for bad_cache in (root / "missing_cache", regular_file): + with self.subTest(bad_cache=bad_cache): + rc, _, stderr = _run_cli([str(bad_cache), f"{key:016x}"]) + self.assertEqual(rc, 1) + self.assertIn("cache directory", stderr) + self.assertNotIn("Traceback", stderr) + + # --pixel or --prove-root-srv without --mesh -> exit 1. + for extra_args in (["--pixel", str(valid_ps)], ["--prove-root-srv", str(valid_ms)]): + with self.subTest(extra_args=extra_args): + rc, _, stderr = _run_cli([str(cache), f"{key:016x}", *extra_args]) + self.assertEqual(rc, 1) + self.assertIn("--mesh", stderr) + self.assertNotIn("Traceback", stderr) + + # Missing or directory paths for --mesh, --pixel, --prove-root-srv -> exit 1. + cases = ( + (["--mesh", str(root / "missing.cso")], "--mesh"), + (["--mesh", str(dir_path)], "--mesh"), + (["--mesh", str(valid_ms), "--pixel", str(root / "missing.cso")], "--pixel"), + (["--mesh", str(valid_ms), "--pixel", str(dir_path)], "--pixel"), + (["--mesh", str(valid_ms), "--pixel", str(valid_ps), "--prove-root-srv", str(root / "missing_dxc")], "--prove-root-srv"), + (["--mesh", str(valid_ms), "--pixel", str(valid_ps), "--prove-root-srv", str(dir_path)], "--prove-root-srv"), + ) + for extra_args, opt in cases: + with self.subTest(opt=opt, extra_args=extra_args): + rc, _, stderr = _run_cli([str(cache), f"{key:016x}", *extra_args]) + self.assertEqual(rc, 1) + self.assertIn(opt, stderr) + self.assertNotIn("Traceback", stderr) + + def test_timeout_subprocess_struct_and_atomic_preservation_guards(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + cache = root / "cache" + cache.mkdir() + key = _write_request(cache, with_pixel=True) + ms_cso = root / "ms.cso" + ps_cso = root / "ps.cso" + ms_cso.write_bytes(_desktop_dxbc(13, marker_byte=1)) + ps_cso.write_bytes(_desktop_dxbc(0, marker_byte=1)) + + # Publish initial valid artifacts so we can verify preservation on subsequent failures. + rc, _, stderr = _run_cli([str(cache), f"{key:016x}", "--mesh", str(ms_cso), "--pixel", str(ps_cso)]) + self.assertEqual(rc, 0, stderr) + ready = cache / f"{key:016x}.mesh86.txt" + ms_out = cache / f"{key:016x}.ms.cso" + ps_out = cache / f"{key:016x}.ps.cso" + prev_ready = ready.read_bytes() + prev_ms = ms_out.read_bytes() + prev_ps = ps_out.read_bytes() + expected_entries = sorted(p.name for p in cache.iterdir()) + + # Replace desktop inputs with distinct valid bytes to detect any partial write on failure. + ms_cso.write_bytes(_desktop_dxbc(13, marker_byte=2)) + ps_cso.write_bytes(_desktop_dxbc(0, marker_byte=2)) + + failing_dxc = _make_fake_dxc(root, "fail_dxc", "import sys\nsys.exit(7)\n") + with mock.patch.object( + mesh86_cache.subprocess, + "run", + side_effect=subprocess.TimeoutExpired(cmd="dxc", timeout=30), + ): + rc, _, stderr = _run_cli([ + str(cache), + f"{key:016x}", + "--mesh", + str(ms_cso), + "--pixel", + str(ps_cso), + "--prove-root-srv", + str(failing_dxc), + ]) + self.assertEqual(rc, 1) + self.assertNotIn("Traceback", stderr) + self.assertEqual(ready.read_bytes(), prev_ready) + self.assertEqual(ms_out.read_bytes(), prev_ms) + self.assertEqual(ps_out.read_bytes(), prev_ps) + self.assertEqual(sorted(p.name for p in cache.iterdir()), expected_entries) + + # Real failing subprocess (--prove-root-srv non-zero exit) preserves existing artifacts. + rc, _, stderr = _run_cli([ + str(cache), + f"{key:016x}", + "--mesh", + str(ms_cso), + "--pixel", + str(ps_cso), + "--prove-root-srv", + str(failing_dxc), + ]) + self.assertEqual(rc, 1) + self.assertNotIn("Traceback", stderr) + self.assertEqual(ready.read_bytes(), prev_ready) + self.assertEqual(ms_out.read_bytes(), prev_ms) + self.assertEqual(ps_out.read_bytes(), prev_ps) + self.assertEqual(sorted(p.name for p in cache.iterdir()), expected_entries) + + # struct.error and ValueError in load_request exit 1 without traceback. + with mock.patch.object(mesh86_cache, "load_request", side_effect=struct.error("short unpack")): + rc, _, stderr = _run_cli([str(cache), f"{key:016x}"]) + self.assertEqual(rc, 1) + self.assertIn("short unpack", stderr) + self.assertNotIn("Traceback", stderr) + + # Subprocess negative smoke test. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(cache), "10000000000000000"], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1) + self.assertIn("64-bit", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/startup/mesh86_cache.py b/tools/startup/mesh86_cache.py index cc70dd050..dd255cf42 100644 --- a/tools/startup/mesh86_cache.py +++ b/tools/startup/mesh86_cache.py @@ -144,7 +144,7 @@ def publish(cache, key, ms_path, ps_path, *, srv_dxc=None): # Dump the very bytes that will be published, including when the # original shader paths change concurrently. dumps = [subprocess.run([srv_dxc, '-dumpbin', work / stage], check=True, - capture_output=True, text=True, encoding='utf-8').stdout + capture_output=True, text=True, encoding='utf-8', timeout=30).stdout for stage in ('ms', 'ps')] extent = prove_mesh_root_srv(*dumps) manifest = f'x2w-mesh86 2 {hashes} srv 0 0 {extent}\n' @@ -156,7 +156,14 @@ def publish(cache, key, ms_path, ps_path, *, srv_dxc=None): (work / 'marker').replace(ready) -def main(): +def _require_file(path: Path, option: str) -> None: + if path.is_dir(): + raise IsADirectoryError(f'{option} must be a regular file, not a directory: {path}') + if not path.is_file(): + raise FileNotFoundError(f'{option} file not found: {path}') + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('cache', type=Path) parser.add_argument('key', type=lambda text: int(text, 16)) @@ -164,19 +171,29 @@ def main(): parser.add_argument('--pixel', type=Path, help='desktop PS DXIL when the captured input has a pixel stage') parser.add_argument('--prove-root-srv', type=Path, metavar='DXC', help='use DXC to verify the bounded single-DWORD mesh root SRV profile') - args = parser.parse_args() + args = parser.parse_args(argv) try: - if args.mesh: + if not 0 <= args.key < (1 << 64): + raise ValueError(f'request key out of 64-bit range: {args.key:#x}') + if not args.cache.is_dir(): + raise NotADirectoryError(f'cache directory not found: {args.cache}') + if args.mesh is not None: + _require_file(args.mesh, '--mesh') + if args.pixel is not None: + _require_file(args.pixel, '--pixel') + if args.prove_root_srv is not None: + _require_file(args.prove_root_srv, '--prove-root-srv') publish(args.cache, args.key, args.mesh, args.pixel, srv_dxc=args.prove_root_srv) print(f'{args.key:016x}: published desktop stages') else: - if args.pixel or args.prove_root_srv: + if args.pixel is not None or args.prove_root_srv is not None: raise ValueError('--pixel and --prove-root-srv require --mesh') ms, ps, root, stream = load_request(args.cache, args.key) print(f'{args.key:016x}: MS {len(ms)}, PS {len(ps)}, root {len(root)}, stream {len(stream)} bytes') - except (ValueError, OSError, struct.error, subprocess.CalledProcessError) as error: + except (ValueError, OSError, struct.error, subprocess.SubprocessError) as error: parser.exit(1, f'{error}\n') + return 0 if __name__ == '__main__': - main() + raise SystemExit(main()) From 168f2477f6d05b02ceedacc9cafce31022581470 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <lycqay@gmail.com> Date: Thu, 26 Nov 2026 06:10:18 +0800 Subject: [PATCH 197/232] tests: verify formatted mesh loads against the descriptor format and selector (#2576) Part of #2413 (T3). AI-assisted with Codex (GPT-6.2 Astra, xhigh). Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- CMakeLists.txt | 4 ++ docs/experiments.md | 8 +++ tests/startup_mesh57_skeleton_check.py | 70 +++++++++++++++++++++++++- 3 files changed, 81 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7fb325fa6..1af9d9983 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8791,6 +8791,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) set_tests_properties(startup_mesh57_skeleton_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_formatted_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" formatted "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_mesh57_formatted_load_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_skeleton_exchange_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" exchange "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter} "$<TARGET_FILE:startup_indirect_draw_indexed>") diff --git a/docs/experiments.md b/docs/experiments.md index 7c81370a7..9275336d7 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9471,6 +9471,14 @@ VGPR source, a different VCC write, or a narrowed EXEC at the branch invalidates the proof. The CPU-reference draws cover both outcomes for each branch polarity and a VCC-zero branch after a join. +The `startup_mesh57_formatted_load_{warp,hardware}` tests use one +`buffer_load_format_x` to set vertex red. The fixture supplies descriptor word 3 +in the constant slot published as `descword3` for SRV 0. It draws the same mesh +and buffer with R32_FLOAT, RGBA8_UNORM red and RGBA8_UNORM blue. The CPU +rasterizer checks all 1,024 pixels for each view and counts the changed pixels +when the draw uses the wrong format or component. Overwriting the descriptor's +format word in the guest program produces a translation refusal. + Set `X2W_REFUSE_FIXED_MESH=1` to report unavailable fixed mesh pipelines at slot 57 creation. The descriptor must name a registered root, have an empty VS slot and have a readable 16-byte to 64-KiB MS span. The PS span must be diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index 14c661f44..cd00dec9b 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -3,6 +3,7 @@ usage: startup_mesh57_skeleton_check.py startup_mesh57_skeleton_check.py binary <llvm-mc> startup_mesh57_skeleton_check.py draw <dxc> <offscreen_check> <warp|hardware> + startup_mesh57_skeleton_check.py formatted <dxc> <offscreen_check> <warp|hardware> startup_mesh57_skeleton_check.py exchange <dxc> <offscreen_check> <warp|hardware> <publisher> The fixture (tests/startup_mesh57_skeleton.s, source-built) holds the accepted shape: lane 0 of wave 0 stores a @@ -44,6 +45,13 @@ 'v_interp_mov_f32 v3, p0, attr0.w\nexp mrt0 v0, v1, v2, v3 done vm\ns_endpgm\n') PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() +# Overwrite red after the raw colour load; green, blue and alpha still come from its other three words. +COLOUR_LOAD = 'buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192' +FORMAT_LOAD = 'buffer_load_format_x v20, v4, s[16:19], 0 offen offset:192' +AFTER_COLOUR_LOAD = MESH.index('e03810c0') + 2 +FORMATTED_MESH = MESH[:AFTER_COLOUR_LOAD] + ['e00010c0', '80041404'] + MESH[AFTER_COLOUR_LOAD:] +REWRITTEN_FORMAT = FORMATTED_MESH[:AFTER_COLOUR_LOAD] + ['be930380'] + FORMATTED_MESH[AFTER_COLOUR_LOAD:] # s_mov_b32 s19, 0 + def code(words): return b''.join(struct.pack('<I', int(word, 16)) for word in words) @@ -148,6 +156,8 @@ def expect(what, got, want): REFUSALS = ( + ('formatted load with descriptor word 3 overwritten', REWRITTEN_FORMAT, + 'formatted buffer load through a descriptor whose words were rewritten'), # The request must carry the two stored counts, in this order. ('a request that publishes another count', mutate('887c0e04', '887c0d04'), 'slot 57 mesh count exchange: instruction 15 of the accepted shape (s_or_b32) is absent'), @@ -301,6 +311,14 @@ def controls(): expect(what + ' uses forward block dispatch', ('if (pc ==' in text, '[loop]' in text), (True, False)) expect(what + ' guards the position export', bool(re.search( r'if \(exec & 1\) \{[^\n]*o\.pos = [^\n]*mesh_vertex = true;', text)), True) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, FORMATTED_MESH) + expect('formatted mesh translates', result, 'ok') + if result == 'ok': + manifest = (Path(tmp) / ('%016x.ms57.txt' % key)).read_text().splitlines() + expect('formatted mesh reads word 3 from its bound SRV', + [s.split()[2:] for s in manifest if s.startswith('udsrc ') and 'descword3' in s], [['descword3', '0']]) + expect('formatted mesh SRV', [s for s in manifest if s.startswith('srv ')], ['srv 0 buf table 1 0']) for what, mesh, reason in REFUSALS: with tempfile.TemporaryDirectory() as tmp: key, result = request(tmp, mesh) @@ -361,7 +379,12 @@ def assemble(mc, text): def binary(mc): - expect('mesh words match llvm-mc', assemble(mc, (HERE / 'startup_mesh57_skeleton.s').read_text()), MESH) + mesh = (HERE / 'startup_mesh57_skeleton.s').read_text() + expect('mesh words match llvm-mc', assemble(mc, mesh), MESH) + expect('formatted mesh words match llvm-mc', assemble(mc, mesh.replace(COLOUR_LOAD, COLOUR_LOAD + '\n' + FORMAT_LOAD)), + FORMATTED_MESH) + expect('rewritten descriptor words match llvm-mc', + assemble(mc, mesh.replace(COLOUR_LOAD, COLOUR_LOAD + '\ns_mov_b32 s19, 0\n' + FORMAT_LOAD)), REWRITTEN_FORMAT) expect('pixel words match llvm-mc', assemble(mc, PIXEL_ASM), PIXEL) @@ -539,12 +562,57 @@ def draw(dxc, renderer, adapter, publisher=None): return 0 +def draw_formatted(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + words = [a | b << 10 | c << 20 for a, b, c in indices] + data = buffer(points, colours, words) + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, FORMATTED_MESH) + if result != 'ok': + raise AssertionError(result) + name = str(Path(tmp) / ('%016x' % key)) + manifest = Path(name + '.ms57.txt').read_text().splitlines() + uds = {tuple(fields[2:]): int(fields[1]) for fields in map(str.split, manifest) if fields and fields[0] == 'udsrc'} + constants = bytearray(1024) + struct.pack_into('<I', constants, 4 * uds['rootconst', '0', '0'], len(indices)) + struct.pack_into('<I', constants, 4 * uds['rootconst', '0', '1'], len(points)) + # gfx10 descriptor word 3: FORMAT in bits 12..18, DST_SEL_X in bits 0..2. Decode the same + # four bytes at each vertex as either its original float or an individual UNORM8 component. + float_x, unorm_x, unorm_z = (22 << 12) | 4, (56 << 12) | 4, (56 << 12) | 6 + images = {} + for word3, byte in ((float_x, None), (unorm_x, 0), (unorm_z, 2)): + shaded = [(r if byte is None else data[192 + 16 * slot + byte], g, b, a) + for slot, (r, g, b, a) in enumerate(colours)] + images[word3] = rasterise(points, shaded, indices, len(points), len(indices)) + path = Path(tmp) / 'formatted.bin' + args = [renderer, adapter, '--mesh-indexed', name + '.ms57.cso', name + '.ps57.cso', str(path)] + for word3, reference in ((float_x, float_x), (unorm_x, unorm_x), (unorm_z, unorm_z), + (float_x, unorm_x), (unorm_x, unorm_z)): + struct.pack_into('<I', constants, 4 * uds['descword3', '0'], word3) + path.write_bytes(bytes(constants) + data + b'\xcd' * 80 + b''.join(map(bytes, images[reference]))) + mismatches = sum(a != b for a, b in zip(images[word3], images[reference])) + assert (word3 == reference) == (mismatches == 0) + run = subprocess.run(args, capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + if (run.returncode != int(bool(mismatches)) + or not re.search(rf'\bpixels={SIDE * SIDE} mismatches={mismatches}\b', run.stdout)): + raise AssertionError(f'descriptor {word3:#x}, reference {reference:#x}: {run.stdout}{run.stderr}') + print(f'descriptor {word3:#x}, reference {reference:#x}: {mismatches} differing pixels') + return 0 + + def main(argv): status = 0 if argv[1:2] == ['binary'] and len(argv) == 3: binary(argv[2]) elif argv[1:2] == ['draw'] and len(argv) == 5: status = draw(*argv[2:]) + elif argv[1:2] == ['formatted'] and len(argv) == 5: + status = draw_formatted(*argv[2:]) elif argv[1:2] == ['exchange'] and len(argv) == 6: status = draw(*argv[2:]) elif len(argv) == 1: From db5c181c0d0f8f13b1eb78b0968d5ebc1408b733 Mon Sep 17 00:00:00 2001 From: NiiRoZz <simonin.remi25@gmail.com> Date: Wed, 25 Nov 2026 23:10:31 +0100 Subject: [PATCH 198/232] startup: lower v_interp_p2_f16 with op_sel 0x8 (destination high half) in gfx2hlsl (#2422) check_encoding refused every op_sel bit on v_interp_p1ll_f16 / v_interp_p2_f16. op_sel 0x8 (word 0 bit 14) on p2 is Mesa ACO's v_interp_p2_hi_f16: it writes bits 31:16 of the destination and keeps bits 15:0. It is lowered only when the destination holds the low half of a preceding plain p2; every other op_sel pattern, and op_sel on p1ll, stays refused with the pattern in the message. Refs #2413 Refs #711 Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 3 +- AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 2 +- tests/startup_gfx2hlsl_interp_f16_check.py | 3 +- tests/startup_gfx2hlsl_interp_p2_hi_check.py | 191 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 49 +++-- 7 files changed, 236 insertions(+), 16 deletions(-) create mode 100644 tests/startup_gfx2hlsl_interp_p2_hi_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 1837fd411..d2e5e460e 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -111,6 +111,7 @@ jobs: (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_interp_f16_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_interp_p2_hi_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_sgpr_spill_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_mad_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_compute_check.py", "binary", "llvm-mc-15"], {}), @@ -273,7 +274,7 @@ jobs: tests/startup_ps_input_scan_check.py \ tests/startup_build_rev_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ - tests/startup_gfx2hlsl_interp_f16_check.py \ + tests/startup_gfx2hlsl_interp_f16_check.py tests/startup_gfx2hlsl_interp_p2_hi_check.py \ tests/startup_gfx2hlsl_sgpr_spill_check.py \ tests/startup_gfx2hlsl_mad_check.py \ tests/startup_gfx2hlsl_neg_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 6bcd9cd28..d7c8b49ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -166,6 +166,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_table_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_mad_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_neg_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_interp_p2_hi_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1af9d9983..ac338fd77 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3497,6 +3497,9 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter}) set_tests_properties(startup_gfx2hlsl_interp_f16_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_interp_p2_f16 with op_sel 0x8 (destination high half, #2413 item T9): CPU reference and mutations. + add_test(NAME startup_gfx2hlsl_interp_p2_hi_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_interp_p2_hi_check.py") # gfx2hlsl DPP16 pair broadcasts: each of the four quad_perm patterns is drawn over 16 x 16 pixels with a different # word per pixel and compared with a CPU reference (#2125 item C); lane mutations must fail; compiled with DXC ps_6_0. foreach(adapter IN ITEMS warp hardware) diff --git a/docs/experiments.md b/docs/experiments.md index 9275336d7..d1d929e31 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14437,7 +14437,7 @@ lane masks and the discard destination. Run `tests/startup_gfx2hlsl_bit_alu_check.py` translates a source-built pixel stage that applies each operation to four lanes (the VOP1 operations alternate `_e32` and `_e64`) and evaluates the generated text with a small 32-bit HLSL evaluator against a reference written from the ISA description with bit loops, string reversal and integer arithmetic. The grid holds 17,459 inputs for `v_bfe_i32` (every offset and width 0 to 31 for 17 base words, plus offsets and widths above 31), 324 for `v_bcnt_u32_b32` and 81 for each scan. Each lowering also has a mutation that must read a wrong word: no sign extension, a subtracted addend, 0 instead of 0xffffffff for zero, no `31u -`, a negative value scanned unchanged, and no bit reversal. On `origin/main` the check fails with `Unsupported: v_bfe_i32`. `binary <llvm-mc>` reassembles the fixtures (llvm-mc 19 here; the CI job passes llvm-mc 15). The `draw` mode compiles the translated pair with FXC and DXC and draws one pixel per four input sets through `offscreen_check --startup-flat-param`; the inputs travel as flat vertex parameters so the compilers cannot fold them. It also draws the first set of each operation with the mutated lowering and requires the mutated words in the readback. The evaluator and reference results above come from Linux. The draw mode passed at `48d9571d` on Windows 11 build 26300.9974 with DXC 1.8.2502.11 and the Windows SDK 10.0.26100 FXC, with the debug layer on and 0 errors and 0 warnings. It passed on WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003). On each adapter, all 34 draws (17 through FXC `ps_5_1` and 17 through DXC `ps_6_0`) matched the reference words, and all 12 mutated draws read their mutated words. Tests: `startup_gfx2hlsl_bit_alu_controls`, `startup_gfx2hlsl_bit_alu_warp` and `startup_gfx2hlsl_bit_alu_hardware`. [AMD RDNA 2 ISA reference](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) `v_xor3_b32` (`D = S0 ^ S1 ^ S2`, the LLVM 15 and RDNA 2 definition, as in the compute lowering of #1573) joins the same check with 729 grid inputs and three draw sets whose three sources differ in every byte (0x13579bdf, 0x2468ace0, 0xfedcba98 and their rotations); its mutation drops the third operand and reads `src0 ^ src1`. Source modifiers, `clamp`, `op_sel` and a wrong operand count stay refused. `binary` matches the xor3 words with llvm-mc 23; the draw has not run on Windows for it yet. -`tools/startup/gfx2hlsl.py` lowers the gfx1013 binary16 interpolation pair `v_interp_p1ll_f16` / `v_interp_p2_f16` (#1996, item C). The attribute channel holds two binary16 values that the vertex stage exports with `compr`; half `h` of channel `c` is float channel `2 * c + h` of the parameter, and the pair becomes `(vD & 0xffff0000u) | f32tof16(i.paramN.<channel>)`, with the upper half of the destination kept. Only the plain form and `high` are lowered: `clamp`, an output modifier, a source modifier, a `p2` whose third source is not the matching `p1ll` result, and an attribute that the vertex stage does not export are refused. A vertex stage that packs the halves into a plain 32-bit export (no `compr`, e.g. with `v_cvt_pkrtz_f16_f32`) is lowered too, for all four channels: half `h` of channel `c` is `f16tof32(word_c >> 16 * h)`, carried by the extra interpolated outputs `hparamN_lo` and `hparamN_hi` that exist only when the pixel stage reads the attribute this way. An attribute exported both with `compr` and plain, and a read of a channel the plain export leaves `off`, are refused; the compr export still fills only `x` and `y`. `tests/startup_gfx2hlsl_interp_f16_check.py` evaluates the translated text on the CPU against a reference from the ISA layout and fails when the lowering is removed or the `high` bit is inverted; `binary <llvm-mc>` reassembles the fixtures and `draw` is the desktop readback (tests `startup_gfx2hlsl_interp_f16_controls`, `_warp` and `_hardware`). The `op_sel` bits (word 0 bits 11 to 14, each refused on its own) and any read of the upper 16 bits of a `p2` destination stay refused because no source states them for gfx10. Either of two kinds of evidence would lift the refusals: a source that states the gfx10 behaviour of the high 16 bits of the `v_interp_p2_f16` destination and of `op_sel` (kept, cleared or written), or a hardware draw on RDNA that reads back both halves of a `p2` result for each `op_sel` value and compares them with the lowering. +`tools/startup/gfx2hlsl.py` lowers the gfx1013 binary16 interpolation pair `v_interp_p1ll_f16` / `v_interp_p2_f16` (#1996, item C). The attribute channel holds two binary16 values that the vertex stage exports with `compr`; half `h` of channel `c` is float channel `2 * c + h` of the parameter, and the pair becomes `(vD & 0xffff0000u) | f32tof16(i.paramN.<channel>)`, with the upper half of the destination kept. Only the plain form and `high` are lowered: `clamp`, an output modifier, a source modifier, a `p2` whose third source is not the matching `p1ll` result, and an attribute that the vertex stage does not export are refused. A vertex stage that packs the halves into a plain 32-bit export (no `compr`, e.g. with `v_cvt_pkrtz_f16_f32`) is lowered too, for all four channels: half `h` of channel `c` is `f16tof32(word_c >> 16 * h)`, carried by the extra interpolated outputs `hparamN_lo` and `hparamN_hi` that exist only when the pixel stage reads the attribute this way. An attribute exported both with `compr` and plain, and a read of a channel the plain export leaves `off`, are refused; the compr export still fills only `x` and `y`. `tests/startup_gfx2hlsl_interp_f16_check.py` evaluates the translated text on the CPU against a reference from the ISA layout and fails when the lowering is removed or the `high` bit is inverted; `binary <llvm-mc>` reassembles the fixtures and `draw` is the desktop readback (tests `startup_gfx2hlsl_interp_f16_controls`, `_warp` and `_hardware`). `v_interp_p2_f16` with `op_sel` 0x8 (word 0 bit 14; Mesa ACO's `v_interp_p2_hi_f16`) writes bits 31:16 of the destination and keeps bits 15:0: `(vD & 0xffffu) | (f32tof16(...) << 16)`. It is lowered only when the destination holds the low half written by a preceding plain `p2` that no reader has consumed yet; the pair then defines the whole register, which any reader may use. The semantics come from Mesa `aco_assembler.cpp` (the `op_sel` value 0x8 of `v_interp_p2_hi_f16`) and `aco_register_allocation.cpp` (`add_subdword_definition` places a 16-bit `p2` result at byte 2 of a register that holds another 16-bit value, so the instruction must keep the low half); LLVM 15 leaves word 0 bits 14:11 undefined for this instruction (`VOP3Interp_gfx10`) and its assembler rejects `op_sel` here, so the fixture sets the bit on the assembled plain word. `tests/startup_gfx2hlsl_interp_p2_hi_check.py` evaluates the translated text against a reference from that layout and fails when the high half is written as the low half or the low half is cleared (test `startup_gfx2hlsl_interp_p2_hi_controls`). Every other `op_sel` value, `op_sel` on `v_interp_p1ll_f16`, and any read of the upper 16 bits of a plain `p2` destination stay refused. The kept low half rests on the ACO sources, not on an ISA statement or a hardware read-back; a hardware draw on RDNA that reads back both halves would settle it. The startup pixel stage lowers DPP16 quad swaps (#2125 item B): `v_mov_b32_dpp` and the VOP2 forms in the integer and binary32 operation tables with `quad_perm:[1,0,3,2]`, `[2,3,0,1]` or `[3,2,1,0]` and full `row_mask`/`bank_mask` read the source from the neighbouring pixel of the 2x2 quad (X, Y or diagonal), written as `QuadReadAcrossX`, `QuadReadAcrossY` and `QuadReadAcrossDiagonal` (SM 6.0, helper lanes included). The second source of a VOP2 keeps the lane's own register. The form needs a straight-line pixel stage at entry EXEC, proven whole-quad by an earlier `s_wqm_b64 exec, exec` (a partly covered quad has inactive source lanes that the hardware masks and `QuadReadAcross*` does not; a later write to EXEC or a restored older copy drops the proof), and plain VGPR operands. A binary32 source may carry the `neg`/`abs` modifier (`-vN`, `|vN|`, `-|vN|`): the permuted word is read from the neighbour first and the modifier applies to that value (RDNA 2 ISA 12.19, LLVM 15 prints them on the `_dpp` spelling), while integer sources, SGPR sources and every other modifier stay refused. Vertex stages, broadcast and pair selections (items A and C), row shifts, mirrors, DPP8, partial masks and operations without a table entry are refused. `fi:1` (fetch inactive) is accepted under the same whole-quad proof, where no source lane is disabled, and gives the same translation. FXC ps_5_1 has no quad intrinsic, so `translate_to` compiles a pair that uses one with DXC as vs_6_0/ps_6_0 (`X2W_DXC`, then PATH) and refuses it when no DXC exists. `tests/startup_gfx2hlsl_dpp_quad_swap_check.py` builds three pixel programs from the lane rule (OR and move forms, plus `v_min_u32_dpp` of the exchanged and own positions, #2023 item H, whose reference is the integer unsigned minimum and which also rejects a maximum) (the packed position in v0, the neighbour at x^1, y^1 or both, an own-lane control), draws 16 x 16 pixels and compares every word with an integer reference; three wrong exchanges, a missing exchange and (for the minimum) a maximum must read a different image, and a reference with one swap dropped must be rejected. Run `ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_dpp_quad_swap_' -V`. The Python controls run on Linux; the draws need DXC and `offscreen_check` on Windows. `startup_gfx2hlsl_dpp_quad_swap_controls` checks `-v0` and `|v0|` against the emitted `QuadReadAcrossX` text and keeps an integer `-v0` refused; the draw mode also checks all 256 pixels of a binary32 multiply-by-one fixture. Its three channels use NEG, ABS and NEG+ABS on different neighbours, and each dropped modifier produces a mismatch. The binary mode reassembles the modified DPP source words. [Refs #1723](https://github.com/R0Y00/Xbox2Windows/issues/1723) diff --git a/tests/startup_gfx2hlsl_interp_f16_check.py b/tests/startup_gfx2hlsl_interp_f16_check.py index 74b850354..a6944cdfe 100644 --- a/tests/startup_gfx2hlsl_interp_f16_check.py +++ b/tests/startup_gfx2hlsl_interp_f16_check.py @@ -20,7 +20,8 @@ interpreter of exactly the statements the fixture produces. Negative controls: the lowering removed (the pair is refused), the high bit inverted on both instructions (the evaluated words differ from the reference), and every modifier or form the fixture does not cover (refused), -including every op_sel bit (ACO's v_interp_p2_hi_f16 writes the high half of the destination). +including every op_sel bit (ACO's v_interp_p2_hi_f16, op_sel 0x8 on p2, is lowered by startup_gfx2hlsl_interp_p2_hi_check.py; +here it is refused where no plain p2 low half precedes it). Plain export (follow-up of #2052): real programs pack the binary16 halves into a plain 32-bit export, e.g. with v_cvt_pkrtz_f16_f32, and read all four channels. Half h of 32-bit channel c is f16tof32(word_c >> 16 * h) (the low diff --git a/tests/startup_gfx2hlsl_interp_p2_hi_check.py b/tests/startup_gfx2hlsl_interp_p2_hi_check.py new file mode 100644 index 000000000..128c36809 --- /dev/null +++ b/tests/startup_gfx2hlsl_interp_p2_hi_check.py @@ -0,0 +1,191 @@ +"""v_interp_p2_f16 with op_sel 0x8 (destination high half) in tools/startup/gfx2hlsl.py (issue #2413, item T9). + + (no arguments) translation controls and mutations, pure Python + binary <llvm-mc> reassemble the fixture and compare it with the words below + +Semantics (public sources; the notes are in tools/startup/gfx2hlsl.py check_encoding): + Mesa ACO, aco_assembler.cpp (the VINTRP emitter): v_interp_p2_hi_f16 is encoded as v_interp_p2_f16 with + op_sel = 0x8, that is word 0 bit 14. aco_register_allocation.cpp (add_subdword_definition) turns v_interp_p2_f16 + into v_interp_p2_hi_f16 when its 16-bit result is placed at byte 2 of a register, so bytes 0..1 of that register + hold another 16-bit value that the instruction must keep (aco_ir.cpp instr_is_16bit lists both opcodes as + partial-register writes). LLVM 15 (VOPInstructions.td VOP3Interp_gfx10) leaves word 0 bits 14:11 undefined for this + instruction and its assembler rejects op_sel here; VOP3OpSel_gfx10 gives bit 14 the meaning "destination high half" + for the other 16-bit VOP3 operations. + v_interp_p2_f16 vD, vJ, attrN.c, vP1 [high] with op_sel 0x8: vD[31:16] = f16(P1 + J * P20), vD[15:0] unchanged. + +The fixture packs two attribute halves per register: a plain p2 writes the low half, then a p2 with op_sel 0x8 the +high half, and the halves are read back with a shift and v_cvt_f32_f16. LLVM 15 cannot print or accept the op_sel +form, so the words are the assembled plain instructions with word 0 bit 14 set (binary mode checks exactly that). +The reference is written from the layout above with struct 'e' conversions; the translated text is evaluated on the +CPU by a small interpreter of the statements the fixture produces. Controls: the op_sel bit cleared (refused, the readers +see an unwritten half), the statement +writing the low half instead of the high half, and the statement clearing instead of keeping the other half all give +other words; every other op_sel pattern, op_sel on p1ll, an op_sel 0x8 p2 whose destination holds no plain p2 low +half, and a read of a register whose high half was never written are refused. +""" +import re +import struct +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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, root_blob # noqa: E402 +from startup_gfx2hlsl_interp_f16_check import VS_WORDS # noqa: E402 (param0 compr: x = (1.5, -2.0), y = (0.5, 3.0)) + +PS_SOURCE = """\ +s_mov_b32 m0, s2 +v_interp_p1ll_f16 v10, v0, attr0.x +v_interp_p2_f16 v8, v1, attr0.x, v10 +v_interp_p1ll_f16 v11, v0, attr0.y +v_interp_p2_f16 v8, v1, attr0.y, v11 +v_interp_p1ll_f16 v12, v0, attr0.x high +v_interp_p2_f16 v9, v1, attr0.x, v12 high +v_interp_p1ll_f16 v13, v0, attr0.y high +v_interp_p2_f16 v9, v1, attr0.y, v13 high +v_cvt_f32_f16 v4, v8 +v_lshrrev_b32 v5, 16, v8 +v_cvt_f32_f16 v5, v5 +v_cvt_f32_f16 v6, v9 +v_lshrrev_b32 v7, 16, v9 +v_cvt_f32_f16 v7, v7 +exp mrt0 v4, v5, v6, v7 done vm +s_endpgm +""" +HI_P2 = (1, 3) # the v_interp_p2_f16 instructions that carry op_sel 0x8 (the second of each pair) +PS_WORDS = bytes.fromhex( + '0203fcbe0a0042d70000020008005ad700022a040b0042d74000020008405ad740022e040c0042d70001020009005ad7000332040d0042d7400102' + '0009405ad7400336040817087e90100a2c05170a7e09170c7e90120e2c07170e7e0f1800f804050607000081bf') +# What the vertex stage exports (compr): attr0.x = (param.x, param.y), attr0.y = (param.z, param.w). +CHANNELS = {'x': 1.5, 'y': -2.0, 'z': 0.5, 'w': 3.0} + + +def f16_bits(x): + return struct.unpack('<H', struct.pack('<e', x))[0] + + +def f32_bits(x): + return struct.unpack('<I', struct.pack('<f', x))[0] + + +def half_to_f32_bits(h): + return f32_bits(struct.unpack('<e', struct.pack('<H', h))[0]) + + +def reference(): + """The words the pixel stage exports, from the layout above: v8 = (attr0.x low, attr0.y low), + v9 = (attr0.x high, attr0.y high); each export is one half widened to f32.""" + v8 = f16_bits(CHANNELS['x']) | f16_bits(CHANNELS['z']) << 16 + v9 = f16_bits(CHANNELS['y']) | f16_bits(CHANNELS['w']) << 16 + return tuple(half_to_f32_bits(h) for h in (v8 & 0xffff, v8 >> 16, v9 & 0xffff, v9 >> 16)) + + +def evaluate(ps): + """Evaluate the translated pixel text: `vN = expr;` over f32tof16, f16tof32, U and the interpolated param0.""" + regs = {} + env = {'f32tof16': f16_bits, 'U': f32_bits, 'regs': regs, + 'f16tof32': lambda w: struct.unpack('<e', struct.pack('<H', w & 0xffff))[0]} + for line in ps.splitlines(): + m = re.fullmatch(r' (v\d+) = (.*);', line) + if not m: + continue + expr = re.sub(r'i\.param0\.([xyzw])', lambda p: repr(CHANNELS[p.group(1)]), m.group(2)) + expr = re.sub(r'\b(0x[0-9a-f]+)u\b', r'\1', expr) + expr = re.sub(r'\b(v\d+)\b', r'regs.get("\1", 0)', expr) + regs[m.group(1)] = eval(expr, {'__builtins__': {}}, env) & 0xffffffff # interpreter of this fixture only + return tuple(regs['v%d' % n] for n in (4, 5, 6, 7)) + + +def patched(words, name, index, *, set_bits=0, clear_bits=0, drop=False): + """Words with the index-th `name` instruction's word 0 changed (set_bits ORed, clear_bits cleared), or removed.""" + out, pos, seen = bytearray(), 0, 0 + while pos < len(words): + n, got, _, _ = G.D.decode_instruction(words, pos) + chunk = bytearray(words[pos:pos + n]) + if got == name: + if seen == index: + if drop: + chunk = bytearray() + else: + chunk[:4] = struct.pack('<I', struct.unpack('<I', chunk[:4])[0] & ~clear_bits | set_bits) + seen += 1 + out += chunk + pos += n + return bytes(out) + + +def translate(ps_words): + return G.Pipeline(VS_WORDS, ps_words, root_blob()).hlsl_ps() + + +def refused(label, ps_words, needle): + try: + translate(ps_words) + except G.Unsupported as error: + assert needle in str(error), (label, str(error)) + print('refused: %s (%s)' % (label, error)) + return + raise AssertionError('%s was translated' % label) + + +def controls(): + expected = reference() + assert expected == tuple(f32_bits(v) for v in (1.5, 0.5, -2.0, 3.0)), [hex(w) for w in expected] + ps = translate(PS_WORDS) + got = evaluate(ps) + assert got == expected, ('translated words', [hex(w) for w in got], [hex(w) for w in expected]) + print('op_sel 0x8 pair: %s' % ','.join('%08x' % w for w in got)) + + hi_line = ' v8 = (v8 & 0xffffu) | (f32tof16(i.param0.z) << 16);' + assert hi_line in ps.splitlines(), ps + # Negative control 1: the op_sel bit cleared on both (p2 writes the low half again), and a lowering that writes + # the low half instead of the high half. + bit_off = PS_WORDS + for index in HI_P2: + bit_off = patched(bit_off, 'v_interp_p2_f16', index, clear_bits=0x4000) + refused('op_sel cleared on the high-half p2', bit_off, 'upper 16 bits') # the readers see an unwritten half + low_write = ps.replace(hi_line, ' v8 = (v8 & 0xffff0000u) | f32tof16(i.param0.z);') + assert evaluate(low_write) != expected, 'a low-half write is not detected' + # Negative control 2: the lowering clearing the other half instead of keeping it. + assert evaluate(ps.replace(hi_line, ' v8 = (f32tof16(i.param0.z) << 16);')) != expected, 'a clearing write is not detected' + print('negative controls: low-half write and clearing write differ from the reference') + + # Negative control 3: every other op_sel pattern is refused, on p2 and on p1ll (bit 14 alone is the lowered one). + for sel in range(1, 16): + for index in range(4): + if sel == 8 and index in HI_P2: + continue + word = patched(PS_WORDS, 'v_interp_p2_f16', index, clear_bits=0x7800, set_bits=sel << 11) + if sel == 8: # a p2 that is not the second of a pair holds no plain p2 low half in its destination + refused('op_sel 0x8 on p2 #%d' % index, word, 'holds no v_interp_p2_f16 low half') + else: + refused('p2 #%d op_sel 0x%x' % (index, sel), word, 'op_sel 0x%x' % sel) + refused('p1ll op_sel 0x%x' % sel, patched(PS_WORDS, 'v_interp_p1ll_f16', 0, set_bits=sel << 11), + 'op_sel 0x%x' % sel) + # Without its high-half p2, v8 has an undefined upper half and the shift reads it. + refused('read before the high half is written', patched(PS_WORDS, 'v_interp_p2_f16', 1, drop=True), 'upper 16 bits') + print('op_sel controls ok') + + +def check_binary(llvm_mc): + built = assemble(llvm_mc, PS_SOURCE) + for index in HI_P2: + built = patched(built, 'v_interp_p2_f16', index, set_bits=0x4000) + if built != PS_WORDS: + raise AssertionError('pixel fixture: assembled %s, recorded %s' % (built.hex(), PS_WORDS.hex())) + print('fixture words match llvm-mc (word 0 bit 14 set on the assembled plain p2)') + + +def main(): + if len(sys.argv) == 1: + controls() + elif sys.argv[1] == 'binary' and len(sys.argv) == 3: + check_binary(sys.argv[2]) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index f3844a9f7..70f6d4767 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -385,6 +385,9 @@ def stream_interface(vs_container, ps_container): 0x3e22f983) # 1/(2*pi) +INTERP_DST_HIGH = 'op_sel:[0,0,0,1]' + + def check_encoding(code, off, n, name, asm): # These SOP1 forms have an unused field that the disassembler does not print. # Only the ordinary four-byte encodings (no literal or hidden operand) are used @@ -395,11 +398,17 @@ def check_encoding(code, off, n, name, asm): if n != 4 or unused: raise Unsupported('s_setpc_b64: unsupported %s encoding at +0x%x' % (name, off)) if name in ('v_interp_p1ll_f16', 'v_interp_p2_f16'): - # The shared disassembler ignores op_sel (w0[14:11]) here, as LLVM 15 does. Mesa ACO's - # v_interp_p2_hi_f16 is p2 with op_sel bit 3 (w0[14]): it writes the high half of the destination. The - # attribute half `high` is a different bit (w1[8]) and is printed, so it is not refused here. - if struct.unpack_from('<I', code, off)[0] & 0x7800: - raise Unsupported('%s with op_sel: only the plain form and high are lowered' % name) + # The shared disassembler ignores op_sel (w0[14:11]) here, as LLVM 15 does (its VOP3Interp_gfx10 encoding + # leaves bits 14:11 undefined). Only Mesa ACO states a meaning: v_interp_p2_hi_f16 is p2 with op_sel 0x8 (bit + # 14, aco_assembler.cpp), which writes the high half of the destination; register allocation turns p2 into it + # for a 16-bit value at byte 2 of a register that holds another 16-bit value. It is passed on as the printed + # LLVM modifier `op_sel:[0,0,0,1]`. The attribute half `high` is a different bit (w1[8]) and is printed. + sel = struct.unpack_from('<I', code, off)[0] >> 11 & 15 + if sel == 8 and name == 'v_interp_p2_f16': + return asm + ' ' + INTERP_DST_HIGH + if sel: + raise Unsupported('%s with op_sel 0x%x: only the plain form and, on v_interp_p2_f16, op_sel 0x8 ' + '(destination high half) are lowered' % (name, sel)) if name == 'image_load_mip': # The shared disassembler does not expose these gfx10 MIMG flags. word0, word1 = struct.unpack_from('<2I', code, off) @@ -5288,7 +5297,8 @@ def interp_f16(self, op, ops, mods, vsrc, n_ops): f16tof32(word_c >> 16 * h), carried by the extra outputs hparamN_lo (h = 0) and hparamN_hi (h = 1), channel c of each. All four channels exist. """ - extra = [m for m in mods if m != 'high'] + allowed = ('high', INTERP_DST_HIGH) if op == 'v_interp_p2_f16' else ('high',) + extra = [m for m in mods if m not in allowed] if extra: raise Unsupported('%s with %s: only the plain form and high are lowered' % (op, ' '.join(extra))) if len(ops) != n_ops: @@ -5327,9 +5337,10 @@ def interp_f16_scan(self): never written (they still hold the entry barycentrics wherever the pair reads them), (2) v_interp_p1ll_f16, which emits nothing, has no consumer but the v_interp_p2_f16 that follows it in the same straight-line run and nothing reads the destination it leaves stale when p2 writes elsewhere, and (3) nothing reads the - upper 16 bits of the p2 destination: whether gfx10 keeps or clears them is not established by a source + upper 16 bits of a plain p2 destination: whether gfx10 keeps or clears them is not established by a source (LLVM 15 SIInstrInfo/VOP3Instructions.td model the result as f16 only; the encoding states no - high-half behaviour), so only a plain v_cvt_f32_f16 reading the low half may consume it. + high-half behaviour), so only a plain v_cvt_f32_f16 reading the low half may consume it, until a p2 with + op_sel 0x8 writes the high half of that register (Mesa ACO keeps the other half, see check_encoding). """ if self.interp_scanned: return @@ -5397,7 +5408,15 @@ def regs(tok): stale.discard(out) if out != d: stale.add(d) - high_undefined.add(out) + if INTERP_DST_HIGH in mods: + # Completes a 16-bit pair: the low half it keeps must be a plain p2 result still waiting for its + # upper half (no other writer is modelled), after which every reader sees defined halves. + if out not in high_undefined: + raise Unsupported('v_interp_p2_f16 op_sel 0x8 into v%d, which holds no v_interp_p2_f16 low ' + 'half: the half it keeps is not modelled' % out) + high_undefined.discard(out) + else: + high_undefined.add(out) elif low_reader: high_undefined.discard(int(ops[0][1:])) stale.discard(int(ops[0][1:])) @@ -5425,9 +5444,10 @@ def op_v_interp_p1ll_f16(self, ops, mods): self.interp_p1[int(ops[0][1:])] = (attr, field, high) def op_v_interp_p2_f16(self, ops, mods): - # P1 + J * P20, converted to binary16 into the low half of the destination (LLVM: the result is f16, the - # high bit selects the attribute half only). The upper half is not modelled: interp_f16_scan refuses - # every consumer of it, so the preserved half emitted here is never observed. + # P1 + J * P20, converted to binary16 into one half of the destination, the other half kept (LLVM: the + # result is f16, the high bit selects the attribute half only). The plain form writes the low half; with + # op_sel 0x8 (ACO's v_interp_p2_hi_f16) the high half. interp_f16_scan refuses every consumer of a half the + # pair has not written, so a half that is never written is never observed. attr, field, high = self.interp_f16('v_interp_p2_f16', ops, mods, 1, 4) self.interp_f16_pair('v_interp_p2_f16', ops) self.interp_f16_scan() @@ -5435,7 +5455,10 @@ def op_v_interp_p2_f16(self, ops, mods): raise Unsupported('v_interp_p2_f16 source %s is not the v_interp_p1ll_f16 result of %s' % (ops[3], ops[2])) d = reg_range(ops[0])[1] self.used_v.add(d) - self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(i.%s)' % (d, field)) + if INTERP_DST_HIGH in mods: + self.set_v(d, '(v%d & 0xffffu) | (f32tof16(i.%s) << 16)' % (d, field)) + else: + self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(i.%s)' % (d, field)) def note_attr(self, tok, how): m = re.fullmatch(r'attr(\d+)\.([xyzw])', tok) From 5d97a82cd66da13d62fddc58a04cc2bafb4ee7f4 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:10:44 +0200 Subject: [PATCH 199/232] shader: extract main(argv) and add manifest/pipelines schema and LLVM path guards in pso_readiness with CLI suite (#2583) --- CMakeLists.txt | 2 + tests/pso_readiness_cli_check.py | 351 +++++++++++++++++++++++++++++++ tools/pso_readiness.py | 35 ++- 3 files changed, 383 insertions(+), 5 deletions(-) create mode 100644 tests/pso_readiness_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ac338fd77..4904a92fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8729,6 +8729,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/disasm_rdna2_cli_check.py") add_test(NAME pso_readiness_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pso_readiness_check.py") + add_test(NAME shader_pso_readiness_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pso_readiness_cli_check.py") add_test(NAME dxcontainer_part_offsets COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dxcontainer_part_offsets_check.py") add_test(NAME depth_mask_aot_cli COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/pso_readiness_cli_check.py b/tests/pso_readiness_cli_check.py new file mode 100644 index 000000000..4debf5580 --- /dev/null +++ b/tests/pso_readiness_cli_check.py @@ -0,0 +1,351 @@ +"""CLI, schema, path guard, error handling, and mutation suite for tools/pso_readiness.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import types +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "pso_readiness.py" +sys.path.insert(0, str(ROOT / "tools")) + +import pso_readiness # noqa: E402 + +EXPECTED_TOP_KEYS = { + "archive_records", + "records_with_native_sha256", + "unique_native_stage_hashes", + "pipeline_count", + "pipeline_status_counts", + "pipelines", +} + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = pso_readiness.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +def _write_fixture(root: Path): + code = b"synthetic shader bytes" + digest = hashlib.sha256(code).hexdigest() + pixel = {"stage": "pixel", "sha256": digest} + manifest = {"shaders": [{**pixel, "native_file": "pixel.bin"}]} + pipelines = { + "pipelines": [ + {"id": "p0", "effective_root_signature": "present", "shaders": [pixel]}, + ] + } + (root / "pixel.bin").write_bytes(code) + manifest_path = root / "manifest.json" + pipelines_path = root / "pipelines.json" + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + pipelines_path.write_text(json.dumps(pipelines), encoding="utf-8") + return manifest, pipelines, manifest_path, pipelines_path, code, digest + + +class PsoReadinessCliPositiveTests(unittest.TestCase): + def test_cli_json_schema_without_llvm_and_with_llvm_file(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + _, _, manifest_path, pipelines_path, code_bytes, digest = _write_fixture(root) + + code, out, err = _run_main([str(manifest_path), str(pipelines_path)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + doc = json.loads(out) + self.assertEqual(set(doc), EXPECTED_TOP_KEYS) + self.assertEqual(doc["archive_records"], 1) + self.assertEqual(doc["records_with_native_sha256"], 1) + self.assertEqual(doc["unique_native_stage_hashes"], 1) + self.assertEqual(doc["pipeline_count"], 1) + self.assertEqual(doc["pipeline_status_counts"], {"needs_evidence": 1}) + self.assertEqual(doc["pipelines"][0]["status"], "needs_evidence") + self.assertEqual(doc["pipelines"][0]["shaders"]["pixel"]["status"], "pixel_scan_untested") + + proc = _run_subprocess(str(manifest_path), str(pipelines_path)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), doc) + + # With --llvm pointing to an existing regular file, CLI accepts it and passes path string. + llvm_file = root / "fake_llvm.dll" + llvm_file.write_bytes(b"MZ") + seen_calls = [] + + def fake_disassemble(blob, llvm_arg, **kwargs): + seen_calls.append((blob, llvm_arg, kwargs)) + return ["v_mov_b32_e32 v0, v1", "s_endpgm"] + + fake_pixel_aot = types.SimpleNamespace(disassemble=fake_disassemble) + with ( + mock.patch.dict(sys.modules, {"pixel_aot": fake_pixel_aot}), + mock.patch.object(pso_readiness, "assess_pixel", return_value=("pixel_lowering_passed", None)), + ): + code_l, out_l, err_l = _run_main([ + str(manifest_path), str(pipelines_path), "--llvm", str(llvm_file), + ]) + + self.assertIs(type(code_l), int) + self.assertEqual(code_l, 0, err_l) + self.assertEqual(err_l, "") + self.assertEqual(seen_calls, [(code_bytes, str(llvm_file), {})]) + doc_l = json.loads(out_l) + self.assertEqual(doc_l["pipelines"][0]["status"], "needs_pso_validation") + self.assertEqual(doc_l["pipelines"][0]["shaders"]["pixel"]["sha256"], digest) + self.assertEqual( + sorted(p.name for p in root.iterdir()), + ["fake_llvm.dll", "manifest.json", "pipelines.json", "pixel.bin"], + ) + + def test_report_preserves_string_llvm_for_direct_callers(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + manifest, pipelines, _, _, code_bytes, _ = _write_fixture(root) + seen = [] + + def fake_disassemble(blob, llvm_arg, **kwargs): + seen.append((blob, llvm_arg)) + return ["s_endpgm"] + + fake_pixel_aot = types.SimpleNamespace(disassemble=fake_disassemble) + with ( + mock.patch.dict(sys.modules, {"pixel_aot": fake_pixel_aot}), + mock.patch.object(pso_readiness, "assess_pixel", return_value=("pixel_lowering_passed", None)), + ): + doc = pso_readiness.report(manifest, pipelines, root, llvm="test-llvm") + + self.assertEqual(seen, [(code_bytes, "test-llvm")]) + self.assertEqual(doc["pipelines"][0]["status"], "needs_pso_validation") + + def test_main_sys_argv_forwarding_and_script_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + _, _, manifest_path, pipelines_path, _, _ = _write_fixture(root) + cli_argv = [str(TOOL), str(manifest_path), str(pipelines_path)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(json.loads(out)["pipeline_count"], 1) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue())["pipeline_count"], 1) + + +class PsoReadinessCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_code=1, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + if expected_code == 1: + self.assertTrue(err.startswith("PSO report: "), err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + if expected_code == 1: + self.assertTrue(proc.stderr.startswith("PSO report: "), proc.stderr) + + def test_argparse_errors_exit_nonzero_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + _, _, manifest_path, pipelines_path, _, _ = _write_fixture(root) + + for argv, frag in ( + ([], "usage:"), + ([str(manifest_path)], "usage:"), + ([str(manifest_path), str(pipelines_path), "--unknown-flag"], "unrecognized"), + ): + with self.subTest(argv=argv): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + pso_readiness.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_clean_failure(argv, expected_code=2, expected_fragment=frag) + + def test_manifest_and_pipelines_schema_guards_kill_mutations(self): + valid_manifest = {"shaders": []} + valid_pipelines = {"pipelines": []} + + bad_manifests = [ + ([], "manifest"), + ("text", "manifest"), + (42, "manifest"), + ({}, "shaders"), + ({"shaders": {}}, "shaders"), + ({"shaders": "text"}, "shaders"), + ({"shaders": 5}, "shaders"), + ({"shaders": None}, "shaders"), + ({"shaders": [123]}, "manifest shader entries"), + ] + for bad_manifest, frag in bad_manifests: + with self.subTest(bad_manifest=bad_manifest): + with self.assertRaises(ValueError) as raised: + pso_readiness.report(bad_manifest, valid_pipelines, Path(".")) + self.assertIn(frag, str(raised.exception)) + + bad_pipelines = [ + ([], "pipelines"), + ("text", "pipelines"), + (42, "pipelines"), + ({}, "pipelines"), + ({"pipelines": {}}, "pipelines"), + ({"pipelines": "text"}, "pipelines"), + ({"pipelines": 5}, "pipelines"), + ({"pipelines": None}, "pipelines"), + ] + for bad_pipeline, frag in bad_pipelines: + with self.subTest(bad_pipeline=bad_pipeline): + with self.assertRaises(ValueError) as raised: + pso_readiness.report(valid_manifest, bad_pipeline, Path(".")) + self.assertIn(frag, str(raised.exception)) + + with TemporaryDirectory() as tmp: + root = Path(tmp) + manifest_path = root / "manifest.json" + pipelines_path = root / "pipelines.json" + manifest_path.write_text(json.dumps(valid_manifest), encoding="utf-8") + pipelines_path.write_text(json.dumps(valid_pipelines), encoding="utf-8") + + for bad_manifest, frag in bad_manifests: + manifest_path.write_text(json.dumps(bad_manifest), encoding="utf-8") + self._assert_clean_failure( + [str(manifest_path), str(pipelines_path)], + expected_fragment=frag, + check_subprocess=False, + ) + manifest_path.write_text(json.dumps(valid_manifest), encoding="utf-8") + + for bad_pipeline, frag in bad_pipelines: + pipelines_path.write_text(json.dumps(bad_pipeline), encoding="utf-8") + self._assert_clean_failure( + [str(manifest_path), str(pipelines_path)], + expected_fragment=frag, + check_subprocess=False, + ) + + # Corrupt JSON also exits 1 with exact prefix and zero traceback. + pipelines_path.write_text("{corrupt", encoding="utf-8") + self._assert_clean_failure( + [str(manifest_path), str(pipelines_path)], + expected_fragment="Expecting", + ) + + def test_manifest_pipelines_and_llvm_path_guards_kill_mutations(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + _, _, manifest_path, pipelines_path, _, _ = _write_fixture(root) + existing_dir = root / "existing_dir" + existing_dir.mkdir() + missing_file = root / "missing.bin" + + # 1) manifest is an existing directory (including ""). + for bad_manifest in (str(existing_dir), ""): + with mock.patch.object(pso_readiness, "report") as report_mock: + self._assert_clean_failure( + [bad_manifest, str(pipelines_path)], + expected_fragment="existing directory", + check_subprocess=bool(bad_manifest), + ) + report_mock.assert_not_called() + + # 2) pipelines is an existing directory (including ""). + for bad_pipelines in (str(existing_dir), ""): + with mock.patch.object(pso_readiness, "report") as report_mock: + self._assert_clean_failure( + [str(manifest_path), bad_pipelines], + expected_fragment="existing directory", + check_subprocess=bool(bad_pipelines), + ) + report_mock.assert_not_called() + + # 3) --llvm missing or directory rejected upfront before report(). + for bad_llvm, frag in ( + (str(missing_file), "not found"), + (str(existing_dir), "regular file"), + ("", "regular file"), + ): + with mock.patch.object(pso_readiness, "report") as report_mock: + self._assert_clean_failure( + [str(manifest_path), str(pipelines_path), "--llvm", bad_llvm], + expected_fragment=frag, + check_subprocess=bool(bad_llvm), + ) + report_mock.assert_not_called() + + # 4) Missing manifest / pipelines files exit 1 cleanly. + self._assert_clean_failure( + [str(missing_file), str(pipelines_path)], + expected_fragment=missing_file.name, + ) + self._assert_clean_failure( + [str(manifest_path), str(missing_file)], + expected_fragment=missing_file.name, + ) + + def test_os_value_type_and_key_errors_caught_cleanly_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + _, _, manifest_path, pipelines_path, _, _ = _write_fixture(root) + for exc in ( + OSError("simulated io error"), + ValueError("simulated value error"), + TypeError("simulated type error"), + KeyError("simulated_key"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(pso_readiness, "report", side_effect=exc): + self._assert_clean_failure( + [str(manifest_path), str(pipelines_path)], + expected_fragment=str(exc), + check_subprocess=False, + ) + self.assertEqual( + sorted(p.name for p in root.iterdir()), + ["manifest.json", "pipelines.json", "pixel.bin"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/pso_readiness.py b/tools/pso_readiness.py index 51dd24a04..78b02056e 100644 --- a/tools/pso_readiness.py +++ b/tools/pso_readiness.py @@ -93,16 +93,27 @@ def assess_pixel(digest, instructions): def report(manifest, pipelines, root, llvm=None): + if not isinstance(manifest, dict): + raise ValueError("manifest must be a JSON object") + records = manifest.get("shaders") + if not isinstance(records, list): + raise ValueError("manifest 'shaders' must be a list") + if not isinstance(pipelines, dict): + raise ValueError("pipelines must be a JSON object") + pipeline_entries = pipelines.get("pipelines") + if not isinstance(pipeline_entries, list): + raise ValueError("pipelines 'pipelines' must be a list") root = root.resolve() - records = manifest["shaders"] indexed = defaultdict(list) for record in records: + if not isinstance(record, dict): + raise ValueError("manifest shader entries must be JSON objects") if "sha256" in record: indexed[shader_key(record)].append(record) assessments = {} ids = set() rows = [] - for pipeline in pipelines["pipelines"]: + for pipeline in pipeline_entries: if not isinstance(pipeline, dict): raise ValueError("pipeline entries must be JSON objects") identity = pipeline["id"] @@ -158,20 +169,34 @@ def report(manifest, pipelines, root, llvm=None): "pipeline_status_counts": dict(status_counts), "pipelines": rows} -def main(): +def _validate_cli_paths(manifest_path: Path, pipelines_path: Path, llvm: str | None) -> None: + for label, path in (("manifest", manifest_path), ("pipelines", pipelines_path)): + if path.exists() and path.is_dir(): + raise ValueError(f"{label} path is an existing directory: {path}") + if llvm is not None: + llvm_path = Path(llvm) + if not llvm_path.exists(): + raise FileNotFoundError(f"--llvm library not found: {llvm}") + if llvm_path.is_dir() or not llvm_path.is_file(): + raise ValueError(f"--llvm path must be a regular file: {llvm}") + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("manifest", type=Path, help="manifest.json from extract_shaders.py --format native or both") parser.add_argument("pipelines", type=Path, help="JSON metadata with pipeline IDs and stage/digest references") parser.add_argument("--llvm", help="AMDGPU LLVM library for optional pixel and mesh lowering checks and compute ISA recognition") - args = parser.parse_args() + args = parser.parse_args(argv) try: + _validate_cli_paths(args.manifest, args.pipelines, args.llvm) result = report(json.loads(args.manifest.read_text(encoding="utf-8")), json.loads(args.pipelines.read_text(encoding="utf-8")), args.manifest.resolve().parent, args.llvm) except (OSError, ValueError, TypeError, KeyError) as exc: parser.exit(1, f"PSO report: {exc}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 826b7347b08fa688750705205d3b4f12e2491b23 Mon Sep 17 00:00:00 2001 From: Rachel Amber <77208679+Holastor@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:11:29 -0700 Subject: [PATCH 200/232] startup: support interleaved chunked streams in DirectStorage (#1429) DirectStorage submissions with interleaved multi-file requests previously broke chunked stream continuation enrollment: 1. Continuation Chain Interleaving: in following_chunk_ids, queued entries for different files within the same submission now use continue rather than break, allowing interleaved multi-file submissions to preserve their respective continuation chains. 2. Continuation Step and Guards: retains existing stride logic (step = destination_size ? destination_size : 0x10000) and consecutive offset checks (expected = offset + step). Guards delta against UINT32_MAX and offset + step against uint64_t overflow. Any non-matching size or non-consecutive offset on the same file ends continuation enrollment. 3. Clean Cache Helper Extraction: extracted try_serve_cached_continuation to handle lookup and extraction of continuation slices from the stream cache, reporting destination capacity exceeded when destination_size exceeds available. 4. Preserved Failed Read Status: failed disk reads retain their normal read failure status rather than falling back to the stream cache. 5. Tests in tests/startup_stub_consumer.cpp: - Interleaved requests across multiple files in a single queue submission (file 1 piece 0, file 2 standalone, file 1 piece 1 continuation) with full two-file readback verification. - Negative control: an independent same-size request at an accepted stride whose read fails on disk (past physical file EOF) fails cleanly and leaves its destination buffer completely untouched (0xA5). - Same-file break controls for non-matching compressed size, non-consecutive offset, non-compressed requests, and submission boundaries. Refs #1198 --- src/startup_stubs/xcrdapi.cpp | 113 +++++++++------ tests/startup_stub_consumer.cpp | 246 ++++++++++++++++++++++++++++++++ 2 files changed, 318 insertions(+), 41 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index 3dfaf65aa..a6d013a71 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -179,8 +179,8 @@ static bool destination_writable(const void* destination, std::size_t bytes) } // Return the exact queued requests that continue this stream in this submission, in queue order. -// Status entries are skipped, and any unrelated request, submission boundary, or non-matching -// source/offset ends the continuation chain. +// Status entries and requests for unrelated files are skipped. In the same file, any non-matching +// size, non-consecutive offset, or submission boundary ends the continuation chain (Refs #1136, #1144, #1198, #1214). static std::vector<u64> following_chunk_ids(Object* self, u64 current_submission_id, u64 source, u64 offset, unsigned source_size, unsigned destination_size, std::size_t total_size) { @@ -198,17 +198,22 @@ static std::vector<u64> following_chunk_ids(Object* self, u64 current_submission } if (e.type != Entry::request) continue; const u64 e_options = *reinterpret_cast<const u64*>(e.bytes); + const u64 e_source = *reinterpret_cast<const u64*>(e.bytes + 0x20); + // Skip requests for other files (interleaving across unrelated files within one submission). + if (e_source != source) { + continue; + } + // For the same file, requests must strictly be compressed file requests continuing this sequence. if (!(e_options & 1) || (e_options & 0x400000)) { break; } - const u64 e_source = *reinterpret_cast<const u64*>(e.bytes + 0x20); const u64 e_offset = *reinterpret_cast<const u64*>(e.bytes + 0x28); const unsigned e_source_size = *reinterpret_cast<const unsigned*>(e.bytes + 0x30); - if (e_source != source || e_source_size != source_size || e_offset != expected) { + if (e_source_size != source_size || e_offset != expected) { break; } const u64 delta = expected - offset; - if (delta >= total_size) { + if (delta >= total_size || delta > UINT32_MAX) { break; } ids.push_back(e.id); @@ -576,6 +581,53 @@ void log_bcpack_summary() format_counts(blank, sizeof(blank), bcpack_blank)); } +// Try to serve an identified continuation slice of an already-inflated chunked stream from the in-memory cache +// (Refs #1136, #1144, #1198, #1214). Returns true if this request was matched as a continuation slice. +static bool try_serve_cached_continuation(Object* self, u64 source, u64 offset, unsigned source_size, + unsigned destination_size, u64 entry_id, + std::vector<unsigned char>& output, std::size_t& decode_length, + const char*& outcome, StorageFailure& failure, const unsigned char*& data) +{ + if (!self || !self->work) return false; + QueueWork& work = *self->work; + const std::lock_guard guard(work.mutex); + for (auto it = work.cached_streams.begin(); it != work.cached_streams.end(); ++it) { + if (it->source == source && it->compressed_size == source_size && offset > it->base_offset) { + auto pos = std::find(it->continuation_ids.begin(), it->continuation_ids.end(), entry_id); + if (pos != it->continuation_ids.end()) { + const u64 delta = offset - it->base_offset; + const unsigned step = it->chunk_size ? it->chunk_size : 0x10000; + if ((delta % step) == 0 && delta < it->data.size() && delta <= UINT32_MAX) { + const std::size_t available = it->data.size() - static_cast<std::size_t>(delta); + if (destination_size > available) { + outcome = "destination capacity exceeded"; + failure = StorageFailure::destination_capacity; + data = nullptr; + it->continuation_ids.erase(pos); + if (it->continuation_ids.empty()) { + work.cached_streams.erase(it); + } + return true; + } + const std::size_t slice_size = destination_size < available ? destination_size : available; + if (slice_size > 0) { + output.assign(it->data.begin() + delta, it->data.begin() + delta + slice_size); + decode_length = slice_size; + data = output.data(); + outcome = "inflated (slice from stream cache)"; + it->continuation_ids.erase(pos); + if (it->continuation_ids.empty()) { + work.cached_streams.erase(it); + } + return true; + } + } + } + } + } + return false; +} + void execute_request(Object* self, const unsigned char* request, const ULONG_PTR* tokens, u64 entry_id, u64 submission_id) { X2W_ZONE("DirectStorage request"); @@ -607,6 +659,11 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR StorageFailure failure = StorageFailure::other; // the heartbeat's cause, if the request fails std::vector<unsigned char> packed, output; const unsigned char* input = nullptr; + const unsigned char* data = nullptr; + std::size_t decode_length = source_size; + const std::size_t destination_capacity = destination_size; + bool written = false; + if (options & ~known) { outcome = "unknown option bits, not done"; } else if (!destination || !source_size) { @@ -623,10 +680,6 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR failure = read_failure_cause(file_object, offset, source_size); } } - const unsigned char* data = nullptr; - std::size_t decode_length = source_size; - const std::size_t destination_capacity = destination_size; - bool written = false; if (input) { data = input; @@ -665,10 +718,11 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR output.resize(produced); bool cached_chunked = false; // If the stream expanded beyond this request's destination and continuation chunks are queued - // in this submission, scope the cache to those identified continuation requests and serve slice 0 (Refs #1136, #1214). + // in this submission, scope the cache to those identified continuation requests and serve slice 0 (Refs #1136, #1144, #1198, #1214). // BCPack streams are atomic multi-lane rANS payloads; they are not chunk-split continuation streams (Refs #1139). if (!memory_source && !bcpack && produced > destination_size && self && self->work) { - auto continuation_ids = following_chunk_ids(self, submission_id, source, offset, source_size, destination_size, produced); + auto continuation_ids = following_chunk_ids(self, submission_id, source, offset, source_size, + destination_size, produced); if (!continuation_ids.empty()) { QueueWork& work = *self->work; const std::lock_guard guard(work.mutex); @@ -694,37 +748,12 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR // slice of an already-inflated chunked stream on this queue (Refs #1136, #1144, #1214). // A request presenting a zlib header that failed decode (e.g. damaged checksum) is an actual // decode error and must stay distinct from a proven continuation. Memory requests stay strictly on direct decode. - if (!direct_decoded && !decode_error && !memory_source && self && self->work) { + if (!direct_decoded && !decode_error && !memory_source && !bcpack && destination && source_size && self && self->work) { auto* file_object = reinterpret_cast<Object*>(source); - if (file_object && file_object->kind == file && file_object->handle != INVALID_HANDLE_VALUE) { - QueueWork& work = *self->work; - const std::lock_guard guard(work.mutex); - for (auto it = work.cached_streams.begin(); it != work.cached_streams.end(); ++it) { - if (it->source == source && it->compressed_size == source_size && offset > it->base_offset) { - auto pos = std::find(it->continuation_ids.begin(), it->continuation_ids.end(), entry_id); - if (pos != it->continuation_ids.end()) { - const u64 delta = offset - it->base_offset; - const unsigned step = it->chunk_size ? it->chunk_size : 0x10000; - if ((delta % step) == 0 && delta < it->data.size()) { - const std::size_t available = it->data.size() - delta; - // Handle short final destinations in multi-piece streams (Refs #1144) - const std::size_t slice_size = destination_size < available ? destination_size : available; - if (slice_size > 0 && destination_size <= available) { - output.assign(it->data.begin() + delta, it->data.begin() + delta + slice_size); - decode_length = slice_size; - data = output.data(); - outcome = "inflated (slice from stream cache)"; - direct_decoded = true; - it->continuation_ids.erase(pos); - if (it->continuation_ids.empty()) { - work.cached_streams.erase(it); - } - break; - } - } - } - } - } + if (file_object && file_object->kind == file && file_object->handle != INVALID_HANDLE_VALUE && + try_serve_cached_continuation(self, source, offset, source_size, destination_size, entry_id, + output, decode_length, outcome, failure, data)) { + direct_decoded = true; } } @@ -741,6 +770,8 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR } } } + } + if (input) { bool bcpack_decoded = false; if (data && bcpack) { if (bcpack == 7 || bcpack == 1 || bcpack == 4 || bcpack == 5 || bcpack == 3) { diff --git a/tests/startup_stub_consumer.cpp b/tests/startup_stub_consumer.cpp index 0f42a2ae1..3951fa93a 100644 --- a/tests/startup_stub_consumer.cpp +++ b/tests/startup_stub_consumer.cpp @@ -969,6 +969,252 @@ bool dstorage_checks() { } } + // Control: interleaved requests for distinct files in a single submission continue their own streams + // without breaking each other's continuation chains (Refs #1198). + { + const size_t plain1_size = 128 * 1024; + const size_t plain2_size = 64 * 1024; + const auto comp1 = make_fixed_deflate_zlib(0x41, plain1_size); + const auto comp2 = make_fixed_deflate_zlib(0x42, plain2_size); + + wchar_t temp_dir[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp_dir)) return false; + wchar_t temp_file1[MAX_PATH], temp_file2[MAX_PATH]; + if (!GetTempFileNameW(temp_dir, L"x2w", 0, temp_file1)) return false; + if (!GetTempFileNameW(temp_dir, L"x2w", 0, temp_file2)) { + DeleteFileW(temp_file1); + return false; + } + + HANDLE h1 = CreateFileW(temp_file1, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + HANDLE h2 = CreateFileW(temp_file2, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h1 == INVALID_HANDLE_VALUE || h2 == INVALID_HANDLE_VALUE) { + if (h1 != INVALID_HANDLE_VALUE) CloseHandle(h1); + if (h2 != INVALID_HANDLE_VALUE) CloseHandle(h2); + DeleteFileW(temp_file1); + DeleteFileW(temp_file2); + return false; + } + std::vector<unsigned char> file1_bytes(128 * 1024, 0); + std::memcpy(file1_bytes.data(), comp1.data(), comp1.size()); + DWORD written = 0; + WriteFile(h1, file1_bytes.data(), static_cast<DWORD>(file1_bytes.size()), &written, nullptr); + WriteFile(h2, comp2.data(), static_cast<DWORD>(comp2.size()), &written, nullptr); + CloseHandle(h1); + CloseHandle(h2); + + void* file_ptr1 = nullptr; + void* file_ptr2 = nullptr; + if (reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, temp_file1, nullptr, &file_ptr1) != 0 || !file_ptr1 || + reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, temp_file2, nullptr, &file_ptr2) != 0 || !file_ptr2) { + if (file_ptr1) reinterpret_cast<CloseFileFn>(static_cast<Object*>(file_ptr1)->vtable[3])(static_cast<Object*>(file_ptr1)); + DeleteFileW(temp_file1); + DeleteFileW(temp_file2); + return false; + } + auto* file_obj1 = static_cast<Object*>(file_ptr1); + auto* file_obj2 = static_cast<Object*>(file_ptr2); + + void* status_ptr = nullptr; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 3, "InterleavedStatus", nullptr, &status_ptr) != 0 || !status_ptr) { + reinterpret_cast<CloseFileFn>(file_obj1->vtable[3])(file_obj1); + reinterpret_cast<CloseFileFn>(file_obj2->vtable[3])(file_obj2); + DeleteFileW(temp_file1); + DeleteFileW(temp_file2); + return false; + } + auto* status = static_cast<Object*>(status_ptr); + + void* queue_ptr = nullptr; + unsigned char desc[0x20] = {}; + *reinterpret_cast<uint16_t*>(desc + 8) = 16; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, desc, nullptr, &queue_ptr) != 0 || !queue_ptr) { + reinterpret_cast<CloseFileFn>(file_obj1->vtable[3])(file_obj1); + reinterpret_cast<CloseFileFn>(file_obj2->vtable[3])(file_obj2); + DeleteFileW(temp_file1); + DeleteFileW(temp_file2); + return false; + } + auto* queue = static_cast<Object*>(queue_ptr); + + std::vector<unsigned char> dest1_0(64 * 1024, 0); + std::vector<unsigned char> dest2(64 * 1024, 0); + std::vector<unsigned char> dest1_1(64 * 1024, 0); + + unsigned char req1_0[0x48] = {}; + *reinterpret_cast<u64*>(req1_0 + 0x00) = 1; + *reinterpret_cast<void**>(req1_0 + 0x08) = dest1_0.data(); + *reinterpret_cast<unsigned*>(req1_0 + 0x18) = 64 * 1024; + *reinterpret_cast<void**>(req1_0 + 0x20) = file_obj1; + *reinterpret_cast<u64*>(req1_0 + 0x28) = 0; + *reinterpret_cast<unsigned*>(req1_0 + 0x30) = static_cast<unsigned>(comp1.size()); + *reinterpret_cast<unsigned*>(req1_0 + 0x38) = static_cast<unsigned>(plain1_size); + + unsigned char req2[0x48] = {}; + *reinterpret_cast<u64*>(req2 + 0x00) = 1; + *reinterpret_cast<void**>(req2 + 0x08) = dest2.data(); + *reinterpret_cast<unsigned*>(req2 + 0x18) = 64 * 1024; + *reinterpret_cast<void**>(req2 + 0x20) = file_obj2; + *reinterpret_cast<u64*>(req2 + 0x28) = 0; + *reinterpret_cast<unsigned*>(req2 + 0x30) = static_cast<unsigned>(comp2.size()); + *reinterpret_cast<unsigned*>(req2 + 0x38) = static_cast<unsigned>(plain2_size); + + unsigned char req1_1[0x48] = {}; + *reinterpret_cast<u64*>(req1_1 + 0x00) = 1; + *reinterpret_cast<void**>(req1_1 + 0x08) = dest1_1.data(); + *reinterpret_cast<unsigned*>(req1_1 + 0x18) = 64 * 1024; + *reinterpret_cast<void**>(req1_1 + 0x20) = file_obj1; + *reinterpret_cast<u64*>(req1_1 + 0x28) = 64 * 1024; + *reinterpret_cast<unsigned*>(req1_1 + 0x30) = static_cast<unsigned>(comp1.size()); + *reinterpret_cast<unsigned*>(req1_1 + 0x38) = static_cast<unsigned>(plain1_size); + + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, req1_0); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 0); + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, req2); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 1); + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, req1_1); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 2); + reinterpret_cast<SubmitFn>(queue->vtable[6])(queue); + + for (int i = 0; i < 200; ++i) { + if (reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 2)) break; + Sleep(10); + } + if (!reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 0) || + !reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 1) || + !reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 2)) { + reinterpret_cast<CloseFileFn>(file_obj1->vtable[3])(file_obj1); + reinterpret_cast<CloseFileFn>(file_obj2->vtable[3])(file_obj2); + DeleteFileW(temp_file1); + DeleteFileW(temp_file2); + return false; + } + long hr0 = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 0); + long hr1 = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 1); + long hr2 = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 2); + reinterpret_cast<CloseFileFn>(file_obj1->vtable[3])(file_obj1); + reinterpret_cast<CloseFileFn>(file_obj2->vtable[3])(file_obj2); + DeleteFileW(temp_file1); + DeleteFileW(temp_file2); + + if (hr0 != 0 || hr1 != 0 || hr2 != 0) return false; + for (unsigned char b : dest1_0) if (b != 0x41) return false; + for (unsigned char b : dest2) if (b != 0x42) return false; + for (unsigned char b : dest1_1) if (b != 0x41) return false; + } + + + // Control: independent same-size request at an accepted stride whose own read fails (beyond physical file end) + // fails without cache fallback, leaving its destination buffer completely untouched (Refs #1198). + { + const size_t stream_plain_size = 128 * 1024; + const auto comp = make_fixed_deflate_zlib(0x55, stream_plain_size); + + wchar_t temp_dir[MAX_PATH]; + if (!GetTempPathW(MAX_PATH, temp_dir)) return false; + wchar_t temp_file[MAX_PATH]; + if (!GetTempFileNameW(temp_dir, L"x2w", 0, temp_file)) return false; + HANDLE file = CreateFileW(temp_file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + // The file on disk contains ONLY comp.size() bytes (< 1 KiB), so any read at 64 KiB or beyond fails on disk. + WriteFile(file, comp.data(), static_cast<DWORD>(comp.size()), &written, nullptr); + CloseHandle(file); + + void* file_ptr = nullptr; + if (reinterpret_cast<OpenFileFn>(factory->vtable[4])(factory, temp_file, nullptr, &file_ptr) != 0 || !file_ptr) { + DeleteFileW(temp_file); + return false; + } + auto* file_obj = static_cast<Object*>(file_ptr); + + void* status_ptr = nullptr; + if (reinterpret_cast<CreateStatusArrayFn>(factory->vtable[5])(factory, 3, "IndependentRecordsStatus", nullptr, &status_ptr) != 0 || !status_ptr) { + reinterpret_cast<CloseFileFn>(file_obj->vtable[3])(file_obj); + DeleteFileW(temp_file); + return false; + } + auto* status = static_cast<Object*>(status_ptr); + + void* queue_ptr = nullptr; + unsigned char desc[0x20] = {}; + *reinterpret_cast<uint16_t*>(desc + 8) = 16; + if (reinterpret_cast<CreateQueueFn>(factory->vtable[10])(factory, desc, nullptr, &queue_ptr) != 0 || !queue_ptr) { + reinterpret_cast<CloseFileFn>(file_obj->vtable[3])(file_obj); + DeleteFileW(temp_file); + return false; + } + auto* queue = static_cast<Object*>(queue_ptr); + + std::vector<unsigned char> dest0(64 * 1024, 0); + std::vector<unsigned char> dest_stride(64 * 1024, 0xA5); + std::vector<unsigned char> dest_eof(64 * 1024, 0x5A); + + unsigned char req0[0x48] = {}; + *reinterpret_cast<u64*>(req0 + 0x00) = 1; + *reinterpret_cast<void**>(req0 + 0x08) = dest0.data(); + *reinterpret_cast<unsigned*>(req0 + 0x18) = 64 * 1024; + *reinterpret_cast<void**>(req0 + 0x20) = file_obj; + *reinterpret_cast<u64*>(req0 + 0x28) = 0; + *reinterpret_cast<unsigned*>(req0 + 0x30) = static_cast<unsigned>(comp.size()); + *reinterpret_cast<unsigned*>(req0 + 0x38) = static_cast<unsigned>(stream_plain_size); + + // An independent request at exactly the accepted stride (0x10000 = 64 KiB), with identical source_size. + // Even though its geometry matches the stride, its read fails on disk (past file EOF), so it must NOT + // be served from the stream cache. It must report failure and leave dest_stride completely untouched. + unsigned char req_stride[0x48] = {}; + *reinterpret_cast<u64*>(req_stride + 0x00) = 1; + *reinterpret_cast<void**>(req_stride + 0x08) = dest_stride.data(); + *reinterpret_cast<unsigned*>(req_stride + 0x18) = 64 * 1024; + *reinterpret_cast<void**>(req_stride + 0x20) = file_obj; + *reinterpret_cast<u64*>(req_stride + 0x28) = 64 * 1024; + *reinterpret_cast<unsigned*>(req_stride + 0x30) = static_cast<unsigned>(comp.size()); + *reinterpret_cast<unsigned*>(req_stride + 0x38) = static_cast<unsigned>(stream_plain_size); + + // A second request with an aligned gap (0x80000) beyond EOF. + unsigned char req_eof[0x48] = {}; + *reinterpret_cast<u64*>(req_eof + 0x00) = 1; + *reinterpret_cast<void**>(req_eof + 0x08) = dest_eof.data(); + *reinterpret_cast<unsigned*>(req_eof + 0x18) = 64 * 1024; + *reinterpret_cast<void**>(req_eof + 0x20) = file_obj; + *reinterpret_cast<u64*>(req_eof + 0x28) = 0x80000; + *reinterpret_cast<unsigned*>(req_eof + 0x30) = static_cast<unsigned>(comp.size()); + *reinterpret_cast<unsigned*>(req_eof + 0x38) = static_cast<unsigned>(stream_plain_size); + + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, req0); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 0); + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, req_stride); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 1); + reinterpret_cast<EnqueueRequestFn>(queue->vtable[3])(queue, req_eof); + reinterpret_cast<EnqueueStatusFn>(queue->vtable[4])(queue, status, 2); + reinterpret_cast<SubmitFn>(queue->vtable[6])(queue); + + for (int i = 0; i < 200; ++i) { + if (reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 2)) break; + Sleep(10); + } + if (!reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 0) || + !reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 1) || + !reinterpret_cast<IsCompleteFn>(status->vtable[3])(status, 2)) { + reinterpret_cast<CloseFileFn>(file_obj->vtable[3])(file_obj); + DeleteFileW(temp_file); + return false; + } + long hr0 = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 0); + long hr_stride = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 1); + long hr_eof = reinterpret_cast<GetHResultFn>(status->vtable[4])(status, 2); + reinterpret_cast<CloseFileFn>(file_obj->vtable[3])(file_obj); + DeleteFileW(temp_file); + + if (hr0 != 0) return false; + for (unsigned char b : dest0) if (b != 0x55) return false; + + // Both the at-stride failed read and the gap request must report failure and leave destinations untouched. + if (hr_stride == 0 || hr_eof == 0) return false; + for (unsigned char b : dest_stride) if (b != 0xA5) return false; + for (unsigned char b : dest_eof) if (b != 0x5A) return false; + } + // Control: standalone stream with damaged checksum at matching offset fails and leaves destination unchanged (Refs #1214) { const size_t stream_plain_size = 128 * 1024; From adc2fd95164cfe4361d93b79015babb9e464e3cf Mon Sep 17 00:00:00 2001 From: Jess Doit <86271385+Jess-Doit@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:15:18 -0800 Subject: [PATCH 201/232] shader: lower gfx1013 1D float image stores and mip loads (#2056) Full-mask R32G32B32A32_FLOAT image_store into a 1D UAV view and full-mask image_load_mip from a separate 1D SRV, declared with --image-uav-dimension 1d and --image-srv-dimension 1d, lower to RWTexture1D<float4> and Texture1D<float4>.Load(int2(x, mip)). The same-texel UAV load path stays 2D: a plain image_load of another dimension is refused as before. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- .github/workflows/windows.yml | 1 + CMakeLists.txt | 5 + README.md | 2 +- docs/experiments.md | 34 +++- tests/compute_check.cpp | 42 +++-- tests/compute_mimg_float_store_1d.s | 12 ++ tests/compute_mimg_float_store_1d_check.py | 174 +++++++++++++++++++++ tools/compute_store_aot.py | 66 +++++--- 8 files changed, 300 insertions(+), 36 deletions(-) create mode 100644 tests/compute_mimg_float_store_1d.s create mode 100644 tests/compute_mimg_float_store_1d_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index d2e5e460e..4a225bda8 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -72,6 +72,7 @@ jobs: (["tests/compute_mimg_float_store_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_mimg_image_uav_load_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_mimg_float_store_layers_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), + (["tests/compute_mimg_float_store_1d_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_mimg_float_store_d16_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_image_atomics_gfx1013_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), (["tests/compute_gather4_l_check.py", "--binary", "llvm-mc-15", "llvm-objcopy-15", "--llvm", "libLLVM-15.so.1"], {}), diff --git a/CMakeLists.txt b/CMakeLists.txt index 4904a92fa..f91a204d9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9195,6 +9195,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter}) set_tests_properties(compute_store_aot_gfx1013_image_store_layers_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_image_store_layers_${adapter}.txt") + add_test(NAME compute_store_aot_gfx1013_image_store_1d_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/compute_mimg_float_store_1d_check.py" --draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(compute_store_aot_gfx1013_image_store_1d_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/compute_store_aot_gfx1013_image_store_1d_${adapter}.txt") add_test(NAME compute_store_aot_gfx1013_image_store_d16_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/compute_mimg_float_store_d16_check.py" --draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) diff --git a/README.md b/README.md index cfa6e4579..39a74b438 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1013 32-bit buffer atomics | Lower [raw UAV add, unsigned max and compare-swap](docs/experiments.md#gfx1013-32-bit-mubuf-buffer-atomics) and check old-value returns and contended add serialization. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_buffer_atomics_'` | | gfx1030 atomic buffer reductions | Lower [fixed-address MUBUF integer reductions](docs/experiments.md#gfx1030-fixed-address-mubuf-atomic-reductions) and verify the final value under lane contention. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_reduction_'` | | gfx1030 raw vector reads | Lower [indexed `buffer_load_dwordx2/x3/x4`](docs/experiments.md#indexed-gfx1030-raw-vector-reads) and verify channel order, destination/index aliasing and untouched output. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_vector_'` | -| gfx1013 float image stores | Lower [full-mask 2D RGBA32 FLOAT stores and explicit-mip SRV reads](docs/experiments.md#gfx1013-2d-float-image-stores-and-mip-loads) [D16 stores to RGBA16 FLOAT](docs/experiments.md#gfx1013-2d-d16-float-image-stores) and [same-texel UAV loads](docs/experiments.md#gfx1013-same-texel-uav-loads). Compare all three destination mips, including untouched texels. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_(store\|uav_load)_'` | +| gfx1013 float image stores | Lower full-mask RGBA32 FLOAT stores to [1D](docs/experiments.md#gfx1013-1d-float-image-stores-and-mip-loads), [2D](docs/experiments.md#gfx1013-2d-float-image-stores-and-mip-loads), and [2D array and 3D](docs/experiments.md#gfx1013-2d-array-and-3d-float-image-stores) images, [D16 stores to RGBA16 FLOAT](docs/experiments.md#gfx1013-2d-d16-float-image-stores) and [same-texel UAV loads](docs/experiments.md#gfx1013-same-texel-uav-loads). The 1D and 2D fixtures read explicit mips from a separate SRV and compare all three destination mips. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_(store\|uav_load)_'` | | gfx1013 array and 3D image stores | Lower [full-mask RGBA32 FLOAT array and volume stores](docs/experiments.md#gfx1013-2d-array-and-3d-float-image-stores) and compare all slices and mips. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_store_layers_'` | | gfx1013 image atomics | Lower [2D `R32_UINT` `image_atomic_add`, `umax` and `cmpswap`](docs/experiments.md#gfx1013-2d-image-atomics) with the gfx1030 lowering and compare every texel of a three-mip texture, including contended adds. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_image_atomics_'` | | gfx1013 image gathers | Lower [one 2D `image_gather4_l` with a constant sampler and a known integer LOD](docs/experiments.md#gfx1013-2d-explicit-lod-image-gathers) on an RGBA32 FLOAT view. Compare all four taps at three mips and on a view that starts at mip 1. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_gfx1013_gather4_l_'` | diff --git a/docs/experiments.md b/docs/experiments.md index d1d929e31..0951e975e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4381,8 +4381,8 @@ For a raw UAV output, `--image-descriptor` names this SRV. For a typed image output, `--image-srv-descriptor` declares a distinct eight-word SRV descriptor. The caller supplies distinct, non-aliasing desktop resources in that combined case. Wait for descriptors with `lgkmcnt(0)` and the load with `vmcnt(0)`. -The explicit-mip SRV path refuses sample instructions, atomics, A16, D16 and -non-2D dimensions. +The 2D explicit-mip SRV path refuses sample instructions, atomics, A16 and +D16. The source-built fixture loads red and blue from mip 1 into consecutive VGPRs. A full store writes those two words and two distinct constants into 16 unique @@ -4475,6 +4475,36 @@ ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_gfx1013_image_st python3 -B tests/compute_mimg_float_store_layers_check.py --binary llvm-mc-15 llvm-objcopy-15 --llvm libLLVM-15.so.1 ``` +### gfx1013 1D float image stores and mip loads + +For `R32G32B32A32_FLOAT` 1D images, declare `--image-uav-dimension 1d` +for the mip-zero destination and `--image-srv-dimension 1d` with a separate +`--image-srv-descriptor` for the source. The view declarations must match the +instructions. The store binds `RWTexture1D<float4>` at `u0` and uses one +full-width address VGPR for X. The explicit-mip load binds `Texture1D<float4>` +at `t0` and uses two consecutive VGPRs for `Load(int2(x, mip))`. RDNA 2 ISA +§8.2.3, Table 42 specifies these operands, and LLVM 15 assembles both forms. +[AMD RDNA 2 ISA](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content) + +The fixture copies all four channels from source mips 1 and 2, selecting the +mip by lane, into eight distinct texels of destination mip 0. The comparator +checks all 224 words across destination mips of widths 32, 16 and 8, including +192 sentinel words. Forcing source mip 0 changes 32 words. Shifting destination +X by one changes 36. Both 1D operations require DMASK `0xf`. The translation +controls also refuse A16, D16, 1D arrays, `image_store_mip`, plain +`image_load`, 1D atomics, same-descriptor reads, wrong view dimensions and +gfx1030. The fixture uses normal binary32 values and in-bounds coordinates. + +```powershell +cmake --build --preset dev --target offscreen_check -j 2 +ctest --preset dev --no-tests=error -j 1 -R '^compute_store_aot_gfx1013_image_store_1d_(warp|hardware)$' -V +``` + +```bash +python3 -B tests/compute_mimg_float_store_1d_check.py +python3 -B tests/compute_mimg_float_store_1d_check.py --binary llvm-mc-15 llvm-objcopy-15 --llvm libLLVM-15.so.1 +``` + ### gfx1013 2D D16 float image stores Declare `--image-format R16G16B16A16_FLOAT` and `--image-uav-mip 0` diff --git a/tests/compute_check.cpp b/tests/compute_check.cpp index aaddced65..4b6ada2a5 100644 --- a/tests/compute_check.cpp +++ b/tests/compute_check.cpp @@ -42,8 +42,9 @@ constexpr UINT texture_uav_load_flag = 1u << 21; constexpr UINT texture_rgba16_float_flag = 1u << 22; constexpr UINT texture_array_flag = 1u << 31; constexpr UINT texture_volume_flag = texture_array_flag | texture_rgba32_float_flag; -constexpr UINT texture_format_mask = texture_rgba8_flag | texture_atomic_mask | texture_volume_flag | - texture_rgba16_float_flag | texture_uav_load_flag; +constexpr UINT texture_1d_flag = 1u << 23; // The image case uses only scalar X group counts. +constexpr UINT texture_format_mask = texture_1d_flag | texture_rgba8_flag | texture_atomic_mask | + texture_volume_flag | texture_rgba16_float_flag | texture_uav_load_flag; constexpr UINT texture_width = 32, texture_height = 8, texture_channels = 4; constexpr UINT texture_mip_levels = 3, texture_layers = 4; @@ -96,14 +97,18 @@ static ComPtr<ID3D12Resource> upload_texture(ID3D12Device* device, ID3D12Graphic D3D12_UAV_DIMENSION dimension = D3D12_UAV_DIMENSION_TEXTURE2D) { const UINT words_per_texel = texture_words_per_texel(format); - const UINT base_words = texture_width * texture_height * words_per_texel; + const bool one_dimensional = dimension == D3D12_UAV_DIMENSION_TEXTURE1D; + const UINT height = one_dimensional ? 1 : texture_height; + const UINT base_words = texture_width * height * words_per_texel; const UINT mips = texels.size() == base_words ? 1 : texture_mip_levels; D3D12_RESOURCE_DESC desc{}; - desc.Dimension = dimension == D3D12_UAV_DIMENSION_TEXTURE3D - ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Dimension = one_dimensional ? D3D12_RESOURCE_DIMENSION_TEXTURE1D + : dimension == D3D12_UAV_DIMENSION_TEXTURE3D ? D3D12_RESOURCE_DIMENSION_TEXTURE3D + : D3D12_RESOURCE_DIMENSION_TEXTURE2D; desc.Width = texture_width; - desc.Height = texture_height; - desc.DepthOrArraySize = dimension == D3D12_UAV_DIMENSION_TEXTURE2D ? 1 : texture_layers; + desc.Height = height; + desc.DepthOrArraySize = dimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || + dimension == D3D12_UAV_DIMENSION_TEXTURE3D ? texture_layers : 1; desc.SampleDesc.Count = 1; desc.MipLevels = static_cast<UINT16>(mips); desc.Format = format; @@ -177,6 +182,9 @@ static ComPtr<ID3D12DescriptorHeap> bind_tables(ID3D12Device* device, ID3D12Grap if (output_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; image.Texture3D = {output_mip, 0, ~0u}; + } else if (output_desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) { + image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + image.Texture1D.MipSlice = output_mip; } else if (output_desc.DepthOrArraySize > 1) { image.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; image.Texture2DArray = {output_mip, 0, output_desc.DepthOrArraySize, 0}; @@ -559,6 +567,10 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co format = DXGI_FORMAT_R32G32B32A32_FLOAT; required |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; break; + case texture_1d_flag: + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + dimension = D3D12_UAV_DIMENSION_TEXTURE1D; + break; case texture_array_flag: format = DXGI_FORMAT_R32G32B32A32_FLOAT; dimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; @@ -593,23 +605,24 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co break; default: throw std::runtime_error("Invalid compute image store format selector"); } - const bool float_image = selector == texture_rgba32_float_flag; const bool uav_load = selector == texture_uav_load_flag; - const bool layered = dimension != D3D12_UAV_DIMENSION_TEXTURE2D; + const bool one_dimensional = dimension == D3D12_UAV_DIMENSION_TEXTURE1D; + const bool separate_srv = selector == texture_rgba32_float_flag || one_dimensional; + const bool layered = dimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY || dimension == D3D12_UAV_DIMENSION_TEXTURE3D; const bool half_image = selector == texture_rgba16_float_flag; const UINT words_per_texel = texture_words_per_texel(format); - const UINT base_words = texture_width * texture_height * words_per_texel; UINT all_words = 0; for (UINT level = 0; level < texture_mip_levels; ++level) { UINT depth = layered ? texture_layers : 1; if (dimension == D3D12_UAV_DIMENSION_TEXTURE3D) depth >>= level; - all_words += (base_words >> (2 * level)) * depth; + const UINT height = one_dimensional ? 1 : texture_height >> level; + all_words += (texture_width >> level) * height * depth * words_per_texel; } std::vector<UINT> initial(all_words), expected(all_words); source.read(reinterpret_cast<char*>(initial.data()), all_words * sizeof(UINT)); source.read(reinterpret_cast<char*>(expected.data()), all_words * sizeof(UINT)); - std::vector<UINT> input_texels(float_image ? all_words : 0); - if (float_image) source.read(reinterpret_cast<char*>(input_texels.data()), all_words * sizeof(UINT)); + std::vector<UINT> input_texels(separate_srv ? all_words : 0); + if (separate_srv) source.read(reinterpret_cast<char*>(input_texels.data()), all_words * sizeof(UINT)); if (!source || source.peek() != std::char_traits<char>::eof() || !groups || groups > 2 || mip >= texture_mip_levels || (((selector & texture_atomic_mask) || uav_load) && mip != 0)) throw std::runtime_error("Invalid compute image store reference"); @@ -627,6 +640,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co } } const UINT required_shape = dimension == D3D12_UAV_DIMENSION_TEXTURE3D ? D3D12_FORMAT_SUPPORT1_TEXTURE3D + : one_dimensional ? D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_MIP : layered ? D3D12_FORMAT_SUPPORT1_TEXTURE2D : 0; if ((support.Support2 & required) != required || (support.Support1 & required_shape) != required_shape) { std::printf("format=%u dimension=%u required_support1=0x%x required_support2=0x%x support1=0x%x support2=0x%x\n", @@ -649,7 +663,7 @@ bool check_compute_texture_store_file(ID3D12Device* device, const char* path, co auto* list = commands.list.Get(); ComPtr<ID3D12Resource> staging, input_staging, input_image; auto texture = upload_texture(device, list, initial, format, staging, true, dimension); - if (float_image) input_image = upload_texture(device, list, input_texels, format, input_staging); + if (separate_srv) input_image = upload_texture(device, list, input_texels, format, input_staging, false, dimension); auto constants_buffer = make_buffer(device, constants_offset + 4 * alignment, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); fill_upload(constants_buffer.Get()); diff --git a/tests/compute_mimg_float_store_1d.s b/tests/compute_mimg_float_store_1d.s new file mode 100644 index 000000000..e6f027cf2 --- /dev/null +++ b/tests/compute_mimg_float_store_1d.s @@ -0,0 +1,12 @@ +s_mov_b32 s12, s7 +s_mov_b32 s13, 0 +s_load_dwordx8 s[24:31], s[12:13], 0x40 +s_load_dwordx8 s[32:39], s[12:13], 0x60 +v_lshl_add_u32 v8, s10, 2, v0 +v_and_b32_e32 v9, 1, v8 +v_add_nc_u32_e32 v9, 1, v9 +s_waitcnt lgkmcnt(0) +image_load_mip v[14:17], v[8:9], s[32:39] dmask:0xf dim:SQ_RSRC_IMG_1D +s_waitcnt vmcnt(0) +image_store v[14:17], v8, s[24:31] dmask:0xf dim:SQ_RSRC_IMG_1D +s_endpgm diff --git a/tests/compute_mimg_float_store_1d_check.py b/tests/compute_mimg_float_store_1d_check.py new file mode 100644 index 000000000..4e93f63d1 --- /dev/null +++ b/tests/compute_mimg_float_store_1d_check.py @@ -0,0 +1,174 @@ +"""Check gfx1013 1D RGBA32 FLOAT image_store and explicit-mip SRV reads.""" +import argparse +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from compute_store_check import aot, assemble, disassemble, rejects, store_container, variant + +HERE = Path(__file__).resolve().parent +LINES = (HERE / "compute_mimg_float_store_1d.s").read_text(encoding="ascii").splitlines() +GROUP = (4, 1, 1) +GROUPS = 2 +WIDTH = 32 +MIPS = 3 +BINDING = dict(table_reg=7, group_reg=10, image_descriptor=0x40, image_srv_descriptor=0x60, + image_format="R32G32B32A32_FLOAT", image_uav_mip=0, + image_uav_dimension="1d", image_srv_dimension="1d") +LOAD = next(line for line in LINES if line.startswith("image_load_mip")) +STORE = next(line for line in LINES if line.startswith("image_store")) +# Little-endian instruction words assembled by LLVM 15.0.7. +WORDS = bytes.fromhex( + "07038cbe 80038dbe 06060cf4 400000fa 06080cf4 600000fa 080046d7 0a040104" + " 81101236 8112124a 7fc08cbf 000f04f0 080e0800 703f8cbf 000f20f0 080e0600 000081bf" +) +TEXTURE_1D_FLAG = 1 << 23 # tests/compute_check.cpp texture_1d_flag +MIP_ADDRESS = "asint((0x00000001u + (0x00000001u & tid.x)))" +STORE_INDEX = "outputData[tid.x]" + + +def controls(): + source = aot.lower(LINES, GROUP, **BINDING) + assert "Texture1D<float4> imageData : register(t0);" in source, source + assert "RWTexture1D<float4> outputData : register(u0);" in source, source + assert f"asuint(imageData.Load(int2(asint(tid.x), {MIP_ADDRESS})))" in source, source + assert (f"{STORE_INDEX} = " + "asfloat(uint4(image_load_0.x, image_load_0.y, image_load_0.z, image_load_0.w));") in source, source + for instruction, kind in ((STORE, "store"), (LOAD, "load")): + op = instruction.split()[0] + sparse = instruction.replace("v[14:17]", "v[14:15]").replace("dmask:0xf", "dmask:0x5") + d16 = instruction.replace("v[14:17]", "v[14:15]") + " d16" + a16 = instruction.replace(", v[8:9],", ", v8,") + " a16" + address = (", v8,", ", v[8:9],") if kind == "store" else (", v[8:9],", ", v[8:10],") + array = instruction.replace("IMG_1D", "IMG_1D_ARRAY").replace(*address) + for changed, diagnostic in ( + (sparse, f"{op} requires full DMASK 0xf"), + (d16, "Unsupported compute instruction"), + (a16, f"Unsupported image {kind} target: gfx1013 requires full-width"), + (array, "Unsupported compute instruction"), + ): + rejects(diagnostic, aot.lower, variant(LINES, (instruction, changed)), GROUP, **BINDING) + for original, changed, diagnostic in ( + (STORE, STORE.replace(", v8,", ", v[8:9],"), "Unsupported image store target"), + (LOAD, LOAD.replace(", v[8:9],", ", v8,"), "Unsupported image load target"), + (LOAD, LOAD.replace("image_load_mip", "image_load").replace(", v[8:9],", ", v8,"), + "Unsupported image load target: gfx1013 requires full-width"), + (STORE, STORE.replace("image_store", "image_store_mip").replace(", v8,", ", v[8:9],"), + "Unsupported image store target: gfx1013 requires full-width"), + (LOAD, LOAD.replace("s[32:39]", "s[24:31]"), "Unverified image descriptor"), + (STORE, STORE.replace("image_store v[14:17]", "image_atomic_add v14").replace("dmask:0xf", "dmask:0x1"), + "Unsupported compute instruction: image_atomic_add"), + ("s_waitcnt vmcnt(0)", "", "before s_waitcnt vmcnt(0)"), + ): + rejects(diagnostic, aot.lower, variant(LINES, (original, changed)), GROUP, **BINDING) + for binding, diagnostic in ( + ({"image_uav_dimension": "2d"}, "image_store dimension 1d does not match the 2d UAV view"), + ({"image_srv_dimension": "2d"}, "image_load_mip dimension 1d does not match the 2d SRV view"), + ({"image_srv_descriptor": 0x40}, "overlapping image SRV descriptor"), + ({"image_srv_descriptor": None}, "1D image loads require a separate gfx1013 RGBA32 FLOAT SRV binding"), + ({"cpu": "gfx1030"}, "1D image UAVs require a gfx1013 RGBA32 FLOAT store binding"), + ({"cpu": "gfx1030", "image_uav_dimension": "2d"}, + "1D image loads require a separate gfx1013 RGBA32 FLOAT SRV binding"), + ({"image_format": "R32G32B32A32_UINT"}, "1D image UAVs require a gfx1013 RGBA32 FLOAT store binding"), + ): + rejects(diagnostic, aot.lower, LINES, GROUP, **(BINDING | binding)) + print("1D translation controls passed", flush=True) + return source + + +def binary(directory, assembler, objcopy, library, source): + code = assemble(directory, assembler, objcopy, LINES) + assert code == WORDS, f"assembled {code.hex()} != recorded {WORDS.hex()}" + print("1D gfx1013 machine words match llvm-mc", flush=True) + if not library: + return + decoded = aot.labelled(disassemble(code, library, offsets=True, cpu=b"gfx1013")) + assert [line for line in decoded if line.startswith("image_")] == [LOAD, STORE] + assert aot.lower(decoded, GROUP, **BINDING) == source + container, output = directory / "image-1d.dxbc", directory / "cli.hlsl" + container.write_bytes(store_container(code, GROUP)) + options = [arg for key, value in BINDING.items() for arg in ("--" + key.replace("_", "-"), str(value))] + subprocess.run([sys.executable, "-B", aot.__file__, container, "--output", output, "--llvm", library, + *options], check=True) + assert output.read_text() == source + + +def input_word(mip, x, channel): + return 0x3f000000 + mip * 0x100000 + x * 0x20 + channel * 2 + + +def reference(): + initial, expected, texels = [], [], [] + for mip in range(MIPS): + for x in range(WIDTH >> mip): + words = [input_word(mip, x, channel) for channel in range(4)] + sentinels = [word | 0x80000000 for word in words] + texels.extend(words) + initial.extend(sentinels) + # Each invocation reads from one of two source mips and writes a unique destination. + if mip == 0 and x < GROUP[0] * GROUPS: + expected.extend(input_word(1 + x % 2, x, channel) for channel in range(4)) + else: + expected.extend(sentinels) + assert sum(a != b for a, b in zip(initial, expected, strict=True)) == 32 + return initial + expected + texels + + +def draw(directory, compiler, renderer, adapter, source): + hlsl, cso, case = (directory / f"image-1d.{ext}" for ext in ("hlsl", "cso", "case")) + payload = reference() + case.write_bytes(struct.pack(f"<2I{len(payload)}I", GROUPS | TEXTURE_1D_FLAG, 0, *payload)) + cases = ( + ("translated", source, 0, None), + ("force source mip zero", source.replace(MIP_ADDRESS, "0"), + 32, "mip=0 word=0 expected=3f100000 actual=3f000000"), + ("shift destination X", source.replace(STORE_INDEX, "outputData[tid.x + 1u]"), + 36, "mip=0 word=0 expected=3f100000 actual=bf000000"), + ) + if record := os.environ.get("FORM_COVERAGE_RECORD"): + path = Path(record) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("image_load_mip\nimage_store\n", encoding="ascii") + for name, code, mismatches, first_mismatch in cases: + assert (code == source) == (mismatches == 0), name + hlsl.write_text(code, encoding="ascii") + subprocess.run([compiler, "-T", "cs_6_0", "-E", "main", "-Fo", cso, hlsl], check=True) + result = subprocess.run([renderer, adapter, "--compute-texture-store-case", cso, case], + capture_output=True, text=True, timeout=15) + print(f"{name}:\n{result.stdout}{result.stderr}", end="", flush=True) + if result.returncode == 77: + return 77 + if "debug_layer=enabled" in result.stdout: + assert "debug_errors=0 debug_warnings=0" in result.stdout, name + assert f"compared_words=224 mismatches={mismatches}" in result.stdout, name + assert result.returncode == int(mismatches != 0), name + if first_mismatch: + assert first_mismatch in result.stderr, name + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--binary", nargs=2, metavar=("LLVM_MC", "LLVM_OBJCOPY")) + modes.add_argument("--draw", nargs=3, metavar=("DXC", "RENDERER", "ADAPTER")) + parser.add_argument("--llvm", metavar="LIBLLVM", help="Also check disassembly and the container CLI") + args = parser.parse_args() + source = controls() + if not (args.binary or args.draw): + return 0 + out = HERE.parent / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(prefix="compute_mimg_1d_", dir=out) as tmp: + directory = Path(tmp) + if args.binary: + binary(directory, *args.binary, args.llvm, source) + return 0 + return draw(directory, *args.draw, source) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/compute_store_aot.py b/tools/compute_store_aot.py index ed5140888..a76f40afd 100644 --- a/tools/compute_store_aot.py +++ b/tools/compute_store_aot.py @@ -205,7 +205,8 @@ # Value: (HLSL texel type, channel count). IMAGE_FORMATS = {"R32G32B32A32_UINT": ("uint4", 4), "R8G8B8A8_UINT": ("uint4", 4)} RGBA32_FLOAT = "R32G32B32A32_FLOAT" -IMAGE_UAV_TYPES = {"2d": "RWTexture2D", "2d-array": "RWTexture2DArray", "3d": "RWTexture3D"} +IMAGE_UAV_TYPES = {"1d": "RWTexture1D", "2d": "RWTexture2D", "2d-array": "RWTexture2DArray", "3d": "RWTexture3D"} +FLOAT_IMAGE_SRV_TYPES = {"1d": "Texture1D<float4>", "2d": "Texture2D<float4>"} RGBA16_FLOAT = "R16G16B16A16_FLOAT" # image_gather4_l on the gfx1013 RGBA32 FLOAT SRV, with the sampler profile of pixel_aot.check_gather_sampler # (normalized coordinates, clamp to the last texel, point mip, no LOD bias). RDNA 2 MIMG gathers return one DMASK @@ -784,7 +785,7 @@ def heap_store_view_hlsl(table_offset, view_count, output_bytes, *, components=4 def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=None, stride=None, - image_uav_dimension="2d", + image_uav_dimension="2d", image_srv_dimension="2d", image_srv_descriptor=None, constant_descriptor=None, group_reg_y=None, group_reg_z=None, source_descriptor=None, source_stride=None, source_format=None, output_format=None, image_descriptor=None, image_format=None, image_uav_mip=None, image_float_domain=None, buffer_float_domain=None, cpu="gfx1013", lds_bytes=0, @@ -816,6 +817,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N both are used, image_srv_descriptor supplies the separate t0 descriptor. One full-mask plain image_load can read the same mip-zero UAV texel its lane will write. This path requires a dispatch with one Z group. + image_srv_dimension declares that view for a full-mask 1D mip load. A full-mask 2D D16 image_store requires an RGBA16 FLOAT UAV. mubuf_d16_xyz_mode opts into a caller-verified W-preserving RGBA16 store. wave_size is the caller's statement that the program runs as wave32 (32). A lane index is only @@ -823,8 +825,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N image_descriptor is the table byte offset of the 8-dword image descriptor. image_format is the caller's statement of the image format inside it. The image binds to t0 for loads or u0 for writes, where image_uav_mip selects the writable subresource and replaces descriptor_offset. - image_uav_dimension declares the view for a store. Array and volume - stores require three address VGPRs and are available for gfx1013 RGBA32 FLOAT. + image_uav_dimension declares the view for a store. The 1D, array and volume + stores are available for gfx1013 RGBA32 FLOAT. R32_UINT selects the 4-sample Texture2DMS profile for an SRV or the non-returning 2D integer atomic profile for a UAV. R32_SINT is UAV-only and selects signed min/max. R32_FLOAT declares a native atomic image carried as raw words @@ -869,7 +871,13 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if image_uav_dimension not in IMAGE_UAV_TYPES: raise ValueError("Unknown image UAV dimension") if image_uav_dimension != "2d" and not (image_output and rgba32_float_image): + if image_uav_dimension == "1d": + raise ValueError("1D image UAVs require a gfx1013 RGBA32 FLOAT store binding") raise ValueError("Array and 3D image UAVs require a gfx1013 RGBA32 FLOAT store binding") + if image_srv_dimension not in FLOAT_IMAGE_SRV_TYPES: + raise ValueError("Unknown image SRV dimension") + if image_srv_dimension == "1d" and not (rgba32_float_image and image_srv_descriptor is not None): + raise ValueError("1D image loads require a separate gfx1013 RGBA32 FLOAT SRV binding") # gfx1013 takes the shared image atomic lowering on an R32_UINT UAV only (add, umax, cmpswap; see lower()). gfx1013_image_atomic = cpu == "gfx1013" and image_atomic_type is not None and image_format == "R32_UINT" if image_output: @@ -2586,24 +2594,31 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N elif m := re.fullmatch(r"image_(?P<kind>load|store|get_resinfo)(?P<mip>_mip)?(?P<packed>_pck(?:_sgn)?)? " r"(?P<data>v\d+|v\[\d+:\d+\]), (?P<addr>v\d+|v\[\d+:\d+\]), " r"s\[(?P<base>\d+):(?P<high>\d+)\] dmask:0x(?P<mask>[0-9a-f]+) " - r"dim:SQ_RSRC_IMG_(?P<dimension>2D_ARRAY|2D|3D)(?: unorm)?(?P<a16> a16)?(?P<d16> d16)?", line): + r"dim:SQ_RSRC_IMG_(?P<dimension>1D|2D_ARRAY|2D|3D)(?: unorm)?(?P<a16> a16)?(?P<d16> d16)?", line): # A16 packs x/y into one dword and takes the mip from the low half of the next dword. mip, a16 = bool(m["mip"]), bool(m["a16"]) d16 = bool(m["d16"]) write = m["kind"] == "store" resinfo = m["kind"] == "get_resinfo" dimension = m["dimension"].lower().replace("_", "-") - layered = dimension != "2d" - if m["d16"] and layered: - # D16 stores are 2D only; refuse array and volume forms as an unmatched instruction. + one_dimensional = dimension == "1d" + layered = dimension in ("2d-array", "3d") + if m["d16"] and dimension != "2d": + # D16 stores are 2D only; refuse other dimensions as an unmatched instruction. raise ValueError(f"Unsupported compute instruction: {line}") - if write and dimension != image_uav_dimension: - raise ValueError(f"Unsupported compute instruction: image_store dimension {dimension} " - f"does not match the {image_uav_dimension} UAV view") - if layered and (not write or not rgba32_float_image or a16 or mip or m["packed"]): + if layered and not write: + raise ValueError(f"Unsupported compute instruction: {line}") + view_dimension = image_uav_dimension if write else image_srv_dimension + if dimension != view_dimension: + view = "UAV" if write else "SRV" + raise ValueError(f"Unsupported compute instruction: image_{m['kind']}{'_mip' if mip else ''} " + f"dimension {dimension} does not match the {view_dimension} {view} view") + if layered and (not rgba32_float_image or a16 or mip or m["packed"]): raise ValueError(f"Unsupported compute instruction: {line}") vaddr = [int(n) for n in re.findall(r"\d+", m["addr"])] - address_words = 1 if resinfo else (1 if a16 else 2) + int(mip) + int(layered) + # RDNA 2 ISA §8.2.3, Table 42 and LLVM 15 agree: full-width 1D stores take + # one address VGPR (X), and 1D mip loads take two (X, then mip). + address_words = 1 if resinfo else (1 if a16 or one_dimensional else 2) + int(mip) + int(layered) base, high = int(m["base"]), int(m["high"]) dmask = int(m["mask"], 16) # DMASK selects components in XYZW order and packs them into consecutive VGPRs. @@ -2611,7 +2626,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N data_words = 2 if d16 else len(channels) data = [int(n) for n in re.findall(r"\d+", m["data"])] first, last = data[0], data[-1] - uav_load = rgba32_float_image and image_output and m["kind"] == "load" and not mip + uav_load = rgba32_float_image and image_output and m["kind"] == "load" and not mip and dimension == "2d" if d16: if not write or a16 or mip or m["packed"]: raise ValueError("Unsupported compute instruction: D16 requires a 2D image_store " @@ -2639,9 +2654,11 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N elif cpu == "gfx1013" and (not rgba32_float_image or a16 or m["packed"] or (m["kind"], mip) not in (("store", False), ("load", True))): raise ValueError(f"Unsupported image {m['kind']} target: " - "gfx1013 requires full-width RGBA32 FLOAT image_store or 2D image_load_mip") + "gfx1013 requires full-width RGBA32 FLOAT image_store or image_load_mip") if rgba32_float_image and write and dmask != 0xf: raise ValueError("gfx1013 RGBA32 FLOAT image_store requires full DMASK 0xf") + if one_dimensional and not write and dmask != 0xf: + raise ValueError("gfx1013 RGBA32 FLOAT 1D image_load_mip requires full DMASK 0xf") separate_srv = not write and not uav_load and image_srv_descriptor is not None if rgba32_float_image and image_output and m["kind"] == "load" and mip and not separate_srv: raise ValueError("Unsupported image load target: image_load_mip requires a separate SRV") @@ -2671,6 +2688,8 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if a16: packed = hlsl_word(coordinates[0]) x, y = f"{packed} & 0xffffu", f"{packed} >> 16u" + elif one_dimensional: + x = hlsl_word(coordinates[0]) else: x, y = map(hlsl_word, coordinates[:2]) if write: @@ -2702,8 +2721,12 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N selected = dict(zip(channels, words)) texel = ", ".join(selected.get(channel, "0u") for channel in "xyzw") value = f"uint4({texel})" - address = (f"uint3({x}, {y}, {hlsl_word(coordinates[2])})" if layered - else f"uint2({x}, {y})") + if one_dimensional: + address = x + elif layered: + address = f"uint3({x}, {y}, {hlsl_word(coordinates[2])})" + else: + address = f"uint2({x}, {y})" stores.append(f" outputData[{address}] = {value};") continue if resinfo: @@ -2723,7 +2746,9 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if mip: mip_word = hlsl_word(coordinates[-1]) lod = f"asint({mip_word}{' & 0xffffu' if a16 else ''})" - load = f"imageData.Load(int3(asint({x}), asint({y}), {lod}))" + address = (f"int2(asint({x}), {lod})" if one_dimensional + else f"int3(asint({x}), asint({y}), {lod})") + load = f"imageData.Load({address})" if rgba32_float_image: staged_steps.append((None, f" uint4 {name} = asuint({load});")) else: @@ -3071,7 +3096,7 @@ def lower(instructions, group, *, table_reg, descriptor_offset=None, group_reg=N if source_descriptor is not None: cbuffer += "ByteAddressBuffer inputData : register(t0);\n" if image_srv_descriptor is not None or (image_descriptor is not None and not image_output): - texture_type = ("Texture2DMS<uint, 4>" if image_msaa else "Texture2D<float4>" if rgba32_float_image + texture_type = ("Texture2DMS<uint, 4>" if image_msaa else FLOAT_IMAGE_SRV_TYPES[image_srv_dimension] if rgba32_float_image else f"Texture2D<{IMAGE_FORMATS[image_format][0]}>") cbuffer += f"{texture_type} imageData : register(t0);\n" local = "" @@ -3157,6 +3182,8 @@ def main(): help="Bind the image to u0 at this mip instead of binding a raw output descriptor") parser.add_argument("--image-uav-dimension", choices=IMAGE_UAV_TYPES, default="2d", help="Declare the u0 view dimension for an image store") + parser.add_argument("--image-srv-dimension", choices=FLOAT_IMAGE_SRV_TYPES, default="2d", + help="Declare the t0 view dimension for a gfx1013 RGBA32 FLOAT mip load") parser.add_argument("--image-srv-descriptor", type=lambda n: int(n, 0), help="Separate image descriptor at t0 when u0 is a gfx1013 RGBA32 FLOAT image") parser.add_argument("--image-format", choices=sorted(IMAGE_FORMATS.keys() | IMAGE_ATOMIC_TYPES.keys() @@ -3197,6 +3224,7 @@ def main(): cpu=args.cpu, lds_bytes=args.lds_bytes, lds_f32_mode=args.lds_f32_mode, lds_f64_mode=args.lds_f64_mode, mubuf_d16_xyz_mode=args.mubuf_d16_xyz_mode, image_srv_descriptor=args.image_srv_descriptor, + image_srv_dimension=args.image_srv_dimension, descriptor_format_constant=args.descriptor_format_constant, rsrc2=args.rsrc2, wave_size=args.wave_size, load_format_constant=args.load_format_constant, heap_view=tuple(args.heap_view) if args.heap_view else None, heap_store_view=args.heap_store_view, From af1720249e7a28ca75cf15550e5daf4259d8871f Mon Sep 17 00:00:00 2001 From: KomaGuy <thedaghan@gmail.com> Date: Thu, 26 Nov 2026 01:18:23 +0300 Subject: [PATCH 202/232] pixel_aot: lower 25 exact binary16 min, max, fract, and frexp forms (#2578) Co-authored-by: KomaGuy <265821007+KomaGuy@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 17 ++ tests/form_coverage_check.py | 47 ++++++ tests/pixel_aot_check.py | 280 +++++++++++++++++++++++++++++-- tests/rdna2_tools_check.py | 2 +- tools/pixel_aot.py | 311 +++++++++++++++++++++++++++++++++++ 6 files changed, 643 insertions(+), 19 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index f91a204d9..df59aa9c7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9401,6 +9401,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter}) set_tests_properties(pixel_aot_sdwa_int_extra_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_int_extra_${adapter}.txt") + add_test(NAME pixel_aot_f16_exact_extra_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-exact-extra "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(pixel_aot_f16_exact_extra_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_exact_extra_${adapter}.txt") add_test(NAME pixel_aot_dpp_extra_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-dpp-extra "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 0951e975e..9a41a0761 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15699,3 +15699,20 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_int_extra_warp|pixel_ao ``` Linux controls, `form_coverage_check.check_sdwa_int_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. + +## Exact binary16 min, max, fract, and frexp forms (VOP1/VOP2/VOP3/DPP16/DPP8/SDWA) in pixel_aot + +[The pixel shader translator](../tools/pixel_aot.py) adds 25 exact binary16 forms across all 5 encodings (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): + +- `v_min_f16`, `v_max_f16` (`VOP2`, `VOP3` `_e64`, `DPP16`, `DPP8`, `SDWA` — 10 forms) +- `v_fract_f16` (`VOP1`, `VOP3` `_e64`, `DPP16`, `DPP8`, `SDWA` — 5 forms) +- `v_frexp_mant_f16`, `v_frexp_exp_i16_f16` (`VOP1`, `VOP3` `_e64`, `DPP16`, `DPP8`, `SDWA` — 10 forms) + +All 25 require explicit `half_denorm="preserve"`, refuse `HALF_RTZ`, and enforce the static finite-proof contract. `v_min_f16`/`v_max_f16` compare finite 16-bit bit patterns directly in integer order (`f16_min_bits`/`f16_max_bits`) and refuse opposite-signed zeros (`+0.0` vs `-0.0`). `v_fract_f16` lowers `widen16(x) - floor(widen16(x))` through `narrow16` and refuses tiny negative inputs (`-2^-11 < x < 0`, `0x8001..0x93ff`) where `1 + x` is not representable on the binary16 grid. `v_frexp_mant_f16` (`("half16", alu)`) and `v_frexp_exp_i16_f16` (`("low16", alu)`) decompose finite binary16 operands in pure 16-bit integer arithmetic (`frexp_mant_f16`/`frexp_exp_i16_f16`), preserving subnormals under `-denorm ftz`. + +```powershell +python3 tests/pixel_aot_check.py +ctest --preset dev --no-tests=error -R '^(pixel_aot_f16_exact_extra_warp|pixel_aot_f16_exact_extra_hardware|pixel_aot_binary)$' -V +``` + +Linux controls, `form_coverage_check.check_f16_exact_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 6edf044ac..07d634cbf 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -1570,6 +1570,52 @@ def check_sdwa_int_extra_forms(): pixel.ACCEPTED.update(saved) +def check_f16_exact_extra_forms(): + """The 25 exact binary16 min, max, fract, frexp_mant, and frexp_exp_i16 forms (VOP1/VOP2, VOP3, + DPP16, DPP8, SDWA) count as covered once the translator accepts their fixtures.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + forms = { + ("VOP2", "v_min_f16"), ("VOP2", "v_max_f16"), + ("VOP1", "v_fract_f16"), ("VOP1", "v_frexp_mant_f16"), ("VOP1", "v_frexp_exp_i16_f16"), + ("VOP3", "v_min_f16_e64"), ("VOP3", "v_max_f16_e64"), + ("VOP3", "v_fract_f16_e64"), ("VOP3", "v_frexp_mant_f16_e64"), ("VOP3", "v_frexp_exp_i16_f16_e64"), + *{ + (group, f"{op}_dpp") + for group in ("DPP16", "DPP8") + for op in ("v_min_f16", "v_max_f16", "v_fract_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16") + }, + *{ + ("SDWA", f"{op}_sdwa") + for op in ("v_min_f16", "v_max_f16", "v_fract_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16") + }, + } + assert len(forms) == 25 + neighbours = { + ("VOP1", "v_rcp_f16"), ("VOP3", "v_rcp_f16_e64"), + ("DPP16", "v_rcp_f16_dpp"), ("DPP8", "v_rcp_f16_dpp"), ("SDWA", "v_rcp_f16_sdwa"), + ("DPP16", "v_cvt_norm_i16_f16_dpp"), ("DPP8", "v_cvt_norm_i16_f16_dpp"), + ("SDWA", "v_cvt_norm_i16_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not (neighbours & covered), (name, sorted(neighbours & covered)) + stripped = pixel.ACCEPTED - {"v_frexp_mant_f16_dpp"} + assert not {("DPP16", "v_frexp_mant_f16_dpp"), ("DPP8", "v_frexp_mant_f16_dpp")} & fc.gfx_forms( + stripped, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + if __name__ == "__main__": check_denominators() check_example() @@ -1594,6 +1640,7 @@ def check_sdwa_int_extra_forms(): check_dpp_f16_cvt_fmac_ldexp_forms() check_sdwa_f16_forms() check_sdwa_int_extra_forms() + check_f16_exact_extra_forms() check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 484c35134..932f31f93 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -7690,7 +7690,7 @@ def refuse(line, message): for line in ("v_add_nc_u16 v24, v18, v19 op_sel:[0,0,1]", "v_add_nc_u16 v24, v18, v19 clamp", "v_add_nc_u16_dpp v24, v18, v19 quad_perm:[0,1,2,3]", "v_add_nc_u16_sdwa v24, v18, v19 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - "v_min_f16_e64 v24, v18, v19"): + "v_rcp_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") refuse("v_add_nc_u16 v24, v18, -v19", "Unsupported 16-bit integer operand") refuse("v_add_nc_u16 v24, v18, 1.0", "Unsupported 16-bit integer operand") @@ -10463,11 +10463,11 @@ def check_dpp_f16_contract_controls(): (f"v_cvt_f16_f32_dpp v256, v20 {identity}", "Invalid f16 DPP operation"), (f"v_cvt_norm_i16_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_rcp_f16_dpp v23, v20 {identity}", "Unsupported instruction"), - (f"v_min_f16_dpp v23, v20, v20 {identity}", "Unsupported instruction"), - (f"v_max_f16_dpp v23, v20, v20 {identity}", "Unsupported instruction"), + (f"v_exp_f16_dpp v23, v20 {identity}", "Unsupported instruction"), + (f"v_log_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_sin_f16_dpp v23, v20 {identity}", "Unsupported instruction"), (f"v_cos_f16_dpp v23, v20 {identity}", "Unsupported instruction"), - (f"v_fract_f16_dpp v23, v20 {identity}", "Unsupported instruction"), + (f"v_sqrt_f16_dpp v23, v20 {identity}", "Unsupported instruction"), ): expect_value_error(translate_f16, uncompressed_export(["v_mov_b32_e32 v20, s44", bad]), message) # Positive and negative controls for binary16 arithmetic & rounding DPP16/DPP8. @@ -11017,9 +11017,9 @@ def check_sdwa_f16_controls(): (proven_pair, f"v_floor_f16_sdwa v24, v20 mul:2 {sdwa1}WORD_0", "Unsupported binary16 SDWA operands"), (proven_pair, f"v_cvt_f16_f32_sdwa v24, v20 clamp {sdwa1}DWORD", "Unsupported binary16 SDWA operands"), (proven_pair, f"v_add_f16_sdwa v256, v20, v21 {sdwa2}", "Invalid binary16 SDWA operation"), - (proven_pair, f"v_min_f16_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), - (proven_pair, f"v_max_f16_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), - (proven_pair, f"v_fract_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_exp_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_log_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), + (proven_pair, f"v_sqrt_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_rcp_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_cvt_norm_i16_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_cvt_pkrtz_f16_f32_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), @@ -11349,6 +11349,247 @@ def check_sdwa_int_extra_draw(directory, compiler, renderer, backend): return 0 +# Exact binary16 min, max, fract, frexp_mant, and frexp_exp_i16 fixtures covering 25 forms across +# VOP1/VOP2 (e32), VOP3 (e64), DPP16, DPP8, and SDWA under the static finite-proof contract (#839). +F16_EXACT_EXTRA_PROGRAMS = { + "plain_e32": [ + "v_mov_b32_e32 v20, 0xbe00", # -1.5 + "v_mov_b32_e32 v21, 0x3e00", # 1.5 + "v_mov_b32_e32 v22, 0x0001", # +2^-24 (smallest positive subnormal) + "v_mov_b32_e32 v23, 0x8300", # -3*2^-16 = -0.75 * 2^-14 (negative subnormal) + "v_mov_b32_e32 v24, 0xc100", # -2.5 + "v_min_f16_e32 v25, v20, v21", + "v_max_f16_e32 v26, 0, v22", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_fract_f16_e32 v27, v24", + "v_fract_f16_e32 v28, v22", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_frexp_mant_f16_e32 v29, v23", + "v_frexp_exp_i16_f16_e32 v30, v23", + "v_mov_b32_sdwa v14, v29 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v30 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_frexp_mant_f16_e32 v31, v22", + "v_frexp_exp_i16_f16_e32 v32, v22", + "v_mov_b32_sdwa v15, v31 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v32 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], + "plain_e64": [ + "s_mov_b32 s60, 0x4200", # 3.0 + "s_mov_b32 s61, 0xbf00", # -1.75 + "v_mov_b32_e32 v20, 0x3b00", # 0.875 + "v_mov_b32_e32 v21, 0x0400", # 2^-14 (smallest normal) + "v_mov_b32_e32 v22, 0x8000", # -0.0 + "v_min_f16_e64 v25, v20, 0.5", + "v_max_f16_e64 v26, s61, -2.0", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_fract_f16_e64 v27, s61", + "v_fract_f16_e64 v28, v22", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_frexp_mant_f16_e64 v29, s60", + "v_frexp_exp_i16_f16_e64 v30, s60", + "v_mov_b32_sdwa v14, v29 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v14, v30 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_frexp_mant_f16_e64 v31, v21", + "v_frexp_exp_i16_f16_e64 v32, v21", + "v_mov_b32_sdwa v15, v31 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v15, v32 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], + "dpp16": [ + "v_mov_b32_e32 v20, 0xbe00", # -1.5 + "v_mov_b32_e32 v21, 0x4100", # 2.5 + "v_mov_b32_e32 v22, 0x8300", # -3*2^-16 + "v_mov_b32_e32 v23, 0x0002", # 2*2^-24 + "v_min_f16_dpp v25, |v20|, v21 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_max_f16_dpp v26, -v21, v20 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_fract_f16_dpp v27, -v21 quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "v_fract_f16_dpp v28, v23 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v13, v27 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v13, v28 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_frexp_mant_f16_dpp v29, |v22| quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v14, v29 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_frexp_exp_i16_f16_dpp v30, -v22 quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", + "v_mov_b32_sdwa v15, v30 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + ], + "dpp8": [ + "v_mov_b32_e32 v20, 0xc000", # -2.0 + "v_mov_b32_e32 v21, 0x3e00", # 1.5 + "v_mov_b32_e32 v22, 0x4280", # 3.25 + "v_mov_b32_e32 v23, 0x0001", # 2^-24 + "v_min_f16_dpp v25, v20, v21 dpp8:[1,2,3,0,5,6,7,4]", + "v_max_f16_dpp v26, v20, v21 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v12, v25 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_mov_b32_sdwa v12, v26 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + "v_fract_f16_dpp v27, v22 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v13, v27 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_frexp_mant_f16_dpp v28, v22 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v14, v28 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_frexp_exp_i16_f16_dpp v29, v23 dpp8:[1,2,3,0,5,6,7,4]", + "v_mov_b32_sdwa v15, v29 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + ], + "sdwa": [ + "v_mov_b32_e32 v20, 0xbe003e00", # WORD_0=1.5, WORD_1=-1.5 + "v_mov_b32_e32 v21, 0x00014280", # WORD_0=3.25, WORD_1=2^-24 + "s_mov_b32 s60, 0x8300c100", # WORD_0=-2.5, WORD_1=-3*2^-16 + "v_min_f16_sdwa v12, v20, s60 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0", + "v_max_f16_sdwa v12, -v20, v21 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0", + "v_fract_f16_sdwa v13, s60 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_fract_f16_sdwa v13, v21 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_frexp_mant_f16_sdwa v24, s60 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_mov_b32_sdwa v14, v24 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_frexp_exp_i16_f16_sdwa v14, s60 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", + "v_frexp_mant_f16_sdwa v15, |v21| dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_frexp_exp_i16_f16_sdwa v25, v21 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_mov_b32_sdwa v15, v25 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", + ], +} +F16_EXACT_EXTRA_EXPECTED = { + "plain_e32": (0x0001be00, 0x00013800, 0xfff2ba00, 0xffe93800), + "plain_e64": (0xbf003800, 0x00003400, 0x00023a00, 0xfff33800), + "dpp16": (0xbe003e00, 0x00023800, 0x00003a00, 0x0000fff2), + "dpp8": (0x3e00c000, 0x00003400, 0x00003a80, 0x0000ffe9), + "sdwa": (0x4280c100, 0x00013800, 0xfff2ba00, 0xffe93800), +} +F16_EXACT_EXTRA_MUTATIONS = { + "plain_e32": ( + ("v_min_f16_e32 v25, v20, v21", "v_max_f16_e32 v25, v20, v21"), + ("v_max_f16_e32 v26, 0, v22", "v_min_f16_e32 v26, 0, v22"), + ("v_fract_f16_e32 v27, v24", "v_floor_f16_e32 v27, v24"), + ("v_frexp_mant_f16_e32 v29, v23", "v_frexp_mant_f16_e32 v29, v22"), + ), + "plain_e64": ( + ("v_min_f16_e64 v25, v20, 0.5", "v_max_f16_e64 v25, v20, 0.5"), + ("v_max_f16_e64 v26, s61, -2.0", "v_min_f16_e64 v26, s61, -2.0"), + ("v_fract_f16_e64 v27, s61", "v_trunc_f16_e64 v27, s61"), + ("v_frexp_exp_i16_f16_e64 v30, s60", "v_frexp_exp_i16_f16_e64 v30, v21"), + ), + "dpp16": ( + ("v_min_f16_dpp v25, |v20|, v21", "v_min_f16_dpp v25, v20, v21"), + ("v_max_f16_dpp v26, -v21, v20", "v_max_f16_dpp v26, v21, v20"), + ("v_fract_f16_dpp v27, -v21", "v_floor_f16_dpp v27, -v21"), + ("v_frexp_mant_f16_dpp v29, |v22|", "v_frexp_mant_f16_dpp v29, v22"), + ), + "dpp8": ( + ("v_min_f16_dpp v25, v20, v21", "v_max_f16_dpp v25, v20, v21"), + ("v_fract_f16_dpp v27, v22", "v_trunc_f16_dpp v27, v22"), + ("v_frexp_mant_f16_dpp v28, v22", "v_frexp_mant_f16_dpp v28, v23"), + ("v_frexp_exp_i16_f16_dpp v29, v23", "v_frexp_exp_i16_f16_dpp v29, v22"), + ), + "sdwa": ( + ("v_min_f16_sdwa v12, v20, s60", "v_max_f16_sdwa v12, v20, s60"), + ("v_max_f16_sdwa v12, -v20, v21 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_max_f16_sdwa v12, -v20, v21 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ("v_fract_f16_sdwa v13, s60", "v_floor_f16_sdwa v13, s60"), + ("v_frexp_exp_i16_f16_sdwa v14, s60 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_frexp_exp_i16_f16_sdwa v14, s60 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), +} + + +def check_f16_exact_extra_controls(): + """Positive and negative controls for all 25 exact binary16 min/max/fract/frexp forms.""" + identity = "quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf" + sdwa1 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0" + sdwa2 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0" + for name, body in F16_EXACT_EXTRA_PROGRAMS.items(): + prog = uncompressed_export(body) + hlsl = translate_f16(prog) + for helper in ("f16_min_bits(", "f16_max_bits(", "frexp_mant_f16(", "frexp_exp_i16_f16("): + assert helper in hlsl, (name, helper) + for old, new in F16_EXACT_EXTRA_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + assert translate_f16(mutated) != hlsl, (name, old, new) + # Bare and _e32 spellings lower identically. + pair = ["v_mov_b32_e32 v20, 0x3e00", "v_mov_b32_e32 v21, 0xc000"] + for bare, e32 in ( + ("v_min_f16 v24, v20, v21", "v_min_f16_e32 v24, v20, v21"), + ("v_max_f16 v24, v20, v21", "v_max_f16_e32 v24, v20, v21"), + ("v_fract_f16 v24, v20", "v_fract_f16_e32 v24, v20"), + ("v_frexp_mant_f16 v24, v20", "v_frexp_mant_f16_e32 v24, v20"), + ("v_frexp_exp_i16_f16 v24, v20", "v_frexp_exp_i16_f16_e32 v24, v20"), + ): + assert translate_f16(uncompressed_export([*pair, bare])) == translate_f16(uncompressed_export([*pair, e32])) + # Entry profile (half_denorm="preserve") and HALF_RTZ controls across all 5 ops and encodings. + for inst, op in ( + ("v_min_f16_e32 v24, v20, v21", "v_min_f16_e32"), + ("v_max_f16_e64 v24, v20, 1.0", "v_max_f16_e64"), + ("v_fract_f16_e32 v24, v20", "v_fract_f16_e32"), + ("v_frexp_mant_f16_e64 v24, v20", "v_frexp_mant_f16_e64"), + ("v_frexp_exp_i16_f16_e32 v24, v20", "v_frexp_exp_i16_f16_e32"), + (f"v_min_f16_dpp v24, v20, v21 {identity}", "v_min_f16_dpp"), + (f"v_fract_f16_dpp v24, v20 {identity}", "v_fract_f16_dpp"), + (f"v_frexp_exp_i16_f16_dpp v24, v20 {identity}", "v_frexp_exp_i16_f16_dpp"), + (f"v_max_f16_sdwa v24, v20, v21 {sdwa2}", "v_max_f16_sdwa"), + (f"v_frexp_mant_f16_sdwa v24, v20 {sdwa1}", "v_frexp_mant_f16_sdwa"), + ): + prog = uncompressed_export([*pair, inst, f"v_mov_b32_sdwa v12, v24 {sdwa1}"]) + expect_value_error(translate_int, prog, "binary16 denormal mode unknown at entry") + expect_value_error(translate_f16, [HALF_RTZ, *prog], f"under round toward zero: {op}") + # Chaining: frexp_mant -> half16 reader, frexp_exp_i16 -> low16 reader (v_cvt_f16_i16); cross-tag refused. + translate_f16(uncompressed_export([*pair, "v_frexp_mant_f16_e32 v24, v20", "v_add_f16_e32 v25, v24, v21"])) + translate_f16(uncompressed_export([*pair, "v_frexp_exp_i16_f16_e32 v24, v20", "v_cvt_f16_i16_e32 v25, v24"])) + # Refusals: opposite-signed zeros on min/max, tiny negative on fract, unproven/non-finite, e32 SGPR src1, + # DPP8 modifiers, SDWA UNUSED_SEXT/sext/BYTE src, low16 vs half16 tag separation. + for prefix, bad, message in ( + (["v_mov_b32_e32 v20, 0x0000", "v_mov_b32_e32 v21, 0x8000"], "v_min_f16_e32 v24, v20, v21", + "binary16 min of opposite-signed zeros is not lowered"), + (["v_mov_b32_e32 v20, 0x8000", "v_mov_b32_e32 v21, 0x0000"], f"v_max_f16_dpp v24, v20, v21 {identity}", + "binary16 max of opposite-signed zeros is not lowered"), + (["v_mov_b32_e32 v20, 0x0000"], f"v_min_f16_sdwa v24, v20, -v20 {sdwa2}", + "binary16 min of opposite-signed zeros is not lowered"), + (["v_mov_b32_e32 v20, 0x8001"], "v_fract_f16_e32 v24, v20", "binary16 fract rounds to 1.0 on tiny negative input"), + (["v_mov_b32_e32 v20, 0x93ff"], f"v_fract_f16_dpp v24, v20 {identity}", "binary16 fract rounds to 1.0 on tiny negative input"), + (["v_mov_b32_e32 v20, 0x0001"], f"v_fract_f16_sdwa v24, -v20 {sdwa1}", "binary16 fract rounds to 1.0 on tiny negative input"), + ([], "v_min_f16_e64 v24, s44, 1.0", "binary16 operand lacks a finite proof: s44"), + (["v_mov_b32_e32 v20, 0x7c00"], "v_frexp_mant_f16_e32 v24, v20", "binary16 operand is not finite: v20"), + (["v_mov_b32_e32 v20, 0x7e00"], f"v_frexp_exp_i16_f16_sdwa v24, v20 {sdwa1}", "binary16 operand is not finite: v20"), + (pair, "v_min_f16_e32 v24, v20, 1.0", "Binary16 e32 src1 must be a VGPR"), + (pair, "v_max_f16_dpp v24, -v20, v21 dpp8:[1,2,3,0,5,6,7,4]", "Source modifiers are not allowed on -v20"), + (pair, "v_fract_f16_dpp v24, |v20| dpp8:[1,2,3,0,5,6,7,4]", "Source modifiers are not allowed on |v20|"), + (pair, f"v_frexp_mant_f16_sdwa v24, sext(v20) {sdwa1}", "Unsupported binary16 SDWA source modifier: sext(v20)"), + (pair, "v_min_f16_sdwa v24, v20, v21 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_0", + "UNUSED_SEXT is not lowered"), + ([*pair, "v_frexp_exp_i16_f16_e32 v24, v20"], "v_cvt_f32_f16_e32 v12, v24", "Expected a numeric register"), + ([*pair, "v_frexp_mant_f16_e32 v24, v20"], "v_cvt_f16_i16_e32 v25, v24", "Expected a numeric register"), + ): + expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) + # Boundary acceptance: -2^-11 (0x9400) is exact in fract (-2^-11 -> 1 - 2^-11 = 0x3bff). + translate_f16(uncompressed_export(["v_mov_b32_e32 v20, 0x9400", "v_fract_f16_e32 v24, v20"])) + + +def check_f16_exact_extra_draw(directory, compiler, renderer, backend): + check_f16_exact_extra_controls() + for name, body in F16_EXACT_EXTRA_PROGRAMS.items(): + prog = uncompressed_export(body) + expected = F16_EXACT_EXTRA_EXPECTED[name] + src_path = directory / f"f16_exact_extra_{name}.hlsl" + cso_path = directory / f"f16_exact_extra_{name}.cso" + pass_case = directory / f"f16_exact_extra_{name}_pass.case" + pass_case.write_bytes(bytes(256) + struct.pack("<4I", *expected) * 64 + b"\x01") + src_path.write_text(translate_f16(prog), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + # Binary32 -denorm ftz must preserve binary16 subnormals and -0.0. + compile_shader(compiler, src_path, cso_path, mode="ftz") + run_pixel_batch(renderer, backend, cso_path, [(pass_case, "pass")]) + for old, new in F16_EXACT_EXTRA_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + src_path.write_text(translate_f16(mutated), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cso_path, [pass_case]) + print(f"f16_exact_extra {name} mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"f16_exact_extra {name} mutation {old!r} -> {new!r} escaped detection") + return 0 + + # Quad-local DPP16 and DPP8 integer/bitwise/shift/bit-scan/saturate fixture covering 24 VOP1/VOP2 DPP forms. # Derives integer quad lane ID {0, 1, 2, 3} from interpolated uv.x/uv.y (v8/v9), verifies quad # swizzles across lanes, folds all 23 ops into a 32-bit accumulator, and exports all 4 bytes as @@ -15870,10 +16111,10 @@ def refuse(line, message, translator=translate_f16): refuse(line, "Binary16 e32 src1 must be a VGPR") # Forms the lowering does not accept fall through to the generic refusal, and so do the neighbouring binary16 ops. for line in ("v_add_f16_e64 v24, v18, v19 clamp", "v_mul_f16_e64 v24, v18, v19 mul:2", "v_mul_f16_e64 v24, v18, v19 div:2", - "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_min_f16_dpp v24, v18, v19 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_min_f16_sdwa v24, v18, v19 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_min_f16_e64 v24, v18, v19", - "v_max_f16_e32 v24, v18, v19"): + "v_add_f16_e64 v24, v18, v19 op_sel:[0,1]", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_sqrt_f16_e64 v24, v18", + "v_exp_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -16699,10 +16940,10 @@ def refuse(line, message, translator=translate_f16): for line in ("v_floor_f16_e64 v24, v18 clamp", "v_ceil_f16_e64 v24, v18 clamp", "v_trunc_f16_e64 v24, v18 mul:2", "v_rndne_f16_e64 v24, v18 div:2", "v_rndne_f16_e64 v24, v18 mul:4", "v_floor_f16_e64 v24, v18 op_sel:[0,1]", "v_floor_f16_e64 v24, -v18 clamp", "v_floor_f16_e32 v24, v18 clamp", - "v_fract_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", - "v_fract_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_fract_f16_e32 v24, v18", "v_rcp_f16_e32 v24, v18", - "v_sqrt_f16_e64 v24, v18", "v_fract_f16_e64 v24, v18"): + "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_rcp_f16_e32 v24, v18", + "v_sqrt_f16_e64 v24, v18", "v_exp_f16_e64 v24, v18"): refuse(line, "Unsupported instruction") # Scheduling around the load and the samples: a pending SGPR, an outstanding sample, a non-entry mask. @@ -18395,7 +18636,7 @@ def _check_controls_inline(directory): for expected in ("= ceil(alu", "= round(alu", "= round(params[1].x);", "= ceil((-params[1].y));"): assert expected in source, expected # Neighbouring forms: other widths, output modifiers, a second source and the IEEE-flag reciprocal. - for old, new in (("v_ceil_f32_e32 v12, v18", "v_fract_f16_e32 v12, v18"), + for old, new in (("v_ceil_f32_e32 v12, v18", "v_rcp_f16_e32 v12, v18"), ("v_ceil_f32_e32 v12, v18", "v_ceil_f64_e32 v[12:13], v[18:19]"), ("v_rndne_f32_e32 v13, v19", "v_rcp_f16_e32 v13, v19"), ("v_rndne_f32_e32 v13, v19", "v_rndne_f32_e32 v13, v19, v18"), @@ -19586,6 +19827,7 @@ def _check_controls_inline(directory): "check_dpp_f16_contract_controls", "check_sdwa_f16_controls", "check_sdwa_int_extra_controls", + "check_f16_exact_extra_controls", "check_smem_pointer_controls", "check_masked_controls", "check_masked_mov_close_controls", @@ -20238,6 +20480,7 @@ def check_binary(directory, assembler, objcopy, library): fixtures.extend((uncompressed_export(body), translate_f16) for body in SDWA_F16_PROGRAMS.values()) fixtures.append((uncompressed_export(SDWA_F16_CVT_F32_BODY), translate_f16)) fixtures.extend((uncompressed_export(body), translate_int) for body in SDWA_INT_EXTRA_PROGRAMS.values()) + fixtures.extend((uncompressed_export(body), translate_f16) for body in F16_EXACT_EXTRA_PROGRAMS.values()) fixtures.extend((bit_program(op), translate) for op in BIT_OPERATIONS) fixtures.extend((program, function) for _, program, function, _ in e64_spelling_programs()) fixtures.append((vop1_nop_program(), translate)) @@ -26984,7 +27227,7 @@ def main(): "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", - "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-dpp-extra", "draw-pk-fmac"): + "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, "draw-dpp-cvt": check_dpp_cvt_draw, @@ -27048,7 +27291,8 @@ def main(): "draw-smem-pointers": check_smem_pointer_draw, "draw-dpp-f16": check_dpp_f16_draw, "draw-sdwa-f16": check_sdwa_f16_draw, - "draw-sdwa-int-extra": check_sdwa_int_extra_draw}[mode] + "draw-sdwa-int-extra": check_sdwa_int_extra_draw, + "draw-f16-exact-extra": check_f16_exact_extra_draw}[mode] return draw(directory, *args) except subprocess.CalledProcessError as error: if error.returncode == 77 and str(error.cmd[0]) == str(args[1]): diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index bdb1a3858..1b197796d 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6200,7 +6200,7 @@ def translator_accepts(line): "v_add_f16_e64 v24, 3, v19", "v_add_f16_e64 v24, v18, 3", "v_add_f16_e64 v24, 3.0, v19", "v_add_f16_e64 v24, 0x10000, v19", "v_add_f16_e64 v24, v256, v19", "v_add_f16_e64 v256, v18, v19", "v_add_f16_e64 v24, s106, v19", "v_add_f16_e64 v24, v18", "v_add_f16_e64 v24, v18, v19, v19", - "v_fma_f16_e64 v24, v18, v19, v19", "v_fract_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", + "v_fma_f16_e64 v24, v18, v19, v19", "v_rcp_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", "v_floor_f16_e64 v24, -v18", "v_floor_f16_e64 v24, |v18|", "v_floor_f16_e64 v24, v18 clamp", "v_floor_f16_e64 v24, v18 mul:2", "v_floor_f16_e64 v24, 3", "v_floor_f16_e64 v24, 0x10000", "v_floor_f16_e64 v24, v256", "v_floor_f16_e64 v24, v18, v19", "v_rndne_f16_e64 v24", diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 396a21290..cf6e459b4 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1032,6 +1032,44 @@ def check_vopc_e32_dst(enc, dst): " return asuint(int(exp) - 126);\n" "}" ), + "f16_min_bits": ( + "uint f16_min_bits(uint a, uint b) {\n" + " int sa = (a & 0x8000u) != 0u ? -int(a & 0x7fffu) : int(a & 0x7fffu);\n" + " int sb = (b & 0x8000u) != 0u ? -int(b & 0x7fffu) : int(b & 0x7fffu);\n" + " return sa < sb ? (a & 0xffffu) : (b & 0xffffu);\n" + "}" + ), + "f16_max_bits": ( + "uint f16_max_bits(uint a, uint b) {\n" + " int sa = (a & 0x8000u) != 0u ? -int(a & 0x7fffu) : int(a & 0x7fffu);\n" + " int sb = (b & 0x8000u) != 0u ? -int(b & 0x7fffu) : int(b & 0x7fffu);\n" + " return sa > sb ? (a & 0xffffu) : (b & 0xffffu);\n" + "}" + ), + "frexp_mant_f16": ( + "uint frexp_mant_f16(uint bits) {\n" + " uint h = bits & 0xffffu;\n" + " uint exp = (h >> 10u) & 0x1fu;\n" + " uint mant = h & 0x3ffu;\n" + " if (exp == 0x1fu || (exp == 0u && mant == 0u)) return h;\n" + " uint sign = h & 0x8000u;\n" + " if (exp == 0u) {\n" + " uint shift = 10u - firstbithigh(mant);\n" + " mant = (mant << shift) & 0x3ffu;\n" + " }\n" + " return sign | 0x3800u | mant;\n" + "}" + ), + "frexp_exp_i16_f16": ( + "uint frexp_exp_i16_f16(uint bits) {\n" + " uint h = bits & 0xffffu;\n" + " uint exp = (h >> 10u) & 0x1fu;\n" + " uint mant = h & 0x3ffu;\n" + " if (exp == 0x1fu || (exp == 0u && mant == 0u)) return 0u;\n" + " if (exp == 0u) return asuint(int(firstbithigh(mant)) - 23) & 0xffffu;\n" + " return asuint(int(exp) - 14) & 0xffffu;\n" + "}" + ), "dpp_dot4c_i32_i8": ( "uint dpp_dot4c_i32_i8(uint a, uint b, uint acc) {\n" " int s0 = (asint(a << 24) >> 24) * (asint(b << 24) >> 24);\n" @@ -1829,6 +1867,66 @@ def f16_ldexp_result(bits, exponent): return sign | ((top + 15) << 10) | (count - 0x400) +def f16_minmax_result(name, b0, b1): + """Exact binary16 result bits of v_min_f16 or v_max_f16 on two finite operands. + + Refuses opposite-signed zeros (+0.0 vs -0.0) so the lowering never relies on an unverified + tie-breaking sign rule; every other finite pair has a unique exact bit-order minimum/maximum. + """ + if ((b0 >> 10) & 0x1f) == 0x1f or ((b1 >> 10) & 0x1f) == 0x1f: + raise ValueError(f"binary16 operand is not finite: v_{name}_f16") + if (b0 ^ b1) == 0x8000 and (b0 & 0x7fff) == 0: + raise ValueError(f"binary16 {name} of opposite-signed zeros is not lowered") + s0 = -(b0 & 0x7fff) if b0 & 0x8000 else (b0 & 0x7fff) + s1 = -(b1 & 0x7fff) if b1 & 0x8000 else (b1 & 0x7fff) + return (b0 if s0 < s1 else b1) if name == "min" else (b0 if s0 > s1 else b1) + + +def f16_fract_result(bits): + """Exact binary16 result bits of v_fract_f16 (x - floor(x)) on a finite operand. + + Refuses tiny negative values (-2^-11 < x < 0, bit patterns 0x8001..0x93ff) where 1 + x is not + representable on the binary16 grid and hardware clamping to 0x3bff vs rounding to 1.0 differs. + For every other finite binary16 value, x - floor(x) is exact in binary16. + """ + if ((bits >> 10) & 0x1f) == 0x1f: + raise ValueError(f"binary16 operand is not finite: {bits:#06x}") + if 0x8001 <= bits < 0x9400: + raise ValueError(f"binary16 fract rounds to 1.0 on tiny negative input: {bits:#06x}") + if bits in (0x0000, 0x8000): + return 0x0000 + value = struct.unpack("<e", struct.pack("<H", bits))[0] + return struct.unpack("<H", struct.pack("<e", value - math.floor(value)))[0] + + +def f16_frexp_mant_result(bits): + """Exact binary16 significand bits of v_frexp_mant_f16 on a finite operand.""" + h = bits & 0xffff + exp, mant = (h >> 10) & 0x1f, h & 0x3ff + if exp == 0x1f: + raise ValueError(f"binary16 operand is not finite: {bits:#06x}") + if exp == 0 and mant == 0: + return h + sign = h & 0x8000 + if exp == 0: + shift = 10 - (mant.bit_length() - 1) + mant = (mant << shift) & 0x3ff + return sign | 0x3800 | mant + + +def f16_frexp_exp_result(bits): + """Exact low 16 bits (signed i16) of v_frexp_exp_i16_f16 on a finite operand.""" + h = bits & 0xffff + exp, mant = (h >> 10) & 0x1f, h & 0x3ff + if exp == 0x1f: + raise ValueError(f"binary16 operand is not finite: {bits:#06x}") + if exp == 0 and mant == 0: + return 0 + if exp == 0: + return ((mant.bit_length() - 1) - 23) & 0xffff + return (exp - 14) & 0xffff + + def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bits): """Return (HLSL uint word expression, 32-bit packed bits) for one v_pk_fmac_f16 source operand. @@ -5550,6 +5648,72 @@ def sample_coord(reg): lines.append(f" precise float hs{i} = {VOP1_F16_ROUND[name].format(f'widen16(hf{i}_0)')};") emit_sdwa_f16_dest(lines, i, dst, f"narrow16(hs{i})", dst_sel, unused, vector, known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(r"v_(min|max)_f16_sdwa (.+)"): + # SDWA binary16 min/max under the static finite-proof contract (opposite-signed zeros refused). + name, rest = m.groups() + parsed = SDWA_F16_BINARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_{name}_f16_sdwa {rest}") + dst, src0, src1, dst_sel, unused, sel0, sel1 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + s1_bits, b1 = half16_sdwa_source( + src1, sel1, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_minmax_result(name, b0, b1) + helper = f"f16_{name}_bits" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" uint hf{i}_1 = {s1_bits};") + emit_sdwa_f16_dest(lines, i, dst, f"{helper}(hf{i}_0, hf{i}_1)", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(r"v_fract_f16_sdwa (.+)"): + # SDWA binary16 fractional part (x - floor(x)) on exact finite inputs (tiny negatives refused). + rest = m.group(1) + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_fract_f16_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_fract_result(b0) + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = widen16(hf{i}_0) - floor(widen16(hf{i}_0));") + emit_sdwa_f16_dest(lines, i, dst, f"narrow16(hs{i})", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16", known_result=result) + elif m := match(r"v_frexp_(mant|exp_i16)_f16_sdwa (.+)"): + # SDWA binary16 frexp significand (half16) and signed exponent (low16). + kind, rest = m.groups() + parsed = SDWA_F16_UNARY_OPERANDS.fullmatch(rest) + if not parsed: + raise ValueError(f"Unsupported binary16 SDWA operands: v_frexp_{kind}_f16_sdwa {rest}") + dst, src0, dst_sel, unused, sel0 = parsed.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid binary16 SDWA operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + s0_bits, b0 = half16_sdwa_source( + src0, sel0, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + is_mant = kind == "mant" + result = f16_frexp_mant_result(b0) if is_mant else f16_frexp_exp_result(b0) + helper = "frexp_mant_f16" if is_mant else "frexp_exp_i16_f16" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = {s0_bits};") + emit_sdwa_f16_dest(lines, i, dst, f"{helper}(hf{i}_0)", dst_sel, unused, vector, + known_ssa_bits, known_half, tag="half16" if is_mant else "low16", known_result=result) elif m := match(r"v_cvt_f16_(i16|u16)_sdwa (.+)"): # SDWA 16-bit integer to binary16 conversion (round to nearest even): integer src0 with # optional sext() and any SDWA selection. Runtime i16 is always finite; u16 requires a @@ -6568,6 +6732,89 @@ def sample_coord(reg): lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result + elif m := match(r"v_(min|max)_f16_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 binary16 min/max under the static finite-proof contract. + name, dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, perm, is_dpp8 = parse_dpp(rest, 2) + s0_val, b0, abs0, neg0 = half16_dpp_source( + tokens[0], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + s1_val, b1, abs1, neg1 = half16_dpp_source( + tokens[1], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + result = f16_minmax_result(name, b0, b1) + s0_bits = f"(({emit_quad_swizzle_u32(lines, i, s0_val, perm)}) & 0xffffu)" + if abs0: + s0_bits = f"({s0_bits} & 0x7fffu)" + if neg0: + s0_bits = f"({s0_bits} ^ 0x8000u)" + s1_bits = f"(asuint({s1_val}) & 0xffffu)" + if abs1: + s1_bits = f"({s1_bits} & 0x7fffu)" + if neg1: + s1_bits = f"({s1_bits} ^ 0x8000u)" + helper = f"f16_{name}_bits" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" uint hf{i}_1 = {s1_bits};") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, hf{i}_1));") + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + elif m := match(r"v_fract_f16_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 binary16 fractional part under the exact finite-proof contract. + dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, perm, is_dpp8 = parse_dpp(rest, 1) + s0_val, b0, abs0, neg0 = half16_dpp_source( + tokens[0], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + result = f16_fract_result(b0) + s0_bits = f"(({emit_quad_swizzle_u32(lines, i, s0_val, perm)}) & 0xffffu)" + if abs0: + s0_bits = f"({s0_bits} & 0x7fffu)" + if neg0: + s0_bits = f"({s0_bits} ^ 0x8000u)" + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float hs{i} = widen16(hf{i}_0) - floor(widen16(hf{i}_0));") + lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + elif m := match(r"v_frexp_(mant|exp_i16)_f16_dpp (v\d+), (.+)"): + # Quad-local DPP16/DPP8 binary16 frexp significand (half16) and signed exponent (low16). + kind, dst, rest = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid f16 DPP operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + tokens, perm, is_dpp8 = parse_dpp(rest, 1) + s0_val, b0, abs0, neg0 = half16_dpp_source( + tokens[0], vector, sample_dest, known_ssa_bits, known_half, allow_mods=not is_dpp8) + is_mant = kind == "mant" + result = f16_frexp_mant_result(b0) if is_mant else f16_frexp_exp_result(b0) + s0_bits = f"(({emit_quad_swizzle_u32(lines, i, s0_val, perm)}) & 0xffffu)" + if abs0: + s0_bits = f"({s0_bits} & 0x7fffu)" + if neg0: + s0_bits = f"({s0_bits} ^ 0x8000u)" + helper = "frexp_mant_f16" if is_mant else "frexp_exp_i16_f16" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = {s0_bits};") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0));") + if is_mant: + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + else: + vector[dst] = ("low16", f"alu{i}") elif m := match(r"v_(fmac|ldexp)_f16_dpp (v\d+), (.+)"): # Quad-local DPP16/DPP8 binary16 fused multiply-accumulate (D = S0_swizzled * S1 + D) # and exponent scaling (D = S0_swizzled * 2^S1) under the static finite-proof contract @@ -7117,6 +7364,70 @@ def sample_coord(reg): lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result + elif m := match(r"v_(min|max)_f16(_e32|_e64)? (v\d+), ([^,\s]+), ([^,\s]+)"): + # Plain e32/e64 binary16 min/max under the static finite-proof contract (opposite-signed zeros refused). + name, encoding, dst, *tokens = m.groups() + if mask != "entry": + raise ValueError("Invalid binary16 arithmetic operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if not 0 <= int(dst[1:]) <= 255: + raise ValueError(f"Register out of range: {dst}") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + if encoding != "_e64" and not re.fullmatch(r"v\d+", tokens[1]): + raise ValueError("Binary16 e32 src1 must be a VGPR") + words, proven = zip(*(half16_arith_source(tok, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + for tok in tokens)) + result = f16_minmax_result(name, *proven) + helper = f"f16_{name}_bits" + helpers.add(helper) + for k, word in enumerate(words): + lines.append(f" uint hf{i}_{k} = ({word}) & 0xffffu;") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, hf{i}_1));") + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + elif m := match(r"v_fract_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): + # Plain e32/e64 binary16 fractional part (x - floor(x)) under the exact finite-proof contract. + encoding, dst, token = m.groups() + if mask != "entry": + raise ValueError("Invalid binary16 rounding operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if not 0 <= int(dst[1:]) <= 255: + raise ValueError(f"Register out of range: {dst}") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + word, proven = half16_arith_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + result = f16_fract_result(proven) + lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") + lines.append(f" precise float hs{i} = widen16(hf{i}_0) - floor(widen16(hf{i}_0));") + lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + elif m := match(r"v_frexp_(mant|exp_i16)_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): + # Plain e32/e64 binary16 frexp significand (half16) and signed exponent (low16). + kind, encoding, dst, token = m.groups() + if mask != "entry": + raise ValueError("Invalid binary16 rounding operation") + if half_denorm != HALF_DENORM_PRESERVE: + raise ValueError("binary16 denormal mode unknown at entry") + if not 0 <= int(dst[1:]) <= 255: + raise ValueError(f"Register out of range: {dst}") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + word, proven = half16_arith_source(token, scalar, vector, pending, sample_dest, known_ssa_bits, known_half) + is_mant = kind == "mant" + result = f16_frexp_mant_result(proven) if is_mant else f16_frexp_exp_result(proven) + helper = "frexp_mant_f16" if is_mant else "frexp_exp_i16_f16" + helpers.add(helper) + lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0));") + if is_mant: + vector[dst] = ("half16", f"alu{i}") + known_half[f"alu{i}"] = result + else: + vector[dst] = ("low16", f"alu{i}") elif m := match(r"v_cvt_f16_(i16|u16)(_e32|_e64)? (v\d+), ([^,\s]+)"): # Integer to binary16 (issue #839): LLVM 15.0.7 VOP1Instructions.td L432-433 selects sint_to_fp and uint_to_fp, # round to nearest even. The source is the low 16 bits through the audited reader int16_operand (sign- From 5ba062ebd870341137e66c1025e0b5b68097b8d1 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:20:22 +0200 Subject: [PATCH 203/232] pe: extract main(argv) and add path/struct.error guards in pe_run_package with CLI suite (#2587) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/pe_run_package_cli_check.py | 207 ++++++++++++++++++++++++++++++ tools/pe_run_package.py | 26 +++- 3 files changed, 229 insertions(+), 6 deletions(-) create mode 100644 tests/pe_run_package_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index df59aa9c7..c2fb42134 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10013,6 +10013,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pe_run_package_invalid_check.py") add_test(NAME pe_run_package_plan_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_run_package_plan_check.py") + add_test(NAME pe_run_package_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pe_run_package_cli_check.py") add_test(NAME pe_intake_checks COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/intake_exe_check.py") add_test(NAME pe_host_commit_preflight COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/pe_run_package_cli_check.py b/tests/pe_run_package_cli_check.py new file mode 100644 index 000000000..f5658890c --- /dev/null +++ b/tests/pe_run_package_cli_check.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, path-guard, and error-handling suite for tools/pe_run_package.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "pe_run_package.py" +sys.path.insert(0, str(TOOLS_DIR)) +import pe_run_package # noqa: E402 + + +def _minimal_pe32_plus(*, dll_name: bytes = b"kernel32.dll", symbol_name: bytes = b"ExitProcess") -> bytes: + """Build a synthetic PE32+ executable with one normal import table entry.""" + section_rva = 0x1000 + raw_offset = 0x200 + raw_size = 0x400 + image_base = 0x180000000 + rdata = bytearray(raw_size) + + def put(offset: int, blob: bytes) -> int: + rdata[offset:offset + len(blob)] = blob + return section_rva + offset + + dll_rva = put(0x00, dll_name + b"\0") + hint_rva = put(0x20, struct.pack("<H", 0) + symbol_name + b"\0") + ilt_rva = put(0x60, struct.pack("<QQ", hint_rva, 0)) + iat_rva = put(0x80, struct.pack("<QQ", hint_rva, 0)) + idt_size = 40 + put(0xA0, struct.pack("<5I", ilt_rva, 0, 0, dll_rva, iat_rva) + bytes(20)) + idt_rva = section_rva + 0xA0 + + pe_offset = 0x80 + buf = bytearray(raw_offset + raw_size) + buf[0:2] = b"MZ" + struct.pack_into("<I", buf, 60, pe_offset) + buf[pe_offset:pe_offset + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_offset + 4, 0x8664, 1, 0, 0, 0, 240, 0x2022) + opt = pe_offset + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + 0x20B, 0, 0, 0, raw_size, 0, 0, section_rva, image_base, + 0x1000, 0x200, 6, 0, 0, 0, 6, 0, 0, 0x2000, raw_offset, + 0, 3, 0, 0, 0, 0, 0, 0, 16, + ) + struct.pack_into("<II", buf, opt + 112 + 8, idt_rva, idt_size) + struct.pack_into( + "<8sIIIIIIHHI", + buf, + opt + 240, + b".rdata\0\0", raw_size, section_rva, raw_size, raw_offset, 0, 0, 0, 0, 0x40000040, + ) + buf[raw_offset:raw_offset + raw_size] = rdata + return bytes(buf) + + +def _run_cli(argv: list[str]) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = pe_run_package.main(argv) + except SystemExit as exc: + code = exc.code + rc = 0 if code is None else (int(code) if isinstance(code, int) else 1) + if not isinstance(code, (type(None), int)): + stderr.write(f"{code}\n") + return rc, stdout.getvalue(), stderr.getvalue() + + +class PeRunPackageCliTests(unittest.TestCase): + def test_positive_preflight_in_process_and_subprocess(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + (pkg / "app.exe").write_bytes(_minimal_pe32_plus()) + mapper = base / "mapper.dll" + mapper.write_bytes(b"") + shim = base / "kernel32_shim.dll" + shim.write_bytes(b"") + + rc, stdout, stderr = _run_cli([ + str(mapper), + str(pkg), + "app.exe", + "--preflight-only", + "--shim", + "kernel32.dll", + str(shim), + ]) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + payload = json.loads(stdout) + self.assertEqual(payload["image_order"], ["app.exe"]) + self.assertFalse(payload["entry_executed"]) + self.assertEqual(payload["missing"], ["app.exe: kernel32.dll!ExitProcess"]) + self.assertEqual(sorted(p.name for p in pkg.iterdir()), ["app.exe"]) + + # Non-existent mapper placeholder is also permitted in --preflight-only. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(base / "absent_mapper.dll"), str(pkg), "app.exe", "--preflight-only"], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + sub_payload = json.loads(proc.stdout) + self.assertEqual(sub_payload["image_order"], ["app.exe"]) + self.assertFalse(sub_payload["entry_executed"]) + + def test_path_and_argparse_guards(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + (pkg / "app.exe").write_bytes(_minimal_pe32_plus()) + mapper = base / "mapper.dll" + mapper.write_bytes(b"") + mapper_dir = base / "mapper_dir" + mapper_dir.mkdir() + shim_dir = base / "shim_dir" + shim_dir.mkdir() + not_a_dir = base / "regular.txt" + not_a_dir.write_text("file", encoding="utf-8") + + # Missing args (Py3.14-safe argparse assertion). + rc, _, stderr = _run_cli([]) + self.assertNotEqual(rc, 0) + self.assertIn("required", stderr.lower()) + self.assertNotIn("Traceback", stderr) + + cases = ( + ("missing_package", [str(mapper), str(base / "missing_pkg"), "app.exe", "--preflight-only"], ""), + ("file_package", [str(mapper), str(not_a_dir), "app.exe", "--preflight-only"], "directory"), + ("dir_mapper", [str(mapper_dir), str(pkg), "app.exe", "--preflight-only"], "directory"), + ("missing_shim", [str(mapper), str(pkg), "app.exe", "--shim", "kernel32.dll", str(base / "missing.dll"), "--preflight-only"], "missing.dll"), + ("dir_shim", [str(mapper), str(pkg), "app.exe", "--shim", "kernel32.dll", str(shim_dir), "--preflight-only"], "directory"), + ) + for label, argv, expected_substr in cases: + with self.subTest(case=label): + with mock.patch.object( + pe_run_package, + "inspect", + side_effect=AssertionError(f"inspect called for invalid path case {label}"), + ): + rc, stdout, stderr = _run_cli(argv) + self.assertEqual(rc, 1) + self.assertEqual(stdout, "") + self.assertTrue(stderr.strip()) + if expected_substr: + self.assertIn(expected_substr, stderr) + self.assertNotIn("Traceback", stderr) + + def test_exception_guards_and_subprocess_negative_smoke(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + pkg = base / "package" + pkg.mkdir() + (pkg / "app.exe").write_bytes(b"MZ not a valid PE") + mapper = base / "mapper.dll" + mapper.write_bytes(b"") + + # pefile.PEFormatError -> exit 1 without traceback. + rc, stdout, stderr = _run_cli([str(mapper), str(pkg), "app.exe", "--preflight-only"]) + self.assertEqual(rc, 1) + self.assertEqual(stdout, "") + self.assertTrue(stderr.strip()) + self.assertNotIn("Traceback", stderr) + + # struct.error -> exit 1 without traceback. + with mock.patch.object(pe_run_package, "inspect", side_effect=struct.error("short unpack")): + rc, stdout, stderr = _run_cli([str(mapper), str(pkg), "app.exe", "--preflight-only"]) + self.assertEqual(rc, 1) + self.assertEqual(stdout, "") + self.assertIn("short unpack", stderr) + self.assertNotIn("Traceback", stderr) + + # Subprocess negative smoke test (mapper is a directory). + mapper_dir = base / "mapper_dir" + mapper_dir.mkdir() + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(mapper_dir), str(pkg), "app.exe", "--preflight-only"], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1) + self.assertEqual(proc.stdout, "") + self.assertIn("directory", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/pe_run_package.py b/tools/pe_run_package.py index 06ba16e4e..394846cce 100644 --- a/tools/pe_run_package.py +++ b/tools/pe_run_package.py @@ -8,6 +8,7 @@ import json import os from pathlib import Path +import struct import sys import pefile @@ -284,7 +285,7 @@ def resolve(dll, name, ordinal): return result -def main(): +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("mapper", type=Path) parser.add_argument("package", type=Path) @@ -302,7 +303,7 @@ def main(): help="diagnostic: bind this unresolved external, which the caller must call rather than " "read as data, to a trap that names it on stderr and terminates the process with " f"{TRAP_EXIT_BASE:#x} | trap number; any unlisted unresolved external is still refused") - options = parser.parse_args() + options = parser.parse_args(argv) try: # Perform the opt-in check before parsing the package or loading providers. # A successful check does not reserve memory and cannot promise startup. @@ -312,22 +313,35 @@ def main(): raise ValueError("--min-commit-mib must be between 0 and 1048576") commit_report = require_commit_budget(options.min_commit_mib, read_host_commit()) root = options.package.resolve(strict=True) - shims = {name.casefold(): Path(path).resolve(strict=True) for name, path in options.shim} + if not root.is_dir(): + raise NotADirectoryError(f"package path is not a directory: {root}") + mapper = options.mapper + if mapper.is_dir(): + raise IsADirectoryError(f"mapper path is a directory: {mapper}") + shims = {} + for name, raw_path in options.shim: + shim_path = Path(raw_path).resolve(strict=True) + if shim_path.is_dir(): + raise IsADirectoryError(f"--shim {name} path is a directory: {shim_path}") + if not shim_path.is_file(): + raise ValueError(f"--shim {name} path is not a regular file: {shim_path}") + shims[name.casefold()] = shim_path system = {name.casefold() for name in options.system} if any(not name or name in (".", "..") or Path(name).name != name or "/" in name or "\\" in name for name in system): raise ValueError("System providers must be DLL basenames") report = inspect(root, options.entry) - result = run(root, report, options.mapper.resolve(), shims, system, + result = run(root, report, mapper.resolve(), shims, system, preflight_only=options.preflight_only, pin_shims={name.casefold() for name in options.pin_shim}, trap_callable=options.trap_callable) if commit_report is not None: result = {**result, "host_commit": commit_report} - except (ValueError, OSError, pefile.PEFormatError) as exc: + except (ValueError, OSError, pefile.PEFormatError, struct.error) as exc: parser.exit(1, f"{exc}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 157a477f1665073d74526a6d27b71f1eacca2db4 Mon Sep 17 00:00:00 2001 From: thepatrickworld <thepatrickworld@gmail.com> Date: Wed, 25 Nov 2026 23:24:32 +0100 Subject: [PATCH 204/232] startup: release the per-device D3D12 caches only when the module is unloaded (#2590) The indexed-validation pipeline and the rectangle-list converter own a device, root signatures and pipeline states for as long as the shim is loaded. They are function-local statics, so they are destroyed during the module's CRT teardown, which runs at process exit as well as on FreeLibrary. At process exit the display driver is already detached, and releasing a pipeline state from the destructor reaches a stopped driver (amdxc64, 0x35f2a19, through D3D12Core!CPipelineState::FinalRelease), which ends the process with __fastfail(7). DllMain now records which of the two detaches is running, and both destructors detach their references on the terminating path and release them otherwise. Device keying is unchanged. tests/startup_teardown_unload.cpp loads the built d3d12_xs.dll by path, warms both caches through a probe, unloads it and checks that the objects come back, then leaves a second load to process termination. Co-authored-by: panam <panam@local> Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 17 ++ docs/experiments.md | 35 ++++ src/d3d12_xs_shim.cpp | 21 +++ src/startup_stubs/d3d12_draw.inl | 15 ++ src/startup_stubs/d3d12_teardown.h | 32 ++++ src/startup_stubs/d3d12_xs_device.cpp | 43 +++++ src/startup_stubs/rect_indirect_args.h | 18 ++ tests/startup_teardown_unload.cpp | 245 +++++++++++++++++++++++++ 8 files changed, 426 insertions(+) create mode 100644 src/startup_stubs/d3d12_teardown.h create mode 100644 tests/startup_teardown_unload.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c2fb42134..d723bb129 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1503,6 +1503,23 @@ add_test(NAME startup_indirect_other_refusal_census_control_warp set_tests_properties(startup_indirect_other_refusal_census_control_warp PROPERTIES TIMEOUT 60 PASS_REGULAR_EXPRESSION "got +'x2w-d3d12 indirect-other refusals: total 3. distinct keys 2, distinct pairs 2 \\(overflow calls 0\\)'") +# Teardown of the two per-device caches that keep desktop D3D12 objects (#2572): the built d3d12_xs.dll is +# loaded by explicit path, warmed through its own probe, then unloaded -- the caches must release what they +# own and the module must go -- and a second load is left to process termination, where the caches must +# release nothing because the display driver is already stopped. This check runs the built DLL itself, so +# unlike the Python-driven startup_* tests it needs no INTAKE_PYTHON guard. +add_executable(startup_teardown_unload tests/startup_teardown_unload.cpp) +target_compile_features(startup_teardown_unload PRIVATE cxx_std_17) +target_link_libraries(startup_teardown_unload PRIVATE d3d12 dxgi) +add_dependencies(startup_teardown_unload d3d12_xs_shim) +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_teardown_unload_${backend} COMMAND startup_teardown_unload + "$<TARGET_FILE:d3d12_xs_shim>" ${backend}) + set_tests_properties(startup_teardown_unload_${backend} PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "startup_teardown_unload ${backend}: PASS") +endforeach() +set_tests_properties(startup_teardown_unload_hardware PROPERTIES SKIP_RETURN_CODE 77) + # OMSetRenderTargets with a single descriptor range, handles that hold no view, and a cleared copied descriptor. add_executable(startup_rtv_bind tests/startup_rtv_bind.cpp) target_compile_features(startup_rtv_bind PRIVATE cxx_std_17) diff --git a/docs/experiments.md b/docs/experiments.md index 9a41a0761..667e7799f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15700,6 +15700,41 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_int_extra_warp|pixel_ao Linux controls, `form_coverage_check.check_sdwa_int_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. +## Teardown of the per-device D3D12 caches + +Two caches keep desktop D3D12 objects for a device for as long as the module that holds them is loaded: the +indexed-validation pipeline (`startup_stubs/d3d12_draw.inl`) and the rectangle-list argument converter +(`startup_stubs/rect_indirect_args.h`). Both are function-local statics, so they are destroyed during the +module's CRT teardown, and that teardown happens at two different moments. At process exit Windows has already +detached the display driver: releasing a pipeline state then faults inside the driver (`amdxc64`, at +`0x35f2a19`, through `D3D12Core!CPipelineState::FinalRelease`) and the loader turns it into `0xC0000409`. +`FreeLibrary` unloads the module while the process and the driver stay alive, and there every owned object +must be released. + +`DllMain` in `src/d3d12_xs_shim.cpp` tells the two apart: `lpReserved` is non-null only when the process is +terminating, and the user entry runs before this module's `atexit` table. The flag it sets is declared in +`startup_stubs/d3d12_teardown.h`, and each cache has an explicit destructor that detaches its references on +that path and releases them otherwise. Device keying is unchanged. + +```powershell +cmake --build --preset dev --target d3d12_xs_shim startup_teardown_unload startup_indirect_draw_indexed +ctest --preset dev --no-tests=error -R "^startup_teardown_unload_(warp|hardware)$" -V +ctest --preset dev --no-tests=error -R "^startup_indirect_(translated_indexed|rectlist)" -V +``` + +The fixture (`tests/startup_teardown_unload.cpp`) loads the built `d3d12_xs.dll` by path, warms both caches +through the module's own probe, and unloads it: the caches must release what they own, the device's reference +count must come back, and the module must be gone. A second load is warmed and left loaded, so process +termination exercises the other path. It is source-built and loads no title. + +Measured on Windows 11 25H2 (26200.9974, MSVC 19.44.35230), AMD Radeon RX 9070 XT (`1002:7550`, driver +`32.0.32029.2010`), debug layer unavailable: `startup_teardown_unload` passes on WARP and on the card, and the +five `startup_indirect_*_hardware` runs that died with `0xC0000409` now reach their last assertion and exit +`0`. Removing either destructor brings its own failure back and only its own: without the validation-pipeline +destructor the four `translated_indexed*` runs fail and `rectlist` passes; without the converter destructor +`rectlist` fails and the four pass. Not covered: an explicit unload while a device is still referenced by a +title, and any adapter other than the one above. + ## Exact binary16 min, max, fract, and frexp forms (VOP1/VOP2/VOP3/DPP16/DPP8/SDWA) in pixel_aot [The pixel shader translator](../tools/pixel_aot.py) adds 25 exact binary16 forms across all 5 encodings (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): diff --git a/src/d3d12_xs_shim.cpp b/src/d3d12_xs_shim.cpp index c02660033..852dbdc7a 100644 --- a/src/d3d12_xs_shim.cpp +++ b/src/d3d12_xs_shim.cpp @@ -17,6 +17,7 @@ #include <vector> #include "d3d12x_device_slots.h" +#include "startup_stubs/d3d12_teardown.h" namespace { // Observed console root-signature flag bits set by XboxBvhBuilder.dll. @@ -270,3 +271,23 @@ extern "C" HRESULT WINAPI d3d12_xs_ConfigureVirtualMemoryX(const void* config) ReleaseSRWLockExclusive(&vm_state.lock); return accepted ? S_OK : DXGI_ERROR_INVALID_CALL; } + +// Lifetime boundary of the desktop D3D12 objects this module keeps in function-local statics +// (startup_stubs/d3d12_draw.inl, startup_stubs/rect_indirect_args.h, #2572). Those caches own a device, +// a root signature and a pipeline state per device for as long as this DLL is loaded, and the loader +// detaches the module before their destructors run: +// lpReserved != nullptr the process is exiting. Windows has already stopped the display driver, so a +// Release() there faults inside the driver (amdxc64 offset 0x35f2a19, through +// D3D12Core!CPipelineState::FinalRelease) and the loader ends the process with +// __fastfail(7). The caches detach their references instead of releasing them. +// lpReserved == nullptr FreeLibrary unloads the module while the process and the driver stay alive: +// the caches release the objects they own. +// This DllMain runs before this module's atexit table: the static runtime reaches the user entry before +// it runs the table on detach, which the cpu_native_crt_lifecycle fixture measures (a global destructor +// runs after DllMain(DLL_PROCESS_DETACH), docs/experiments.md), so the destructors see the flag below. +// startup_stubs/d3d12_teardown.h has the details. +extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) +{ + if (reason == DLL_PROCESS_DETACH && reserved) x2w_startup::d3d12_process_terminating = true; + return TRUE; +} diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1cf860745..8c3ee62f2 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1597,6 +1597,21 @@ struct IndexedValidationPipeline { x2w_startup::ComPtr<ID3D12Device> device; x2w_startup::ComPtr<ID3D12RootSignature> root; x2w_startup::ComPtr<ID3D12PipelineState> pipeline; + + // Lifetime boundary: this record owns the device it was built for, its root signature and its + // pipeline, from the first validation that asked for them until the module that holds it is + // unloaded. It is a function-local static in indexed_validation_pipeline() below, so it is destroyed + // during that module's CRT teardown (startup_stubs/d3d12_teardown.h). On process exit the display + // driver may already be stopped and releasing a pipeline state then fails inside it (amdxc64, #2572), + // so the three references are detached and nothing reaches the driver. FreeLibrary keeps the process + // and the driver alive: no flag, and the members above release their objects normally. + ~IndexedValidationPipeline() + { + if (!x2w_startup::d3d12_process_terminating) return; + device.Detach(); + root.Detach(); + pipeline.Detach(); + } }; IndexedValidationPipeline& indexed_validation_pipeline(ID3D12Device* device) diff --git a/src/startup_stubs/d3d12_teardown.h b/src/startup_stubs/d3d12_teardown.h new file mode 100644 index 000000000..278f27580 --- /dev/null +++ b/src/startup_stubs/d3d12_teardown.h @@ -0,0 +1,32 @@ +// Lifetime boundary of the desktop D3D12 objects the stand-in keeps in function-local statics: +// the indexed-validation pipeline (startup_stubs/d3d12_draw.inl) and the rectangle-list argument +// converter (startup_stubs/rect_indirect_args.h). #2572. +// +// Both caches hold their objects for as long as this module is loaded -- a conversion or a validation +// may still be queued when the call that built the entry returns -- so they are destroyed during this +// module's CRT teardown. That teardown runs at two different moments: +// +// process exit Windows detaches every module after the display driver's DLL; releasing a +// D3D12 object then reaches a stopped driver (amdxc64, offset 0x35f2a19, through +// D3D12Core!CPipelineState::FinalRelease) and the loader's __fastfail(7) turns +// that into 0xC0000409. Nothing may be released. +// FreeLibrary the module is unloaded while the process and the driver stay alive: every owned +// object must be released then, or it would be leaked for the rest of the process. +// +// DllMain's lpReserved is what tells the two detaches apart: non-null means the process is +// terminating, null means the loader is unloading this module. src/d3d12_xs_shim.cpp sets the flag +// below from its DllMain, which runs before this module's atexit table -- the static runtime reaches +// the user entry before it runs the table on detach, as the cpu_native_crt_lifecycle fixture measures +// (docs/experiments.md) -- so the destructors read it without a lock. +// +// The variable is defined inline: each module that includes this header has its own copy, so the +// caches compiled into another module (the test executables include rect_indirect_args.h) keep +// releasing normally, and only the DLL that owns the DllMain can silence its own teardown. Being a +// zero-initialized bool, it needs no dynamic initialization and no destruction order. +#pragma once + +namespace x2w_startup { + +inline bool d3d12_process_terminating = false; + +} // namespace x2w_startup diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 06a1eb1c1..44ca60da1 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -47,6 +47,7 @@ #include "startup_stubs/memory_srv_buffer.h" #include "startup_stubs/single_element_srv.h" #include "startup_stubs/list_copy.h" +#include "startup_stubs/d3d12_teardown.h" #include "startup_stubs/rect_indirect_args.h" #include "startup_stubs/profile_zone.h" @@ -5182,6 +5183,48 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_retire_probe(void* resource, voi return TRUE; } +// Fixture probe (startup_teardown_unload, #2572) for the two caches that keep desktop objects for a +// device: the indexed-validation pipeline (d3d12_draw.inl, bit 0) and the rectangle-list argument +// converter (rect_indirect_args.h, bit 1). Warms the selected caches the way their first real call +// would -- the validation pipeline directly, the converter through one record-only conversion, nothing +// executed -- and answers how many objects they now hold for `device`: the validation entry's device, +// root signature and pipeline (3), plus the converter entry's root signature and pipeline (2). The +// caller can warm one cache at a time to see each one release what it owns when the module is unloaded. +extern "C" __declspec(dllexport) UINT x2w_d3d12_cached_objects_probe(ID3D12Device* device, UINT caches) +{ + if (!device || !caches || (caches & ~3u)) return 0; + UINT owned = 0; + if (caches & 1u) { + const auto& validation = indexed_validation_pipeline(device); + if (validation.device) ++owned; + if (validation.root) ++owned; + if (validation.pipeline) ++owned; + } + if (!(caches & 2u)) return owned; + + x2w_startup::ComPtr<ID3D12CommandAllocator> allocator; + x2w_startup::ComPtr<ID3D12GraphicsCommandList> list; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), nullptr, + IID_PPV_ARGS(&list)))) + return owned; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 256; + buffer.Height = buffer.DepthOrArraySize = buffer.MipLevels = buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // convert() copies its 16 source words; an uninitialised buffer in the state it requires is enough. + x2w_startup::ComPtr<ID3D12Resource> source; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, + nullptr, IID_PPV_ARGS(&source)))) + return owned; + const auto scratch = x2w_startup::RectIndirectArguments::make_scratch(device); + if (scratch && x2w_startup::rect_indirect_arguments().convert(list.Get(), source.Get(), 0, scratch.Get())) + owned += 2; // the converter's root signature and pipeline for this device + return owned; +} + // Fixture probes (startup_resource_retire_title) for state the retire bookkeeping maintains for one resource. They read // the same maps the shim reads and never change them; the address index and the upload cache exist with and without // the switch, so these answer in both modes. diff --git a/src/startup_stubs/rect_indirect_args.h b/src/startup_stubs/rect_indirect_args.h index 047fb2846..579350fbb 100644 --- a/src/startup_stubs/rect_indirect_args.h +++ b/src/startup_stubs/rect_indirect_args.h @@ -15,6 +15,8 @@ #include <d3dcompiler.h> #include <wrl/client.h> +#include "startup_stubs/d3d12_teardown.h" + #include <memory> #include <mutex> #include <vector> @@ -94,6 +96,22 @@ class RectIndirectArguments { transition(list, scratch, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); } + // Lifetime boundary: this cache owns one root signature and one pipeline per device, for as long as + // the module that holds it is loaded, because a conversion may still be queued when the recording + // that called convert() returns (the entries are never dropped before that). The cache itself is a + // function-local static in rect_indirect_arguments(), so this destructor runs during the module's + // CRT teardown -- see startup_stubs/d3d12_teardown.h for the two detaches. On process exit the + // driver may already be stopped, so the objects are detached and nothing reaches it; FreeLibrary + // leaves the process and the driver alive and the entries below release their objects normally. + ~RectIndirectArguments() + { + if (!x2w_startup::d3d12_process_terminating) return; + for (auto& entry : entries_) { + entry->root.Detach(); + entry->pipeline.Detach(); + } + } + private: struct Entry { ID3D12Device* device = nullptr; diff --git a/tests/startup_teardown_unload.cpp b/tests/startup_teardown_unload.cpp new file mode 100644 index 000000000..44cc0297d --- /dev/null +++ b/tests/startup_teardown_unload.cpp @@ -0,0 +1,245 @@ +// Loads the built d3d12_xs.dll by explicit path, warms the two caches that keep desktop D3D12 objects +// (#2572) through that module, and walks both detach paths it has to survive: +// +// startup_teardown_unload <path-to-d3d12_xs.dll> <warp|hardware> +// +// Unload: FreeLibrary detaches the module with lpReserved == nullptr. Each cache is loaded and warmed on +// its own, so its release can be seen alone: the device's reference count must return to the count the +// test itself holds (otherwise an owned object was leaked), the module must be gone, and the process must +// still run. +// +// Termination: a second load warms both caches and is deliberately left loaded. On process exit the +// loader detaches the module with lpReserved != nullptr, after Windows has stopped the display driver; +// releasing a pipeline state then faults inside the driver (amdxc64 offset 0x35f2a19, through +// D3D12Core!CPipelineState::FinalRelease) and the process dies with 0xC0000409 before it can report a +// result. The caches must detach their references instead. This is the path the five +// startup_indirect_*_hardware runs hit. +// +// The fixture is source-built and loads no title. +#include <windows.h> +#include <d3d12.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <cstdio> +#include <string> +#include <string_view> + +using Microsoft::WRL::ComPtr; + +namespace { + +using XboxCreateDevice = HRESULT(WINAPI*)(IUnknown*, const void*, REFIID, void**); +// Probe bits: 1 the indexed-validation pipeline, 2 the rectangle-list argument converter. +using CachedObjectsProbe = UINT(WINAPI*)(ID3D12Device*, UINT); + +struct CacheCase { + const char* name; + UINT probe_bits; + UINT owned; // objects the warmed cache holds for one device +}; + +// One case per cache, so a leak names the cache that kept it. +constexpr CacheCase cache_cases[] = { + {"indexed-validation", 1u, 3u}, // device, root signature, pipeline + {"rect-converter", 2u, 2u}, // root signature, pipeline +}; + +// Same selection convention as the other D3D12 fixtures: WARP on request, otherwise the first +// non-software adapter in high-performance order. 77 when the machine has no physical adapter. +int select_adapter(bool warp, ComPtr<IDXGIFactory6>& factory, ComPtr<IDXGIAdapter>& adapter) +{ + HRESULT hr = CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)); + if (FAILED(hr)) { + std::fprintf(stderr, "CreateDXGIFactory2 failed: 0x%08lx\n", static_cast<unsigned long>(hr)); + return 3; + } + if (warp) { + hr = factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); + if (FAILED(hr) || !adapter) { + std::fprintf(stderr, "WARP adapter unavailable: 0x%08lx\n", static_cast<unsigned long>(hr)); + return 3; + } + return 0; + } + for (UINT index = 0;; ++index) { + ComPtr<IDXGIAdapter1> candidate; + hr = factory->EnumAdapterByGpuPreference(index, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) { + std::fprintf(stderr, "EnumAdapterByGpuPreference failed: 0x%08lx\n", static_cast<unsigned long>(hr)); + return 3; + } + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 3; + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; + if (SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + return 0; + } + } +} + +std::wstring widen(const char* path) +{ + const int length = MultiByteToWideChar(CP_ACP, 0, path, -1, nullptr, 0); + if (length <= 0) return std::wstring(); + std::wstring wide(static_cast<std::size_t>(length), L'\0'); + if (!MultiByteToWideChar(CP_ACP, 0, path, -1, wide.data(), length)) return std::wstring(); + return wide; +} + +HMODULE load_shim(const std::wstring& path, XboxCreateDevice& create, CachedObjectsProbe& probe) +{ + HMODULE module = LoadLibraryExW(path.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!module) { + std::fprintf(stderr, "LoadLibraryExW(%ls) failed: %lu\n", path.c_str(), + static_cast<unsigned long>(GetLastError())); + return nullptr; + } + create = reinterpret_cast<XboxCreateDevice>(GetProcAddress(module, "D3D12XboxCreateDevice")); + probe = reinterpret_cast<CachedObjectsProbe>(GetProcAddress(module, "x2w_d3d12_cached_objects_probe")); + if (!create || !probe) { + std::fputs("d3d12_xs.dll does not export D3D12XboxCreateDevice and x2w_d3d12_cached_objects_probe\n", stderr); + FreeLibrary(module); + return nullptr; + } + HMODULE owner = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast<LPCWSTR>(probe), &owner) || + owner != module) { + std::fputs("x2w_d3d12_cached_objects_probe does not resolve inside d3d12_xs.dll\n", stderr); + FreeLibrary(module); + return nullptr; + } + return module; +} + +// The count returned includes the caller's own reference: AddRef then Release leaves the object with the +// references it had and answers how many there are. +ULONG reference_count(IUnknown* object) +{ + object->AddRef(); + return object->Release(); +} + +// Phase 1: load, warm one cache, unload explicitly, and check that this cache released what it owned. +int unload_path(const std::wstring& path, IDXGIAdapter* adapter, const CacheCase& cache) +{ + XboxCreateDevice create = nullptr; + CachedObjectsProbe probe = nullptr; + HMODULE shim = load_shim(path, create, probe); + if (!shim) return 1; + + ComPtr<ID3D12Device> device; + HRESULT hr = create(adapter, nullptr, __uuidof(ID3D12Device), + reinterpret_cast<void**>(device.GetAddressOf())); + if (FAILED(hr) || !device) { + std::fprintf(stderr, "D3D12XboxCreateDevice failed: 0x%08lx\n", static_cast<unsigned long>(hr)); + FreeLibrary(shim); + return 4; + } + + const ULONG before = reference_count(device.Get()); + const UINT owned = probe(device.Get(), cache.probe_bits); + if (owned != cache.owned) { + std::fprintf(stderr, "%s: probe reports %u cached objects, expected %u\n", cache.name, owned, cache.owned); + FreeLibrary(shim); + return 5; + } + const ULONG warm = reference_count(device.Get()); + if (warm <= before) { + std::fprintf(stderr, "%s: the cache holds no reference on the device: %lu before, %lu warm\n", cache.name, + static_cast<unsigned long>(before), static_cast<unsigned long>(warm)); + FreeLibrary(shim); + return 6; + } + + if (!FreeLibrary(shim)) { + std::fprintf(stderr, "%s: FreeLibrary failed: %lu\n", cache.name, + static_cast<unsigned long>(GetLastError())); + return 7; + } + if (GetModuleHandleW(L"d3d12_xs.dll")) { + std::fprintf(stderr, "%s: d3d12_xs.dll is still loaded after FreeLibrary\n", cache.name); + return 8; + } + const ULONG after = reference_count(device.Get()); + if (after != before) { + std::fprintf(stderr, "%s: the unloaded module left %lu device references behind (expected %lu)\n", + cache.name, static_cast<unsigned long>(after), static_cast<unsigned long>(before)); + return 9; + } + std::printf("unload %s: %u objects released, references %lu -> %lu, module unloaded\n", cache.name, owned, + static_cast<unsigned long>(warm), static_cast<unsigned long>(after)); + return 0; +} + +// Phase 2: load and warm both caches, then let the process exit with the module still loaded. Nothing may +// be released from the caches then, so nothing reaches the driver Windows has already stopped. +int termination_path(const std::wstring& path, IDXGIAdapter* adapter) +{ + XboxCreateDevice create = nullptr; + CachedObjectsProbe probe = nullptr; + HMODULE shim = load_shim(path, create, probe); + if (!shim) return 1; + + ComPtr<ID3D12Device> device; + HRESULT hr = create(adapter, nullptr, __uuidof(ID3D12Device), + reinterpret_cast<void**>(device.GetAddressOf())); + if (FAILED(hr) || !device) { + std::fprintf(stderr, "D3D12XboxCreateDevice failed on the second load: 0x%08lx\n", + static_cast<unsigned long>(hr)); + return 4; + } + UINT expected = 0; + for (const CacheCase& cache : cache_cases) expected += cache.owned; + const UINT owned = probe(device.Get(), 3u); + if (owned != expected) { + std::fprintf(stderr, "termination: probe reports %u cached objects, expected %u\n", owned, expected); + return 5; + } + // Deliberately no FreeLibrary: the shim stays loaded, so the loader detaches it during process exit. + // Releasing the device here, while the process and the driver still run, is the test's own reference. + std::printf("termination: %u objects left to the process exit path\n", owned); + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) { + std::fprintf(stderr, "usage: %s <path-to-d3d12_xs.dll> <warp|hardware>\n", argv[0]); + return 2; + } + const std::string_view backend = argv[2]; + if (backend != "warp" && backend != "hardware") { + std::fputs("unknown backend\n", stderr); + return 2; + } + const std::wstring path = widen(argv[1]); + if (path.empty()) { + std::fputs("cannot convert the d3d12_xs.dll path\n", stderr); + return 2; + } + + ComPtr<IDXGIFactory6> factory; + ComPtr<IDXGIAdapter> adapter; + const int selected = select_adapter(backend == "warp", factory, adapter); + if (selected) return selected; + DXGI_ADAPTER_DESC desc{}; + if (SUCCEEDED(adapter->GetDesc(&desc))) + std::printf("startup_teardown_unload backend=%s adapter=%ls vendor=%04x device=%04x\n", argv[2], + desc.Description, desc.VendorId, desc.DeviceId); + + int result = 0; + for (const CacheCase& cache : cache_cases) { + result = unload_path(path, adapter.Get(), cache); + if (result) break; + } + if (result == 0) result = termination_path(path, adapter.Get()); + std::printf("startup_teardown_unload %s: %s\n", argv[2], result == 0 ? "PASS" : "FAIL"); + return result; +} From 0a123934cab683248f2cd75f2452a7e07b28455a Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:26:25 +0200 Subject: [PATCH 205/232] build: harden atomic report writes and path/IO error guards in verify_build with CLI suite (#2586) * build: harden atomic report writes and path/IO error guards in verify_build with CLI suite * tests: forward *args/**kwargs in verify_build_cli_check glob mocks --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/verify_build_cli_check.py | 400 ++++++++++++++++++++++++++++++++ tools/verify_build.py | 46 ++-- 3 files changed, 434 insertions(+), 14 deletions(-) create mode 100644 tests/verify_build_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d723bb129..bfd130961 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9991,6 +9991,8 @@ if(EXISTS "${INTAKE_PYTHON}") endforeach() set_tests_properties(rectlist_draw_hardware PROPERTIES SKIP_RETURN_CODE 77) add_test(NAME conditional_import_paths COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/intake/paths_check.py") + add_test(NAME build_verify_build_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/verify_build_cli_check.py") add_library(intake_provider SHARED tests/intake/provider.cpp tests/intake/provider.def) add_library(intake_delay SHARED tests/intake/provider.cpp tests/intake/delay.def) add_executable(intake_candidate tests/intake/candidate.cpp) diff --git a/tests/verify_build_cli_check.py b/tests/verify_build_cli_check.py new file mode 100644 index 000000000..fd0e39b5d --- /dev/null +++ b/tests/verify_build_cli_check.py @@ -0,0 +1,400 @@ +"""CLI, atomic report write, path/IO error guard, determinism, and mutation suite for tools/verify_build.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "verify_build.py" +sys.path.insert(0, str(ROOT / "tools")) + +import verify_build # noqa: E402 + +EXPECTED_REPORT_KEYS = { + "started_utc", + "directory", + "torrent", + "torrent_sha256", + "payload_bytes", + "payload_count", + "disk_file_count", + "missing", + "size_mismatches", + "extra_disk_files", + "layout", + "torrent_order", + "pieces", + "changed_during_verification", + "torrent_payload_passed", + "finished_utc", +} + + +def _bencode(value): + if isinstance(value, int): + return b"i" + str(value).encode("ascii") + b"e" + if isinstance(value, bytes): + return str(len(value)).encode("ascii") + b":" + value + if isinstance(value, list): + return b"l" + b"".join(_bencode(item) for item in value) + b"e" + if isinstance(value, dict): + items = sorted(value.items(), key=lambda kv: kv[0]) + return b"d" + b"".join(_bencode(k) + _bencode(v) for k, v in items) + b"e" + raise TypeError(type(value)) + + +def _create_package(pkg: Path, *, corrupt_second: bool = False): + pkg.mkdir(parents=True, exist_ok=True) + sub = pkg / "sub" + sub.mkdir(exist_ok=True) + data_a = b"alpha-payload-1234" + data_b = b"bravo-payload-5678" + (pkg / "b.bin").write_bytes(data_b) + (sub / "a.bin").write_bytes(data_a) + layout_xml = ( + '<?xml version="1.0" encoding="utf-8"?>\n' + "<Package>\n" + ' <Chunk Id="1000" Marker="Launch">\n' + ' <FileGroup SourcePath="." DestinationPath="\\sub\\" Include="a.bin" />\n' + ' <FileGroup SourcePath="." DestinationPath="." Include="b.bin" />\n' + " </Chunk>\n" + "</Package>\n" + ) + (pkg / "layout.xml").write_text(layout_xml, encoding="utf-8") + + piece_len = 16 + stream = data_a + data_b + pieces = b"".join( + hashlib.sha1(stream[i:i + piece_len]).digest() + for i in range(0, len(stream), piece_len) + ) + torrent = { + b"info": { + b"files": [ + {b"length": len(data_a), b"path": [b"sub", b"a.bin"]}, + {b"length": len(data_b), b"path": [b"b.bin"]}, + ], + b"name": b"pkg", + b"piece length": piece_len, + b"pieces": pieces, + } + } + (pkg / "pkg.torrent").write_bytes(_bencode(torrent)) + if corrupt_second: + (pkg / "b.bin").write_bytes(b"X" + data_b[1:]) + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = verify_build.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class VerifyBuildCliPositiveTests(unittest.TestCase): + def test_atomic_report_write_schema_and_fail_status_1(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pkg = root / "package" + _create_package(pkg) + out_file = root / "nested" / "reports" / "integrity.json" + self.assertFalse(out_file.parent.exists()) + + seen_replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + self.assertEqual(src_path.name, dst_path.name) + return real_replace(src, dst) + + with mock.patch.object(verify_build.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(pkg), "--output", str(out_file)]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("Payload passed: True", out) + self.assertEqual(len(seen_replaces), 1) + self.assertEqual(sorted(p.name for p in out_file.parent.iterdir()), ["integrity.json"]) + + doc = json.loads(out_file.read_text(encoding="utf-8")) + self.assertEqual(set(doc), EXPECTED_REPORT_KEYS) + self.assertTrue(doc["torrent_payload_passed"]) + self.assertEqual(doc["payload_count"], 2) + self.assertEqual(doc["missing"], []) + self.assertEqual(doc["size_mismatches"], []) + self.assertEqual(doc["pieces"]["issues"], []) + self.assertEqual(doc["changed_during_verification"], []) + + # Subprocess run overwrites existing report atomically; corrupt payload exits 1 cleanly. + (pkg / "b.bin").write_bytes(b"Z" * len(b"bravo-payload-5678")) + proc = _run_subprocess(str(pkg), "--output", str(out_file)) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("Payload passed: False", proc.stdout) + self.assertEqual(sorted(p.name for p in out_file.parent.iterdir()), ["integrity.json"]) + bad_doc = json.loads(out_file.read_text(encoding="utf-8")) + self.assertFalse(bad_doc["torrent_payload_passed"]) + self.assertTrue(bad_doc["pieces"]["issues"]) + + def test_inventory_and_manifest_glob_are_sorted(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pkg = root / "pkg" + _create_package(pkg) + (pkg / "m").mkdir() + for rel in ("z_extra.bin", "m/z.bin", "a_extra.bin", "m/a.bin"): + (pkg / rel).write_bytes(b"extra") + + expected_extra = ["a_extra.bin", "layout.xml", "m/a.bin", "m/z.bin", "pkg.torrent", "z_extra.bin"] + keys = list(verify_build.inventory(pkg).keys()) + self.assertEqual(keys, sorted(keys)) + self.assertEqual( + keys, + ["a_extra.bin", "b.bin", "layout.xml", "m/a.bin", "m/z.bin", "pkg.torrent", "sub/a.bin", "z_extra.bin"], + ) + + real_rglob = Path.rglob + + def reversed_rglob(path_obj, *args, **kwargs): + return reversed(list(real_rglob(path_obj, *args, **kwargs))) + + with mock.patch.object(Path, "rglob", reversed_rglob): + reversed_keys = list(verify_build.inventory(pkg).keys()) + self.assertEqual(reversed_keys, keys) + + real_glob = Path.glob + + def reversed_glob(path_obj, *args, **kwargs): + return reversed(list(real_glob(path_obj, *args, **kwargs))) + + out_file = root / "out.json" + with ( + mock.patch.object(Path, "rglob", reversed_rglob), + mock.patch.object(Path, "glob", reversed_glob), + ): + code, _, err = _run_main([str(pkg), "--output", str(out_file)]) + self.assertEqual(code, 0, err) + doc = json.loads(out_file.read_text(encoding="utf-8")) + self.assertEqual(doc["extra_disk_files"], expected_extra) + + def test_main_sys_argv_forwarding_and_script_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pkg = root / "pkg" + _create_package(pkg) + out_file = root / "entry.json" + cli_argv = [str(TOOL), str(pkg), "--output", str(out_file)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("Payload passed: True", out) + self.assertTrue(out_file.is_file()) + + out_file.unlink() + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertIn("Payload passed: True", stdout.getvalue()) + self.assertTrue(out_file.is_file()) + + +class VerifyBuildCliNegativeAndMutationTests(unittest.TestCase): + def _assert_exit_2_clean(self, argv, *, expected_fragment, check_subprocess=True): + code, _, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_argparse_errors_exit_nonzero_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pkg = root / "pkg" + _create_package(pkg) + + for argv, frag in ( + ([], "usage:"), + ([str(pkg), "--no-such-flag"], "unrecognized"), + ): + with self.subTest(argv=argv): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + verify_build.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_exit_2_clean(argv, expected_fragment=frag) + + def test_directory_regular_file_and_output_guards_kill_mutations(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pkg = root / "pkg" + _create_package(pkg) + regular_file = root / "not_a_dir.txt" + regular_file.write_text("file-content\n", encoding="utf-8") + existing_dir = root / "existing_dir" + existing_dir.mkdir() + missing_dir = root / "missing_dir" + + # 1) Regular file passed as directory rejected upfront before verify_pieces. + with mock.patch.object(verify_build, "verify_pieces") as vp_mock: + self._assert_exit_2_clean( + [str(regular_file), "--output", str(root / "never.json")], + expected_fragment="not a directory", + ) + vp_mock.assert_not_called() + + # 2) Missing directory rejected cleanly. + with mock.patch.object(verify_build, "verify_pieces") as vp_mock: + self._assert_exit_2_clean( + [str(missing_dir)], + expected_fragment="cannot read", + ) + vp_mock.assert_not_called() + + # 3) Output inside input directory rejected. + with mock.patch.object(verify_build, "verify_pieces") as vp_mock: + self._assert_exit_2_clean( + [str(pkg), "--output", str(pkg / "inside.json")], + expected_fragment="outside the input directory", + ) + vp_mock.assert_not_called() + + # 4) Output is an existing directory (including "") rejected before verify_pieces. + for bad_out in (str(existing_dir), ""): + with mock.patch.object(verify_build, "verify_pieces") as vp_mock: + self._assert_exit_2_clean( + [str(pkg), "--output", bad_out], + expected_fragment="existing directory", + check_subprocess=bool(bad_out), + ) + vp_mock.assert_not_called() + + def test_verify_pieces_and_atomic_write_os_value_errors_preserve_prior_and_leave_zero_temp_dirs(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + pkg = root / "pkg" + _create_package(pkg) + out_dir = root / "reports" + out_dir.mkdir() + out_file = out_dir / "integrity.json" + out_file.write_text("prior-report\n", encoding="utf-8") + + # 1) verify_pieces OSError & ValueError both exit 2 cleanly and preserve prior report. + for exc in (OSError("simulated read error"), ValueError("Piece count disagrees")): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(verify_build, "verify_pieces", side_effect=exc): + self._assert_exit_2_clean( + [str(pkg), "--output", str(out_file)], + expected_fragment=str(exc), + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + + # 2) os.replace OSError on pre-existing output -> prior intact, zero temp dirs. + def failing_replace(src, dst): + src_path = Path(src) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), Path(dst).parent.resolve()) + raise OSError("simulated replace failure") + + with mock.patch.object(verify_build.os, "replace", side_effect=failing_replace): + self._assert_exit_2_clean( + [str(pkg), "--output", str(out_file)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["integrity.json"]) + + # 3) os.replace OSError on fresh output -> zero files & zero temp dirs. + out_file.unlink() + with mock.patch.object(verify_build.os, "replace", side_effect=failing_replace): + self._assert_exit_2_clean( + [str(pkg), "--output", str(out_file)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), []) + + # 4) Staging write_text OSError -> os.replace never called, prior intact, zero temp dirs. + out_file.write_text("prior-report\n", encoding="utf-8") + with ( + mock.patch.object(verify_build.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated stage write failure")), + ): + self._assert_exit_2_clean( + [str(pkg), "--output", str(out_file)], + expected_fragment="simulated stage write failure", + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["integrity.json"]) + + # 5) Serialization ValueError -> os.replace never called, prior intact, zero temp dirs. + real_dumps = json.dumps + dump_calls = 0 + + def fail_second_dumps(*args, **kwargs): + nonlocal dump_calls + dump_calls += 1 + if dump_calls >= 2: + raise ValueError("simulated json value error") + return real_dumps(*args, **kwargs) + + with ( + mock.patch.object(verify_build.os, "replace") as replace_mock, + mock.patch.object(verify_build.json, "dumps", side_effect=fail_second_dumps), + ): + self._assert_exit_2_clean( + [str(pkg), "--output", str(out_file)], + expected_fragment="simulated json value error", + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["integrity.json"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/verify_build.py b/tools/verify_build.py index 3d319607e..14c345b04 100644 --- a/tools/verify_build.py +++ b/tools/verify_build.py @@ -5,6 +5,7 @@ import json import os import re +import tempfile import time import xml.etree.ElementTree as ET from datetime import datetime, timezone @@ -69,7 +70,7 @@ def read(depth=0): def inventory(root): files = {} - for path in root.rglob("*"): + for path in sorted(root.rglob("*")): if path.is_file(): name = path.relative_to(root).as_posix() stat = path.stat() @@ -179,7 +180,15 @@ def compare_layout(path, payload, disk): } -def main(argv=None): +def _write_json_atomic(destination: Path, payload: str) -> None: + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=destination.parent) as staging_dir: + staged = Path(staging_dir) / destination.name + staged.write_text(payload, encoding="utf-8") + os.replace(staged, destination) + + +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("directory", type=Path) parser.add_argument("--output", type=Path) @@ -188,12 +197,16 @@ def main(argv=None): root = args.directory.resolve(strict=True) except OSError as exc: parser.error(f"cannot read {args.directory}: {exc.strerror or exc}") - destination = args.output or Path(__file__).resolve().parents[1] / "out" / "integrity" / (root.name + ".json") + if not root.is_dir(): + parser.error(f"not a directory: {args.directory}") + destination = args.output if args.output is not None else Path(__file__).resolve().parents[1] / "out" / "integrity" / (root.name + ".json") if destination.resolve().is_relative_to(root): parser.error("Choose an output outside the input directory") + if destination.exists() and destination.is_dir(): + parser.error(f"Output path is an existing directory: {destination}") def manifest(pattern: str) -> Path: - matches = [path for path in root.glob(pattern) if path.is_file()] + matches = [path for path in sorted(root.glob(pattern)) if path.is_file()] if len(matches) != 1: parser.error(f"expected exactly one {pattern} file in {root}, found {len(matches)}") return matches[0] @@ -214,7 +227,10 @@ def manifest(pattern: str) -> Path: raise ValueError("Invalid torrent file list or piece length") except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc: parser.error(f"{torrent.name} is not a readable multi-file torrent: {type(exc).__name__}: {exc}") - before = inventory(root) + try: + before = inventory(root) + except OSError as exc: + parser.error(f"cannot scan {root}: {exc}") sizes = {p: stat[0] for p, stat in before.items()} missing = sorted(payload - sizes.keys()) wrong_size = [row | {"disk_bytes": sizes[row["path"]]} for row in entries @@ -236,15 +252,17 @@ def manifest(pattern: str) -> Path: report["pieces"] = verify_pieces(root, entries, sizes, piece_length, hashes) except ValueError as exc: parser.error(f"{torrent.name} is not a readable multi-file torrent: {exc}") - after = inventory(root) - changed = sorted(p for p in before.keys() | after.keys() if before.get(p) != after.get(p)) - report["changed_during_verification"] = changed - report["torrent_payload_passed"] = not (missing or wrong_size or report["pieces"]["issues"] or changed) - report["finished_utc"] = datetime.now(timezone.utc).isoformat() - destination.parent.mkdir(parents=True, exist_ok=True) - temporary = destination.with_suffix(f".{os.getpid()}.tmp") - temporary.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - temporary.replace(destination) + except OSError as exc: + parser.error(f"cannot verify torrent pieces: {exc}") + try: + after = inventory(root) + changed = sorted(p for p in before.keys() | after.keys() if before.get(p) != after.get(p)) + report["changed_during_verification"] = changed + report["torrent_payload_passed"] = not (missing or wrong_size or report["pieces"]["issues"] or changed) + report["finished_utc"] = datetime.now(timezone.utc).isoformat() + _write_json_atomic(destination, json.dumps(report, indent=2, ensure_ascii=False) + "\n") + except (OSError, ValueError) as exc: + parser.error(f"cannot write report {destination}: {exc}") print(f"Payload passed: {report['torrent_payload_passed']} | Report: {destination}", flush=True) return 0 if report["torrent_payload_passed"] else 1 From d3702a1ab13f00c06bbc815017122952051e4e52 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:27:13 +0200 Subject: [PATCH 206/232] pe: extract main(argv) and add directory and struct.error guards in pe_authentihash with CLI suite (#2593) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/pe_authentihash_cli_check.py | 290 +++++++++++++++++++++++++++++ tools/pe_authentihash.py | 13 +- 3 files changed, 301 insertions(+), 4 deletions(-) create mode 100644 tests/pe_authentihash_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index bfd130961..148a66e85 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8700,6 +8700,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME pe_authentihash_oracle COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pe_authentihash_oracle_check.py" "$<TARGET_FILE:xmem_shim>") set_tests_properties(pe_authentihash_oracle PROPERTIES SKIP_RETURN_CODE 77) + add_test(NAME pe_authentihash_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pe_authentihash_cli_check.py") add_test(NAME script_dispatch_pairs COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/script_dispatch_check.py" "$<TARGET_FILE:script_path_host>") add_test(NAME script_state_probe_checks COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/pe_authentihash_cli_check.py b/tests/pe_authentihash_cli_check.py new file mode 100644 index 000000000..9a83b9ba5 --- /dev/null +++ b/tests/pe_authentihash_cli_check.py @@ -0,0 +1,290 @@ +"""CLI, read-only, mmap fallback, directory/struct.error guard, and mutation suite for tools/pe_authentihash.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "pe_authentihash.py" +sys.path.insert(0, str(ROOT / "tools")) + +import pe_authentihash # noqa: E402 + +HEADERS = 0x200 +PE_AT = 0x40 +OPTIONAL = PE_AT + 24 +CHECKSUM = OPTIONAL + 64 +CERT_CONTENT = bytes((7 * i + 3) % 256 for i in range(48)) + + +def _build_pe(*, plus: bool, cert: bytes | None = None) -> bytes: + optional_size = 240 if plus else 224 + dirs_at = OPTIONAL + (112 if plus else 96) + bodies = [bytes((i * 13 + k) % 251 for i in range(0x200 * (k + 1))) for k in range(2)] + image = bytearray(bytes((i * 5 + 1) % 253 for i in range(HEADERS))) + image[0:2] = b"MZ" + struct.pack_into("<I", image, 0x3C, PE_AT) + image[PE_AT:PE_AT + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", image, PE_AT + 4, 0x8664, 2, 0, 0, 0, optional_size, 0x2022) + struct.pack_into("<H", image, OPTIONAL, 0x20B if plus else 0x10B) + struct.pack_into("<II", image, OPTIONAL + 32, 0x1000, 0x200) + struct.pack_into("<I", image, OPTIONAL + 56, 0x3000) + struct.pack_into("<I", image, CHECKSUM, 0x11223344) + struct.pack_into("<H", image, OPTIONAL + 68, 3) + struct.pack_into("<I", image, OPTIONAL + 60, HEADERS) + struct.pack_into("<I", image, dirs_at - 4, 16) + struct.pack_into("<II", image, dirs_at + 8 * 4, 0, 0) + section_table = OPTIONAL + optional_size + pointer = HEADERS + for k, body in enumerate(bodies): + row = bytearray(40) + row[0:8] = f".s{k}".encode().ljust(8, b"\0") + struct.pack_into("<IIII", row, 8, len(body), 0x1000 * (k + 1), len(body), pointer) + image[section_table + 40 * k:section_table + 40 * (k + 1)] = row + pointer += len(body) + image += b"".join(bodies) + if cert is not None: + struct.pack_into("<II", image, dirs_at + 32, len(image), len(cert)) + image += cert + return bytes(image) + + +def _reference_digest(image: bytes, *, plus: bool, cert_len: int = 0) -> str: + cert_entry = OPTIONAL + (112 if plus else 96) + 32 + end = len(image) - cert_len + parts = [ + image[:CHECKSUM], + image[CHECKSUM + 4:cert_entry], + image[cert_entry + 8:HEADERS], + image[HEADERS:end], + ] + return hashlib.sha256(b"".join(parts)).hexdigest() + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = pe_authentihash.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=30, + ) + + +class PeAuthentihashCliPositiveTests(unittest.TestCase): + def test_pe32_pe32plus_and_signed_cert_table_readonly_digests(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + cases = [ + ("pe32.exe", False, None), + ("pe32plus.exe", True, None), + ("pe32_signed.exe", False, CERT_CONTENT), + ("pe32plus_signed.exe", True, CERT_CONTENT), + ] + digests = {} + for name, plus, cert in cases: + raw = _build_pe(plus=plus, cert=cert) + expected = _reference_digest(raw, plus=plus, cert_len=len(cert) if cert else 0) + img = root / name + img.write_bytes(raw) + + code, out, err = _run_main([str(img)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(out.strip(), expected) + self.assertEqual(len(out.strip()), 64) + self.assertEqual(img.read_bytes(), raw) + + proc = _run_subprocess(str(img)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(proc.stdout.strip(), expected) + self.assertEqual(img.read_bytes(), raw) + digests[name] = out.strip() + + self.assertEqual(digests["pe32.exe"], digests["pe32_signed.exe"]) + self.assertEqual(digests["pe32plus.exe"], digests["pe32plus_signed.exe"]) + self.assertEqual( + sorted(p.name for p in root.iterdir()), + ["pe32.exe", "pe32_signed.exe", "pe32plus.exe", "pe32plus_signed.exe"], + ) + + def test_main_sys_argv_forwarding_and_script_entrypoint(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + raw = _build_pe(plus=True, cert=CERT_CONTENT) + expected = _reference_digest(raw, plus=True, cert_len=len(CERT_CONTENT)) + img = root / "entry.exe" + img.write_bytes(raw) + cli_argv = [str(TOOL), str(img)] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(out.strip(), expected) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(stdout.getvalue().strip(), expected) + + +class PeAuthentihashCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_code=1, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_argparse_errors_exit_nonzero_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + img = root / "pe.exe" + img.write_bytes(_build_pe(plus=True)) + + for argv, frag in ( + ([], "usage:"), + ([str(img), "--unknown-flag"], "unrecognized"), + ): + with self.subTest(argv=argv): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + pe_authentihash.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_clean_failure(argv, expected_code=2, expected_fragment=frag) + + def test_directory_missing_empty_and_truncated_inputs_exit_1_cleanly(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub_dir = root / "sub_dir" + sub_dir.mkdir() + missing = root / "missing.exe" + empty = root / "empty.exe" + empty.write_bytes(b"") + truncated = root / "truncated.exe" + truncated.write_bytes(_build_pe(plus=True)[:0x150]) + + # 1) Directory (including "") rejected upfront before authentihash(). + for bad_dir in (str(sub_dir), ""): + with mock.patch.object(pe_authentihash, "authentihash") as hash_mock: + self._assert_clean_failure( + [bad_dir], + expected_fragment="directory", + check_subprocess=bool(bad_dir), + ) + hash_mock.assert_not_called() + + # 2) Missing file rejected upfront before authentihash(). + with mock.patch.object(pe_authentihash, "authentihash") as hash_mock: + self._assert_clean_failure( + [str(missing)], + expected_fragment=f"{missing}:", + ) + hash_mock.assert_not_called() + + # 3) Non-regular file (is_file() False) rejected upfront before authentihash(). + with ( + mock.patch.object(Path, "is_dir", return_value=False), + mock.patch.object(Path, "is_file", return_value=False), + mock.patch.object(pe_authentihash, "authentihash") as hash_mock, + ): + self._assert_clean_failure( + [str(empty)], + expected_fragment="regular file", + check_subprocess=False, + ) + hash_mock.assert_not_called() + + # 4) 0-byte file exercises mmap ValueError fallback cleanly -> empty memoryview -> exit 1. + self._assert_clean_failure( + [str(empty)], + expected_fragment=f"{empty}: Not a PE file: missing MZ header", + ) + seen_views = [] + + def check_empty_view(view): + seen_views.append(bytes(view)) + return "0" * 64 + + with mock.patch.object(pe_authentihash, "authentihash", side_effect=check_empty_view): + code_0, out_0, err_0 = _run_main([str(empty)]) + self.assertEqual(code_0, 0, err_0) + self.assertEqual(out_0.strip(), "0" * 64) + self.assertEqual(seen_views, [b""]) + + # 5) Truncated PE rejected cleanly with exit 1 and zero traceback. + self._assert_clean_failure( + [str(truncated)], + expected_fragment=f"{truncated}:", + ) + + self.assertEqual( + sorted(p.name for p in root.iterdir()), + ["empty.exe", "sub_dir", "truncated.exe"], + ) + + def test_os_value_and_struct_errors_caught_cleanly_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + img = root / "sample.exe" + img.write_bytes(_build_pe(plus=False)) + + for exc in ( + OSError("simulated io failure"), + ValueError("simulated value failure"), + struct.error("unpack_from requires a buffer of at least 4 bytes"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(pe_authentihash, "authentihash", side_effect=exc): + self._assert_clean_failure( + [str(img)], + expected_fragment=f"{img}: {exc}", + check_subprocess=False, + ) + + with mock.patch.object(Path, "open", side_effect=OSError("simulated open failure")): + self._assert_clean_failure( + [str(img)], + expected_fragment=f"{img}: simulated open failure", + check_subprocess=False, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/pe_authentihash.py b/tools/pe_authentihash.py index 36d26293d..7e3bdf006 100644 --- a/tools/pe_authentihash.py +++ b/tools/pe_authentihash.py @@ -107,11 +107,15 @@ def authentihash(data: "bytes | memoryview") -> str: return digest.hexdigest() -def main() -> None: +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("image", type=Path) - args = parser.parse_args() + args = parser.parse_args(argv) try: + if args.image.is_dir(): + raise ValueError(f"expected a regular file, got directory: {args.image}") + if not args.image.is_file(): + raise ValueError(f"expected a regular file: {args.image}") with args.image.open("rb") as stream: try: mapped = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) @@ -124,10 +128,11 @@ def main() -> None: view.release() if mapped: mapped.close() - except (OSError, ValueError) as error: + except (OSError, ValueError, struct.error) as error: parser.exit(1, f"{args.image}: {error}\n") print(digest) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From 1652cee184005f94be355dd3cc636884011e2bfd Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:27:28 +0200 Subject: [PATCH 207/232] runtime: extract main(argv=None) and harden atomic publish and path/IO guards in shader_cache_rekey with CLI suite (#2594) --- CMakeLists.txt | 2 + tests/startup_shader_cache_rekey_cli_check.py | 269 ++++++++++++++++++ tools/startup/shader_cache_rekey.py | 67 +++-- 3 files changed, 314 insertions(+), 24 deletions(-) create mode 100644 tests/startup_shader_cache_rekey_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 148a66e85..ba357cff1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4073,6 +4073,8 @@ if(EXISTS "${INTAKE_PYTHON}") # Offline re-key of saved shader requests under the current cache revision (pure Python). add_test(NAME startup_shader_cache_rekey COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_check.py") + add_test(NAME runtime_shader_cache_rekey_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_shader_cache_rekey_cli_check.py") # Partial colour exports carry their channel mask to the manifest; compressed exports of whole pairs lower (#1674). add_test(NAME startup_gfx2hlsl_export_mask COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_export_mask_check.py") diff --git a/tests/startup_shader_cache_rekey_cli_check.py b/tests/startup_shader_cache_rekey_cli_check.py new file mode 100644 index 000000000..c8bee38eb --- /dev/null +++ b/tests/startup_shader_cache_rekey_cli_check.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, atomic-publish, and error-guard suite for tools/startup/shader_cache_rekey.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_STARTUP = ROOT / "tools" / "startup" +TOOL = TOOLS_STARTUP / "shader_cache_rekey.py" +sys.path.insert(0, str(TOOLS_STARTUP)) +import gfx2hlsl # noqa: E402 +import shader_cache_rekey as rekey_tool # noqa: E402 + + +def _write_synthetic_cache(src: Path) -> dict[str, int]: + """Populate src with valid graphics, compute, RTV, and mesh request fixtures.""" + src.mkdir(parents=True, exist_ok=True) + vs = struct.pack("<4I", 0x7E000280, 0x01020304, 1, 0xBF810000) + ps = struct.pack("<3I", 0x7E020281, 7, 0xBF810000) + root = b"RTS0 synthetic root" + ia = b"synthetic layout" + g_key = gfx2hlsl.pipeline_key(vs, ps, root, ia) + for ext, blob in ((".a", vs), (".b", ps), (".root", root), (".ia", ia)): + (src / f"req_{g_key:016x}{ext}").write_bytes(blob) + + c_parts = { + ".desc": struct.pack("<12Q", *range(12)), + ".sa": struct.pack("<7I", *range(7)), + ".sb": b"\x05" * 20, + ".data": struct.pack("<2Q", 0x1122334455667788, 0x99), + ".root": b"RTS0 compute root", + ".c67": struct.pack("<2I", 0x7E020280, 0xBF810000), + } + c_key = gfx2hlsl.compute_key( + c_parts[".c67"], + c_parts[".data"], + c_parts[".root"], + c_parts[".desc"], + c_parts[".sa"], + c_parts[".sb"], + ) + for ext, blob in c_parts.items(): + (src / f"req_{c_key:016x}{ext}").write_bytes(blob) + + rtv_body = f"rtv1 {g_key} 28 87".encode("ascii") + rtv_key = gfx2hlsl.fnv(rtv_body) + (src / f"req_{rtv_key:016x}.rtv").write_bytes(rtv_body) + (src / "req_0123456789abcdef.m86").write_bytes(b"\x01" * 8) + return {"g": g_key, "c": c_key, "rtv": rtv_key} + + +def _run_main(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + rc = rekey_tool.main(argv) + return rc, stdout.getvalue(), stderr.getvalue() + + +class ShaderCacheRekeyCliTests(unittest.TestCase): + def test_positive_main_argv_none_and_subprocess(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + src = base / "src_cache" + dst_argv = base / "dst_argv" + dst_none = base / "dst_none" + dst_sub = base / "dst_sub" + keys = _write_synthetic_cache(src) + + # Explicit argv -> 0 with X2W_TRANSLATE_JOBS=1 to keep in-process test fast. + with mock.patch.dict(os.environ, {"X2W_TRANSLATE_JOBS": "1"}): + rc, stdout, stderr = _run_main([str(src), str(dst_argv)]) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn("m57 0, m86 1", stdout) + expected_names = sorted([ + f"req_{keys['g']:016x}.a", + f"req_{keys['g']:016x}.b", + f"req_{keys['g']:016x}.root", + f"req_{keys['g']:016x}.ia", + f"req_{keys['c']:016x}.desc", + f"req_{keys['c']:016x}.sa", + f"req_{keys['c']:016x}.sb", + f"req_{keys['c']:016x}.data", + f"req_{keys['c']:016x}.root", + f"req_{keys['c']:016x}.c67", + f"req_{keys['rtv']:016x}.rtv", + ]) + self.assertEqual(sorted(p.name for p in dst_argv.iterdir()), expected_names) + + # main(None) uses sys.argv[1:]. + with ( + mock.patch.dict(os.environ, {"X2W_TRANSLATE_JOBS": "1"}), + mock.patch.object(sys, "argv", ["shader_cache_rekey.py", str(src), str(dst_none)]), + ): + rc, stdout, stderr = _run_main(None) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertEqual(sorted(p.name for p in dst_none.iterdir()), expected_names) + + # Subprocess positive smoke test. + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(src), str(dst_sub)], + env={**os.environ, "X2W_TRANSLATE_JOBS": "1"}, + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("m57 0, m86 1", proc.stdout) + self.assertEqual(sorted(p.name for p in dst_sub.iterdir()), expected_names) + + def test_usage_and_path_guards(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + src = base / "src" + _write_synthetic_cache(src) + reg_file = base / "regular.txt" + reg_file.write_text("keep-me", encoding="utf-8") + + # Usage errors -> exit 2 without traceback. + for argv in ([], ["only_one"], ["--help", str(base)]): + with self.subTest(argv=argv): + rc, stdout, stderr = _run_main(argv) + self.assertEqual(rc, 2) + self.assertEqual(stdout, "") + self.assertIn("usage:", stderr) + self.assertNotIn("Traceback", stderr) + + # Invalid src (missing / regular file), samefile, and regular-file dst -> exit 2. + for label, bad_src, bad_dst in ( + ("missing_src", base / "missing_src", base / "out1"), + ("file_src", reg_file, base / "out2"), + ("same_dir", src, src), + ("file_dst", src, reg_file), + ): + with self.subTest(case=label): + rc, stdout, stderr = _run_main([str(bad_src), str(bad_dst)]) + self.assertEqual(rc, 2) + self.assertEqual(stdout, "") + self.assertIn("error:", stderr) + self.assertNotIn("Traceback", stderr) + self.assertEqual(reg_file.read_text(encoding="utf-8"), "keep-me") + + def test_io_error_guards_in_rekey(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + src = base / "src" + dst = base / "dst" + _write_synthetic_cache(src) + + # os.listdir(src) OSError -> exit 1 without traceback. + with mock.patch.object(rekey_tool.os, "listdir", side_effect=OSError("listdir denied")): + rc, _, stderr = _run_main([str(src), str(dst)]) + self.assertEqual(rc, 1) + self.assertIn("listdir denied", stderr) + self.assertNotIn("Traceback", stderr) + + # os.makedirs(dst) OSError -> exit 1 without traceback. + with ( + mock.patch.dict(os.environ, {"X2W_TRANSLATE_JOBS": "1"}), + mock.patch.object(rekey_tool.os, "makedirs", side_effect=OSError("mkdir denied")), + ): + rc, _, stderr = _run_main([str(src), str(dst)]) + self.assertEqual(rc, 1) + self.assertIn("mkdir denied", stderr) + self.assertNotIn("Traceback", stderr) + + # Second-pass read_parts() OSError -> exit 1 without traceback. + real_read_parts = rekey_tool.read_parts + calls = {"count": 0} + + def fail_second_pass(directory, kind, key): + calls["count"] += 1 + if calls["count"] > 2: + raise OSError("second-pass read failed") + return real_read_parts(directory, kind, key) + + with ( + mock.patch.dict(os.environ, {"X2W_TRANSLATE_JOBS": "1"}), + mock.patch.object(rekey_tool, "read_parts", side_effect=fail_second_pass), + ): + rc, _, stderr = _run_main([str(src), str(dst)]) + self.assertEqual(rc, 1) + self.assertIn("second-pass read failed", stderr) + self.assertNotIn("Traceback", stderr) + + # publish() OSError -> exit 1 without traceback. + with ( + mock.patch.dict(os.environ, {"X2W_TRANSLATE_JOBS": "1"}), + mock.patch.object(rekey_tool, "publish", side_effect=OSError("publish io failed")), + ): + rc, _, stderr = _run_main([str(src), str(dst)]) + self.assertEqual(rc, 1) + self.assertIn("publish io failed", stderr) + self.assertNotIn("Traceback", stderr) + + def test_atomic_publish_cleanup_and_preservation(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + out_dir = base / "out" + out_dir.mkdir() + existing = out_dir / "existing.bin" + existing.write_bytes(b"original-bytes") + fresh = out_dir / "fresh.bin" + + stats = {"written": 0, "kept": 0} + # Existing target is kept without creating temp artifacts. + rekey_tool.publish(str(existing), b"new-bytes", stats) + self.assertEqual(stats, {"written": 0, "kept": 1}) + self.assertEqual(existing.read_bytes(), b"original-bytes") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["existing.bin"]) + + # Fresh target succeeds with zero temp artifacts left behind. + rekey_tool.publish(str(fresh), b"payload", stats) + self.assertEqual(stats, {"written": 1, "kept": 1}) + self.assertEqual(fresh.read_bytes(), b"payload") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["existing.bin", "fresh.bin"]) + + # os.replace failure cleans up TemporaryDirectory and leaves zero temp artifacts. + failing = out_dir / "failing.bin" + with mock.patch.object(rekey_tool.os, "replace", side_effect=OSError("replace boom")): + with self.assertRaisesRegex(OSError, "replace boom"): + rekey_tool.publish(str(failing), b"never", stats) + self.assertFalse(failing.exists()) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["existing.bin", "fresh.bin"]) + self.assertEqual(existing.read_bytes(), b"original-bytes") + + # Same failure through main() exits 1 cleanly with zero temp artifacts. + src = base / "src" + _write_synthetic_cache(src) + dst_rekey = base / "dst_rekey" + dst_rekey.mkdir() + sentinel = dst_rekey / "sentinel.txt" + sentinel.write_text("preserved", encoding="utf-8") + with ( + mock.patch.dict(os.environ, {"X2W_TRANSLATE_JOBS": "1"}), + mock.patch.object(rekey_tool.os, "replace", side_effect=OSError("disk full")), + ): + rc, _, stderr = _run_main([str(src), str(dst_rekey)]) + self.assertEqual(rc, 1) + self.assertIn("disk full", stderr) + self.assertNotIn("Traceback", stderr) + self.assertEqual(sorted(p.name for p in dst_rekey.iterdir()), ["sentinel.txt"]) + self.assertEqual(sentinel.read_text(encoding="utf-8"), "preserved") + + # Subprocess negative smoke test (regular-file dst -> exit 2). + proc = subprocess.run( + [sys.executable, "-B", str(TOOL), str(src), str(sentinel)], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 2) + self.assertIn("not a directory", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/startup/shader_cache_rekey.py b/tools/startup/shader_cache_rekey.py index 24585fb55..2e49127a8 100644 --- a/tools/startup/shader_cache_rekey.py +++ b/tools/startup/shader_cache_rekey.py @@ -22,6 +22,7 @@ import os import re import sys +import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import gfx2hlsl as g # noqa: E402 @@ -86,28 +87,37 @@ def publish(path, data, stats): if os.path.exists(path): stats['kept'] += 1 return - tmp = path + '.tmp' - try: + target = os.path.abspath(path) + parent = os.path.dirname(target) + name = os.path.basename(target) + with tempfile.TemporaryDirectory(prefix='.%s.' % name, dir=parent) as tmp_dir: + tmp = os.path.join(tmp_dir, name) with open(tmp, 'wb') as file: file.write(data) os.replace(tmp, path) - except BaseException: - if os.path.exists(tmp): - os.remove(tmp) - raise stats['written'] += 1 -def rekey(src, dst, jobs=None, out=sys.stdout): +def rekey(src, dst, jobs=None, out=None): """Re-key the requests of src into dst; return the exit code.""" + if out is None: + out = sys.stdout if not os.path.isdir(src): print('error: %s is not a directory' % src, file=sys.stderr) return 2 + if os.path.exists(dst) and not os.path.isdir(dst): + print('error: %s is not a directory' % dst, file=sys.stderr) + return 2 if os.path.exists(dst) and os.path.samefile(src, dst): print('error: the new request dir must not be the old cache', file=sys.stderr) return 2 found = {'g': [], 'c': [], 'rtv': [], 'm57': 0, 'm86': 0} - for name in sorted(os.listdir(src)): + try: + entries = sorted(os.listdir(src)) + except OSError as error: + print('error: cannot list %s: %s' % (src, error), file=sys.stderr) + return 1 + for name in entries: m = REQUEST.fullmatch(name) if not m: continue @@ -148,28 +158,37 @@ def rekey(src, dst, jobs=None, out=sys.stdout): print(' ' + line, file=sys.stderr) return 1 - os.makedirs(dst, exist_ok=True) + try: + os.makedirs(dst, exist_ok=True) + except OSError as error: + print('error: cannot create %s: %s' % (dst, error), file=sys.stderr) + return 1 stats = {'written': 0, 'kept': 0} - for kind, label in (('g', 'graphics'), ('c', 'compute')): - done = set() - for old, key in sorted(new[kind].items()): - if key in done: # requests of the same pipeline from several revisions - continue - done.add(key) - # Read again, not checked against the hashing pass: nothing may write the old cache meanwhile. - for ext, data in read_parts(src, kind, old).items(): - publish(request_name(dst, key, ext), data, stats) - current = sum(old == key for old, key in new[kind].items()) - print('%s: %d requests, %d already current -> %d keys' % (label, len(new[kind]), current, len(done)), file=out) - for key, text in sorted(rtv.items()): - publish(request_name(dst, key, '.rtv'), text.encode('ascii'), stats) + try: + for kind, label in (('g', 'graphics'), ('c', 'compute')): + done = set() + for old, key in sorted(new[kind].items()): + if key in done: # requests of the same pipeline from several revisions + continue + done.add(key) + # Read again, not checked against the hashing pass: nothing may write the old cache meanwhile. + for ext, data in read_parts(src, kind, old).items(): + publish(request_name(dst, key, ext), data, stats) + current = sum(old == key for old, key in new[kind].items()) + print('%s: %d requests, %d already current -> %d keys' % (label, len(new[kind]), current, len(done)), file=out) + for key, text in sorted(rtv.items()): + publish(request_name(dst, key, '.rtv'), text.encode('ascii'), stats) + except OSError as error: + print('error: failed writing %s: %s' % (dst, error), file=sys.stderr) + return 1 print('rtv variants: %d requests -> %d keys' % (len(found['rtv']), len(rtv)), file=out) print('not re-keyed (own key strings): m57 %d, m86 %d' % (found['m57'], found['m86']), file=out) print('files: %d written, %d already present in %s' % (stats['written'], stats['kept'], dst), file=out) return 0 -def main(argv): +def main(argv=None) -> int: + argv = sys.argv[1:] if argv is None else argv if len(argv) != 2 or argv[0].startswith('-'): print(__doc__.split('\n\n')[1], file=sys.stderr) return 2 @@ -177,4 +196,4 @@ def main(argv): if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) + raise SystemExit(main()) From a0c810c7e404b137cf5ad3218b2579acb5e3535f Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:27:41 +0100 Subject: [PATCH 208/232] tests: run six descriptor load format launches at once (#2568) * tests: run six descriptor load format launches at once * test: drop stale launch counts from comment --- tests/compute_load_format_check.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/compute_load_format_check.py b/tests/compute_load_format_check.py index f975fd1bd..bdaa9eca3 100644 --- a/tests/compute_load_format_check.py +++ b/tests/compute_load_format_check.py @@ -225,6 +225,8 @@ def program(): ("SNORM without the clamp", ("snorm unclamped",)), ("SINT16 zero-extended", ("sint zero-extended",)), ("FLOAT16 halves swapped", ("swap halves",)), ("FLOAT16 denormals flushed", ("flush halves",)), ("legacy format ignored", ("legacy ignored",)), ("neighbouring element", ("neighbour element",))) +# Independent launches (the mutation ones also compile a mutated source); the Win2025 slots have 11 vCPUs. +LAUNCH_THREADS = 6 FIXED = f"{aot.DESCRIPTOR_LEGACY_FIXED:#x}u" # label, old, new, and the run it must fail: None for the valid two-group run, else an INVALID index. MUTATIONS = ( @@ -377,7 +379,7 @@ def invalid_formats(number): else: add("mutation", label, 2, unwritten, invalid_formats(run_index), mutated=mutated) - with ThreadPoolExecutor(max_workers=min(4, os.cpu_count() or 1)) as pool: + with ThreadPoolExecutor(max_workers=min(LAUNCH_THREADS, os.cpu_count() or 1)) as pool: results = list(pool.map(lambda item: run(*item), enumerate(jobs))) for (check, label, extra, _data, _mutated), result in zip(jobs, results): if check == "pass": From 4ce2931d1fcf606ca4a6e315f5513362f84ff547 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:28:50 +0100 Subject: [PATCH 209/232] feat: record compute root signature and descriptor tables (list slots 33 and 35) (#1803) * feat: record the compute root signature and descriptor tables (slots 33 and 35) Header-only state in list_compute_root.h with a Linux-testable check. Dispatch (slot 14) is not handled here; the state is exposed through ready() and table() for it. Refs #870. * feat: record compute descriptor tables (slot 35) and clear them on a root or heap change --------- Co-authored-by: tedin7 <tedin7@users.noreply.github.com> --- CMakeLists.txt | 6 ++ src/startup_stubs/d3d12_draw.inl | 32 +++++++++-- src/startup_stubs/d3d12_xs_device.cpp | 4 ++ src/startup_stubs/list_compute_root.h | 55 ++++++++++++++++++ tests/startup_compute_root.cpp | 82 +++++++++++++++++++++++++++ 5 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 src/startup_stubs/list_compute_root.h create mode 100644 tests/startup_compute_root.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ba357cff1..95d592512 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2114,6 +2114,12 @@ add_executable(startup_logical_view_table_check tests/startup_logical_view_table target_include_directories(startup_logical_view_table_check PRIVATE src) target_compile_features(startup_logical_view_table_check PRIVATE cxx_std_17) add_test(NAME startup_logical_view_table COMMAND startup_logical_view_table_check) +# Compute descriptor tables (command-list slot 35, src/startup_stubs/list_compute_root.h): a table at a nonzero +# descriptor offset, a wrong handle, clear on a different signature or a view heap change, range limit. +add_executable(startup_compute_root tests/startup_compute_root.cpp) +target_include_directories(startup_compute_root PRIVATE src) +target_compile_features(startup_compute_root PRIVATE cxx_std_17) +add_test(NAME startup_compute_root COMMAND startup_compute_root) # Local switch, logging, and page-probe helpers (src/startup_stubs/local_log.h, #1149). add_executable(startup_local_log_check tests/startup_local_log_check.cpp) target_include_directories(startup_local_log_check PRIVATE src) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 8c3ee62f2..16aa47bd0 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2403,17 +2403,17 @@ void __stdcall list_set_descriptor_heaps(Wrapper* self, UINT count, void* const* } auto& pass = pass_of(self); if (pass.source_view_heap != view_heap) + { for (auto& table : pass.view_tables) table = {}; + pass.compute_tables.clear(); + } pass.source_view_heap = view_heap; pass.title_samplers = source; } -// List slot 36 (desktop 32 + 4), SetGraphicsRootDescriptorTable(parameter, GPU handle): the table's -// address in the title's descriptor memory is kept for the draw. -void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) +// The table at a title GPU handle, looked up in the title's view heap (the one set by slot 32 when known). +x2w_startup::ViewTable resolve_title_table(const Pass& pass, u64 gpu_handle) { - if (parameter >= 16) return; - auto& pass = pass_of(self); x2w_startup::ViewTable table; AcquireSRWLockShared(¬e_lock); for (const HeapInfo& heap : heap_infos()) { @@ -2424,7 +2424,27 @@ void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) if (table.address) break; } ReleaseSRWLockShared(¬e_lock); - pass.view_tables[parameter] = table; + return table; +} + +// List slot 36 (desktop 32 + 4), SetGraphicsRootDescriptorTable(parameter, GPU handle): the table's +// address in the title's descriptor memory is kept for the draw. +void __stdcall list_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + if (parameter >= 16) return; + auto& pass = pass_of(self); + pass.view_tables[parameter] = resolve_title_table(pass, gpu_handle); +} +// List slot 35 (desktop 31 + 4), SetComputeRootDescriptorTable(parameter, GPU handle). Recorded only for a later +// Dispatch; slot 33 keeps the desktop compute root bind. +void __stdcall list_compute_table(Wrapper* self, UINT parameter, u64 gpu_handle) +{ + static LONG dropped; + if (!self->own().list_open) return; + auto& pass = pass_of(self); + if (!pass.compute_tables.set_table(parameter, resolve_title_table(pass, gpu_handle)) && first_calls(dropped, 4)) + log("x2w-render compute descriptor table dropped: parameter %u (%u parameters are kept)", parameter, + x2w_startup::ComputeTables::max_parameters); } // List slot 40 (desktop 36 + 4), SetGraphicsRoot32BitConstants(parameter, count, data, offset). void __stdcall list_root_constants(Wrapper* self, UINT parameter, UINT count, const std::uint32_t* data, UINT offset) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 44ca60da1..292937af1 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -17,6 +17,7 @@ #include "xmem_page_batch.h" #include "startup_stubs/local_log.h" #include "startup_stubs/logical_view_table.h" +#include "startup_stubs/list_compute_root.h" #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/draw_dump_tracking.h" @@ -2358,6 +2359,7 @@ struct Pass { const std::vector<RootParameter>* requested_mesh_root = nullptr; UINT topology = 0; x2w_startup::ViewTable view_tables[16]{}; + x2w_startup::ComputeTables compute_tables; // slot 35, read by a Dispatch handler u64 source_view_heap = 0; u64 root_address[16] = {}; // title address of each root descriptor std::uint32_t constants[16][8] = {}; @@ -2561,6 +2563,7 @@ void __stdcall list_compute_root(Wrapper* self, void* root) Pass& pass = pass_of(self); const bool real = w && w->own().kind == root_signature_kind && w->own().real && !root_heap_flags(w); pass.compute_root = real ? static_cast<ID3D12RootSignature*>(w->own().real) : nullptr; + pass.compute_tables.set_signature(w ? root_info(w) : nullptr); // a different signature leaves no table bound pass.compute_params = real ? root_info(w) : nullptr; if (compute_binding_trace_enabled() && (!pass.compute_trace || pass.compute_trace->root != w)) { pass.compute_trace = std::make_unique<ComputeBindingTrace>(); @@ -6106,6 +6109,7 @@ void build_tables() list_typed[42] = reinterpret_cast<ListTyped>(&list_root_cbv); list_typed[50] = reinterpret_cast<ListTyped>(&list_targets); list_typed[13] = reinterpret_cast<ListTyped>(&list_draw_indexed); + list_typed[35] = reinterpret_cast<ListTyped>(&list_compute_table); list_typed[36] = reinterpret_cast<ListTyped>(&list_table); list_typed[40] = reinterpret_cast<ListTyped>(&list_root_constants); list_typed[47] = reinterpret_cast<ListTyped>(&list_index_buffer); diff --git a/src/startup_stubs/list_compute_root.h b/src/startup_stubs/list_compute_root.h new file mode 100644 index 000000000..6e5d89c46 --- /dev/null +++ b/src/startup_stubs/list_compute_root.h @@ -0,0 +1,55 @@ +#pragma once + +// Descriptor tables of the compute root of one command list: command-list slot 35 (desktop 31 + 4, +// SetComputeRootDescriptorTable). Slot 33 (SetComputeRootSignature) keeps its own desktop bind; it only tells this +// state which root signature is current. Tables are recorded for a later Dispatch handler and are not forwarded. +// +// The rules follow the graphics side (slots 34 and 36): setting the root signature that is already set keeps the +// tables, setting a different one (or none) leaves no table bound, and so does a change of the title's view heap. +// A parameter past the kept range is refused and counted. + +#include <cstdint> + +#include "startup_stubs/logical_view_table.h" + +namespace x2w_startup { + +class ComputeTables { +public: + static constexpr unsigned max_parameters = 16; // same range as the graphics tables + + // The root signature is identified by any stable pointer (the title wrapper's parameter list); null clears it. + void set_signature(const void* signature) + { + if (signature != signature_) clear(); + signature_ = signature; + } + + // Slot 32 with another view heap: the recorded addresses belong to the old one. + void clear() + { + for (auto& table : tables_) table = {}; + } + + // False when the parameter is out of range (counted). + bool set_table(unsigned parameter, const ViewTable& table) + { + if (parameter >= max_parameters) { + ++out_of_range_; + return false; + } + tables_[parameter] = table; + return true; + } + + const void* signature() const { return signature_; } + ViewTable table(unsigned parameter) const { return parameter < max_parameters ? tables_[parameter] : ViewTable{}; } + std::uint32_t out_of_range_count() const { return out_of_range_; } + +private: + const void* signature_ = nullptr; + ViewTable tables_[max_parameters] = {}; + std::uint32_t out_of_range_ = 0; +}; + +} // namespace x2w_startup diff --git a/tests/startup_compute_root.cpp b/tests/startup_compute_root.cpp new file mode 100644 index 000000000..b31cd9bcc --- /dev/null +++ b/tests/startup_compute_root.cpp @@ -0,0 +1,82 @@ +// Checks src/startup_stubs/list_compute_root.h without a device: the descriptor tables slot 35 records for a +// compute Dispatch, resolved against a title view heap the way the graphics tables are (slot 36). +#include "startup_stubs/list_compute_root.h" + +#include <cstdint> +#include <cstdio> + +namespace { +using x2w_startup::ComputeTables; +using x2w_startup::ViewTable; +using x2w_startup::resolve_view_table; +int failures; + +void check(bool ok, const char* name) +{ + if (!ok) { + std::printf("FAIL %s\n", name); + ++failures; + } +} + +// A title heap of 8 descriptors of 32 bytes: GPU base 0x10000, CPU base 0x7000. +constexpr std::uint64_t gpu_base = 0x10000, cpu_base = 0x7000; +constexpr unsigned count = 8, stride = 32; +ViewTable at(unsigned descriptor) { return resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base + std::uint64_t{descriptor} * stride); } +} // namespace + +int main() +{ + int root_a = 0, root_b = 0; + + { + // A UAV table at a nonzero descriptor offset resolves to that offset, not to the heap start. + ComputeTables s; + s.set_signature(&root_a); + check(s.set_table(2, at(3)), "table set"); + check(s.table(2).address == cpu_base + 3 * stride && s.table(2).bytes == 5 * stride, "slot 35 keeps the offset table"); + check(s.table(2).address != at(0).address, "a nonzero offset is not the default table"); + check(s.table(3).address == 0, "an unset parameter has no table"); + } + { + // A handle that is not in the heap resolves to nothing: the wrong binding is not turned into a default. + check(resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base + count * stride).address == 0, "past the heap"); + check(resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base + 5).address == 0, "inside a descriptor"); + check(resolve_view_table(gpu_base, cpu_base, count, stride, gpu_base - stride).address == 0, "before the heap"); + ComputeTables s; + s.set_signature(&root_a); + s.set_table(0, at(1)); + s.set_table(0, resolve_view_table(gpu_base, cpu_base, count, stride, 0xdead0000)); + check(s.table(0).address == 0, "a wrong handle replaces the earlier binding with nothing"); + } + { + ComputeTables s; + s.set_signature(&root_a); + s.set_table(0, at(1)); + s.set_table(5, at(4)); + s.set_signature(&root_a); + check(s.table(0).address == cpu_base + stride && s.table(5).address == cpu_base + 4 * stride, "the same signature keeps the tables"); + s.set_signature(&root_b); + check(s.signature() == &root_b && s.table(0).address == 0 && s.table(5).address == 0, "a different signature clears the tables"); + s.set_table(1, at(2)); + s.set_signature(nullptr); + check(s.signature() == nullptr && s.table(1).address == 0, "a null signature clears the tables"); + } + { + ComputeTables s; + s.set_signature(&root_a); + s.set_table(7, at(6)); + s.clear(); + check(s.table(7).address == 0 && s.signature() == &root_a, "a view heap change clears the tables and keeps the signature"); + } + { + ComputeTables s; + s.set_signature(&root_a); + s.set_table(1, at(1)); + check(s.set_table(ComputeTables::max_parameters - 1, at(2)) && s.table(ComputeTables::max_parameters - 1).address, "the last parameter is kept"); + check(!s.set_table(ComputeTables::max_parameters, at(3)) && s.out_of_range_count() == 1, "a parameter out of range is refused and counted"); + check(s.table(ComputeTables::max_parameters).address == 0 && s.table(1).address == cpu_base + stride, "a refused call leaves the other tables alone"); + } + std::printf("startup_compute_root: %s\n", failures ? "FAILED" : "ok"); + return failures ? 1 : 0; +} From bee07b90b8480f0a81e6f901707549857a62b845 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:30:09 +0100 Subject: [PATCH 210/232] tests: split startup_debug into parallel ctest cases (#2488) * tests: split startup_debug into parallel ctest cases * docs: select every startup_debug group with the unanchored -R pattern --- CMakeLists.txt | 17 +- docs/startup-runtime.md | 2 +- docs/wine.md | 2 +- tests/startup_debug_check.py | 343 ++++++++++++++++++----------------- 4 files changed, 192 insertions(+), 172 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 95d592512..bd107f2a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3807,10 +3807,19 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_stage_package COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stage_package_check.py" "${STARTUP_POWERSHELL}") set_tests_properties(startup_stage_package PROPERTIES TIMEOUT 120) - add_test(NAME startup_debug COMMAND "${INTAKE_PYTHON}" -B - "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_debug_check.py" "$<TARGET_FILE:startup_debug_probe>" - "$<TARGET_FILE:startup_debug_calls>") - set_tests_properties(startup_debug PROPERTIES TIMEOUT 300) + # One script, three groups of cases that ctest can run in parallel. startup_debug keeps the old + # name; select all three with -R '^startup_debug' (the anchored -R '^startup_debug$' runs only the core group). + foreach(group IN ITEMS core log hooks) + if(group STREQUAL "core") + set(startup_debug_test startup_debug) + else() + set(startup_debug_test startup_debug_${group}) + endif() + add_test(NAME ${startup_debug_test} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_debug_check.py" "$<TARGET_FILE:startup_debug_probe>" + "$<TARGET_FILE:startup_debug_calls>" ${group}) + set_tests_properties(${startup_debug_test} PROPERTIES TIMEOUT 300) + endforeach() add_test(NAME startup_stream_request_warp COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_stream_check.py" "$<TARGET_FILE:startup_stream_consumer>") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 673534dbf..c4fd9a0e0 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -728,7 +728,7 @@ from process creation. The ordinary-heap run also recorded process audio levels. There was one run per setting. Measure the window and the first visible content separately when repeating this comparison. Time from the first recorded button release to language selection was about 17 seconds in both runs. For the public -heap-flag regression, run `ctest --preset dev --no-tests=error -R '^startup_debug$'`. +heap-flag regression, run `ctest --preset dev --no-tests=error -R '^startup_debug'`. It writes: diff --git a/docs/wine.md b/docs/wine.md index 8e1b57c32..3864e7129 100644 --- a/docs/wine.md +++ b/docs/wine.md @@ -129,6 +129,6 @@ pactl list short sink-inputs On Windows, these checks cover the Wine differences above (`startup_debug` fails its debug-heap control under Wine): ```powershell -ctest --preset dev --no-tests=error -R '^startup_debug$' --output-on-failure +ctest --preset dev --no-tests=error -R '^startup_debug' --output-on-failure ctest --preset release --no-tests=error -R '^xmem_shim_(mapped_pages|page_runs)$' -V ``` diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index 11f74805b..67a8c8319 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -107,183 +107,194 @@ def log_at_records(logdir, rva, count): return records -def main(probe, calls_dll): +GROUPS = ('core', 'log', 'hooks') + + +def main(probe, calls_dll, group='all'): + """Run one group of cases (core, log, hooks) or all of them; ctest runs the groups as separate tests.""" + if group != 'all' and group not in GROUPS: + raise SystemExit(f'unknown group {group!r}; use all or one of {GROUPS}') + groups = GROUPS if group == 'all' else (group,) sys.path.insert(0, str(DEBUG.parent)) from debug_launch import MOVIE_CALL_HOOKS, MOVIE_MODULE, read_qword, read_stack - require_hooked(HOOKED_MODULE, HOOKED_EXPORT, MOVIE_MODULE, MOVIE_CALL_HOOKS) - # Control: the guard rejects the fixture once its export is dropped from the hook list. - try: - require_hooked(HOOKED_MODULE, HOOKED_EXPORT, MOVIE_MODULE, tuple(e for e in MOVIE_CALL_HOOKS if e != HOOKED_EXPORT)) - except AssertionError: - pass - else: - raise AssertionError("the hook-list guard accepted an export the launcher does not hook") - word = bytes.fromhex("ab cd ef 01 23 45 67 89") - for readable in range(8): - assert read_qword(lambda address, size: word[:readable], 0) is None - assert read_qword(lambda address, size: word[:size], 0) == 0x8967452301efcdab - assert read_qword(lambda address, size: bytes(size), 0) == 0 - # read_stack on a stack whose committed pages end at 0x7000: a read past that end fails as a whole, - # so only the retry within RSP's page recovers the words nearest RSP. - def stack_read(address, size): - return bytes((address + i) & 0xff for i in range(size)) if address + size <= 0x7000 else b"" - for rsp, recovered in ((0x6000, 1600), (0x6a00, 1536), (0x6fe0, 32), (0x6ff8, 8)): - data = read_stack(stack_read, rsp, 200) - assert len(data) == 1600 and data[:recovered] == stack_read(rsp, recovered), hex(rsp) - assert data[recovered:] == bytes(1600 - recovered), hex(rsp) - assert read_stack(lambda address, size: b"", 0x6000, 200) == bytes(1600) + if 'hooks' in groups: + require_hooked(HOOKED_MODULE, HOOKED_EXPORT, MOVIE_MODULE, MOVIE_CALL_HOOKS) + # Control: the guard rejects the fixture once its export is dropped from the hook list. + try: + require_hooked(HOOKED_MODULE, HOOKED_EXPORT, MOVIE_MODULE, tuple(e for e in MOVIE_CALL_HOOKS if e != HOOKED_EXPORT)) + except AssertionError: + pass + else: + raise AssertionError("the hook-list guard accepted an export the launcher does not hook") + if 'core' in groups: + word = bytes.fromhex("ab cd ef 01 23 45 67 89") + for readable in range(8): + assert read_qword(lambda address, size: word[:readable], 0) is None + assert read_qword(lambda address, size: word[:size], 0) == 0x8967452301efcdab + assert read_qword(lambda address, size: bytes(size), 0) == 0 + # read_stack on a stack whose committed pages end at 0x7000: a read past that end fails as a whole, + # so only the retry within RSP's page recovers the words nearest RSP. + def stack_read(address, size): + return bytes((address + i) & 0xff for i in range(size)) if address + size <= 0x7000 else b"" + for rsp, recovered in ((0x6000, 1600), (0x6a00, 1536), (0x6fe0, 32), (0x6ff8, 8)): + data = read_stack(stack_read, rsp, 200) + assert len(data) == 1600 and data[:recovered] == stack_read(rsp, recovered), hex(rsp) + assert data[recovered:] == bytes(1600 - recovered), hex(rsp) + assert read_stack(lambda address, size: b"", 0x6000, 200) == bytes(1600) probe = Path(probe).resolve() image = probe.name with tempfile.TemporaryDirectory() as temporary: work = Path(temporary) - # Baseline: both breakpoints are stepped over and the probe exits 0. - out, logdir = run(probe, work, "baseline", {}) - assert "process exited with 0x00000000" in out, out - sites = [int(m, 16) for m in re.findall(r"breakpoint at %s\+0x([0-9a-f]+) first-chance" % re.escape(image), - text(logdir / "events.txt"))] - assert len(sites) == 2 and sites[0] != sites[1], text(logdir / "events.txt") - assert "debugger stop " not in text(logdir / "events.txt") - assert not (logdir / "threads_stop.txt").exists() and "VALLOC" not in text(logdir / "files.txt") - log_rva, opcode = log_probe_state(logdir) - assert opcode != 0xcc and "LOG_AT" not in out and "LOG_AT" not in text(logdir / "files.txt") - # The launcher keeps the debug heap off by default ... - assert "debug-probe heap flags 0x0\n" in text(logdir / "stdout.txt"), missing_heap_flags(logdir) - # ... and a caller who sets _NO_DEBUG_HEAP=0 gets it back (control: the loader's three heap bits). - out, logdir = run(probe, work, "debug-heap", {"_NO_DEBUG_HEAP": "0"}) - assert "process exited with 0x00000000" in out, out - assert "debug-probe heap flags 0x70\n" in text(logdir / "stdout.txt"), missing_heap_flags(logdir) - - out, _ = run(probe, work, "unlimited", {}, options=("--timeout", "0", "--continue-asserts", "-1")) - assert "process exited with 0x00000000" in out and "timeout after" not in out, out - out, _ = run(probe, work, "assert-cap", {}, options=("--timeout", "0", "--continue-asserts", "1")) - assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out, out - out, _ = run(probe, work, "finite", {}, options=("--timeout", "1", "--continue-asserts", "-1")) - assert "timeout after" in out and "process exited with" not in out, out - - # X2W_STOP_AT on the second site: the first is still stepped over, the run stops at the second. - out, logdir = run(probe, work, "stop", {"X2W_STOP_AT": f"{sites[1]:x}"}) - assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out and "first chance" in out, out - events = text(logdir / "events.txt") - assert events.splitlines().count("debugger stop 0x80000003 first-chance") == 1, events - assert f"breakpoint at {image}+{sites[0]:#x}" in events, events - stacks = text(logdir / "threads_stop.txt") - assert image in stacks and "rip=" in stacks, stacks - # Control: an address that is not a breakpoint site stops nothing. - out, logdir = run(probe, work, "stop-control", {"X2W_STOP_AT": f"{sites[1] + 0x1000:x}"}) - assert "process exited with 0x00000000" in out and not (logdir / "threads_stop.txt").exists(), out - # Control: without --continue-asserts the first site stops the run as before, with or without the switch. - out, _ = run(probe, work, "stop-first", {"X2W_STOP_AT": f"{sites[1]:x}"}, options=()) - assert f"stopped at breakpoint (0x80000003) at {image}+{sites[0]:#x}" in out, out - - # X2W_DUMP_AT: a dump one second in, while the probe is still alive. - out, logdir = run(probe, work, "dump", {"X2W_DUMP_AT": "1"}) - assert "process exited with 0x00000000" in out, out - assert "rip=" in text(logdir / "threads_1.txt"), text(logdir / "threads_1.txt") - assert not (work / "baseline" / "threads_1.txt").exists() - - # <logdir>/stop ends the run with thread stacks even when the timer is disabled, while the probe - # (which waits 3 s) is still alive. Control: a stop file left in the directory before the run is removed at - # start, so that run exits normally. - out, logdir = run_with_stop(probe, work, "stop-file") - assert "stopped by request after" in out and "process exited" not in out, out - assert "stop file found" in text(logdir / "events.txt"), text(logdir / "events.txt") - assert "rip=" in text(logdir / "threads.txt"), text(logdir / "threads.txt") - stale = work / "stop-stale" - stale.mkdir(exist_ok=True) - (stale / "stop").write_text("", encoding="utf-8") - out, logdir = run(probe, work, "stop-stale", {}) - assert "process exited with 0x00000000" in out and "stopped by request" not in out, out - assert not (logdir / "stop").exists(), "stale stop file kept" - - # X2W_VALLOC_MIN: the 256 MiB reservation is logged with a caller in the probe; a higher - # threshold logs nothing. - out, logdir = run(probe, work, "valloc", {"X2W_VALLOC_MIN": "10000000"}) - lines = [line for line in text(logdir / "files.txt").splitlines() if " VALLOC " in line] - ours = [line for line in lines if "size=0x10000000" in line and "type=0x2000" in line] - assert len(ours) == 1 and "requested=0x0" in ours[0] and image in ours[0].split("callers:")[1], lines - out, logdir = run(probe, work, "valloc-control", {"X2W_VALLOC_MIN": "20000000"}) - assert "process exited with 0x00000000" in out and " VALLOC " not in text(logdir / "files.txt"), out - # An empty value is the same as unset. - out, logdir = run(probe, work, "valloc-empty", {"X2W_VALLOC_MIN": ""}) - assert "process exited with 0x00000000" in out and " VALLOC " not in text(logdir / "files.txt"), out - - # Log two out of 19 calls, even with the usual file hooks off. RDX changes each call, - # RCX points into a known array, and R8 - 1 is the unreadable null address. - entry = f"{log_rva:#x}@2:rdx;[rcx+8];[rcx-8];[r8-1]" - malformed = ("xyz", f"{log_rva:x}@0", f"{log_rva:x}:rdx;[rcx*8]", f"{log_rva:x}:rip", f"{log_rva:x}:rdx;rdx", - f"{log_rva:x}:[rcx+8];[RCX+0x8]") - unusable = (0xffffffff, 0, sites[0]) - out, logdir = run(probe, work, "log-at", - {"X2W_LOG_AT": ",".join((*malformed, entry, *(f"{rva:x}:rax" for rva in unusable), entry))}, - options=("--continue-asserts", "10", "--offline", "0")) - assert "process exited with 0x00000000" in out and f"LOG_AT hit counts: +{log_rva:x} x2\n" in out, out - assert log_probe_state(logdir) == (log_rva, opcode), text(logdir / "stdout.txt") - assert log_at_records(logdir, log_rva, 2) == [ - f"rdx={LOG_TOKEN + i:#x} [rcx+8]=0x89abcdef01234567 " - "[rcx-8]=0x1020304050607080 [r8-1]=unreadable" - for i in range(2) - ], text(logdir / "files.txt") - events = text(logdir / "events.txt") - for invalid in (*malformed, entry): - assert f"X2W_LOG_AT ignored {invalid!r}:" in events, events - for rva in unusable: - assert f"X2W_LOG_AT ignored {rva:#x}:" in events, events - - # Without a limit or item list, log all 16 GPRs for the first 16 hits only. The - # shared X2W_COUNT breakpoint must still count the calls beyond the logging limit. - out, logdir = run(probe, work, "log-at-default", - {"X2W_LOG_AT": f"{log_rva:x}", "X2W_COUNT": f"{log_rva:x}"}) - assert "process exited with 0x00000000" in out, out - assert f"LOG_AT hit counts: +{log_rva:x} x16\n" in out, out - assert f" hit counts: +{log_rva:x} x{LOG_CALLS}\n" in out, out - for i, record in enumerate(log_at_records(logdir, log_rva, 16)): - registers = dict(field.split("=") for field in record.split()) - assert set(registers) == LOG_REGISTERS, record - assert int(registers["rdx"], 16) == LOG_TOKEN + i and registers["r8"] == "0x1", record - assert log_probe_state(logdir) == (log_rva, 0xcc), text(logdir / "stdout.txt") - - # Eight threads hit one site 16000 times with a limit of 1. INT3 events that other threads - # queued before the breakpoint was removed must resume, not stop the run as asserts. - found = re.search(r"^debug-probe threaded log site (0x[0-9a-f]+) byte (0x[0-9a-f]+) calls (\d+)$", - text(logdir / "stdout.txt"), re.M) - assert found, text(logdir / "stdout.txt") - threaded_rva = int(found[1], 16) - for attempt in range(3): - out, logdir = run(probe, work, f"log-at-threads-{attempt}", {"X2W_LOG_AT": f"{threaded_rva:x}@1:rcx"}) - stdout = text(logdir / "stdout.txt") - assert "process exited with 0x00000000" in out and "debugger stop " not in text(logdir / "events.txt"), out - assert f"LOG_AT hit counts: +{threaded_rva:x} x1\n" in out, out - assert f"debug-probe threaded log site {threaded_rva:#x} byte" in stdout and "calls 16000\n" in stdout, stdout - assert f"breakpoint at {image}+{threaded_rva:#x}" not in text(logdir / "events.txt"), text(logdir / "events.txt") - assert len([line for line in text(logdir / "files.txt").splitlines() if " LOG_AT " in line]) == 1 - - # Call hooks: off by default, so the 7 export calls stop nothing; with --trace-calls 1 the - # launcher counts each of them (the positive control that the probe reaches the hook). - folder = work / "calls-bin" - folder.mkdir() - hooked_probe = Path(shutil.copy2(probe, folder / image)) - dll = Path(shutil.copy2(calls_dll, folder / HOOKED_MODULE)) - variables = {"STARTUP_DEBUG_PROBE_DLL": str(dll), "STARTUP_DEBUG_PROBE_EXPORT": HOOKED_EXPORT} - banners = {"calls-default": "call tracing: off (", "calls-on": "call tracing: on (", - "calls-no-file-tracing": "call tracing: off: --trace-calls 1 needs file tracing"} - for name, extra, want in (("calls-default", (), None), - ("calls-on", ("--trace-calls", "1"), f"{HOOKED_EXPORT} x{CALLS}"), - # Requested without file tracing: nothing is armed, and the summary says why. - ("calls-no-file-tracing", ("--offline", "0", "--trace-calls", "1"), None)): - out, logdir = run(hooked_probe, work, name, variables, options=("--continue-asserts", "10", *extra)) + # Baseline: both breakpoints are stepped over and the probe exits 0 (core and log both need its sites). + if group != 'hooks': + out, logdir = run(probe, work, "baseline", {}) + assert "process exited with 0x00000000" in out, out + sites = [int(m, 16) for m in re.findall(r"breakpoint at %s\+0x([0-9a-f]+) first-chance" % re.escape(image), + text(logdir / "events.txt"))] + assert len(sites) == 2 and sites[0] != sites[1], text(logdir / "events.txt") + assert "debugger stop " not in text(logdir / "events.txt") + assert not (logdir / "threads_stop.txt").exists() and "VALLOC" not in text(logdir / "files.txt") + log_rva, opcode = log_probe_state(logdir) + assert opcode != 0xcc and "LOG_AT" not in out and "LOG_AT" not in text(logdir / "files.txt") + if 'core' in groups: + # The launcher keeps the debug heap off by default ... + assert "debug-probe heap flags 0x0\n" in text(logdir / "stdout.txt"), missing_heap_flags(logdir) + # ... and a caller who sets _NO_DEBUG_HEAP=0 gets it back (control: the loader's three heap bits). + out, logdir = run(probe, work, "debug-heap", {"_NO_DEBUG_HEAP": "0"}) assert "process exited with 0x00000000" in out, out - assert f"debug-probe calls {CALLS}\n" in text(logdir / "stdout.txt"), text(logdir / "stdout.txt") + assert "debug-probe heap flags 0x70\n" in text(logdir / "stdout.txt"), missing_heap_flags(logdir) + + out, _ = run(probe, work, "unlimited", {}, options=("--timeout", "0", "--continue-asserts", "-1")) + assert "process exited with 0x00000000" in out and "timeout after" not in out, out + out, _ = run(probe, work, "assert-cap", {}, options=("--timeout", "0", "--continue-asserts", "1")) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out, out + out, _ = run(probe, work, "finite", {}, options=("--timeout", "1", "--continue-asserts", "-1")) + assert "timeout after" in out and "process exited with" not in out, out + + # X2W_STOP_AT on the second site: the first is still stepped over, the run stops at the second. + out, logdir = run(probe, work, "stop", {"X2W_STOP_AT": f"{sites[1]:x}"}) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[1]:#x}" in out and "first chance" in out, out events = text(logdir / "events.txt") - assert re.search(r" load %s at " % re.escape(HOOKED_MODULE), events, re.I), events - found = re.search(r"bink calls: (.*)", out) - assert (found.group(1).strip() if found else None) == want, (name, out) - assert banners[name] in out, (name, out) - - print("startup_debug: PASS (stop at a chosen assert, timed thread dump, large-allocation log, debug heap off, " + assert events.splitlines().count("debugger stop 0x80000003 first-chance") == 1, events + assert f"breakpoint at {image}+{sites[0]:#x}" in events, events + stacks = text(logdir / "threads_stop.txt") + assert image in stacks and "rip=" in stacks, stacks + # Control: an address that is not a breakpoint site stops nothing. + out, logdir = run(probe, work, "stop-control", {"X2W_STOP_AT": f"{sites[1] + 0x1000:x}"}) + assert "process exited with 0x00000000" in out and not (logdir / "threads_stop.txt").exists(), out + # Control: without --continue-asserts the first site stops the run as before, with or without the switch. + out, _ = run(probe, work, "stop-first", {"X2W_STOP_AT": f"{sites[1]:x}"}, options=()) + assert f"stopped at breakpoint (0x80000003) at {image}+{sites[0]:#x}" in out, out + + # X2W_DUMP_AT: a dump one second in, while the probe is still alive. + out, logdir = run(probe, work, "dump", {"X2W_DUMP_AT": "1"}) + assert "process exited with 0x00000000" in out, out + assert "rip=" in text(logdir / "threads_1.txt"), text(logdir / "threads_1.txt") + assert not (work / "baseline" / "threads_1.txt").exists() + + # <logdir>/stop ends the run with thread stacks even when the timer is disabled, while the probe + # (which waits 3 s) is still alive. Control: a stop file left in the directory before the run is removed + # at start, so that run exits normally. + out, logdir = run_with_stop(probe, work, "stop-file") + assert "stopped by request after" in out and "process exited" not in out, out + assert "stop file found" in text(logdir / "events.txt"), text(logdir / "events.txt") + assert "rip=" in text(logdir / "threads.txt"), text(logdir / "threads.txt") + stale = work / "stop-stale" + stale.mkdir(exist_ok=True) + (stale / "stop").write_text("", encoding="utf-8") + out, logdir = run(probe, work, "stop-stale", {}) + assert "process exited with 0x00000000" in out and "stopped by request" not in out, out + assert not (logdir / "stop").exists(), "stale stop file kept" + if 'hooks' in groups: + # X2W_VALLOC_MIN: the 256 MiB reservation is logged with a caller in the probe; a higher + # threshold logs nothing. + out, logdir = run(probe, work, "valloc", {"X2W_VALLOC_MIN": "10000000"}) + lines = [line for line in text(logdir / "files.txt").splitlines() if " VALLOC " in line] + ours = [line for line in lines if "size=0x10000000" in line and "type=0x2000" in line] + assert len(ours) == 1 and "requested=0x0" in ours[0] and image in ours[0].split("callers:")[1], lines + out, logdir = run(probe, work, "valloc-control", {"X2W_VALLOC_MIN": "20000000"}) + assert "process exited with 0x00000000" in out and " VALLOC " not in text(logdir / "files.txt"), out + # An empty value is the same as unset. + out, logdir = run(probe, work, "valloc-empty", {"X2W_VALLOC_MIN": ""}) + assert "process exited with 0x00000000" in out and " VALLOC " not in text(logdir / "files.txt"), out + if 'log' in groups: + # Log two out of 19 calls, even with the usual file hooks off. RDX changes each call, + # RCX points into a known array, and R8 - 1 is the unreadable null address. + entry = f"{log_rva:#x}@2:rdx;[rcx+8];[rcx-8];[r8-1]" + malformed = ("xyz", f"{log_rva:x}@0", f"{log_rva:x}:rdx;[rcx*8]", f"{log_rva:x}:rip", f"{log_rva:x}:rdx;rdx", + f"{log_rva:x}:[rcx+8];[RCX+0x8]") + unusable = (0xffffffff, 0, sites[0]) + out, logdir = run(probe, work, "log-at", + {"X2W_LOG_AT": ",".join((*malformed, entry, *(f"{rva:x}:rax" for rva in unusable), entry))}, + options=("--continue-asserts", "10", "--offline", "0")) + assert "process exited with 0x00000000" in out and f"LOG_AT hit counts: +{log_rva:x} x2\n" in out, out + assert log_probe_state(logdir) == (log_rva, opcode), text(logdir / "stdout.txt") + assert log_at_records(logdir, log_rva, 2) == [ + f"rdx={LOG_TOKEN + i:#x} [rcx+8]=0x89abcdef01234567 " + "[rcx-8]=0x1020304050607080 [r8-1]=unreadable" + for i in range(2) + ], text(logdir / "files.txt") + events = text(logdir / "events.txt") + for invalid in (*malformed, entry): + assert f"X2W_LOG_AT ignored {invalid!r}:" in events, events + for rva in unusable: + assert f"X2W_LOG_AT ignored {rva:#x}:" in events, events + + # Without a limit or item list, log all 16 GPRs for the first 16 hits only. The + # shared X2W_COUNT breakpoint must still count the calls beyond the logging limit. + out, logdir = run(probe, work, "log-at-default", + {"X2W_LOG_AT": f"{log_rva:x}", "X2W_COUNT": f"{log_rva:x}"}) + assert "process exited with 0x00000000" in out, out + assert f"LOG_AT hit counts: +{log_rva:x} x16\n" in out, out + assert f" hit counts: +{log_rva:x} x{LOG_CALLS}\n" in out, out + for i, record in enumerate(log_at_records(logdir, log_rva, 16)): + registers = dict(field.split("=") for field in record.split()) + assert set(registers) == LOG_REGISTERS, record + assert int(registers["rdx"], 16) == LOG_TOKEN + i and registers["r8"] == "0x1", record + assert log_probe_state(logdir) == (log_rva, 0xcc), text(logdir / "stdout.txt") + + # Eight threads hit one site 16000 times with a limit of 1. INT3 events that other threads + # queued before the breakpoint was removed must resume, not stop the run as asserts. + found = re.search(r"^debug-probe threaded log site (0x[0-9a-f]+) byte (0x[0-9a-f]+) calls (\d+)$", + text(logdir / "stdout.txt"), re.M) + assert found, text(logdir / "stdout.txt") + threaded_rva = int(found[1], 16) + for attempt in range(3): + out, logdir = run(probe, work, f"log-at-threads-{attempt}", {"X2W_LOG_AT": f"{threaded_rva:x}@1:rcx"}) + stdout = text(logdir / "stdout.txt") + assert "process exited with 0x00000000" in out and "debugger stop " not in text(logdir / "events.txt"), out + assert f"LOG_AT hit counts: +{threaded_rva:x} x1\n" in out, out + assert f"debug-probe threaded log site {threaded_rva:#x} byte" in stdout and "calls 16000\n" in stdout, stdout + assert f"breakpoint at {image}+{threaded_rva:#x}" not in text(logdir / "events.txt"), text(logdir / "events.txt") + assert len([line for line in text(logdir / "files.txt").splitlines() if " LOG_AT " in line]) == 1 + if 'hooks' in groups: + # Call hooks: off by default, so the 7 export calls stop nothing; with --trace-calls 1 the + # launcher counts each of them (the positive control that the probe reaches the hook). + folder = work / "calls-bin" + folder.mkdir() + hooked_probe = Path(shutil.copy2(probe, folder / image)) + dll = Path(shutil.copy2(calls_dll, folder / HOOKED_MODULE)) + variables = {"STARTUP_DEBUG_PROBE_DLL": str(dll), "STARTUP_DEBUG_PROBE_EXPORT": HOOKED_EXPORT} + banners = {"calls-default": "call tracing: off (", "calls-on": "call tracing: on (", + "calls-no-file-tracing": "call tracing: off: --trace-calls 1 needs file tracing"} + for name, extra, want in (("calls-default", (), None), + ("calls-on", ("--trace-calls", "1"), f"{HOOKED_EXPORT} x{CALLS}"), + # Requested without file tracing: nothing is armed, and the summary says why. + ("calls-no-file-tracing", ("--offline", "0", "--trace-calls", "1"), None)): + out, logdir = run(hooked_probe, work, name, variables, options=("--continue-asserts", "10", *extra)) + assert "process exited with 0x00000000" in out, out + assert f"debug-probe calls {CALLS}\n" in text(logdir / "stdout.txt"), text(logdir / "stdout.txt") + events = text(logdir / "events.txt") + assert re.search(r" load %s at " % re.escape(HOOKED_MODULE), events, re.I), events + found = re.search(r"bink calls: (.*)", out) + assert (found.group(1).strip() if found else None) == want, (name, out) + assert banners[name] in out, (name, out) + + print(f"startup_debug[{group}]: PASS (stop at a chosen assert, timed thread dump, large-allocation log, debug heap off, " "call hooks opt-in, bounded register and qword logging)") return 0 if __name__ == "__main__": - sys.exit(main(*sys.argv[1:3])) + sys.exit(main(*sys.argv[1:4])) From b41f6fcac78146ab50ff2eea439877fb1f638d4f Mon Sep 17 00:00:00 2001 From: chasegrindy <szymonkubica.biz@gmail.com> Date: Wed, 25 Nov 2026 23:33:31 +0100 Subject: [PATCH 211/232] shader: reject base requests with a mismatched source cache key (#2595) Co-authored-by: chasegrindy <302242206+chasegrindy@users.noreply.github.com> Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 3 + CMakePresets.json | 2 +- docs/experiments.md | 26 +++++++ tests/startup_shader_cache_key_check.py | 93 +++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 8 +-- 5 files changed, 127 insertions(+), 5 deletions(-) create mode 100644 tests/startup_shader_cache_key_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index bd107f2a7..be1e2da1c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -267,6 +267,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup tooling lint (#1149): every Python file under tools/startup must parse. The check compiles each # source without running it and self-tests that a broken snippet is rejected, so a passing run means the # files were actually looked at. It needs no GPU and no game files. + add_test(NAME startup_shader_cache_key COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_shader_cache_key_check.py") + set_tests_properties(startup_shader_cache_key PROPERTIES TIMEOUT 30) add_test(NAME startup_tools_lint COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_tools_lint_check.py" "${CMAKE_SOURCE_DIR}/tools/startup") set_tests_properties(startup_tools_lint PROPERTIES TIMEOUT 60) diff --git a/CMakePresets.json b/CMakePresets.json index 398176d5b..1327cb617 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -42,7 +42,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_indirect_(dispatch|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index 667e7799f..983a28dac 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15700,6 +15700,32 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_int_extra_warp|pixel_ao Linux controls, `form_coverage_check.check_sdwa_int_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. +## Startup shader request identity + +`startup_shader_cache_key` uses the explicit `X2W_FXC=''` manifest-only mode: no GPU +or shader compiler is required, and it does not claim compiled bytecode. Real hashing, +raw classification, container extraction and HLSL generation remain active. A wrapping +translation spy requires every identity failure to occur before translation. All rejected +fresh requests must publish only the exact `.fail` diagnostic, not a shader or manifest. + +The source-built raw VS/PS pair, reversed raw storage, full containers and a minimal +RTS0 root cover accepted identities; wrong keys and independent VS/PS/root/input layout mutations +cover rejection. Valid and invalid RTV requests preserve existing behavior and diagnostic. +A literal known-answer vector independently executed with the runtime C++ `fnv_bytes` +and revision/order (including optional `.ia`) (`src/startup_stubs/d3d12_draw.inl`) prevents a shared Python-key error +from silently agreeing in both producer and validator. + +```powershell +python -B tests/startup_shader_cache_key_check.py +ctest --preset dev --no-tests=error -j 1 -R '^startup_shader_cache_key$' -V +``` + +Publication through `translate_request` validates base request identity as well as RTV source identity. The refusal-only diagnostic mode is unchanged. +Before this guard, a base request could publish a manifest under a key that did not hash +its inputs. This is malformed-request integrity hardening, not a demonstrated normal-game +misrender, cryptographic authenticity, cleanup of already-published artifacts or driver +PSO-cache change. Canonical output bytes remain unchanged. + ## Teardown of the per-device D3D12 caches Two caches keep desktop D3D12 objects for a device for as long as the module that holds them is loaded: the diff --git a/tests/startup_shader_cache_key_check.py b/tests/startup_shader_cache_key_check.py new file mode 100644 index 000000000..7a7d7218a --- /dev/null +++ b/tests/startup_shader_cache_key_check.py @@ -0,0 +1,93 @@ +"""Validate stored source identity before startup translation or output publication.""" +import importlib +import os +import struct +import sys +import tempfile +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup")) +gfx2hlsl = importlib.import_module("gfx2hlsl") + +VERTEX = struct.pack("<3I", 0xf800080f | (12 << 4), 0, 0xbf810000) +PIXEL = struct.pack("<3I", 0xf800080f, 0, 0xbf810000) +ROOT = (b"DXBC" + bytes(16) + struct.pack("<4I", 1, 68, 1, 36) + + b"RTS0" + struct.pack("<I", 24) + struct.pack("<6I", 1, 0, 24, 0, 24, 0)) +BASE_MISMATCH = "shader request source key mismatch" + + +def check_request(blobs, key, diagnostic=None, rtv_request=None, layout=None): + with tempfile.TemporaryDirectory() as directory: + cache = Path(directory) + base = int(rtv_request.split()[1]) if rtv_request else key + for suffix, data in zip((".a", ".b", ".root"), blobs): + (cache / f"req_{base:016x}{suffix}").write_bytes(data) + if layout is not None: + (cache / f"req_{base:016x}.ia").write_bytes(layout) + if rtv_request: + (cache / f"req_{key:016x}.rtv").write_text(rtv_request, encoding="ascii") + # Explicit upstream manifest-only mode; real hashing, parsing and HLSL translation. + # The wrapping spy observes translation; it never replaces its behavior. + with patch.dict(os.environ, {"X2W_FXC": ""}), patch.object( + gfx2hlsl, "translate_to", wraps=gfx2hlsl.translate_to) as translate: + result = gfx2hlsl.translate_request(str(cache), key) + outputs = {p.name: p.read_bytes() for p in cache.glob(f"{key:016x}.*")} + if diagnostic is not None: + assert result == f"unsupported: {diagnostic}", (result, sorted(outputs)) + assert set(outputs) == {f"{key:016x}.fail"}, outputs + assert (cache / f"{key:016x}.fail").read_text() == diagnostic + "\n" + translate.assert_not_called() + else: + assert result == "ok", result + assert set(outputs) == {f"{key:016x}{s}" for s in (".vs.hlsl", ".ps.hlsl", ".txt")}, outputs + translate.assert_called_once() + if rtv_request: + assert rtv_request in outputs[f"{key:016x}.txt"].decode().splitlines() + return outputs + + +def main(): + # Independently executed C++ runtime fnv_bytes/cached_translation known-answer vector. + # Revision x2w-startup-shader-17 excludes NUL. Stored order is a, b, root, then optional input layout. + vector = (b"\x00VS\xff", b"PS\x00\x80", b"RTS0\x00") + assert gfx2hlsl.pipeline_key(*vector) == 0xd9521cd3fde79d61 + assert gfx2hlsl.pipeline_key(*vector, b"ia\x00\xfe") == 0xbaa2837ef61006ad + blobs = (VERTEX, PIXEL, ROOT) + canonical = gfx2hlsl.pipeline_key(*blobs) + check_request(blobs, canonical) + print("canonical raw request: accepted and published") + check_request(blobs, canonical ^ 1, BASE_MISMATCH) + print("wrong base key: exact diagnostic, no shader/manifest, no translation") + for index, suffix in enumerate((".a", ".b", ".root")): + changed = tuple(data + (b"\x00" if i == index else b"") for i, data in enumerate(blobs)) + check_request(changed, canonical, BASE_MISMATCH) + print(f"changed {suffix}: exact diagnostic, no shader/manifest, no translation") + # Identity includes the optional .ia bytes even when this VS needs no vertex fetch. + layout = b"slot 0" + layout_key = gfx2hlsl.pipeline_key(*blobs, layout) + check_request(blobs, layout_key, layout=layout) + check_request(blobs, layout_key, BASE_MISMATCH, layout=layout + b"\n") + check_request(blobs, layout_key, BASE_MISMATCH) + print("input layout: correct accepted; changed or missing .ia rejected before translation") + # Legacy raw storage order is hashed as stored, then classified for translation. + reversed_blobs = (PIXEL, VERTEX, ROOT) + check_request(reversed_blobs, gfx2hlsl.pipeline_key(*reversed_blobs)) + from startup_stream_check import container + stored = (container(1), container(0), ROOT) + container_key = gfx2hlsl.pipeline_key(*stored) + check_request(stored, container_key) + check_request(stored, container_key ^ 1, BASE_MISMATCH) + print("container requests: correct accepted; mismatch rejected before translation") + for correct in (True, False): + base = canonical if correct else canonical ^ 1 + request = f"rtv1 {base} 28" + key = gfx2hlsl.fnv(request.encode("ascii")) + check_request(blobs, key, None if correct else "RTV variant source key mismatch", request) + print("RTV requests: correct accepted; existing mismatch diagnostic preserved") + print("startup shader cache key checks: passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 70f6d4767..03aa977d2 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7261,7 +7261,7 @@ def classify(blob): return classify_decoded(decode(strip_header(blob))) -def load_request(out_dir, key, refusals=None, pair_info=None): +def load_request(out_dir, key, refusals=None, pair_info=None, *, validate_base_key=False): """Read a base request or an RTV variant and classify the source stages.""" decoded = {} @@ -7292,8 +7292,8 @@ def classify_stage(blob): pair_info.append((hashlib.sha256(struct.pack('<Q', len(a)) + a + b).digest(), root)) # A stream with an input layout publishes it as .ia (before .a) and hashes it into the key. layout = open(name + '.ia', 'rb').read() if os.path.isfile(name + '.ia') else b'' - if request and pipeline_key(a, b, root, layout) != base: - raise Unsupported('RTV variant source key mismatch') + if (request or validate_base_key) and pipeline_key(a, b, root, layout) != base: + raise Unsupported('RTV variant source key mismatch' if request else 'shader request source key mismatch') fetch = attr_map = None if a.startswith(b'DXBC') or b.startswith(b'DXBC'): # Slot 86 records complete containers in canonical (VS, PS) order. @@ -7394,7 +7394,7 @@ def translate_request(out_dir, key): open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason try: - kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key) + kinds, root, formats, request, fetch, _, attr_map = load_request(out_dir, key, validate_base_key=True) except (Unsupported, OSError, UnicodeError) as reason: open(os.path.join(out_dir, '%016x.fail' % key), 'w').write(str(reason) + '\n') return 'unsupported: %s' % reason From 47887e6a66afff2797b2873a444f4b646311d47e Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:36:57 +0200 Subject: [PATCH 212/232] shader: harden input file and struct/zlib error guards in section_probe with CLI suite (#2597) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 2 + tests/section_probe_cli_check.py | 374 +++++++++++++++++++++++++++++++ tools/section_probe.py | 14 +- 3 files changed, 388 insertions(+), 2 deletions(-) create mode 100644 tests/section_probe_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index be1e2da1c..d3561aa31 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4162,6 +4162,8 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/spirv_sampler_split_check.py") add_test(NAME spirv_address_window_check COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/spirv_address_window_check.py") + add_test(NAME shader_section_probe_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/section_probe_cli_check.py") # Outside a Git checkout, such as a source archive, the tracked-path check cannot run. set_tests_properties(docs_links PROPERTIES SKIP_RETURN_CODE 77) diff --git a/tests/section_probe_cli_check.py b/tests/section_probe_cli_check.py new file mode 100644 index 000000000..e359cd5d5 --- /dev/null +++ b/tests/section_probe_cli_check.py @@ -0,0 +1,374 @@ +#!/usr/bin/env python3 +"""CLI, error-guard, window-dedup, and mutation suite for tools/section_probe.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock +import zlib + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "section_probe.py" +sys.path.insert(0, str(ROOT / "tools")) + +import section_probe # noqa: E402 + +EXPECTED_KEYS = {"file", "bytes_sampled", "valid_zlib", "section_records", "layouts"} + + +def _make_doc(*items: tuple[bytes, bytes]) -> bytes: + """Pack big-endian (4-byte tag, uint32 length, payload) section records.""" + parts = [] + for tag, payload in items: + assert len(tag) == 4 + parts.append(struct.pack(">4sI", tag, 8 + len(payload)) + payload) + return b"".join(parts) + + +def _pad16(blob: bytes) -> bytes: + return blob + bytes(-len(blob) % 16) + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = section_probe.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str | Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *(str(a) for a in args)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + ) + + +class SectionProbeCliPositiveTests(unittest.TestCase): + def test_empty_single_byte_and_multi_archive_json_schema(self) -> None: + doc = _make_doc((b"HEAD", b"abcd"), (b"FOOT", b"")) + with TemporaryDirectory() as tmp: + root = Path(tmp) + empty_path = root / "empty.bin" + one_byte_path = root / "one.bin" + valid_path = root / "valid.bin" + empty_path.write_bytes(b"") + one_byte_path.write_bytes(b"\x78") + valid_path.write_bytes(zlib.compress(doc)) + + code, out, err = _run_main([ + str(empty_path), + str(one_byte_path), + str(valid_path), + "--first", + "HEAD", + "--last", + "FOOT", + ]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + reports = json.loads(out) + self.assertEqual(len(reports), 3) + for item in reports: + self.assertEqual(set(item), EXPECTED_KEYS) + self.assertEqual( + reports[0], + {"file": "empty.bin", "bytes_sampled": 0, "valid_zlib": 0, "section_records": 0, "layouts": {}}, + ) + self.assertEqual( + reports[1], + {"file": "one.bin", "bytes_sampled": 1, "valid_zlib": 0, "section_records": 0, "layouts": {}}, + ) + self.assertEqual( + reports[2], + { + "file": "valid.bin", + "bytes_sampled": valid_path.stat().st_size, + "valid_zlib": 1, + "section_records": 1, + "layouts": {"HEAD FOOT": 1}, + }, + ) + + proc = _run_subprocess(empty_path, valid_path, "--first", "HEAD", "--last", "FOOT") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), [reports[0], reports[2]]) + self.assertEqual(sorted(p.name for p in root.iterdir()), ["empty.bin", "one.bin", "valid.bin"]) + + def test_valid_corrupt_preset_dict_and_unaligned_zlib_streams(self) -> None: + matching_doc = _make_doc((b"HEAD", b"1234"), (b"BODY", b"5678"), (b"FOOT", b"")) + other_end_doc = _make_doc((b"HEAD", b"1234"), (b"TAIL", b"")) + bad_section_payload = b"HEAD\x00\x00\x00\x04" + + valid_match = zlib.compress(matching_doc) + valid_other_end = zlib.compress(other_end_doc) + valid_bad_sections = zlib.compress(bad_section_payload) + corrupt_checksum = valid_match[:-1] + bytes([valid_match[-1] ^ 0xFF]) + truncated_stream = valid_match[:6] + + dict_comp = zlib.compressobj(wbits=15, zdict=b"HEAD BODY FOOT") + preset_dict = dict_comp.compress(matching_doc) + dict_comp.flush() + with mock.patch.object(section_probe.zlib, "decompressobj", side_effect=AssertionError("FDICT skipped")) as decomp_mock: + self.assertEqual(section_probe.scan_window(preset_dict, 0, "HEAD", "FOOT"), (0, {})) + decomp_mock.assert_not_called() + + # Place an otherwise valid stream at +1 misalignment inside a 16-byte chunk. + unaligned_block = b"\x00" + valid_match + + archive = b"".join([ + _pad16(valid_match), + _pad16(valid_other_end), + _pad16(valid_bad_sections), + _pad16(corrupt_checksum), + _pad16(truncated_stream), + _pad16(preset_dict), + _pad16(unaligned_block), + ]) + + with TemporaryDirectory() as tmp: + path = Path(tmp) / "mixed.bin" + path.write_bytes(archive) + + direct = section_probe.inspect(path, "HEAD", "FOOT") + self.assertEqual(direct["valid_zlib"], 3) + self.assertEqual(direct["section_records"], 1) + self.assertEqual(dict(direct["layouts"]), {"HEAD BODY FOOT": 1}) + + proc = _run_subprocess(path, "--first", "HEAD", "--last", "FOOT") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual( + json.loads(proc.stdout), + [{ + "file": "mixed.bin", + "bytes_sampled": len(archive), + "valid_zlib": 3, + "section_records": 1, + "layouts": {"HEAD BODY FOOT": 1}, + }], + ) + + def test_multi_window_overlap_dedup_and_three_window_sampling(self) -> None: + packet = zlib.compress(_make_doc((b"HEAD", b"w"), (b"FOOT", b""))) + with TemporaryDirectory() as tmp: + root = Path(tmp) + + # 9 MiB file: all three 8 MiB windows overlap and merge into one [0, 9 MiB] span. + overlap_size = 9 << 20 + overlap_buf = bytearray(overlap_size) + for offset in (0, 2 << 20, 7 << 20, (8 << 20) + 1024): + overlap_buf[offset:offset + len(packet)] = packet + overlap_path = root / "overlap.bin" + overlap_path.write_bytes(overlap_buf) + + overlap_report = section_probe.inspect(overlap_path, "HEAD", "FOOT") + self.assertEqual(overlap_report["bytes_sampled"], overlap_size) + self.assertEqual(overlap_report["valid_zlib"], 4) + self.assertEqual(overlap_report["section_records"], 4) + self.assertEqual(dict(overlap_report["layouts"]), {"HEAD FOOT": 4}) + + # 25 MiB file: three disjoint 8 MiB windows at [0, 8M], [8.5M, 16.5M], [17M, 25M]. + large_size = 25 << 20 + large_buf = bytearray(large_size) + mid_start = (large_size - (8 << 20)) // 2 # 8.5 MiB, 16-byte aligned + sampled_offsets = (0, mid_start + 1024, 24 << 20) + unsampled_gap_offset = (8 << 20) + 64 + for offset in (*sampled_offsets, unsampled_gap_offset): + large_buf[offset:offset + len(packet)] = packet + large_path = root / "large.bin" + large_path.write_bytes(large_buf) + + large_report = section_probe.inspect(large_path, "HEAD", "FOOT") + self.assertEqual(large_report["bytes_sampled"], 3 * (8 << 20)) + self.assertEqual(large_report["valid_zlib"], 3) + self.assertEqual(large_report["section_records"], 3) + self.assertEqual(dict(large_report["layouts"]), {"HEAD FOOT": 3}) + + def test_main_sys_argv_forwarding_and_script_entrypoint(self) -> None: + packet = zlib.compress(_make_doc((b"HEAD", b"ok"), (b"FOOT", b""))) + with TemporaryDirectory() as tmp: + path = Path(tmp) / "entry.bin" + path.write_bytes(packet) + cli_argv = [str(TOOL), str(path), "--first", "HEAD", "--last", "FOOT"] + + with mock.patch.object(sys, "argv", cli_argv): + code, out, err = _run_main(None) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertEqual(json.loads(out)[0]["section_records"], 1) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue())[0]["section_records"], 1) + + +class SectionProbeCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv, + *, + expected_code=1, + expected_fragment, + require_prefix=True, + check_subprocess=True, + ) -> None: + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + if require_prefix: + self.assertTrue(err.startswith("section_probe: "), err) + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + if require_prefix: + self.assertTrue(proc.stderr.startswith("section_probe: "), proc.stderr) + + def test_missing_directory_and_non_regular_archive_refusals(self) -> None: + packet = zlib.compress(_make_doc((b"HEAD", b"ok"), (b"FOOT", b""))) + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_path = root / "valid.bin" + valid_path.write_bytes(packet) + existing_dir = root / "dir_archive" + existing_dir.mkdir() + missing_path = root / "missing.bin" + + # Directories and missing files must be rejected by is_file() before open() or size stat runs. + real_open = Path.open + open_calls = [] + + def guarded_open(self_path, *args, **kwargs): + open_calls.append(self_path) + return real_open(self_path, *args, **kwargs) + + with mock.patch.object(Path, "open", guarded_open): + with self.assertRaisesRegex(ValueError, "directory"): + section_probe.inspect(existing_dir, "HEAD", "FOOT") + with self.assertRaises(FileNotFoundError): + section_probe.inspect(missing_path, "HEAD", "FOOT") + self.assertEqual(open_calls, []) + + dir_mock = mock.MagicMock(spec=Path) + dir_mock.is_file.return_value = False + dir_mock.is_dir.return_value = True + dir_mock.__str__.return_value = "mock_dir" + with self.assertRaisesRegex(ValueError, "directory"): + section_probe.inspect(dir_mock, "HEAD", "FOOT") + dir_mock.stat.assert_not_called() + dir_mock.open.assert_not_called() + + # Non-regular file (exists=True, is_dir=False, is_file=False) raises ValueError. + special_path = mock.MagicMock(spec=Path) + special_path.is_file.return_value = False + special_path.is_dir.return_value = False + special_path.exists.return_value = True + special_path.__str__.return_value = "special_fifo" + with self.assertRaisesRegex(ValueError, "regular file"): + section_probe.inspect(special_path, "HEAD", "FOOT") + special_path.stat.assert_not_called() + special_path.open.assert_not_called() + + # CLI refuses directories (including ""), missing paths, and mixed lists with exit 1 and no stdout. + for bad_arg, frag, subproc in ( + (str(existing_dir), "directory", True), + ("", "directory", False), + (str(missing_path), missing_path.name, True), + ): + with self.subTest(bad_arg=bad_arg): + self._assert_clean_failure( + [bad_arg, "--first", "HEAD", "--last", "FOOT"], + expected_fragment=frag, + check_subprocess=subproc, + ) + self._assert_clean_failure( + [str(valid_path), bad_arg, "--first", "HEAD", "--last", "FOOT"], + expected_fragment=frag, + check_subprocess=subproc, + ) + + def test_caught_exceptions_and_py314_argparse_errors_without_traceback(self) -> None: + packet = zlib.compress(_make_doc((b"HEAD", b"ok"), (b"FOOT", b""))) + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_path = root / "valid.bin" + valid_path.write_bytes(packet) + + for exc in ( + OSError("simulated io failure"), + ValueError("simulated value failure"), + struct.error("simulated struct failure"), + zlib.error("simulated zlib failure"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(section_probe, "inspect", side_effect=exc): + self._assert_clean_failure( + [str(valid_path), "--first", "HEAD", "--last", "FOOT"], + expected_fragment=str(exc), + check_subprocess=False, + ) + + # Invalid 4-char tags and missing/unknown argparse flags exit non-zero without tracebacks. + for argv, frag in ( + ([str(valid_path), "--first", "head", "--last", "FOOT"], "section tag"), + ([str(valid_path), "--first", "HEAD", "--last", "foot"], "section tag"), + ([str(valid_path), "--first", "HEA", "--last", "FOOT"], "section tag"), + ([str(valid_path), "--first", "HEADS", "--last", "FOOT"], "section tag"), + ([str(valid_path), "--first", "HÉAD", "--last", "FOOT"], "section tag"), + ([str(valid_path), "--first", "A-CD", "--last", "FOOT"], "section tag"), + ([], "usage:"), + ([str(valid_path)], "--first"), + ([str(valid_path), "--first", "HEAD"], "--last"), + ([str(valid_path), "--first", "HEAD", "--last", "FOOT", "--bogus"], "--bogus"), + ): + with self.subTest(argv=argv): + stdout = io.StringIO() + stderr = io.StringIO() + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(stdout), redirect_stderr(stderr): + section_probe.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertIn(frag, stderr.getvalue()) + self.assertNotIn("Traceback", stderr.getvalue()) + + proc = _run_subprocess(valid_path, "--first", "bad", "--last", "FOOT") + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(proc.stdout, "") + self.assertIn("section tag", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + self.assertEqual(sorted(p.name for p in root.iterdir()), ["valid.bin"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/section_probe.py b/tools/section_probe.py index fed03d1d7..e7a8adbac 100644 --- a/tools/section_probe.py +++ b/tools/section_probe.py @@ -49,6 +49,12 @@ def scan_window(data, base, first, last): def inspect(path, first, last): + if not path.is_file(): + if path.is_dir(): + raise ValueError(f"archive path is a directory, not a file: {path}") + if not path.exists(): + raise FileNotFoundError(f"archive file not found: {path}") + raise ValueError(f"archive path is not a regular file: {path}") size = path.stat().st_size window = 8 << 20 # Merge overlapping windows on small files so a stream is counted only once. @@ -77,14 +83,18 @@ def section_tag(value): return value -def main(argv=None): +def main(argv=None) -> int: """Run the section probe CLI and return the process exit code.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("archives", type=Path, nargs="+") parser.add_argument("--first", required=True, type=section_tag) parser.add_argument("--last", required=True, type=section_tag) args = parser.parse_args(argv) - print(json.dumps([inspect(p, args.first, args.last) for p in args.archives], indent=2)) + try: + reports = [inspect(p, args.first, args.last) for p in args.archives] + except (OSError, ValueError, struct.error, zlib.error) as exc: + parser.exit(1, f"section_probe: {exc}\n") + print(json.dumps(reports, indent=2)) return 0 From 2a14c0d7cb38d2e6653515d16e386241453e62c1 Mon Sep 17 00:00:00 2001 From: Matheus Sergio <matheusolovics@gmail.com> Date: Wed, 25 Nov 2026 19:37:18 -0300 Subject: [PATCH 213/232] startup: lower v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 in gfx2hlsl (#2589) Lower the VOP3A-only 32-to-16-bit saturating integer pack pair (`0x36a` and `0x36b`) in `tools/startup/gfx2hlsl.py`: - `v_cvt_pk_u16_u32`: clamp `S0` and `S1` as unsigned 32-bit integers to `[0, 65535]` and pack `S0` in `[15:0]` and `S1` in `[31:16]`. - `v_cvt_pk_i16_i32`: clamp `S0` and `S1` as signed 32-bit integers to `[-32768, 32767]` and pack `S0` in `[15:0]` and `S1` in `[31:16]`. - Accept VGPRs, SGPRs, inline constants, and 32-bit literals across `Pipeline` and `ComputePipeline` (including explicit `_e64` spelling), propagate scalar uniformity through `UNIFORM_VALU` for `v_readfirstlane_b32`, require whole-32-bit source definitions, and clear `low16_only_v` on the destination VGPR. - Refuse VOP3A source `abs`/`neg` bits and non-zero unused `src2` in `check_encoding` before disassembly, and refuse `clamp`, `omod`, `op_sel`, lane-mask sources, non-VOP3 spellings (`_e32`, `_sdwa`, `_dpp`), and invalid operand counts or widths in `Stage`. Add `tests/startup_gfx2hlsl_cvt_pk_int16_check.py` covering LLVM 15 `llvm-mc` / `libLLVM` round-trips, 676 `(S0, S1)` boundary pairs per opcode, `ComputePipeline`, `UNIFORM_VALU`, `low16_only_v`, encoding and Stage refusal controls, and WARP / hardware D3D12 draws with four mutated-HLSL negative controls per opcode across FXC `ps_5_1` and DXC `ps_6_0`. Part of #1723. AI-assisted. --- .github/workflows/windows.yml | 3 + AGENTS.md | 1 + CMakeLists.txt | 10 + docs/experiments.md | 15 + tests/startup_gfx2hlsl_cvt_pk_int16_check.py | 543 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 39 +- 6 files changed, 607 insertions(+), 4 deletions(-) create mode 100644 tests/startup_gfx2hlsl_cvt_pk_int16_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4a225bda8..6a37c4bfd 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -88,6 +88,8 @@ jobs: (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "decode", "libLLVM-15.so.1"], {}), (["tests/startup_gfx2hlsl_cmp16_check.py", "binary", "llvm-mc-15", "llvm-objcopy-15"], {}), (["tests/startup_image_sample_l_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_sample_b_check.py", "binary", "llvm-mc-15"], {}), @@ -239,6 +241,7 @@ jobs: tests/startup_live_telemetry_check.py \ tests/startup_gfx2hlsl_cvt_alu_check.py \ tests/startup_gfx2hlsl_cvt_pk_u8_check.py \ + tests/startup_gfx2hlsl_cvt_pk_int16_check.py \ tests/startup_gfx2hlsl_cvt_off_f32_i4_check.py \ tests/startup_gfx2hlsl_int_med3_check.py \ tests/startup_gfx2hlsl_cselect_mask_check.py \ diff --git a/AGENTS.md b/AGENTS.md index d7c8b49ab..f17a5c5dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -253,6 +253,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_getpc_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_image_arity_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sad_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_cvt_pk_int16_check.py ``` `tests/pixel_aot_check.py binary` additionally needs LLVM with gfx1013 support diff --git a/CMakeLists.txt b/CMakeLists.txt index d3561aa31..ef3e09517 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3332,6 +3332,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_cvt_pk_u8_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32 (#1723): VOP3A saturating 16-bit integer packs, encoding/refusal + # controls, and WARP/hardware draws (FXC 5_1 and DXC 6_0) with four mutations per opcode. + add_test(NAME startup_gfx2hlsl_cvt_pk_int16_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cvt_pk_int16_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_cvt_pk_int16_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_cvt_pk_int16_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_cvt_pk_int16_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cvt_off_f32_i4 (VOP1 0x0e and VOP3A 0x18e): signed 4-bit nibble conversion with output modifiers, # low16_only provenance, uniformity tracking, refusals, and WARP/hardware draws with mutated controls. add_test(NAME startup_gfx2hlsl_cvt_off_f32_i4_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 983a28dac..1bed7f90b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15777,3 +15777,18 @@ ctest --preset dev --no-tests=error -R '^(pixel_aot_f16_exact_extra_warp|pixel_a ``` Linux controls, `form_coverage_check.check_f16_exact_extra_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. + +## Startup translator: saturating 32-to-16-bit integer packs (`v_cvt_pk_u16_u32`, `v_cvt_pk_i16_i32`) + +`tools/startup/gfx2hlsl.py` lowers the VOP3A-only 32-to-16-bit saturating integer pack pair (`0x36a` / `0x36b`, #1723) via `VEC_U`: + +- `v_cvt_pk_u16_u32`: `min({0}, 0xffffu) | (min({1}, 0xffffu) << 16u)` (`S0` clamped to `[0, 65535]` in `[15:0]`, `S1` in `[31:16]`). +- `v_cvt_pk_i16_i32`: `(asuint(clamp(asint({0}), -32768, 32767)) & 0xffffu) | (asuint(clamp(asint({1}), -32768, 32767)) << 16u)` (`S0` signed-clamped to `[-32768, 32767]` in `[15:0]`, `S1` in `[31:16]`). +- Both instructions accept VGPRs, SGPRs (`s0..s105`), 32-bit inline constants, and 32-bit literals across `Pipeline` and `ComputePipeline` (including explicit `_e64` spelling), propagate scalar uniformity through `UNIFORM_VALU` for `v_readfirstlane_b32`, require whole-32-bit source definitions (`low16_only=False`), and clear `low16_only_v` on their destination VGPR. +- `check_encoding` refuses VOP3A source `abs` (`w0[10:8]`), `neg` (`w1[31:29]`), and non-zero unused `src2` (`w1[26:18]`) on the raw words before disassembly; `Stage` refuses `clamp`, `omod`, `op_sel`, printed `|vN|`/`-vN` modifiers, lane-mask sources (`vcc_lo`, `exec_lo`), non-VOP3 spellings (`_e32`, `_sdwa`, `_dpp`), and invalid operand counts or widths. + +[`tests/startup_gfx2hlsl_cvt_pk_int16_check.py`](../tests/startup_gfx2hlsl_cvt_pk_int16_check.py) constructs synthetic gfx1013 VOP3A words (no game data), verifies all 676 `(S0, S1)` boundary pairs per opcode against independent Python saturation references, checks LLVM 15 `llvm-mc` / `libLLVM` round-trips in Linux CI, tests `ComputePipeline`, `UNIFORM_VALU`, `low16_only_v`, and encoding/Stage refusal controls, and runs four mutated-HLSL negative controls per opcode (`trunc_lo`, `trunc_hi`, `swap_halves`, and opposite-signedness clamp). On Windows 11 with the D3D12 debug layer enabled (`0` errors, `0` warnings) across both FXC `ps_5_1` and DXC `ps_6_0`, all 16 good draws and 16 mutated-HLSL negative controls matched on Microsoft WARP (`1414:008c`, driver `10.0.26100.9818`) and on an AMD Radeon RX 9070 XT (`1002:7550`, driver `32.0.32029.2010`). + +```powershell +ctest --test-dir out/build/release --no-tests=error -R "^startup_gfx2hlsl_cvt_pk_int16_(controls|warp|hardware)$" -V +``` diff --git a/tests/startup_gfx2hlsl_cvt_pk_int16_check.py b/tests/startup_gfx2hlsl_cvt_pk_int16_check.py new file mode 100644 index 000000000..5f905b654 --- /dev/null +++ b/tests/startup_gfx2hlsl_cvt_pk_int16_check.py @@ -0,0 +1,543 @@ +"""Saturating 32-to-16-bit integer packs (v_cvt_pk_u16_u32, v_cvt_pk_i16_i32) in tools/startup/gfx2hlsl.py (#1723). + + (no arguments) translation, CPU boundary-grid evaluation, low16_only / uniformity / compute + provenance, encoding-guard and refusal controls, pure Python + binary <llvm-mc> reassemble every fixture and instruction spelling and compare with recorded words + decode <libLLVM> disassemble the VOP3A words with LLVM's C API and compare with disasm_rdna2.py + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pairs with FXC ps_5_1 when given and with DXC ps_6_0, + draw 16 input pairs per opcode and verify four mutated HLSL controls per opcode + +AMD RDNA 2 ISA reference (VOP3A opcodes 0x36a / 874 and 0x36b / 875) places the narrowed src0 in bits 15:0 and src1 +in bits 31:16, with saturation bounds [0, 65535] (unsigned) and [-32768, 32767] (signed) matching Mesa's NIR +pack_uvec2_to_uint / pack_ivec2_to_uint selected in ACO and the pixel_aot lowering (#779). Both instructions exist +only in the VOP3A encoding on gfx10. +""" +import re +import struct +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 disasm_rdna2 as D # noqa: E402 +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + MASK, + POST_SOURCE, + POST_WORDS, + PRE_SOURCE, + PRE_WORDS, + Probe, + check, + refused, + signed, + vs_source, + vs_words, + words_text, +) + +OPCODES = { + 'v_cvt_pk_u16_u32': 0x36a, + 'v_cvt_pk_i16_i32': 0x36b, +} + + +def vop3a(op, vdst, src0, src1, src2=0, *, abs_bits=0, op_sel=0, clamp=0, omod=0, neg=0, lit=None): + """Encode one synthetic gfx1013 VOP3A 64-bit (or 96-bit with literal) instruction word.""" + w0 = 0xd4000000 | (op << 16) | (clamp << 15) | (op_sel << 11) | (abs_bits << 8) | vdst + w1 = (neg << 29) | (omod << 27) | (src2 << 18) | (src1 << 9) | src0 + out = struct.pack('<2I', w0, w1) + if lit is not None: + out += struct.pack('<I', lit & MASK) + return out + + +BODY_SOURCE = { + op: ''.join(f'{op} v{12 + lane}, v{lane}, v{4 + lane}\n' for lane in range(4)) + for op in OPCODES +} +BODY_WORDS = { + op: b''.join(vop3a(code, 12 + lane, 256 + lane, 256 + 4 + lane) for lane in range(4)) + for op, code in OPCODES.items() +} + +# Canonical LLVM 15 round-trip lines (disasm_rdna2 <-> llvm-mc <-> libLLVM). +CANONICAL_CASES = ( + ('v_cvt_pk_u16_u32 v12, v0, v4', vop3a(0x36a, 12, 256, 260)), + ('v_cvt_pk_u16_u32 v1, s4, 64', vop3a(0x36a, 1, 4, 192)), + ('v_cvt_pk_u16_u32 v2, 0x12345, v3', vop3a(0x36a, 2, 255, 259, lit=0x12345)), + ('v_cvt_pk_u16_u32 v5, 0, -1', vop3a(0x36a, 5, 128, 193)), + ('v_cvt_pk_i16_i32 v12, v0, v4', vop3a(0x36b, 12, 256, 260)), + ('v_cvt_pk_i16_i32 v1, -16, s4', vop3a(0x36b, 1, 208, 4)), + ('v_cvt_pk_i16_i32 v2, v3, 0x12345', vop3a(0x36b, 2, 259, 255, lit=0x12345)), + ('v_cvt_pk_i16_i32 v5, -1, 0', vop3a(0x36b, 5, 193, 128)), +) + +# Additional disasm_rdna2 + gfx2hlsl inline-float / signed-hex literal encodings checked in pure-Python controls(). +DISASM_EXTRA_CASES = ( + ('v_cvt_pk_u16_u32 v5, 1.0, -1', vop3a(0x36a, 5, 242, 193)), + ('v_cvt_pk_i16_i32 v2, v3, 0xffff7fff', vop3a(0x36b, 2, 259, 255, lit=0xffff7fff)), + ('v_cvt_pk_i16_i32 v5, -2.0, 0.5', vop3a(0x36b, 5, 245, 240)), +) + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +def sat_u16(x): + return min(x & MASK, 0xffff) + + +def sat_i16(x): + s = signed(x & MASK) + return max(-32768, min(32767, s)) & 0xffff + + +def ref_pk_u16(a, b): + return sat_u16(a) | (sat_u16(b) << 16) + + +def ref_pk_i16(a, b): + return sat_i16(a) | (sat_i16(b) << 16) + + +REF = { + 'v_cvt_pk_u16_u32': ref_pk_u16, + 'v_cvt_pk_i16_i32': ref_pk_i16, +} + +# Four distinct mutations per opcode: low truncation, high truncation, swapped halves, and opposite signedness. +# Set 0 of DRAW is chosen so every mutation produces 4 words distinct from REF on the very first draw. +MUTATIONS = { + 'v_cvt_pk_u16_u32': ( + ( + 'trunc_lo', + r'min\(v(\d+), 0xffffu\) \| \(min\(v(\d+), 0xffffu\) << 16u\)', + r'(v\1 & 0xffffu) | (min(v\2, 0xffffu) << 16u)', + lambda a, b: (a & 0xffff) | (sat_u16(b) << 16), + ), + ( + 'trunc_hi', + r'min\(v(\d+), 0xffffu\) \| \(min\(v(\d+), 0xffffu\) << 16u\)', + r'min(v\1, 0xffffu) | ((v\2 & 0xffffu) << 16u)', + lambda a, b: sat_u16(a) | ((b & 0xffff) << 16), + ), + ( + 'swap_halves', + r'min\(v(\d+), 0xffffu\) \| \(min\(v(\d+), 0xffffu\) << 16u\)', + r'min(v\2, 0xffffu) | (min(v\1, 0xffffu) << 16u)', + lambda a, b: sat_u16(b) | (sat_u16(a) << 16), + ), + ( + 'signed_clamp', + r'min\(v(\d+), 0xffffu\) \| \(min\(v(\d+), 0xffffu\) << 16u\)', + r'(asuint(clamp(asint(v\1), -32768, 32767)) & 0xffffu) | ' + r'(asuint(clamp(asint(v\2), -32768, 32767)) << 16u)', + ref_pk_i16, + ), + ), + 'v_cvt_pk_i16_i32': ( + ( + 'trunc_lo', + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) & 0xffffu\) \| ' + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) << 16u\)', + r'(v\1 & 0xffffu) | (asuint(clamp(asint(v\2), -32768, 32767)) << 16u)', + lambda a, b: (a & 0xffff) | (sat_i16(b) << 16), + ), + ( + 'trunc_hi', + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) & 0xffffu\) \| ' + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) << 16u\)', + r'(asuint(clamp(asint(v\1), -32768, 32767)) & 0xffffu) | ((v\2 & 0xffffu) << 16u)', + lambda a, b: sat_i16(a) | ((b & 0xffff) << 16), + ), + ( + 'swap_halves', + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) & 0xffffu\) \| ' + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) << 16u\)', + r'(asuint(clamp(asint(v\2), -32768, 32767)) & 0xffffu) | ' + r'(asuint(clamp(asint(v\1), -32768, 32767)) << 16u)', + lambda a, b: sat_i16(b) | (sat_i16(a) << 16), + ), + ( + 'unsigned_clamp', + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) & 0xffffu\) \| ' + r'\(asuint\(clamp\(asint\(v(\d+)\), -32768, 32767\)\) << 16u\)', + r'min(v\1, 0xffffu) | (min(v\2, 0xffffu) << 16u)', + ref_pk_u16, + ), + ), +} + +BOUNDARY_WORDS = ( + 0x00000000, 0x00000001, 0x00007ffe, 0x00007fff, 0x00008000, 0x00008001, + 0x0000fffe, 0x0000ffff, 0x00010000, 0x00010001, 0x00012345, 0x12345678, + 0x7ffffffe, 0x7fffffff, 0x80000000, 0x80000001, 0xffff0000, 0xffff7ffe, + 0xffff7fff, 0xffff8000, 0xffff8001, 0xfffffffe, 0xffffffff, 0xdeadbeef, + 0x3f000000, 0xbf800000, +) + +# 16 (src0, src1, unused_src2) triples per opcode (4 draws x 4 lanes). +DRAW = { + 'v_cvt_pk_u16_u32': [ + (0x00010002, 0x00020003, 0), + (0x00008000, 0x00010001, 0), + (0xffffffff, 0x00001234, 0), + (0x80000001, 0x7ffffffe, 0), + (0x00000000, 0x00000000, 0), + (0x00000001, 0x0000ffff, 0), + (0x0000ffff, 0x00000001, 0), + (0x0000fffe, 0x00010000, 0), + (0x00010000, 0x0000fffe, 0), + (0x12345678, 0x0000abcd, 0), + (0x0000fedc, 0x87654321, 0), + (0x7fffffff, 0x80000000, 0), + (0x00000000, 0xffffffff, 0), + (0xffffffff, 0x00000000, 0), + (0x00007fff, 0x00008000, 0), + (0xdeadbeef, 0x0000cafe, 0), + ], + 'v_cvt_pk_i16_i32': [ + (0x00008000, 0xffff7fff, 0), + (0x7fffffff, 0x80000001, 0), + (0xffff0001, 0x00010002, 0), + (0x80000000, 0x00007ffe, 0), + (0x00000000, 0x00000000, 0), + (0x00007fff, 0xffff8000, 0), + (0xffff8000, 0x00007fff, 0), + (0xffffffff, 0x00000001, 0), + (0x00000001, 0xffffffff, 0), + (0xffff8001, 0x00007ffe, 0), + (0x00001234, 0xffffedcc, 0), + (0xfffffffe, 0xffff7ffe, 0), + (0x00008001, 0x00010000, 0), + (0x00000000, 0xffffffff, 0), + (0xffffffff, 0x00000000, 0), + (0xcafebabe, 0x00001357, 0), + ], +} + + +def eval_hlsl_uint_expr(expr, env): + """Evaluate a translated HLSL uint expression for v_cvt_pk_{u16_u32,i16_i32} on 32-bit unsigned inputs.""" + py = re.sub(r'\b(0x[0-9a-fA-F]+|\d+)u\b', r'\1', expr) + scope = { + 'min': min, + 'clamp': lambda x, lo, hi: max(lo, min(hi, x)), + 'asint': lambda u: signed(u & MASK), + 'asuint': lambda i: i & MASK, + **{k: v & MASK for k, v in env.items()}, + } + return eval(py, {'__builtins__': {}}, scope) & MASK + + +def translate(op, mut_entry=None): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()) + text = pipe.hlsl_ps() + if mut_entry is not None: + name, pattern, replacement, _ = mut_entry + mutated, count = re.subn(pattern, replacement, text) + assert count == 4 and mutated != text, (op, name, count) + text = mutated + return pipe, text + + +def decode_single(word): + ins = G.decode(word) + assert len(ins) == 1, ins + _, _, name, asm = ins[0] + probe = Probe() + probe.one(name, asm) + return probe.lines + + +def controls(): + # 1. Verify recorded VOP3A encodings round-trip through disasm_rdna2.decode_instruction. + for text, raw in CANONICAL_CASES + DISASM_EXTRA_CASES: + n, _, asm, _ = D.decode_instruction(raw, 0) + check(f'disasm_rdna2 round-trip: {text}', n == len(raw) and asm == text) + for op, blob in BODY_WORDS.items(): + off, lines = 0, [] + while off < len(blob): + n, _, asm, _ = D.decode_instruction(blob, off) + lines.append(asm + '\n') + off += n + check(f'{op}: BODY_WORDS matches BODY_SOURCE', ''.join(lines) == BODY_SOURCE[op]) + + # 2. Exhaustive boundary-pair evaluation of the live emitted HLSL expressions against independent ISA math. + grid = [(a, b) for a in BOUNDARY_WORDS for b in BOUNDARY_WORDS] + for op in OPCODES: + _, ps_text = translate(op) + lanes = dict(re.findall(r'^\s*v(1[2-5]) = (.*);$', ps_text, re.M)) + check(f'{op}: four lanes translated', sorted(lanes) == ['12', '13', '14', '15']) + expr0 = lanes['12'] + ref_fn = REF[op] + mismatches = 0 + for a, b in grid: + if eval_hlsl_uint_expr(expr0, {'v0': a, 'v4': b}) != ref_fn(a, b): + mismatches += 1 + check(f'{op}: {len(grid)} boundary pairs match ISA saturation reference', mismatches == 0) + + first = DRAW[op][:4] + ref_first = [ref_fn(a, b) for a, b, _ in first] + for mut in MUTATIONS[op]: + mut_name, _, _, mut_fn = mut + _, mut_text = translate(op, mut) + mut_lanes = dict(re.findall(r'^\s*v(1[2-5]) = (.*);$', mut_text, re.M)) + mut_first = [mut_fn(a, b) for a, b, _ in first] + eval_first = [ + eval_hlsl_uint_expr(mut_lanes[str(12 + i)], {f'v{i}': first[i][0], f'v{4 + i}': first[i][1]}) + for i in range(4) + ] + check(f'{op} ({mut_name}): mutates draw set 0 and matches mutated model', + eval_first == mut_first and mut_first != ref_first) + + # 3. ComputePipeline, _e64 alias, inline negative/float constants, literals, and EXEC-masked emission. + cs_blob = ( + vop3a(0x36a, 1, 4, 255, lit=0x00012345) + + vop3a(0x36b, 2, 208, 242) # -16 and 1.0 (0x3f800000) + + struct.pack('<I', 0xbf810000) + ) + cs_hlsl = G.ComputePipeline(cs_blob, root_blob(), (4 << 1) | (1 << 7), (1, 1, 1)).hlsl_cs() + check('ComputePipeline: SGPR, literal, inline -16 and inline 1.0 lower cleanly', + 'v1 = min(s4, 0xffffu) | (min(0x00012345u, 0xffffu) << 16u);' in cs_hlsl + and 'v2 = (asuint(clamp(asint(0xfffffff0u), -32768, 32767)) & 0xffffu) | ' + '(asuint(clamp(asint(0x3f800000u), -32768, 32767)) << 16u);' in cs_hlsl) + + for op in OPCODES: + p_e64 = Probe() + p_e64.one(f'{op}_e64', f'{op}_e64 v1, v2, s4') + check(f'{op}_e64: explicit _e64 suffix accepted', len(p_e64.lines) == 1) + + masked = Probe() + masked.exec_known = False + masked.one(op, f'{op} v1, v2, v3') + check(f'{op}: exec-masked emission guards assignment', + len(masked.lines) == 1 and masked.lines[0].startswith('if (exec & 1) v1 = ')) + + # 4. UNIFORM_VALU (v_readfirstlane_b32) and odd-dmask D16 low16_only_v provenance. + class DummyPipe: + resources = {} + uavs = {} + rtv_formats = () + srv_formats = {} + + def __init__(self): + self.uds = [] + + def resource(self, key, kind): + self.resources.setdefault(key, {'index': 0, 'kind': kind}) + return 'r0' + + def ud(self, tag): + if tag not in self.uds: + self.uds.append(tag) + return self.uds.index(tag) + + def run_stage(*instructions): + s = G.Stage.__new__(G.Stage) + s.pipe, s.kind, s.lines = DummyPipe(), 'ps', [] + s.attrs, s.exports, s.write_masks = {}, {}, {} + s.sym = {16 + i: ('desc', ('table', 0), 0, i) for i in range(8)} + s.used_s, s.used_v, s.masks = set(), set(), set() + s.exec_known = True + s.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + s.translate() + return [line for _, lines, _ in s.blocks for line in lines] + + for op in OPCODES: + u_lines = run_stage(f'{op} v7, s2, 0x1234', 'v_readfirstlane_b32 s9, v7') + check(f'{op}: uniform SGPR/constant pack proves v_readfirstlane_b32', u_lines[-1] == 's9 = v7;') + try: + run_stage(f'{op} v7, s2, v0', 'v_readfirstlane_b32 s9, v7') + except G.Unsupported as exc: + check(f'{op}: varying VGPR source refuses v_readfirstlane_b32', 'proven uniform source' in str(exc)) + else: + raise AssertionError(f'{op}: varying source unexpectedly accepted by v_readfirstlane_b32') + + odd_d16 = 'image_load v4, v[0:1], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D d16' + for bad_seq in ((odd_d16, f'{op} v5, v4, v2'), (odd_d16, f'{op} v5, v2, v4')): + try: + run_stage(*bad_seq) + except G.Unsupported as exc: + assert 'whole-word read of v4' in str(exc), exc + else: + raise AssertionError(f'{op}: accepted odd-dmask D16 source without masking') + cleared = run_stage(odd_d16, f'{op} v4, v2, v3', 'v_add_nc_u32_e32 v5, 1, v4') + check(f'{op}: whole-VGPR destination overwrite clears low16_only_v', cleared[-1] == 'v5 = 0x00000001u + v4;') + + # 5. Binary VOP3A encoding-guard and Stage.one refusal controls. + for op, code in OPCODES.items(): + modifiers = [ + ('clamp', vop3a(code, 12, 256, 260, clamp=1)), + ('omod=mul:2', vop3a(code, 12, 256, 260, omod=1)), + ('omod=mul:4', vop3a(code, 12, 256, 260, omod=2)), + ('omod=div:2', vop3a(code, 12, 256, 260, omod=3)), + ('op_sel=[1,0]', vop3a(code, 12, 256, 260, op_sel=1)), + ('op_sel=[0,1]', vop3a(code, 12, 256, 260, op_sel=2)), + ('op_sel_dst', vop3a(code, 12, 256, 260, op_sel=8)), + ] + abs_neg = [ + ('abs src0 VGPR', vop3a(code, 12, 256, 260, abs_bits=1)), + ('abs src1 VGPR', vop3a(code, 12, 256, 260, abs_bits=2)), + ('abs unused src2', vop3a(code, 12, 256, 260, abs_bits=4)), + ('abs src0 inline 1', vop3a(code, 12, 129, 260, abs_bits=1)), + ('neg src0 VGPR', vop3a(code, 12, 256, 260, neg=1)), + ('neg src1 VGPR', vop3a(code, 12, 256, 260, neg=2)), + ('neg unused src2', vop3a(code, 12, 256, 260, neg=4)), + ('neg src0 inline 1', vop3a(code, 12, 129, 260, neg=1)), + ('neg src1 inline 1', vop3a(code, 12, 256, 129, neg=2)), + ] + unused_src2 = [ + ('src2=1', vop3a(code, 12, 256, 260, src2=1)), + ('src2=256', vop3a(code, 12, 256, 260, src2=256)), + ] + for label, bad_word in modifiers + abs_neg + unused_src2: + try: + G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + bad_word + POST_WORDS, root_blob()) + except G.Unsupported: + pass + else: + raise AssertionError(f'{op}: accepted binary VOP3A with {label}') + for label, bad_word in abs_neg: + reasons = [] + G.decode(bad_word, reasons) + check(f'{op}: encoding guard refuses {label}', + [r for r, _ in reasons] == [f'{op} with neg/abs']) + for label, bad_word in unused_src2: + reasons = [] + G.decode(bad_word, reasons) + check(f'{op}: encoding guard refuses {label}', + [r for r, _ in reasons] == [f'{op} with unused src2 field set']) + + check(f'{op}: Stage refuses non-VOP3 spellings, modifiers, lane masks and bad operands', all(refused(asm) for asm in ( + f'{op}_e32 v1, v2, v3', + f'{op}_sdwa v1, v2, v3 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD', + f'{op}_dpp v1, v2, v3 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf', + f'{op}_dpp v1, v2, v3 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf bound_ctrl:1', + f'{op} v1, v2, v3 clamp', + f'{op} v1, v2, v3 mul:2', + f'{op} v1, v2, v3 div:2', + f'{op} v1, v2, v3 op_sel:[1,0]', + f'{op} v1, |v2|, v3', + f'{op} v1, v2, |v3|', + f'{op} v1, -v2, v3', + f'{op} v1, v2, -v3', + f'{op} v1, vcc_lo, v3', + f'{op} v1, v2, exec_lo', + f'{op} s0, v2, v3', + f'{op} v[0:1], v2, v3', + f'{op} v1, v[2:3], v4', + f'{op} v1, s[2:3], v4', + f'{op} v1, s106, v4', + f'{op} v1, 0x100000000, v4', + f'{op}', + f'{op} v1', + f'{op} v1, v2', + f'{op} v1, v2, v3, v4', + ))) + + # 6. Unlowered control: removing the entries from VEC_U must restore refusals. + saved = {op: G.VEC_U.pop(op) for op in OPCODES} + try: + for op in OPCODES: + try: + translate(op) + except G.Unsupported: + pass + else: + raise AssertionError(f'{op}: translated after removal from VEC_U') + assert refused(f'{op} v1, v2, v3'), op + finally: + G.VEC_U.update(saved) + check('unlowered control: removing v_cvt_pk_{u16_u32,i16_i32} from VEC_U restores refusals', True) + + +def check_binary(llvm_mc): + for op, src in BODY_SOURCE.items(): + built = assemble(llvm_mc, src) + assert built == BODY_WORDS[op], f'{op}: assembled {built.hex()}, recorded {BODY_WORDS[op].hex()}' + for text, expected in CANONICAL_CASES: + built = assemble(llvm_mc, text + '\n') + assert built == expected, f'{text}: assembled {built.hex()}, recorded {expected.hex()}' + # Explicit _e64 spelling assembles to the identical VOP3A word. + for op, code in OPCODES.items(): + assert assemble(llvm_mc, f'{op}_e64 v12, v0, v4\n') == vop3a(code, 12, 256, 260) + for name, source, raw in (('prologue', PRE_SOURCE, PRE_WORDS), ('export', POST_SOURCE, POST_WORDS)): + assert assemble(llvm_mc, source) == raw, f'{name} fixture differs from llvm-mc' + for op, sets in DRAW.items(): + for i in range(0, len(sets), 4): + chunk = sets[i:i + 4] + assert assemble(llvm_mc, vs_source(chunk)) == vs_words(chunk), (op, chunk) + print('llvm-mc: all VOP3A cases, _e64 aliases and draw fixtures match recorded words') + + +def check_decode(library): + from pixel_aot import disassemble + blob = b''.join(raw for _, raw in CANONICAL_CASES) + llvm_lines = disassemble(blob, library) + ours = [text for text, _ in CANONICAL_CASES] + assert llvm_lines == ours, f'LLVM vs disasm_rdna2 mismatch: {list(zip(llvm_lines, ours))}' + print(f'libLLVM: {len(CANONICAL_CASES)} VOP3A encodings match disasm_rdna2.py verbatim') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + draws = mut_checks = 0 + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op, triples in DRAW.items(): + ref_fn = REF[op] + good_ps = compile_hlsl(compiler, kind, translate(op)[1], f'ps_{op}_{kind}', ps_profile, directory) + for index in range(0, len(triples), 4): + chunk = triples[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs(), + f'vs_{op}_{index}_{kind}', vs_profile, directory) + expected = words_text(ref_fn(a, b) for a, b, _ in chunk) + run = draw(renderer, adapter, vs, good_ps, expected) + if run.returncode: + raise AssertionError(f'{kind} {op} inputs {chunk}\n{run.stdout}\n{run.stderr}') + draws += 1 + print(f'{kind} {op} {[tuple(f"{v:x}" for v in t[:2]) for t in chunk]}: {expected}', flush=True) + if index: + continue + for mut in MUTATIONS[op]: + mut_name, _, _, mut_fn = mut + wrong = words_text(mut_fn(a, b) for a, b, _ in chunk) + bad_ps = compile_hlsl(compiler, kind, translate(op, mut)[1], + f'mut_{op}_{mut_name}_{kind}', ps_profile, directory) + mrun = draw(renderer, adapter, vs, bad_ps, expected) + if mrun.returncode == 0 or f'actual={wrong}' not in mrun.stderr: + raise AssertionError( + f'{kind} {op} mutation {mut_name} did not read {wrong}\n{mrun.stdout}\n{mrun.stderr}' + ) + mut_checks += 1 + print(f'{kind} {op} mutation ({mut_name}): fails as expected, reads {wrong}', flush=True) + print(f'{adapter}: {draws} draws matched, {mut_checks} mutated draws read their mutated words') + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary' and len(args) == 1: + check_binary(args[0]) + elif mode == 'decode' and len(args) == 1: + check_decode(args[0]) + elif mode == 'draw' and len(args) in (3, 4): + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 03aa977d2..ea7957264 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -431,12 +431,14 @@ def check_encoding(code, off, n, name, asm): word0, word1 = struct.unpack_from('<2I', code, off) if word0 & 0x700 or word1 & 0xe0000000: raise Unsupported('%s with neg/abs: not a 16-bit integer source modifier' % name) - if name in ('v_sad_u8', 'v_sad_u16', 'v_sad_u32'): - # VOP3A integer SAD forms take no source abs/neg; refuse those bits here so neg on an inline + if name in ('v_sad_u8', 'v_sad_u16', 'v_sad_u32', *VOP3_ONLY_VEC_U): + # VOP3A integer forms take no source abs/neg; refuse those bits here so neg on an inline # integer does not print as -N and get accepted as a negative constant. word0, word1 = struct.unpack_from('<2I', code, off) if word0 & 0x700 or word1 & 0xe0000000: raise Unsupported('%s with neg/abs' % name) + if name in VOP3_ONLY_VEC_U and (word1 >> 18) & 0x1ff: + raise Unsupported('%s with unused src2 field set' % name) if name == 'v_cvt_off_f32_i4_e64': # Integer-nibble conversion: the instruction has one source, so only src0's VOP3A ABS (w0[8]) and NEG # (w1[29]) can carry a modifier. Masking all three bit positions of each field (w0[10:8], w1[31:29]) @@ -844,6 +846,7 @@ def smem_mods(mods): # only local arithmetic. Move copies its input bits. None reads a lane ID or another lane. UNIFORM_VALU = frozenset(( 'v_cvt_u32_f32', 'v_cvt_i32_f32', 'v_cvt_f32_u32', 'v_cvt_f32_ubyte0', 'v_cvt_off_f32_i4', + 'v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32', 'v_mul_f32', 'v_fma_f32', 'v_fmaak_f32', 'v_rcp_f32', 'v_med3_f32', 'v_mov_b32', )) @@ -1798,7 +1801,7 @@ def u(self, tok, *, low16_only=False): def is_lane_mask(self, tok): reg = reg_range(tok) return (tok in ('exec', 'exec_lo', 'exec_hi', 'vcc', 'vcc_lo', 'vcc_hi') - or bool(reg and reg[0] == 's' and reg[1] in self.masks)) + or bool(reg and reg[0] == 's' and reg[1] in getattr(self, 'masks', ()))) @staticmethod def split_neg(tok): @@ -2664,6 +2667,8 @@ def uniform_source(self, tok): def one(self, name, asm): _, ops, mods = parse(asm) + if name.endswith('_e32') and name[:-4] in VOP3_ONLY_VEC_U: + raise Unsupported(name) base = re.sub(r'_e(32|64)$', '', name) # Compute the proof before lowering, since a destination can also be a source. dst = None @@ -2955,6 +2960,24 @@ def lower(self, base, asm, ops, mods): raise Unsupported('%s with %s' % (base, mods)) if len(ops) != arity + 1: raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) + if base in VOP3_ONLY_VEC_U: + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[1] != dst[2] or dst[1] > 255: + raise Unsupported('%s destination %s' % (base, ops[0])) + for src in ops[1:1 + arity]: + if self.is_lane_mask(src): + raise Unsupported('%s on a lane mask' % base) + sr = reg_range(src) + if sr is not None: + if sr[1] != sr[2] or (sr[0] == 'v' and sr[1] > 255) or (sr[0] == 's' and sr[1] > 105): + raise Unsupported('%s source %s' % (base, src)) + elif src not in FLOATS and src != 'm0': + try: + val = int(src, 0) + except ValueError: + raise Unsupported('operand %r' % src) + if not -0x80000000 <= val <= 0xffffffff: + raise Unsupported('%s source %s' % (base, src)) if base == 'v_and_b32': c0, c1 = self.const_u32(ops[1]), self.const_u32(ops[2]) args = [self.u(ops[1], low16_only=c1 is not None and (c1 & 0xffff0000) == 0), @@ -3044,6 +3067,8 @@ def dpp_broadcast(self, base, ops, mods): # proved whole-quad EXEC: the hardware can return 0 or the old value for a source lane whose EXEC bit # is off (an uncovered pixel of an edge quad), and the intrinsics have no such case. Other permutations, fi:1 without that proof, DPP8, row shifts and partial masks stay refused. def dpp(self, base, ops, mods): + if base in VOP3_ONLY_VEC_U: + raise Unsupported('DPP form of %s' % base) # fi:1 (fetch inactive, DPP16 dword bit 18; LLVM AMDGPU `fi`, Mesa ACO fetch_inactive) only decides what a # disabled source lane returns. Every lowering below is taken only with the whole quad proven active, so no # source lane is disabled and it decides nothing. @@ -3117,7 +3142,7 @@ def dpp(self, base, ops, mods): # VEC_U_TO_F conversions apply output modifiers before dst_sel, VEC_F forms stay refused, and # dst_unused UNUSED_SEXT has no lowering. def sdwa(self, base, ops, mods): - if base == 'v_cvt_off_f32_i4': + if base in ('v_cvt_off_f32_i4', *VOP3_ONLY_VEC_U): raise Unsupported('SDWA form of %s' % base) fields = {} out_mods = [] @@ -6231,7 +6256,13 @@ def declarations(self): 'v_sad_u8': (3, 'sad_u8({0}, {1}, {2})'), 'v_sad_u16': (3, 'sad_u16({0}, {1}, {2})'), 'v_sad_u32': (3, 'sad_u32({0}, {1}, {2})'), + # Saturating 32-to-16-bit integer packs (AMD RDNA 2 ISA reference, VOP3A opcodes 0x36a and 0x36b; saturation + # bounds per Mesa NIR pack_uvec2_to_uint / pack_ivec2_to_uint selected in ACO): src0 -> low 16 bits, src1 -> high 16 bits. + 'v_cvt_pk_u16_u32': (2, 'min({0}, 0xffffu) | (min({1}, 0xffffu) << 16u)'), + 'v_cvt_pk_i16_i32': (2, '(asuint(clamp(asint({0}), -32768, 32767)) & 0xffffu) | ' + '(asuint(clamp(asint({1}), -32768, 32767)) << 16u)'), } +VOP3_ONLY_VEC_U = frozenset(('v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32')) # scalar ops: (expression over uint sources, SCC rule with $ for the result or None) # Scalar ops that write SCC on the hardware (carry, overflow, or which source was selected) but have # no SCC template here: the emitted scc keeps its previous value, so the uniformity proof stops From 069e64fe1279aed4c6a2967963749908d8cc8d3f Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:43:33 +0200 Subject: [PATCH 214/232] ci: harden script path validation and subprocess error handling in run_checks_parallel with CLI suite (#2598) --- CMakeLists.txt | 2 + tests/run_checks_parallel_cli_check.py | 340 +++++++++++++++++++++++++ tools/run_checks_parallel.py | 38 ++- 3 files changed, 375 insertions(+), 5 deletions(-) create mode 100644 tests/run_checks_parallel_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ef3e09517..06f0adefd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,8 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME pyc_main_entry COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pyc_main_check.py") set_tests_properties(pyc_main_entry PROPERTIES TIMEOUT 60) + add_test(NAME ci_run_checks_parallel_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/run_checks_parallel_cli_check.py") endif() set(DSTORAGE_SDK_ROOT "" CACHE PATH "Extracted Microsoft.Direct3D.DirectStorage NuGet package") diff --git a/tests/run_checks_parallel_cli_check.py b/tests/run_checks_parallel_cli_check.py new file mode 100644 index 000000000..81590d689 --- /dev/null +++ b/tests/run_checks_parallel_cli_check.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +"""Pure-Python CLI, path-validation, subprocess-error, and mutation suite for tools/run_checks_parallel.py.""" + +import concurrent.futures +from contextlib import redirect_stderr, redirect_stdout +import inspect +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "run_checks_parallel.py" +sys.path.insert(0, str(TOOLS_DIR)) +import run_checks_parallel as R # noqa: E402 + + +def _run_cli(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = R.main(argv) + except SystemExit as exc: + code = exc.code + rc = 0 if code is None else (int(code) if isinstance(code, int) else 1) + if not isinstance(code, (type(None), int)): + stderr.write(f"{code}\n") + return rc, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + errors="replace", + env=env, + timeout=30, + ) + + +class RunChecksParallelCliPositiveTests(unittest.TestCase): + def test_signature_and_main_positive_modes(self): + sig = inspect.signature(R.run_checks) + params = list(sig.parameters.values()) + self.assertEqual([p.name for p in params], ["checks", "jobs"]) + self.assertIs(params[1].default, None) + self.assertEqual(R.SKIP_EXIT_CODE, 77) + + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + ok1 = base / "ok1.py" + ok2 = base / "ok2.py" + ok1.write_text("import sys\nassert sys.flags.dont_write_bytecode\nprint('one')\n", encoding="utf-8") + ok2.write_text("print('two')\n", encoding="utf-8") + + rc, stdout, stderr = _run_cli([str(ok1), str(ok2)]) + self.assertIs(type(rc), int) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn(f"::group::{ok1} (ok, ", stdout) + self.assertIn(f"::group::{ok2} (ok, ", stdout) + self.assertLess(stdout.index("one\n"), stdout.index("two\n")) + self.assertEqual(stdout.splitlines().count("::endgroup::"), 2) + self.assertIn("all 2 checks passed", stdout) + + # main(None) reads sys.argv. + with mock.patch.object(sys, "argv", [str(TOOL), str(ok1)]): + rc_argv, out_argv, err_argv = _run_cli(None) + self.assertIs(type(rc_argv), int) + self.assertEqual(rc_argv, 0, err_argv) + self.assertEqual(err_argv, "") + self.assertIn("all 1 checks passed", out_argv) + + # __main__ entrypoint raises SystemExit(0). + out_main, err_main = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(ok2)]), + redirect_stdout(out_main), + redirect_stderr(err_main), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(err_main.getvalue(), "") + self.assertIn("all 1 checks passed", out_main.getvalue()) + + # Subprocess positive smoke test. + proc = _run_subprocess(str(ok1), str(ok2)) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("all 2 checks passed", proc.stdout) + + def test_jobs_clamping_ordering_skip_and_env_isolation(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + slow = base / "slow.py" + fast = base / "fast.py" + skip = base / "skip.py" + partial = base / "partial.py" + env_echo = base / "env_echo.py" + + slow.write_text("import time\ntime.sleep(0.08)\nprint('slow done')\n", encoding="utf-8") + fast.write_text("print('fast done')\n", encoding="utf-8") + skip.write_text("import sys\nprint('skip reason')\nsys.exit(77)\n", encoding="utf-8") + partial.write_text("import sys\nsys.stderr.write('partial line')\nsys.exit(3)\n", encoding="utf-8") + env_echo.write_text( + "import os, sys\nprint(sys.argv[1], os.environ.get('RCP_CLI_VAR', 'unset'))\n", + encoding="utf-8", + ) + + seen_workers: list[int] = [] + real_executor = concurrent.futures.ThreadPoolExecutor + + def tracking_executor(*args, **kwargs): + seen_workers.append(kwargs.get("max_workers")) + return real_executor(*args, **kwargs) + + with mock.patch.object(R.concurrent.futures, "ThreadPoolExecutor", side_effect=tracking_executor): + rc_zero, out_zero, err_zero = _run_cli(["-j", "0", str(fast)]) + self.assertEqual(rc_zero, 0, err_zero) + self.assertIn("all 1 checks passed", out_zero) + + stdout_buf = io.StringIO() + with redirect_stdout(stdout_buf): + rc_neg = R.run_checks([([str(fast)], None)], jobs=-4) + self.assertEqual(rc_neg, 0) + + self.assertEqual(seen_workers, [1, 1]) + + # Ordered groups, partial newline normalization, SKIP_EXIT_CODE=77, and FAILED ordering. + buf = io.StringIO() + with redirect_stdout(buf): + rc_mix = R.run_checks( + [([str(slow)], None), ([str(skip)], None), ([str(partial)], None), ([str(fast)], None)], + jobs=4, + ) + text = buf.getvalue() + self.assertEqual(rc_mix, 1) + self.assertLess(text.index("slow done\n"), text.index("skip reason\n")) + self.assertLess(text.index("skip reason\n"), text.index("partial line\n::endgroup::")) + self.assertLess(text.index("partial line\n"), text.index("fast done\n")) + self.assertIn(f"::group::{skip} (exit 77, ", text) + self.assertIn(f"::group::{partial} (exit 3, ", text) + self.assertIn(f"FAILED: {partial}\n", text) + self.assertIn(f"SKIPPED: {skip}\n", text) + + # Per-check extra_env must not leak across siblings. + env_buf = io.StringIO() + with mock.patch.dict(os.environ, {"RCP_CLI_VAR": "base"}): + with redirect_stdout(env_buf): + rc_env = R.run_checks( + [([str(env_echo), "a"], {"RCP_CLI_VAR": "custom"}), ([str(env_echo), "b"], None)], + jobs=2, + ) + self.assertEqual(rc_env, 0) + env_out = env_buf.getvalue() + self.assertIn("a custom\n", env_out) + self.assertIn("b base\n", env_out) + + def test_invalid_utf8_child_output_uses_replacement_without_crash(self): + with tempfile.TemporaryDirectory() as tmp: + script = Path(tmp) / "emit_bad_bytes.py" + script.write_text("import sys\nsys.stdout.buffer.write(b'ok \\xff\\xfe\\n')\n", encoding="utf-8") + env = dict(os.environ, PYTHONIOENCODING="utf-8") + proc = _run_subprocess(str(script), env=env) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("all 1 checks passed", proc.stdout) + + +class RunChecksParallelCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + expected_substrings: tuple[str, ...] = (), + check_subprocess: bool = False, + ) -> str: + rc, stdout, stderr = _run_cli(argv) + if expected_code is None: + self.assertNotEqual(rc, 0) + else: + self.assertEqual(rc, expected_code, stderr) + self.assertEqual(stdout, "") + self.assertTrue(stderr.strip()) + self.assertNotIn("Traceback", stderr) + for fragment in expected_substrings: + self.assertIn(fragment, stderr) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code) + self.assertEqual(proc.stdout, "") + self.assertTrue(proc.stderr.strip()) + self.assertNotIn("Traceback", proc.stderr) + for fragment in expected_substrings: + self.assertIn(fragment, proc.stderr) + return stderr + + def test_argparse_rejections_are_py314_compatible(self): + # Missing positional scripts argument. + err_missing = self._assert_clean_failure([], expected_code=None, check_subprocess=True) + self.assertIn("required", err_missing.lower()) + + # Invalid -j integer argument. + with tempfile.TemporaryDirectory() as tmp: + ok = Path(tmp) / "ok.py" + ok.write_text("print('ok')\n", encoding="utf-8") + err_jobs = self._assert_clean_failure(["-j", "abc", str(ok)], expected_code=None, check_subprocess=True) + self.assertIn("invalid", err_jobs.lower()) + + def test_upfront_script_path_validation_guards_kill_mutations(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + valid = base / "valid.py" + valid.write_text("print('should not run')\n", encoding="utf-8") + missing = base / "missing.py" + script_dir = base / "dir_as_script" + script_dir.mkdir() + + invalid_cases = ( + ("missing_single", [str(missing)], (str(missing), "does not exist"), True), + ("dir_single", [str(script_dir)], (str(script_dir), "directory"), True), + ("empty_str", [""], ("empty",), False), + ("whitespace_str", [" "], ("empty",), False), + # Second script invalid: kills missing upfront loop / running first check anyway. + ("second_missing", [str(valid), str(missing)], (str(missing), "does not exist"), True), + ("second_dir", [str(valid), str(script_dir)], (str(script_dir), "directory"), True), + ) + for label, argv, fragments, subproc in invalid_cases: + with self.subTest(case=label): + with mock.patch.object( + R, + "run_checks", + side_effect=AssertionError(f"run_checks called for invalid case {label}"), + ): + self._assert_clean_failure( + argv, + expected_code=1, + expected_substrings=fragments, + check_subprocess=subproc, + ) + + # Existing non-regular path (e.g. FIFO/special file): kills removal of `not path.is_file()`. + with ( + mock.patch.object(R.Path, "exists", return_value=True), + mock.patch.object(R.Path, "is_dir", return_value=False), + mock.patch.object(R.Path, "is_file", return_value=False), + mock.patch.object(R, "run_checks", side_effect=AssertionError("run_checks must not be called")), + ): + self._assert_clean_failure( + [str(valid)], + expected_code=1, + expected_substrings=(str(valid), "regular file"), + ) + + def test_run_one_catches_oserror_and_subprocess_error_without_crashing_pool(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + broken = base / "broken.py" + healthy = base / "healthy.py" + broken.write_text("print('broken')\n", encoding="utf-8") + healthy.write_text("print('healthy ok')\n", encoding="utf-8") + + error_cases = ( + ("filenotfound", FileNotFoundError("python missing"), "FileNotFoundError: python missing"), + ("permission", PermissionError("access denied"), "PermissionError: access denied"), + ("subproc_err", subprocess.SubprocessError("spawn failure"), "SubprocessError: spawn failure"), + ("timeout_err", subprocess.TimeoutExpired(["python"], 5), "TimeoutExpired:"), + ("empty_oserror", OSError(), "OSError"), + ) + for label, exc, expected_msg in error_cases: + with self.subTest(case=label): + with mock.patch.object(R.subprocess, "run", side_effect=exc): + script, code, output, elapsed = R.run_one(([str(broken)], None)) + self.assertEqual(script, str(broken)) + self.assertNotEqual(code, 0) + self.assertEqual(code, 1) + self.assertGreaterEqual(elapsed, 0.0) + self.assertIn(expected_msg, output) + self.assertTrue(output.endswith("\n")) + self.assertNotIn("Traceback", output) + + # Empty command raises ValueError cleanly (guarded by main()). + with self.assertRaises(ValueError): + R.run_one(([], None)) + + # Pool isolation: one failing spawn must not crash ThreadPoolExecutor or lose sibling output. + real_run = subprocess.run + + def selective_run(cmd, *args, **kwargs): + if str(broken) in cmd: + raise OSError("cannot execute python") + return real_run(cmd, *args, **kwargs) + + buf = io.StringIO() + with mock.patch.object(R.subprocess, "run", side_effect=selective_run): + with redirect_stdout(buf): + rc = R.run_checks([([str(broken)], None), ([str(healthy)], None)], jobs=2) + out = buf.getvalue() + self.assertEqual(rc, 1) + self.assertIn(f"::group::{broken} (exit 1, ", out) + self.assertIn("OSError: cannot execute python\n", out) + self.assertIn(f"::group::{healthy} (ok, ", out) + self.assertIn("healthy ok\n", out) + self.assertEqual(out.splitlines().count("::endgroup::"), 2) + self.assertIn(f"FAILED: {broken}\n", out) + self.assertNotIn("Traceback", out) + + def test_main_guards_value_os_and_subprocess_errors(self): + with tempfile.TemporaryDirectory() as tmp: + ok = Path(tmp) / "ok.py" + ok.write_text("print('ok')\n", encoding="utf-8") + + for label, exc, expected in ( + ("value_error", ValueError("invalid command"), ("invalid command",)), + ("os_error", OSError("executor init failed"), ("executor init failed",)), + ("subproc_error", subprocess.SubprocessError("subproc failure"), ("subproc failure",)), + ("empty_value_error", ValueError(), ("ValueError",)), + ): + with self.subTest(case=label): + with mock.patch.object(R, "run_checks", side_effect=exc): + self._assert_clean_failure([str(ok)], expected_code=1, expected_substrings=expected) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/run_checks_parallel.py b/tools/run_checks_parallel.py index 2c0b2590f..c6703aa63 100644 --- a/tools/run_checks_parallel.py +++ b/tools/run_checks_parallel.py @@ -16,6 +16,7 @@ import argparse import concurrent.futures import os +from pathlib import Path import subprocess import sys import time @@ -23,13 +24,34 @@ SKIP_EXIT_CODE = 77 +def _validate_script_path(raw_path: str) -> str: + if not raw_path or not raw_path.strip(): + raise ValueError("script path must not be empty") + path = Path(raw_path) + if not path.exists(): + raise FileNotFoundError(f"script path does not exist: {raw_path}") + if path.is_dir(): + raise IsADirectoryError(f"script path is a directory: {raw_path}") + if not path.is_file(): + raise ValueError(f"script path is not a regular file: {raw_path}") + return raw_path + + def run_one(check): command, extra_env = check + if not command: + raise ValueError("check command must not be empty") env = {**os.environ, **extra_env} if extra_env else None start = time.monotonic() - proc = subprocess.run([sys.executable, "-B", *command], env=env, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - text=True, errors="replace") + try: + proc = subprocess.run([sys.executable, "-B", *command], env=env, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, errors="replace") + except (OSError, subprocess.SubprocessError) as exc: + detail = str(exc) + msg = f"{type(exc).__name__}: {detail}\n" if detail else f"{type(exc).__name__}\n" + return command[0], 1, msg, time.monotonic() - start return command[0], proc.returncode, proc.stdout, time.monotonic() - start @@ -59,12 +81,18 @@ def run_checks(checks, jobs=None): return 0 -def main(argv=None): +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("-j", "--jobs", type=int, default=os.cpu_count() or 2) parser.add_argument("scripts", nargs="+") args = parser.parse_args(argv) - return run_checks([([script], None) for script in args.scripts], jobs=args.jobs) + try: + scripts = [_validate_script_path(script) for script in args.scripts] + return run_checks([([script], None) for script in scripts], jobs=args.jobs) + except (ValueError, OSError, subprocess.SubprocessError) as exc: + detail = str(exc) + msg = f"{detail}\n" if detail else f"{type(exc).__name__}\n" + parser.exit(1, msg) if __name__ == "__main__": From d0585a0b639f858c95086ad5dbd4c6939909755b Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:45:31 +0200 Subject: [PATCH 215/232] shader: harden atomic report writes and path/collision guards in dxc_compile_time with CLI suite (#2581) * shader: harden atomic report writes and path/collision guards in dxc_compile_time with CLI suite * tests: bound dxc_compile_time_cli_check timeout and replace fake exe spawn --------- Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/dxc_compile_time_cli_check.py | 573 ++++++++++++++++++++++++++++ tools/dxc_compile_time.py | 138 ++++--- 3 files changed, 666 insertions(+), 48 deletions(-) create mode 100644 tests/dxc_compile_time_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 06f0adefd..e0d25db35 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4138,6 +4138,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME dxc_compile_time_gvn COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/dxc_compile_time_check.py" "${DXC_EXECUTABLE}") set_tests_properties(dxc_compile_time_gvn PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + add_test(NAME dxc_compile_time_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/dxc_compile_time_cli_check.py") + set_tests_properties(dxc_compile_time_cli_check PROPERTIES TIMEOUT 60) # Dispatch condstore_256 built with and without GVN; compare the whole raw UAV bit for bit (#775). foreach(adapter IN ITEMS warp hardware) add_test(NAME dxc_gvn_output_${adapter} COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/dxc_compile_time_cli_check.py b/tests/dxc_compile_time_cli_check.py new file mode 100644 index 000000000..0f7e89415 --- /dev/null +++ b/tests/dxc_compile_time_cli_check.py @@ -0,0 +1,573 @@ +"""CLI, atomic JSON/CSV report, path/collision guard, error handling, and mutation suite for tools/dxc_compile_time.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import csv +import io +import json +import os +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "dxc_compile_time.py" +sys.path.insert(0, str(ROOT / "tools")) + +import dxc_compile_time as tool # noqa: E402 + +SAMPLE_FTIME = ( + "; 0.1250 ( 75.0%) 0.0250 (100.0%) 0.1500 ( 80.0%) 0.1510 ( 80.0%) " + "Global Value Numbering\n" + "; 0.1550 (100.0%) 0.0250 (100.0%) 0.1800 (100.0%) 0.1888 (100.0%) Total\n" +) + +EXPECTED_JSON_TOP_KEYS = { + "recorded_utc", + "dxc", + "dxc_version", + "target", + "entry", + "flags", + "repeat", + "timeout_s", + "ftime_report", + "variants", +} + +EXPECTED_VARIANT_KEYS = { + "variant", + "family", + "size", + "hlsl_bytes", + "dxil_bytes", + "reps", + "wall_median_s", + "wall_min_s", + "wall_max_s", + "peak_median_mib", + "peak_max_mib", + "outcome", + "exit_codes", + "first_diagnostic", + "pass_total_s", + "passes", + "command", + "runs", +} + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = tool.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=15, + ) + + +def _fake_run_once(dxc, hlsl, cso, flags, timeout_s, sample_interval=0.005): + name = hlsl.stem + cso.write_bytes(b"DXBC" + b"\x00" * 12) + return { + "args": [str(dxc), *flags, "-Fo", str(cso), str(hlsl)], + "wall_s": 0.25 if name == "control" else 0.5, + "peak_bytes": 16 * 1024 * 1024, + "exit_code": 0, + "outcome": "dxil", + "cso_bytes": 16, + "first_diagnostic": "", + "output": SAMPLE_FTIME if "-ftime-report" in flags else "", + } + + +def _fake_subprocess_run(args, **kwargs): + return subprocess.CompletedProcess(args, 0, stdout="dxcompiler.dll: 1.8.2407\n", stderr="") + + +class DxcCompileTimeCliPositiveTests(unittest.TestCase): + def test_list_variants_and_entrypoint(self): + code, out, err = _run_main(["--list-variants"]) + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("variant", out) + self.assertIn("control", out) + self.assertIn("condstore_1024", out) + self.assertIn("stores_16384", out) + + proc = _run_subprocess("--list-variants") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(proc.stdout, out) + + cli_argv = [str(TOOL), "--list-variants"] + with mock.patch.object(sys, "argv", cli_argv): + code2, out2, err2 = _run_main(None) + self.assertIs(type(code2), int) + self.assertEqual(code2, 0, err2) + self.assertEqual(out2, out) + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", cli_argv), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(stdout.getvalue(), out) + + def test_atomic_json_and_csv_reports_with_mocked_dxc(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + fake_dxc = root / "dxc.exe" + fake_dxc.write_bytes(b"MZ") + work_dir = root / "work" + json_out = root / "nested" / "json" / "report.json" + csv_out = root / "nested" / "csv" / "report.csv" + + seen_replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + self.assertEqual(src_path.name, dst_path.name) + return real_replace(src, dst) + + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool.os, "replace", side_effect=tracking_replace), + ): + code, out, err = _run_main([ + "--dxc", str(fake_dxc), + "--variants", "control,condstore_64", + "--timeout", "90", + "--ftime-report", + "--work-dir", str(work_dir), + "--out", str(json_out), + ]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn(f"wrote {json_out}", out) + self.assertEqual(len(seen_replaces), 1) + self.assertEqual(sorted(p.name for p in json_out.parent.iterdir()), ["report.json"]) + self.assertEqual( + sorted(p.name for p in work_dir.iterdir()), + ["condstore_64.cso", "condstore_64.hlsl", "control.cso", "control.hlsl"], + ) + + doc = json.loads(json_out.read_text(encoding="utf-8")) + self.assertEqual(set(doc), EXPECTED_JSON_TOP_KEYS) + self.assertEqual(doc["dxc"], str(fake_dxc)) + self.assertEqual(doc["dxc_version"], "dxcompiler.dll: 1.8.2407") + self.assertEqual(doc["target"], tool.DEFAULT_TARGET) + self.assertEqual(doc["entry"], tool.DEFAULT_ENTRY) + self.assertEqual(doc["repeat"], 1) + self.assertEqual(doc["timeout_s"], 90.0) + self.assertTrue(doc["ftime_report"]) + self.assertEqual([v["variant"] for v in doc["variants"]], ["control", "condstore_64"]) + for variant_rec in doc["variants"]: + self.assertEqual(set(variant_rec), EXPECTED_VARIANT_KEYS) + self.assertEqual(variant_rec["outcome"], "dxil") + self.assertEqual(variant_rec["pass_total_s"], 0.18) + self.assertEqual(variant_rec["passes"][0]["name"], "Global Value Numbering") + + # Overwrite pre-existing JSON and write CSV report via atomic staging. + json_out.write_text("stale-json\n", encoding="utf-8") + seen_replaces.clear() + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool.os, "replace", side_effect=tracking_replace), + ): + code_j2, _, err_j2 = _run_main([ + "--dxc", str(fake_dxc), + "--variants", "control", + "--timeout", "90", + "--out", str(json_out), + ]) + code_c, out_c, err_c = _run_main([ + "--dxc", str(fake_dxc), + "--variants", "control,condstore_64", + "--timeout", "90", + "--ftime-report", + "--out", str(csv_out), + ]) + + self.assertEqual(code_j2, 0, err_j2) + self.assertEqual(code_c, 0, err_c) + self.assertIn(f"wrote {csv_out}", out_c) + self.assertEqual(len(seen_replaces), 2) + self.assertEqual(sorted(p.name for p in json_out.parent.iterdir()), ["report.json"]) + self.assertEqual(sorted(p.name for p in csv_out.parent.iterdir()), ["report.csv"]) + self.assertEqual( + [v["variant"] for v in json.loads(json_out.read_text(encoding="utf-8"))["variants"]], + ["control"], + ) + + with csv_out.open("r", encoding="utf-8", newline="") as handle: + reader = csv.DictReader(handle) + self.assertEqual(reader.fieldnames, list(tool.CSV_FIELDS)) + rows = list(reader) + self.assertEqual([row["variant"] for row in rows], ["control", "condstore_64"]) + self.assertEqual(rows[0]["outcome"], "dxil") + self.assertIn("Global Value Numbering=0.150s", rows[0]["top_passes"]) + + # No --out writes nothing and still returns 0. + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + ): + code_no_out, out_no_out, err_no_out = _run_main([ + "--dxc", str(fake_dxc), + "--variants", "control", + "--timeout", "90", + ]) + self.assertEqual(code_no_out, 0, err_no_out) + self.assertIn("No --out given; nothing written", out_no_out) + + def test_dxc_version_handles_subprocess_outcomes(self): + fake_dxc = Path("fake-dxc.exe") + with mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run): + self.assertEqual(tool.dxc_version(fake_dxc), "dxcompiler.dll: 1.8.2407") + for exc in (OSError("missing"), subprocess.TimeoutExpired(["dxc", "--version"], 30)): + with mock.patch.object(tool.subprocess, "run", side_effect=exc): + self.assertEqual(tool.dxc_version(fake_dxc), "") + + +class DxcCompileTimeCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure(self, argv, *, expected_code=1, expected_fragment, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, expected_code, err) + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + if expected_code == 1: + self.assertIn("dxc_compile_time:", err) + else: + self.assertEqual(out, "") + + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, expected_code, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + if expected_code == 1: + self.assertIn("dxc_compile_time:", proc.stderr) + else: + self.assertEqual(proc.stdout, "") + + def test_argparse_and_cli_parameter_errors_exit_nonzero_cleanly(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + fake_dxc = root / "dxc.exe" + fake_dxc.write_bytes(b"MZ") + a_dir = root / "a_dir" + a_dir.mkdir() + missing_dxc = root / "missing_dxc.exe" + + cases = [ + (["--dxc", str(fake_dxc)], "--timeout"), + (["--dxc", str(fake_dxc), "--timeout", "0"], "positive"), + (["--dxc", str(fake_dxc), "--timeout", "10", "--repeat", "0"], "--repeat"), + (["--timeout", "10"], "--dxc"), + (["--dxc", str(missing_dxc), "--timeout", "10"], "DXC executable not found"), + (["--dxc", str(a_dir), "--timeout", "10"], "DXC executable not found"), + (["--dxc", str(fake_dxc), "--timeout", "10", "--variants", " , "], "selects nothing"), + (["--dxc", str(fake_dxc), "--timeout", "10", "--variants", "bogus_1"], "unknown variant"), + (["--dxc", str(fake_dxc), "--timeout", "10", "--variants", "condstore_65537"], "exceeds"), + (["--no-such-flag"], "unrecognized"), + ] + for argv, frag in cases: + with self.subTest(argv=argv): + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + tool.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self._assert_clean_failure( + argv, + expected_code=2, + expected_fragment=frag, + ) + + def test_upfront_out_and_work_dir_guards_kill_mutations(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + sub = root / "sub" + sub.mkdir() + fake_dxc = root / "dxc.exe" + dxc_bytes = b"MZ-DXC-SENTINEL" + fake_dxc.write_bytes(dxc_bytes) + + existing_dir = root / "existing_dir" + existing_dir.mkdir() + work_file = root / "work_file.txt" + work_file.write_text("keep-work-file\n", encoding="utf-8") + + dxc_alias = root / "sub" / ".." / "dxc.exe" + dxc_link = sub / "dxc_link.json" + os.link(fake_dxc, dxc_link) + self.assertNotEqual(fake_dxc.resolve(), dxc_link.resolve()) + self.assertTrue(fake_dxc.samefile(dxc_link)) + + # 1) --out is an existing directory (including ""). + for bad_out in (str(existing_dir), ""): + with mock.patch.object(tool, "measure_variant") as mv_mock: + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--timeout", "10", "--out", bad_out], + expected_fragment="existing directory", + check_subprocess=bool(bad_out), + ) + mv_mock.assert_not_called() + + # 2) --out collides with --dxc via resolve() and hardlink samefile(). + for bad_out in (dxc_alias, dxc_link): + with mock.patch.object(tool, "measure_variant") as mv_mock: + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--timeout", "10", "--out", str(bad_out)], + expected_fragment="collides with --dxc", + ) + mv_mock.assert_not_called() + self.assertEqual(fake_dxc.read_bytes(), dxc_bytes) + + # 3) --out collides with --work-dir via resolve(). + ghost_work = root / "new_work" + with mock.patch.object(tool, "measure_variant") as mv_mock: + self._assert_clean_failure( + [ + "--dxc", str(fake_dxc), "--timeout", "10", + "--work-dir", str(ghost_work), + "--out", str(root / "sub" / ".." / "new_work"), + ], + expected_fragment="collides with --work-dir", + ) + mv_mock.assert_not_called() + self.assertFalse(ghost_work.exists()) + + # 4) --work-dir is an existing regular file. + with mock.patch.object(tool, "measure_variant") as mv_mock: + self._assert_clean_failure( + [ + "--dxc", str(fake_dxc), "--timeout", "10", + "--work-dir", str(work_file), + ], + expected_fragment="existing regular file", + ) + mv_mock.assert_not_called() + self.assertEqual(work_file.read_text(encoding="utf-8"), "keep-work-file\n") + + def test_runtime_os_value_and_subprocess_errors_exit_1_cleanly(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + fake_dxc = root / "dxc.exe" + fake_dxc.write_bytes(b"NOT_A_REAL_PE_EXECUTABLE") + out_file = root / "reports" / "out.json" + out_file.parent.mkdir() + out_file.write_text("prior-report\n", encoding="utf-8") + + # Simulated Popen launch OSError through real run_once -> measure_variant -> main exits 1 cleanly. + with mock.patch.object(tool.subprocess, "Popen", side_effect=OSError("simulated exec format error")): + self._assert_clean_failure( + [ + "--dxc", str(fake_dxc), + "--variants", "control", + "--timeout", "10", + "--out", str(out_file), + ], + expected_fragment="simulated exec format error", + check_subprocess=False, + ) + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + + # Bounded real subprocess control with a deterministic failing child (sys.executable rejects -T). + real_out = root / "reports" / "real_child.json" + proc_real = _run_subprocess( + "--dxc", sys.executable, + "--variants", "control", + "--timeout", "5", + "--work-dir", str(root / "real_work"), + "--out", str(real_out), + ) + self.assertEqual(proc_real.returncode, 0, proc_real.stderr) + self.assertEqual(proc_real.stderr, "") + real_doc = json.loads(real_out.read_text(encoding="utf-8")) + self.assertEqual(real_doc["variants"][0]["outcome"], "diagnostic") + self.assertEqual(real_doc["variants"][0]["exit_codes"], [2]) + + # work_dir.mkdir OSError (ancestor is a regular file) exits 1 cleanly. + blocker = root / "blocker_file" + blocker.write_bytes(b"x") + with mock.patch.object(tool, "measure_variant") as mv_mock: + self._assert_clean_failure( + [ + "--dxc", str(fake_dxc), + "--variants", "control", + "--timeout", "10", + "--work-dir", str(blocker / "nested"), + ], + expected_fragment="dxc_compile_time:", + ) + mv_mock.assert_not_called() + + # measure_variant / dxc_version / write_report failures across OSError, ValueError, SubprocessError. + for exc in ( + OSError("simulated io error"), + ValueError("simulated value error"), + subprocess.TimeoutExpired(["dxc"], 1), + ): + with self.subTest(stage="measure_variant", exc=type(exc).__name__): + with ( + mock.patch.object(tool, "measure_variant", side_effect=exc), + mock.patch.object(tool, "write_report") as write_mock, + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(out_file)], + expected_fragment=str(exc), + check_subprocess=False, + ) + write_mock.assert_not_called() + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + + with self.subTest(stage="dxc_version", exc=type(exc).__name__): + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool, "dxc_version", side_effect=exc), + mock.patch.object(tool, "write_report") as write_mock, + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(out_file)], + expected_fragment=str(exc), + check_subprocess=False, + ) + write_mock.assert_not_called() + self.assertEqual(out_file.read_text(encoding="utf-8"), "prior-report\n") + + with self.subTest(stage="write_report", exc=type(exc).__name__): + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool, "write_report", side_effect=exc), + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(out_file)], + expected_fragment=str(exc), + check_subprocess=False, + ) + + def test_atomic_write_report_failures_preserve_prior_and_leave_zero_temp_dirs(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + fake_dxc = root / "dxc.exe" + fake_dxc.write_bytes(b"MZ") + out_dir = root / "out" + + def failing_replace(src, dst): + src_path = Path(src) + self.assertTrue(src_path.is_file()) + self.assertEqual(src_path.parent.parent.resolve(), Path(dst).parent.resolve()) + raise OSError("simulated replace failure") + + for ext, prior_text in ((".json", "prior-json\n"), (".csv", "prior-csv\n")): + out_path = out_dir / f"report{ext}" + + # 1) Fresh target + os.replace OSError -> exit 1, zero temp artifacts. + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool.os, "replace", side_effect=failing_replace), + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(out_path)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), []) + + # 2) Pre-existing target + os.replace OSError -> prior file intact, zero temp artifacts. + out_path.write_text(prior_text, encoding="utf-8") + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool.os, "replace", side_effect=failing_replace), + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(out_path)], + expected_fragment="simulated replace failure", + check_subprocess=False, + ) + self.assertEqual(out_path.read_text(encoding="utf-8"), prior_text) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), [out_path.name]) + out_path.unlink() + + # 3) Staging write failures preserve pre-existing JSON and CSV and leave zero temp artifacts. + json_out = out_dir / "report.json" + json_out.write_text("keep-json\n", encoding="utf-8") + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated stage write failure")), + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(json_out)], + expected_fragment="simulated stage write failure", + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(json_out.read_text(encoding="utf-8"), "keep-json\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json"]) + + csv_out = out_dir / "report.csv" + csv_out.write_text("keep-csv\n", encoding="utf-8") + with ( + mock.patch.object(tool, "run_once", side_effect=_fake_run_once), + mock.patch.object(tool.subprocess, "run", side_effect=_fake_subprocess_run), + mock.patch.object(tool.os, "replace") as replace_mock, + mock.patch.object(Path, "open", side_effect=OSError("simulated csv stage failure")), + ): + self._assert_clean_failure( + ["--dxc", str(fake_dxc), "--variants", "control", "--timeout", "10", "--out", str(csv_out)], + expected_fragment="simulated csv stage failure", + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(csv_out.read_text(encoding="utf-8"), "keep-csv\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.csv", "report.json"]) + + # 4) Serialization failures (json.dumps ValueError, csv_row KeyError) preserve prior files. + with mock.patch.object(tool.os, "replace") as replace_mock: + circular = {} + circular["self"] = circular + with self.assertRaises(ValueError): + tool.write_report(json_out, circular, []) + with self.assertRaises(KeyError): + tool.write_report(csv_out, {}, [{"variant": "broken"}]) + replace_mock.assert_not_called() + self.assertEqual(json_out.read_text(encoding="utf-8"), "keep-json\n") + self.assertEqual(csv_out.read_text(encoding="utf-8"), "keep-csv\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.csv", "report.json"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/dxc_compile_time.py b/tools/dxc_compile_time.py index 60cc3855a..9bf68e758 100644 --- a/tools/dxc_compile_time.py +++ b/tools/dxc_compile_time.py @@ -48,6 +48,7 @@ import re import statistics import subprocess +import sys import tempfile import threading import time @@ -325,7 +326,10 @@ def monitor(): except subprocess.TimeoutExpired: timed_out = True proc.kill() - stdout, stderr = proc.communicate() + try: + stdout, stderr = proc.communicate(timeout=5) + except subprocess.TimeoutExpired: + stdout, stderr = b"", b"" elapsed = time.perf_counter() - start stop.set() if thread: @@ -492,19 +496,52 @@ def print_table(records): print(f" passes: {top_passes_text(record['passes'])}") -def write_report(path, payload, records): +def _same_path(left, right): + if left.resolve() == right.resolve(): + return True + return left.exists() and right.exists() and left.samefile(right) + + +def _validate_paths(dxc, out_path, work_dir): + if out_path is not None: + if out_path.exists() and out_path.is_dir(): + raise ValueError(f"--out path is an existing directory: {out_path}") + if _same_path(out_path, dxc): + raise ValueError(f"--out path collides with --dxc: {out_path}") + if work_dir is not None and _same_path(out_path, work_dir): + raise ValueError(f"--out path collides with --work-dir: {out_path}") + if work_dir is not None and work_dir.exists() and not work_dir.is_dir(): + raise ValueError(f"--work-dir path is an existing regular file: {work_dir}") + + +def _atomic_write_stage(path, write_fn): path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=path.parent) as staging_dir: + staged = Path(staging_dir) / path.name + write_fn(staged) + os.replace(staged, path) + + +def write_report(path, payload, records): + path = Path(path) + if path.exists() and path.is_dir(): + raise ValueError(f"--out path is an existing directory: {path}") if path.suffix.lower() == ".json": - path.write_text(json.dumps({**payload, "variants": records}, indent=1) + "\n", - encoding="utf-8") + content = json.dumps({**payload, "variants": records}, indent=1) + "\n" + _atomic_write_stage(path, lambda staged: staged.write_text(content, encoding="utf-8")) else: - with path.open("w", encoding="utf-8", newline="") as handle: - writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS, extrasaction="ignore") - writer.writeheader() - writer.writerows(csv_row(record) for record in records) + rows = [csv_row(record) for record in records] + + def write_csv(staged): + with staged.open("w", encoding="utf-8", newline="") as handle: + writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS, extrasaction="ignore") + writer.writeheader() + writer.writerows(rows) + _atomic_write_stage(path, write_csv) -def main(argv=None): + +def main(argv=None) -> int: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--dxc", type=Path, @@ -566,46 +603,51 @@ def main(argv=None): except ValueError as exc: parser.error(str(exc)) - flags = ["-T", args.target, "-E", args.entry, "-enable-16bit-types", *args.extra_arg] - if args.ftime_report: - flags.append("-ftime-report") - print(f"DXC: {args.dxc}") - - temporary = None - if args.work_dir: - args.work_dir.mkdir(parents=True, exist_ok=True) - work = args.work_dir - else: - temporary = tempfile.TemporaryDirectory(prefix="dxc-compile-time-") - work = Path(temporary.name) - - records = [] try: - for name in names: - print(f"{name}:") - records.append(measure_variant(name, args.dxc, work, flags, args.repeat, - args.timeout, args.ftime_report)) - finally: - if temporary: - temporary.cleanup() - - print_table(records) - payload = { - "recorded_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), - "dxc": str(args.dxc), - "dxc_version": dxc_version(args.dxc), - "target": args.target, - "entry": args.entry, - "flags": flags, - "repeat": args.repeat, - "timeout_s": args.timeout, - "ftime_report": args.ftime_report, - } - if args.out: - write_report(args.out, payload, records) - print(f"\nwrote {args.out}") - else: - print("\nNo --out given; nothing written. Use --out measurements.csv or .json.") + _validate_paths(args.dxc, args.out, args.work_dir) + flags = ["-T", args.target, "-E", args.entry, "-enable-16bit-types", *args.extra_arg] + if args.ftime_report: + flags.append("-ftime-report") + print(f"DXC: {args.dxc}") + + temporary = None + if args.work_dir is not None: + args.work_dir.mkdir(parents=True, exist_ok=True) + work = args.work_dir + else: + temporary = tempfile.TemporaryDirectory(prefix="dxc-compile-time-") + work = Path(temporary.name) + + records = [] + try: + for name in names: + print(f"{name}:") + records.append(measure_variant(name, args.dxc, work, flags, args.repeat, + args.timeout, args.ftime_report)) + finally: + if temporary is not None: + temporary.cleanup() + + print_table(records) + payload = { + "recorded_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "dxc": str(args.dxc), + "dxc_version": dxc_version(args.dxc), + "target": args.target, + "entry": args.entry, + "flags": flags, + "repeat": args.repeat, + "timeout_s": args.timeout, + "ftime_report": args.ftime_report, + } + if args.out is not None: + write_report(args.out, payload, records) + print(f"\nwrote {args.out}") + else: + print("\nNo --out given; nothing written. Use --out measurements.csv or .json.") + except (OSError, ValueError, subprocess.SubprocessError) as exc: + print(f"dxc_compile_time: {exc}", file=sys.stderr) + return 1 return 0 From b96bbf7d91ebfeb9f0387a3362d57ae8603cd3be Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:46:46 +0200 Subject: [PATCH 216/232] tooling: extract main(argv) and add dest path and subprocess error guards in fetch_addrlib with CLI suite (#2600) --- CMakeLists.txt | 5 + tests/fetch_addrlib_cli_check.py | 328 +++++++++++++++++++++++++++++++ tools/fetch_addrlib.py | 52 ++--- 3 files changed, 362 insertions(+), 23 deletions(-) create mode 100644 tests/fetch_addrlib_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e0d25db35..3613c8502 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2711,6 +2711,11 @@ else() endif() add_test(NAME xg_bc64_tiling_reference COMMAND xg_swizzle_select_check --bc64-tiling) set_tests_properties(xg_bc64_tiling_reference PROPERTIES TIMEOUT 30 SKIP_RETURN_CODE 77) +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME tooling_fetch_addrlib_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/fetch_addrlib_cli_check.py") + set_tests_properties(tooling_fetch_addrlib_cli_check PROPERTIES TIMEOUT 60) +endif() # 4 KiB allocation answers for small 2D textures (src/startup_stubs/small_texture_4k.h): literal sizes and # refused descriptions without a device; the mutated run is the negative control; the addrlib run compares # every accepted shape with addrlib's GFX10 4 KiB layout and skips (77) without addrlib. diff --git a/tests/fetch_addrlib_cli_check.py b/tests/fetch_addrlib_cli_check.py new file mode 100644 index 000000000..29aad3e1a --- /dev/null +++ b/tests/fetch_addrlib_cli_check.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Pure-Python offline CLI, path-guard, subprocess-error, and mutation suite for tools/fetch_addrlib.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOLS_DIR = ROOT / "tools" +TOOL = TOOLS_DIR / "fetch_addrlib.py" +sys.path.insert(0, str(TOOLS_DIR)) +import fetch_addrlib as F # noqa: E402 + + +def _run_cli(argv: list[str] | None) -> tuple[int, str, str]: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + rc = F.main(argv) + except SystemExit as exc: + code = exc.code + rc = 0 if code is None else (int(code) if isinstance(code, int) else 1) + if not isinstance(code, (type(None), int)): + stderr.write(f"{code}\n") + return rc, stdout.getvalue(), stderr.getvalue() + + +_REAL_SUBPROCESS_RUN = subprocess.run + + +def _run_subprocess(*args: str) -> subprocess.CompletedProcess[str]: + return _REAL_SUBPROCESS_RUN( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + errors="replace", + timeout=30, + ) + + +def _make_fake_git( + dest: Path, + calls: list[tuple[list[str], Path | None]], + *, + origin_url: str = F.URL, + dirty_calls: set[int] | None = None, + head_commit: str = F.COMMIT, + create_header: bool = True, +): + status_count = 0 + dirty_indices = dirty_calls or set() + + def fake_run(cmd, cwd=None, check=False, capture_output=False, text=False): + nonlocal status_count + calls.append((list(cmd), Path(cwd) if cwd is not None else None)) + sub = cmd[1:] + if sub[:2] == ["init", "-q"]: + (dest / ".git").mkdir(parents=True, exist_ok=True) + return subprocess.CompletedProcess(cmd, 0, "", "") + if sub[:3] == ["remote", "get-url", "origin"]: + return subprocess.CompletedProcess(cmd, 0, f"{origin_url}\n", "") + if sub[:2] == ["status", "--porcelain"]: + status_count += 1 + out = " M src/amd/addrlib/file.cpp\n" if status_count in dirty_indices else "" + return subprocess.CompletedProcess(cmd, 0, out, "") + if sub[:2] == ["checkout", "-q"]: + if create_header: + header = dest / F.SUBDIR / "inc" / "addrinterface.h" + header.parent.mkdir(parents=True, exist_ok=True) + header.write_text("// stub header\n", encoding="utf-8") + return subprocess.CompletedProcess(cmd, 0, "", "") + if sub[:2] == ["rev-parse", "HEAD"]: + return subprocess.CompletedProcess(cmd, 0, f"{head_commit}\n", "") + return subprocess.CompletedProcess(cmd, 0, "", "") + + return fake_run + + +class FetchAddrlibCliPositiveTests(unittest.TestCase): + def test_fresh_checkout_and_entrypoints_succeed_offline(self): + with tempfile.TemporaryDirectory() as tmp: + dest = Path(tmp) / "mesa_fresh" + calls: list[tuple[list[str], Path | None]] = [] + with mock.patch.object(F.subprocess, "run", side_effect=_make_fake_git(dest, calls)): + rc, stdout, stderr = _run_cli(["--dest", str(dest)]) + + self.assertIs(type(rc), int) + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + addrlib = dest.resolve() / F.SUBDIR + self.assertIn(f"addrlib {F.COMMIT} at {addrlib}", stdout) + self.assertIn(f"configure with -DXBOX2WINDOWS_ADDRLIB_DIR={addrlib.as_posix()}", stdout) + self.assertEqual( + [cmd[1] for cmd, _ in calls], + ["init", "remote", "sparse-checkout", "fetch", "checkout", "status", "rev-parse"], + ) + self.assertTrue(all(cwd == dest.resolve() for _, cwd in calls)) + + # main(None) reads sys.argv. + dest_argv = Path(tmp) / "mesa_argv" + calls_argv: list[tuple[list[str], Path | None]] = [] + with ( + mock.patch.object(sys, "argv", [str(TOOL), "--dest", str(dest_argv)]), + mock.patch.object(F.subprocess, "run", side_effect=_make_fake_git(dest_argv, calls_argv)), + ): + rc_argv, out_argv, err_argv = _run_cli(None) + self.assertIs(type(rc_argv), int) + self.assertEqual(rc_argv, 0, err_argv) + self.assertEqual(err_argv, "") + self.assertIn(f"addrlib {F.COMMIT}", out_argv) + + # __main__ entrypoint raises SystemExit(0). + dest_main = Path(tmp) / "mesa_main" + calls_main: list[tuple[list[str], Path | None]] = [] + out_main, err_main = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), "--dest", str(dest_main)]), + mock.patch.object(F.subprocess, "run", side_effect=_make_fake_git(dest_main, calls_main)), + redirect_stdout(out_main), + redirect_stderr(err_main), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertIs(type(exited.exception.code), int) + self.assertEqual(exited.exception.code, 0) + self.assertEqual(err_main.getvalue(), "") + self.assertIn(f"addrlib {F.COMMIT}", out_main.getvalue()) + + def test_existing_clean_checkout_and_help_smoke(self): + with tempfile.TemporaryDirectory() as tmp: + dest = Path(tmp) / "mesa_existing" + (dest / ".git").mkdir(parents=True) + calls: list[tuple[list[str], Path | None]] = [] + with mock.patch.object(F.subprocess, "run", side_effect=_make_fake_git(dest, calls)): + rc, stdout, stderr = _run_cli(["--dest", str(dest)]) + + self.assertEqual(rc, 0, stderr) + self.assertEqual(stderr, "") + self.assertIn(f"addrlib {F.COMMIT}", stdout) + self.assertEqual( + [cmd[1] for cmd, _ in calls], + ["remote", "status", "sparse-checkout", "fetch", "checkout", "status", "rev-parse"], + ) + + proc = _run_subprocess("--help") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("--dest", proc.stdout) + + +class FetchAddrlibCliNegativeAndMutationTests(unittest.TestCase): + def _assert_clean_failure( + self, + argv: list[str], + *, + expected_code: int | None = 1, + expected_substrings: tuple[str, ...] = (), + check_subprocess: bool = False, + ) -> str: + rc, stdout, stderr = _run_cli(argv) + if expected_code is None: + self.assertNotEqual(rc, 0) + else: + self.assertEqual(rc, expected_code, stderr) + self.assertEqual(stdout, "") + self.assertTrue(stderr.strip()) + self.assertNotIn("Traceback", stderr) + for fragment in expected_substrings: + self.assertIn(fragment, stderr) + + if check_subprocess: + proc = _run_subprocess(*argv) + if expected_code is None: + self.assertNotEqual(proc.returncode, 0) + else: + self.assertEqual(proc.returncode, expected_code) + self.assertEqual(proc.stdout, "") + self.assertTrue(proc.stderr.strip()) + self.assertNotIn("Traceback", proc.stderr) + for fragment in expected_substrings: + self.assertIn(fragment, proc.stderr) + return stderr + + def test_argparse_rejection_is_py314_compatible(self): + err = self._assert_clean_failure(["--bogus-flag"], expected_code=None, check_subprocess=True) + self.assertIn("unrecognized", err.lower()) + + def test_dest_path_and_non_empty_guards_kill_mutations(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + regular_file = base / "not_a_dir.txt" + regular_file.write_text("file contents", encoding="utf-8") + + non_empty = base / "non_empty" + non_empty.mkdir() + (non_empty / ".keep").write_text("x", encoding="utf-8") + + # Existing regular file passed as --dest (and as parent of --dest) -> clean exit 1 before any git call. + for label, target, substrs, subproc in ( + ("regular_file_dest", regular_file, ("fetch_addrlib:", "not a directory"), True), + ("file_as_parent", regular_file / "child", ("fetch_addrlib:",), True), + ("non_empty_dir", non_empty, ("is not empty",), True), + ): + with self.subTest(case=label): + with mock.patch.object( + F.subprocess, + "run", + side_effect=AssertionError(f"subprocess.run called for {label}"), + ): + self._assert_clean_failure( + ["--dest", str(target)], + expected_code=1, + expected_substrings=substrs, + check_subprocess=subproc, + ) + + def test_checkout_refusals_preserved_without_tracebacks(self): + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + + # Wrong origin remote. + wrong_origin = base / "wrong_origin" + (wrong_origin / ".git").mkdir(parents=True) + calls_origin: list[tuple[list[str], Path | None]] = [] + with mock.patch.object( + F.subprocess, + "run", + side_effect=_make_fake_git(wrong_origin, calls_origin, origin_url="https://example.invalid/repo.git"), + ): + self._assert_clean_failure( + ["--dest", str(wrong_origin)], + expected_code=1, + expected_substrings=("not the Mesa dependency checkout",), + ) + self.assertEqual([cmd[1] for cmd, _ in calls_origin], ["remote"]) + + # Dirty checkout before fetch (status call #1). + dirty_pre = base / "dirty_pre" + (dirty_pre / ".git").mkdir(parents=True) + with mock.patch.object( + F.subprocess, + "run", + side_effect=_make_fake_git(dirty_pre, [], dirty_calls={1}), + ): + self._assert_clean_failure( + ["--dest", str(dirty_pre)], + expected_code=1, + expected_substrings=("has local changes", "src/amd/addrlib/file.cpp"), + ) + + # Dirty checkout after checkout (status call #2). + dirty_post = base / "dirty_post" + (dirty_post / ".git").mkdir(parents=True) + with mock.patch.object( + F.subprocess, + "run", + side_effect=_make_fake_git(dirty_post, [], dirty_calls={2}), + ): + self._assert_clean_failure( + ["--dest", str(dirty_post)], + expected_code=1, + expected_substrings=("has local changes",), + ) + + # Commit mismatch. + bad_commit = base / "bad_commit" + with mock.patch.object( + F.subprocess, + "run", + side_effect=_make_fake_git(bad_commit, [], head_commit="0" * 40), + ): + self._assert_clean_failure( + ["--dest", str(bad_commit)], + expected_code=1, + expected_substrings=("checked out", f"expected {F.COMMIT}"), + ) + + # Missing addrinterface.h header. + no_header = base / "no_header" + with mock.patch.object( + F.subprocess, + "run", + side_effect=_make_fake_git(no_header, [], create_header=False), + ): + self._assert_clean_failure( + ["--dest", str(no_header)], + expected_code=1, + expected_substrings=("has no inc/addrinterface.h",), + ) + + def test_oserror_valueerror_and_subprocess_error_guards_kill_mutations(self): + with tempfile.TemporaryDirectory() as tmp: + dest = Path(tmp) / "err_dest" + + for label, exc, expected in ( + ("called_process_error", subprocess.CalledProcessError(128, ["git", "fetch"]), ("fetch_addrlib:", "128")), + ("timeout_expired", subprocess.TimeoutExpired(["git", "fetch"], 10), ("fetch_addrlib:", "timed out")), + ("missing_git_oserror", FileNotFoundError("git executable not found"), ("fetch_addrlib:", "git executable not found")), + ): + with self.subTest(case=label): + target = dest / label + with mock.patch.object(F.subprocess, "run", side_effect=exc): + self._assert_clean_failure( + ["--dest", str(target)], + expected_code=1, + expected_substrings=expected, + ) + + # ValueError inside guarded block -> clean exit 1 via parser.exit. + empty_dest = dest / "value_err_dest" + empty_dest.mkdir(parents=True) + with mock.patch.object(F.pathlib.Path, "iterdir", side_effect=ValueError("invalid path value")): + self._assert_clean_failure( + ["--dest", str(empty_dest)], + expected_code=1, + expected_substrings=("fetch_addrlib:", "invalid path value"), + ) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tools/fetch_addrlib.py b/tools/fetch_addrlib.py index 1a2ab712d..d96c4dce1 100644 --- a/tools/fetch_addrlib.py +++ b/tools/fetch_addrlib.py @@ -34,36 +34,42 @@ def require_clean(dest): sys.exit(f"{dest} has local changes. Keep them and choose an empty --dest.\n{dirty}") -def main(): +def main(argv=None) -> int: root = pathlib.Path(__file__).resolve().parents[1] parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--dest", type=pathlib.Path, default=root / "out" / "deps" / "mesa") - args = parser.parse_args() - dest = args.dest.resolve() + args = parser.parse_args(argv) + try: + dest = args.dest.resolve() + if dest.exists() and not dest.is_dir(): + raise ValueError(f"{dest} is not a directory") - if (dest / ".git").is_dir(): - if git_output("remote", "get-url", "origin", cwd=dest) != URL: - sys.exit(f"{dest} is not the Mesa dependency checkout. Choose an empty --dest.") + if (dest / ".git").is_dir(): + if git_output("remote", "get-url", "origin", cwd=dest) != URL: + sys.exit(f"{dest} is not the Mesa dependency checkout. Choose an empty --dest.") + require_clean(dest) + else: + dest.mkdir(parents=True, exist_ok=True) + if sorted(dest.iterdir()): + sys.exit(f"{dest} is not empty. Choose an empty --dest.") + git("init", "-q", cwd=dest) + git("remote", "add", "origin", URL, cwd=dest) + git("sparse-checkout", "set", "--cone", SUBDIR, cwd=dest) + git("fetch", "--depth", "1", "--filter=blob:none", "origin", COMMIT, cwd=dest) + git("checkout", "-q", "--detach", COMMIT, cwd=dest) require_clean(dest) - else: - dest.mkdir(parents=True, exist_ok=True) - if any(dest.iterdir()): - sys.exit(f"{dest} is not empty. Choose an empty --dest.") - git("init", "-q", cwd=dest) - git("remote", "add", "origin", URL, cwd=dest) - git("sparse-checkout", "set", "--cone", SUBDIR, cwd=dest) - git("fetch", "--depth", "1", "--filter=blob:none", "origin", COMMIT, cwd=dest) - git("checkout", "-q", "--detach", COMMIT, cwd=dest) - require_clean(dest) - head = git_output("rev-parse", "HEAD", cwd=dest) - if head != COMMIT: - sys.exit(f"checked out {head}, expected {COMMIT}") - addrlib = dest / SUBDIR - if not (addrlib / "inc" / "addrinterface.h").is_file(): - sys.exit(f"{addrlib} has no inc/addrinterface.h") + head = git_output("rev-parse", "HEAD", cwd=dest) + if head != COMMIT: + sys.exit(f"checked out {head}, expected {COMMIT}") + addrlib = dest / SUBDIR + if not (addrlib / "inc" / "addrinterface.h").is_file(): + sys.exit(f"{addrlib} has no inc/addrinterface.h") + except (OSError, ValueError, subprocess.SubprocessError) as exc: + parser.exit(1, f"fetch_addrlib: {exc}\n") print(f"addrlib {COMMIT} at {addrlib}") print(f"configure with -DXBOX2WINDOWS_ADDRLIB_DIR={addrlib.as_posix()}") + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From a91990d209c0c7508b6f7d33720738ac389e9a63 Mon Sep 17 00:00:00 2001 From: Roland Edi <rolandedi@codivoire.com> Date: Wed, 25 Nov 2026 22:47:19 +0000 Subject: [PATCH 217/232] startup: NOP a soft-assert site after the first continue (#2493) --continue-asserts steps over main-image INT3s one debug event at a time. A retail mapping loop can trap once per 8 KiB chunk, so one 158 MiB mapping costs about 19,000 events and exhausts any fixed budget. Raising the budget only postpones the stop. X2W_NOP_SOFT_ASSERTS=1 writes 0x90 over the cc after the debugger continues the site for the first time. DBG_CONTINUE already bypasses the image's handler, so the guest sees the same continuation; later executions no longer raise an exception. The patch lasts for the life of the process and only covers main-image RVAs; X2W_STOP_AT sites are excluded. Once patched, a site no longer increments asserts_seen, so the --continue-asserts budget no longer measures real hits there. Extend tests/startup_debug_probe.cpp with a repeated site behind STARTUP_DEBUG_PROBE_ASSERTS (default 0, so existing cases are unchanged), and check the patched and unpatched counts in tests/startup_debug_check.py. The patched case asserts one repeated-site hit relative to the baseline sites, and the control without the switch logs every hit. --- docs/startup-runtime.md | 1 + tests/startup_debug_check.py | 31 ++++++++++++++++++++++++++++--- tests/startup_debug_probe.cpp | 25 +++++++++++++++++++++++-- tools/startup/debug_launch.py | 9 +++++++++ 4 files changed, 61 insertions(+), 5 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c4fd9a0e0..8c11e8db3 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1366,6 +1366,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_TRAP_CONTINUE=<exports>` | lets listed trap exports return 0 instead of ending the process | | `X2W_STOP_AT=<rva>[,...]` | the startup debugger stops at a main-image breakpoint at one of these addresses even while `-ContinueAsserts` steps over the others, and writes every thread's stack to `threads_stop.txt` | | `X2W_LOG_AT=<rva>[@<max hits>][:<item>[;<item>...]][,...]` | logs the elapsed time, thread ID, main-image instruction RVA, hit number and selected values to `files.txt`. RVAs and offsets are hexadecimal. The hit limit is decimal and defaults to 16 per RVA. Items are `rax`, `rcx`, `rdx`, `rbx`, `rsp`, `rbp`, `rsi`, `rdi`, `r8` through `r15`, or `[reg+hex]` / `[reg-hex]` for a qword read (`unreadable` on failure). Omit the item list to log all 16 registers. At the limit the debugger restores the original instruction unless another hook shares the breakpoint. INT3 events that other threads raised before the restore are resumed at the restored instruction, not logged, and counted on a separate `LOG_AT late hits resumed after the limit` summary line. Malformed entries (including a repeated item, compared by register and offset) and unusable breakpoints are reported in `events.txt`. The end summary lists logged hits per RVA. Fixture: `ctest --preset dev --no-tests=error -R '^startup_debug' -V`. | +| `X2W_NOP_SOFT_ASSERTS=1` | after `-ContinueAsserts` steps over a main-image `int3` for the first time, the startup debugger replaces its `cc` byte with a `NOP`, so a routine that traps once per chunk runs at native speed. The patch lasts for the life of the process and only targets RVAs of the main image; `X2W_STOP_AT` sites are never patched. `DBG_CONTINUE` already bypasses the title's handler, so the visible behavior is unchanged. Once a site is patched it no longer raises an exception and `asserts_seen` stops counting it, so the `--continue-asserts N` budget no longer measures real hits at that site | | `X2W_DUMP_AT=<seconds>[,...]` | the startup debugger writes every thread's stack to `threads_<seconds>.txt` at those times, for a run that stalls before a watchdog or the timeout ends it | | `X2W_VALLOC_MIN=<hex bytes>` | the startup debugger logs each virtual-memory allocation of at least that size to `files.txt` (`VALLOC`), with the requested address (0 for any, unreadable for an incomplete read), size, type, protection and the main-image and stand-in return addresses on the caller's stack | | `X2W_HOST_CPU=1` (`run.ps1 -HostCpu`) | the startup debugger rewrites main-image instructions the host processor lacks at their first fault: see [Host processors without the console's instructions](#host-processors-without-the-consoles-instructions) | diff --git a/tests/startup_debug_check.py b/tests/startup_debug_check.py index 67a8c8319..f0e78798a 100644 --- a/tests/startup_debug_check.py +++ b/tests/startup_debug_check.py @@ -5,8 +5,10 @@ virtual-memory allocations with their callers. X2W_LOG_AT captures registers and qwords at a function entry, then removes the breakpoint at the hit limit. A `stop` file created in the log directory ends the run as the timeout does; one left from an earlier run is removed at start. The launcher keeps the debug heap off unless -the caller sets _NO_DEBUG_HEAP=0. tests/startup_debug_probe.cpp is the main input: it hits two -breakpoints, reserves 256 MiB, prints its debug-heap flags, waits 3 s and exits 0. +the caller sets _NO_DEBUG_HEAP=0. X2W_NOP_SOFT_ASSERTS=1 replaces a main-image INT3 with a NOP after +the first continue, and the probe repeats one site when STARTUP_DEBUG_PROBE_ASSERTS is set. +tests/startup_debug_probe.cpp is the main input: it hits two breakpoints, optionally repeats a +third, reserves 256 MiB, prints its debug-heap flags, waits 3 s and exits 0. The gaming-runtime and movie-player call hooks are armed only with --trace-calls 1. For that case the probe and tests/startup_debug_calls.cpp are copied into one folder, the DLL under the @@ -75,6 +77,12 @@ def text(path): return path.read_text(encoding="utf-8", errors="replace") if path.exists() else "" +def breakpoint_sites(logdir, image): + """The main-image RVAs of the breakpoints the debugger logged, in order.""" + return [int(m, 16) for m in re.findall(r"breakpoint at %s\+0x([0-9a-f]+) first-chance" % re.escape(image), + text(logdir / "events.txt"))] + + HOOKED_MODULE = "bink2scarlett.dll" # the movie-player module name debug_launch.py hooks HOOKED_EXPORT = "BinkNextFrame" CALLS = 7 # kCalls in tests/startup_debug_probe.cpp @@ -187,6 +195,23 @@ def stack_read(address, size): out, _ = run(probe, work, "stop-first", {"X2W_STOP_AT": f"{sites[1]:x}"}, options=()) assert f"stopped at breakpoint (0x80000003) at {image}+{sites[0]:#x}" in out, out + # X2W_NOP_SOFT_ASSERTS=1: a site that traps once per iteration is patched after its first + # hit, so the loop finishes with one logged breakpoint. Without the switch every hit is logged. + repeats = 4 + out, logdir = run(probe, work, "nop-repeat", {"STARTUP_DEBUG_PROBE_ASSERTS": str(repeats), + "X2W_NOP_SOFT_ASSERTS": "1"}) + assert "process exited with 0x00000000" in out, out + assert f"debug-probe repeated {repeats}\n" in text(logdir / "stdout.txt"), text(logdir / "stdout.txt") + hits = breakpoint_sites(logdir, image) + repeated = [site for site in hits if site not in sites] + assert len(hits) == len(sites) + 1 and len(repeated) == 1, text(logdir / "events.txt") + nop_line = next((line for line in out.splitlines() if "soft asserts NOP'd:" in line), "") + assert f"{image}+{repeated[0]:#x}" in nop_line, out + # Control: without the switch the same run logs every hit at the repeated site. + out, logdir = run(probe, work, "nop-repeat-control", {"STARTUP_DEBUG_PROBE_ASSERTS": str(repeats)}) + assert "process exited with 0x00000000" in out, out + assert breakpoint_sites(logdir, image).count(repeated[0]) == repeats, text(logdir / "events.txt") + # X2W_DUMP_AT: a dump one second in, while the probe is still alive. out, logdir = run(probe, work, "dump", {"X2W_DUMP_AT": "1"}) assert "process exited with 0x00000000" in out, out @@ -292,7 +317,7 @@ def stack_read(address, size): assert banners[name] in out, (name, out) print(f"startup_debug[{group}]: PASS (stop at a chosen assert, timed thread dump, large-allocation log, debug heap off, " - "call hooks opt-in, bounded register and qword logging)") + "soft asserts NOP'd after the first hit when the core group runs, call hooks opt-in, bounded register and qword logging)") return 0 diff --git a/tests/startup_debug_probe.cpp b/tests/startup_debug_probe.cpp index c40eb86fa..4c1db8e51 100644 --- a/tests/startup_debug_probe.cpp +++ b/tests/startup_debug_probe.cpp @@ -1,6 +1,8 @@ // Input for the startup debugger's diagnostics check (tests/startup_debug_check.py). It reaches two -// breakpoints in its own image, the way a retail image keeps soft asserts, reserves one large -// range, reports whether the loader gave it the debug heap, stays alive for a moment and exits 0. +// breakpoints in its own image, the way a retail image keeps soft asserts, and with +// STARTUP_DEBUG_PROBE_ASSERTS=<n> n more at a third site (the repeated-assert case). It also +// reserves one large range, reports whether the loader gave it the debug heap, stays alive for a +// moment and exits 0. // With STARTUP_DEBUG_PROBE_DLL=<file> and STARTUP_DEBUG_PROBE_EXPORT=<name> it also loads that DLL // and calls the export kCalls times (the call-hook case; tests/startup_debug_calls.cpp). // No GPU and no other input is involved. @@ -29,6 +31,21 @@ __declspec(noinline) void second_assert() __debugbreak(); } +// One trap site, called repeatedly: the shape a mapping loop has when it traps once per chunk. +// Kept out of line so the compiler leaves a single INT3. +__declspec(noinline) void third_assert() +{ + __debugbreak(); +} + +__declspec(noinline) void repeated_assert(int times) +{ + for (int i = 0; i < times; ++i) { + reached = 3 + i; + third_assert(); + } +} + __declspec(noinline) void* reserve_large() { // 256 MiB, reserved only: nothing is committed. @@ -128,6 +145,10 @@ int main() { first_assert(); second_assert(); + const char* const repeated = std::getenv("STARTUP_DEBUG_PROBE_ASSERTS"); + const int repeated_count = repeated ? std::atoi(repeated) : 0; + repeated_assert(repeated_count); + std::printf("debug-probe repeated %d\n", repeated_count); void* const range = reserve_large(); std::printf("debug-probe reserved %s\n", range ? "ok" : "failed"); std::printf("debug-probe heap flags 0x%lx\n", debug_heap_flags()); diff --git a/tools/startup/debug_launch.py b/tools/startup/debug_launch.py index 5bc7afa6e..2f0be7602 100644 --- a/tools/startup/debug_launch.py +++ b/tools/startup/debug_launch.py @@ -128,6 +128,11 @@ def print(*args, **kwargs): print("expected a finite nonnegative timeout and an assertion limit of -1 or greater") return 2 asserts_seen = {} + # X2W_NOP_SOFT_ASSERTS=1: after the first hit of a main-image int3 that is continued, replace the + # trap byte with NOP. DBG_CONTINUE already bypasses the title's handler, so the visible behavior is + # unchanged, but a long mapping that traps once per chunk then runs at native speed. + nop_soft_asserts = os.environ.get("X2W_NOP_SOFT_ASSERTS") == "1" + nop_sites = {} # X2W_HOST_CPU=1: rewrite main-image instructions the host processor lacks (host_cpu.py). host_cpu_on = os.environ.get("X2W_HOST_CPU") == "1" host_cpu_sites = {} @@ -759,6 +764,8 @@ def poll_watches(): and (skip_asserts == -1 or sum(asserts_seen.values()) < skip_asserts) and (ex_addr - main_base) not in stop_at): asserts_seen[ex_addr] = asserts_seen.get(ex_addr, 0) + 1 + if nop_soft_asserts and ex_addr not in nop_sites and read(ex_addr, 1) == b"\xcc" and write(ex_addr, b"\x90"): + nop_sites[ex_addr] = 1 status = DBG_CONTINUE # rip is already past the int3 elif (not first) or stop_first or (ex_code == 0x80000003 and main_base and main_base <= ex_addr < main_base + 0x10000000): @@ -870,6 +877,8 @@ def poll_watches(): print(" host-cpu sites rewritten: " + ", ".join(f"{name} x{n}" for name, n in sorted(host_cpu_sites.items()))) if host_cpu_resumed: print(f" host-cpu threads resumed at a site another thread had rewritten: {len(host_cpu_resumed)}") + if nop_sites: + print(" soft asserts NOP'd: " + ", ".join(where(addr) for addr in nop_sites)) bink_report() if os.environ.get("X2W_COUNT"): print(" hit counts: " + ", ".join(f"+{item} x{hit_counts.get('+' + item, 0)}" From 5ca71c5b5bbbaaa6948ccdb0cc57fff1dd6774c3 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 00:51:59 +0200 Subject: [PATCH 218/232] runtime: extract main(argv) and add directory and safe import guards in live_view with CLI suite (#2602) Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 3 + tests/startup_live_view_cli_check.py | 239 ++++++++++++++++++ tools/startup/live_view.py | 357 +++++++++++++++------------ 3 files changed, 437 insertions(+), 162 deletions(-) create mode 100644 tests/startup_live_view_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 3613c8502..d645bd522 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3060,6 +3060,9 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_live_view COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_live_view_check.py") set_tests_properties(startup_live_view PROPERTIES TIMEOUT 60) + add_test(NAME runtime_startup_live_view_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_live_view_cli_check.py") + set_tests_properties(runtime_startup_live_view_cli_check PROPERTIES TIMEOUT 60) add_test(NAME startup_uniform_lane COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_uniform_lane_check.py") # NGG primitive-shader cases (#1723): identity triangle against single-change contrasts, reference model. diff --git a/tests/startup_live_view_cli_check.py b/tests/startup_live_view_cli_check.py new file mode 100644 index 000000000..bf0840472 --- /dev/null +++ b/tests/startup_live_view_cli_check.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""CLI, safe-import, path-guard, OSError, and mutation suite for tools/startup/live_view.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import importlib +import io +from pathlib import Path +import runpy +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "startup" / "live_view.py" +sys.path.insert(0, str(ROOT / "tools" / "startup")) + + +def _run_main(live_view_mod, argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = live_view_mod.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args: str | Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), *(str(a) for a in args)], + capture_output=True, + text=True, + encoding="utf-8", + timeout=30, + ) + + +class _ReconfigurableStringIO(io.StringIO): + def __init__(self): + super().__init__() + self.reconfigure_calls = [] + + def reconfigure(self, **kwargs): + self.reconfigure_calls.append(kwargs) + + +class LiveViewCliPositiveTests(unittest.TestCase): + def test_safe_import_has_zero_side_effects(self) -> None: + # Importing live_view with no CLI args must not touch sys.argv, sys.stdout, os.system, or block. + fake_stdout = _ReconfigurableStringIO() + stderr = io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL)]), + mock.patch("os.system", side_effect=AssertionError("os.system called on import")) as sys_mock, + mock.patch("time.sleep", side_effect=AssertionError("time.sleep called on import")) as sleep_mock, + redirect_stdout(fake_stdout), + redirect_stderr(stderr), + ): + if "live_view" in sys.modules: + mod = importlib.reload(sys.modules["live_view"]) + else: + mod = importlib.import_module("live_view") + sys_mock.assert_not_called() + sleep_mock.assert_not_called() + self.assertEqual(fake_stdout.reconfigure_calls, []) + self.assertEqual(fake_stdout.getvalue(), "") + self.assertEqual(stderr.getvalue(), "") + self.assertTrue(callable(mod.main)) + + def test_main_and_subprocess_preserve_output_reconfigure_and_split_utf8(self) -> None: + import live_view + + with TemporaryDirectory() as tmp: + root = Path(tmp) + rundir = root / "run" + rundir.mkdir() + pkg_dir = root / "pkg" + pkg_dir.mkdir() + (rundir / "events.txt").write_bytes( + b"1.0 load engine.dll at 0x1000\n" + b"2.0 debug-output hello from runtime\n" + b"3.0 exit 0x0\n" + ) + (rundir / "files.txt").write_bytes( + b"1.0 NtCreateFile G:\\caf\xc3\xa9.bin from 0x1000 -> 0x00000000\r\n" + b"2.0 NtOpenFile " + str(pkg_dir.resolve()).encode("utf-8") + b"\\data.bin from 0x1000 -> 0xc0000034\r\n" + b"3.0 NtCreateFile C:\\Windows\\sys.dll from 0x1000 -> 0x00000000\r\n" + ) + (rundir / "trap.log").write_text( + "x2w-d3d12 heartbeat: 30 frames presented in 1.0 s (30.0 fps overall)\n", + encoding="utf-8", + ) + (rundir / "finished.txt").write_text("clean exit\n", encoding="utf-8") + + reconf_out = _ReconfigurableStringIO() + stderr = io.StringIO() + with ( + mock.patch("os.system") as system_mock, + mock.patch("time.sleep") as sleep_mock, + redirect_stdout(reconf_out), + redirect_stderr(stderr), + ): + code = live_view.main([str(rundir), str(pkg_dir)]) + self.assertIs(type(code), int) + self.assertEqual(code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(reconf_out.reconfigure_calls, [{"encoding": "utf-8", "errors": "replace"}]) + system_mock.assert_called_once() + self.assertEqual(sleep_mock.call_count, 10) # 10s countdown loop (0 polling sleeps since finished.txt exists) + + out = reconf_out.getvalue() + self.assertIn("Xbox2Windows local startup experiment: live log of ", out) + self.assertIn("module engine.dll", out) + self.assertIn("runtime hello from runtime", out) + self.assertIn("EXIT 3.0 exit 0x0", out) + self.assertIn("file G:\\café.bin", out) + self.assertIn("data.bin (failed 0xc0000034)", out) + self.assertNotIn("sys.dll", out) + self.assertIn("frames 30 frames presented, 30.0 fps", out) + self.assertIn("clean exit", out) + self.assertIn("Run ended. Full logs are in ", out) + + # Verify sys.argv forwarding when argv=None and __main__ execution via runpy and subprocess. + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(rundir)]), + mock.patch("os.system"), + mock.patch("time.sleep"), + ): + code_none, out_none, err_none = _run_main(live_view, None) + self.assertIs(type(code_none), int) + self.assertEqual(code_none, 0) + self.assertEqual(err_none, "") + self.assertIn("Run ended.", out_none) + + runpy_out, runpy_err = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(rundir)]), + mock.patch("os.system"), + mock.patch("time.sleep"), + redirect_stdout(runpy_out), + redirect_stderr(runpy_err), + ): + try: + runpy.run_path(str(TOOL), run_name="__main__") + except SystemExit as exc: + self.assertEqual(exc.code, 0) + self.assertEqual(runpy_err.getvalue(), "") + self.assertIn("Run ended.", runpy_out.getvalue()) + + # Subprocess check (with finished.txt present, runs ~10s countdown cleanly and exits 0). + proc = _run_subprocess(rundir, pkg_dir) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("Run ended.", proc.stdout) + self.assertEqual( + sorted(p.name for p in rundir.iterdir()), + ["events.txt", "files.txt", "finished.txt", "trap.log"], + ) + + +class LiveViewCliNegativeAndMutationTests(unittest.TestCase): + def test_rundir_and_package_path_guards_exit_2_without_looping(self) -> None: + import live_view + + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_rundir = root / "run" + valid_rundir.mkdir() + regular_file = root / "not_a_dir.txt" + regular_file.write_text("payload", encoding="utf-8") + missing_dir = root / "missing_dir" + + for argv, frag, check_subproc in ( + ([str(missing_dir)], "directory", True), + ([str(regular_file)], "directory", True), + (["", ], "directory", False), + ([str(valid_rundir), str(regular_file)], "package", True), + ): + with self.subTest(argv=argv): + with mock.patch("time.sleep", side_effect=AssertionError("must not enter polling loop")): + code, out, err = _run_main(live_view, argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.startswith("live_view: "), err) + self.assertIn(frag, err) + + if check_subproc: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertTrue(proc.stderr.startswith("live_view: "), proc.stderr) + self.assertIn(frag, proc.stderr) + + def test_oserror_caught_cleanly_and_py314_argparse_errors(self) -> None: + import live_view + + with TemporaryDirectory() as tmp: + root = Path(tmp) + valid_rundir = root / "run" + valid_rundir.mkdir() + + with mock.patch("os.system", side_effect=OSError("simulated console failure")): + code, out, err = _run_main(live_view, [str(valid_rundir)]) + self.assertEqual(code, 1, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertTrue(err.startswith("live_view: "), err) + self.assertIn("simulated console failure", err) + + for argv, frag in ( + ([], "usage:"), + ([str(valid_rundir), str(root), "extra_arg"], "extra_arg"), + ([str(valid_rundir), "--unknown-flag"], "--unknown-flag"), + ): + with self.subTest(argv=argv): + stdout = io.StringIO() + stderr = io.StringIO() + with self.assertRaises(SystemExit) as exited: + with redirect_stdout(stdout), redirect_stderr(stderr): + live_view.main(argv) + self.assertNotEqual(exited.exception.code, 0) + self.assertEqual(stdout.getvalue(), "") + self.assertIn(frag, stderr.getvalue()) + self.assertNotIn("Traceback", stderr.getvalue()) + + proc = _run_subprocess() + self.assertNotEqual(proc.returncode, 0) + self.assertEqual(proc.stdout, "") + self.assertIn("usage:", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup/live_view.py b/tools/startup/live_view.py index 9c436ed04..350681ec4 100644 --- a/tools/startup/live_view.py +++ b/tools/startup/live_view.py @@ -5,174 +5,207 @@ It only reads the log files the debugger and the stand-in DLLs write; it does not touch the game. File opens are shown for paths on the G: mount and under the package root, if one is given. """ +import argparse import os import re import sys import time -if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - -rundir = sys.argv[1] -# The package root the run uses as its working directory (run.ps1 -DataDir), next to the G:\ mount. -roots = ["G:\\"] + [os.path.join(os.path.abspath(sys.argv[2]), "")] if len(sys.argv) > 2 else ["G:\\"] -game_file = re.compile(r"Nt(?:CreateFile|OpenFile) (?:\\\?\?\\)?((?i:" + "|".join(map(re.escape, roots)) + r").+)(?= from (?:[^+]*\+)?0x[0-9a-fA-F]+ )") -os.system("title Xbox2Windows debug log - " + os.path.basename(os.path.abspath(rundir))) -start = time.time() -counts = {"modules": 0, "files": 0, "refused": 0, "chunks": 0, "gpu calls first seen": 0} -last_status = 0.0 -state = "?" -frames = "0" - - -def say(tag, text): - print(f"{time.time() - start:7.1f}s {tag:<9} {text}", flush=True) - - -def on_event(line): - global state - m = re.match(r"\s*[\d.]+ load (\S+) at", line) - if m: - counts["modules"] += 1 - say("module", m.group(1)) - return - if " debug-output " in line: - say("runtime", line.split(" debug-output ", 1)[1].strip()[:150]) - elif " watch " in line: - say("watch", line.split(" watch ", 1)[1].strip()) - elif " exception " in line and "first-chance" in line and any( - f" at {m}+" in line for m in ("d3d12_xs.dll", "xg_xs.dll", "GameInput.dll", "xmem.dll", "XCRDAPI.dll")): - # A stand-in DLL probing whether an address is readable: caught and handled there (expected). - counts["handled probes"] = counts.get("handled probes", 0) + 1 - if counts["handled probes"] == 1: - say("probe", "stand-in read probes fault on purpose and are handled; counted in the status line from now on") - elif " exception " in line and "C++ exception" not in line and "thread name" not in line: - say("EXCEPTION", line.split(" exception ", 1)[1].strip()[:150]) - elif re.search(r" exit 0x", line): - say("EXIT", line.strip()) - - -def on_file(line): - if "DENIED (offline)" in line: - counts["refused"] += 1 - target = line.split("DENIED (offline)", 1)[1].split(" from ")[0].strip() - say("offline", "refused network open: " + target[:100]) - return - if "Bink" in line: - say("movie", re.sub(r" from .*", "", line.split(None, 1)[1]).strip()[:140]) - return - if " REDIRECT " in line: - say("EXPERIMENT", "forced code path: " + line.split(" REDIRECT ", 1)[1].strip()[:120]) - return - if " HIT " in line: - say("hit", line.split(" HIT ", 1)[1].strip()[:140]) - return - m = game_file.search(line) - if m: - counts["files"] += 1 - result = line.rsplit("->", 1)[-1].strip() - say("file", m.group(1) + ("" if result == "0x00000000" else f" (failed {result})")) - - -def on_shim(line): - global state, frames - line = line.strip() - if not line: - return - if line.startswith("x2w-trap"): - say("TRAP", line[9:200] + " <- unimplemented console function: the run stops here") - elif "Factory::OpenFile" in line: - m = re.search(r'path="([^"]+)"', line) - say("storage", "opened " + (m.group(1) if m else line[:120])) - elif "Queue::EnqueueStatus" in line: - m = re.search(r"inflated=(\d+) failed=(\d+)", line) - if m: - counts["chunks"] = int(m.group(1)) - say("storage", f"read batch complete: {m.group(1)} compressed chunks decompressed so far, {m.group(2)} failed") - elif "EnqueueRequest" in line or "options=" in line or "Queue::Submit" in line or "IsComplete" in line: - return - elif line.startswith("x2w-dstorage heartbeat "): - m = re.search(r"\binflated=(\d+)", line) - if m: - counts["chunks"] = int(m.group(1)) - say("storage", line) - elif line.startswith("x2w-render totals:"): - say("render", line) - elif "heartbeat" in line: - m = re.search(r"heartbeat: (\d+) frames presented in ([\d.]+) s \(([\d.]+) fps", line) + +class _LogViewer: + """Stateful log parser and status tracker for a single live_view session.""" + + def __init__(self, package=None): + # The package root the run uses as its working directory (run.ps1 -DataDir), next to the G:\ mount. + roots = ["G:\\"] + ([os.path.join(os.path.abspath(package), "")] if package is not None else []) + self.game_file = re.compile( + r"Nt(?:CreateFile|OpenFile) (?:\\\?\?\\)?((?i:" + + "|".join(map(re.escape, roots)) + + r").+)(?= from (?:[^+]*\+)?0x[0-9a-fA-F]+ )" + ) + self.start = time.time() + self.counts = {"modules": 0, "files": 0, "refused": 0, "chunks": 0, "gpu calls first seen": 0} + self.last_status = 0.0 + self.state = "?" + self.frames = "0" + + def say(self, tag, text): + print(f"{time.time() - self.start:7.1f}s {tag:<9} {text}", flush=True) + + def on_event(self, line): + m = re.match(r"\s*[\d.]+ load (\S+) at", line) if m: - frames = m.group(1) - say("frames", f"{m.group(1)} frames presented, {m.group(3)} fps") - elif "title main state" in line: - m = re.search(r"state (-?\d+) -> (-?\d+)", line) + self.counts["modules"] += 1 + self.say("module", m.group(1)) + return + if " debug-output " in line: + self.say("runtime", line.split(" debug-output ", 1)[1].strip()[:150]) + elif " watch " in line: + self.say("watch", line.split(" watch ", 1)[1].strip()) + elif " exception " in line and "first-chance" in line and any( + f" at {m}+" in line for m in ("d3d12_xs.dll", "xg_xs.dll", "GameInput.dll", "xmem.dll", "XCRDAPI.dll")): + # A stand-in DLL probing whether an address is readable: caught and handled there (expected). + self.counts["handled probes"] = self.counts.get("handled probes", 0) + 1 + if self.counts["handled probes"] == 1: + self.say("probe", "stand-in read probes fault on purpose and are handled; counted in the status line from now on") + elif " exception " in line and "C++ exception" not in line and "thread name" not in line: + self.say("EXCEPTION", line.split(" exception ", 1)[1].strip()[:150]) + elif re.search(r" exit 0x", line): + self.say("EXIT", line.strip()) + + def on_file(self, line): + if "DENIED (offline)" in line: + self.counts["refused"] += 1 + target = line.split("DENIED (offline)", 1)[1].split(" from ")[0].strip() + self.say("offline", "refused network open: " + target[:100]) + return + if "Bink" in line: + self.say("movie", re.sub(r" from .*", "", line.split(None, 1)[1]).strip()[:140]) + return + if " REDIRECT " in line: + self.say("EXPERIMENT", "forced code path: " + line.split(" REDIRECT ", 1)[1].strip()[:120]) + return + if " HIT " in line: + self.say("hit", line.split(" HIT ", 1)[1].strip()[:140]) + return + m = self.game_file.search(line) if m: - state = m.group(2) - meaning = {"0": "starting", "1": "loading", "3": "start-up flow, waiting"}.get(state, "") - say("STATE", f"title main state {m.group(1)} -> {m.group(2)} {meaning}") - elif line.startswith("x2w-audio"): - say("audio", line[10:170]) - elif line.startswith("x2w-xmem"): - say("memory", line[9:170]) - elif line.startswith("x2w-noop"): - counts["gpu calls first seen"] += 1 - m = re.search(r"!(\S+)", line) - say("gpu", "first use of an untranslated call: " + (m.group(1) if m else line[9:80])) - elif "DEVICE REMOVED" in line or "failed" in line.lower() and "failed=0" not in line: - say("WARNING", line[:170]) - elif line.startswith("x2w-d3d12") and ("placeholder" in line or "Create" in line or "slot" in line): - say("gpu", line[10:170]) - elif line.startswith("x2w-xg"): - say("texture", line[7:150]) - - -sources = {"events.txt": on_event, "files.txt": on_file, "trap.log": on_shim} -positions = {name: 0 for name in sources} -partial = {name: b"" for name in sources} # bytes: a character can be split between two reads -print("Xbox2Windows local startup experiment: live log of " + os.path.abspath(rundir)) -print("Columns: time since this window opened, category, detail. Network refusals are shown when observed.") -print("-" * 110, flush=True) -finished = os.path.join(rundir, "finished.txt") -ended = False -while True: - progressed = False - for name, handler in sources.items(): - path = os.path.join(rundir, name) + self.counts["files"] += 1 + result = line.rsplit("->", 1)[-1].strip() + self.say("file", m.group(1) + ("" if result == "0x00000000" else f" (failed {result})")) + + def on_shim(self, line): + line = line.strip() + if not line: + return + if line.startswith("x2w-trap"): + self.say("TRAP", line[9:200] + " <- unimplemented console function: the run stops here") + elif "Factory::OpenFile" in line: + m = re.search(r'path="([^"]+)"', line) + self.say("storage", "opened " + (m.group(1) if m else line[:120])) + elif "Queue::EnqueueStatus" in line: + m = re.search(r"inflated=(\d+) failed=(\d+)", line) + if m: + self.counts["chunks"] = int(m.group(1)) + self.say("storage", f"read batch complete: {m.group(1)} compressed chunks decompressed so far, {m.group(2)} failed") + elif "EnqueueRequest" in line or "options=" in line or "Queue::Submit" in line or "IsComplete" in line: + return + elif line.startswith("x2w-dstorage heartbeat "): + m = re.search(r"\binflated=(\d+)", line) + if m: + self.counts["chunks"] = int(m.group(1)) + self.say("storage", line) + elif line.startswith("x2w-render totals:"): + self.say("render", line) + elif "heartbeat" in line: + m = re.search(r"heartbeat: (\d+) frames presented in ([\d.]+) s \(([\d.]+) fps", line) + if m: + self.frames = m.group(1) + self.say("frames", f"{m.group(1)} frames presented, {m.group(3)} fps") + elif "title main state" in line: + m = re.search(r"state (-?\d+) -> (-?\d+)", line) + if m: + self.state = m.group(2) + meaning = {"0": "starting", "1": "loading", "3": "start-up flow, waiting"}.get(self.state, "") + self.say("STATE", f"title main state {m.group(1)} -> {m.group(2)} {meaning}") + elif line.startswith("x2w-audio"): + self.say("audio", line[10:170]) + elif line.startswith("x2w-xmem"): + self.say("memory", line[9:170]) + elif line.startswith("x2w-noop"): + self.counts["gpu calls first seen"] += 1 + m = re.search(r"!(\S+)", line) + self.say("gpu", "first use of an untranslated call: " + (m.group(1) if m else line[9:80])) + elif "DEVICE REMOVED" in line or "failed" in line.lower() and "failed=0" not in line: + self.say("WARNING", line[:170]) + elif line.startswith("x2w-d3d12") and ("placeholder" in line or "Create" in line or "slot" in line): + self.say("gpu", line[10:170]) + elif line.startswith("x2w-xg"): + self.say("texture", line[7:150]) + + +def _build_parser(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("rundir", help="Run log directory to follow") + parser.add_argument("package", nargs="?", default=None, help="Optional package root directory") + return parser + + +def main(argv=None) -> int: + """Follow a run's log directory until finished.txt appears and return the exit code.""" + parser = _build_parser() + args = parser.parse_args(argv) + if not os.path.isdir(args.rundir): + parser.exit(2, f"live_view: run directory does not exist or is not a directory: {args.rundir}\n") + if args.package is not None and os.path.isfile(args.package): + parser.exit(2, f"live_view: package root must be a directory, not a file: {args.package}\n") + + try: + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + viewer = _LogViewer(args.package) + os.system("title Xbox2Windows debug log - " + os.path.basename(os.path.abspath(args.rundir))) + sources = {"events.txt": viewer.on_event, "files.txt": viewer.on_file, "trap.log": viewer.on_shim} + positions = {name: 0 for name in sources} + partial = {name: b"" for name in sources} # bytes: a character can be split between two reads + print("Xbox2Windows local startup experiment: live log of " + os.path.abspath(args.rundir)) + print("Columns: time since this window opened, category, detail. Network refusals are shown when observed.") + print("-" * 110, flush=True) + finished = os.path.join(args.rundir, "finished.txt") + ended = False + while True: + progressed = False + for name, handler in sources.items(): + path = os.path.join(args.rundir, name) + try: + with open(path, "rb") as handle: + handle.seek(positions[name]) + chunk = handle.read() + positions[name] += len(chunk) + except OSError: + continue + if not chunk: + continue + progressed = True + lines = (partial[name] + chunk).split(b"\n") + partial[name] = lines.pop() + for raw in lines: + try: + handler(raw.decode("utf-8", errors="replace").rstrip("\r")) + except Exception as error: # a viewer bug must not hide the rest of the log + viewer.say("viewer", f"could not format a line: {error}") + if time.time() - viewer.last_status >= 10 and not ended: + viewer.last_status = time.time() + viewer.say( + "status", + f"state {viewer.state}, {viewer.frames} frames, {viewer.counts['modules']} modules, " + f"{viewer.counts['files']} game-file opens, {viewer.counts['chunks']} chunks decompressed, " + f"{viewer.counts['refused']} network opens refused, " + f"{viewer.counts.get('handled probes', 0)} handled probes", + ) + if ended and not progressed: + break + if os.path.exists(finished): + ended = True + continue + time.sleep(0.25) + print("-" * 110) try: - with open(path, "rb") as handle: - handle.seek(positions[name]) - chunk = handle.read() - positions[name] += len(chunk) + with open(finished, encoding="utf-8", errors="replace") as handle: + print(handle.read().strip()) except OSError: - continue - if not chunk: - continue - progressed = True - lines = (partial[name] + chunk).split(b"\n") - partial[name] = lines.pop() - for raw in lines: - try: - handler(raw.decode("utf-8", errors="replace").rstrip("\r")) - except Exception as error: # a viewer bug must not hide the rest of the log - say("viewer", f"could not format a line: {error}") - if time.time() - last_status >= 10 and not ended: - last_status = time.time() - say("status", f"state {state}, {frames} frames, {counts['modules']} modules, {counts['files']} game-file opens, " - f"{counts['chunks']} chunks decompressed, {counts['refused']} network opens refused, " - f"{counts.get('handled probes', 0)} handled probes") - if ended and not progressed: - break - if os.path.exists(finished): - ended = True - continue - time.sleep(0.25) -print("-" * 110) -try: - with open(finished, encoding="utf-8", errors="replace") as handle: - print(handle.read().strip()) -except OSError: - pass -print("\nRun ended. Full logs are in " + os.path.abspath(rundir) + " (events.txt, files.txt, trap.log).") -# Closes by itself (the full logs stay in the run folder). -for left in range(10, 0, -1): - print(f"\rThis window closes in {left} s ", end="", flush=True) - time.sleep(1) + pass + print("\nRun ended. Full logs are in " + os.path.abspath(args.rundir) + " (events.txt, files.txt, trap.log).") + # Closes by itself (the full logs stay in the run folder). + for left in range(10, 0, -1): + print(f"\rThis window closes in {left} s ", end="", flush=True) + time.sleep(1) + except OSError as exc: + parser.exit(1, f"live_view: {exc}\n") + return 0 + + +if __name__ == "__main__": + _exit_code = main() + if _exit_code: + raise SystemExit(_exit_code) From e0da6b397ab5fde65f6257618a39aca38e67436a Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:55:38 +0100 Subject: [PATCH 219/232] shader: allow s_load into high SGPRs s[104:107] in gfx2hlsl (Part of #1723) (#2057) * fix: accept descriptor s_load into s[104:107] s106/s107 are vcc; a descriptor load emits no code, so it may end there. Root constant-buffer loads and destinations past s107 stay refused. * fix: refuse vcc reads after a descriptor s_load into s106/s107 * test: add WARP/hardware draw for s_load into s[104:107] with vcc compare/select --------- Co-authored-by: Codex <codex@openai.com> --- CMakeLists.txt | 10 ++ tests/startup_gfx2hlsl_sload_s104_check.py | 162 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 90 +++++++++++- 3 files changed, 261 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_sload_s104_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d645bd522..96eb3b956 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3743,6 +3743,13 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_mul_mad_i24_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl s_load into s[104:107] followed by a vcc compare and select: WARP/hardware draw vs CPU reference (Refs #1723). + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_sload_s104_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_sload_s104_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl dual-offset/stride-64 32-bit LDS ops and 32-bit LDS atomics (Refs #1541, #2274). add_test(NAME startup_compute_lds_dual_atomics_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_compute_lds_dual_atomics_check.py") @@ -4070,6 +4077,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Startup shader translator: the SMEM offset 'off' is the literal 0; m0 and other operands keep their handling (#1674). add_test(NAME startup_gfx2hlsl_smem_offset COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_smem_offset_check.py") + # Startup shader translator: s_load descriptor into s[104:107] (vcc is s106/s107) (#1723). + add_test(NAME startup_gfx2hlsl_sload_s104 COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sload_s104_check.py") # Startup shader translator: scalar constants are dropped at a branch join that another path writes (loop counters). add_test(NAME startup_gfx2hlsl_loop_constants COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_loop_constants_check.py") diff --git a/tests/startup_gfx2hlsl_sload_s104_check.py b/tests/startup_gfx2hlsl_sload_s104_check.py new file mode 100644 index 000000000..138a114f3 --- /dev/null +++ b/tests/startup_gfx2hlsl_sload_s104_check.py @@ -0,0 +1,162 @@ +"""Check s_load into s[104:107] in tools/startup/gfx2hlsl.py (#1723). + +usage: startup_gfx2hlsl_sload_s104_check.py pure Python controls + startup_gfx2hlsl_sload_s104_check.py draw <dxc> <offscreen_check> <warp|hardware> [fxc] + draw the translated pair, compare with a CPU reference + +s106 and s107 are vcc. A descriptor load (a table pointer plus an immediate offset) emits no code and only +records which table bytes the destination registers name, so it may end in s[104:107]. A load that must +write the registers (a root constant buffer) or that starts above s105 is still refused. +""" +import os +import struct +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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 compile_hlsl, draw # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import POST_WORDS, PRE_WORDS, vs_words, words_text # noqa: E402 + + +class Pipe: + sampler_heap = False + + def resource(self, key, kind): + return 'r0' + + +def run(symbols, op, operands): + s = G.Stage.__new__(G.Stage) + s.pipe, s.sym, s.lines = Pipe(), dict(symbols), [] + s.used_s, s.used_v, s.uniform_v, s.exec_known = set(), set(), set(), True + try: + getattr(s, 'op_' + op)(operands.split(', '), []) + except G.Unsupported as error: + return str(error) + return s + + +def translate(*instructions): + stage = G.Stage.__new__(G.Stage) + stage.pipe, stage.sym, stage.lines = Pipe(), dict(TABLE), [] + stage.kind, stage.attrs = 'ps', {} + stage.used_s, stage.used_v, stage.masks = set(), set(), set() + stage.exec_known = True + stage.ins = [(4 * i, 4, asm.split()[0], asm) for i, asm in enumerate(instructions)] + stage.translate() + return stage + + +TABLE = {4: ('ptr', ('table', 0))} +ROOT = {4: ('ptr', ('root', 1))} + + +# One descriptor table at s[8:9] (an SRV/UAV range of two entries, as the buffer store check declares it). +_RTS0 = b''.join((struct.pack('<6I', 2, 1, 24, 0, 0, 0), struct.pack('<3I', 0, 0, 36), + struct.pack('<2I', 1, 44), struct.pack('<6I', 0, 2, 0, 0, 0, 0))) +_PART = b'RTS0' + struct.pack('<I', len(_RTS0)) + _RTS0 +TABLE_ROOT = b'DXBC' + bytes(16) + struct.pack('<4I', 1, 36 + len(_PART), 1, 36) + _PART + +# Pixel body, words from llvm-mc gfx1013 with the first instruction's SDST patched from s[100:103] to s[104:107] +# (the assembler does not name s106/s107, the machine code does): +# s_load_dwordx4 s[104:107], s[8:9], 0x20 +# lane 0..3: v_cmp_eq_u32 vcc_lo, v<lane>, v<4+lane>; v_cndmask_b32 v<12+lane>, v<8+lane>, v<lane>, vcc_lo +# The descriptor load overwrites the vcc word; the compare redefines it before the mask is read. +BODY_WORDS = bytes.fromhex('041a08f4200000fa0009847d08011802010b847d09031a02020d847d0a051c02030f847d0b071e02') +DRAW = [(5, 5, 7), (1, 2, 9), (0xffffffff, 0xffffffff, 3), (0x80000000, 0x7fffffff, 0x1234)] +DRAW_B = [(9, 9, 0), (4, 4, 4), (0, 1, 2), (0xdeadbeef, 0xdeadbeef, 1)] + + +def reference(sets): + return [a if a == b else c for a, b, c in sets] + + +def check_draw(dxc, renderer, adapter, fxc=None): + main() + ps = PRE_WORDS + BODY_WORDS + POST_WORDS + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for number, sets in enumerate((DRAW, DRAW_B)): + # Triples are (a, b, c): the load is a no-op, so the pixel is a == b ? a : c on each lane. + pipe = G.Pipeline(vs_words(sets), ps, TABLE_ROOT) + vs = compile_hlsl(compiler, kind, pipe.hlsl_vs(), 'vs%d_%s' % (number, kind), vs_profile, directory) + px = compile_hlsl(compiler, kind, pipe.hlsl_ps(), 'ps%d_%s' % (number, kind), ps_profile, directory) + expected = words_text(reference(sets)) + run = draw(renderer, adapter, vs, px, expected) + if run.returncode: + raise AssertionError('%s %s\n%s\n%s' % (kind, expected, run.stdout, run.stderr)) + print('%s s104 draw %d: %s' % (kind, number, expected), flush=True) + + +def main(): + s = run(TABLE, 's_load_dwordx4', 's[104:107], s[4:5], 0x20') + assert not isinstance(s, str), s + assert [s.sym[104 + i] for i in range(4)] == [('desc', ('table', 0), 0x20, i) for i in range(4)], s.sym + assert s.lines == [], s.lines + s = run(TABLE, 's_load_dwordx8', 's[100:107], s[4:5], 0x20') + assert not isinstance(s, str), s + for bad, symbols in (('s_load_dwordx4 s[104:107], s[4:5], 0x20', ROOT), + ('s_load_dwordx2 s[106:107], s[4:5], 0x20', TABLE), + ('s_load_dwordx2 s[105:106], s[4:5], 0x20', TABLE), + ('s_load_dwordx4 s[105:108], s[4:5], 0x20', TABLE)): + op, operands = bad.split(' ', 1) + message = run(symbols, op, operands) + assert isinstance(message, str) and 's_load destination' in message, (bad, message) + # The loaded descriptor replaced vcc: reads are refused until vcc is written again. + s = run(TABLE, 's_load_dwordx4', 's[104:107], s[4:5], 0x20') + for read in (lambda: s.u('vcc_lo'), lambda: s.emit('v0 = (vcc & 1) ? 1u : 0u;')): + try: + read() + except G.Unsupported as error: + assert 'vcc read' in str(error), error + else: + raise AssertionError('vcc read accepted after s_load into s[104:107]') + assert s.descriptor('s[104:107]') == (('table', 0), 0x20) + s.emit('vcc = (v1 == 0u) & 1;') + assert s.u('vcc_lo') == 'vcc' + try: + s.descriptor('s[104:107]') + except G.Unsupported as error: + assert 'overlaps a redefined vcc' in str(error), error + else: + raise AssertionError('descriptor still accepted after its VCC word was clobbered') + # The branch jumps over the compare, so its target can read the descriptor word as VCC. + load = 's_load_dwordx4 s[104:107], s[4:5], 0x20' + compare = 'v_cmp_eq_u32_e32 0, v1' + read = 'v_cndmask_b32_e32 v0, 0, 1' + assert translate(load, compare, read, 's_endpgm').u('vcc_lo') == 'vcc' + try: + translate(load, 's_cbranch_scc0 label_000C', compare, read, 's_endpgm') + except G.Unsupported as error: + assert 'vcc read after a descriptor load into s106/s107' in str(error), error + else: + raise AssertionError('branch skipped the only VCC redefinition') + translate(load, compare, 's_cbranch_scc0 label_0010', 's_nop 0', read, 's_endpgm') + # The load may be bypassed on one path; the resource would then have no matching descriptor. + fetch = 'buffer_load_dword v0, off, s[104:107], 0' + translate(load, 's_cbranch_scc0 label_000C', 's_nop 0', fetch, 's_endpgm') + try: + translate('s_cbranch_scc0 label_000C', load, 's_nop 0', fetch, 's_endpgm') + except G.Unsupported as error: + assert ('without a matching load on every path' in str(error) + or 'joined at a branch target' in str(error)), error + else: + raise AssertionError('branch skipped the only descriptor load') + s = run(TABLE, 's_load_dwordx4', 's[100:103], s[4:5], 0x20') + assert s.u('vcc_lo') == 'vcc' + print('ok') + + +if __name__ == '__main__': + if len(sys.argv) == 1: + main() + elif sys.argv[1] == 'draw': + check_draw(*sys.argv[2:]) + else: + raise SystemExit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ea7957264..3a74275aa 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1774,6 +1774,7 @@ def note_whole_read(self, reg): def u(self, tok, *, low16_only=False): """uint expression for a 32-bit operand.""" if tok in ('vcc_lo', 'vcc'): + self.read_vcc() return 'vcc' if tok in ('exec_lo', 'exec'): return 'exec' @@ -1857,9 +1858,67 @@ def const_u32(self, tok): except ValueError: return None + def read_vcc(self): + if getattr(self, 'has_branches', False): + self.vcc_events.setdefault(self.pc, []).append(('read_vcc', None)) + elif getattr(self, 'vcc_lost', False): + raise Unsupported('vcc read after a descriptor load into s106/s107') + def emit(self, text): + if 'vcc' in text: + assignment = re.match(r'vcc = (.*);$', text) + rhs = assignment.group(1) if assignment else text + if re.search(r'\bvcc\b', rhs): + self.read_vcc() + if assignment: + if getattr(self, 'has_branches', False): + self.vcc_events.setdefault(self.pc, []).append(('write_vcc', None)) + if getattr(self, 'vcc_lost', False): + # The scalar symbols are provisional across branches, checked after translation. + self.vcc_lost = False + self.vcc_descriptor_overwritten = True + if not getattr(self, 'has_branches', False): + self.sym.pop(106, None) + self.sym.pop(107, None) self.lines.append(text) + def check_vcc_paths(self): + """An overlapping descriptor must reach its use on every path, and VCC must be numeric at a mask read.""" + if not self.has_branches or not any(event == 'load_descriptor' for events in self.vcc_events.values() + for event, _ in events): + return + offsets = [off for off, _, _ in self.blocks] + index = {off: i for i, off in enumerate(offsets)} + by_block = [[] for _ in offsets] + block = 0 + for off, events in sorted(self.vcc_events.items()): + while block + 1 < len(offsets) and offsets[block + 1] <= off: + block += 1 + by_block[block].extend(events) + todo = [(0, None)] + seen = set() + while todo: + block, state = todo.pop() + if (block, state) in seen: + continue + seen.add((block, state)) + for event, value in by_block[block]: + if event == 'read_vcc' and state is not None: + raise Unsupported('vcc read after a descriptor load into s106/s107') + if event == 'read_descriptor': + if state is None or any(state[reg] != symbol for reg, symbol in value): + raise Unsupported('descriptor operand overlaps s106/s107 without a matching load on every path') + if event == 'load_descriptor': + state = value + elif event == 'write_vcc': + state = None + term = self.blocks[block][2] + if term and term[0] in ('jump', 'branch'): + if term[-1] in index: + todo.append((index[term[-1]], state)) + if (not term or term[0] == 'branch') and block + 1 < len(offsets): + todo.append((block + 1, state)) + def clear_low16(self, n): if isinstance(self.low16_only_v, set) and self.exec_known and n not in self.pinned_low16_v: self.low16_only_v.discard(n) @@ -1969,6 +2028,12 @@ def descriptor(self, tok): """Resource key for a descriptor operand like s[8:11]: (source, byte offset or None).""" r = reg_range(tok) s = self.sym.get(r[1]) if r else None + if r and r[0] == 's' and r[1] <= 107 and r[2] >= 106: + if getattr(self, 'has_branches', False): + expected = tuple((i - 106, self.sym.get(i)) for i in range(max(106, r[1]), min(107, r[2]) + 1)) + self.vcc_events.setdefault(self.pc, []).append(('read_descriptor', expected)) + elif getattr(self, 'vcc_descriptor_overwritten', False): + raise Unsupported('descriptor operand %s overlaps a redefined vcc' % tok) if s and s[0] == 'desc': # A descriptor can start inside a wider load (s_load_dwordx16 fetches two image # descriptors): its offset is the load's offset plus the first register's dword index. @@ -2396,6 +2461,7 @@ 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.vcc_events = {} self.entry_table_pointers = { reg: sym[1] for reg, sym in init_sym.items() if isinstance(reg, int) and sym[0] == 'ptr' and sym[1][0] == 'table' @@ -2590,6 +2656,12 @@ def translate(self): raise Unsupported(reason) refusals.append((reason, self.kind)) self.pinned_low16_v.update(self.low16_only_v) + try: + self.check_vcc_paths() + except Unsupported as reason: + if refusals is None: + raise + refusals.append((str(reason), self.kind)) leak = self.pinned_low16_v & self.whole_read_v if leak: reason = 'whole-word read of v%d after odd d16 image_load' % min(leak) @@ -2863,6 +2935,8 @@ def lower(self, base, asm, ops, mods): self.emit('GroupMemoryBarrierWithGroupSync();') return None if base.startswith('s_cbranch_'): + if base[10:].startswith('vcc'): + self.read_vcc() if getattr(self, 'kind', None) == 'ms' and base in ('s_cbranch_scc0', 's_cbranch_scc1') and not self.scc_uniform: 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', @@ -3643,7 +3717,11 @@ def op_s_load_dwordx4(self, ops, mods, count=4): if len(ops) != 3: raise Unsupported('s_load with %d operands' % len(ops)) dst, base = reg_range(ops[0]), reg_range(ops[1]) - if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[2] > 105: + if not dst or dst[0] != 's' or dst[2] - dst[1] + 1 != count or dst[1] > 105 or dst[2] > 107: + raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) + # s106/s107 are vcc: only a descriptor load, which emits no code, may end there (s[104:107]). + into_vcc = dst[2] > 105 + if into_vcc and (dst[1] > 104 or dst[2] != 107): raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) if not base or base[0] != 's' or base[2] - base[1] != 1 or base[2] > 105: raise Unsupported('s_load base %s' % ops[1]) @@ -3670,6 +3748,8 @@ def op_s_load_dwordx4(self, ops, mods, count=4): if imm is not None: raise Unsupported('SMEM literal offset %s with offset:%#x' % (ops[2], imm)) if p[1][0] == 'root': + if into_vcc: + raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) buf = self.pipe.resource((p[1], None), 'buf') for i in range(count): self.set_s(dst[1] + i, '%s.Load(%d)' % (buf, off + 4 * i)) @@ -3689,7 +3769,15 @@ def op_s_load_dwordx4(self, ops, mods, count=4): load = (self.pc,) for i in range(count): self.sym[dst[1] + i] = ('desc', p[1], off, i) + load + if into_vcc: + self.vcc_lost = True + self.vcc_descriptor_overwritten = False + if getattr(self, 'has_branches', False): + value = tuple(self.sym.get(i) for i in (106, 107)) + self.vcc_events.setdefault(self.pc, []).append(('load_descriptor', value)) return + if into_vcc: + raise Unsupported('s_load destination %s for %d dwords' % (ops[0], count)) if p[1] == ('smpheap',): if self.pipe.sampler_heap and count == 4: # A sampler picked at run time from the sampler heap: keep the byte offset in the From f03cf16f3bf98197c7679a3eb12ded26e08f2b98 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:55:51 +0100 Subject: [PATCH 220/232] shader: lower binary16 arithmetic and integer conversions in gfx2hlsl (Part of #1723) (#2073) * shader: lower 16-bit vector ALU and i16/u16 conversions in gfx2hlsl Part of #1723. Adds v_add/sub/subrev/mul/min/max/fmac/fmamk/fmaak_f16 and v_cvt_f16_i16/u16, v_cvt_i16/u16_f16, with a unit test registered in CMakeLists.txt. * fix: round the 1/(2*pi) inline constant to binary16 in 16-bit VALU * test: draw the 16-bit vector ALU lowering on WARP against a binary16 reference * fix: decode 16-bit VALU inline constants and negated literals at half width, round f16 results to nearest even * test: tag integer results in the 16-bit ALU draw so FXC keeps denormal-range words * test: anchor the ubyte2 mutation to the byte mask so the f16 rounding helper is not matched The always-emitted f16rn helper contains '>> 16)', so the unanchored pattern matched five times instead of four lanes. * fix: round v_fmac_f16 family once, TwoSum plus round to odd before the binary16 rounding The binary32 sum a*b + c was rounded and then rounded again to binary16, one unit off on about 2e-5 of triples. Add the four measured counterexample triples to the Python check and to the real draw fixture. * fix: lower v_fmac/fmamk/fmaak_f16 with integer fma16_rne (#2073) --- CMakeLists.txt | 13 + tests/startup_gfx2hlsl_cvt_alu_check.py | 2 +- tests/startup_gfx2hlsl_f16_alu_check.py | 148 +++++++++ tests/startup_gfx2hlsl_f16_alu_draw_check.py | 299 +++++++++++++++++++ tools/startup/gfx2hlsl.py | 75 +++++ 5 files changed, 536 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_f16_alu_check.py create mode 100644 tests/startup_gfx2hlsl_f16_alu_draw_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 96eb3b956..1835c1584 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3168,6 +3168,9 @@ if(EXISTS "${INTAKE_PYTHON}") # The binary16 class comparison (#1855). add_test(NAME startup_gfx2hlsl_cmp_class_f16 COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_cmp_class_f16_check.py") + # The 16-bit vector ALU: add, sub, mul, min, max, fma forms and the i16/u16 conversions (#1723). + add_test(NAME startup_gfx2hlsl_f16_alu COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_check.py") # op_sel on a translated float operation is refused, not dropped (#1735). add_test(NAME startup_gfx2hlsl_opsel COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_opsel_check.py") @@ -3572,6 +3575,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sgpr_spill_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl 16-bit vector ALU (#1723): the translated pairs drawn on WARP and hardware (FXC 5_1 and DXC 6_0), + # four result words per draw against an exact binary16 reference. + add_test(NAME startup_gfx2hlsl_f16_alu_draw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_draw_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_f16_alu_draw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_f16_alu_draw_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_f16_alu_draw_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl v_cmpx_le_i32_sdwa on a sign-extended byte decides which of 16 x 16 pixels survive, checked # pixel by pixel (#1906); translations without the select or without sext() must fail the same draw. foreach(adapter IN ITEMS warp hardware) diff --git a/tests/startup_gfx2hlsl_cvt_alu_check.py b/tests/startup_gfx2hlsl_cvt_alu_check.py index f4df92f7a..d49a18287 100644 --- a/tests/startup_gfx2hlsl_cvt_alu_check.py +++ b/tests/startup_gfx2hlsl_cvt_alu_check.py @@ -82,7 +82,7 @@ def to_half(word): lambda a: 0 if value(a) != value(a) or value(a) <= 0 else round(value(a))), 'v_cvt_f32_ubyte0': (r'& 255\)\)', r'& 127))', lambda a: f32(float(a & 127))), 'v_cvt_f32_ubyte1': (r'>> 8\)', r'>> 16)', lambda a: f32(float(a >> 16 & 255))), - 'v_cvt_f32_ubyte2': (r'(v\d+) >> 16\)', r'\1 >> 8)', lambda a: f32(float(a >> 8 & 255))), + 'v_cvt_f32_ubyte2': (r'(v\d+) >> 16\) & 255', r'\1 >> 8) & 255', lambda a: f32(float(a >> 8 & 255))), 'v_cvt_f32_ubyte3': (r'U\(float\((v\d+) >> 24\)\)', r'U(float((\1 >> 16) & 255))', lambda a: f32(float(a >> 16 & 255))), 'v_cvt_f32_f16': (r'f16tof32\((v\d+)\)', r'f16tof32(\1 >> 16)', lambda a: f32(half(a >> 16))), 'v_cvt_f16_f32': (r'f32tof16\(F\((v\d+)\)\)', r'f32tof16(-F(\1))', lambda a: to_half(a ^ 0x80000000)), diff --git a/tests/startup_gfx2hlsl_f16_alu_check.py b/tests/startup_gfx2hlsl_f16_alu_check.py new file mode 100644 index 000000000..98a93969f --- /dev/null +++ b/tests/startup_gfx2hlsl_f16_alu_check.py @@ -0,0 +1,148 @@ +"""16-bit vector ALU lowering in tools/startup/gfx2hlsl.py (Part of #1723). + +usage: startup_gfx2hlsl_f16_alu_check.py + +v_add/sub/subrev/mul/min/max/fmac/fmamk/fmaak_f16 and v_cvt_f16_i16/u16, v_cvt_i16/u16_f16 read the low 16 bits of +their sources and write the low 16 bits of the destination (RDNA 2 zeroes the upper half). The check lowers each +instruction through Stage.one() and runs the emitted statement with a small Python model of the HLSL helpers, so the +result is compared as bits, not as text. +""" +import math +from fractions import Fraction +import os +import re +import struct +import sys + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def h2f(bits): + return struct.unpack('<e', struct.pack('<H', bits & 0xffff))[0] + + +def f2h(value): + return struct.unpack('<H', struct.pack('<e', value))[0] + + +def fma16o(a, b, c): + """Model of the HLSL fma16o contract: finite binary16 operands give a*b+c rounded once, ties to even (the HLSL + does it in 32-bit integer arithmetic, #2073); non-finite operands use binary32 arithmetic.""" + if not all(math.isfinite(v) for v in (a, b, c)): + with_nan = a * b + c if not (math.isinf(a * b) and math.isinf(c) and (a * b > 0) != (c > 0)) else math.nan + return with_nan + exact = Fraction(a) * Fraction(b) + Fraction(c) + return h2f(f2h_exact(exact)) + + +def f2h_exact(x): + """Binary16 encoding of a rational, rounded to nearest even, overflow to infinity.""" + sign = 0x8000 if x < 0 else 0 + x = abs(x) + if x == 0: + return sign + e = max(x.numerator.bit_length() - x.denominator.bit_length() - 1, -14) + if Fraction(2) ** (e + 1) <= x: + e += 1 + while Fraction(2) ** e > x and e > -14: + e -= 1 + q = x / Fraction(2) ** (e - 10) + n = int(q) + if q - n > Fraction(1, 2) or (q - n == Fraction(1, 2) and n & 1): + n += 1 + if n == 0x800: + n, e = 0x400, e + 1 + if e > 15: + return sign | 0x7c00 + return sign | (n if e == -14 and n < 0x400 else ((e + 15) << 10) | (n & 0x3ff)) + + +def stage(): + s = G.Stage.__new__(G.Stage) + s.lines, s.sym, s.used_s, s.used_v, s.masks = [], {}, set(), set(), set() + s.exec_known = True + return s + + +def run(asm, regs): + """Lower one instruction and evaluate its single statement over the register values in regs (v0, v1, ...).""" + s = stage() + name = asm.split()[0] + s.one(name, asm) + assert len(s.lines) == 1, s.lines + dst, expr = re.fullmatch(r'(v\d+) = (.*);', s.lines[0]).groups() + env = {f'v{i}': v for i, v in enumerate(regs)} + env.update( + f16tof32=lambda x: h2f(x), fma16o=fma16o, f16rn=lambda x: f2h(x) if abs(x) < 65520.0 else (0xfc00 if x < 0 else 0x7c00), saturate=lambda x: min(max(x, 0.0), 1.0), + abs=abs, min=min, max=max, clamp=lambda x, lo, hi: min(max(x, lo), hi), + trunc=lambda x: float(int(x)), isnan=math.isnan, + asint=lambda x: x - (1 << 32) if x >> 31 else x, float=float, uint=lambda x: int(x) & 0xffffffff, int=int) + py = expr.replace('0u', '0').replace('&&', 'and') + py = re.sub(r'(0x[0-9a-f]+)u', r'\1', py) + py = re.sub(r'\b(\d+)u\b', r'\1', py) + py = re.sub(r'^isnan\((.*?)\) \? 0 : (.*)$', r'(0 if isnan(\1) else \2)', py) + return dst, eval(py, {}, env) + + +ONE, TWO, HALF, THREE = f2h(1.0), f2h(2.0), f2h(0.5), f2h(3.0) +HIGH = 0xabcd0000 +CASES = [ + ('v_add_f16 v3, v0, v1', [ONE | HIGH, TWO | HIGH], THREE), + ('v_sub_f16 v3, v0, v1', [THREE, ONE], TWO), + ('v_subrev_f16 v3, v0, v1', [ONE, THREE], TWO), + ('v_mul_f16 v3, v0, v1', [THREE | HIGH, TWO], f2h(6.0)), + ('v_min_f16 v3, v0, v1', [THREE, TWO], TWO), + ('v_max_f16 v3, v0, v1', [THREE, TWO], THREE), + ('v_fmac_f16 v2, v0, v1', [TWO, THREE, ONE], f2h(7.0)), + ('v_fmamk_f16 v3, v0, 0x4000, v1', [THREE, ONE], f2h(7.0)), + ('v_fmaak_f16 v3, v0, v1, 0x3c00', [THREE, TWO], f2h(7.0)), + # Binary32 sum then binary16 would be one unit low on each (#2073); one rounding gives these words. + ('v_fmac_f16 v2, v0, v1', [0x4a54, 0x1ef4, 0x4e2d], 0x4e33), + ('v_fmac_f16 v2, v0, v1', [0x51ea, 0xbf3e, 0x1d5f], 0xd55b), + ('v_fmac_f16 v2, v0, v1', [0x2bd5, 0xbe83, 0x4528], 0x450f), + ('v_fmac_f16 v2, v0, v1', [0x3915, 0x387a, 0x4b71], 0x4b9f), + ('v_add_f16 v3, 1.0, v1', [0, TWO], THREE), + ('v_mul_f16 v3, 0.15915494, v1', [0, f2h(100.0)], f2h(h2f(f2h(0.15915494)) * 100.0)), + ('v_mul_f16 v3, 0.15915494, v1', [0, 0x3002], 0x251b), + ('v_cvt_f16_i16 v3, 1.0', [], f2h(15360.0)), + ('v_cvt_f16_u16 v3, -1.0', [], f2h(48128.0)), + ('v_add_f16 v3, -0x3c01, v1', [0, 0], 0xbc01), + ('v_add_f16 v3, -v0, v1', [ONE, THREE], TWO), + ('v_add_f16 v3, |v0|, v1', [f2h(-1.0), TWO], THREE), + ('v_cvt_f16_i16 v3, v0', [0xfffd | HIGH], f2h(-3.0)), + ('v_cvt_f16_u16 v3, v0', [0x8403 | HIGH], f2h(33795.0)), + ('v_cvt_i16_f16 v3, v0', [f2h(-2.75) | HIGH], 0xfffe), + ('v_cvt_i16_f16 v3, v0', [f2h(60000.0)], 0x7fff), + ('v_cvt_u16_f16 v3, v0', [f2h(2.75) | HIGH], 2), + ('v_cvt_u16_f16 v3, v0', [f2h(-1.5)], 0), +] +for asm, regs, expected in CASES: + dst, got = run(asm, regs + [0] * (4 - len(regs))) + check(asm + ' ' + str(regs), got == expected, 'got %#x want %#x' % (got, expected)) +check('clamp saturates the binary16 result', run('v_add_f16 v3, v0, v1 clamp', [THREE, TWO, 0, 0])[1] == ONE) + +for asm in ('v_add_f16 v3, v0, v1 op_sel:[1,0]', 'v_cvt_i16_f16 v3, v0 clamp', 'v_add_f16 v3, v0', + 'v_fmaak_f16 v3, v0, v1', 'v_mul_f16 v3, v0, v1 mul:2'): + try: + stage().one(asm.split()[0], asm) + check('refuses ' + asm, False) + except G.Unsupported: + check('refuses ' + asm, True) + +if failures: + print('FAILED: ' + ', '.join(failures)) + sys.exit(1) +print('f16 alu ok') diff --git a/tests/startup_gfx2hlsl_f16_alu_draw_check.py b/tests/startup_gfx2hlsl_f16_alu_draw_check.py new file mode 100644 index 000000000..49a5e674c --- /dev/null +++ b/tests/startup_gfx2hlsl_f16_alu_draw_check.py @@ -0,0 +1,299 @@ +"""16-bit vector ALU lowering in tools/startup/gfx2hlsl.py, drawn on a real D3D12 adapter (Part of #1723). + + (no arguments) translation controls and reference self-checks, pure Python + binary <llvm-mc> reassemble the fixture bodies and compare them with the words below + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair (FXC ps_5_1 when given, DXC ps_6_0), draw one pixel + per four input sets and compare the four result words with the CPU reference + +The pixel fixture is the one of startup_gfx2hlsl_bit_alu_check.py: three flat parameters (v0..v3, v4..v7, v8..v11), +one operation per lane, results in v12..v15 exported to mrt0. The vertex stage places the inputs in the parameters, so +the pixel stage cannot fold them. Every source word carries garbage in its upper half: the 16-bit operations read the +low half only and write a result whose upper half is zero. + +The expected words come from an exact rational model of binary16 arithmetic (Fraction, then one round to binary16), +not from the lowering's expressions. +""" +import math +import re +import struct +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)) +import gfx2hlsl as G # noqa: E402 +from startup_flat_param_check import assemble, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import ( # noqa: E402 + POST_WORDS, PRE_WORDS, vs_source, vs_words, words_text) + +K = 0x4900 # literal operand of v_fmamk_f16 / v_fmaak_f16: 10.0 + + +def h2f(bits): + return struct.unpack('<e', struct.pack('<H', bits & 0xffff))[0] + + +def f2h(value): + return struct.unpack('<H', struct.pack('<e', value))[0] + + +def exact(bits): + return Fraction(h2f(bits)) + + +def round_half(value): + """Nearest binary16 (ties to even) of an exact rational; overflow gives infinity.""" + try: + return f2h(float(value)) + except OverflowError: + return 0xfc00 if value < 0 else 0x7c00 + + +def trunc_clamp(bits, lo, hi): + value = h2f(bits) + if math.isnan(value): + return 0 + return int(max(lo, min(hi, math.trunc(value)))) if not math.isinf(value) else (hi if value > 0 else lo) + + +def signed16(v): + v &= 0xffff + return v - 0x10000 if v & 0x8000 else v + + +def f_min(a, b): + return a if exact(a) < exact(b) else b + + +def f_max(a, b): + return a if exact(a) > exact(b) else b + + +# mnemonic -> (source count, VOP1 spelling, reference over (s0, s1, s2) words) +OPS = { + 'v_add_f16': (2, False, lambda a, b, c: round_half(exact(a) + exact(b))), + 'v_sub_f16': (2, False, lambda a, b, c: round_half(exact(a) - exact(b))), + 'v_subrev_f16': (2, False, lambda a, b, c: round_half(exact(b) - exact(a))), + 'v_mul_f16': (2, False, lambda a, b, c: round_half(exact(a) * exact(b))), + 'v_min_f16': (2, False, lambda a, b, c: f_min(a & 0xffff, b & 0xffff)), + 'v_max_f16': (2, False, lambda a, b, c: f_max(a & 0xffff, b & 0xffff)), + 'v_fmac_f16': (2, False, lambda a, b, c: round_half(exact(a) * exact(b) + exact(c))), + 'v_fmamk_f16': (2, False, lambda a, b, c: round_half(exact(a) * exact(K) + exact(b))), + 'v_fmaak_f16': (2, False, lambda a, b, c: round_half(exact(a) * exact(b) + exact(K))), + 'v_cvt_f16_i16': (1, True, lambda a, b, c: round_half(Fraction(signed16(a)))), + 'v_cvt_f16_u16': (1, True, lambda a, b, c: round_half(Fraction(a & 0xffff))), + 'v_cvt_i16_f16': (1, True, lambda a, b, c: trunc_clamp(a, -32768, 32767) & 0xffff), + 'v_cvt_u16_f16': (1, True, lambda a, b, c: trunc_clamp(a, 0, 65535)), +} + +G_ = {name: f2h(value) for name, value in ( + ('1', 1.0), ('2', 2.0), ('3', 3.0), ('half', 0.5), ('m1', -1.0), ('m2.5', -2.5), ('100', 100.0), ('0.1', 0.1), + ('1000', 1000.0), ('m3', -3.0), ('7', 7.0), ('2.75', 2.75), ('m2.75', -2.75), ('60000', 60000.0), + ('m60000', -60000.0), ('3.25', 3.25), ('300', 300.0), ('0', 0.0), ('1.5', 1.5), ('0.3', 0.3))} +HIGH = (0xabcd0000, 0x5a5a0000, 0xdead0000, 0x12340000) + + +def sets(pairs, accumulators=None): + """Eight lanes of (s0, s1, s2) with garbage in the upper half of every word.""" + out = [] + for i, (a, b) in enumerate(pairs): + c = accumulators[i] if accumulators else 0 + out.append((a | HIGH[i % 4], b | HIGH[(i + 1) % 4], c | HIGH[(i + 2) % 4])) + return out + + +F = G_ +ARITH = [(F['1'], F['2']), (F['3'], F['m1']), (F['0.1'], F['0.3']), (F['100'], F['1000']), + (F['m2.5'], F['half']), (F['1.5'], F['7']), (F['300'], F['m3']), (F['3.25'], F['2.75'])] +ACC = [F['1'], F['m1'], F['half'], F['100'], F['2'], F['0'], F['3'], F['7']] +# (a, b, c) binary16 triples where rounding the binary32 sum and then binary16 differs from one rounding (#2073). +# Measured on AMD RX 9070 XT and WARP: the earlier f16rn(a*b + c) lowering was one binary16 unit low on each. +FMAC_DOUBLE_ROUNDING = [(0x4a54, 0x1ef4, 0x4e2d), (0x51ea, 0xbf3e, 0x1d5f), (0x2bd5, 0xbe83, 0x4528), + (0x3915, 0x387a, 0x4b71)] +INTS = [(0x0003, 0), (0xfffd, 0), (0x8403, 0), (0x7fff, 0), (0x8000, 0), (0, 0), (0xffff, 0), (0x00ff, 0)] +FLOATS = [(F['2.75'], 0), (F['m2.75'], 0), (F['60000'], 0), (F['m60000'], 0), (F['half'], 0), (F['m1'], 0), + (F['100'], 0), (f2h(0.99951171875), 0)] +DRAW = {} +for _name, (_arity, _vop1, _ref) in OPS.items(): + if _name.startswith('v_cvt_f16'): + DRAW[_name] = sets(INTS) + elif _name.startswith('v_cvt_'): + DRAW[_name] = sets(FLOATS) + else: + DRAW[_name] = sets(ARITH, ACC if _name == 'v_fmac_f16' else None) +# Four double-rounding lanes replace the first four fixture lanes of v_fmac_f16 (eight lanes stay two draws). +DRAW['v_fmac_f16'] = [tuple(w | HIGH[(i + k) % 4] for k, w in enumerate(t)) for i, t in + enumerate(FMAC_DOUBLE_ROUNDING)] + DRAW['v_fmac_f16'][4:] + + +def body_source(op): + arity, vop1, _ = OPS[op] + lines = [] + for lane in range(4): + dst, a, b = 12 + lane, lane, 4 + lane + if op == 'v_fmac_f16': + lines.append('v_mov_b32 v%d, v%d\n' % (dst, 8 + lane)) + if op == 'v_fmamk_f16': + lines.append('%s v%d, v%d, 0x%x, v%d\n' % (op, dst, a, K, b)) + elif op == 'v_fmaak_f16': + lines.append('%s v%d, v%d, v%d, 0x%x\n' % (op, dst, a, b, K)) + elif vop1: + lines.append('%s%s v%d, v%d\n' % (op, '_e64' if lane % 2 else '', dst, a)) + else: + lines.append('%s v%d, v%d, v%d\n' % (op, dst, a, b)) + return ''.join(lines) + + +# Recorded llvm-mc (gfx1013) encodings of body_source(op); `binary <llvm-mc>` regenerates and compares them. +BODY_WORDS = { + 'v_add_f16': bytes.fromhex( + '00091864010b1a64020d1c64030f1e64'), + 'v_sub_f16': bytes.fromhex( + '00091866010b1a66020d1c66030f1e66'), + 'v_subrev_f16': bytes.fromhex( + '00091868010b1a68020d1c68030f1e68'), + 'v_mul_f16': bytes.fromhex( + '0009186a010b1a6a020d1c6a030f1e6a'), + 'v_min_f16': bytes.fromhex( + '00091874010b1a74020d1c74030f1e74'), + 'v_max_f16': bytes.fromhex( + '00091872010b1a72020d1c72030f1e72'), + 'v_fmac_f16': bytes.fromhex( + '0803187e0009186c09031a7e010b1a6c0a031c7e020d1c6c0b031e7e030f1e6c'), + 'v_fmamk_f16': bytes.fromhex( + '0009186e00490000010b1a6e00490000020d1c6e00490000030f1e6e00490000'), + 'v_fmaak_f16': bytes.fromhex( + '0009187000490000010b1a7000490000020d1c7000490000030f1e7000490000'), + 'v_cvt_f16_i16': bytes.fromhex( + '00a3187e0d00d1d50101000002a31c7e0f00d1d503010000'), + 'v_cvt_f16_u16': bytes.fromhex( + '00a1187e0d00d0d50101000002a11c7e0f00d0d503010000'), + 'v_cvt_i16_f16': bytes.fromhex( + '00a7187e0d00d3d50101000002a71c7e0f00d3d503010000'), + 'v_cvt_u16_f16': bytes.fromhex( + '00a5187e0d00d2d50101000002a51c7e0f00d2d503010000'), +} + + +def ps_words(op): + return PRE_WORDS + BODY_WORDS[op] + POST_WORDS + + +def reference(op, x): + return OPS[op][2](*x) & 0xffffffff + + +def translate(op): + return G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()).hlsl_ps() + + +# The target is R32G32B32A32_FLOAT, so a small integer result is a binary32 denormal and FXC drops it when it comes +# from a float to integer conversion. The integer-result operations therefore set bit 30 on the way out of the pixel +# stage and in the expected word; the translated statements themselves are unchanged. +INTEGER_RESULT = ('v_cvt_i16_f16', 'v_cvt_u16_f16') +TAG = 0x40000000 + + +def draw_text(op): + text = translate(op) + return re.sub(r'F\(v(1[2-5])\)', r'F(v\1 | 0x%xu)' % TAG, text) if op in INTEGER_RESULT else text + + +def draw_word(op, x): + return reference(op, x) | (TAG if op in INTEGER_RESULT else 0) + + +def controls(): + failures = [] + + def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + failures.append(label) + + # The model itself, by hand: 0.1 + 0.3 in binary16, saturation, truncation toward zero, NaN reads 0. + check('model: 1 + 2 = 3', OPS['v_add_f16'][2](F['1'], F['2'], 0) == F['3']) + check('model: 60000 truncates to the i16 limit', OPS['v_cvt_i16_f16'][2](F['60000'], 0, 0) == 0x7fff) + check('model: -60000 saturates to -32768', OPS['v_cvt_i16_f16'][2](F['m60000'], 0, 0) == 0x8000) + check('model: a negative value converts to u16 zero', OPS['v_cvt_u16_f16'][2](F['m1'], 0, 0) == 0) + check('model: NaN converts to zero', OPS['v_cvt_i16_f16'][2](0x7e00, 0, 0) == 0) + check('model: 0xfffd is -3 as i16', OPS['v_cvt_f16_i16'][2](0xfffd, 0, 0) == F['m3']) + for a, b, c, want in ((0x4a54, 0x1ef4, 0x4e2d, 0x4e33), (0x51ea, 0xbf3e, 0x1d5f, 0xd55b), + (0x2bd5, 0xbe83, 0x4528, 0x450f), (0x3915, 0x387a, 0x4b71, 0x4b9f)): + check('model: fmac %04x*%04x+%04x is one rounding' % (a, b, c), OPS['v_fmac_f16'][2](a, b, c) == want) + check('draw: fmac covers the double-rounding triples', + all(tuple(w & 0xffff for w in x) in FMAC_DOUBLE_ROUNDING + for x in DRAW['v_fmac_f16'][:4])) + for op in OPS: + check('%s: every draw reference has a zero upper half' % op, + all(reference(op, x) >> 16 == 0 for x in DRAW[op])) + check('%s: draw sets cover two draws of four lanes' % op, len(DRAW[op]) == 8) + if BODY_WORDS: + for op in OPS: + try: + text = translate(op) + except G.Unsupported as e: + check('%s: translates (%s)' % (op, e), False) + continue + check('%s: translates to four lane results' % op, + all(('v%d = ' % r) in text for r in range(12, 16))) + if failures: + raise SystemExit('FAILED: ' + ', '.join(failures)) + + +def check_binary(llvm_mc): + for op in OPS: + built = assemble(llvm_mc, body_source(op)) + if built != BODY_WORDS[op]: + raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), BODY_WORDS[op].hex())) + for op in OPS: + for i in range(0, 8, 4): + if assemble(llvm_mc, vs_source(DRAW[op][i:i + 4])) != vs_words(DRAW[op][i:i + 4]): + raise AssertionError('vertex fixture for %s differs from llvm-mc' % op) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + controls() + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + failures = [] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op, lanes in DRAW.items(): + ps = compile_hlsl(compiler, kind, draw_text(op), 'ps_%s_%s' % (op, kind), ps_profile, directory) + for index in range(0, len(lanes), 4): + chunk = lanes[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + expected = words_text(draw_word(op, x) for x in chunk) + run = draw(renderer, adapter, vs, ps, expected) + if run.returncode: + failures.append('%s %s set %d' % (kind, op, index // 4)) + print('%s %s set %d MISMATCH inputs %s\n%s' % (kind, op, index // 4, chunk, run.stderr.strip()), + flush=True) + continue + print('%s %s set %d: %s' % (kind, op, index // 4, expected), flush=True) + if failures: + raise AssertionError('draw mismatches: ' + ', '.join(failures)) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3a74275aa..ab77ba394 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3007,6 +3007,8 @@ def lower(self, base, asm, ops, mods): return self.compare(base, ops, mods) if base.endswith('_sdwa'): return self.sdwa(base[:-len('_sdwa')], ops, mods) + if base in VEC_H: + return self.half_alu(base, ops, mods) if base in VEC_F: arity, text = VEC_F[base] # A missing source used to raise IndexError and an extra one was dropped without a word. @@ -3210,6 +3212,50 @@ def dpp(self, base, ops, mods): expr = text.format(*args) self.set_v(reg_range(ops[0])[1], 'U(%s)' % expr if kind == 'f' else expr) + def half_operand(self, tok, kind): + """Float expression for a 16-bit operand: the low half of the register, or an inline constant.""" + if kind in ('i16', 'u16'): + if tok in FLOATS: # an inline float constant is a binary16 word at 16-bit width, not binary32 + word = struct.unpack('<H', struct.pack('<e', FLOATS[tok]))[0] + src = '%du' % word + else: + src = self.u(tok) + if kind == 'i16': + return 'float(asint((%s & 0xffffu) << 16u) >> 16)' % src + return 'float(%s & 0xffffu)' % src + neg = False + if tok.startswith('-') and (not re.match(r'-[\d.]', tok) or re.match(r'-0x', tok)): + neg, tok = True, tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + if tok in FLOATS: + text = repr(struct.unpack('<e', struct.pack('<e', FLOATS[tok]))[0]) # inline constants are binary16 here + elif tok == '-0': + text = '0.0' + else: + text = 'f16tof32(%s & 0xffffu)' % self.u(tok) + if absolute: + text = 'abs(%s)' % text + return '(-%s)' % text if neg else text + + def half_alu(self, base, ops, mods): + """16-bit VALU: operands are the low 16 bits, the result fills the low 16 bits and zeroes the rest (RDNA 2).""" + arity, kind, text, result = VEC_H[base] + if len(ops) != arity + 1: + raise Unsupported('%s with %d operands, expected %d' % (base, len(ops), arity + 1)) + if any(m != 'clamp' for m in mods) or ('clamp' in mods and result != 'h'): + raise Unsupported('%s with %s' % (base, mods)) + args = [self.half_operand(o, kind) for o in ops[1:1 + arity]] + if base in ('v_fmac_f16', 'v_mac_f16'): + args.append(self.half_operand(ops[0], 'h')) + expr = text.format(*args) + if result == 'h': + if 'clamp' in mods: + expr = 'saturate(%s)' % expr + expr = 'f16rn(%s)' % expr + self.set_v(reg_range(ops[0])[1], expr) + # VOP1/VOP2 with sub-dword addressing: select the source fields, run the same operation, then place # the low bits of the result in the destination field. The integer forms reuse VEC_U unchanged, # v_mov_b32 is the same path with the selected source as its result, @@ -6299,6 +6345,20 @@ def declarations(self): 'v_sin_f32': (1, 'sin({0} * 6.283185307)'), 'v_cos_f32': (1, 'cos({0} * 6.283185307)'), 'v_med3_f32': (3, 'med3_32({0}, {1}, {2})'), 'v_min3_f32': (3, 'min({0}, min({1}, {2}))'), 'v_max3_f32': (3, 'max({0}, max({1}, {2}))'), } +# 16-bit VALU: (sources, source kind, float or uint expression of the sources, result kind). 'h' sources are +# binary16 read from the low half and computed in binary32; an 'h' result is rounded back to binary16. The +# i16/u16 conversions to binary16 read the low half as an integer; the conversions to integers truncate toward +# zero, saturate to the 16-bit range and read NaN as 0. +VEC_H = { + 'v_add_f16': (2, 'h', '{0} + {1}', 'h'), 'v_sub_f16': (2, 'h', '{0} - {1}', 'h'), + 'v_subrev_f16': (2, 'h', '{1} - {0}', 'h'), 'v_mul_f16': (2, 'h', '{0} * {1}', 'h'), + 'v_min_f16': (2, 'h', 'min({0}, {1})', 'h'), 'v_max_f16': (2, 'h', 'max({0}, {1})', 'h'), + 'v_fmac_f16': (2, 'h', 'fma16o({0}, {1}, {2})', 'h'), 'v_fmamk_f16': (3, 'h', 'fma16o({0}, {1}, {2})', 'h'), + 'v_fmaak_f16': (3, 'h', 'fma16o({0}, {1}, {2})', 'h'), + 'v_cvt_f16_i16': (1, 'i16', '{0}', 'h'), 'v_cvt_f16_u16': (1, 'u16', '{0}', 'h'), + 'v_cvt_i16_f16': (1, 'h', 'isnan({0}) ? 0u : (uint(int(clamp(trunc({0}), -32768.0, 32767.0))) & 0xffffu)', 'u'), + 'v_cvt_u16_f16': (1, 'h', 'isnan({0}) ? 0u : uint(clamp(trunc({0}), 0.0, 65535.0))', 'u'), +} # Conversions whose result is binary32. The expression is the float value, so an output modifier # (clamp, mul:2, mul:4, div:2) can wrap it the way it wraps any other float result. The uint-result # conversions stay in VEC_U. @@ -6642,6 +6702,7 @@ def sampler_lines(self): return lines def common(self): + import pixel_aot out = ['#define F(x) asfloat(x)', '#define U(x) asuint(x)', 'float mul_legacy(float a, float b) { return (a == 0.0 || b == 0.0) ? 0.0 : a * b; }', # Match pixel_aot: round the product before adding and flush denormals to signed zero. @@ -6679,6 +6740,20 @@ def common(self): 'uint mul_hi_u32(uint a, uint b) { uint la = a & 0xffffu, lb = b & 0xffffu;' ' uint middle = (a >> 16) * lb + ((la * lb) >> 16);' ' return (a >> 16) * (b >> 16) + (middle >> 16) + (((middle & 0xffffu) + la * (b >> 16)) >> 16); }', + # a * b + c for binary16 inputs with one rounding (#2073). The first form recovered the binary32 sum error + # with a floating-point TwoSum; an NVIDIA driver (RTX 3070 Ti, 32.0.16.2101) simplified that error term to + # zero despite `precise`, so ties rounded the wrong way. fma16_rne works on the encodings in 32-bit integer + # arithmetic, so no driver floating-point rewrite can reach it. Infinities and NaNs keep float semantics. + pixel_aot.SALU_HELPERS['fma16_rne'], + 'float fma16o(float a, float b, float c) {', + ' if (!isfinite(a) || !isfinite(b) || !isfinite(c)) return a * b + c;', + ' return f16tof32(fma16_rne(f32tof16(a), f32tof16(b), f32tof16(c)));', + '}', + # binary32 to binary16 rounded to nearest even: f32tof16 truncates, a binary16 result must round (#1723). + 'uint f16rn(float v) { uint b = asuint(v), s = (b >> 16) & 0x8000u, a = b & 0x7fffffffu;' + ' if (a > 0x7f800000u) return s | 0x7e00u; if (a >= 0x47800000u) return s | 0x7c00u;' + ' if (a < 0x38800000u) return s | uint(round(asfloat(a) * 16777216.0));' + ' uint r = a + 0xfffu + ((a >> 13) & 1u); return s | min((r - 0x38000000u) >> 13, 0x7c00u); }', # The ten binary32 classes v_cmp_class_f32 tests, from the raw encoding (#1795). 'uint class32(float value) { uint bits = asuint(value), magnitude = bits & 0x7fffffffu;' ' bool negative = bits >= 0x80000000u;' From d233f210c491beebcf99724c9ce47f19d771f22b Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:01:37 +0100 Subject: [PATCH 221/232] tests: add opt-in DXC compile cache for the Python shader checks (#2357) * tests: add opt-in X2W_DXC_CACHE compile cache for Python shader checks * fix: DXC cache runs uncached when the compiler is not a file A stub name or a bare name on PATH made os.stat raise. The compiler is now resolved (file, else PATH); if unresolved the call goes through subprocess.run unchanged. The cache key uses the resolved path. * fix: include the DXC libraries in the compile cache key * fix: never replay output files for a cached failed compile * fix: skip output restore for cached failures and bump DXC cache key version * fix: never cache DXC failures and bypass Wine launchers * tests: preserve DXC missing output directory failures with a warm cache --------- Co-authored-by: Royoo <3230853833@qq.com> --- .github/workflows/windows.yml | 1 + tests/compute_store_check.py | 4 + tests/dxc_cache_check.py | 181 ++++++++++++++++++++++++++ tests/pixel_aot_check.py | 3 +- tools/dxc_cache.py | 236 ++++++++++++++++++++++++++++++++++ 5 files changed, 424 insertions(+), 1 deletion(-) create mode 100644 tests/dxc_cache_check.py create mode 100644 tools/dxc_cache.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 6a37c4bfd..eec590bdf 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -210,6 +210,7 @@ jobs: tests/xmem_attribute_scan_check.py \ tests/xgameruntime_table_check.py \ tests/docs_links_check.py \ + tests/dxc_cache_check.py \ tests/bidi_controls_check.py \ tests/pixel_denorm_vulkan_check.py \ tests/vk_offscreen.py \ diff --git a/tests/compute_store_check.py b/tests/compute_store_check.py index fd6e3e713..964b2447f 100644 --- a/tests/compute_store_check.py +++ b/tests/compute_store_check.py @@ -16,6 +16,10 @@ import shader_profile_audit from pixel_aot import _read_named_container, disassemble from resource_inventory import parts +import dxc_cache + +# Route DXC compiles through the opt-in X2W_DXC_CACHE cache; other subprocess calls are untouched. +subprocess = dxc_cache.with_dxc_cache(subprocess) SENTINEL = 0xc5c5c5c5 INDEXED = [ diff --git a/tests/dxc_cache_check.py b/tests/dxc_cache_check.py new file mode 100644 index 000000000..8ec04d0de --- /dev/null +++ b/tests/dxc_cache_check.py @@ -0,0 +1,181 @@ +"""Check the opt-in DXC compile cache with a fake compiler (no DXC needed).""" +import json +import os +import stat +import subprocess +import sys +import tempfile +from unittest import mock +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import dxc_cache # noqa: E402 + +FAKE = """#!/usr/bin/env python3 +import sys +args = sys.argv[1:] +counter = args[args.index("-Fo") + 1] + ".calls" +open(counter, "a").write("x") +src = open(args[-1], "rb").read() +if b"BROKEN" in src: + sys.stderr.write("error in " + args[-1] + "\\n") + sys.exit(3) +open(args[args.index("-Fo") + 1], "wb").write(b"OBJ:" + src + " ".join(args[:-1]).encode().split(b"-Fo")[0]) +sys.stdout.write("compiled " + args[-1] + "\\n") +""" + + +def fail(message): + raise SystemExit("dxc_cache_check: " + message) + + +class Rig: + def __init__(self, root): + self.root = Path(root) + self.cache = str(self.root / "cache") + self.compiler = str(self.root / "fakedxc") + Path(self.compiler).write_text(FAKE) + os.chmod(self.compiler, os.stat(self.compiler).st_mode | stat.S_IEXEC) + self.n = 0 + + def compile(self, source, extra=(), cache=True, check=False, out=None): + """Compile into a fresh (or given) output path; return (result, object bytes).""" + self.n += 1 + src = self.root / "in.hlsl" + src.write_text(source) + out = out or self.root / ("out%d.cso" % self.n) + if cache: + os.environ[dxc_cache.ENV_VAR] = self.cache + else: + os.environ.pop(dxc_cache.ENV_VAR, None) + result = dxc_cache.run_dxc(self.compiler, ["-T", "cs_6_0", *extra, "-Fo", str(out), str(src)], + check=check, capture_output=True, text=True) + obj = out.read_bytes() if out.exists() else None + return result, obj + + def calls(self): + return sum(len(p.read_text()) for p in self.root.glob("*.calls")) + + +def main(): + with tempfile.TemporaryDirectory() as root: + rig = Rig(root) + first, obj1 = rig.compile("void main(){}") + second, obj2 = rig.compile("void main(){}") + if rig.calls() != 1: + fail("identical compile ran %d real calls, expected 1" % rig.calls()) + if (obj1, first.returncode) != (obj2, second.returncode) or obj1 is None: + fail("cache hit differs from the real result") + if first.stdout.replace("in.hlsl", "") != second.stdout.replace("in.hlsl", "") or "compiled" not in second.stdout: + fail("stdout not replayed") + + # A hit must not create a directory where the real compiler would refuse the output. + missing_output = rig.root / "missing" / "output.cso" + rejected, obj = rig.compile("void main(){}", out=missing_output) + if rejected.returncode == 0 or obj is not None or missing_output.parent.exists(): + fail("cache hit bypassed a missing output directory") + + rig.compile("void main(){ int x; }") + if rig.calls() != 2: + fail("changed source reused a stale entry") + rig.compile("void main(){}", extra=["-Gis"]) + if rig.calls() != 3: + fail("changed argument reused a stale entry") + os.utime(rig.compiler, ns=(1, 1)) + rig.compile("void main(){}") + if rig.calls() != 4: + fail("changed compiler reused a stale entry") + library = Path(rig.compiler).with_name("dxcompiler.dll") + library.write_bytes(b"v1") + rig.compile("void main(){}") + before = rig.calls() + rig.compile("void main(){}") + if rig.calls() != before: + fail("unchanged compiler library missed the cache") + os.utime(library, ns=(1, 1)) + rig.compile("void main(){}") + if rig.calls() != before + 1: + fail("changed compiler library reused a stale entry") + library.write_bytes(b"version two") + rig.compile("void main(){}") + if rig.calls() != before + 2: + fail("resized compiler library reused a stale entry") + + before = rig.calls() + bad1, _ = rig.compile("BROKEN") + bad2, _ = rig.compile("BROKEN") + if rig.calls() != before + 2 or bad1.returncode != 3 or bad2.returncode != 3: + fail("a failing compile must run for real every time with its own return code") + if "in.hlsl" not in bad2.stderr: + fail("failing compile stderr lost") + try: + rig.compile("BROKEN", check=True) + except subprocess.CalledProcessError as error: + if error.returncode != 3: + fail("failure raised the wrong return code") + else: + fail("failure did not raise with check=True") + + missing = Path(root) / "no-such-dir" / "x.cso" + rig.compile("void main(){ /*late dir*/ }", out=missing) + (Path(root) / "no-such-dir").mkdir() + _, late = rig.compile("void main(){ /*late dir*/ }", out=missing) + if late is None: + fail("a failure caused by a missing output directory poisoned the cache") + + cache_dir = Path(rig.cache) + known = set(cache_dir.glob("*.json")) + rig.compile("BROKEN seeded") + if set(cache_dir.glob("*.json")) != known: + fail("a failure was written to the cache") + rig.compile("void main(){ /*seeded*/ }") + (entry,) = set(cache_dir.glob("*.json")) - known + record = json.loads(entry.read_text()) + record["returncode"] = 3 + entry.write_text(json.dumps(record)) + before = rig.calls() + replay, _ = rig.compile("void main(){ /*seeded*/ }") + if replay.returncode != 0 or rig.calls() != before + 1: + fail("a stored failure record was replayed") + + wine = Path(root) / "winedxc" + wine.write_text('#!/bin/bash\nexec wine "$DXC" "$@"\n' + FAKE.split("\n", 1)[1].replace("\n", "\n# ")) + os.chmod(wine, os.stat(wine).st_mode | stat.S_IEXEC) + if dxc_cache._is_wrapper(str(wine)) is not True or dxc_cache._is_wrapper(rig.compiler) is not False: + fail("a Wine launcher must bypass the cache, a plain compiler must not") + + before = rig.calls() + old_path = Path(root) / "legacy_v1.cso" + replay, nothing = rig.compile("BROKEN legacy v1", out=old_path) + if rig.calls() != before + 1 or replay.returncode != 3 or nothing is not None or old_path.exists(): + fail("a record from an older key version was reused") + + before = rig.calls() + rig.compile("void main(){}", cache=False) + rig.compile("void main(){}", cache=False) + if rig.calls() != before + 2: + fail("cache off must make every call real") + + before = rig.calls() + rig.compile('#include "x.hlsli"\nvoid main(){}') + rig.compile('#include "x.hlsli"\nvoid main(){}') + rig.compile("void main(){}", extra=["-I", root]) + rig.compile("void main(){}", extra=["-I", root]) + if rig.calls() != before + 4: + fail("#include or -I compile was cached") + + src = Path(root) / "stub.hlsl" + src.write_text("void main(){}") + os.environ[dxc_cache.ENV_VAR] = str(Path(root) / "cache-stub") + sentinel = subprocess.CompletedProcess(["stub-dxc"], 0, "patched", "") + with mock.patch.object(subprocess, "run", return_value=sentinel) as patched: + got = dxc_cache.run_dxc("stub-dxc", ["-T", "cs_6_0", "-Fo", str(Path(root) / "stub.cso"), str(src)], + check=True) + if got is not sentinel or patched.call_count != 1: + fail("a compiler that is not a file must run uncached through subprocess.run") + os.environ.pop(dxc_cache.ENV_VAR, None) + print("dxc_cache_check: ok") + + +if __name__ == "__main__": + main() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 932f31f93..e11b5faf1 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -17,6 +17,7 @@ from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import dxc_cache import pixel_aot from pixel_aot import ALU, disassemble, native_program @@ -364,7 +365,7 @@ def compile_shader(compiler, source, shader, *, listing=None, mode=F32_DENORM_MO if SPIRV_ARGS is not None: command += SPIRV_ARGS command.append(source) - subprocess.run(command, check=True) + dxc_cache.run_dxc(command[0], command[1:], check=True) if SPIRV_ARGS is not None: subprocess.run(["spirv-val", "--target-env", "vulkan1.2", shader], check=True) diff --git a/tools/dxc_cache.py b/tools/dxc_cache.py new file mode 100644 index 000000000..8a9f36161 --- /dev/null +++ b/tools/dxc_cache.py @@ -0,0 +1,236 @@ +"""Opt-in content-addressed cache for DXC compiles in the Python shader tests. + +Active only when the environment variable X2W_DXC_CACHE names a directory. +Unset, run_dxc is a plain subprocess.run. Anything the cache cannot reason +about (includes, -I, response files, unknown -F outputs, extra run options) +bypasses it, so a cached result is never reused for a different compile. +""" +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +ENV_VAR = "X2W_DXC_CACHE" +OUTPUT_FLAGS = ("-Fo", "-Fc", "-Fh", "-Fre", "-Fd") +SUPPORTED_KWARGS = {"check", "capture_output", "text", "timeout"} +INCLUDE_RE = re.compile(rb"#\s*(include|import)\b|@import") +KEY_VERSION = "2" + + +def _plan(compiler, args): + """Return (key_args, input_path, outputs) or None when the compile is not cacheable.""" + args = [str(a) for a in args] + if not args: + return None + source = args[-1] + if source.startswith("-") or not os.path.isfile(source): + return None + key_args = [] + outputs = {} + for index, arg in enumerate(args[:-1]): + if arg.startswith("@") or arg.startswith("-I") or arg.startswith("-Fi"): + return None + if arg.startswith("-F") and arg not in OUTPUT_FLAGS: + return None + if index > 0 and args[index - 1] in OUTPUT_FLAGS: + continue # output path value, handled with its flag + if arg in OUTPUT_FLAGS: + if index + 1 >= len(args) - 1: + return None + path = args[index + 1] + if path.endswith(("/", "\\")) or os.path.isdir(path) or path in outputs.values() or path == source: + return None + if not os.path.isdir(os.path.dirname(os.path.abspath(path))): + return None + outputs[arg] = path + key_args.append(arg) + key_args.append("<out:%s>" % arg) + elif os.path.exists(arg): + return None # unknown file-like argument + else: + key_args.append(arg) + if not outputs: + return None + return key_args + ["<in>"], source, outputs + + +def _scrub(data, mapping): + for text, token in mapping: + data = data.replace(text.encode(), token.encode()) + return data + + +def _restore(data, mapping): + for text, token in mapping: + data = data.replace(token.encode(), text.encode()) + return data + + +def _store(path, payload): + handle, temp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".tmp-") + try: + with os.fdopen(handle, "wb") as out: + out.write(payload) + os.replace(temp, path) + except BaseException: + if os.path.exists(temp): + os.unlink(temp) + raise + + +def _write_file(path, data): + with open(path, "wb") as out: + out.write(data) + + +def _emit(result_bytes, text, stream): + stream.write(result_bytes.decode(errors="replace") if text else result_bytes) # pragma: no cover + stream.flush() + + +def _passthrough(options, check): + """Keyword arguments exactly as the caller gave them (check only when given).""" + return dict(options, check=check) if check is not None else dict(options) + + +def _resolve(compiler): + """Absolute path of the compiler (a file, else found on PATH), or None when it is neither.""" + name = os.fspath(compiler) + if os.path.isfile(name): + return os.path.abspath(name) + found = shutil.which(name) + return os.path.abspath(found) if found else None + + +def _is_wrapper(resolved): + """True for a shell/script launcher that delegates to a compiler we cannot fingerprint (Wine).""" + try: + with open(resolved, "rb") as handle: + head = handle.read(4096) + except OSError: + return True + return head.startswith(b"#!") and b"wine" in head.lower() + + +COMPILER_LIBRARIES = ("dxcompiler.dll", "dxil.dll", "libdxcompiler.so", "libdxil.so") + + +def _libraries(resolved): + """Name, size and mtime of the DXC libraries next to the compiler (missing ones are skipped).""" + folder = os.path.dirname(resolved) + found = [] + for name in COMPILER_LIBRARIES: + try: + info = os.stat(os.path.join(folder, name)) + except OSError: + continue + found.append([name, info.st_size, info.st_mtime_ns]) + return found + + +def run_dxc(compiler, args, **options): + """Mirror subprocess.run([compiler, *args]) with an optional on-disk cache.""" + command = [compiler, *args] + check = options.pop("check", None) + capture_output = options.get("capture_output", False) + text = options.get("text", False) + timeout = options.get("timeout") + extra = {k: v for k, v in options.items() if k not in SUPPORTED_KWARGS} + cache_dir = os.environ.get(ENV_VAR) + plan = None + resolved = None + if cache_dir and not extra: + resolved = _resolve(compiler) + if resolved is not None and not _is_wrapper(resolved): + plan = _plan(compiler, args) + if plan is None: + return subprocess.run(command, **_passthrough(options, check)) + key_args, source, outputs = plan + with open(source, "rb") as handle: + source_bytes = handle.read() + if INCLUDE_RE.search(source_bytes): + return subprocess.run(command, **_passthrough(options, check)) + try: + info = os.stat(resolved) + except OSError: + return subprocess.run(command, **_passthrough(options, check)) + digest = hashlib.sha256() + digest.update(json.dumps([KEY_VERSION, resolved, info.st_size, info.st_mtime_ns, + _libraries(resolved), key_args]).encode()) + digest.update(b"\0") + digest.update(source_bytes) + entry = os.path.join(cache_dir, digest.hexdigest() + ".json") + mapping = [(source, "<in>")] + [(path, "<out:%s>" % flag) for flag, path in outputs.items()] + mapping.sort(key=lambda item: -len(item[0])) + cached = None + try: + with open(entry, "r", encoding="utf-8") as handle: + cached = json.load(handle) + except (OSError, ValueError): + cached = None + if cached is not None: + try: + files = {flag: bytes.fromhex(cached["files"][flag]) for flag in cached["files"]} + stdout = _restore(bytes.fromhex(cached["stdout"]), mapping) + stderr = _restore(bytes.fromhex(cached["stderr"]), mapping) + returncode = int(cached["returncode"]) + if returncode != 0: + raise ValueError("failures are never replayed") + except (KeyError, ValueError, TypeError): + cached = None + if cached is None: + done = subprocess.run(command, capture_output=True, timeout=timeout) + stdout, stderr, returncode = done.stdout, done.stderr, done.returncode + files = {} + for flag, path in outputs.items(): + if os.path.isfile(path): + with open(path, "rb") as handle: + files[flag] = handle.read() + # Only successes are cached: a failure may be transient (I/O, resources, bad output directory). + if returncode == 0: + os.makedirs(cache_dir, exist_ok=True) + record = {"returncode": returncode, "stdout": _scrub(stdout, mapping).hex(), + "stderr": _scrub(stderr, mapping).hex(), + "files": {flag: data.hex() for flag, data in files.items()}} + _store(entry, json.dumps(record).encode()) + elif returncode == 0: + for flag, data in files.items(): + _write_file(outputs[flag], data) + if capture_output: + out, err = stdout, stderr + if text: + out, err = stdout.decode(errors="replace"), stderr.decode(errors="replace") + else: + out = err = None + sys.stdout.flush() + os.write(1, stdout) if stdout else None + os.write(2, stderr) if stderr else None + result = subprocess.CompletedProcess(command, returncode, out, err) + if check: + result.check_returncode() + return result + + +class _SubprocessProxy: + """Module-like wrapper: subprocess.run goes through run_dxc for DXC-looking compiles only.""" + + def __init__(self, real): + self._real = real + + def __getattr__(self, name): + return getattr(self._real, name) + + def run(self, command, **kwargs): + if (isinstance(command, (list, tuple)) and len(command) > 3 and "-T" in command + and "-Fo" in command and not str(command[0]).startswith("-")): + return run_dxc(command[0], list(command[1:]), **kwargs) + return self._real.run(command, **kwargs) + + +def with_dxc_cache(subprocess_module): + """Return subprocess_module with .run routed through the cache for DXC compiles.""" + return _SubprocessProxy(subprocess_module) From fe4f4696cab1dcfc65b96c0a4884eafd47e46ab3 Mon Sep 17 00:00:00 2001 From: Chad Hyatt <chad@hyatt.page> Date: Wed, 25 Nov 2026 17:01:52 -0600 Subject: [PATCH 222/232] shader: omit unused ordinary integer temporaries after validation (#2479) * shader: omit unused ordinary integer temporaries after validation Retain all used values and validate operands and instruction ordering before elimination. * tests: require live pixel temporaries to precede their consumers --------- Co-authored-by: Royoo <3230853833@qq.com> --- docs/experiments.md | 14 +++++++++ tests/pixel_aot_check.py | 64 ++++++++++++++++++++++++++++++++++++++++ tools/pixel_aot.py | 29 ++++++++++++++++++ 3 files changed, 107 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 1bed7f90b..9be817c20 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -6862,6 +6862,20 @@ record counts have not been remeasured after this change. A local scan of 2,689 compute records accepted 12 records (10 distinct instruction streams). Ten use one-thread groups and fixed addresses. Two use 32- and 64-thread groups and indexed addresses. Tested table bindings used s4 or s5 with descriptor offsets of 0, 32 or 64. The indexed bindings used strides of 4, 8, 12 or 16 bytes, selecting the first compatible profile. On RTX 4060 Laptop (32.0.16.1656) and WARP (10.0.26100.9818), each record compiled to desktop DXIL and dispatched. Each adapter completed 14 full-buffer comparisons with zero mismatches, including two different group counts for both indexed records. +## Unused integer results in emitted pixel HLSL + +After validating a shader, the pixel translator omits unused temporary +declarations created by `s_xor_b32`, `s_lshl_b32`, `v_xor_b32` and +`v_add_nc_u32`. A use in a predicate, address or exported value keeps +its dependencies. The controls in `tests/pixel_aot_check.py` exercise +these uses and the instruction refusal paths. + +Reproduction: + +```powershell +python -B tests/pixel_aot_check.py +``` + ## Vector bit operations in pixel shaders `pixel_aot.py` adds vector bitfield extraction (`v_bfe_u32`, `v_bfe_i32`), diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index e11b5faf1..e89caad63 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -15043,6 +15043,69 @@ def check_nc_integer_lowering(): must_reject(translate_int, uncompressed_export(["v_mov_b32_e32 v18, s45", bad])) +def check_dead_integer_temporaries(): + def declaration(program, instruction, name): + return f"{name}{program.index(instruction)} =" + + def exists(source, name): + return any(name in line for line in source.splitlines()) + + scalar = ("s_xor_b32 s50, s44, s45", "s_lshl_b32 s50, s50, 3") + vector = ("v_xor_b32_e32 v18, s46, v12", "v_add_nc_u32_e32 v18, 1, v18") + + dead = uncompressed_export([*scalar, *vector]) + source = translate_int(dead) + for chain, stem in ((scalar, "salu"), (vector, "alu")): + for instruction in chain: + assert not exists(source, declaration(dead, instruction, stem)), instruction + assert "return uint4(asuint(sample" in source + assert source.count(".Sample(") == 1 + assert "params[" in source + + # The scalar chain reaches the export only via SCC written by the shift. + # The vector chain feeds both a predicate and the outer value of a masked join. + live = uncompressed_export([ + *scalar, + "s_cselect_b32 s51, 1, 0", + "v_mov_b32_e32 v14, s51", + *vector, + "v_cmp_lt_u32_e64 vcc_lo, v18, s47", + "v_mov_b32_e32 v13, v18", + "s_and_saveexec_b64 s[60:61], vcc", + "v_mov_b32_e32 v13, s45", + MASKED_OR_RESTORE, + ]) + source = translate_int(live) + for chain, stem in ((scalar, "salu"), (vector, "alu")): + for instruction in chain: + assert exists(source, declaration(live, instruction, stem)), instruction + scalar_producer, scalar_consumer = (declaration(live, instruction, "salu") for instruction in scalar) + vector_producer, vector_consumer = (declaration(live, instruction, "alu") for instruction in vector) + assert source.index(scalar_producer) < source.index(scalar_consumer) < source.index(f"salu{live.index(scalar[-1])} != 0u") + assert source.index(vector_producer) < source.index(vector_consumer) < source.index(f"asuint(alu{live.index(vector[-1])})") + assert f"alu{live.index(MASKED_OR_RESTORE)}_v13" in source + + # A load with unused data still roots its integer address and remains emitted. + address = "v_add_nc_u32_e32 v20, 1, v12" + title = uncompressed_export([ + address, + "v_mov_b32_e32 v21, s45", + "flat_load_dword v22, v[20:21]", + "s_waitcnt vmcnt(0) lgkmcnt(0)", + ]) + source = translate_title(title) + assert exists(source, declaration(title, address, "alu")) + assert "title_load_dword(uint2(" in source + + # Even a dead result still has to pass operand and wait validation. + unsupported_modifier = "v_add_nc_u32_e64 v18, v12, v13 clamp" + expect_value_error(translate_int, uncompressed_export([unsupported_modifier]), "Unsupported instruction") + must_reject(translate_int, uncompressed_export(["v_add_nc_u32_e32 v18, 1, v200"])) + early = uncompressed_export([]) + early.insert(early.index("s_waitcnt vmcnt(0)"), vector[0]) + must_reject(translate_int, early) + + def check_masked_mov_close_controls(): """Issue #1315: an s_and_saveexec_b64 region may close with the s_mov_b64 copy of its exact saved pair.""" # EXEC inside the region is a subset of the saved entry mask, so both closes restore the same mask and lower @@ -19863,6 +19926,7 @@ def _check_controls_inline(directory): "check_scalar_pair_reads", "check_readfirstlane_controls", "check_flat_scratch_controls", + "check_dead_integer_temporaries", "check_nc_integer_lowering", "check_e64_integer_lowering", "check_carry_out_lowering", diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index cf6e459b4..49994cd4a 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -3494,6 +3494,26 @@ def inline_calls(instructions): *((call_offset + 4 + offset - target, text) for offset, text in instructions[start:end]), *((offset + size, text) for offset, text in instructions[c + 1:start])]) +INTEGER_TEMPORARY = re.compile(r"\b(?:salu|alu)[0-9]+\b") + + +def discard_dead_integer_temporaries(lines, candidates): + """Remove only emitter-marked, single-assignment locals after validation.""" + live = set() + retained = [] + first = next(iter(candidates)) # Emit sites mark candidates in line order. + # Locals are declared before their uses. Scan backwards from the roots + # (all unmarked lines), so skipped declarations do not root their inputs. + for index in range(len(lines) - 1, first - 1, -1): + name = candidates.get(index) + if name is not None and name not in live: + continue + line = lines[index] + retained.append(line) + live.update(INTEGER_TEMPORARY.findall(line)) + retained.reverse() + return lines[:first] + retained + def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor=None, *, texture_offset=0, second_texture_offset=None, integer_export=False, texcoord_components=2, extra_constants=(), @@ -3569,6 +3589,7 @@ def lower(instructions, texture_sgpr, interp_sgpr, sampler, constant_descriptor= # The boolean records whether the quad value depends on interpolated coordinates. quad_values = {"uv.x": True, "uv.y": True} lines = [PREAMBLE] if sampler is None else [SAMPLED_RESOURCES, PREAMBLE] + dead_integer_candidates = {} if constant_descriptor is not None: if constant_descriptor < 0 or constant_descriptor % 4: raise ValueError("Invalid constant descriptor offset") @@ -4644,6 +4665,8 @@ def match(pattern): elif op == "flbit_i32": helpers.add("dpp_ffbh_i32") values = [scalar_u32(t, scalar, pending) for t in tokens] + if mask == "entry" and op in ("xor_b32", "lshl_b32"): + dead_integer_candidates[len(lines)] = f"salu{i}" lines.append(f" uint salu{i} = {template.format(*values)};") if carry: scc = f"({carry.format(*values, r=f'salu{i}')})" @@ -5837,6 +5860,8 @@ def sample_coord(reg): helpers.update(INTEGER_HELPERS.get(op, ())) helpers.update(SAD_HELPERS.get(op, ())) vector[dst] = f"alu{i}" + if op == "xor_b32": + dead_integer_candidates[len(lines)] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({template.format(*args)});") elif m := match(rf"v_cmp_class_f32(_e32|_e64)? {LANE_MASK}, ([^,]+), ([^,]+)"): enc, dst, value, classes = m.groups() @@ -5876,6 +5901,8 @@ def sample_coord(reg): b = int_operand(src1, scalar, vector, pending, sample_dest, signed=False) expression = {"add": f"{a} + {b}", "sub": f"{a} - {b}", "subrev": f"{b} - {a}"}[op] vector[dst] = f"alu{i}" + if line.startswith("v_add_nc_u32"): + dead_integer_candidates[len(lines)] = f"alu{i}" lines.append(f" precise float alu{i} = asfloat({expression});") elif m := match(rf"v_(add|sub|subrev)_co_u32 (v\d+), {LANE_MASK}, ([^,\s]+), ([^,\s]+)"): # 32-bit add or subtract that also writes the unsigned carry or borrow of each lane to a lane @@ -7728,6 +7755,8 @@ def sample_coord(reg): raise ValueError("Expected one gather for the declared view") if not ended or sampled_textures != set(bindings.values()): raise ValueError("Unexpected sample count or missing color export") + if dead_integer_candidates: + lines = discard_dead_integer_temporaries(lines, dead_integer_candidates) if helpers: defs = [body for name, body in SALU_HELPERS.items() if name in helpers] if "div_fmas32" in helpers: From 3b093d4769e3e9a9a16788811e8fda3a235dd396 Mon Sep 17 00:00:00 2001 From: KomaGuy <thedaghan@gmail.com> Date: Thu, 26 Nov 2026 02:02:40 +0300 Subject: [PATCH 223/232] pixel_aot: lower 13 SDWA cvt, frexp_exp, and pkrtz forms (#2571) * pixel_aot: lower 13 SDWA cvt, frexp_exp, and pkrtz forms * tests: align sdwa_cvt_reference flr/rpi NaN and negative-subnormal rules with #1772 --------- Co-authored-by: KomaGuy <265821007+KomaGuy@users.noreply.github.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- CMakeLists.txt | 5 + docs/experiments.md | 17 ++ tests/form_coverage_check.py | 44 ++++- tests/pixel_aot_check.py | 309 ++++++++++++++++++++++++++++++++++- tools/pixel_aot.py | 113 +++++++++++++ 5 files changed, 483 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1835c1584..927193029 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9493,6 +9493,11 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter}) set_tests_properties(pixel_aot_f16_exact_extra_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_exact_extra_${adapter}.txt") + add_test(NAME pixel_aot_sdwa_cvt_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-sdwa-cvt "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(pixel_aot_sdwa_cvt_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77 + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_sdwa_cvt_${adapter}.txt") add_test(NAME pixel_aot_dpp_extra_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-dpp-extra "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 9be817c20..1919948c3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15806,3 +15806,20 @@ Linux controls, `form_coverage_check.check_f16_exact_extra_forms`, and Python re ```powershell ctest --test-dir out/build/release --no-tests=error -R "^startup_gfx2hlsl_cvt_pk_int16_(controls|warp|hardware)$" -V ``` + +## Binary32 conversion, frexp_exp, and packed-RTZ SDWA forms in pixel_aot + +[The pixel shader translator](../tools/pixel_aot.py) adds 13 `SDWA` forms (counted in both `docs/coverage/gfx1013.tsv` and `docs/coverage/rdna2.tsv`): + +- Binary32 to int32 & exponent (5): `v_cvt_i32_f32_sdwa`, `v_cvt_u32_f32_sdwa`, `v_cvt_flr_i32_f32_sdwa`, `v_cvt_rpi_i32_f32_sdwa`, `v_frexp_exp_i32_f32_sdwa` +- Integer / byte / nibble to binary32 (7): `v_cvt_f32_i32_sdwa`, `v_cvt_f32_u32_sdwa`, `v_cvt_f32_ubyte0_sdwa`, `v_cvt_f32_ubyte1_sdwa`, `v_cvt_f32_ubyte2_sdwa`, `v_cvt_f32_ubyte3_sdwa`, `v_cvt_off_f32_i4_sdwa` +- Packed RTZ export conversion (1): `v_cvt_pkrtz_f16_f32_sdwa` + +Float-source forms (`f32->int32`, `frexp_exp`, and `pkrtz`) require whole-dword register sources (`src0_sel:DWORD`, plus `src1_sel:DWORD` and `dst_sel:DWORD` for `pkrtz`) with optional bit-31 `abs`/`neg` modifiers and refuse `sext()`. Integer-source forms (`int->f32`) accept VGPR/SGPR sources with `BYTE_0..3`, `WORD_0..1`, or `DWORD` selection, optional `sext()`, and optional `clamp`, refusing float modifiers. All 13 refuse `UNUSED_SEXT` and `omod`. + +```powershell +python3 tests/pixel_aot_check.py +ctest --preset dev --no-tests=error -R '^(pixel_aot_sdwa_cvt_warp|pixel_aot_sdwa_cvt_hardware|pixel_aot_binary)$' -V +``` + +Linux controls, `form_coverage_check.check_sdwa_cvt_forms`, and Python reference/mutation checks ran locally; LLVM 15 `pixel_aot_binary` round-trips and Windows WARP/hardware D3D12 draws run in CI. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 07d634cbf..6fb84217d 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -392,7 +392,7 @@ def check_shader_records(): sop2_scalar_alu_forms = {("SOP2", op) for op in pixel.SCALAR_ALU_SOP2_OPS} rejected_forms = { "s_or_saveexec_b64", "s_andn2_saveexec_b64", - "v_cvt_pkrtz_f16_f32_sdwa", + "v_rcp_f16_sdwa", "v_cvt_pk_u8_f32", "v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16", "s_lshl0_add_u32", "s_lshl5_add_u32", @@ -516,7 +516,7 @@ def check_shader_records(): for group in ("DPP16", "DPP8") for form in ("v_cvt_flr_i32_f32_dpp", "v_cvt_rpi_i32_f32_dpp", "v_cvt_pkrtz_f16_f32_dpp") } - cvt_f32_excluded = {"v_cvt_flr_i32_f32_sdwa", "v_cvt_rpi_i32_f32_sdwa"} + cvt_f32_excluded = {"v_cvt_norm_i16_f16_sdwa", "v_cvt_norm_u16_f16_sdwa"} for name in ("gfx1013.tsv", "rdna2.tsv"): reference = fc.load_reference(name) assert cvt_f32_int | cvt_dpp_forms <= reference, name @@ -1616,6 +1616,45 @@ def check_f16_exact_extra_forms(): pixel.ACCEPTED.update(saved) +def check_sdwa_cvt_forms(): + """The 13 SDWA conversion, frexp_exp, and packed-RTZ forms count as covered once the translator + accepts their fixtures; unlowered SDWA neighbours stay uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for body in pixel.SDWA_CVT_PROGRAMS.values(): + pixel.translate_int(pixel.uncompressed_export(body)) + pixel.translate(pixel.sdwa_pkrtz_program()) + ops = ( + "v_cvt_i32_f32_sdwa", "v_cvt_u32_f32_sdwa", "v_cvt_flr_i32_f32_sdwa", + "v_cvt_rpi_i32_f32_sdwa", "v_frexp_exp_i32_f32_sdwa", + "v_cvt_f32_i32_sdwa", "v_cvt_f32_u32_sdwa", + "v_cvt_f32_ubyte0_sdwa", "v_cvt_f32_ubyte1_sdwa", + "v_cvt_f32_ubyte2_sdwa", "v_cvt_f32_ubyte3_sdwa", + "v_cvt_off_f32_i4_sdwa", "v_cvt_pkrtz_f16_f32_sdwa", + ) + forms = {("SDWA", op) for op in ops} + assert len(forms) == 13 + neighbours = { + ("SDWA", "v_cndmask_b32_sdwa"), ("SDWA", "v_rcp_f16_sdwa"), + ("SDWA", "v_sqrt_f16_sdwa"), ("SDWA", "v_cvt_norm_i16_f16_sdwa"), + ("SDWA", "v_cvt_norm_u16_f16_sdwa"), + } + for name in ("gfx1013.tsv", "rdna2.tsv"): + reference = fc.load_reference(name) + assert forms <= reference, (name, sorted(forms - reference)) + assert neighbours <= reference, (name, sorted(neighbours - reference)) + covered = fc.gfx_forms(pixel.ACCEPTED, reference) + assert forms <= covered, (name, sorted(forms - covered)) + assert not (neighbours & covered), (name, sorted(neighbours & covered)) + stripped = pixel.ACCEPTED - {"v_cvt_pkrtz_f16_f32_sdwa"} + assert ("SDWA", "v_cvt_pkrtz_f16_f32_sdwa") not in fc.gfx_forms(stripped, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + if __name__ == "__main__": check_denominators() check_example() @@ -1641,6 +1680,7 @@ def check_f16_exact_extra_forms(): check_sdwa_f16_forms() check_sdwa_int_extra_forms() check_f16_exact_extra_forms() + check_sdwa_cvt_forms() check_swap_coverage() check_pk_fmac_coverage() check_sdwa_cmp_coverage() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index e89caad63..2c1098356 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -11023,7 +11023,7 @@ def check_sdwa_f16_controls(): (proven_pair, f"v_sqrt_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_rcp_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), (proven_pair, f"v_cvt_norm_i16_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), - (proven_pair, f"v_cvt_pkrtz_f16_f32_sdwa v24, v20, v21 {sdwa2}", "Unsupported instruction"), + (proven_pair, f"v_cvt_norm_u16_f16_sdwa v24, v20 {sdwa1}WORD_0", "Unsupported instruction"), ): expect_value_error(translate_f16, uncompressed_export([*prefix, bad]), message) # Scheduling: pending scalar load, outstanding sample, and non-entry EXEC mask must refuse. @@ -11591,6 +11591,305 @@ def check_f16_exact_extra_draw(directory, compiler, renderer, backend): return 0 +# SDWA binary32 conversion, frexp_exp, and packed-RTZ fixtures covering 13 SDWA forms: +# f32->int32 (cvt_{i32,u32,flr_i32,rpi_i32}_f32_sdwa, frexp_exp_i32_f32_sdwa), +# int->f32 (cvt_f32_{i32,u32,ubyte0..3}_sdwa, cvt_off_f32_i4_sdwa), and v_cvt_pkrtz_f16_f32_sdwa. +SDWA_CVT_PROGRAMS = { + "f32_to_int": [ + "v_mov_b32_e32 v18, s45", + # ch0: cvt_i32_f32(-s44) + "v_cvt_i32_f32_sdwa v12, -s44 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", + # ch1: cvt_u32_f32(|v18|) + "v_cvt_u32_f32_sdwa v13, |v18| dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", + # ch2: cvt_flr_i32_f32(s46) in WORD_0, cvt_rpi_i32_f32(-s47) in WORD_1 with UNUSED_PRESERVE. + "v_cvt_flr_i32_f32_sdwa v14, s46 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_cvt_rpi_i32_f32_sdwa v14, -s47 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", + # ch3: frexp_exp(-|s44|) in WORD_0, frexp_exp(s46) in WORD_1 with UNUSED_PRESERVE. + "v_frexp_exp_i32_f32_sdwa v15, -|s44| dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_frexp_exp_i32_f32_sdwa v15, s46 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", + ], + "int_to_f32": [ + "v_mov_b32_e32 v18, s45", + # ch0: float(sext(BYTE_1(s44))) + "v_cvt_f32_i32_sdwa v12, sext(s44) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1", + # ch1: float(WORD_1(v18)) + "v_cvt_f32_u32_sdwa v13, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + # ch2: off_i4(BYTE_2(s46)) = signed_nibble(BYTE_2(s46) & 0xf) * 0.0625 + "v_cvt_off_f32_i4_sdwa v14, s46 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2", + # ch3: saturate(float(sext(BYTE_0(s47)))) + "v_cvt_f32_i32_sdwa v15, sext(s47) clamp dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", + ], + "ubyte_to_f32": [ + "v_mov_b32_e32 v18, s45", + "v_cvt_f32_ubyte0_sdwa v12, s44 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_f32_ubyte1_sdwa v13, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_f32_ubyte2_sdwa v14, sext(s46) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", + "v_cvt_f32_ubyte3_sdwa v15, s47 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", + ], +} +SDWA_CVT_ROWS = { + "f32_to_int": ( + # Row 0: s44=3.75, s45=-5.5, s46=-1.25 (flr=-2, exp=1), s47=-2.5 (-s47=+2.5 -> rpi=3). + (0x40700000, 0xc0b00000, 0xbfa00000, 0xc0200000), + # Row 1: s44=-6.0 (-s44=6, exp=3), s45=0.0, s46=0.25 (flr=0, exp=-1), s47=0.5 (-s47=-0.5 -> rpi=0). + (0xc0c00000, 0x00000000, 0x3e800000, 0x3f000000), + # Row 2: saturation & special values: s44=+Inf (-s44=-Inf -> INT_MIN, exp=0), s45=-Inf (|-Inf|->UINT_MAX), + # s46=NaN (flr=0x7fffffff per #1772, exp=0), s47=1.75 (-s47=-1.75 -> rpi=-2). + (0x7f800000, 0xff800000, 0x7fc00001, 0x3fe00000), + ), + "int_to_f32": ( + # Row 0: BYTE_1(s44)=0x80 (-128.0), WORD_1(s45)=0x8001 (32769.0), BYTE_2(s46)=0x08 (-0.5), sext(BYTE_0(s47))=-5 -> clamp 0.0. + (0x00008000, 0x80010000, 0x00080000, 0x000000fb), + # Row 1: BYTE_1(s44)=0x7f (127.0), WORD_1(s45)=0xffff (65535.0), BYTE_2(s46)=0x07 (0.4375), sext(BYTE_0(s47))=42 -> clamp 1.0. + (0x00007f00, 0xffff1234, 0x00070000, 0x0000002a), + # Row 2: BYTE_1(s44)=0xff (-1.0), WORD_1(s45)=0x0000 (0.0), BYTE_2(s46)=0x0f (-0.0625), sext(BYTE_0(s47))=0 -> clamp 0.0. + (0x0000ff00, 0x0000ffff, 0x000f0000, 0x00000000), + ), + "ubyte_to_f32": ( + (0x12345678, 0xab00cdef, 0x00000080, 0xfe112233), + (0x00ff0000, 0x01000000, 0x0000007f, 0x00ffeedd), + (0xdeadbeef, 0x42000000, 0x123456ff, 0x7f000000), + ), +} +SDWA_CVT_MUTATIONS = { + "f32_to_int": ( + ("v_cvt_i32_f32_sdwa v12, -s44", "v_cvt_i32_f32_sdwa v12, s44"), + ("v_cvt_u32_f32_sdwa v13, |v18|", "v_cvt_u32_f32_sdwa v13, v18"), + ("v_cvt_flr_i32_f32_sdwa v14, s46", "v_cvt_i32_f32_sdwa v14, s46"), + ("v_cvt_rpi_i32_f32_sdwa v14, -s47 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_cvt_rpi_i32_f32_sdwa v14, -s47 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ("v_frexp_exp_i32_f32_sdwa v15, s46 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE", + "v_frexp_exp_i32_f32_sdwa v15, s46 dst_sel:WORD_1 dst_unused:UNUSED_PAD"), + ), + "int_to_f32": ( + ("v_cvt_f32_i32_sdwa v12, sext(s44)", "v_cvt_f32_i32_sdwa v12, s44"), + ("v_cvt_f32_u32_sdwa v13, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", + "v_cvt_f32_u32_sdwa v13, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"), + ("v_cvt_off_f32_i4_sdwa v14, s46", "v_cvt_f32_ubyte0_sdwa v14, s46"), + ("v_cvt_f32_i32_sdwa v15, sext(s47) clamp", "v_cvt_f32_i32_sdwa v15, sext(s47)"), + ), + "ubyte_to_f32": ( + ("v_cvt_f32_ubyte0_sdwa v12, s44", "v_cvt_f32_ubyte1_sdwa v12, s44"), + ("v_cvt_f32_ubyte1_sdwa v13, v18", "v_cvt_f32_ubyte0_sdwa v13, v18"), + ("v_cvt_f32_ubyte2_sdwa v14, sext(s46)", "v_cvt_f32_ubyte2_sdwa v14, s46"), + ("v_cvt_f32_ubyte3_sdwa v15, s47", "v_cvt_f32_ubyte2_sdwa v15, s47"), + ), +} + + +def sdwa_pkrtz_program(): + """Compressed-export program exercising v_cvt_pkrtz_f16_f32_sdwa with modifiers and UNUSED_PAD/PRESERVE.""" + program = with_constants(["v_mov_b32_e32 v18, s45", "v_mov_b32_e32 v19, s47"]) + i16 = program.index("v_cvt_pkrtz_f16_f32_e32 v16, v12, v13") + i17 = program.index("v_cvt_pkrtz_f16_f32_e32 v17, v14, v15") + program[i16] = "v_cvt_pkrtz_f16_f32_sdwa v16, -s44, |v18| dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD" + program[i17] = "v_cvt_pkrtz_f16_f32_sdwa v17, -|s46|, v19 dst_sel:DWORD dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:DWORD" + return program + + +def sdwa_cvt_reference(group, row): + """Independent Python reference 32-bit words for SDWA_CVT_PROGRAMS.""" + a, b, c, d = row + f32 = lambda w: struct.unpack("<f", struct.pack("<I", w & 0xffffffff))[0] + u32_f = lambda x: struct.unpack("<I", struct.pack("<f", x))[0] + sel_u32 = lambda w, off, wid, sx: ( + ((w >> off) & ((1 << wid) - 1)) | ((~((1 << wid) - 1) & 0xffffffff) if (sx and ((w >> (off + wid - 1)) & 1)) else 0) + ) & 0xffffffff + def cvt_i32(w, mode): + w &= 0xffffffff + if mode == "flr" and 0x80000000 < w < 0x80800000: + return 0xffffffff + x = f32(w) + if math.isnan(x): + # Per #1772, v_cvt_flr_i32_f32 and v_cvt_rpi_i32_f32 map NaN to 0x7fffffff + sign bit; + # v_cvt_i32_f32 maps NaN to 0. + return ((0x7fffffff + (w >> 31)) & 0xffffffff) if mode in ("flr", "rpi") else 0 + if x >= 2147483648.0: + return 0x7fffffff + if x <= -2147483648.0: + return 0x80000000 + if mode == "trunc": + v = int(math.trunc(x)) + elif mode == "flr": + v = int(math.floor(x)) + else: + v = int(math.floor(x + 0.5)) + return max(-0x80000000, min(0x7fffffff, v)) & 0xffffffff + def cvt_u32(w): + x = f32(w) + if math.isnan(x) or x <= 0.0: + return 0 + if x >= 4294967296.0: + return 0xffffffff + return int(math.trunc(x)) & 0xffffffff + def frexp_exp(w): + exp = (w >> 23) & 0xff + mant = w & 0x7fffff + if exp == 0xff or (exp == 0 and mant == 0): + return 0 + if exp == 0: + return (-126 - (23 - (mant.bit_length() - 1))) & 0xffffffff + return (exp - 126) & 0xffffffff + if group == "f32_to_int": + ch0 = cvt_i32(a ^ 0x80000000, "trunc") + ch1 = cvt_u32(b & 0x7fffffff) + ch2 = (cvt_i32(c, "flr") & 0xffff) | ((cvt_i32(d ^ 0x80000000, "rpi") & 0xffff) << 16) + ch3 = (frexp_exp((a & 0x7fffffff) ^ 0x80000000) & 0xffff) | ((frexp_exp(c) & 0xffff) << 16) + return (ch0, ch1, ch2, ch3) + if group == "int_to_f32": + s0 = sel_u32(a, 8, 8, True) + ch0 = u32_f(float(s0 - 0x100000000 if s0 & 0x80000000 else s0)) + ch1 = u32_f(float(sel_u32(b, 16, 16, False))) + n = sel_u32(c, 16, 8, False) & 0xf + ch2 = u32_f(float(n - 16 if n & 8 else n) * 0.0625) + s3 = sel_u32(d, 0, 8, True) + v3 = float(s3 - 0x100000000 if s3 & 0x80000000 else s3) + ch3 = u32_f(min(max(v3, 0.0), 1.0)) + return (ch0, ch1, ch2, ch3) + # ubyte_to_f32: + ch0 = u32_f(float(sel_u32(a, 16, 16, False) & 0xff)) + ch1 = u32_f(float((sel_u32(b, 16, 16, False) >> 8) & 0xff)) + ch2 = u32_f(float((sel_u32(c, 0, 8, True) >> 16) & 0xff)) + ch3 = u32_f(float((d >> 24) & 0xff)) + return (ch0, ch1, ch2, ch3) + + +def check_sdwa_cvt_controls(): + """Static lowering and refusal controls for the 13 SDWA conversion, frexp_exp, and pkrtz forms.""" + for name, body in SDWA_CVT_PROGRAMS.items(): + prog = uncompressed_export(body) + hlsl = translate_int(prog) + if name == "f32_to_int": + for helper in ("cvt_i32_f32(", "cvt_u32_f32(", "cvt_flr_i32_f32(", "cvt_rpi_i32_f32(", "dpp_frexp_exp_i32_f32("): + assert helper in hlsl, (helper, hlsl) + for old, new in SDWA_CVT_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + assert translate_int(mutated) != hlsl, (name, old, new) + pkrtz_prog = sdwa_pkrtz_program() + pkrtz_hlsl = translate(pkrtz_prog) + assert "export16(" in pkrtz_hlsl + # v_cvt_pkrtz_f16_f32_sdwa is explicitly RTZ and stays exempt from HALF_RTZ refusal. + assert translate([HALF_RTZ, *pkrtz_prog]) == translate(["s_nop 0", *pkrtz_prog]) + # abs(reg) spelling accepted on float-source SDWA forms, and sub-dword dst_sel works on int->f32. + translate_int(uncompressed_export([ + "v_mov_b32_e32 v18, s45", + "v_cvt_i32_f32_sdwa v12, abs(v18) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD", + "v_cvt_f32_u32_sdwa v13, v18 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_0", + ])) + sdwa1 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + sdwa2 = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD" + for bad, message in ( + # f32->int / frexp_exp: non-DWORD src0_sel, sext, UNUSED_SEXT, clamp/omod, untracked preserve, out-of-range dst. + (f"v_cvt_i32_f32_sdwa v12, s44 {sdwa1}WORD_0", "v_cvt_i32_f32_sdwa requires src0_sel:DWORD, got WORD_0"), + (f"v_frexp_exp_i32_f32_sdwa v12, s44 {sdwa1}BYTE_0", "v_frexp_exp_i32_f32_sdwa requires src0_sel:DWORD, got BYTE_0"), + (f"v_cvt_u32_f32_sdwa v12, sext(s44) {sdwa1}DWORD", "Unsupported float SDWA source modifier: sext(s44)"), + ("v_cvt_flr_i32_f32_sdwa v12, s44 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:DWORD", "UNUSED_SEXT is not lowered"), + ("v_cvt_rpi_i32_f32_sdwa v20, s44 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", + "UNUSED_PRESERVE needs a tracked numeric destination"), + (f"v_cvt_i32_f32_sdwa v12, s44 clamp {sdwa1}DWORD", "Unsupported instruction"), + (f"v_cvt_i32_f32_sdwa v12, s44 mul:2 {sdwa1}DWORD", "Unsupported instruction"), + (f"v_cvt_i32_f32_sdwa v256, s44 {sdwa1}DWORD", "Invalid conversion SDWA operation"), + # int->f32: float modifiers refused, UNUSED_SEXT, omod, unbalanced sext, untracked preserve. + (f"v_cvt_f32_i32_sdwa v12, -s44 {sdwa1}DWORD", "Source modifiers are not allowed on -s44"), + (f"v_cvt_f32_u32_sdwa v12, |s44| {sdwa1}DWORD", "Source modifiers are not allowed on |s44|"), + (f"v_cvt_f32_ubyte0_sdwa v12, abs(s44) {sdwa1}DWORD", "Source modifiers are not allowed on abs(s44)"), + (f"v_cvt_off_f32_i4_sdwa v12, sext(s44 {sdwa1}BYTE_0", "Unsupported SDWA integer operand"), + ("v_cvt_f32_u32_sdwa v12, s44 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:DWORD", "UNUSED_SEXT is not lowered"), + ("v_cvt_f32_i32_sdwa v20, s44 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", + "UNUSED_PRESERVE needs a tracked numeric destination"), + (f"v_cvt_f32_u32_sdwa v12, s44 mul:2 {sdwa1}DWORD", "Unsupported instruction"), + # pkrtz: non-DWORD dst_sel or src_sel, UNUSED_SEXT, sext(), clamp/omod. + ("v_cvt_pkrtz_f16_f32_sdwa v12, s44, s45 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD", + "v_cvt_pkrtz_f16_f32_sdwa requires dst_sel:DWORD, got WORD_0"), + ("v_cvt_pkrtz_f16_f32_sdwa v12, s44, s45 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:DWORD", + "v_cvt_pkrtz_f16_f32_sdwa requires whole-dword sources"), + ("v_cvt_pkrtz_f16_f32_sdwa v12, s44, s45 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:DWORD src1_sel:DWORD", + "UNUSED_SEXT is not lowered"), + (f"v_cvt_pkrtz_f16_f32_sdwa v12, sext(s44), s45 {sdwa2}", "Unsupported float SDWA source modifier: sext(s44)"), + (f"v_cvt_pkrtz_f16_f32_sdwa v12, s44, s45 clamp {sdwa2}", "Unsupported instruction"), + ): + expect_value_error(translate_int, uncompressed_export([bad]), message) + # Scheduling: pending scalar load, outstanding sample, and non-entry EXEC mask must refuse. + base = uncompressed_export([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + expect_value_error(translate_int, base[:load + 1] + [f"v_cvt_i32_f32_sdwa v24, s44 {sdwa1}DWORD"] + base[load + 1:], + "Constant read before load completion") + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(translate_int, base[:sample + 1] + [f"v_cvt_f32_u32_sdwa v12, s44 {sdwa1}DWORD"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(translate_int, base[:sample + 1] + [f"v_cvt_f32_u32_sdwa v24, v12 {sdwa1}DWORD"] + base[sample + 1:], + "Sample used before vmcnt wait") + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(translate_int, base[:masked] + [f"v_cvt_i32_f32_sdwa v24, s44 {sdwa1}DWORD"] + base[masked:], + "Invalid conversion SDWA operation") + + +def check_sdwa_cvt_draw(directory, compiler, renderer, backend): + check_sdwa_cvt_controls() + # 1. Integer-export draws for f32->int32 / frexp_exp, int->f32, and ubyte0..3->f32 SDWA. + for name, body in SDWA_CVT_PROGRAMS.items(): + prog = uncompressed_export(body) + src_path = directory / f"sdwa_cvt_{name}.hlsl" + cso_path = directory / f"sdwa_cvt_{name}.cso" + src_path.write_text(translate_int(prog), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + cases = [] + for idx, row in enumerate(SDWA_CVT_ROWS[name]): + expected = sdwa_cvt_reference(name, row) + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *row) + case_path = directory / f"sdwa_cvt_{name}_{idx}.case" + case_path.write_bytes(bytes(constants) + struct.pack("<4I", *expected) * 64 + b"\x01") + cases.append((case_path, "pass")) + run_pixel_batch(renderer, backend, cso_path, cases) + case_paths = [p for p, _ in cases] + for old, new in SDWA_CVT_MUTATIONS[name]: + mutated = [line.replace(old, new) for line in prog] + assert mutated != prog, (name, old) + src_path.write_text(translate_int(mutated), encoding="ascii") + compile_shader(compiler, src_path, cso_path) + statuses, _ = run_pixel_batch_statuses(renderer, backend, cso_path, case_paths) + print(f"sdwa_cvt {name} mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"sdwa_cvt {name} mutation {old!r} -> {new!r} escaped detection") + # 2. Compressed float-export draw for v_cvt_pkrtz_f16_f32_sdwa (including RTZ tie discrimination). + pkrtz_prog = sdwa_pkrtz_program() + pkrtz_src = directory / "sdwa_cvt_pkrtz.hlsl" + pkrtz_cso = directory / "sdwa_cvt_pkrtz.cso" + pkrtz_src.write_text(translate(pkrtz_prog), encoding="ascii") + compile_shader(compiler, pkrtz_src, pkrtz_cso) + pkrtz_rows = ( + ((0x3fc00000, 0xc0100000, 0x40600000, 0x40800000), (-1.5, 2.25, -3.5, 4.0)), + ((0x3f803000, 0xbf803000, 0x40000000, 0xc0a00000), (-1.0009765625, 1.0009765625, -2.0, -5.0)), + ) + pkrtz_cases = [] + for idx, (words, expected) in enumerate(pkrtz_rows): + for val in expected: + assert half_rtz(val) == val, val + constants = bytearray(256) + struct.pack_into("<4I", constants, 12, *words) + case_path = directory / f"sdwa_cvt_pkrtz_{idx}.case" + case_path.write_bytes(bytes(constants) + struct.pack("<4f", *expected) * 64) + pkrtz_cases.append((case_path, "pass")) + run_pixel_batch(renderer, backend, pkrtz_cso, pkrtz_cases) + pkrtz_paths = [p for p, _ in pkrtz_cases] + for old, new in ( + ("v_cvt_pkrtz_f16_f32_sdwa v16, -s44, |v18|", "v_cvt_pkrtz_f16_f32_sdwa v16, s44, |v18|"), + ("v_cvt_pkrtz_f16_f32_sdwa v16, -s44, |v18|", "v_cvt_pkrtz_f16_f32_sdwa v16, -s44, v18"), + ("v_cvt_pkrtz_f16_f32_sdwa v17, -|s46|, v19", "v_cvt_pkrtz_f16_f32_sdwa v17, |s46|, v19"), + ): + mutated = [line.replace(old, new) for line in pkrtz_prog] + assert mutated != pkrtz_prog, old + pkrtz_src.write_text(translate(mutated), encoding="ascii") + compile_shader(compiler, pkrtz_src, pkrtz_cso) + statuses, _ = run_pixel_batch_statuses(renderer, backend, pkrtz_cso, pkrtz_paths) + print(f"sdwa_cvt pkrtz mutation {old!r} -> {new!r}: statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"sdwa_cvt pkrtz mutation {old!r} -> {new!r} escaped detection") + return 0 + + # Quad-local DPP16 and DPP8 integer/bitwise/shift/bit-scan/saturate fixture covering 24 VOP1/VOP2 DPP forms. # Derives integer quad lane ID {0, 1, 2, 3} from interpolated uv.x/uv.y (v8/v9), verifies quad # swizzles across lanes, folds all 23 ops into a 32-bit accumulator, and exports all 4 bytes as @@ -19892,6 +20191,7 @@ def _check_controls_inline(directory): "check_sdwa_f16_controls", "check_sdwa_int_extra_controls", "check_f16_exact_extra_controls", + "check_sdwa_cvt_controls", "check_smem_pointer_controls", "check_masked_controls", "check_masked_mov_close_controls", @@ -20546,6 +20846,8 @@ def check_binary(directory, assembler, objcopy, library): fixtures.append((uncompressed_export(SDWA_F16_CVT_F32_BODY), translate_f16)) fixtures.extend((uncompressed_export(body), translate_int) for body in SDWA_INT_EXTRA_PROGRAMS.values()) fixtures.extend((uncompressed_export(body), translate_f16) for body in F16_EXACT_EXTRA_PROGRAMS.values()) + fixtures.extend((uncompressed_export(body), translate_int) for body in SDWA_CVT_PROGRAMS.values()) + fixtures.append((sdwa_pkrtz_program(), translate)) fixtures.extend((bit_program(op), translate) for op in BIT_OPERATIONS) fixtures.extend((program, function) for _, program, function, _ in e64_spelling_programs()) fixtures.append((vop1_nop_program(), translate)) @@ -27292,7 +27594,7 @@ def main(): "draw-region-body", "draw-region-waits", "draw-region-scalar-alu", "draw-region-scalar-load", "draw-div-fmas", "draw-cmp64", "draw-cmp-f64", "draw-shift64", "draw-f16-arith", "draw-f16-round", "draw-f16-fmac-ldexp", "draw-f16-cvt-int16", "draw-f16-to-int16", "draw-flat-scratch", "draw-smem-pointers", "draw-sopk-hwreg", "draw-sopp-round-mode", - "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-dpp-extra", "draw-pk-fmac"): + "draw-dpp-cvt", "draw-dpp-movrel", "draw-plain-movrel", "draw-swaprel", "draw-sdwa-movrel", "draw-smovrel", "draw-dpp-f16", "draw-sdwa-f16", "draw-sdwa-int-extra", "draw-f16-exact-extra", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, "draw-dpp-cvt": check_dpp_cvt_draw, @@ -27357,7 +27659,8 @@ def main(): "draw-dpp-f16": check_dpp_f16_draw, "draw-sdwa-f16": check_sdwa_f16_draw, "draw-sdwa-int-extra": check_sdwa_int_extra_draw, - "draw-f16-exact-extra": check_f16_exact_extra_draw}[mode] + "draw-f16-exact-extra": check_f16_exact_extra_draw, + "draw-sdwa-cvt": check_sdwa_cvt_draw}[mode] return draw(directory, *args) except subprocess.CalledProcessError as error: if error.returncode == 77 and str(error.cmd[0]) == str(args[1]): diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 49994cd4a..20d01a27e 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -3127,6 +3127,24 @@ def sdwa_cmp_bits(token, sel, sext, scalar, vector, pending, sample_dest, *, f16 r" dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" r" dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE)" r" src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD) src1_sel:(BYTE_[0-3]|WORD_[01]|DWORD)") +# SDWA binary32-to-int32 conversions and frexp_exp (float src0 with src0_sel:DWORD -> int32 result). +SDWA_CVT_F32_TO_INT = { + "cvt_i32_f32": "cvt_i32_f32", + "cvt_u32_f32": "cvt_u32_f32", + "cvt_flr_i32_f32": "cvt_flr_i32_f32", + "cvt_rpi_i32_f32": "cvt_rpi_i32_f32", + "frexp_exp_i32_f32": "dpp_frexp_exp_i32_f32", +} +# SDWA integer-to-binary32 conversions (integer src0 with optional sext() and any src0_sel, optional clamp). +SDWA_CVT_INT_TO_F32 = { + "cvt_f32_i32": "float(asint({0}))", + "cvt_f32_u32": "float({0})", + "cvt_f32_ubyte0": "float(({0} >> 0u) & 0xffu)", + "cvt_f32_ubyte1": "float(({0} >> 8u) & 0xffu)", + "cvt_f32_ubyte2": "float(({0} >> 16u) & 0xffu)", + "cvt_f32_ubyte3": "float(({0} >> 24u) & 0xffu)", + "cvt_off_f32_i4": "(float(asint({0} << 28u) >> 28) * 0.0625f)", +} SDWA_F16_SRC = re.compile(r"(-?)(?:abs\(([vs]\d+)\)|\|([vs]\d+)\||([vs]\d+))") SDWA_F16_UNARY_OPERANDS = re.compile( r"(v\d+), ([^,\s]+) dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD)" @@ -5560,6 +5578,101 @@ def sample_coord(reg): lines.append(f" precise float alu{i} = asfloat({placed});") scalar["vcc"] = ("condition", f"cmp{i}", 0, 1) vector[dst] = f"alu{i}" + elif m := match(rf"v_({'|'.join(SDWA_CVT_F32_TO_INT)})_sdwa (v\d+), ([^,\s]+) dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD) dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD)"): + # SDWA binary32-to-int32 conversions and frexp_exp: whole-dword float register source with + # optional bit-31 abs/neg modifiers, reusing the e64/DPP IEEE-754 bit helpers and SDWA dest placement. + op, dst, src0, dst_sel, unused, sel0 = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid conversion SDWA operation") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + if unused == "UNUSED_SEXT": + raise ValueError("UNUSED_SEXT is not lowered") + if sel0 != "DWORD": + raise ValueError(f"v_{op}_sdwa requires src0_sel:DWORD, got {sel0}") + if src0.startswith("sext("): + raise ValueError(f"Unsupported float SDWA source modifier: {src0}") + sm = SDWA_F16_SRC.fullmatch(src0) + if not sm: + raise ValueError(f"Unsupported float SDWA operand: {src0}") + neg, abs_fn, abs_bars, plain = sm.groups() + reg = abs_fn or abs_bars or plain + if not 0 <= int(reg[1:]) <= (255 if reg[0] == "v" else 105): + raise ValueError(f"Register out of range: {reg}") + val = fp_operand(reg, scalar, vector, pending, sample_dest) + bits = f"asuint({val})" + if abs_fn or abs_bars: + bits = f"({bits} & 0x7fffffffu)" + if neg: + bits = f"({bits} ^ 0x80000000u)" + helper = SDWA_CVT_F32_TO_INT[op] + helpers.add(helper) + placed = sdwa_dest(f"{helper}({bits})", dst_sel, unused, vector.get(dst)) + vector[dst] = f"alu{i}" + lines.append(f" precise float alu{i} = asfloat({placed});") + elif m := match(rf"v_({'|'.join(SDWA_CVT_INT_TO_F32)})_sdwa (v\d+), ([^,\s]+)( clamp)? dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD) dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD)"): + # SDWA integer-to-binary32 conversions (i32, u32, ubyte0..3, off_i4): integer register source + # with optional sext() and any SDWA selection, optional clamp, and SDWA destination placement. + op, dst, src0, clamp, dst_sel, unused, sel0 = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid conversion SDWA operation") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + if unused == "UNUSED_SEXT": + raise ValueError("UNUSED_SEXT is not lowered") + if src0.startswith(("-", "|", "abs(")): + raise ValueError(f"Source modifiers are not allowed on {src0}") + sm = re.fullmatch(SDWA_INT_SOURCE, src0) + if not sm or bool(sm.group(1)) != bool(sm.group(3)): + raise ValueError(f"Unsupported SDWA integer operand: {src0}") + is_sext, reg = bool(sm.group(1)), sm.group(2) + if not 0 <= int(reg[1:]) <= (255 if reg[0] == "v" else 105): + raise ValueError(f"Register out of range: {reg}") + selected = sdwa_source(int_operand(reg, scalar, vector, pending, sample_dest, signed=False), sel0, is_sext) + lines.append(f" uint sc{i} = {selected};") + expr = SDWA_CVT_INT_TO_F32[op].format(f"sc{i}") + if clamp: + expr = f"saturate({expr})" + if dst_sel != "DWORD": + expr = f"asfloat({sdwa_dest(f'asuint({expr})', dst_sel, unused, vector.get(dst) if unused == 'UNUSED_PRESERVE' else None)})" + vector[dst] = f"alu{i}" + lines.append(f" precise float alu{i} = {expr};") + elif m := match(r"v_cvt_pkrtz_f16_f32_sdwa (v\d+), ([^,\s]+), ([^,\s]+) dst_sel:(BYTE_[0-3]|WORD_[01]|DWORD) dst_unused:(UNUSED_PAD|UNUSED_SEXT|UNUSED_PRESERVE) src0_sel:(BYTE_[0-3]|WORD_[01]|DWORD) src1_sel:(BYTE_[0-3]|WORD_[01]|DWORD)"): + # SDWA compressed-export pack: whole-dword binary32 float register sources with optional bit-31 + # abs/neg modifiers and whole-dword destination, producing the same (lo, hi) compressed-export pair + # as v_cvt_pkrtz_f16_f32_e32 and v_cvt_pkrtz_f16_f32_dpp. + dst, src0, src1, dst_sel, unused, sel0, sel1 = m.groups() + if mask != "entry" or not 0 <= int(dst[1:]) <= 255: + raise ValueError("Invalid pack SDWA operation") + if dst in sample_dest: + raise ValueError("Write overlaps an outstanding sample") + if unused == "UNUSED_SEXT": + raise ValueError("UNUSED_SEXT is not lowered") + if dst_sel != "DWORD": + raise ValueError(f"v_cvt_pkrtz_f16_f32_sdwa requires dst_sel:DWORD, got {dst_sel}") + if sel0 != "DWORD" or sel1 != "DWORD": + raise ValueError("v_cvt_pkrtz_f16_f32_sdwa requires whole-dword sources") + pair_bits = [] + for tok in (src0, src1): + if tok.startswith("sext("): + raise ValueError(f"Unsupported float SDWA source modifier: {tok}") + sm = SDWA_F16_SRC.fullmatch(tok) + if not sm: + raise ValueError(f"Unsupported float SDWA operand: {tok}") + neg, abs_fn, abs_bars, plain = sm.groups() + reg = abs_fn or abs_bars or plain + if not 0 <= int(reg[1:]) <= (255 if reg[0] == "v" else 105): + raise ValueError(f"Register out of range: {reg}") + val = fp_operand(reg, scalar, vector, pending, sample_dest) + bits = f"asuint({val})" + if abs_fn or abs_bars: + bits = f"({bits} & 0x7fffffffu)" + if neg: + bits = f"({bits} ^ 0x80000000u)" + pair_bits.append(bits) + lines.append(f" precise float alu{i}_lo = asfloat({pair_bits[0]});") + lines.append(f" precise float alu{i}_hi = asfloat({pair_bits[1]});") + vector[dst] = (f"alu{i}_lo", f"alu{i}_hi") elif m := match(r"v_cvt_f16_f32_sdwa (.+)"): # SDWA binary32-to-binary16 conversion under the declared entry profile (half_denorm="preserve" # and HW_REG_MODE RNE). Takes a whole-dword register source (so f32 denormal mode never touches From c97baa15f9169fc3fb13cf33516413eb963aa836 Mon Sep 17 00:00:00 2001 From: TheVoid <MrDominoGrm@gmail.com> Date: Thu, 26 Nov 2026 00:02:54 +0100 Subject: [PATCH 224/232] gpu: back slot 133 linear buffers by sharing or a submit-time copy (opt-in) (#2218) * gpu: back slot 133 linear buffers by sharing or a submit-time copy (opt-in) X2W_D3D12_LINEAR_BUFFERS=1 (or =copy) gives device slot 133 buffers in COMMON state (row-major or unknown layout) a backing that keeps the title's bytes visible to the GPU. Unset, slot 133 is unchanged. - Share only after D3D12_FEATURE_EXISTING_HEAPS reports support (queried once, before any open), for a buffer inside one committed private allocation at a 64 KiB-aligned offset. The heap is cached by base, which the open heap keeps from being released. - An XMem view is not shared: a heap opened from a view makes XMem's unmap of those pages fail with error 87 (measured), and desktop resources live for the process. Sharing reports 0x80070032 and the buffer is copied. - Copy into a committed default buffer at each submission through the queue wrapper, before the title's lists run, never at bind or record. Only changed bytes are copied, through staging buffers that are reused only after their submission's queue fence completes. - Refuse with a defined HRESULT where the copy cannot keep the guarantees: a GPU-written use returns the sharing HRESULT (or DXGI_ERROR_UNSUPPORTED when sharing was not attempted), no submit fence returns E_NOT_VALID_STATE, and a submission whose refresh cannot be staged is not executed. tests/linear_buffer_backing_check.cpp drives slot 133, wrapper lists and the queue wrapper in d3d12_xs.dll over XMem pages and a private range with the #1942 cases and sentinels: default (old behaviour asserted), share, copy, host sharing refusal (EXISTING_HEAPS forced to 0) and a copy without a submit fence, plus four mutants that each remove one guarantee inside the DLL and must fail their case. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: keep slot 133's default backing where the linear path refuses A title run with X2W_D3D12_LINEAR_BUFFERS=1 faulted at 1.76 s: the first eligible placement, a GPU-written buffer across XMem views, was refused with 0x80070057, and the title, for which CreatePlacedResourceX never fails on the console, used the null object. - Where neither sharing nor the copy keeps its guarantees (a GPU-written use that is not shared, no submit fence, no copy buffer), slot 133 now keeps the default backing and returns what it returns with the switch off. The refusal HRESULT is appended to the slot 133 log line, kept in x2w_d3d12_linear_buffer_info (path 3, refusal_hr) and counted in the totals (kept_default, last_refusal_hr). - A submission whose refresh cannot be staged now runs. The buffer keeps its last upload and is reported stale (info: stale, refresh_failures, last_refresh_hr; totals: refresh_failures, last_refresh_hr) until a later refresh succeeds; the first failures are logged. The fixture asserts the old behaviour and the reported refusal for every kept default (the log line read back through X2W_TRAP_LOG), adds a stale path (X2W_TEST_LINEAR_REFRESH_FAIL) and a refusal-silent mutant that drops the report and must fail. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: refresh linear buffers without holding their lock across waits Review of #2218: - before_submit snapshots the copied buffers' work under mutex_, then takes, creates or waits for staging (a full pool waits up to 5 s for the oldest fence), fills it, resets and records a refresh list and runs ExecuteCommandLists without the lock, and publishes the result under it again. A release(), the fixture exports or another queue's submission no longer wait behind a fence wait or ExecuteCommandLists. Staging is still reused only after its fence, the refresh still runs at submit, and a buffer whose staging fails is still marked stale. - In render mode the refresh runs before queue_execute takes draw_lock and allocator_lock, so a staging wait does not stall list recording. - x2w_d3d12_linear_buffer_info returns false for a wrapper without a desktop object. The fixture adds a contention path (X2W_TEST_LINEAR_STAGING_LIMIT=1): while a refresh waits for the only staging buffer behind a gate, the info export, release() and a second queue's submission must finish, and a hold-lock mutant that keeps the lock across the wait must fail. The copy path also refreshes on COMPUTE and COPY queues, read by a dispatch and by CopyBufferRegion. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: note why concurrent linear-buffer publishes only cost a refresh Two submissions that snapshot the same copied buffer can publish `uploaded` in either order, so it may briefly lag the GPU copy. The next diff is then redundant or larger than needed, never one that misses a change. Comment only (tedin7's review nit on #2218). Refs #1914 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: refresh linear buffers on an internal queue that consumers wait for Review of #2218 (R0Y00): one copied buffer, one CPU write, then a list on queue 1 behind an unsignalled gate and a list on queue 2. Queue 2 read the old bytes: queue 1's refresh was enqueued behind its gate but recorded as uploaded, so queue 2 skipped its own. - Every refresh now runs on one internal COPY queue per device, which never waits on a title fence, and signals an internal fence value. Each copied buffer remembers the value of its last refresh. - Every submission through a queue wrapper first makes its queue wait for the highest such value among the live copied buffers that has not completed. A consumer on any queue runs after every refresh enqueued before it, and no title queue waits on another, so title-owned cross-queue fences cannot form a cycle with a refresh. - Staging is reused once its copy's internal fence value completes. The per-title-queue fences, after_submit and linear_submitted go. - If the internal queue or fence cannot be created, copied placements keep the default backing with that HRESULT recorded. - x2w_d3d12_linear_buffer_internal_queue lets fixtures hold refreshes. The fixture adds gate2q (both reads see the CPU write), gate2q.held (the second queue waits for a held refresh), xq (queue 1 waits on a fence queue 2 signals: no deadlock, both read the write) and a skip-consumer-wait mutant that must fail gate2q.held. Case c and contention hold the internal queue so staging stays in flight. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: count linear-buffer backings in the D3D12 budget With X2W_D3D12_BUDGET=1, slot 133's linear buffers are counted as the default backing counts its own: a shared buffer as a placed resource whose heap (opened once per private range) has a backing-heap ticket in use while a buffer on it is held, a copied buffer as a committed default buffer. The pool's staging buffers are counted as upload memory when they are created; they live for the process. The fixture enables the budget and checks, on the share and copy paths, that one placement goes live in its category, the heap is live for a shared one, and the title's release moves it to retained, with nothing unmeasured. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: defer slot 133 linear buffers to the XMem lease path The mesh XMem lease path (#2280; X2W_MESH86_XMEM_SRV or X2W_MESH_INDIRECT_XMEM) takes the default copied placements of XMem pages whose console flags are 0: it mirrors their GPU writes into a leased view of the section and publishes that to mesh readers. Those are exactly the GPU-read XMem buffers the linear copy path would back. While the lease path is on, slot 133 now keeps the default backing for such a placement and records the deferral as a refusal, HRESULT_FROM_WIN32(ERROR_BUSY), in the log line, the info and the totals, so one placement never has two owners. Other placements are unaffected, and nothing changes while the lease path is off. The fixture adds a lease path (=copy with X2W_MESH86_XMEM_SRV=1): an XMem buffer keeps the default backing with the deferral reported, and a private one is still copied. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: stop refreshing a copied linear buffer that a list copy writes Main now forwards CopyBufferRegion and CopyResource into slot 133 placed buffers (list_copy.inl), so a copied linear buffer can be written by the GPU. Those bytes never reach the title memory, and a later refresh whose changed span covers them copied the title's older bytes over them. A copied buffer that a recorded copy writes now keeps the GPU's bytes from that recording on and is no longer refreshed, as the default backing behaves for it. The info (gpu_written) and the totals report it, and the first few are logged. The fixture adds gpuw on the copy path: a list CopyBufferRegion (list slot 15) writes G into the buffer, the title changes the words on both sides, and the next read must still see G. The refresh-gpu-written mutant keeps refreshing and must fail it. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: record linear-buffer budgets, list-copy holds and the lease deferral Describe, for slot 133's opt-in linear buffers on current main: the refresh and consumer Wait ahead of red_producers and split mesh submissions, the D3D12 budget categories, a copied buffer that a list copy wrote, and the deferral to the mesh XMem lease path. Record the budget, gpuw and lease cases, the refresh-gpu-written control and the results at ff06794b on WARP and an RX 9070 XT (driver 32.0.32029.2010), and note sharing XMem views through the section lease (#2280) as a follow-up. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: mark a copied linear buffer GPU-written when its copy is submitted A list copy into a copied linear buffer changed the backing when the copy was recorded. A recording that was closed and then reset without being submitted therefore stopped the buffer's refreshes for good: the next read saw the old upload instead of the CPU's later bytes, on XMem and private memory alike (review repro on WARP and an RTX 4060). The write is now pending on the recording, next to the texture writes that list_copy.inl already tracks: commit_list_gpu_writes marks the buffer GPU-written after the recording's ExecuteCommandLists, and a Reset or a failed Close (discard_list_gpu_writes) drops it. The recording's own submission still refreshes the buffer first, and its queue waits for that refresh before the copy runs. The gpuw-at-record mutant restores the recording-time mark. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: order linear-buffer refreshes behind earlier submissions A refresh's copy into a copied linear buffer was ordered only before later consumers (their queues Wait for the internal fence). An earlier submission that still reads or writes the backing, on any queue, could run at the same time as the internal COPY queue overwrote it. Simultaneous access allows concurrent operations on one buffer only on disjoint ranges. Each queue wrapper now signals a user fence of its own after the title's lists (render and plain submissions). Before a refresh's copy executes, the internal queue Waits for every queue's latest user fence value that has not completed (totals: producer_waits). The wrappers cannot tell which buffers a submission reads, since titles bind them by GPU virtual address, so every earlier submission counts as a user of every copied backing. A queue whose latest submission sits behind a title Wait (queue slot 17) on a fence that has not been reached is not waited for (totals: producer_wait_skips, logged): a later submission that waits for this refresh may be the one that signals that fence, and waiting would deadlock both queues. That submission has not started and reads the CPU's newer bytes once it runs. A fence reached while the copy still executes can still overlap the read; the header says so. A submission now also waits for the refresh it enqueued itself, even if the title released the buffer meanwhile; before, such a refresh was left out of the consumer Wait. The contention case asserts the new order: S1, gated, reads B because C's copy waits for it; S2 reads C. The gate opens before the internal queue is drained. The skip-producer-wait mutant removes the wait. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: publish linear-buffer uploads in the order their copies execute Two submissions on different threads could snapshot one copied buffer against the same upload record, stage the title's bytes at different times, execute their copies in one order and publish the upload record in the other. With X staged first, the CPU then writing Y and Y staged second, Y's copy could take the lower internal fence value and X's the higher, so the backing held X while the record said Y. No later submission refreshed the buffer until the title changed those bytes again. The comment that called this a redundant copy at worst was wrong. A copied buffer now remembers the internal fence value of its newest applied publish. A newer refresh applies its span; an older one that arrives after it drops the record (totals: reordered_publishes), and the next submission copies the whole buffer. An unknown record is set again only by a copy of the whole buffer. The publish-out-of-order mutant applies every publish in lock order, as before. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: probe and guard title memory right before staging a linear buffer before_submit snapshots every live copied buffer, not only those the submitted lists read, and probes its title memory under the lock. refresh() then copied that memory into staging without the lock. If the title released one of those buffers on another thread and freed or unmapped its pages in between, the copy faulted inside d3d12_xs.dll. The title memory is now probed again right before it is staged, and the copy runs under a fault guard (access violation or in-page error). A buffer whose memory is gone is skipped and counted (unreadable), as the snapshot already does; a read that faults anyway is counted (copy_faults) and fails that buffer's refresh. A buffer released after the snapshot whose pages are still mapped is staged for that submission, which may read it (the contention case does). The wrappers cannot tell which buffers a submission's lists read, so the snapshot still covers every live copied buffer. The copy-after-retire mutant skips the second probe; the guard then catches the faulting read. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * tests: drive discarded copies, earlier reads and refresh races in linear_buffer_backing New cases on the copy path, on XMem and private memory: - gpuw.discard (the review repro): a list copy into a copied buffer is recorded, closed and reset without a submission; after the CPU writes B the next read must see B, with gpu_written 0. - war: a read of A on queue 1 behind a title gate; the CPU writes B and queue 2 submits a read. Queue 2 must not complete while the gate is closed, queue 1 must read A, queue 2 B, and producer_waits must grow. - xq.write: queue 1 waits through its wrapper (slot 17) on a title fence and submits a read; after the CPU writes B, queue 2's read must complete while queue 1 still waits (no deadlock), both read B, and the skip is counted. - order: two threads refresh one buffer, parked through a new fixture hook (x2w_d3d12_linear_buffer_test_pause) so that the older copy publishes last; the next submission must refresh and read D. - retire: a submission parks after its snapshot while the title releases X and frees its pages; X must be skipped as unreadable, with no copy fault and no failed refresh, and Y must read C. Four controls run on WARP with WILL_FAIL, each failing its own case: gpuw-at-record, skip-producer-wait, publish-out-of-order and copy-after-retire. The totals line prints the new counters. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: record the linear-buffer submit-time GPU write, producer wait and refresh races Describe the review fixes for slot 133's copied linear buffers. A list copy marks a buffer GPU-written only when its recording is submitted. A refresh's copy waits for every queue's earlier submission, except one that sits behind an unreached title Wait, which is skipped so that title fences cannot close a cycle. Uploads are published in the order their copies execute. Title memory is probed again and read under a fault guard right before it is staged. Add the gpuw.discard, war, xq.write, order and retire cases, the changed contention expectation (S1 reads B), the four new controls, and the results at 981b519c on WARP and an RX 9070 XT (driver 32.0.32029.2010) in the dev and release presets. Note the remaining overlap window and the cost of treating every submission as a user of every backing. Refs #1914 Refs #874 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: refuse a linear-buffer submission whose refresh has no safe completion order A refresh no longer skips a queue whose latest submission sits behind an unreached title Wait (slot 17). Skipping did not prove that the fence stays blocked until the copy finishes: another producer can reach it meanwhile and the copy then overlaps that read. Instead, right before the refresh would be enqueued (under internal_mutex_), a refresh that would have to wait for such a submission, or for one without a user fence value, refuses the whole submission: no refresh, consumer Wait, title lists or user fence Signal is enqueued. Staging buffers and the refresh list are freed, no upload record or refresh state changes, and recorded GPU writes stay pending on their recordings. The title's own Signal/Wait paths are untouched, so a later Signal still releases the earlier queue. Counted as unsafe_refresh_refusals (replacing producer_wait_skips) and logged. A title wait that cannot be stored now blocks the queue until the next submission behind it completes, instead of being forgotten at that submission. xq.write now gates queue 1 on a title fence with a read of A, writes B and expects queue 2's read to be refused (slot keeps P), queue 1 to read A after the title's Signal through queue 2's wrapper, and the refused recording to read B when resubmitted. New control accept-unsafe-refresh restores the skip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: record the linear-buffer refusal of a refresh with no safe completion order Replace the producer-wait skip in the runtime notes with the refusal: when it applies, what a refused submission leaves in place, its log line and the unsafe_refresh_refusals counter. In the experiment notes, rewrite the xq.write oracle, drop the skip results and the overlap caveat, and record the c6a0c8a9 runs and the accept-unsafe-refresh control. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gpu: order a queue's title waits and user fence values under one lock A title Wait (queue slot 17) and ExecuteCommandLists on the same queue from two threads could be recorded in the opposite order to the desktop queue: a submission behind the desktop Wait took its user fence value before note_title_wait ran, so the Wait was recorded as preceding only later submissions. Another queue's refresh was then accepted and waited for the blocked submission, and that queue's own Signal of the fence sat behind the refresh. Each queue's linear-buffer record now has an order lock (SRWLOCK; users_ becomes a deque so records never move). Slot 17 holds it from the desktop Wait through note_title_wait; a submission holds it from the title's ExecuteCommandLists through after_submit, taken before draw_lock and allocator_lock in render mode and with no other lock held. It is not held across the refresh, nothing under it waits on the CPU for the GPU, and the title's Signal does not take it. The fixture adds xq.race: the Wait is parked through a new pause point (3) between the desktop Wait and its record while another thread submits the read of A on queue 1. Queue 2's read must still be refused and queue 2 must still signal the fence; waits are bounded with a CPU Signal of the fence as cleanup. Control unlocked-title-wait skips the lock in slot 17 and reproduces the review's pending lanes with zero refusals. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> --- CMakeLists.txt | 36 + docs/experiments.md | 90 + docs/startup-runtime.md | 45 + src/startup_stubs/d3d12_xs_device.cpp | 197 ++- src/startup_stubs/linear_buffer_backing.h | 1256 +++++++++++++ src/startup_stubs/linear_buffer_report.h | 39 + src/startup_stubs/list_copy.inl | 34 + tests/linear_buffer_backing_check.cpp | 1952 +++++++++++++++++++++ 8 files changed, 3619 insertions(+), 30 deletions(-) create mode 100644 src/startup_stubs/linear_buffer_backing.h create mode 100644 src/startup_stubs/linear_buffer_report.h create mode 100644 tests/linear_buffer_backing_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 927193029..e86361468 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2668,6 +2668,42 @@ foreach(mutant IN ITEMS skip_refresh skip_copy_back reuse_early) set_tests_properties(unified_buffer_paths_${mutant}_control PROPERTIES WILL_FAIL TRUE TIMEOUT 90 SKIP_RETURN_CODE 77) endforeach() +# The production slice (#1914): slot 133's opt-in linear-buffer backing (X2W_D3D12_LINEAR_BUFFERS, +# src/startup_stubs/linear_buffer_backing.h) through the device and queue wrappers of d3d12_xs.dll, over +# XMem pages and a private range: the default, real sharing, forced copying, host sharing refusal, a +# copy without a submit fence (the default backing is kept and the refusal reported), a refresh that +# cannot be staged (the submission runs, the buffer is reported stale) and a one-buffer staging pool +# (a waiting refresh must not block release(), the info export or another queue). Refreshes run on an +# internal copy queue; the copy path also reads on COMPUTE and COPY queues, reads one buffer on two +# queues after one CPU write (both must see it), and follows a title-owned cross-queue fence without +# deadlock. It also counts the backings in the D3D12 budget, keeps a buffer a submitted list copy wrote +# (and refreshes one whose copy was discarded), orders a refresh behind an earlier read on another queue, +# refuses a submission whose refresh would have to wait for a queue behind an unreached title Wait (also +# when that Wait and the submission behind it arrive on two threads), publishes two threads' refreshes in execution order, skips a buffer released and freed mid-refresh, and +# defers XMem placements to the mesh XMem lease path when that is on. Each mutant removes one guarantee in +# the DLL and must fail its case. +add_executable(linear_buffer_backing_check tests/linear_buffer_backing_check.cpp) +target_include_directories(linear_buffer_backing_check PRIVATE tests) +target_compile_features(linear_buffer_backing_check PRIVATE cxx_std_17) +target_link_libraries(linear_buffer_backing_check PRIVATE xmem_shim d3d12_xs_shim d3d12 dxgi d3dcompiler) +foreach(adapter IN ITEMS warp hardware) + foreach(path IN ITEMS default share copy refusal untracked stale contention lease) + add_test(NAME linear_buffer_backing_${path}_${adapter} COMMAND linear_buffer_backing_check ${adapter} ${path}) + set_tests_properties(linear_buffer_backing_${path}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endforeach() +foreach(control IN ITEMS copy:skip_refresh copy:reuse_early copy:copy_gpu_writes refusal:ignore_feature + copy:refusal_silent contention:hold_lock copy:skip_consumer_wait copy:refresh_gpu_written copy:gpuw_at_record + copy:skip_producer_wait copy:publish_out_of_order copy:copy_after_retire copy:accept_unsafe_refresh + copy:unlocked_title_wait) + string(REPLACE ":" ";" parts "${control}") + list(GET parts 0 path) + list(GET parts 1 mutant) + string(REPLACE "_" "-" flag "${mutant}") + add_test(NAME linear_buffer_backing_${mutant}_control COMMAND linear_buffer_backing_check warp ${path} --mutate ${flag}) + set_tests_properties(linear_buffer_backing_${mutant}_control PROPERTIES WILL_FAIL TRUE TIMEOUT 120 + SKIP_RETURN_CODE 77) +endforeach() # The configured range's windows and GPU addresses (src/d3d12_xs_range.h) with a fake device and fake # windows. The mutated run is the negative control. add_executable(d3d12_xs_range_check tests/d3d12_xs_range_check.cpp src/d3d12_xs_range.cpp) diff --git a/docs/experiments.md b/docs/experiments.md index 1919948c3..f98cf844a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9905,6 +9905,96 @@ cmake --build --preset release --target startup_indirect_draw_indexed startup_li ctest --preset release --no-tests=error -j1 -R '^(xmem_section_lease_|xmem_shim_(exports|mapped_pages|page_runs)$|startup_(mesh_xmem_writer|mesh86_srv_proof|list_copy|list_resubmit.*_warp$))' --output-on-failure ``` +#### Production slice: slot 133 linear buffers (#1914) + +The first production change wires the #1942 comparison to one buffer kind in `d3d12_xs.dll`: device slot 133 (`CreatePlacedResourceX`) with a buffer description and initial state `COMMON`. The title writes such a buffer with the CPU and the GPU reads it as vertex, index, constant, shader-resource or indirect-argument data. The behaviour is opt-in through `X2W_D3D12_LINEAR_BUFFERS`; unset, slot 133 keeps its backing (see [Linear buffer backing](startup-runtime.md#linear-buffer-backing-device-slot-133-opt-in)). `src/startup_stubs/linear_buffer_backing.h` shares a buffer in a private allocation after `D3D12_FEATURE_EXISTING_HEAPS`. It copies any other buffer from title memory at each submission through the queue wrapper. The copy runs on an internal COPY queue that never waits on a title fence, and every submission through a queue wrapper waits for the internal fence value of every pending refresh of a live copied buffer. A second queue's consumer therefore cannot run ahead of a refresh that another queue enqueued, and no title queue waits on another. Where the copy cannot keep the guarantees, slot 133 keeps the default backing and returns what it returns without the switch, and the refusal HRESULT is recorded in the log, the buffer's info and the totals. A refresh that cannot be staged does not hold the submission back; the buffer keeps its last upload and is reported stale. + +A title run motivated the fallback. An earlier revision returned the refusal from slot 133. On the RX 9070 XT with a warm shader cache and the same input, the run with the switch off stopped at 294 s at the slot 148 builder, as before. With `X2W_D3D12_LINEAR_BUFFERS=1` the title faulted at 1.76 s, reading address `0x18`. Its first eligible placement was a GPU-written buffer of `0xae00000` bytes on an XMem view (`MEM_MAPPED`) across views: sharing `0x80070057`, so slot 133 returned `0x80070057`. On the console `CreatePlacedResourceX` does not fail, and the title used the null object. In the switch-off run, slot 133 placed: +- 2,987 GPU-read buffers (14.2 MiB), not aliased; +- 506 GPU-written buffers (856 MiB), not aliased; +- 61 GPU-written buffers (167 MiB), aliased (private). + +`tests/linear_buffer_backing_check.cpp` drives the production entry points: slot 133 on the device wrapper, list Reset (139) and Close (9) on wrapper lists recorded on their desktop lists, and `ExecuteCommandLists` (queue slot 10) on the queue wrapper, in render mode. It reuses #1942's sentinels and cases. The GPU reads the buffer through a root SRV and writes it through a root UAV. Title memory is either `xmem.dll` physical pages (64 KiB slots of 256 MiB sections, `X2W_XMEM_SHARED_VIEWS=1`) or one committed private range. The buffer sits at offset `0x30000` behind three neighbour pages, and the first XMem buffer lands on slots that a previous user freed, which must read zero. Each run sets its own environment. The path is one of `default` (unset), `share` (`=1`), `copy` (`=copy`), `refusal` (`=1` with `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1`, as on an adapter with `EXISTING_HEAPS = 0`), `untracked` (`=copy` with `X2W_TEST_SUBMIT_FENCE_FAIL=1`), `stale` (`=copy` with `X2W_TEST_LINEAR_REFRESH_FAIL=3`, so staging requests 2, 5, 8 and so on fail with `E_OUTOFMEMORY`), `contention` (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`) and `lease` (`=copy` with `X2W_MESH86_XMEM_SRV=1`, the mesh XMem lease path on). Every run sets `X2W_D3D12_BUDGET=1`. A kept default must return `S_OK` with an object, behave as before (an XMem view not aliased, a private range aliased on an adapter with existing heaps), and carry the refusal HRESULT in `x2w_d3d12_linear_buffer_info`, in the totals and in its slot 133 log line. The fixture reads that line back from `X2W_TRAP_LOG`. + +| Case | Sequence and oracle | +|---|---| +| a | Slot 133 and a list that reads the buffer are recorded over A; the CPU writes B before `ExecuteCommandLists`. The GPU must read B in all 1,024 words. | +| a2 | 16 words then change to E. The next submission must read them, and a copy must move only those 64 bytes. | +| b | A GPU-written use (`ALLOW_UNORDERED_ACCESS`). The GPU writes G ^ key; after the fence the CPU alias must hold it and the rest of the buffer its filler. Where the buffer would be copied, slot 133 must keep the default backing and report the refusal. | +| c | Three submissions (B, C, D, each its own buffer) are held on a gate fence; each must read its own sentinel. Sharing: the title releases X while it is held, and after the fence places E at X's address. Copying: no staging buffer may be handed out twice while held, and after the fence the next refresh must take one of them again. | +| d1 | After a refreshed submission of A the CPU writes B, and the list runs on the desktop queue directly, past the wrapper. A copy must expose the stale A; sharing reads B. Through the wrapper, B. | +| d2 | As b, held on the gate. Before it opens, the fence must be incomplete and the alias must hold P in every word; after it, G ^ key. | +| split | `share` only: a buffer across two XMem views is copied, and must read B. | +| gate | `refusal` only: one feature query and no heap open. | +| off | `default` only: none of the linear-buffer code ran. | +| kept | every path with refusals: the totals count as many kept default backings as the run refused. | +| stale | `stale` only: a refreshed submission of A, then the CPU writes B and the refresh fails. The submission must still run and complete and read A (the last upload). The buffer must be reported stale with `E_OUTOFMEMORY` in its info and the log. The next submission must read B and clear it. | +| q.comp, q.copy | `copy` only: the buffer is read on a COMPUTE queue (a dispatch) and on a COPY queue (`CopyBufferRegion`), each through its queue wrapper, so the refresh runs on that queue. The first submission must read B with the whole buffer copied, and a 16-word change must then copy 64 bytes. | +| gate2q, gate2q.held | `copy` only (review repro): one buffer holding A, read by a list on queue 1 behind a title gate and by a list on queue 2, with one CPU write of B before both submissions. Queue 2 must complete while the gate is still closed and read B, and queue 1 must read B after it. In `.held` the fixture also holds the internal refresh queue, and queue 2 must not complete before the refresh lands. | +| xq | `copy` only: queue 1 waits on a title fence that queue 2 signals after its list. Both read the buffer the CPU changed to B. Both must complete, with no deadlock, and read B. | +| budget | `share` and `copy`: one placement must go live in its budget category, placed for a shared buffer (with its heap live) and buffer for a copied one. The title's release must move it to retained, with nothing unmeasured. | +| gpuw | `copy` only: a list `CopyBufferRegion` (list slot 15) writes G into the buffer, and the title then changes its first and last words. The next read must still see G (no refresh spans the written words), and info and totals must report it as GPU-written. | +| gpuw.discard | `copy` only (review repro): the same copy is recorded and closed, then the list is reset without a submission, and the CPU writes B. The next read must see B, and the buffer must not be reported GPU-written. | +| war | `copy` only: a read of A on queue 1 behind a title gate (on the desktop queue), then the CPU writes B and queue 2 submits a read. Queue 2 must not complete while the gate is closed, queue 1 must read A, queue 2 must read B, and `producer_waits` must grow. | +| xq.write | `copy` only: queue 1 waits through its wrapper (queue slot 17) on a title fence and submits a read of A; the CPU writes B and queue 2 submits a read. That refresh would have to wait for queue 1, behind the unreached fence, so queue 2's submission must be refused: `unsafe_refresh_refusals` +1, the refusal logged, and its result slot must keep the fixture's P. The title then signals the fence through queue 2's wrapper (queue slot 16). Queue 1 must complete and read A, and the refused recording, submitted again on queue 2, must read B with no further refusal. | +| xq.race | `copy` only (review repro): xq.write with queue 1's title `Wait` and its read of A issued from two threads. Thread W's `Wait` (queue slot 17) is parked through `x2w_d3d12_linear_buffer_test_pause` (point 3) after the desktop `Wait` and before it is recorded. Meanwhile thread S submits the read of A on queue 1 and gets up to 1 s to return before W resumes. The read sits behind the fence on the desktop queue, so after the CPU writes B, queue 2's read must be refused (refusals +1, its result slot keeps P, queue 2's own fence is reached). The title's `Signal` through queue 2's wrapper (queue slot 16) must succeed, queue 1 must complete and read A, and the refused recording, submitted again, must read B. If queue 2 or queue 1 does not complete within 3 s, the fixture signals the fence from the CPU so both queues drain, and the row fails. | +| order | `copy` only: two threads refresh one buffer, parked through `x2w_d3d12_linear_buffer_test_pause`. Thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes its copy first and parks before publishing; A executes (the backing ends with C) and publishes, and B publishes last. The next submission must refresh D and read it, with `reordered_publishes` +1. | +| retire | `copy` only: a submission that reads Y snapshots the changed X and Y and parks before staging. The title releases X and frees its pages. X must be skipped as unreadable, with no copy fault and no failed refresh, and Y must read C. | +| lease | `lease` only: an XMem buffer must keep the default backing (not aliased: it reads zero) with the deferral `0x800700aa` reported. A private buffer must still be copied and read B. | +| contention | `contention` only (`=copy` with `X2W_TEST_LINEAR_STAGING_LIMIT=1`): S1 reads X behind a title gate, and its refresh, held on the internal queue, holds the only staging buffer. S2's refresh of X, on another thread, must wait for that copy. During that wait, three probes must finish while S2 is still waiting: the info export, the title's release of X, and a submission on a second direct queue. After the refreshes land and the gate opens, S2 must have reused the same staging buffer (none created), with no refresh failure. S1 must read B, because C's copy waits for S1 (the producer wait), and S2 must read C. Before the producer wait both read C. | + +On Windows 11 build 26300.9974 at `ff06794b` plus this change, the results were identical on in-box WARP (`1414:008c`, driver 10.0.26100.9818) and an AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), with the debug layer off and on (`X2W_TEST_DEBUG_LAYER=1`, no errors stored). Both adapters report `D3D12_FEATURE_EXISTING_HEAPS`. All eight paths pass with no skips, and every totals line matches across the four runs. Bytes are those copied from title memory into the backing; HRESULTs are the slot 133 result and the sharing result. + +| Path | Pool | Backing | Slot 133 / sharing HRESULT | Bytes copied | Results | +|---|---|---|---|---|---| +| `default` | XMem | committed default buffer, not aliased (old behaviour) | `S_OK` / not attempted | 0 | a reads zero in all words; b leaves P | +| `default` | private | aliased through the cached heap (old behaviour) | `S_OK` / not attempted | 0 | a B; b G ^ key; no linear-buffer code ran | +| `share` | private | title memory, one heap opened for the range (generation 1, 7 cache hits) | `S_OK` / `S_OK` | 0 | a B; a2 E; b G ^ key; c B, C, D, then E at X's address on the same heap; d1 B both ways; d2 P before the fence, then G ^ key | +| `share` | XMem | copied; b and d2 kept default (not aliased) | `S_OK` / `0x80070032` (view), `0x80070057` (split); b, d2 refusal `0x80070032` | a 131,072; a2 64; split 131,072; c 4 × 131,072; d1 131,072 + 4,096 | as `copy`; b and d2 leave P, as before; 2 kept default backings reported | +| `copy` | XMem, private | committed default buffer refreshed at submit; b and d2 kept default | `S_OK` / not attempted; b, d2 refusal `0x887A0004` | a 131,072; a2 64; c 4 × 131,072; d1 131,072 + 4,096 | a B; a2 E; c B, C, D on staging 1, 2, 3, then staging 1 again after the fence; d1 stale A past the wrapper, B through it; b and d2 as before (XMem leaves P, private G ^ key); 4 kept | +| `refusal` | XMem, private | as `copy` | `S_OK` / `0x887A0004` from the feature gate, no heap opened; b, d2 refusal `0x887A0004` | as `copy` | as `copy`; 4 kept | +| `untracked` | XMem, private | kept default for every placement | `S_OK`; refusal `0x8007139F` (`E_NOT_VALID_STATE`) for a, `0x887A0004` for b and d2 | 0 | a: XMem reads zero, private B; b and d2: XMem leaves P, private G ^ key (as before); 6 kept | +| `stale` | XMem, private | copied | `S_OK` / not attempted | 131,072 + 4,096 per pool; the failed refresh copies 0 | the failed submission completes and reads A, stale reported with `0x8007000E`, then B and stale cleared; 2 refresh failures | +| `copy` (q.comp, q.copy) | XMem, private | copied, refreshed on the COMPUTE or COPY queue | `S_OK` / not attempted | 131,072, then 64 | B in all words, then 16 E; no refresh failure | +| `copy` (gate2q, gate2q.held, xq) | XMem, private | copied | `S_OK` / not attempted | 131,072 for A, then 4,096 for B | queue 2 completes with queue 1 still gated and reads B; queue 1 then reads B; `.held`: queue 2 waits for the held refresh; xq: both complete and read B | +| `copy` (budget, gpuw) | XMem, private | copied | `S_OK` / not attempted | 131,072; gpuw then 0 (not refreshed) | budget: buffer objects live 0 -> 1 -> 0 after release, retained +1; gpuw: G after the title's writes around it, `gpu_written` 1 | +| `share` (budget) | private | shared | `S_OK` / `S_OK` | 0 | placed objects live 0 -> 1 -> 0, retained +1, heap live 1 | +| `lease` | XMem | kept default, deferred to the lease path | `S_OK` / not attempted / refusal `0x800700AA` | 0 | reads zero, as before; deferral in info, totals and the log | +| `lease` | private | copied | `S_OK` / not attempted | 131,072 | B | +| `contention` | XMem, private | copied, one staging buffer | `S_OK` / not attempted | 540,672 for the run | the probes took 0 ms each while S2 waited about 310 ms for the held copy; S1 C, S2 C; staging created 1, no refresh failure | + +The run also measures why an XMem view is not shared, and does not assert it. On both adapters `OpenExistingHeapFromAddress` accepts the five-page view and a buffer places at `+0x30000` (`S_OK`). While they live, XMem's unmap of those pages fails with error 87 (`x2w-xmem unmap of 5 page(s) failed`). After they are released it succeeds and the pages are freed. Desktop resources live for the process, so sharing a view would keep the title from ever unmapping or freeing those pages. + +Negative controls each set `X2W_TEST_LINEAR_BUFFER_MUTANT`, which removes one guarantee inside `d3d12_xs.dll`. Each must fail its case in both pools. The first eight did so on both adapters at `ff06794b`: +- `skip-refresh` takes the copy at placement (bind) and never at submit, so a reads A (2 of 2) and d1 reads A through the wrapper. +- `reuse-early` hands out staging buffers without their fence. With the internal queue held, all three held refreshes share staging 1, and X, Y and Z all read D (2 of 2). +- `copy-gpu-writes` lets the copy accept a GPU-written use. b and d2 leave P in the alias (2 of 2). +- `ignore-feature` opens a heap although the feature query reports no support. gate sees one heap open (1 of 1), and the private buffers are shared. +- `refusal-silent` keeps the default backing without reporting it. b finds no refusal in the info and no log line (2 of 2), and the kept totals stay at 0. +- `hold-lock` keeps the backing's lock held while a refresh waits for a staging fence. contention's info probe then blocks for about 4.7 s, until the wait gives up after 5 s. S2 goes stale and reads B (2 of 2). +- `skip-consumer-wait` stops submissions from waiting for the internal fence. In gate2q.held, queue 2 completes before the held refresh lands and reads A (2 of 2). Case c reads zeros as well. +- `refresh-gpu-written` keeps refreshing a copied buffer that a list copy wrote. In gpuw, the refresh of the title's two changed words spans the written region and copies A over G (2 of 2). + +The review of `bfdd583f` found four more problems. A list copy into a copied buffer changed its backing when recorded, so a discarded recording stopped its refreshes for good. A refresh's copy was not ordered behind earlier submissions that still read the backing. Two threads' refreshes could publish the upload record in the opposite order to their copies, leaving the buffer stale. And title memory was staged without the lock, so a buffer released and freed on another thread could fault the DLL. The rework adds gpuw.discard, war, xq.write, order and retire, changes contention as above, and adds four controls: +- `gpuw-at-record` marks the buffer GPU-written when the copy is recorded. gpuw.discard reads A, `gpu_written` 1 (2 of 2). +- `skip-producer-wait` stops the refresh's copy from waiting for earlier submissions. In war, queue 2 completes while the gate is closed and queue 1 reads B (2 of 2). +- `publish-out-of-order` applies every publish in lock order. order then reads C, `reordered_publishes` +0 (2 of 2). +- `copy-after-retire` skips the probe right before staging. In retire, the fault guard catches the read of X's freed pages: copy faults +1, one refresh failure `0x800703E6` (2 of 2). + +On Windows 11 build 26300.9974 at `981b519c`, in-box WARP (`1414:008c`, driver 10.0.26100.9818) and the AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010), debug layer off: all 16 path entries pass, with no skips, in the dev and release presets. Every new row passes in both pools on both adapters: gpuw.discard B, `gpu_written` 0; war queue 1 A and queue 2 B, producer waits +1; order D, reordered publishes +1; retire unreadable +1, copy faults 0, Y C; contention S1 B and S2 C. All twelve controls fail their targeted rows (2 of 2, gate 1 of 1). The producer wait can idle the GPU between submissions, because every earlier submission counts as a user of every copied backing. + +The review of `58971a4a` rejected that revision's handling of xq.write, which skipped a queue behind an unreached title fence. Skipping does not establish that the fence stays blocked until the copy finishes, because another producer can reach it while the copy runs. A submission whose refresh would have to wait for such a submission (on any queue, including its own) or for one without a user fence value is now refused before anything is enqueued (`unsafe_refresh_refusals`, logged): no refresh, no consumer `Wait`, none of its lists and no user fence `Signal`. The staging buffers, the refresh list and every buffer's upload record stay as they were, so a later safe submission copies whatever still differs. A recorded copy's GPU write stays pending on the refused recording. xq.write now drives this case (table above), and one control is added: +- `accept-unsafe-refresh` restores the skip. In xq.write, queue 2's read is not refused and reads B, and queue 1 reads B after its fence instead of A (2 of 2). Neither queue hangs. + +On Windows 11 build 26300.9974 at `c6a0c8a9`, with the same adapters and drivers and the debug layer off, all 16 path entries pass with no skips in the dev and release presets, and all thirteen controls fail their targeted rows (2 of 2, gate 1 of 1). In both pools on both adapters, xq.write refuses queue 2's read (refusals +1, log line present) and leaves its result slot at P in all 1,024 words, and queue 2's own fence is reached. After the title's `Signal` through queue 2's wrapper (queue slot 16, `S_OK`), queue 1 completes and reads A. The refused recording, submitted again on queue 2, reads B with no further refusal and no stale or failed refresh. war (queue 1 A, queue 2 B, producer waits +1), gate2q, gate2q.held and xq pass as before. A refused submission's work does not run; the log line and the counter are how a run shows it. The producer wait can still idle the GPU between submissions. A proven disjoint resource or an immutable per-submission backing could let more of these cases run; neither is implemented. + +The review of `7ecb6cfd` reproduced a race when queue slot 17 and `ExecuteCommandLists` overlap on one queue. With a pause after the desktop `Wait(F, 1)` and before `note_title_wait`, another thread's read of A on queue 1 took its user fence value first. The `Wait` was then recorded as preceding only later submissions, even though the desktop queue held it ahead of that read. Queue 2's refresh was accepted and waited for queue 1, queue 2's own `Signal(F, 1)` sat behind that refresh, and both queues stayed pending until a CPU `Signal` of F. Each queue's linear-buffer record now has an order lock. Slot 17 holds it from the desktop `Wait` through `note_title_wait`. A submission holds it from the title's `ExecuteCommandLists` through its user fence `Signal`, in render mode before `draw_lock` and `allocator_lock`. A queue's waits and user values are therefore recorded in the order its desktop queue received them. The lock is not held across the refresh, so its staging waits and fixture pauses run without it. Nothing under it waits on the CPU for the GPU, and the title's `Signal` does not take it, so a queue whose submission was refused can still signal the fence. The fixture adds xq.race (table above) and one control: +- `unlocked-title-wait` lets slot 17 run without the order lock. In xq.race, S's read returns while W is parked, and queue 2's read is not refused (refusals +0). Queue 2 and queue 1 then stay pending after the title's `Signal` on queue 2. After the fixture's CPU `Signal` of F, both drain: queue 1 reads A and queue 2 reads B (2 of 2). + +On Windows 11 build 26300 at `7ecb6cfd` plus this change, with in-box WARP (`1414:008c`, driver 10.0.26100.9818) and the AMD Radeon RX 9070 XT (`1002:7550`, driver 32.0.32029.2010) and the debug layer off, all 16 path entries pass with no skips in the dev and release presets. All fourteen controls fail their targeted rows (2 of 2, gate 1 of 1). In both pools on both adapters, xq.race parks W, and S does not return while W is parked. Queue 2's read is refused (refusals +1) and its slot keeps P in all 1,024 words, and queue 2's own fence is reached. The title's `Signal` on queue 2 returns `S_OK`, queue 1 completes and reads A, and the resubmission reads B with no further refusal. xq.write and the other rows pass as before. `ctest --preset release --no-tests=error -R '^linear_buffer_backing_copy_(warp|hardware)$' --repeat until-fail:20` passed 20 of 20 runs on each adapter, which is 80 xq.race rows with none failed. The `unlocked_title_wait` control, repeated with `--repeat until-fail:5`, failed its rows in all 5 runs as expected. + +Run `cmake --build --preset dev --target linear_buffer_backing_check` and `ctest --preset dev --no-tests=error -R '^linear_buffer_backing_' -V`. Set `XBOX2WINDOWS_ADAPTER` to select a hardware adapter and `X2W_TEST_DEBUG_LAYER=1` to enable the debug layer. `linear_buffer_backing_share_hardware` skips (77) on an adapter without existing-heap support; `refusal` covers that case. The controls run on WARP as `WILL_FAIL` tests. Each run writes the DLL's log to `linear_buffer_backing_<path>_<adapter>.log` next to the executable. Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs still take `upload_from_title` at bind; neither reads the slot 133 backing. Shared buffers and their heaps live for the process, so a private range under one cannot be released, as with the default backing. A copied buffer that a submitted list copy wrote keeps the GPU's bytes and stops following the title memory, as the default backing does. Sharing XMem views through the section lease (#2280) instead of copying them is a follow-up. Unsynchronized concurrent writes, textures, render targets, acceleration structures and command-list slot 148 are outside this slice. + #### Xbox frame events and token wait semantics (#874) The source-built frame events fixture (`tests/cpu/frame_events_caller.asm`, `tests/cpu/frame_events_provider.cpp`, `tests/cpu/frame_events_check.py`, CTest `cpu_native_frame_events`) models the scheduling and wait semantics of the Xbox frame-pacing extensions in `d3d12_xs.dll`: diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8c11e8db3..1353b96e3 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1343,6 +1343,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | | `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}`, when needed RTV variants `req_<key>.rtv`, and for device slot 67 compute pipelines `req_<key>.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_<key>.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | +| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it, otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | @@ -2958,6 +2959,50 @@ layouts"): - `ctest --preset release --no-tests=error -R '^startup_gfx10_layout' -V` - `ctest --preset release --no-tests=error -j 1 -R '^startup_address_console_' -V` +## Linear buffer backing (device slot 133, opt-in) + +By default slot 133 aliases a buffer only in private memory, through an existing heap cached by +allocation base and opened without a `D3D12_FEATURE_EXISTING_HEAPS` query. Anything else gets a +committed default buffer that does not alias the title memory, holds zeros and is reported as +success (`not aliased` in the log). `X2W_D3D12_LINEAR_BUFFERS` changes this for one buffer kind: a +buffer description with row-major or unknown layout and initial state `COMMON` +(`src/startup_stubs/linear_buffer_backing.h`, [#1914](https://github.com/R0Y00/Xbox2Windows/issues/1914)). +Buffers in `UNORDERED_ACCESS` or acceleration-structure state, and textures, keep the default backing. + +| Value | Backing | +|---|---| +| unset or `0` | the default above; none of the linear-buffer code runs | +| `1` | shared when the adapter reports `D3D12_FEATURE_EXISTING_HEAPS` (queried once, before any open) and the buffer lies in one committed private allocation at a 64 KiB-aligned offset; otherwise copied; otherwise the default backing, with the refusal recorded | +| `copy` | copied; otherwise the default backing, with the refusal recorded | + +- Shared: a cross-adapter buffer placed on the private allocation's heap, cached by base. The GPU reads and writes title memory; nothing is copied. +- An XMem view is never shared. A heap opened from a view keeps it mapped, and XMem's unmap of those pages then fails with error 87. Sharing reports `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)` (`0x80070032`) and the buffer is copied. A buffer across several allocations, or at an unaligned offset, reports `E_INVALIDARG`. Both are decided before any D3D12 call. +- Copied: a committed default buffer that is refreshed from title memory at each submission through a command-queue wrapper, just before the title's lists run, not at bind or record. Only bytes that changed since the last upload are copied, through an upload staging buffer. + - **Internal queue.** Every refresh runs on one internal COPY queue per device, which never waits on a title fence. It signals an internal fence value, and each buffer remembers the value of its last refresh. + - **Consumer wait.** Every submission through a queue wrapper, of any type (direct, compute or copy), first makes its queue `Wait` for the highest such value among the live copied buffers that has not completed. A consumer on any queue therefore runs after every refresh enqueued before it, wherever that refresh came from. So when one CPU write is followed by submissions on two queues, both read the new bytes, even if the first is still held behind a title fence. + - **Producer wait.** A refresh's copy is also ordered behind earlier GPU access to the backing. Simultaneous access allows concurrent operations on one buffer only on disjoint ranges, so the copy must not overlap an earlier submission that still reads or writes it. Each queue wrapper signals a user fence of its own after the title's lists. Before a refresh's copy executes, the internal queue `Wait`s for every queue's latest user fence value that has not completed (`producer_waits`). The wrappers cannot tell which buffers a submission reads, because titles bind them by GPU virtual address, so every earlier submission counts as a user of every copied backing. This conservative choice can idle the GPU between a frame's submissions and the next refresh. + - **Unsafe refresh refused.** A submission whose refresh has no safe completion order is refused (`unsafe_refresh_refusals`, logged). That is the case when the refresh would have to wait for an earlier submission, on any queue including its own, that sits behind a title `Wait` (queue slot 17) on a fence that has not been reached, or for one whose user fence `Signal` failed. Waiting could deadlock: the fence may be signalled only by work that itself waits for the refresh, such as queue 2 signalling a fence that queue 1 waits on. Not waiting would let the copy overlap that read, because the blocked queue is not known to stay blocked until the copy finishes; the CPU or another queue may reach the fence meanwhile. The decision is made right before the refresh would be enqueued, and nothing of the submission reaches the GPU: no refresh, no consumer `Wait`, none of the title's lists and no user fence `Signal`. The staging buffers and refresh list are free again, no buffer's upload record or refresh state changes, and a recorded copy's GPU write stays pending on its recording. The next submission copies whatever still differs. The title's own `Signal` and `Wait` on its queues do not pass through this path, so a later `Signal` still releases the earlier queue. A submission with no changed bytes is never refused. A title `Wait` issued on the desktop queue past the wrapper is not seen, and that queue is waited for. + - **Queue order lock.** A title can call slot 17 and `ExecuteCommandLists` on one queue from two threads at once. Each queue's linear-buffer record has an order lock, so the record of which submissions sit behind which title `Wait` matches the desktop queue's order. Slot 17 holds it from the desktop `Wait` through recording that `Wait`. A submission holds it from the title's `ExecuteCommandLists` through its user fence `Signal`, before `draw_lock` and `allocator_lock` in render mode. Without it, a submission could reach the desktop queue behind a `Wait` but take its user value before that `Wait` was recorded. Another queue's refresh would then wait for that blocked submission instead of being refused. The lock is not held across the refresh, so staging waits and fixture pauses run without it. Nothing under it waits on the CPU for the GPU. The title's `Signal` does not take it, so a queue whose submission was refused can still signal the fence its blocked peer waits on. + - **Own refresh.** A submission also waits for the refresh it enqueued itself, even if the title released that buffer meanwhile. + - **Staging reuse.** A staging buffer is reused only after the internal fence value of the copy that read it has completed. + - **No internal queue.** If the internal queue or its fence cannot be created, copied placements keep the default backing with that HRESULT recorded. + - In render mode the refresh and the consumer `Wait` run before the wrapper takes its draw and allocator locks, so they precede every list of the submission, including the producer fences `red_producers` adds and each split submission of mesh XMem recordings. + - Budgets (`X2W_D3D12_BUDGET=1`) count the linear backings as the default backing counts its own. A shared buffer counts as placed memory on its heap, whose backing-heap ticket is in use while a buffer on it is held. A copied buffer counts as a committed buffer. Staging buffers count as upload memory and live for the process. + - A copied buffer that a recorded copy writes (list `CopyBufferRegion` or `CopyResource`, `list_copy.inl`) keeps the GPU's bytes once that recording is submitted and is no longer refreshed, as the default backing behaves for it. The title memory never receives those bytes, and a refresh spanning them would copy older title bytes over them. Info and totals report it (`gpu_written`). Until the submission the write is pending on the recording, with the texture writes of `list_copy.inl`: a `Reset` or a failed `Close` drops it, and the buffer stays refreshed. The recording's own submission still refreshes the buffer first, and its queue waits for that refresh before the copy runs. + - **Publish order.** Two submissions on different threads can stage one buffer's bytes at different times and execute their copies in one order but publish the upload record in the other. A buffer remembers the internal fence value of its newest applied publish. An older publish that arrives after a newer one drops the record (`reordered_publishes`), and the next submission copies the whole buffer. + - **Title memory reads.** Every live copied buffer is snapshotted, not only those the submitted lists read. Its title memory is probed again right before it is staged, and staged under a fault guard. A buffer whose memory the title freed after the snapshot is skipped and counted (`unreadable`); a read that faults anyway is counted (`copy_faults`) and fails that buffer's refresh. A buffer released after the snapshot whose pages are still mapped is staged for that submission, which may read it. + - The lock that guards the backing is held only to choose and publish. Waiting for a staging fence (a full pool), creating staging or a refresh list, recording it and `ExecuteCommandLists` all happen without it. A `Release`, the fixture exports and another queue's submission therefore never wait behind them. +- Kept default: where neither path keeps its guarantees, slot 133 keeps the default backing above and returns what it returns without the switch. On the console `CreatePlacedResourceX` does not fail, and a title that received a failure faulted on the null object. The refusal HRESULT is recorded instead: + - a GPU-written use (`ALLOW_UNORDERED_ACCESS`) that cannot be shared records the sharing HRESULT, or `DXGI_ERROR_UNSUPPORTED` when sharing was not attempted. The copy has no point at which GPU writes reach title memory; + - without the internal refresh queue: `E_NOT_VALID_STATE` (`0x8007139f`) under `X2W_TEST_SUBMIT_FENCE_FAIL=1`, else the HRESULT of creating the queue or its fence; + - when the copy's default buffer cannot be created, that HRESULT; + - when the mesh XMem lease path is on (`X2W_MESH86_XMEM_SRV` or `X2W_MESH_INDIRECT_XMEM`) and the placement is one it takes: XMem pages (`MEM_MAPPED`) with console flags 0. `HRESULT_FROM_WIN32(ERROR_BUSY)` (`0x800700aa`) means the placement was deferred to the lease path, which mirrors and publishes that default copied placement. The two never back one placement. +- A submission whose refresh cannot be staged still runs. This happens when the staging pool stays full of in-flight buffers past a 5 s wait (`DXGI_ERROR_WAS_STILL_DRAWING`) or when staging cannot be created. That buffer keeps its last upload and is reported stale until a later refresh succeeds. The first failures are logged (`x2w-d3d12 linear buffers: refresh of <resource> failed <hr>; the submission runs with its last upload (stale)`) and every one is counted. + +A shared or copied placement logs `x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer ... existing-heaps=<hr> share=<hr> -> <hr> shared|copied at submit`. A kept default logs the usual slot 133 line with `(kept default backing: linear refusal <hr>, use=... type=... existing-heaps=<hr> share=<hr>)` appended. `x2w_d3d12_linear_buffer_info` reports path 3 with `refusal_hr`, and `stale`, `refresh_failures` and `last_refresh_hr` for a copied buffer. A refused submission logs `x2w-d3d12 linear buffers: submission on queue <queue> refused: its refresh would have to wait for queue <queue> (<reason>), so it has no safe completion order; none of its lists ran` (the first eight). `x2w_d3d12_linear_buffer_totals` counts `kept_default`, `refresh_failures` and `unsafe_refresh_refusals`. Fixtures read the same facts through `x2w_d3d12_linear_buffer_info` and `x2w_d3d12_linear_buffer_totals` (`src/startup_stubs/linear_buffer_report.h`). Fixture-only switches: `X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1` makes the feature query report no support, as an adapter with `EXISTING_HEAPS = 0` does. `X2W_TEST_LINEAR_REFRESH_FAIL=<n>` makes staging requests 2, 2 + n, 2 + 2n and so on fail with `E_OUTOFMEMORY`. `X2W_TEST_LINEAR_STAGING_LIMIT=<n>` shrinks the staging pool from 256 buffers to `n`. `x2w_d3d12_linear_buffer_internal_queue` hands fixtures the internal queue, so they can hold refreshes in flight behind a fence of their own. `x2w_d3d12_linear_buffer_test_pause` parks the next refresh at one point (before staging, after staging, or after its copy executed and before it is published), so a fixture can order two threads' refreshes or release a buffer while one is parked. Point 3 instead parks the next title `Wait` (queue slot 17) after the desktop `Wait` and before it is recorded, while it holds that queue's order lock. `X2W_TEST_LINEAR_BUFFER_MUTANT=<name>` removes one guarantee for a negative control. Results and commands: [Production slice: slot 133 linear buffers](experiments.md#production-slice-slot-133-linear-buffers-1914). + +Not covered: table SRVs of copied buffers in translated draws still take `frame_copy` at record, and root SRVs (`list_root_srv`) still take `upload_from_title` at bind. Neither reads the slot 133 backing. Shared buffers and their heaps live for the process, like every wrapper, so a private range under one cannot be released. + ## Buffer memory SRVs (device slot 70) Device slot 70 (`src/startup_stubs/d3d12_memory_srv.inl`, validation in diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 292937af1..f92272d09 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -40,6 +40,7 @@ #include "startup_stubs/resource_address_index.h" #include "startup_stubs/placed_build.h" #include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/linear_buffer_backing.h" #include "startup_stubs/memory_srv_report.h" #include "startup_stubs/memory_srv_census.h" #include "startup_stubs/memory_srv_as.h" @@ -964,6 +965,13 @@ HRESULT __stdcall query_interface(Wrapper* self, const GUID* iid, void** out) return hr; } ULONG __stdcall add_ref(Wrapper* self) { return static_cast<ULONG>(InterlockedIncrement(&self->own().refs)); } +// X2W_D3D12_LINEAR_BUFFERS (opt-in): the shared or copied backing of slot 133's linear buffers +// (src/startup_stubs/linear_buffer_backing.h). Unused while the switch is off. +x2w_startup::LinearBuffers& linear_buffers() +{ + static x2w_startup::LinearBuffers buffers; + return buffers; +} // The wrappers and their desktop objects stay alive for the process (experiment scope). The one exception is // X2W_D3D12_RELEASE_RETIRED=1: the desktop object of a resource of the retire class is freed once nothing refers to it. // The wrapper stays. @@ -996,6 +1004,8 @@ ULONG __stdcall release(Wrapper* self) drop_mesh_lease_owner(self); retire_placement(self); if (self->own().retire_when_idle) retire_note_title_release(self); + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().retire(static_cast<ID3D12Resource*>(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { discard_mesh_lease_recording(static_cast<ID3D12CommandList*>(self->own().real)); @@ -1595,6 +1605,40 @@ extern "C" __declspec(dllexport) void x2w_d3d12_render_target_stats(unsigned* bi if (unresolved) *unresolved = static_cast<unsigned>(InterlockedCompareExchange(&render_target_unresolved, 0, 0)); } +// Fixtures (X2W_D3D12_LINEAR_BUFFERS): how slot 133 backed a linear buffer (false: the default backing, or +// not a placed buffer), and the totals since the process started. +extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_info(void* resource, X2wLinearBufferInfo* info) +{ + Wrapper* w = as_wrapper(resource); + if (!info || !w || w->own().kind != resource_kind || !w->own().real || + x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + return false; + return linear_buffers().info(static_cast<ID3D12Resource*>(w->own().real), info); +} +extern "C" __declspec(dllexport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals* totals) +{ + if (!totals) return; + *totals = X2wLinearBufferTotals{}; + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().totals(totals); +} +// Fixtures: the next refresh that reaches `point` (0 before staging, 1 after the title bytes are staged, +// 2 after its copy was executed, before it is published), or for point 3 the next title Wait (queue slot 17) +// after its desktop Wait and before it is recorded, sets the `reached` event, then waits up to 20 s for +// `resume`. Null events disarm the point. False with the switch off or for an unknown point. +extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_test_pause(unsigned point, void* reached, void* resume) +{ + return x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off && + linear_buffers().arm_pause(point, static_cast<HANDLE>(reached), static_cast<HANDLE>(resume)); +} +// Fixtures: the internal queue that runs every refresh (AddRef'd), so a fixture can hold refreshes in +// flight behind a fence of its own. False before the first copied placement. +extern "C" __declspec(dllexport) bool x2w_d3d12_linear_buffer_internal_queue(void** queue) +{ + if (!queue) return false; + *queue = x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off ? nullptr : linear_buffers().internal_queue(); + return *queue != nullptr; +} + // Fixtures: the number of desktop allocators a title allocator stands for (0 if it has none yet). extern "C" __declspec(dllexport) unsigned x2w_d3d12_allocator_pool_size(void* allocator) { @@ -3602,6 +3646,32 @@ bool console_layout_srv(const D3D12_RESOURCE_DESC& desc); #include "startup_stubs/d3d12_compute_binding_trace.inl" #include "startup_stubs/list_copy_texture.inl" +// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers are refreshed from title memory on the internal +// refresh queue, and queue waits for those refreshes, just before the title's lists. A refresh that +// fails leaves that buffer stale (logged, counted); the lists run either way. False: a refresh had no +// safe completion order and the submission is refused (logged, counted): nothing was enqueued, and the +// caller drops the title's lists without executing them or committing their bookkeeping. The title's +// fence Signal and Wait on its queues stay as they are, so a later Signal still releases a queue that +// waits on it. +bool linear_refresh(ID3D12CommandQueue* queue) +{ + return x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off || linear_buffers().before_submit(queue); +} +// After the title's lists on queue: a later refresh's copy waits for this submission (the producer wait). +void linear_submitted(ID3D12CommandQueue* queue) +{ + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().after_submit(queue); +} +// The queue's order lock (linear_buffer_backing.h), so its title waits and user fence values are recorded in +// the order the desktop queue receives them: held by a submission from its ExecuteCommandLists through +// linear_submitted, and by queue slot 17 from the desktop Wait through note_title_wait. Taken before +// draw_lock and allocator_lock and with no other lock held; nothing while the switch is off. +x2w_startup::LinearBuffers::QueueOrder linear_queue_order(ID3D12CommandQueue* queue, bool title_wait) +{ + if (x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) return {}; + return linear_buffers().queue_order(queue, title_wait); +} + // Queue slot 10, desktop ExecuteCommandLists(count, lists). void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) { @@ -3612,6 +3682,14 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) // A closed list stays submittable until its next Reset, as on the desktop. std::vector<ID3D12CommandList*> ready; std::vector<Wrapper*> submitted; + auto* queue = static_cast<ID3D12CommandQueue*>(self->own().real); + // Before the wrapper's locks: a refresh may wait for a staging fence, and recording must not + // wait with it. A refused submission runs nothing: its recordings stay closed and submittable, + // with their pending GPU writes (committed only after an executed submission). + if (count && !linear_refresh(queue)) return; + // From here through linear_submitted, a title Wait on this queue (slot 17) on another thread is + // recorded either before this submission's user value or after it, as the desktop queue gets them. + auto order = linear_queue_order(queue, false); // Pin the closed recording and its allocator through submission bookkeeping. AcquireSRWLockExclusive(&draw_lock); AcquireSRWLockExclusive(&allocator_lock); @@ -3622,7 +3700,6 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) submitted.push_back(w); } } - auto* queue = static_cast<ID3D12CommandQueue*>(self->own().real); bool split = false; const auto submit = [&](const auto& native_lists, const auto& wrappers) { const UINT ready_count = static_cast<UINT>(native_lists.size()); @@ -3660,8 +3737,10 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) } else if (!ready.empty()) { submit(ready, submitted); } + if (!ready.empty()) linear_submitted(queue); ReleaseSRWLockExclusive(&allocator_lock); ReleaseSRWLockExclusive(&draw_lock); + order.release(); check_device("CommandQueue execute", 35); return; } @@ -3672,7 +3751,13 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) // No hold or flight is recorded here: the copy handlers that create holds exist only in render mode. std::vector<ID3D12CommandList*> real(count); for (UINT i = 0; i < count; ++i) real[i] = reinterpret_cast<ID3D12CommandList*>(unwrap(reinterpret_cast<u64>(lists[i]))); - static_cast<ID3D12CommandQueue*>(self->own().real)->ExecuteCommandLists(count, real.data()); + auto* queue = static_cast<ID3D12CommandQueue*>(self->own().real); + if (!linear_refresh(queue)) return; + { + const auto order = linear_queue_order(queue, false); // as in render mode above + queue->ExecuteCommandLists(count, real.data()); + if (count) linear_submitted(queue); + } if (first_calls(calls)) log("x2w-d3d12 CommandQueue::ExecuteCommandLists count=%u", count); } @@ -3788,7 +3873,17 @@ u64 __stdcall queue_wait(Wrapper* self, u64 rdx, u64 r8, u64 r9) Wrapper* fence = as_wrapper(reinterpret_cast<void*>(rdx)); if (!fence || fence->own().kind != fence_kind) return queue_dynamic<17>(self, rdx, r8, r9); InterlockedExchange(&self->own().queue_wait_seen, 1); - const HRESULT hr = static_cast<ID3D12CommandQueue*>(self->own().real)->Wait(static_cast<ID3D12Fence*>(fence->own().real), r8); + auto* queue = static_cast<ID3D12CommandQueue*>(self->own().real); + // X2W_D3D12_LINEAR_BUFFERS: until this wait is reached, a submission whose refresh would have to wait for a + // submission behind it is refused. The queue's order lock spans the desktop Wait and its record, so a + // submission on this queue from another thread takes its user value wholly before or after both. + HRESULT hr; + { + const auto order = linear_queue_order(queue, true); + hr = queue->Wait(static_cast<ID3D12Fence*>(fence->own().real), r8); + if (SUCCEEDED(hr) && x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) + linear_buffers().note_title_wait(queue, static_cast<ID3D12Fence*>(fence->own().real), r8); + } static LONG calls; if (first_calls(calls, 2)) log("x2w-d3d12 CommandQueue::slot17(fence=%p, value=0x%llx) -> Wait 0x%08lx", static_cast<void*>(fence), r8, @@ -4311,6 +4406,40 @@ IndirectAddressAlias indirect_address_alias(Wrapper* device, u64 address, u64 by } volatile LONG64 placed_buffer_calls, placed_buffer_region_info, placed_buffer_queries; // five-second totals +// Wraps a placed buffer's desktop resource and publishes it in the placement index. aliased: the +// resource reads and writes the title memory itself, placed on a heap whose budget is backing_budget +// (or none); otherwise it is a committed default buffer. +HRESULT publish_placed_buffer(Wrapper* self, void* address, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, + ID3D12Resource* resource, bool aliased, x2w_budget::Ticket* backing_budget, void** out) +{ + Wrapper* w = wrap(resource, resource_kind); + if (release_retired_enabled()) w->own().retire_never = static_cast<std::uint8_t>(RetireNever::buffer); + w->own().title_memory = address; + const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; + auto& group = placement_group(desc->Width); + const HRESULT hr = x2w_startup::publish_placement(note_lock, resource_infos, group.by_start, group.max_width, + static_cast<const Wrapper*>(w), reinterpret_cast<u64>(address), record, [&] { index_resource(w, record); }); + if (FAILED(hr)) { + // The caller has never received this wrapper; release its desktop resource and storage. + AcquireSRWLockExclusive(®istry_lock); + registry().erase(w); + ReleaseSRWLockExclusive(®istry_lock); + if (x2w_startup::linear_buffer_mode() != x2w_startup::LinearBufferMode::off) linear_buffers().discard(resource); + resource->Release(); + _aligned_free(&w->own()); + return hr; + } + if (aliased) { + w->own().budget = x2w_budget::resource(device_of(self), resource, x2w_budget::placed); + w->own().backing_budget = backing_budget; + if (backing_budget) backing_budget->begin_use(); + } else { + w->own().budget = x2w_budget::committed(device_of(self), resource, D3D12_HEAP_TYPE_DEFAULT); + } + *out = w; + return S_OK; +} + HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3D12_RESOURCE_DESC* desc, UINT state, const void* clear, const GUID* iid, void** out) { @@ -4383,6 +4512,37 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 if (initial_state != D3D12_RESOURCE_STATE_COMMON && !(desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return E_INVALIDARG; const UINT64 offset = static_cast<char*>(address) - static_cast<char*>(base); + // X2W_D3D12_LINEAR_BUFFERS=1 or copy: shared or copied at submit (linear_buffer_backing.h). Where + // neither keeps its guarantees, the default backing below is kept and the refusal recorded. + X2wLinearBufferInfo linear{}; + char linear_note[160] = ""; + if (x2w_startup::LinearBuffers::eligible(*desc, initial_state)) { + const bool uav = (sanitized(*desc).Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) != 0; + ID3D12Resource* resource = nullptr; + bool shared = false; + x2w_budget::Ticket* linear_heap_budget = nullptr; + // The mesh XMem lease path takes the default (copied) placements of XMem pages whose console flags + // are 0 (note_mesh_xmem_write); while it is on, the linear backing defers to it there. + const bool lease_owns = mesh_xmem_tracking() && range.type == MEM_MAPPED && desc->Flags == D3D12_RESOURCE_FLAG_NONE; + const HRESULT placed = lease_owns ? x2w_startup::LinearBuffers::defer(uav, &linear) + : linear_buffers().place(device_of(self), address, desc->Width, uav, range, &resource, + &shared, &linear_heap_budget, &linear); + if (SUCCEEDED(placed)) { + log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) linear buffer address=%p base=%p type=0x%lx offset=0x%llx " + "width=0x%llx flags=0x%x use=%s existing-heaps=0x%08lx share=0x%08lx -> 0x%08lx %s gpuva=0x%llx", address, base, + static_cast<unsigned long>(range.type), offset, desc->Width, desc->Flags, uav ? "gpu-written" : "gpu-read", + static_cast<unsigned long>(linear.feature_hr), static_cast<unsigned long>(linear.share_hr), + static_cast<unsigned long>(placed), shared ? "shared" : "copied at submit", resource->GetGPUVirtualAddress()); + // Budgets as for the default backing: a shared buffer is a placed resource on its heap, a copied + // one a committed default buffer (its staging is counted as upload memory when it is created). + return publish_placed_buffer(self, address, desc, initial_state, resource, shared, linear_heap_budget, out); + } + if (x2w_startup::LinearBuffers::report_refusals()) + std::snprintf(linear_note, sizeof(linear_note), + " (kept default backing: linear refusal 0x%08lx, use=%s type=0x%lx existing-heaps=0x%08lx share=0x%08lx)", + static_cast<unsigned long>(placed), uav ? "gpu-written" : "gpu-read", static_cast<unsigned long>(range.type), + static_cast<unsigned long>(linear.feature_hr), static_cast<unsigned long>(linear.share_hr)); + } ID3D12Heap* heap = nullptr; x2w_budget::Ticket* backing_budget = nullptr; HRESULT hr = S_OK; @@ -4431,34 +4591,11 @@ HRESULT __stdcall device_place_resource_x(Wrapper* self, void* address, const D3 placement = "not aliased"; } log("x2w-d3d12 Device::slot133(CreatePlacedResourceX?) address=%p base=%p offset=0x%llx width=0x%llx flags=0x%x " - "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx", address, base, offset, desc->Width, desc->Flags, state, - clear, text, static_cast<unsigned long>(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull); + "state=0x%x clear=%p riid=%s -> 0x%08lx %s gpuva=0x%llx%s", address, base, offset, desc->Width, desc->Flags, state, + clear, text, static_cast<unsigned long>(hr), placement, resource ? resource->GetGPUVirtualAddress() : 0ull, linear_note); if (FAILED(hr)) return hr; - Wrapper* w = wrap(resource, resource_kind); - if (release_retired_enabled()) w->own().retire_never = static_cast<std::uint8_t>(RetireNever::buffer); - w->own().title_memory = address; - const ResourceInfo record{*desc, desc->Width, aliased ? Placement::aliased_buffer : Placement::copied_buffer, self, initial_state}; - auto& group = placement_group(desc->Width); - hr = x2w_startup::publish_placement(note_lock, resource_infos, group.by_start, group.max_width, - static_cast<const Wrapper*>(w), reinterpret_cast<u64>(address), record, [&] { index_resource(w, record); }); - if (FAILED(hr)) { - // The caller has never received this wrapper; release its desktop resource and storage. - AcquireSRWLockExclusive(®istry_lock); - registry().erase(w); - ReleaseSRWLockExclusive(®istry_lock); - resource->Release(); - _aligned_free(&w->own()); - return hr; - } - if (aliased) { - w->own().budget = x2w_budget::resource(device_of(self), resource, x2w_budget::placed); - w->own().backing_budget = backing_budget; - if (backing_budget) backing_budget->begin_use(); - } else { - w->own().budget = x2w_budget::committed(device_of(self), resource, D3D12_HEAP_TYPE_DEFAULT); - } - *out = w; - return S_OK; + if (linear.path == x2w_startup::LinearBuffers::kept_default_path) linear_buffers().kept_default(resource, linear); + return publish_placed_buffer(self, address, desc, initial_state, resource, aliased, backing_budget, out); } #include "d3d12_memory_srv.inl" diff --git a/src/startup_stubs/linear_buffer_backing.h b/src/startup_stubs/linear_buffer_backing.h new file mode 100644 index 000000000..929a7eca8 --- /dev/null +++ b/src/startup_stubs/linear_buffer_backing.h @@ -0,0 +1,1256 @@ +#pragma once + +// Opt-in backing for one ordinary linear buffer kind placed at a title address (#1914, #874): +// device slot 133 (CreatePlacedResourceX) with a buffer description, row-major or unknown layout, +// and initial state COMMON. The title writes it with the CPU and the GPU reads it (vertex, index, +// constant, shader-resource or indirect-argument data). X2W_D3D12_LINEAR_BUFFERS selects it: +// +// unset or 0 the default: slot 133 keeps its backing (an existing heap cached by allocation +// base for a private range, otherwise a committed default buffer that does not alias +// the title memory and holds zeros). Nothing in this file runs. +// 1 share when the adapter, the extent and the use allow it, else copy, else keep the +// default backing and record why. +// copy never share; copy, else keep the default backing and record why. +// +// XMem owns the title memory (identity, mapping, offsets, lifetime); this file owns the desktop +// backing and the fences that say when the GPU is done with it. +// +// Share. Only when D3D12_FEATURE_EXISTING_HEAPS reports support (queried once per device, before +// any open), the whole buffer lies in one committed private allocation (MEM_PRIVATE) at a 64 KiB- +// aligned offset, and the opened heap covers it. The heap is cached by allocation base, as the +// default backing caches it: while it is open the range cannot be released or decommitted +// (VirtualFree fails with error 87, measured in #1942), so a later allocation cannot appear at that +// base under it. Each opened heap gets a generation. The GPU reads and writes the title memory +// itself; nothing is copied. +// +// An XMem view (MEM_MAPPED) is not shared: a heap opened from a view keeps it mapped, and XMem's +// unmap of those pages then fails with error 87 (tests/linear_buffer_backing_check.cpp measures it). +// Desktop resources live for the process, so the title could never unmap or free those pages again. +// Sharing reports HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) for a view and the buffer is copied. A +// buffer across several allocations, or at an unaligned offset, reports E_INVALIDARG. Both are +// decided without a D3D12 call. +// +// Copy. A committed default-heap buffer whose bytes are refreshed from the title memory at each +// submission through a command-queue wrapper, before the title's lists execute, never at bind or +// record. Only the bytes that differ from the last upload are copied, through an upload staging +// buffer. +// +// Every refresh runs on one internal COPY queue per device, which never waits on a title fence. A +// refresh's copy (staging -> backing) is executed there and signals an internal fence value; the +// buffer remembers the value of its last refresh. Every submission through a queue wrapper, on any +// queue type, first makes that queue Wait for the highest such value among the live copied buffers +// (when it has not completed yet). A consumer on any queue therefore runs after every refresh that +// was enqueued before it, wherever that refresh came from, so the bytes recorded as uploaded at +// enqueue are the bytes the consumer reads. A submission whose recording writes a copied buffer +// (gpu_written, below) is ordered behind that buffer's earlier refreshes by the same Wait. +// +// The refresh is ordered behind earlier GPU access too (the producer wait). Simultaneous access +// allows concurrent operations on one buffer from several queues only on disjoint ranges, so a copy +// into a backing must not overlap an earlier submission that still reads or writes it. After the +// title's lists, each queue wrapper signals a fence of its own (one per desktop queue); before a +// refresh's copy executes, the internal queue Waits for every such queue's latest value that has not +// completed (producer_waits in the totals). The wrappers cannot tell which buffers a submission +// reads (the title binds them by GPU virtual address in root arguments, views and descriptors), so +// every earlier submission counts as a user of every copied backing: the conservative choice. +// +// A submission whose refresh has no safe completion order is refused (unsafe_refresh_refusals, +// logged). That is the case when the refresh would have to wait for an earlier submission, on any +// queue including its own, that sits behind a title Wait (queue slot 17) on a fence that has not +// reached its value, or for a submission without a user fence value (its Signal failed). Waiting could +// deadlock: the fence may be signalled only by work that itself waits for this refresh (queue 1 waits on +// a fence that queue 2 signals after its lists, case xq.write; every later consumer waits for the +// refresh). Not waiting would let the copy overlap that read: a blocked queue is not known to stay +// blocked until the copy finishes, since another producer (the CPU, or another queue) may reach the +// fence while it runs. The decision is made under internal_mutex_, right before the refresh would be +// enqueued: nothing of the submission reaches the GPU, neither the refresh, nor the consumer Wait, nor +// the title's lists, nor the queue's user fence Signal after them (no value stands for lists that did +// not run). Bookkeeping stays as it was: the staging buffers and refresh list are free again, no +// buffer's upload record, refresh value, staleness or failure count changes, and a recorded copy's GPU +// write stays pending on its recording (list_copy.inl commits it only after an executed submission). The +// next submission compares the title memory with the same upload record and copies what still differs. +// The title's own Signal and Wait on its queues (slot 16 and any shape-dispatched Signal, slot 17) do not +// go through this file, so a later Signal still releases the earlier queue. A title Wait issued on the +// desktop queue past the wrapper is not seen, and that queue is waited for. A submission that has no +// changed bytes to refresh is never refused; it waits only for refreshes already enqueued, none of which +// waits for a blocked queue. +// +// The refusal is only as good as the record of which submissions sit behind which title Wait, and a +// title can call slot 17 and ExecuteCommandLists on one queue from two threads at once. Each queue's +// record therefore has an order lock (queue_order), so its title waits and user fence values are +// recorded in the order the desktop queue received them. Slot 17 holds it from the desktop Wait through +// note_title_wait; a submission holds it from the title's ExecuteCommandLists through after_submit's +// user fence Signal. Without it a submission could reach the desktop queue behind a Wait yet take its +// user value before that Wait was recorded, which would then count only later submissions as behind it: +// another queue's refresh would wait for the blocked submission instead of being refused. The lock is +// not held across the refresh (its staging waits and fixture pauses run without it), and nothing that +// waits on the CPU for the GPU runs under it, since a desktop Wait, ExecuteCommandLists and Signal only +// enqueue. The title's Signal (slot 16, or a shape-dispatched Signal) does not take it, so a queue whose +// submission was refused can still signal the fence its blocked peer waits on. The order is: a queue's +// order lock, then draw_lock and allocator_lock (render mode), then mutex_; mutex_ is never held while it +// is taken (queue_order looks the lock up under mutex_ and takes it after releasing mutex_). A refresh +// decision that runs while a Wait on another queue has been enqueued but not yet recorded is still safe: +// that Wait precedes only submissions whose user value is not yet assigned, and a refresh waits only for +// values already assigned. +// +// A staging buffer is reused only after the internal fence value of the copy that read it has +// completed (title fences do not matter: only that copy reads it). If the internal queue or its fence +// cannot be created, the copy cannot order its consumers: placements keep the default backing and +// record the refusal (below). +// +// Where neither path can keep its guarantees, slot 133 keeps the default backing and returns what it +// returns without this switch. A title on the console does not see CreatePlacedResourceX fail, so a +// failed call would be a new failure (a title run that took the null object faulted at 1.76 s). The +// refusal is recorded instead: in the slot 133 log line ("kept default backing: linear refusal +// 0x..."), in x2w_d3d12_linear_buffer_info (path 3 and refusal_hr) and in the totals (kept_default, +// last_refusal_hr). The refusals: +// - a GPU-written use (ALLOW_UNORDERED_ACCESS) that cannot be shared: the copy has no point at which +// GPU writes reach the title memory. refusal_hr is the sharing HRESULT, or DXGI_ERROR_UNSUPPORTED +// when sharing was not attempted (X2W_D3D12_LINEAR_BUFFERS=copy). +// - no internal refresh queue or fence (X2W_TEST_SUBMIT_FENCE_FAIL=1 gives E_NOT_VALID_STATE, else +// the HRESULT of creating them): consumers could not be ordered behind refreshes. +// - the copy's default buffer cannot be created: that HRESULT. +// - the XMem lease path is on (X2W_MESH86_XMEM_SRV or X2W_MESH_INDIRECT_XMEM) and the placement is one +// it takes: XMem pages (MEM_MAPPED) with console flags 0, kept as the default copied placement that +// the lease path mirrors and publishes. HRESULT_FROM_WIN32(ERROR_BUSY): deferred to that owner, so +// the two never back one placement. +// +// Title memory is read twice per refresh: compared with the last upload under mutex_ (after a probe), +// then staged without it. Every live copied buffer is snapshotted, not only those the submitted lists +// read (the wrappers cannot tell), so the title may release one on another thread in between and free +// or unmap its pages. Its memory is probed again right before it is staged, and staged under a fault +// guard: a buffer that is gone is skipped and counted (unreadable), a read that faults anyway is +// counted (copy_faults) and fails that buffer's refresh. A buffer released after the snapshot whose +// pages are still there is staged for that submission, which may read it. +// +// Apart from the unsafe refresh above, nothing is refused at submit: holding back a submission can +// leave a title waiting on its fences. When a copied buffer's refresh cannot be staged (a staging +// buffer or refresh list cannot be created, or the pool stays full of buffers in flight past a 5 s +// wait: DXGI_ERROR_WAS_STILL_DRAWING), the title's lists run with the backing's last upload. The +// buffer is marked stale until a later refresh succeeds; the HRESULT is logged (the first few times) +// and kept in the buffer's info and the totals (refresh_failures, last_refresh_hr). +// +// A copied buffer that a recorded copy writes (list CopyBufferRegion or CopyResource, list_copy.inl) +// keeps the GPU's bytes once that recording is submitted: it is no longer refreshed. The title memory +// never receives those bytes, and a later refresh that spans them would copy the title's older bytes +// over them. This is what the default backing does for such a buffer; info and totals report it +// (gpu_written). Until the submission the write is pending on the recording, with the texture writes +// of list_copy.inl: a Reset or a failed Close drops it, and the buffer stays refreshed. The recording's +// own submission still refreshes it first (its queue waits for that refresh, then the copy runs). +// +// Fixtures only: +// X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1 the feature query reports no support (an adapter such as +// Intel Gen9 reports EXISTING_HEAPS = 0). +// X2W_TEST_LINEAR_BUFFER_MUTANT=<name> removes one guarantee, for negative controls: +// skip-refresh the copy is taken at placement (bind) and never refreshed at submit +// reuse-early a staging buffer is reused without waiting for its fence +// copy-gpu-writes the copy path accepts a GPU-written use +// ignore-feature sharing is attempted although the feature query reports no support +// refusal-silent a kept default backing is not reported (no log text, info or totals) +// hold-lock the wait for a full staging pool keeps mutex_ held (other callers block) +// skip-consumer-wait submissions do not Wait for the internal fence (consumers race refreshes) +// refresh-gpu-written a copied buffer that a recorded copy wrote is still refreshed +// gpuw-at-record the buffer stops being refreshed when the copy is recorded, not when it is submitted +// skip-producer-wait a refresh does not Wait for earlier submissions (it may overwrite a backing in use) +// publish-out-of-order an older refresh's span is applied to `uploaded` after a newer one's +// copy-after-retire the title memory is not probed again right before it is staged (the fault guard +// then catches the read of a released buffer's freed pages) +// accept-unsafe-refresh a refresh with no safe completion order is enqueued without waiting for the +// blocked queue instead of refusing the submission (its copy may overlap that read) +// unlocked-title-wait queue slot 17 does not take the queue's order lock (a submission on another +// thread can take its user value between the desktop Wait and its record) +// x2w_d3d12_linear_buffer_test_pause parks the next refresh at one point (before staging, after +// staging, after its copy executed), so a fixture can order two +// threads' refreshes or release a buffer while one is parked; +// or the next title Wait between the desktop Wait and its record +// x2w_d3d12_linear_buffer_internal_queue returns the internal queue, so a fixture can hold refreshes +// X2W_TEST_LINEAR_STAGING_LIMIT=<n> the staging pool holds n buffers instead of 256 +// X2W_TEST_LINEAR_REFRESH_FAIL=<n> staging requests 2, 2 + n, 2 + 2n, ... fail with E_OUTOFMEMORY + +#include <windows.h> +#include <d3d12.h> + +#include <algorithm> +#include <atomic> +#include <cstdint> +#include <cstdlib> +#include <cstring> +#include <deque> +#include <memory> +#include <mutex> +#include <new> +#include <unordered_map> +#include <vector> + +#include "startup_stubs/linear_buffer_report.h" +#include "startup_stubs/local_log.h" +#include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/resource_budget.h" + +namespace x2w_startup { + +enum class LinearBufferMode { off, automatic, copy }; + +inline LinearBufferMode linear_buffer_mode() +{ + static const LinearBufferMode mode = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_D3D12_LINEAR_BUFFERS", value, sizeof(value)); + SetLastError(saved); + if (!n || n >= sizeof(value)) return LinearBufferMode::off; + if (std::strcmp(value, "1") == 0) return LinearBufferMode::automatic; + if (_stricmp(value, "copy") == 0) return LinearBufferMode::copy; + return LinearBufferMode::off; + }(); + return mode; +} + +namespace linear_detail { +inline bool mutant(const char* name) +{ + static char value[32] = {}; + static const bool read = [] { + const DWORD saved = GetLastError(); + const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", value, sizeof(value)); + if (n >= sizeof(value)) value[0] = 0; + SetLastError(saved); + return true; + }(); + (void)read; + return value[0] && std::strcmp(value, name) == 0; +} +inline bool existing_heaps_forced_off() +{ + static const bool on = x2w_local::env_on("X2W_TEST_EXISTING_HEAPS_UNSUPPORTED"); + return on; +} +inline unsigned refresh_fault_period() +{ + static const unsigned period = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_REFRESH_FAIL", value, sizeof(value)); + SetLastError(saved); + return n && n < sizeof(value) ? static_cast<unsigned>(std::strtoul(value, nullptr, 10)) : 0u; + }(); + return period; +} +inline bool submit_fence_forced_off() +{ + static const bool on = GetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", nullptr, 0) != 0; + return on; +} +// Copies title memory that may have been freed or unmapped since it was probed: false on an access +// violation or an in-page error instead of a fault in the DLL. +inline bool guarded_copy(void* to, const void* from, std::size_t bytes) noexcept +{ + __try { + std::memcpy(to, from, bytes); + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } + return true; +} +inline D3D12_RESOURCE_DESC buffer(UINT64 width, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = width; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_UNKNOWN; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} +} // namespace linear_detail + +class LinearBuffers { + struct Staging; + struct RefreshList; + +public: + enum Path : std::uint32_t { shared_path = 1, copied_path = 2, kept_default_path = 3 }; + enum Use : std::uint32_t { gpu_read = 1, gpu_written = 2 }; + + // The kind this file handles. Anything else keeps the default backing. + static bool eligible(const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES initial_state) + { + return linear_buffer_mode() != LinearBufferMode::off && desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && + (desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR || desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN) && + desc.Width && initial_state == D3D12_RESOURCE_STATE_COMMON; + } + + // The refusal recorded for a placement that another owner takes: the XMem lease path, which takes + // the default (copied) placements of XMem pages whose console flags are 0 while it is on. + static constexpr HRESULT lease_deferral = HRESULT_FROM_WIN32(ERROR_BUSY); + static HRESULT defer(bool uav, X2wLinearBufferInfo* report) + { + *report = X2wLinearBufferInfo{}; + report->use = uav ? gpu_written : gpu_read; + report->feature_hr = S_FALSE; + report->share_hr = S_FALSE; + report->path = kept_default_path; + report->refusal_hr = lease_deferral; + return lease_deferral; + } + + // False under the refusal-silent mutant: a kept default backing is then not reported anywhere. + static bool report_refusals() { return !linear_detail::mutant("refusal-silent"); } + + // Slot 133 for an eligible buffer. range is measure_placed_buffer's answer for (address, width) and + // uav says whether the desktop flags keep ALLOW_UNORDERED_ACCESS. On success *out holds the + // desktop resource and *shared whether it aliases the title memory; a shared one's heap budget + // (X2W_D3D12_BUDGET, or null) is in *backing_budget. A failure is a refusal: the caller keeps the + // default backing and passes *report (path kept_default_path) to kept_default(). + HRESULT place(ID3D12Device* device, void* address, UINT64 width, bool uav, const PlacedBufferRange& range, + ID3D12Resource** out, bool* shared, x2w_budget::Ticket** backing_budget, X2wLinearBufferInfo* report) + { + *out = nullptr; + *shared = false; + *backing_budget = nullptr; + std::lock_guard lock(mutex_); + ++totals_.placements; + Record record{}; + record.info.use = uav ? gpu_written : gpu_read; + record.info.feature_hr = S_FALSE; + record.info.share_hr = S_FALSE; + const UINT64 offset = static_cast<UINT64>(static_cast<char*>(address) - static_cast<char*>(range.base)); + ID3D12Resource* resource = nullptr; + if (linear_buffer_mode() == LinearBufferMode::automatic) { + record.info.feature_hr = feature(device); + const bool allowed = SUCCEEDED(record.info.feature_hr) || linear_detail::mutant("ignore-feature"); + if (!allowed) + record.info.share_hr = record.info.feature_hr; + else if (!range.covered || (offset & 0xFFFF)) + record.info.share_hr = E_INVALIDARG; // decided without D3D12: each failed open throws in D3D12Core + else if (range.type == MEM_MAPPED) + record.info.share_hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); // an open heap would pin the view + else if (range.type != MEM_PRIVATE) + record.info.share_hr = E_INVALIDARG; + else + record.info.share_hr = share(device, range, offset, width, uav, &resource, &record.info.heap_generation, + backing_budget); + } + HRESULT hr = S_OK; + if (SUCCEEDED(record.info.share_hr) && record.info.share_hr != S_FALSE) { + record.info.path = shared_path; + ++totals_.shared; + } else if (uav && !linear_detail::mutant("copy-gpu-writes")) { + hr = record.info.share_hr == S_FALSE ? DXGI_ERROR_UNSUPPORTED : record.info.share_hr; + } else if (const HRESULT internal = linear_detail::submit_fence_forced_off() ? E_NOT_VALID_STATE : internal_ready(device); + FAILED(internal)) { + hr = internal; + } else { + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const auto desc = linear_detail::buffer(width, uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + : D3D12_RESOURCE_FLAG_NONE); + hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&resource)); + if (SUCCEEDED(hr)) { + try { + record.copy = std::make_shared<Copied>(); + record.copy->title = static_cast<const unsigned char*>(address); + record.copy->bytes = width; + if (linear_detail::mutant("skip-refresh")) { + // Mutant: the bytes at placement are what every submission gets. + const std::size_t readable = x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(address), + static_cast<std::size_t>(width)); + record.copy->bound.assign(record.copy->title, record.copy->title + readable); + record.copy->bound.resize(static_cast<std::size_t>(width)); + } + } catch (const std::bad_alloc&) { + resource->Release(); + resource = nullptr; + hr = E_OUTOFMEMORY; + } + } + if (SUCCEEDED(hr)) { + record.info.path = copied_path; + ++totals_.copied; + } + } + if (SUCCEEDED(hr)) { + record.info.backing = resource; + try { + records_.emplace(resource, std::move(record)); + } catch (const std::bad_alloc&) { + hr = E_OUTOFMEMORY; + --(record.info.path == shared_path ? totals_.shared : totals_.copied); + } + } + if (FAILED(hr)) { + if (resource) resource->Release(); + *backing_budget = nullptr; + record.info.path = kept_default_path; + record.info.refusal_hr = hr; + record.info.backing = nullptr; + if (report) *report = record.info; + return hr; + } + const auto& stored = records_.at(resource).info; + if (report) *report = stored; + const bool is_shared = stored.path == shared_path; + *out = resource; + *shared = is_shared; + return S_OK; + } + + // Slot 133 kept the default backing for a refused placement: record why, for this resource. + void kept_default(ID3D12Resource* resource, const X2wLinearBufferInfo& report) + { + if (!report_refusals()) return; + std::lock_guard lock(mutex_); + ++totals_.kept_default; + totals_.last_refusal_hr = report.refusal_hr; + try { + Record record{}; + record.info = report; + record.info.path = kept_default_path; + record.info.backing = resource; + records_.insert_or_assign(resource, std::move(record)); + } catch (const std::bad_alloc&) { + } + } + + // A submitted recording writes the backing of `resource` (list_copy.inl, after its ExecuteCommandLists): + // if it is a copied buffer, it keeps the GPU's bytes from now on and is no longer refreshed from the + // title memory. + void note_gpu_write(ID3D12Resource* resource) + { + if (linear_detail::mutant("refresh-gpu-written")) return; + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + if (found == records_.end() || !found->second.copy || found->second.copy->gpu_written) return; + found->second.copy->gpu_written = true; + ++totals_.gpu_written; + if (x2w_local::first_calls(gpu_write_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffer %p: a recorded copy writes it; it keeps the GPU's bytes and is no " + "longer refreshed from title memory", static_cast<void*>(resource)); + } + + // The resource never reached the title and is about to be released. + void discard(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + records_.erase(resource); + } + + // The title released the resource: its memory is not read again. The desktop backing stays (as + // every wrapper's does); a shared one keeps its heap. + void retire(ID3D12Resource* resource) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + if (found == records_.end() || !found->second.copy) return; + found->second.copy->live = false; + std::vector<unsigned char>().swap(found->second.copy->uploaded); + } + + // Before the title's lists are executed on queue (the contract's copy point): refreshes every live + // copied buffer whose title bytes changed, on the internal queue, then makes queue wait for every + // refresh of a live copied buffer that has not landed yet. A buffer whose refresh fails keeps its last + // upload and is marked stale; the submission still runs. False: the refresh has no safe completion + // order (see the producer wait above) and the submission is refused: nothing was enqueued, and the + // caller must neither execute the title's lists nor call after_submit or commit their GPU writes. + // + // mutex_ is held only to read and publish state: the work is snapshotted under it, then staging + // is taken (and, with the pool full, its fence waited for), filled, recorded and executed without + // it, and the results are published under it again. A release() or another queue's submission + // therefore never waits behind a fence wait or ExecuteCommandLists here. internal_mutex_ only + // keeps the internal queue's ExecuteCommandLists and Signal in fence-value order (and the refusal + // decision next to them). + [[nodiscard]] bool before_submit(ID3D12CommandQueue* queue) + { + struct Work { + ID3D12Resource* dest; + std::shared_ptr<Copied> copy; + const unsigned char* source; + UINT64 offset, bytes; + Staging* staging = nullptr; + HRESULT hr = S_OK; + bool unreadable = false; // the title memory was gone when it was to be staged + bool faulted = false; // reading it faulted (caught) + }; + std::vector<Work> work; + { + std::lock_guard lock(mutex_); + ++totals_.submissions; + bool any = false; + for (auto& [resource, record] : records_) any |= record.copy && record.copy->live; + if (!any || !internal_queue_) return true; + for (auto& [resource, record] : records_) { + const std::shared_ptr<Copied>& copy = record.copy; + if (!copy || !copy->live || copy->gpu_written) continue; + const std::size_t bytes = static_cast<std::size_t>(copy->bytes); + const unsigned char* source = copy->bound.empty() ? copy->title : copy->bound.data(); + if (copy->bound.empty() && x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(source), bytes) < bytes) { + if (x2w_local::first_calls(unreadable_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffer %p: title memory %p is no longer readable; its backing " + "keeps the last upload", static_cast<void*>(resource), static_cast<const void*>(source)); + ++totals_.unreadable; + continue; + } + std::size_t first = 0, last = bytes; + if (copy->uploaded.size() == bytes) { + if (std::memcmp(copy->uploaded.data(), source, bytes) == 0) { + copy->stale = false; + continue; + } + while (first < bytes && copy->uploaded[first] == source[first]) ++first; + while (last > first && copy->uploaded[last - 1] == source[last - 1]) --last; + first &= ~std::size_t{3}; + last = (std::min)(bytes, (last + 3) & ~std::size_t{3}); + } + try { + work.push_back({resource, copy, source, first, last - first}); + } catch (const std::bad_alloc&) { + refresh_failed(resource, *copy, E_OUTOFMEMORY); + } + } + } + // This submission's own refreshes, including those of a buffer the title released meanwhile. + bool refused = false; + const UINT64 own = work.empty() ? 0 : refresh(work, queue, &refused); + if (refused) return false; + + // Order this submission behind every refresh of a live copied buffer that may not have landed. + UINT64 wait_for = own; + { + std::lock_guard lock(mutex_); + for (auto& [resource, record] : records_) + if (record.copy && record.copy->live && record.copy->refresh_value > wait_for) wait_for = record.copy->refresh_value; + if (wait_for && internal_fence_->GetCompletedValue() < wait_for && !linear_detail::mutant("skip-consumer-wait")) + ++totals_.consumer_waits; + else + wait_for = 0; + } + if (wait_for) { + const HRESULT hr = queue->Wait(internal_fence_, wait_for); + if (FAILED(hr) && x2w_local::first_calls(wait_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffers: queue %p could not wait for refresh 0x%llx (0x%08lx)", + static_cast<void*>(queue), static_cast<unsigned long long>(wait_for), static_cast<unsigned long>(hr)); + } + return true; + } + + // After the title's lists were executed on `queue` (a queue wrapper): signals that queue's user fence, + // so a later refresh can be ordered behind this submission (the producer wait). Nothing before the + // first copied placement: earlier submissions cannot name a copied backing that did not exist yet. + // Not called for a refused submission: its lists did not run, so no user value stands for them. The + // caller holds the queue's order lock from its ExecuteCommandLists through this call. + void after_submit(ID3D12CommandQueue* queue) + { + std::lock_guard lock(mutex_); + if (!internal_queue_) return; + UserQueue* user = user_queue(queue); + if (!user) return; + if (!user->fence && !user->untracked) { + ID3D12Device* device = nullptr; + HRESULT hr = queue->GetDevice(IID_PPV_ARGS(&device)); + if (SUCCEEDED(hr)) { + hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&user->fence)); + device->Release(); + } + if (FAILED(hr)) { + user->fence = nullptr; + x2w_local::logf("x2w-d3d12 linear buffers: queue %p has no user fence (0x%08lx); refreshes cannot wait for " + "its submissions", static_cast<void*>(queue), static_cast<unsigned long>(hr)); + } + } + if (!user->fence || FAILED(queue->Signal(user->fence, user->value + 1))) { + // This submission cannot be waited for: a refresh that would have to wait for it is refused until + // the queue's next submission has a value (which then covers this one). + user->untracked = true; + return; + } + user->untracked = false; + ++user->value; + } + + // The title enqueued Wait(fence, value) on `queue` (queue slot 17, already forwarded). Recorded until the + // fence reaches the value: a refresh that would have to wait for a submission behind it is refused (see + // the producer wait). The caller holds the queue's order lock from the desktop Wait through this call. + void note_title_wait(ID3D12CommandQueue* queue, ID3D12Fence* fence, UINT64 value) + { + pause_at(pause_title_wait); + if (!fence || fence->GetCompletedValue() >= value) return; + std::lock_guard lock(mutex_); + UserQueue* user = user_queue(queue); + if (!user) return; + prune_waits(*user); + try { + user->waits.push_back({fence, value, user->value + 1}); + fence->AddRef(); + } catch (const std::bad_alloc&) { + // Not remembered with its fence: the queue's submissions from the next one on count as blocked until + // that next one completes (its user fence value passes the unknown wait). + if (!user->lost_wait_before) user->lost_wait_before = user->value + 1; + } + } + + // A queue's order lock, held until destroyed or release() (an empty one holds nothing). + class QueueOrder { + public: + QueueOrder() = default; + explicit QueueOrder(SRWLOCK* lock) : lock_(lock) + { + if (lock_) AcquireSRWLockExclusive(lock_); + } + QueueOrder(QueueOrder&& other) noexcept : lock_(other.lock_) { other.lock_ = nullptr; } + QueueOrder(const QueueOrder&) = delete; + QueueOrder& operator=(const QueueOrder&) = delete; + QueueOrder& operator=(QueueOrder&&) = delete; + ~QueueOrder() { release(); } + void release() + { + if (lock_) ReleaseSRWLockExclusive(lock_); + lock_ = nullptr; + } + + private: + SRWLOCK* lock_ = nullptr; + }; + + // Takes the order lock of `queue` (see the order lock above): queue slot 17 (title_wait) across the + // desktop Wait and note_title_wait, a queue wrapper's submission across the title's ExecuteCommandLists + // and after_submit. The caller holds none of this file's locks, nor draw_lock or allocator_lock. A queue + // whose record cannot be stored shares one fallback lock. + [[nodiscard]] QueueOrder queue_order(ID3D12CommandQueue* queue, bool title_wait) + { + // Mutant: slot 17 takes no lock, so a submission on another thread can take its user value between + // the desktop Wait and its record. + if (title_wait && linear_detail::mutant("unlocked-title-wait")) return QueueOrder{}; + SRWLOCK* lock = &order_fallback_; + { + std::lock_guard guard(mutex_); + if (UserQueue* user = user_queue(queue)) lock = &user->order; + } + return QueueOrder(lock); + } + + // Fixtures only (x2w_d3d12_linear_buffer_test_pause): the next refresh that reaches `point` sets + // `reached`, then waits up to 20 s for `resume`, holding no lock. One shot per arming. The points: + // before its staging (after the snapshot), after the title bytes are staged (before its copy is + // executed), and after the copy is executed and signalled (before it is published). The last point + // parks the next title Wait (queue slot 17) after the desktop Wait and before note_title_wait records + // it, holding that queue's order lock (and nothing else). Null events disarm the point, so a fixture can + // close its events when nothing came. + enum PausePoint : unsigned { pause_before_stage, pause_after_stage, pause_after_execute, pause_title_wait, pause_points }; + bool arm_pause(unsigned point, HANDLE reached, HANDLE resume) + { + if (point >= pause_points) return false; + std::lock_guard lock(pause_mutex_); + pauses_[point] = reached && resume ? Pause{reached, resume} : Pause{}; + if (pauses_[point].reached) pauses_armed_.store(true); + return true; + } + + // The internal queue, AddRef'd, for fixtures that hold refreshes in flight; null before the first + // copied placement. + ID3D12CommandQueue* internal_queue() + { + std::lock_guard lock(mutex_); + if (internal_queue_) internal_queue_->AddRef(); + return internal_queue_; + } + + bool info(ID3D12Resource* resource, X2wLinearBufferInfo* out) + { + std::lock_guard lock(mutex_); + const auto found = records_.find(resource); + if (found == records_.end()) return false; + *out = found->second.info; + if (const Copied* copy = found->second.copy.get()) { + out->refreshes = copy->refreshes; + out->bytes_copied = copy->bytes_copied; + out->last_staging = copy->last_staging; + out->last_fence = copy->refresh_value; + out->stale = copy->stale ? 1 : 0; + out->gpu_written = copy->gpu_written ? 1 : 0; + out->refresh_failures = copy->refresh_failures; + out->last_refresh_hr = copy->last_refresh_hr; + } + return true; + } + + void totals(X2wLinearBufferTotals* out) + { + std::lock_guard lock(mutex_); + *out = totals_; + } + +private: + struct Copied { + const unsigned char* title = nullptr; + UINT64 bytes = 0; + bool live = true; + std::vector<unsigned char> uploaded; // what the backing holds (empty before the first refresh) + std::vector<unsigned char> bound; // skip-refresh mutant: the bytes at placement + UINT64 refreshes = 0, bytes_copied = 0, last_staging = 0, refresh_failures = 0; + UINT64 refresh_value = 0; // internal fence value of the last enqueued refresh + UINT64 published_value = 0; // internal fence value of the newest refresh published into `uploaded` + bool stale = false; + bool gpu_written = false; // a recorded copy wrote it: not refreshed any more + HRESULT last_refresh_hr = S_OK; + }; + struct Record { + X2wLinearBufferInfo info{}; + std::shared_ptr<Copied> copy; // shared: a submission's snapshot outlives a discard + }; + struct Staging { + ID3D12Resource* buffer = nullptr; + unsigned char* mapped = nullptr; + UINT64 bytes = 0, id = 0; + ID3D12Fence* fence = nullptr; // the internal fence, whose value completes the copy that read it + UINT64 value = 0; // 0: free; ~0: in use with no signalled value + }; + struct RefreshList { + ID3D12CommandAllocator* allocator = nullptr; + ID3D12GraphicsCommandList* list = nullptr; + UINT64 value = 0; + }; + // A title Wait (queue slot 17) that had not completed when it was enqueued; `before` is the first user + // value it precedes. + struct TitleWait { + ID3D12Fence* fence; + UINT64 value, before; + }; + // A queue wrapper's desktop queue, its user fence (signalled after each submission of the title's + // lists), the title waits it may still sit behind and its order lock (queue_order). Kept for the + // process, as the queues are, at a stable address (users_ is a deque that only grows). + struct UserQueue { + SRWLOCK order = SRWLOCK_INIT; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; // the latest submission's user fence value (0: none yet) + bool untracked = false; // the latest submission has no fence value: it cannot be waited for + std::vector<TitleWait> waits; + UINT64 lost_wait_before = 0; // a title wait that could not be stored precedes this user value (0: none) + }; + struct Heap { + void* base; + ID3D12Heap* heap; + UINT64 generation, bytes; + x2w_budget::Ticket* budget; // the heap's budget ticket (X2W_D3D12_BUDGET), counted while a buffer uses it + }; + // 256 staging buffers; X2W_TEST_LINEAR_STAGING_LIMIT=<n> (fixtures) lowers it, to make the pool fill. + static std::size_t staging_limit() + { + static const std::size_t limit = [] { + const DWORD saved = GetLastError(); + char value[16]{}; + const DWORD n = GetEnvironmentVariableA("X2W_TEST_LINEAR_STAGING_LIMIT", value, sizeof(value)); + SetLastError(saved); + const unsigned long parsed = n && n < sizeof(value) ? std::strtoul(value, nullptr, 10) : 0; + return parsed ? static_cast<std::size_t>(parsed) : std::size_t{256}; + }(); + return limit; + } + + // A fixture's pause (arm_pause); nothing unless one was armed. + void pause_at(unsigned point) + { + if (!pauses_armed_.load()) return; + Pause pause{}; + { + std::lock_guard lock(pause_mutex_); + pause = pauses_[point]; + pauses_[point] = {}; + } + if (!pause.reached) return; + SetEvent(pause.reached); + WaitForSingleObject(pause.resume, 20000); + } + + // Under mutex_. The record of `queue`, created on first use; null if it cannot be stored. + UserQueue* user_queue(ID3D12CommandQueue* queue) + { + for (UserQueue& user : users_) + if (user.queue == queue) return &user; + try { + users_.emplace_back(); + } catch (const std::bad_alloc&) { + return nullptr; + } + users_.back().queue = queue; + return &users_.back(); + } + // Under mutex_: forgets the title waits whose fences reached their values, and a lost one once the first + // submission behind it completed. + static void prune_waits(UserQueue& user) + { + if (user.lost_wait_before && user.fence && user.value >= user.lost_wait_before && + user.fence->GetCompletedValue() >= user.lost_wait_before) + user.lost_wait_before = 0; + auto& waits = user.waits; + for (std::size_t i = 0; i < waits.size();) { + if (waits[i].fence->GetCompletedValue() >= waits[i].value) { + waits[i].fence->Release(); + waits[i] = waits.back(); + waits.pop_back(); + } else { + ++i; + } + } + } + // Under mutex_: the (user fence, value) of each queue's latest submission that has not completed, which + // a refresh's copy waits for, in *out. False when one of them has no safe completion order (behind an + // unreached title wait, or without a fence value): the refresh must not be enqueued and the submission is + // refused (see the producer wait above); *blocker and *why name the first such queue. bad_alloc + // propagates: a refresh that cannot list what it waits for is not enqueued either. + bool earlier_users(std::vector<std::pair<ID3D12Fence*, UINT64>>* out, ID3D12CommandQueue** blocker, const char** why) + { + bool safe = true; + for (UserQueue& user : users_) { + prune_waits(user); + const bool pending = user.fence && user.value && user.fence->GetCompletedValue() < user.value; + if (!pending && !user.untracked) continue; + const char* reason = user.untracked ? "its latest submission has no user fence value" : nullptr; + if (!reason && user.lost_wait_before && user.lost_wait_before <= user.value) + reason = "its latest submission is behind a title Wait that could not be recorded"; + for (const TitleWait& wait : user.waits) + if (!reason && wait.before <= user.value) reason = "its latest submission is behind a title Wait that has not completed"; + if (reason) { + // Mutant: the blocked queue is not waited for and the refresh goes ahead (it may overlap that read). + if (linear_detail::mutant("accept-unsafe-refresh")) continue; + if (safe) { + *blocker = user.queue; + *why = reason; + } + safe = false; + continue; + } + if (linear_detail::mutant("skip-producer-wait")) continue; + out->emplace_back(user.fence, user.value); + } + return safe; + } + + HRESULT feature(ID3D12Device* device) + { + if (feature_device_ != device) { + feature_device_ = device; + ++totals_.feature_queries; + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + const HRESULT hr = device->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps)); + feature_hr_ = FAILED(hr) ? hr + : heaps.Supported && !linear_detail::existing_heaps_forced_off() ? S_OK : DXGI_ERROR_UNSUPPORTED; + x2w_local::logf("x2w-d3d12 linear buffers (X2W_D3D12_LINEAR_BUFFERS=%s): D3D12_FEATURE_EXISTING_HEAPS -> 0x%08lx " + "supported=%d%s", linear_buffer_mode() == LinearBufferMode::copy ? "copy" : "1", + static_cast<unsigned long>(hr), heaps.Supported ? 1 : 0, + linear_detail::existing_heaps_forced_off() ? " (reported as unsupported: X2W_TEST_EXISTING_HEAPS_UNSUPPORTED)" : ""); + } + return feature_hr_; + } + + // A private range only (place() decides the rest). Its heap is opened once per allocation base and + // cached: the open heap keeps the range from being released, so the base cannot name other memory. + HRESULT share(ID3D12Device* device, const PlacedBufferRange& range, UINT64 offset, UINT64 width, bool uav, + ID3D12Resource** out, UINT64* generation, x2w_budget::Ticket** budget) + { + const Heap* entry = nullptr; + for (const Heap& known : heaps_) + if (known.base == range.base) entry = &known; + if (entry) { + ++totals_.heap_cache_hits; + } else { + ID3D12Device3* device3 = nullptr; + ID3D12Heap* heap = nullptr; + HRESULT hr = device->QueryInterface(IID_PPV_ARGS(&device3)); + if (SUCCEEDED(hr)) { + ++totals_.heap_opens; + hr = device3->OpenExistingHeapFromAddress(range.base, IID_PPV_ARGS(&heap)); + device3->Release(); + if (FAILED(hr)) ++totals_.heap_open_failures; + } + if (FAILED(hr)) return hr; + try { + heaps_.push_back({range.base, heap, ++generation_, heap->GetDesc().SizeInBytes, x2w_budget::backing_heap(heap, 0)}); + } catch (const std::bad_alloc&) { + heap->Release(); + return E_OUTOFMEMORY; + } + entry = &heaps_.back(); + } + *generation = entry->generation; + *budget = entry->budget; + if (entry->bytes < offset || width > entry->bytes - offset) return E_INVALIDARG; + const auto desc = linear_detail::buffer(width, static_cast<D3D12_RESOURCE_FLAGS>( + (uav ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE) | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER)); + const HRESULT hr = device->CreatePlacedResource(entry->heap, offset, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(out)); + if (FAILED(hr)) ++totals_.place_failures; + return hr; + } + + // The internal refresh queue and its fence, created once (under mutex_, from place()). + HRESULT internal_ready(ID3D12Device* device) + { + if (internal_queue_) return S_OK; + if (internal_tried_) return internal_hr_; + internal_tried_ = true; + const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_COPY}; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + internal_hr_ = device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)); + if (SUCCEEDED(internal_hr_)) internal_hr_ = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)); + if (FAILED(internal_hr_)) { + if (queue) queue->Release(); + x2w_local::logf("x2w-d3d12 linear buffers: the internal refresh queue could not be created (0x%08lx); copied " + "buffers keep the default backing", static_cast<unsigned long>(internal_hr_)); + return internal_hr_; + } + queue->SetName(L"x2w linear-buffer refresh"); + internal_device_ = device; + internal_queue_ = queue; + internal_fence_ = fence; + return S_OK; + } + + // Staging, the refresh list and the internal queue, without mutex_; then publish under it. + // Returns the internal fence value of the refresh it enqueued (0: none). *refused: the refresh had no + // safe completion order and nothing was enqueued or published (the submission on `queue` is refused). + template <class Work> + UINT64 refresh(std::vector<Work>& work, ID3D12CommandQueue* queue, bool* refused) + { + pause_at(pause_before_stage); + std::vector<Staging*> taken; + bool any_staged = false; + for (Work& w : work) { + w.hr = acquire_staging(w.bytes, taken, &w.staging); + if (FAILED(w.hr)) continue; + taken.push_back(w.staging); + // The snapshot probed the title memory under mutex_, but the title may have released this buffer + // since (any live buffer is snapshotted, not only those the lists read) and freed or unmapped its + // pages: probe again right before reading, and read under a fault guard. + const unsigned char* from = w.source + w.offset; + const auto bytes = static_cast<std::size_t>(w.bytes); + if (!linear_detail::mutant("copy-after-retire") && + x2w_local::probe_readable(reinterpret_cast<std::uintptr_t>(from), bytes) < bytes) { + w.unreadable = true; + w.hr = HRESULT_FROM_WIN32(ERROR_NOACCESS); + continue; + } + if (!linear_detail::guarded_copy(w.staging->mapped, from, bytes)) { + w.faulted = true; + w.hr = HRESULT_FROM_WIN32(ERROR_NOACCESS); + continue; + } + any_staged = true; + } + if (any_staged) pause_at(pause_after_stage); + RefreshList* list = nullptr; + HRESULT list_hr = S_OK; + bool executed = false; + UINT64 value = 0; + if (any_staged) { + list_hr = acquire_list(&list); + if (SUCCEEDED(list_hr)) { + // Buffers rest in COMMON: each copy promotes its destination to COPY_DEST on the internal + // queue, and it decays to COMMON again when this ExecuteCommandLists completes. + for (const Work& w : work) + if (SUCCEEDED(w.hr)) list->list->CopyBufferRegion(w.dest, w.offset, w.staging->buffer, 0, w.bytes); + list_hr = list->list->Close(); + } + if (SUCCEEDED(list_hr)) { + std::lock_guard submit(internal_mutex_); + // The producer wait: the copy runs after every earlier submission that may use a backing, or + // the submission is refused when one of them has no safe completion order. Decided here, under + // internal_mutex_, so no refresh can be enqueued between the decision and this copy. + std::vector<std::pair<ID3D12Fence*, UINT64>> users; + ID3D12CommandQueue* blocker = nullptr; + const char* why = ""; + bool safe = true; + { + std::lock_guard lock(mutex_); + try { + safe = earlier_users(&users, &blocker, &why); + } catch (const std::bad_alloc&) { + list_hr = E_OUTOFMEMORY; // the refresh fails (stale); nothing is enqueued without its waits + } + if (SUCCEEDED(list_hr) && !safe) { + // Nothing was executed: the list and every staging buffer are free again, and no buffer's + // state changes (the next submission compares against the same upload record). + list->value = 0; + for (Work& w : work) + if (w.staging) w.staging->value = 0; + ++totals_.unsafe_refresh_refusals; + if (x2w_local::first_calls(unsafe_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffers: submission on queue %p refused: its refresh would have to " + "wait for queue %p (%s), so it has no safe completion order; none of its lists ran", + static_cast<void*>(queue), static_cast<void*>(blocker), why); + *refused = true; + return 0; + } + if (SUCCEEDED(list_hr)) totals_.producer_waits += users.size(); + } + if (SUCCEEDED(list_hr)) { + for (const auto& [fence, user_value] : users) { + const HRESULT hr = internal_queue_->Wait(fence, user_value); + if (FAILED(hr) && x2w_local::first_calls(wait_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffers: the refresh queue could not wait for submission 0x%llx (0x%08lx)", + static_cast<unsigned long long>(user_value), static_cast<unsigned long>(hr)); + } + ID3D12CommandList* lists[] = {list->list}; + internal_queue_->ExecuteCommandLists(1, lists); + executed = true; + list_hr = internal_queue_->Signal(internal_fence_, internal_value_ + 1); + if (SUCCEEDED(list_hr)) value = ++internal_value_; + } + } + } + if (executed) pause_at(pause_after_execute); + + // Publish under the lock. Two submissions on different threads can snapshot one buffer against the + // same `uploaded`, stage the title's bytes at different times (X, then the CPU writes Y, then Y), + // execute in one order (internal_mutex_: Y gets the lower value, X the higher, so the backing ends + // with X) and publish in the other. Applying both publishes in lock order would leave `uploaded` + // saying Y while the backing holds X, and no later submission would refresh it. So a buffer + // remembers the internal value of its last applied publish: a newer one applies its span; an older + // one arriving after it drops `uploaded` (the backing holds the newer copy's bytes where the spans + // overlap and the older one's elsewhere), and the next submission copies the whole buffer. Every + // consumer waits for the higher of the two fence values. + std::lock_guard lock(mutex_); + // Executed without a fence value: what it read can never be proven free, so it stays in use. + const UINT64 held = executed ? ~UINT64{0} : 0; + if (list) list->value = value ? value : (FAILED(list_hr) ? held : value); + for (Work& w : work) { + if (w.unreadable || w.faulted) { + w.staging->value = 0; // never read by a copy: free again + if (w.faulted) { + ++totals_.copy_faults; + refresh_failed(w.dest, *w.copy, w.hr); + } else { + ++totals_.unreadable; + if (x2w_local::first_calls(unreadable_logged_, 4)) + x2w_local::logf("x2w-d3d12 linear buffer %p: title memory %p is no longer readable; its backing " + "keeps the last upload", static_cast<void*>(w.dest), static_cast<const void*>(w.source)); + } + continue; + } + const HRESULT hr = FAILED(w.hr) ? w.hr : list_hr; + if (FAILED(hr)) { + if (w.staging) w.staging->value = held; + refresh_failed(w.dest, *w.copy, hr); + continue; + } + w.staging->fence = internal_fence_; + w.staging->value = value; + Copied& copy = *w.copy; + if (value > copy.refresh_value) copy.refresh_value = value; + if (copy.live && value < copy.published_value && !linear_detail::mutant("publish-out-of-order")) { + copy.uploaded.clear(); // an older copy after a newer one: unknown, the next submission copies it all + ++totals_.reordered_publishes; + } else if (copy.live) { + // The backing holds these bytes once `value` completes; every consumer waits for it. An unknown + // `uploaded` (empty) is set only by a copy of the whole buffer. + const bool whole = w.offset == 0 && w.bytes == copy.bytes; + try { + if (copy.uploaded.size() != copy.bytes && (whole || linear_detail::mutant("publish-out-of-order"))) + copy.uploaded.assign(static_cast<std::size_t>(copy.bytes), 0); + if (copy.uploaded.size() == copy.bytes) + std::memcpy(copy.uploaded.data() + w.offset, w.staging->mapped, static_cast<std::size_t>(w.bytes)); + } catch (const std::bad_alloc&) { + copy.uploaded.clear(); // the next submission copies the whole buffer again + } + } + if (value > copy.published_value) copy.published_value = value; + copy.stale = false; + ++copy.refreshes; + copy.bytes_copied += w.bytes; + copy.last_staging = w.staging->id; + ++totals_.refreshes; + totals_.bytes_copied += w.bytes; + } + return value; + } + + static bool complete(const Staging& staging) + { + return staging.value == 0 || + (staging.value != ~UINT64{0} && staging.fence && staging.fence->GetCompletedValue() >= staging.value); + } + + // Takes a staging buffer of at least `bytes` that no submission still reads, for this submission + // alone (`taken` are the ones it already holds). Called without mutex_: the lock is taken only to + // choose or publish a buffer; creating one and waiting for a fence happen outside it. + HRESULT acquire_staging(UINT64 bytes, const std::vector<Staging*>& taken, Staging** out) + { + const bool early = linear_detail::mutant("reuse-early"); + { + std::lock_guard lock(mutex_); + if (const unsigned period = linear_detail::refresh_fault_period(); + period && ++staging_requests_ % period == 2 % period) + return E_OUTOFMEMORY; // fixture fault (X2W_TEST_LINEAR_REFRESH_FAIL) + } + for (int attempt = 0; attempt < 2; ++attempt) { + bool create = false; + ID3D12Fence* fence = nullptr; + UINT64 value = 0; + { + std::lock_guard lock(mutex_); + Staging* best = nullptr; + for (const auto& staging : staging_) { + if (staging->bytes < bytes || (!early && !complete(*staging))) continue; + if (std::find(taken.begin(), taken.end(), staging.get()) != taken.end()) continue; + // The reuse-early mutant takes the most recently used buffer, in flight or not. + if (!best || (early ? staging->id > best->id : staging->bytes < best->bytes)) best = staging.get(); + } + if (best) { + ++totals_.staging_reused; + best->value = ~UINT64{0}; + *out = best; + return S_OK; + } + if (staging_.size() + creating_ < staging_limit()) { + ++creating_; + create = true; + } else { + // The pool is full of buffers in flight: the oldest with a signalled value is waited for. + const Staging* oldest = nullptr; + for (const auto& staging : staging_) + if (staging->value != ~UINT64{0} && staging->fence && (!oldest || staging->value < oldest->value)) + oldest = staging.get(); + if (oldest) { + fence = oldest->fence; + value = oldest->value; + } + } + } + if (create) return create_staging(bytes, out); + if (!fence || attempt) break; + // The hold-lock mutant waits with mutex_ held, as before the review: other callers block. + std::unique_lock<std::mutex> held; + if (linear_detail::mutant("hold-lock")) held = std::unique_lock<std::mutex>(mutex_); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool reached = event && SUCCEEDED(fence->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 5000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + if (!reached) return DXGI_ERROR_WAS_STILL_DRAWING; + } + return DXGI_ERROR_WAS_STILL_DRAWING; + } + + // Called without mutex_ after acquire_staging reserved a place in the pool (creating_). + HRESULT create_staging(UINT64 bytes, Staging** out) + { + auto staging = std::make_unique<Staging>(); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_UPLOAD}; + const UINT64 rounded = (bytes + 0xFFFF) & ~UINT64{0xFFFF}; + const UINT64 size = rounded ? rounded : 0x10000; + const auto desc = linear_detail::buffer(size, D3D12_RESOURCE_FLAG_NONE); + HRESULT hr = internal_device_->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&staging->buffer)); + staging->bytes = size; + // The pool's staging buffers live for the process: counted as upload memory (X2W_D3D12_BUDGET). + if (SUCCEEDED(hr)) x2w_budget::committed(internal_device_, staging->buffer, D3D12_HEAP_TYPE_UPLOAD); + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + if (SUCCEEDED(hr)) hr = staging->buffer->Map(0, &none, &mapped); + std::lock_guard lock(mutex_); + --creating_; + if (FAILED(hr)) { + if (staging->buffer) staging->buffer->Release(); + return hr; + } + staging->mapped = static_cast<unsigned char*>(mapped); + staging->id = ++staging_ids_; + staging->value = ~UINT64{0}; + try { + staging_.push_back(std::move(staging)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; // the unique_ptr releases nothing: the buffer is leaked, not reused + } + ++totals_.staging_created; + *out = staging_.back().get(); + return S_OK; + } + + // A refresh list for the internal queue whose last use has completed, or a new one, reset and ours + // alone. Called without mutex_; the lock covers only the choice and the pool. + HRESULT acquire_list(RefreshList** out) + { + RefreshList* found = nullptr; + { + std::lock_guard lock(mutex_); + const UINT64 completed = internal_fence_->GetCompletedValue(); + for (const auto& list : internal_lists_) { + if (list->value == ~UINT64{0} || list->value > completed) continue; + list->value = ~UINT64{0}; + found = list.get(); + break; + } + } + if (found) { + HRESULT hr = found->allocator->Reset(); + if (SUCCEEDED(hr)) hr = found->list->Reset(found->allocator, nullptr); + *out = found; // on failure the caller frees it again under the lock + return hr; + } + auto list = std::make_unique<RefreshList>(); + HRESULT hr = internal_device_->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY, IID_PPV_ARGS(&list->allocator)); + if (SUCCEEDED(hr)) + hr = internal_device_->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, list->allocator, nullptr, + IID_PPV_ARGS(&list->list)); + if (FAILED(hr)) { + if (list->list) list->list->Release(); + if (list->allocator) list->allocator->Release(); + return hr; + } + list->value = ~UINT64{0}; + std::lock_guard lock(mutex_); + try { + internal_lists_.push_back(std::move(list)); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + *out = internal_lists_.back().get(); + return S_OK; + } + + // The submission runs without this buffer's refresh: its backing keeps the last upload. + void refresh_failed(ID3D12Resource* resource, Copied& copy, HRESULT hr) + { + copy.stale = true; + ++copy.refresh_failures; + copy.last_refresh_hr = hr; + ++totals_.refresh_failures; + totals_.last_refresh_hr = hr; + if (x2w_local::first_calls(refresh_logged_, 8)) + x2w_local::logf("x2w-d3d12 linear buffers: refresh of %p failed 0x%08lx; the submission runs with its last " + "upload (stale)", static_cast<void*>(resource), static_cast<unsigned long>(hr)); + } + + std::mutex mutex_; + std::unordered_map<ID3D12Resource*, Record> records_; + std::mutex internal_mutex_; // the internal queue's ExecuteCommandLists and Signal, in value order + ID3D12Device* internal_device_ = nullptr; + ID3D12CommandQueue* internal_queue_ = nullptr; + ID3D12Fence* internal_fence_ = nullptr; + UINT64 internal_value_ = 0; // under internal_mutex_ + bool internal_tried_ = false; + HRESULT internal_hr_ = S_OK; + std::vector<std::unique_ptr<RefreshList>> internal_lists_; + std::vector<std::unique_ptr<Staging>> staging_; + std::vector<Heap> heaps_; + std::deque<UserQueue> users_; // under mutex_; elements never move (their order locks are held outside it) + SRWLOCK order_fallback_ = SRWLOCK_INIT; // the order lock of a queue whose record could not be stored + struct Pause { + HANDLE reached = nullptr, resume = nullptr; + }; + std::mutex pause_mutex_; // fixtures' pauses (a leaf: nothing else is taken under it) + Pause pauses_[pause_points]; + std::atomic<bool> pauses_armed_{false}; + ID3D12Device* feature_device_ = nullptr; + HRESULT feature_hr_ = S_FALSE; + UINT64 generation_ = 0, staging_ids_ = 0, staging_requests_ = 0; + std::size_t creating_ = 0; // staging buffers being created outside the lock + X2wLinearBufferTotals totals_{}; + volatile LONG unreadable_logged_ = 0, wait_logged_ = 0, refresh_logged_ = 0, gpu_write_logged_ = 0, unsafe_logged_ = 0; +}; + +} // namespace x2w_startup diff --git a/src/startup_stubs/linear_buffer_report.h b/src/startup_stubs/linear_buffer_report.h new file mode 100644 index 000000000..107ca76e2 --- /dev/null +++ b/src/startup_stubs/linear_buffer_report.h @@ -0,0 +1,39 @@ +#pragma once + +// What d3d12_xs.dll reports about slot 133's opt-in linear buffers (X2W_D3D12_LINEAR_BUFFERS, +// src/startup_stubs/linear_buffer_backing.h) to fixtures through x2w_d3d12_linear_buffer_info and +// x2w_d3d12_linear_buffer_totals. Plain layouts: the DLL and the fixtures include this file alike. + +#include <cstdint> + +struct X2wLinearBufferInfo { + std::uint32_t path; // 1 shared, 2 copied, 3 kept the default backing (refusal_hr says why) + std::uint32_t use; // 1 GPU-read, 2 GPU-written + std::int32_t feature_hr; // S_OK supported, DXGI_ERROR_UNSUPPORTED not, other: query failed; S_FALSE not queried + std::int32_t share_hr; // result of the sharing attempt; S_FALSE when not attempted + std::int32_t refusal_hr; // kept default: why the new path could not keep its guarantees; else S_OK + std::uint32_t stale; // copied: 1 while the backing holds an older upload than the title's bytes + std::uint64_t heap_generation; // shared: generation of the opened heap + void* backing; // the desktop ID3D12Resource + std::uint64_t refreshes; // copied: submissions that copied bytes into the backing + std::uint64_t bytes_copied; // copied: bytes copied from title memory into the backing + std::uint64_t last_staging; // copied: id of the staging buffer of the last refresh (0: none) + std::uint64_t last_fence; // copied: internal fence value of the last refresh (0: none) + std::uint64_t refresh_failures; // copied: submissions that ran without this buffer's refresh + std::int32_t last_refresh_hr; // copied: HRESULT of the last failed refresh; S_OK if none + std::uint32_t gpu_written; // copied: 1 once a submitted copy wrote it; it is no longer refreshed +}; + +struct X2wLinearBufferTotals { + std::uint64_t placements, shared, copied, kept_default; + std::uint64_t feature_queries, heap_opens, heap_open_failures, heap_cache_hits, place_failures; + std::uint64_t submissions, refreshes, bytes_copied, staging_created, staging_reused, unreadable; + std::uint64_t refresh_failures; + std::uint64_t consumer_waits; // submissions made to Wait for a refresh on the internal queue + std::uint64_t gpu_written; // copied buffers that a submitted copy wrote (held from then on) + std::uint64_t producer_waits; // refresh copies made to Wait for a queue's earlier, uncompleted submission + std::uint64_t unsafe_refresh_refusals; // submissions refused: their refresh had no safe completion order + std::uint64_t reordered_publishes; // an older refresh published after a newer one: `uploaded` dropped + std::uint64_t copy_faults; // staging reads of title memory that faulted (caught; that refresh failed) + std::int32_t last_refusal_hr, last_refresh_hr; +}; diff --git a/src/startup_stubs/list_copy.inl b/src/startup_stubs/list_copy.inl index 5ed62c724..6538a5cd0 100644 --- a/src/startup_stubs/list_copy.inl +++ b/src/startup_stubs/list_copy.inl @@ -110,6 +110,14 @@ std::unordered_map<Wrapper*, std::vector<ID3D12Resource*>>& pending_gpu_writes() static std::unordered_map<Wrapper*, std::vector<ID3D12Resource*>> m; return m; } +// X2W_D3D12_LINEAR_BUFFERS: the copied linear buffers a recording wrote (list slots 15 and 17), under the same +// rule. A copied buffer stops being refreshed from its title memory only once a recording that writes it is +// submitted; a recording that is discarded leaves it refreshed (linear_buffer_backing.h). +std::unordered_map<Wrapper*, std::vector<ID3D12Resource*>>& pending_linear_writes() +{ + static std::unordered_map<Wrapper*, std::vector<ID3D12Resource*>> m; + return m; +} bool list_wrote(Wrapper* list, ID3D12Resource* resource) { @@ -125,11 +133,13 @@ void discard_list_gpu_writes(Wrapper* self) { AcquireSRWLockExclusive(&pending_writes_lock); pending_gpu_writes().erase(self); + pending_linear_writes().erase(self); ReleaseSRWLockExclusive(&pending_writes_lock); } void commit_list_gpu_writes(Wrapper* self) { + std::vector<ID3D12Resource*> linear; AcquireSRWLockShared(&pending_writes_lock); if (const auto it = pending_gpu_writes().find(self); it != pending_gpu_writes().end()) { for (ID3D12Resource* resource : it->second) { @@ -138,7 +148,10 @@ void commit_list_gpu_writes(Wrapper* self) state.done = true; } } + if (const auto it = pending_linear_writes().find(self); it != pending_linear_writes().end()) linear = it->second; ReleaseSRWLockShared(&pending_writes_lock); + // After the recording's ExecuteCommandLists, outside the lock (the backing takes its own). + for (ID3D12Resource* resource : linear) linear_buffers().note_gpu_write(resource); } // A copy or resolve destination will hold what the GPU wrote once `self` is submitted. A title-backed texture @@ -152,6 +165,25 @@ void mark_gpu_written(Wrapper* self, const CopyEndpoint& destination) ReleaseSRWLockExclusive(&pending_writes_lock); } +// X2W_D3D12_LINEAR_BUFFERS: a copied linear buffer that a recorded copy writes keeps the GPU's bytes once +// `self` is submitted, and is no longer refreshed from its title memory from then on (linear_buffer_backing.h). +// Until then the write is pending on the recording: Reset or a failed Close drops it with the texture writes. +void note_linear_gpu_write(Wrapper* self, const CopyEndpoint& destination) +{ + if (!destination.wrapper || !destination.wrapper->own().title_memory || + x2w_startup::linear_buffer_mode() == x2w_startup::LinearBufferMode::off) + return; + if (x2w_startup::linear_detail::mutant("gpuw-at-record")) { + // Mutant: the backing changes at recording, so a discarded recording still stops its refreshes. + linear_buffers().note_gpu_write(destination.resource); + return; + } + AcquireSRWLockExclusive(&pending_writes_lock); + auto& writes = pending_linear_writes()[self]; + if (std::find(writes.begin(), writes.end(), destination.resource) == writes.end()) writes.push_back(destination.resource); + ReleaseSRWLockExclusive(&pending_writes_lock); +} + // Refusal shared by the three handlers once the descriptions passed, or none. x2w_startup::CopyRefusal check_roles_and_sync(Wrapper* self, const CopyEndpoint& to, const CopyEndpoint& from, bool sync) { @@ -218,6 +250,7 @@ void __stdcall list_copy_buffer_region(Wrapper* self, u64 destination, u64 desti note_mesh_xmem_write(self, to.wrapper, destination_offset, bytes, 15, source_kind, srv_word || mesh_record ? from.resource : nullptr, source_offset); } + note_linear_gpu_write(self, to); if (indirect_copy_ranges()) { const auto* info = to.wrapper ? resource_info(to.wrapper) : nullptr; note_copy_gpu_range(self, to.resource, destination_offset, bytes, authoritative && info && @@ -247,6 +280,7 @@ void __stdcall list_copy_resource(Wrapper* self, u64 destination, u64 source) if (to_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { note_mesh_xmem_write(self, to.wrapper, 0, to_desc.Width, 17, "buffer"); note_copy_gpu_range(self, to.resource, 0, to_desc.Width, false); + note_linear_gpu_write(self, to); } else mark_gpu_written(self, to); InterlockedIncrement(&list_resource_copies); } diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp new file mode 100644 index 000000000..a735c1ef8 --- /dev/null +++ b/tests/linear_buffer_backing_check.cpp @@ -0,0 +1,1952 @@ +// Production slice of #1914 (Refs #874): one ordinary linear buffer, written by the CPU and read by +// the GPU, placed at a title address through the device wrapper's slot 133 (CreatePlacedResourceX) +// and submitted through the command-queue wrapper's ExecuteCommandLists, in d3d12_xs.dll. The cases +// and sentinels are those of tests/unified_buffer_paths_check.cpp (#1942); here they run against the +// production backing instead of a model of it. +// +// linear_buffer_backing_check <warp|hardware> <path> [--mutate <name>] +// +// path selects the backing (the process environment is set here, before d3d12_xs.dll reads it): +// default X2W_D3D12_LINEAR_BUFFERS unset: slot 133 as before (the old behaviour, asserted) +// share X2W_D3D12_LINEAR_BUFFERS=1: real sharing where the adapter, extent and memory allow it +// (a private range); an XMem view is refused for sharing by the host rule and copied +// copy X2W_D3D12_LINEAR_BUFFERS=copy: forced copying at submit +// refusal X2W_D3D12_LINEAR_BUFFERS=1 with X2W_TEST_EXISTING_HEAPS_UNSUPPORTED=1: the host refuses +// sharing (as an adapter reporting D3D12_FEATURE_EXISTING_HEAPS = 0 does) +// untracked X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_SUBMIT_FENCE_FAIL=1: no submit fence, so +// the copy cannot keep its lifetime guarantee: slot 133 keeps the default backing +// stale X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_LINEAR_REFRESH_FAIL=3: staging requests 2, +// 5, 8 ... fail, so one refresh per pool cannot be staged +// contention X2W_D3D12_LINEAR_BUFFERS=copy with X2W_TEST_LINEAR_STAGING_LIMIT=1: one staging buffer, +// so a refresh waits for the fence of the submission that holds it +// lease X2W_D3D12_LINEAR_BUFFERS=copy with X2W_MESH86_XMEM_SRV=1: the mesh XMem lease path is on and +// owns XMem placements with console flags 0; the linear backing must defer to it there +// +// Where the new path cannot keep its guarantees (a GPU-written use that is not shared, no submit +// fence), slot 133 must keep the default backing and return what it returns with the switch off: +// S_OK, an XMem view not aliased, a private range aliased (on an adapter with existing heaps). The +// refusal must be reported in x2w_d3d12_linear_buffer_info (path 3, refusal_hr), in the totals +// (kept_default) and in the slot 133 log line ("kept default backing: linear refusal 0x..."), which +// the fixture reads back from X2W_TRAP_LOG (linear_buffer_backing_<path>_<adapter>.log next to the +// executable). +// +// Title memory comes from two pools. "xmem": xmem.dll physical pages (64 KiB slots of 256 MiB +// pagefile sections) mapped with X2W_XMEM_SHARED_VIEWS=1, five pages per mapping call (one view): +// three neighbour pages, then the two-page buffer at view offset 0x30000. A previous user's pages are +// freed first, so the first buffer lands on reused slots that must read zero. "private": one +// committed 8 MiB VirtualAlloc range, five pages per allocation in the same layout. +// +// Cases (sentinels A, B, C, D, E, G, P, filler and neighbour differ in every word): +// a bind A: slot 133 and a list that reads the buffer are recorded over A. The CPU writes B +// before ExecuteCommandLists. The GPU must read B. +// a2 then 16 words change to E: the next submission reads them, and a copy moves only those 64 bytes. +// b a GPU-written use (ALLOW_UNORDERED_ACCESS): the GPU writes G ^ key; after the fence the CPU +// alias holds it and the words around keep theirs. The copy cannot give this: slot 133 keeps the +// default backing and reports the sharing HRESULT (DXGI_ERROR_UNSUPPORTED when not attempted). +// c a submission is held in flight on a gate fence, then two more (other buffers, C and D). Each +// held submission reads its own sentinel. Sharing: the title releases X while it is held, and +// after the fence places a new buffer (E) at X's address, on the same cached heap generation. +// Copying: no staging buffer is handed out again while its submission is held; after the fence +// the next refresh takes one of them again. +// d1 missing refresh: after a refreshed submission of A the CPU writes B, and the list is +// executed on the desktop queue directly, past the wrapper. Copying must expose the stale A +// (the oracle sees a missing refresh); sharing reads B. Through the wrapper the copy reads B. +// d2 readback before the fence: the GPU write of b is held on the gate. Before the gate opens the +// fence has not completed and the alias still holds P in every word (the read is ordered +// before the write by the queue's Wait); after it, G ^ key. Copying keeps the default (as b). +// stale (stale only) a refreshed submission of A; the CPU writes B and the next refresh fails: the +// submission still runs and completes, reads A (the last upload), and the buffer is reported +// stale with E_OUTOFMEMORY in info, totals and the log; the next submission reads B and clears it. +// split (share only) a buffer across two XMem views: sharing is refused with E_INVALIDARG, decided +// before any D3D12 call, and the buffer is copied; case a must still read B. +// gate (refusal only) no heap was opened: D3D12_FEATURE_EXISTING_HEAPS gates sharing before any open. +// q.comp, q.copy (copy only) the buffer is read by a list on a COMPUTE queue (a dispatch) and on a +// COPY queue (CopyBufferRegion) submitted through those queues' wrappers: the refresh runs on +// that queue, the first submission reads B, and a 16-word change then copies 64 bytes. +// gate2q, gate2q.held (copy only) one buffer holding A, read by a list on queue 1 behind a title gate +// and by a list on queue 2; the CPU writes B once before both submissions. Queue 2 must complete +// while the gate is closed and read B, and queue 1 must read B after it. In .held the fixture also +// holds the internal refresh queue: queue 2 must not complete before the refresh lands. +// xq (copy only) queue 1 waits on a title fence that queue 2 signals after its list (a cross-queue +// dependency the title owns); both read the buffer the CPU changed to B. Both must complete (no +// deadlock) and read B. +// contention (contention only) a second queue, a release() and the info export while a submission +// waits for the only staging buffer, whose copy the fixture holds on the internal refresh +// queue: all three must finish while the wait is still under way. After the refreshes land the +// waiting refresh has taken that buffer again (none is created). The gated S1 reads B: C's copy +// waits for it (the producer wait). S2 reads C. +// budget (share, copy) with X2W_D3D12_BUDGET=1: a shared buffer counts as placed memory (its heap +// live), a copied one as a committed buffer; live while held, retained after the title's release. +// gpuw (copy only) a recorded copy (list slot 15) writes G into a copied buffer, then the title changes +// its first and last words: the buffer keeps G (it is no longer refreshed), reported as gpu_written. +// gpuw.discard (copy only) the same copy is recorded and closed, then the list is reset without a +// submission; the CPU writes B: the next read sees B and the buffer is not gpu_written. +// war (copy only) a read of A on queue 1 behind a title gate (on the desktop queue); the CPU writes B and +// queue 2 submits a read. Its refresh's copy waits for queue 1 (producer_waits): queue 2 cannot +// complete while the gate is closed, queue 1 reads A and queue 2 reads B. +// xq.write (copy only) queue 1 waits through its wrapper (slot 17) on a title fence, then submits a read of +// A; the CPU writes B and queue 2 submits a read. Its refresh has no safe completion order (it would +// have to wait for queue 1, behind the unreached fence), so the submission is refused: unsafe refresh +// refusals +1 and logged, its result slot keeps P. The title's Signal through queue 2's wrapper (slot +// 16) releases queue 1, which reads A; the refused recording submitted again on queue 2 reads B. +// xq.race (copy only) xq.write with queue 1's title Wait and its read of A on two threads: the Wait is parked +// through x2w_d3d12_linear_buffer_test_pause (point 3) after the desktop Wait and before it is recorded, +// and the read is submitted meanwhile. The read is behind the fence on the desktop queue, so queue 2's +// read must still be refused, queue 2 must still signal the fence, queue 1 must read A and the +// resubmission B. A queue that does not complete within 3 s is released by a CPU Signal of the fence. +// order (copy only) two threads refresh one buffer, parked through x2w_d3d12_linear_buffer_test_pause: +// thread A stages C and parks before its copy executes; the CPU writes D; thread B stages D, executes +// first and parks before publishing; A executes (the backing ends with C) and publishes, B publishes +// last. The next submission must refresh D (reordered_publishes +1) and read it. +// retire (copy only) a submission that reads Y snapshots the changed X and Y and parks before staging; +// the title releases X and frees its pages. X is skipped as unreadable (no copy fault, no failed +// refresh); Y reads C. +// lease (lease only) an XMem buffer keeps the default backing with HRESULT_FROM_WIN32(ERROR_BUSY) +// reported (old behaviour: reads zero); a private one is copied and reads B. +// pin (share, XMem; measured, not asserted) a heap opened from an XMem view and a buffer placed on +// it, then XMem's unmap of those pages, while they live and after their release. +// +// The default path asserts what slot 133 did before: a private range is aliased (a and b pass) and +// an XMem view gets a committed buffer that does not alias it (a reads zero, b leaves P), with no +// linear-buffer bookkeeping at all. +// +// --mutate <name> sets X2W_TEST_LINEAR_BUFFER_MUTANT, which removes one guarantee inside d3d12_xs.dll: +// skip-refresh (copy) case a, reuse-early (copy) case c, copy-gpu-writes (copy) case b, +// ignore-feature (refusal) case gate, refusal-silent (copy) case b (the kept default is not reported), +// hold-lock (contention) case contention (the wait keeps the backing's lock held), +// skip-consumer-wait (copy) case gate2q.held (no submission waits for the internal fence), +// refresh-gpu-written (copy) case gpuw (a refresh spanning the written words copies the title's A over G), +// gpuw-at-record (copy) case gpuw.discard (the buffer stops being refreshed when the copy is recorded), +// skip-producer-wait (copy) case war (the refresh's copy lands before queue 1's earlier read), +// publish-out-of-order (copy) case order (B's older publish is applied after A's: no further refresh), +// copy-after-retire (copy) case retire (no probe before staging: the fault guard catches the read), +// accept-unsafe-refresh (copy) case xq.write (the refresh skips the blocked queue: queue 2 runs and both read B), +// unlocked-title-wait (copy) case xq.race (slot 17 takes no order lock: the read takes its user value before the +// Wait is recorded, queue 2's refresh is accepted and waits for queue 1, and both stay pending until the CPU +// signals the fence). +// +// Refreshes run on an internal COPY queue that the DLL exports to fixtures +// (x2w_d3d12_linear_buffer_internal_queue); cases c, contention and gate2q.held hold it behind a fence +// of their own to keep a refresh in flight. Cases order and retire park a refresh on its thread through +// x2w_d3d12_linear_buffer_test_pause, and xq.race parks a title Wait. +// The run then exits 1 only if every targeted case failed, else 0 (negative controls, WILL_FAIL). +// X2W_TEST_DEBUG_LAYER=1 enables the D3D12 debug layer; any stored error fails the run. +// Returns 0 on pass, 1 on failure, 77 without the adapter, or on the share path when the adapter +// reports no existing-heap support. +#include <windows.h> +#include <d3d12.h> +#include <d3d12sdklayers.h> +#include <d3dcompiler.h> +#include <dxgi1_6.h> +#include <wrl/client.h> + +#include <atomic> +#include <chrono> +#include <cstdint> +#include <cstdio> +#include <cstring> +#include <string> +#include <thread> +#include <vector> + +#include "xmem_test_device.h" +#include "../src/startup_stubs/linear_buffer_report.h" +#include "../src/startup_stubs/resource_budget.h" + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_info(void*, X2wLinearBufferInfo*); +extern "C" __declspec(dllimport) void x2w_d3d12_linear_buffer_totals(X2wLinearBufferTotals*); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_internal_queue(void**); +extern "C" __declspec(dllimport) bool x2w_d3d12_linear_buffer_test_pause(unsigned, void*, void*); +extern "C" __declspec(dllimport) BOOL x2w_d3d12_budget_snapshot(x2w_budget::Snapshot*, SIZE_T); +extern "C" __declspec(dllimport) void* WINAPI XMemVirtualAlloc(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +extern "C" __declspec(dllimport) BOOL WINAPI XMemAllocatePhysicalPages(ULONG_PTR, PULONG_PTR, PULONG_PTR); +extern "C" __declspec(dllimport) BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR); +extern "C" __declspec(dllimport) void* WINAPI XMemMapPhysicalPages(void*, ULONG_PTR, const ULONG_PTR*); + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT64 page = 64 * 1024; +constexpr unsigned alloc_pages = 5; // three neighbour pages, then the buffer +constexpr UINT64 buffer_offset = 3 * page; +constexpr UINT64 buffer_bytes = 2 * page; +constexpr UINT words = 1024; +constexpr UINT64 region_bytes = words * 4; +constexpr UINT64 r0 = page - region_bytes / 2; // the region the GPU reads; straddles the buffer's two pages +constexpr UINT64 r1 = page + 0x8000; // the region the GPU writes +constexpr std::uint32_t key = 0x5a5a5a5au; + +enum Tag { neighbour, filler, A, B, C, D, E, G, P, tag_count }; +const char* const tag_names[tag_count] = {"neighbour", "filler", "A", "B", "C", "D", "E", "G", "P"}; +constexpr std::uint32_t seeds[tag_count] = {0x6e656967u, 0x66696c6cu, 0xa1a1a1a1u, 0xb2b2b2b2u, 0xc3c3c3c3u, + 0xd4d4d4d4u, 0xe5e5e5e5u, 0x47474747u, 0x50505050u}; +std::uint32_t pattern(Tag tag, UINT64 word) { return seeds[tag] ^ static_cast<std::uint32_t>(word * 0x9e3779b1u); } + +std::string hex(HRESULT hr) +{ + char text[16]; + std::snprintf(text, sizeof(text), "0x%08lx", static_cast<unsigned long>(hr)); + return text; +} + +// `count` words of `tag` at byte `offset` of `cpu`; the pattern index is the word's index from `cpu`. +void write(std::uint8_t* cpu, UINT64 offset, Tag tag, UINT64 count) +{ + auto* w = reinterpret_cast<std::uint32_t*>(cpu); + for (UINT64 i = 0; i < count; ++i) w[offset / 4 + i] = pattern(tag, offset / 4 + i); +} + +struct Tally { + unsigned count[tag_count]{}; + unsigned zero = 0, other = 0; + std::string text() const + { + std::string out; + for (int t = 0; t < tag_count; ++t) + if (count[t]) out += (out.empty() ? "" : " ") + std::string(tag_names[t]) + "=" + std::to_string(count[t]); + if (zero) out += (out.empty() ? "" : " ") + std::string("zero=") + std::to_string(zero); + if (other) out += (out.empty() ? "" : " ") + std::string("other=") + std::to_string(other); + return out + "/" + std::to_string(words); + } +}; +// Attributes each word to the sentinel it holds after removing `mask`; word i has pattern index first + i. +Tally tally(const std::uint32_t* got, UINT64 first, std::uint32_t mask) +{ + Tally t; + for (UINT i = 0; i < words; ++i) { + const std::uint32_t value = got[i] ^ mask; + bool matched = false; + for (int tag = 0; tag < tag_count && !matched; ++tag) + if (value == pattern(static_cast<Tag>(tag), first + i)) { + ++t.count[tag]; + matched = true; + } + if (!matched) ++(value == 0 ? t.zero : t.other); + } + return t; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 size, D3D12_RESOURCE_FLAGS flags) +{ + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +using Word = std::uint64_t; +Word invoke(void* object, unsigned index, Word a = 0, Word b = 0, Word c = 0, Word d = 0, Word e = 0) +{ + using Slot = Word(WINAPI*)(void*, Word, Word, Word, Word, Word); + return reinterpret_cast<Slot>((*static_cast<void***>(object))[index])(object, a, b, c, d, e); +} +template <class T> Word arg(T* value) { return reinterpret_cast<Word>(value); } + +// The desktop object behind a wrapper: SetPrivateDataInterface unwraps its argument before the call +// reaches the shared desktop device (as in tests/startup_indirect_dispatch.cpp). +template <typename T> +ComPtr<T> underlying(ID3D12Device* desktop, ID3D12Device* guest, IUnknown* object) +{ + constexpr GUID slot{0x6c1f0a3e, 0x2b51, 0x4d0e, {0x9b, 0x31, 0x5e, 0x0c, 0x72, 0x14, 0x88, 0x19}}; + ComPtr<T> result; + if (FAILED(guest->SetPrivateDataInterface(slot, object))) return result; + ComPtr<IUnknown> stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = desktop->GetPrivateData(slot, &bytes, stored.GetAddressOf()); + guest->SetPrivateDataInterface(slot, nullptr); + if (SUCCEEDED(read)) stored.As(&result); + return result; +} + +constexpr char shader_source[] = R"( +ByteAddressBuffer src : register(t0); +RWByteAddressBuffer dst : register(u0); +cbuffer Key : register(b0) { uint key; }; +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { dst.Store(id.x * 4, src.Load(id.x * 4) ^ key); } +)"; + +// The X2W_TRAP_LOG file d3d12_xs.dll appends its log lines to; a line with both needles. +std::wstring log_path; +bool log_has(const std::string& first, const std::string& second) +{ + HANDLE file = CreateFileW(log_path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + std::string text; + char chunk[65536]; + DWORD got = 0; + while (ReadFile(file, chunk, sizeof(chunk), &got, nullptr) && got) text.append(chunk, got); + CloseHandle(file); + std::size_t at = 0; + while (at < text.size()) { + std::size_t end = text.find('\n', at); + if (end == std::string::npos) end = text.size(); + const std::string line = text.substr(at, end - at); + if (line.find(first) != std::string::npos && line.find(second) != std::string::npos) return true; + at = end + 1; + } + return false; +} +std::string pointer_text(const void* p) +{ + char text[32]; + std::snprintf(text, sizeof(text), "%p", p); + return text; +} + +enum class Path { default_backing, share, copy, refusal, untracked, stale, contention, lease }; +const char* path_name(Path p) +{ + switch (p) { + case Path::default_backing: return "default"; + case Path::share: return "share"; + case Path::copy: return "copy"; + case Path::refusal: return "refusal"; + case Path::untracked: return "untracked"; + case Path::stale: return "stale"; + case Path::contention: return "contention"; + default: return "lease"; + } +} + +// ---- Title memory ---- + +struct Memory { + std::uint8_t* cpu = nullptr; // allocation start; the buffer is at cpu + buffer_offset + std::vector<ULONG_PTR> tokens; + std::uint8_t* buffer() const { return cpu + buffer_offset; } +}; + +struct Pool { + bool xmem; + std::uint8_t* base = nullptr; + UINT64 cursor = 0, bytes = 0; + explicit Pool(bool x) : xmem(x) {} + const char* name() const { return xmem ? "xmem" : "private"; } + + bool init() + { + bytes = xmem ? UINT64{16} << 30 : UINT64{8} << 20; // XMem takes the 16 GiB startup reservation shape + base = static_cast<std::uint8_t*>(xmem ? XMemVirtualAlloc(nullptr, static_cast<SIZE_T>(bytes), 0x20402000, 0x21, PAGE_READWRITE) + : VirtualAlloc(nullptr, static_cast<SIZE_T>(bytes), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!base) return false; + if (!xmem) return true; + // A previous user: its slots are freed, so the next allocation reuses them and must read zero. + Memory previous; + if (!map(previous, alloc_pages)) return false; + write(previous.cpu, 0, D, alloc_pages * page / 4); + return release(previous); + } + bool map(Memory& out, unsigned pages) + { + out.cpu = base + cursor; + if (cursor + pages * page > bytes) return false; + cursor += pages * page; + if (!xmem) return true; + out.tokens.assign(pages, 0); + ULONG_PTR got = pages; + return XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) && got == pages && + XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + } + // One allocation in the case layout: neighbour pages, then the buffer filled with `fill`. + bool allocate(Memory& out, Tag fill, bool* zero = nullptr) + { + if (!map(out, alloc_pages)) return false; + bool clean = true; + for (UINT64 i = 0; i < alloc_pages * page; i += 4) clean &= *reinterpret_cast<std::uint32_t*>(out.cpu + i) == 0; + if (zero) *zero = clean; + write(out.cpu, 0, neighbour, buffer_offset / 4); + write(out.buffer(), 0, fill, buffer_bytes / 4); + return true; + } + // Two pages of the buffer in two mapping calls (two views): the buffer crosses a view boundary. + bool allocate_split(Memory& out, Tag fill) + { + Memory first, second; + if (!xmem || !map(first, alloc_pages - 1) || !map(second, 1)) return false; + out.cpu = first.cpu; + out.tokens = first.tokens; + out.tokens.insert(out.tokens.end(), second.tokens.begin(), second.tokens.end()); + write(out.cpu, 0, neighbour, buffer_offset / 4); + write(out.buffer(), 0, fill, buffer_bytes / 4); + return true; + } + bool release(Memory& memory) + { + if (!xmem) return true; + const auto count = static_cast<ULONG_PTR>(memory.tokens.size()); + return XMemMapPhysicalPages(memory.cpu, count, nullptr) == memory.cpu && + XMemFreePhysicalPages(count, memory.tokens.data()); + } +}; + +// ---- Device, the wrapper's queue, and recording ---- + +// Another queue of the title's device: its wrapper, the desktop queue behind it and a completion fence. +struct Lane { + ComPtr<ID3D12CommandQueue> guest, native; + ComPtr<ID3D12Fence> fence; + UINT64 value = 0; +}; + +bool wait_fence(ID3D12Fence* fence, UINT64 value) +{ + if (fence->GetCompletedValue() >= value) return true; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool ok = event && SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return ok; +} +// Polls instead of registering an event, for a wait that is expected to time out in a negative control (a +// registration left on a closed handle could later set an unrelated event that reuses it). +bool poll_fence(ID3D12Fence* fence, UINT64 value, DWORD timeout_ms) +{ + const ULONGLONG deadline = GetTickCount64() + timeout_ms; + while (fence->GetCompletedValue() < value) { + if (GetTickCount64() >= deadline) return false; + Sleep(1); + } + return true; +} + +struct Gpu { + ComPtr<ID3D12Device> desktop, guest; + ComPtr<ID3D12CommandQueue> guest_queue, queue; // the wrapper and the desktop queue behind it + ComPtr<ID3D12Fence> done, gate; + ComPtr<ID3D12RootSignature> root; + ComPtr<ID3D12PipelineState> pipeline; + // GPU-read results (one slot per list that may be in flight at once), their CPU copy, the G words. + static constexpr UINT slots = 4; + ComPtr<ID3D12Resource> output, readback, source; + ComPtr<ID3D12InfoQueue> info; + UINT64 submitted = 0, gate_value = 0; + bool gate_armed = false; + + bool init() + { + const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(guest->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&guest_queue)))) return false; + queue = underlying<ID3D12CommandQueue>(desktop.Get(), guest.Get(), guest_queue.Get()); + if (!queue || FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate)))) + return false; + D3D12_ROOT_PARAMETER params[3]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_SRV; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[2].Constants = {0, 0, 1}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr<ID3DBlob> blob, code, errors; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr)) || + FAILED(desktop->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root))) || + FAILED(D3DCompile(shader_source, sizeof(shader_source) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code, &errors))) + return false; + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + if (FAILED(desktop->CreateComputePipelineState(&pso, IID_PPV_ARGS(&pipeline)))) return false; + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + auto desc = buffer_desc(slots * region_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, + IID_PPV_ARGS(&output)))) + return false; + heap.Type = D3D12_HEAP_TYPE_READBACK; + desc.Flags = D3D12_RESOURCE_FLAG_NONE; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback)))) + return false; + heap.Type = D3D12_HEAP_TYPE_UPLOAD; + desc.Width = region_bytes; + if (FAILED(desktop->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, + nullptr, IID_PPV_ARGS(&source)))) + return false; + void* mapped = nullptr; + if (FAILED(source->Map(0, nullptr, &mapped))) return false; + // The G words are indexed as the buffer's words at r1, so the alias can be tallied in place. + for (UINT i = 0; i < words; ++i) static_cast<std::uint32_t*>(mapped)[i] = pattern(G, r1 / 4 + i); + source->Unmap(0, nullptr); + return true; + } + + // The DLL's internal refresh queue, held behind a fence of the fixture's own. + ComPtr<ID3D12CommandQueue> internal; + ComPtr<ID3D12Fence> internal_gate, internal_done; + UINT64 internal_gate_value = 0, internal_done_value = 0; + bool hold_internal() + { + if (!internal) { + void* queue = nullptr; + if (!x2w_d3d12_linear_buffer_internal_queue(&queue)) return false; + internal.Attach(static_cast<ID3D12CommandQueue*>(queue)); + } + if (!internal_gate && (FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&internal_gate))) || + FAILED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&internal_done))))) + return false; + return SUCCEEDED(internal->Wait(internal_gate.Get(), ++internal_gate_value)); + } + void open_internal() + { + if (internal_gate) internal_gate->Signal(internal_gate_value); + } + // Every refresh enqueued so far has landed. + bool drain_internal() + { + return internal && SUCCEEDED(internal->Signal(internal_done.Get(), ++internal_done_value)) && + wait_fence(internal_done.Get(), internal_done_value); + } + + // Later submissions wait on the gate until open_gate(). + void hold() + { + if (!gate_armed) ++gate_value; + gate_armed = true; + } + void open_gate() + { + if (gate_armed) gate->Signal(gate_value); + gate_armed = false; + } + bool lane(Lane& out, D3D12_COMMAND_LIST_TYPE type) + { + const D3D12_COMMAND_QUEUE_DESC desc{type}; + if (FAILED(guest->CreateCommandQueue(&desc, IID_PPV_ARGS(&out.guest)))) return false; + out.native = underlying<ID3D12CommandQueue>(desktop.Get(), guest.Get(), out.guest.Get()); + return out.native && SUCCEEDED(desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&out.fence))); + } + bool wait(UINT64 value) + { + if (done->GetCompletedValue() >= value) return true; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool ok = event && SUCCEEDED(done->SetEventOnCompletion(value, event)) && + WaitForSingleObject(event, 20000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return ok; + } + std::vector<std::uint32_t> read_output(UINT slot = 0) + { + std::vector<std::uint32_t> got(words); + void* mapped = nullptr; + const D3D12_RANGE range{slot * region_bytes, (slot + 1) * region_bytes}; + if (SUCCEEDED(readback->Map(0, &range, &mapped))) { + std::memcpy(got.data(), static_cast<const std::uint8_t*>(mapped) + slot * region_bytes, region_bytes); + const D3D12_RANGE none{0, 0}; + readback->Unmap(0, &none); + } + return got; + } + // The CPU writes `tag` ^ key into result slot `slot` (indexed as the region at r0), so a read that never + // ran leaves it there. + bool fill_output(UINT slot, Tag tag) + { + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + if (FAILED(readback->Map(0, &none, &mapped))) return false; + auto* w = reinterpret_cast<std::uint32_t*>(static_cast<std::uint8_t*>(mapped) + slot * region_bytes); + for (UINT i = 0; i < words; ++i) w[i] = pattern(tag, r0 / 4 + i) ^ key; + const D3D12_RANGE written{slot * region_bytes, (slot + 1) * region_bytes}; + readback->Unmap(0, &written); + return true; + } + unsigned debug_errors() + { + if (!info) return 0; + unsigned errors = 0; + for (UINT64 i = 0; i < info->GetNumStoredMessages(); ++i) { + SIZE_T bytes = 0; + if (FAILED(info->GetMessage(i, nullptr, &bytes))) continue; + std::vector<char> storage(bytes); + auto* message = reinterpret_cast<D3D12_MESSAGE*>(storage.data()); + if (FAILED(info->GetMessage(i, message, &bytes)) || message->Severity > D3D12_MESSAGE_SEVERITY_ERROR) continue; + if (++errors <= 8) std::printf("debug layer ERROR id %d: %.300s\n", message->ID, message->pDescription); + } + return errors; + } +}; + +// One title command list: a wrapper list on its own wrapper allocator, recorded on its desktop list. +struct TitleList { + ComPtr<ID3D12CommandAllocator> allocator; + ComPtr<IUnknown> list; + ComPtr<ID3D12GraphicsCommandList> native; + Gpu* gpu = nullptr; + + bool begin(Gpu& g, D3D12_COMMAND_LIST_TYPE type = D3D12_COMMAND_LIST_TYPE_DIRECT) + { + gpu = &g; + if (FAILED(g.guest->CreateCommandAllocator(type, IID_PPV_ARGS(&allocator)))) return false; + using CreateList = HRESULT(WINAPI*)(IUnknown*, const void*, IUnknown*, IUnknown*, REFIID, void**); + const UINT list_desc[]{static_cast<UINT>(type), 2, 1, 0}; + auto* create = reinterpret_cast<CreateList>((*reinterpret_cast<void***>(g.guest.Get()))[73]); + if (FAILED(create(g.guest.Get(), list_desc, allocator.Get(), nullptr, __uuidof(ID3D12GraphicsCommandList), + reinterpret_cast<void**>(list.GetAddressOf())))) + return false; + if (FAILED(static_cast<HRESULT>(invoke(list.Get(), 139, arg(allocator.Get()))))) return false; + native = underlying<ID3D12GraphicsCommandList>(g.desktop.Get(), g.guest.Get(), list.Get()); + return native != nullptr; + } + void barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) + { + D3D12_RESOURCE_BARRIER b{}; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + native->ResourceBarrier(1, &b); + } + void dispatch(D3D12_GPU_VIRTUAL_ADDRESS src, D3D12_GPU_VIRTUAL_ADDRESS dst) + { + native->SetComputeRootSignature(gpu->root.Get()); + native->SetPipelineState(gpu->pipeline.Get()); + native->SetComputeRootShaderResourceView(0, src); + native->SetComputeRootUnorderedAccessView(1, dst); + native->SetComputeRoot32BitConstant(2, key, 0); + native->Dispatch(words / 64, 1, 1); + } + // output[i] = buffer[r0 + 4i] ^ key, then output -> readback, in result slot `slot`. + void read(ID3D12Resource* buffer, UINT slot = 0) + { + const UINT64 at = slot * region_bytes; + barrier(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + dispatch(buffer->GetGPUVirtualAddress() + r0, gpu->output->GetGPUVirtualAddress() + at); + barrier(buffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + native->CopyBufferRegion(gpu->readback.Get(), at, gpu->output.Get(), at, region_bytes); + barrier(gpu->output.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + } + // For a COPY list: buffer[r0 .. r0 + 4 KiB) -> readback slot, unchanged (the buffer is promoted + // from COMMON to COPY_SOURCE implicitly). + void read_copy(ID3D12Resource* buffer, UINT slot = 0) + { + native->CopyBufferRegion(gpu->readback.Get(), slot * region_bytes, buffer, r0, region_bytes); + } + // buffer[r1 + 4i] = G[i] ^ key. + void write_g(ID3D12Resource* buffer) + { + barrier(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + dispatch(gpu->source->GetGPUVirtualAddress(), buffer->GetGPUVirtualAddress() + r1); + barrier(buffer, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + } + bool close() { return SUCCEEDED(static_cast<HRESULT>(invoke(list.Get(), 9))); } + // Through the queue wrapper (slot 10, ExecuteCommandLists), behind the gate if it is held. + UINT64 submit() + { + if (gpu->gate_armed) gpu->queue->Wait(gpu->gate.Get(), gpu->gate_value); + void* lists[] = {list.Get()}; + invoke(gpu->guest_queue.Get(), 10, 1, arg(lists)); + gpu->queue->Signal(gpu->done.Get(), ++gpu->submitted); + return gpu->submitted; + } + // Through another queue's wrapper; the lane's fence completes it. + UINT64 submit_on(Lane& lane) + { + void* lists[] = {list.Get()}; + invoke(lane.guest.Get(), 10, 1, arg(lists)); + lane.native->Signal(lane.fence.Get(), ++lane.value); + return lane.value; + } + // Past the wrapper: the desktop list on the desktop queue (a submission without the refresh). + UINT64 submit_bypassing() + { + ID3D12CommandList* lists[] = {native.Get()}; + gpu->queue->ExecuteCommandLists(1, lists); + gpu->queue->Signal(gpu->done.Get(), ++gpu->submitted); + return gpu->submitted; + } +}; + +// ---- Placement through slot 133 ---- + +struct Placed { + HRESULT hr = E_FAIL; + const void* address = nullptr; + ComPtr<IUnknown> wrapper; + ComPtr<ID3D12Resource> backing; + X2wLinearBufferInfo info{}; + bool linear = false; +}; + +Placed place(Gpu& gpu, std::uint8_t* address, bool gpu_written) +{ + Placed p; + p.address = address; + using Place = HRESULT(WINAPI*)(IUnknown*, void*, const D3D12_RESOURCE_DESC*, UINT, const void*, REFIID, void**); + const auto desc = buffer_desc(buffer_bytes, gpu_written ? D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS : D3D12_RESOURCE_FLAG_NONE); + auto* slot = reinterpret_cast<Place>((*reinterpret_cast<void***>(gpu.guest.Get()))[133]); + p.hr = slot(gpu.guest.Get(), address, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), + reinterpret_cast<void**>(p.wrapper.GetAddressOf())); + if (SUCCEEDED(p.hr) && p.wrapper) { + p.backing = underlying<ID3D12Resource>(gpu.desktop.Get(), gpu.guest.Get(), p.wrapper.Get()); + p.linear = x2w_d3d12_linear_buffer_info(p.wrapper.Get(), &p.info); + } + return p; +} +void refresh_info(Placed& p) +{ + if (p.wrapper) p.linear = x2w_d3d12_linear_buffer_info(p.wrapper.Get(), &p.info); +} + +std::string backing_text(const Placed& p) +{ + if (FAILED(p.hr)) return "refused " + hex(p.hr); + if (!p.linear) return "default"; + char text[160]; + if (p.info.path == 3) + std::snprintf(text, sizeof(text), "kept default backing (refusal %s, share %s, feature %s)", hex(p.info.refusal_hr).c_str(), + hex(p.info.share_hr).c_str(), hex(p.info.feature_hr).c_str()); + else if (p.info.path == 1) + std::snprintf(text, sizeof(text), "shared (heap generation %llu, feature %s)", + static_cast<unsigned long long>(p.info.heap_generation), hex(p.info.feature_hr).c_str()); + else + std::snprintf(text, sizeof(text), "copied (share %s, feature %s, %llu bytes in %llu refreshes, staging %llu)", + hex(p.info.share_hr).c_str(), hex(p.info.feature_hr).c_str(), + static_cast<unsigned long long>(p.info.bytes_copied), static_cast<unsigned long long>(p.info.refreshes), + static_cast<unsigned long long>(p.info.last_staging)); + return text; +} + +X2wLinearBufferTotals totals() +{ + X2wLinearBufferTotals t{}; + x2w_d3d12_linear_buffer_totals(&t); + return t; +} + +// ---- Cases ---- + +struct Run { + Gpu& gpu; + Path path; + bool adapter_heaps; // the adapter's own D3D12_FEATURE_EXISTING_HEAPS: the default aliases private ranges + unsigned failures = 0, skips = 0, kept_rows = 0; + std::vector<std::pair<std::string, bool>> results; // case name -> passed (for --mutate) + + bool copying() const { return path == Path::copy || path == Path::refusal; } + // The copy backs this pool's buffers: forced, refused by the host, or an XMem view on the share path. + bool copied(const Pool& pool) const { return copying() || (path == Path::share && pool.xmem); } + // The sharing HRESULT a refused sharing attempt reports for a buffer inside one allocation. + HRESULT share_refusal(const Pool& pool) const + { + return path == Path::refusal ? DXGI_ERROR_UNSUPPORTED : path == Path::share && pool.xmem ? HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) : S_FALSE; + } + // The default backing aliases this pool: a private range on an adapter with existing heaps. + bool default_aliases(const Pool& pool) const { return !pool.xmem && adapter_heaps; } + // A refusal that kept the default backing: slot 133 returned S_OK with an object, and info and the + // slot 133 log line carry the refusal HRESULT. + bool kept_ok(const Placed& p, HRESULT want, std::string& text) + { + char needle[64]; + std::snprintf(needle, sizeof(needle), "kept default backing: linear refusal 0x%08lx", static_cast<unsigned long>(want)); + const bool logged = log_has("address=" + pointer_text(p.address), needle); + const bool ok = SUCCEEDED(p.hr) && p.wrapper && p.linear && p.info.path == 3 && p.info.refusal_hr == want && logged; + text += std::string("; refusal ") + (p.linear ? hex(p.info.refusal_hr) : std::string("NOT IN INFO")) + " (expected " + hex(want) + + "), log line " + (logged ? "present" : "MISSING"); + ++kept_rows; + return ok; + } + void row(const Pool& pool, const char* name, bool pass, const std::string& text) + { + std::printf("%-8s %-8s %-6s %s: %s\n", path_name(path), pool.name(), name, pass ? "PASS" : "FAIL", text.c_str()); + results.emplace_back(name, pass); + if (!pass) ++failures; + } + // The path's expected backing for a GPU-read buffer in this pool. + bool backing_ok(const Pool& pool, const Placed& p, bool split = false) const + { + switch (path) { + case Path::default_backing: return SUCCEEDED(p.hr) && !p.linear; + case Path::share: + if (!pool.xmem) return SUCCEEDED(p.hr) && p.linear && p.info.path == 1 && p.info.share_hr == S_OK; + return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.feature_hr == S_OK && + p.info.share_hr == (split ? E_INVALIDARG : HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)); + case Path::copy: return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.share_hr == S_FALSE; + case Path::refusal: return SUCCEEDED(p.hr) && p.linear && p.info.path == 2 && p.info.share_hr == DXGI_ERROR_UNSUPPORTED && + p.info.feature_hr == DXGI_ERROR_UNSUPPORTED; + default: return false; // untracked: kept_ok decides + } + } + // What the GPU must read in case a: B, except where the default backing does not alias (zero). + bool read_ok(const Pool& pool, const Tally& t, Tag want) const + { + if ((path == Path::default_backing || path == Path::untracked) && !default_aliases(pool)) return t.zero == words; + return t.count[want] == words; + } + + void case_a(Pool& pool, bool split = false) + { + const char* name = split ? "split" : "a"; + Memory memory; + if (!(split ? pool.allocate_split(memory, A) : pool.allocate(memory, A))) return row(pool, name, false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, name, false, "slot 133 -> " + hex(p.hr)); + list.read(p.backing.Get()); + if (!list.close()) return row(pool, name, false, "Close failed"); + write(memory.buffer(), r0, B, words); // after bind and record, before ExecuteCommandLists + if (!gpu.wait(list.submit())) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; GPU read " + t.text(); + bool pass = read_ok(pool, t, B) && (!p.linear || p.info.path != 2 || p.info.bytes_copied == buffer_bytes); + if (path == Path::untracked) + pass &= kept_ok(p, E_NOT_VALID_STATE, text); // no submit fence to guard staging reuse + else + pass &= backing_ok(pool, p, split); + if (path == Path::default_backing || path == Path::untracked) + text += default_aliases(pool) ? " (old behaviour: aliased)" : " (old behaviour: not aliased, no copy)"; + row(pool, name, pass, text); + if (split || !pass || path == Path::default_backing || path == Path::untracked) return; + + // a2: 16 words change; only they are copied. + TitleList second; + if (!second.begin(gpu)) return row(pool, "a2", false, "list"); + second.read(p.backing.Get()); + second.close(); + const UINT64 before = p.info.bytes_copied; + write(memory.buffer(), r0 + 64 * 4, E, 16); + if (!gpu.wait(second.submit())) return row(pool, "a2", false, "fence timeout"); + const Tally t2 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const UINT64 copied = p.info.bytes_copied - before; + const bool pass2 = t2.count[E] == 16 && t2.count[B] == words - 16 && (p.info.path != 2 || copied == 64); + row(pool, "a2", pass2, "GPU read " + t2.text() + "; bytes copied for this submission " + std::to_string(copied) + + (p.info.path == 2 ? " (expected 64)" : " (shared: none)")); + } + + void case_b(Pool& pool, bool hold) + { + const char* name = hold ? "d2" : "b"; + Memory memory; + if (!pool.allocate(memory, filler)) return row(pool, name, false, "allocation failed"); + write(memory.buffer(), r1, P, words); + Placed p = place(gpu, memory.buffer(), true); + const auto* alias = reinterpret_cast<const std::uint32_t*>(memory.buffer() + r1); + // The copy has no point at which a GPU write reaches the title memory: slot 133 keeps the default + // backing and reports the sharing HRESULT (the feature gate's DXGI_ERROR_UNSUPPORTED, or + // ERROR_NOT_SUPPORTED for an XMem view), or DXGI_ERROR_UNSUPPORTED when sharing is not attempted. + const bool kept = copied(pool) || path == Path::untracked; + const bool on_default = kept || path == Path::default_backing; + const HRESULT want = share_refusal(pool) == S_FALSE ? DXGI_ERROR_UNSUPPORTED : share_refusal(pool); + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, name, false, "slot 133 -> " + hex(p.hr)); + list.write_g(p.backing.Get()); + if (!list.close()) return row(pool, name, false, "Close failed"); + if (hold) gpu.hold(); + const UINT64 value = list.submit(); + std::string early; + bool early_ok = true; + if (hold) { + // Ordered before the GPU write by the queue's Wait on the gate: no timing assumption. + const bool pending = gpu.done->GetCompletedValue() < value; + const Tally before = tally(alias, r1 / 4, 0); + early_ok = pending && before.count[P] == words; + early = std::string("before the fence: ") + (pending ? "in flight" : "COMPLETE") + ", alias " + before.text() + "; "; + gpu.open_gate(); + } + if (!gpu.wait(value)) return row(pool, name, false, "fence timeout"); + const Tally t = tally(alias, r1 / 4, key), raw = tally(alias, r1 / 4, 0); + // The words around the written region keep their filler. + bool around = true; + const auto* buffer = reinterpret_cast<const std::uint32_t*>(memory.buffer()); + for (UINT64 i = 0; i < buffer_bytes / 4; ++i) + if (i < r1 / 4 || i >= r1 / 4 + words) around &= buffer[i] == pattern(filler, i); + refresh_info(p); + bool pass; + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; " + early + "after the fence alias " + + (t.count[G] ? t.text() + " (G ^ key)" : raw.text()) + (around ? ", neighbours kept" : ", NEIGHBOURS CHANGED"); + // Visible: shared, or a default backing that aliases this pool. + const bool visible = on_default ? default_aliases(pool) : true; + pass = early_ok && around && (visible ? t.count[G] == words : raw.count[P] == words); + if (path == Path::default_backing) pass &= SUCCEEDED(p.hr) && !p.linear; + else if (kept) pass &= kept_ok(p, want, text); + else pass &= p.linear && p.info.path == 1; + if (on_default) text += visible ? " (old behaviour: aliased)" : " (old behaviour: not aliased, the alias keeps P)"; + row(pool, name, pass, text); + } + + // c: held submissions and backing reuse only after completion. + void case_c(Pool& pool) + { + if (path == Path::default_backing || path == Path::untracked) return; + const bool copying = copied(pool); + struct Held { + Memory memory; + Placed placed; + TitleList list; + UINT64 value = 0; + Tag tag; + }; + const Tag tags[3] = {B, C, D}; + Held held[3]; + const X2wLinearBufferTotals start = totals(); + gpu.hold(); + // Copying: the refreshes are held too, on the internal queue, so their staging stays in flight. + if (copying && !gpu.hold_internal()) return row(pool, "c", false, "internal refresh queue not available"); + for (int i = 0; i < 3; ++i) { + Held& h = held[i]; + h.tag = tags[i]; + if (!pool.allocate(h.memory, h.tag)) return row(pool, "c", false, "allocation failed"); + h.placed = place(gpu, h.memory.buffer(), false); + if (FAILED(h.placed.hr) || !h.placed.backing || !h.list.begin(gpu)) return row(pool, "c", false, "slot 133 -> " + hex(h.placed.hr)); + h.list.read(h.placed.backing.Get(), static_cast<UINT>(i + 1)); + h.list.close(); + h.value = h.list.submit(); + refresh_info(h.placed); + // The title is done with X once it is submitted: on the shared path it releases it now. + if (i == 0 && !copying) h.placed.wrapper.Reset(); + } + const X2wLinearBufferTotals during = totals(); + const bool pending = gpu.done->GetCompletedValue() < held[0].value; + // Each held submission reads its own buffer into its own result slot. + if (copying) gpu.open_internal(); + gpu.open_gate(); + if (!gpu.wait(held[2].value)) return row(pool, "c", false, "fence timeout"); + std::string reads = "held reads"; + bool reads_ok = true; + for (int i = 0; i < 3; ++i) { + const Tally t = tally(gpu.read_output(static_cast<UINT>(i + 1)).data(), r0 / 4, key); + reads_ok &= t.count[held[i].tag] == words; + reads += std::string(" ") + "XYZ"[i] + "=[" + t.text() + "]"; + } + std::string text; + bool pass = pending && reads_ok; + if (copying) { + const UINT64 s0 = held[0].placed.info.last_staging, s1 = held[1].placed.info.last_staging, + s2 = held[2].placed.info.last_staging; + const bool distinct = s0 && s1 && s2 && s0 != s1 && s0 != s2 && s1 != s2; + // After completion the next refresh takes one of those buffers again. + Memory memory; + Placed w; + TitleList list; + if (!pool.allocate(memory, E)) return row(pool, "c", false, "allocation failed"); + w = place(gpu, memory.buffer(), false); + if (FAILED(w.hr) || !list.begin(gpu)) return row(pool, "c", false, "slot 133 -> " + hex(w.hr)); + list.read(w.backing.Get()); + list.close(); + if (!gpu.wait(list.submit())) return row(pool, "c", false, "fence timeout"); + const Tally after = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(w); + const X2wLinearBufferTotals end = totals(); + const bool reused_after = w.info.last_staging == s0 || w.info.last_staging == s1 || w.info.last_staging == s2; + pass &= distinct && reused_after && after.count[E] == words && end.staging_reused > during.staging_reused; + char line[320]; + std::snprintf(line, sizeof(line), + "held: staging %llu/%llu/%llu (%s; %llu created, %llu completed ones reused during the hold); after the fence the next refresh " + "took staging %llu (%s) and read %s", + static_cast<unsigned long long>(s0), static_cast<unsigned long long>(s1), static_cast<unsigned long long>(s2), + distinct ? "distinct" : "SHARED", static_cast<unsigned long long>(during.staging_created - start.staging_created), + static_cast<unsigned long long>(during.staging_reused - start.staging_reused), + static_cast<unsigned long long>(w.info.last_staging), reused_after ? "reused" : "NOT REUSED", after.text().c_str()); + text = line; + } else { + // Shared (a private range): after the fence the title places a new buffer Z at X's address. + const std::string reuse = "after the fence Z is placed at X's address"; + Memory z = held[0].memory; + write(z.buffer(), 0, E, buffer_bytes / 4); + Placed zp = place(gpu, z.buffer(), false); + TitleList list; + if (FAILED(zp.hr) || !list.begin(gpu)) return row(pool, "c", false, "slot 133 -> " + hex(zp.hr)); + list.read(zp.backing.Get()); + list.close(); + if (!gpu.wait(list.submit())) return row(pool, "c", false, "fence timeout"); + const Tally after = tally(gpu.read_output().data(), r0 / 4, key); + const UINT64 gx = held[0].placed.info.heap_generation, gz = zp.info.heap_generation; + pass &= zp.linear && zp.info.path == 1 && gz == gx && after.count[E] == words; + text = reuse + "; heap generation " + std::to_string(gx) + " -> " + std::to_string(gz) + + " (the range's cached heap); Z read " + after.text(); + } + row(pool, "c", pass, std::string(pending ? "held in flight" : "NOT HELD") + "; " + reads + "; " + text); + } + + // Measured, not asserted (share path, XMem): why slot 133 does not share a view. A heap opened from + // the view, with a buffer placed on it, and XMem's unmap of the view's pages, before and after the + // heap and buffer are released. + void probe_view_pin(Pool& pool) + { + if (path != Path::share || !pool.xmem) return; + Memory memory; + ComPtr<ID3D12Device3> device3; + if (!pool.allocate(memory, A) || FAILED(gpu.desktop.As(&device3))) return; + ComPtr<ID3D12Heap> heap; + ComPtr<ID3D12Resource> buffer; + HRESULT hr = device3->OpenExistingHeapFromAddress(memory.cpu, IID_PPV_ARGS(&heap)); + const auto desc = buffer_desc(buffer_bytes, D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER); + if (SUCCEEDED(hr)) hr = gpu.desktop->CreatePlacedResource(heap.Get(), buffer_offset, &desc, D3D12_RESOURCE_STATE_COMMON, + nullptr, IID_PPV_ARGS(&buffer)); + const auto count = static_cast<ULONG_PTR>(memory.tokens.size()); + const bool held_unmap = XMemMapPhysicalPages(memory.cpu, count, nullptr) == memory.cpu; + const DWORD held_error = held_unmap ? 0 : GetLastError(); + buffer.Reset(); + heap.Reset(); + const bool unmap = held_unmap || XMemMapPhysicalPages(memory.cpu, count, nullptr) == memory.cpu; + const DWORD error = unmap ? 0 : GetLastError(); + const bool freed = unmap && XMemFreePhysicalPages(count, memory.tokens.data()); + std::printf("%-8s %-8s %-6s measured: heap from the view and placed buffer %s; XMem unmap while they live %s (error %lu); " + "after their release %s (error %lu), pages %s\n", path_name(path), pool.name(), "pin", hex(hr).c_str(), + held_unmap ? "succeeded" : "failed", held_error, unmap ? "succeeded" : "failed", error, + freed ? "freed" : "not freed"); + } + + // stale: a refresh that cannot be staged; the submission still runs, with the last upload. + void case_stale(Pool& pool) + { + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "stale", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList first, second, third; + if (FAILED(p.hr) || !p.backing || !first.begin(gpu) || !second.begin(gpu) || !third.begin(gpu)) + return row(pool, "stale", false, "slot 133 -> " + hex(p.hr)); + first.read(p.backing.Get()); + first.close(); + if (!gpu.wait(first.submit())) return row(pool, "stale", false, "fence timeout (first)"); + const Tally t1 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool fresh1 = p.linear && p.info.path == 2 && !p.info.stale; + write(memory.buffer(), r0, B, words); + second.read(p.backing.Get()); + second.close(); + // The refresh of this submission fails (fixture fault): it must still run and complete. + const bool completed = gpu.wait(second.submit()); + const Tally t2 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + char needle[64]; + std::snprintf(needle, sizeof(needle), "failed 0x%08lx", static_cast<unsigned long>(E_OUTOFMEMORY)); + const bool logged = log_has("refresh of " + pointer_text(p.backing.Get()), needle); + const bool stale2 = p.info.stale == 1 && p.info.refresh_failures == 1 && p.info.last_refresh_hr == E_OUTOFMEMORY; + const unsigned stale_flag = p.info.stale; + third.read(p.backing.Get()); + third.close(); + if (!gpu.wait(third.submit())) return row(pool, "stale", false, "fence timeout (third)"); + const Tally t3 = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool pass = fresh1 && t1.count[A] == words && completed && t2.count[A] == words && stale2 && logged && + t3.count[B] == words && !p.info.stale; + row(pool, "stale", pass, + "refreshed " + t1.text() + "; failed refresh: submission " + (completed ? "completed" : "DID NOT COMPLETE") + ", read " + + t2.text() + " (last upload), stale=" + std::to_string(stale_flag) + " " + (stale2 ? "reported" : "NOT REPORTED") + + " with " + hex(E_OUTOFMEMORY) + ", log line " + (logged ? "present" : "MISSING") + "; next submission read " + t3.text() + + (p.info.stale ? ", STILL STALE" : ", stale cleared")); + } + + // q.comp, q.copy: the refresh on a COMPUTE and a COPY queue (implicit COMMON -> COPY_DEST there too). + void case_queues(Pool& pool) + { + for (const auto type : {D3D12_COMMAND_LIST_TYPE_COMPUTE, D3D12_COMMAND_LIST_TYPE_COPY}) { + const bool compute = type == D3D12_COMMAND_LIST_TYPE_COMPUTE; + const char* name = compute ? "q.comp" : "q.copy"; + Lane lane; + Memory memory; + if (!gpu.lane(lane, type)) return row(pool, name, false, "queue wrapper not created"); + if (!pool.allocate(memory, A)) return row(pool, name, false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList first, second; + if (FAILED(p.hr) || !p.backing || !first.begin(gpu, type) || !second.begin(gpu, type)) + return row(pool, name, false, "slot 133 -> " + hex(p.hr) + " or list creation failed"); + const std::uint32_t mask = compute ? key : 0; + compute ? first.read(p.backing.Get()) : first.read_copy(p.backing.Get()); + if (!first.close()) return row(pool, name, false, "Close failed"); + write(memory.buffer(), r0, B, words); + if (!wait_fence(lane.fence.Get(), first.submit_on(lane))) return row(pool, name, false, "fence timeout"); + const Tally t1 = tally(gpu.read_output().data(), r0 / 4, mask); + refresh_info(p); + const UINT64 after_first = p.info.bytes_copied; + compute ? second.read(p.backing.Get()) : second.read_copy(p.backing.Get()); + second.close(); + write(memory.buffer(), r0 + 64 * 4, E, 16); + if (!wait_fence(lane.fence.Get(), second.submit_on(lane))) return row(pool, name, false, "fence timeout"); + const Tally t2 = tally(gpu.read_output().data(), r0 / 4, mask); + refresh_info(p); + const UINT64 delta = p.info.bytes_copied - after_first; + const bool pass = p.linear && p.info.path == 2 && !p.info.stale && p.info.refresh_failures == 0 && t1.count[B] == words && + after_first == buffer_bytes && t2.count[E] == 16 && t2.count[B] == words - 16 && delta == 64; + row(pool, name, pass, + std::string(compute ? "COMPUTE queue, dispatch read: " : "COPY queue, CopyBufferRegion read: ") + "first submission " + + t1.text() + " (" + std::to_string(after_first) + " bytes refreshed), then " + t2.text() + " (" + + std::to_string(delta) + " bytes)" + (p.info.stale ? ", STALE" : "")); + } + } + + // gate2q: one buffer, two queues, one CPU write before both submissions (the review repro). + void case_gate2q(Pool& pool, bool held) + { + const char* name = held ? "gate2q.held" : "gate2q"; + Lane q2; + Memory memory; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A)) return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + write(memory.buffer(), r0, B, words); + const X2wLinearBufferTotals before = totals(); + gpu.hold(); + if (held && !gpu.hold_internal()) return row(pool, name, false, "internal refresh queue not available"); + const UINT64 v1 = l1.submit(); // queue 1, behind the title gate: its refresh goes to the internal queue + const UINT64 v2 = l2.submit_on(q2); + bool q2_waited = true; + if (held) { + // Queue 2 has nothing to refresh itself (B is already enqueued) but must wait for that refresh. + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + q2_waited = q2.fence->GetCompletedValue() < v2; + gpu.open_internal(); + } + const bool q2_done = wait_fence(q2.fence.Get(), v2); + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + const Tally t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + gpu.open_gate(); + if (!gpu.wait(v1)) return row(pool, name, false, "fence timeout (queue 1)"); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = q2_done && q1_pending && q2_waited && t2.count[B] == words && t1.count[B] == words && !x.info.stale && + x.info.refresh_failures == 0 && after.consumer_waits > before.consumer_waits; + row(pool, name, pass, + std::string("queue 2 ") + (q2_done ? "completed" : "DID NOT COMPLETE") + " with queue 1 " + + (q1_pending ? "still gated" : "NOT GATED") + (held ? (q2_waited ? ", after waiting for the held refresh" : ", WITHOUT WAITING for the held refresh") : "") + + ": read " + t2.text() + "; queue 1 then read " + t1.text() + "; consumer waits +" + + std::to_string(after.consumer_waits - before.consumer_waits) + (x.info.stale ? ", STALE" : "")); + } + + // xq: queue 1 waits on a title fence that queue 2 signals after its list. + // gpuw: a recorded copy (list slot 15, CopyBufferRegion) writes G into a copied buffer; the title then + // changes bytes on both sides of it. The buffer keeps the GPU's bytes (no refresh spans them), and + // info and totals report it. + void case_gpuw(Pool& pool) + { + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "gpuw", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(p.hr) || !p.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, "gpuw", false, "slot 133 -> " + hex(p.hr)); + l0.read(p.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, "gpuw", false, "fence timeout"); // A uploaded + const X2wLinearBufferTotals before = totals(); + // The title's copy, through the list wrapper: G (indexed as at r1) into the buffer at r0. + invoke(l1.list.Get(), 15, arg(p.wrapper.Get()), r0, arg(gpu.source.Get()), 0, region_bytes); + if (!l1.close() || !gpu.wait(l1.submit())) return row(pool, "gpuw", false, "copy submission failed"); + write(memory.buffer(), 0, D, 1); // the first and last words, around the written region + write(memory.buffer(), buffer_bytes - 4, D, 1); + l2.read(p.backing.Get(), 1); + l2.close(); + if (!gpu.wait(l2.submit())) return row(pool, "gpuw", false, "fence timeout"); + const Tally t = tally(gpu.read_output(1).data(), r1 / 4, key); // G words carry their r1 indices + refresh_info(p); + const X2wLinearBufferTotals after = totals(); + const bool pass = p.linear && p.info.path == 2 && p.info.gpu_written == 1 && t.count[G] == words && + after.gpu_written == before.gpu_written + 1; + row(pool, "gpuw", pass, + "after a recorded copy of G and title writes around it the GPU read " + t.text() + " (expected G: not refreshed); " + + "gpu_written " + std::to_string(p.info.gpu_written) + ", totals +" + std::to_string(after.gpu_written - before.gpu_written)); + } + + // gpuw.discard (the review repro): a recorded copy into a copied buffer that is closed and then reset + // without being submitted. The buffer must stay refreshed: the next read sees the CPU's B, and it is + // not reported GPU-written. + void case_gpuw_discard(Pool& pool) + { + const char* name = "gpuw.discard"; + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, name, false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(p.hr) || !p.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(p.hr)); + l0.read(p.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + const X2wLinearBufferTotals before = totals(); + // The title's copy of G into the buffer, recorded and closed on another list, then discarded. + invoke(l1.list.Get(), 15, arg(p.wrapper.Get()), r0, arg(gpu.source.Get()), 0, region_bytes); + const bool closed = l1.close(); + const bool reset = SUCCEEDED(static_cast<HRESULT>(invoke(l1.list.Get(), 139, arg(l1.allocator.Get())))); + write(memory.buffer(), r0, B, words); + l2.read(p.backing.Get(), 1); + l2.close(); + if (!gpu.wait(l2.submit())) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output(1).data(), r0 / 4, key); + refresh_info(p); + const X2wLinearBufferTotals after = totals(); + const bool pass = closed && reset && p.linear && p.info.path == 2 && p.info.gpu_written == 0 && t.count[B] == words && + after.gpu_written == before.gpu_written && !p.info.stale; + row(pool, name, pass, + std::string("a copy of G recorded, closed ") + (closed ? "" : "(CLOSE FAILED) ") + "and reset " + + (reset ? "" : "(RESET FAILED) ") + "without a submission, then the CPU wrote B: the GPU read " + t.text() + + " (expected B: still refreshed); gpu_written " + std::to_string(p.info.gpu_written) + ", totals +" + + std::to_string(after.gpu_written - before.gpu_written)); + } + + // war: a read of A on queue 1 is held behind a title gate (on the desktop queue, past the wrapper); the + // CPU then writes B and queue 2 submits a read, whose refresh must not land before queue 1's read: queue + // 1 reads A, queue 2 reads B, and the refresh's copy waited for queue 1 (producer_waits). + void case_war(Pool& pool) + { + const char* name = "war"; + Lane q2; + Memory memory; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A)) return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + const X2wLinearBufferTotals before = totals(); + gpu.hold(); + const UINT64 v1 = l1.submit(); // queue 1, gated: nothing to refresh (the title still holds A) + write(memory.buffer(), r0, B, words); + const UINT64 v2 = l2.submit_on(q2); // its refresh (B) is ordered behind queue 1's read + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + const bool q2_held = q2.fence->GetCompletedValue() < v2; + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + gpu.open_gate(); + const bool q1_done = gpu.wait(v1), q2_done = wait_fence(q2.fence.Get(), v2); + if (!q1_done || !q2_done) return row(pool, name, false, "fence timeout after the gate"); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = q1_pending && q2_held && t1.count[A] == words && t2.count[B] == words && !x.info.stale && + x.info.refresh_failures == 0 && after.producer_waits > before.producer_waits; + row(pool, name, pass, + std::string("queue 1 ") + (q1_pending ? "gated" : "NOT GATED") + " with a read of A; after the CPU wrote B, queue 2 " + + (q2_held ? "waited for it" : "COMPLETED FIRST (the refresh did not wait)") + "; queue 1 read " + t1.text() + + " (expected A), queue 2 read " + t2.text() + " (expected B); producer waits +" + + std::to_string(after.producer_waits - before.producer_waits)); + } + + // xq.write: queue 1 waits through its wrapper (queue slot 17) on a title fence F, then submits a read of A + // (nothing to refresh). The CPU writes B and queue 2 submits a read. Its refresh would have to wait for + // queue 1, which sits behind F, and F may be reached only by later work (here the title signals it from + // queue 2): there is no safe completion order, so the submission must be refused, with nothing of it + // executed (its result slot keeps the fixture's P) and the refusal counted and logged. The title then + // signals F through queue 2's wrapper (queue slot 16): queue 1 must complete and read A. The refused + // recording, submitted again on queue 2 once queue 1 is done, must read B, with no further refusal. + void case_xq_write(Pool& pool) + { + const char* name = "xq.write"; + Lane q2; + Memory memory; + ComPtr<IUnknown> fence; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A) || + FAILED(static_cast<HRESULT>(invoke(gpu.guest.Get(), 36, 0, D3D12_FENCE_FLAG_NONE, arg(&__uuidof(ID3D12Fence)), + arg(fence.GetAddressOf())))) || !fence) + return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + if (!gpu.fill_output(2, P)) return row(pool, name, false, "result slot could not be filled"); + const X2wLinearBufferTotals before = totals(); + if (FAILED(static_cast<HRESULT>(invoke(gpu.guest_queue.Get(), 17, arg(fence.Get()), 1)))) + return row(pool, name, false, "queue wait (slot 17) failed"); + const UINT64 v1 = l1.submit(); // queue 1, behind F + write(memory.buffer(), r0, B, words); + const UINT64 v2 = l2.submit_on(q2); // needs a refresh of B: refused + // The lane's own fence after the refused lists: queue 2 itself was never blocked. + const bool q2_progress = wait_fence(q2.fence.Get(), v2); + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + const X2wLinearBufferTotals mid = totals(); + const Tally refused = tally(gpu.read_output(2).data(), r0 / 4, key); + const bool logged = log_has("refused: its refresh would have to wait for queue", "no safe completion order"); + // The title's ordinary Signal through queue 2's wrapper releases queue 1. + const HRESULT signal_hr = static_cast<HRESULT>(invoke(q2.guest.Get(), 16, arg(fence.Get()), 1)); + const bool q1_done = gpu.wait(v1); + if (!q1_done) return row(pool, name, false, "queue 1 did not complete after the title's Signal (slot 16) " + hex(signal_hr)); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key); + // A later, safe submission: the refused recording again, with no submission behind a title Wait. + const UINT64 v3 = l2.submit_on(q2); + if (!wait_fence(q2.fence.Get(), v3)) return row(pool, name, false, "fence timeout (queue 2, resubmission)"); + const Tally t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const UINT64 refusals = mid.unsafe_refresh_refusals - before.unsafe_refresh_refusals; + const bool pass = q1_pending && q2_progress && refusals == 1 && refused.count[P] == words && logged && SUCCEEDED(signal_hr) && + t1.count[A] == words && t2.count[B] == words && after.unsafe_refresh_refusals == mid.unsafe_refresh_refusals && + !x.info.stale && x.info.refresh_failures == 0; + row(pool, name, pass, + std::string("queue 1 ") + (q1_pending ? "behind a title Wait (slot 17)" : "NOT HELD by its title Wait") + + " with a read of A; after the CPU wrote B, queue 2's read was " + (refusals == 1 ? "refused" : "NOT REFUSED") + + " (refusals +" + std::to_string(refusals) + ", log line " + (logged ? "present" : "MISSING") + "), its slot " + + refused.text() + " (expected P: nothing ran), queue 2 " + (q2_progress ? "progressed" : "STUCK") + + "; the title's Signal on queue 2 (slot 16) -> " + hex(signal_hr) + ", queue 1 then read " + t1.text() + + " (expected A); the refused recording resubmitted on queue 2 read " + t2.text() + " (expected B), refusals +" + + std::to_string(after.unsafe_refresh_refusals - mid.unsafe_refresh_refusals) + (x.info.stale ? ", STALE" : "")); + } + + // xq.race: xq.write with the title Wait and the read of A on queue 1 issued from two threads at once (the + // review repro). Thread W calls slot 17 Wait(F, 1) on queue 1 and parks through the pause hook (point 3) + // after the desktop Wait and before the wait is recorded. While it is parked, thread S submits the read of A + // on queue 1; the fixture gives it up to 1 s to return before W resumes (S must not take a user value that + // the wait would then be recorded after). Once both returned the CPU writes B and queue 2 submits a read: + // queue 1's read is behind F on the desktop queue, so this refresh has no safe completion order and must be + // refused, as in xq.write (refusals +1, its slot keeps P, queue 2's own fence is reached). The title's + // Signal(F, 1) through queue 2's wrapper must succeed and release queue 1, which reads A; the refused + // recording submitted again then reads B. Every wait is bounded: when queue 2 or queue 1 does not complete, + // the fixture signals F from the CPU (the same fence) so both drain, and the row fails. + void case_xq_race(Pool& pool) + { + const char* name = "xq.race"; + Lane q2; + Memory memory; + ComPtr<IUnknown> fence; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A) || + FAILED(static_cast<HRESULT>(invoke(gpu.guest.Get(), 36, 0, D3D12_FENCE_FLAG_NONE, arg(&__uuidof(ID3D12Fence)), + arg(fence.GetAddressOf())))) || !fence) + return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded and read + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + if (!gpu.fill_output(1, P) || !gpu.fill_output(2, P)) return row(pool, name, false, "result slot could not be filled"); + HANDLE parked = CreateEventW(nullptr, TRUE, FALSE, nullptr), go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE s_returned = CreateEventW(nullptr, TRUE, FALSE, nullptr); + const auto close_events = [&] { + x2w_d3d12_linear_buffer_test_pause(3, nullptr, nullptr); // disarm, if no wait reached it + for (HANDLE h : {parked, go, s_returned}) + if (h) CloseHandle(h); + }; + if (!parked || !go || !s_returned || !x2w_d3d12_linear_buffer_test_pause(3, parked, go)) { + close_events(); + return row(pool, name, false, "pause hook not available"); + } + const X2wLinearBufferTotals before = totals(); + HRESULT wait_hr = E_FAIL; + std::thread tw([&] { wait_hr = static_cast<HRESULT>(invoke(gpu.guest_queue.Get(), 17, arg(fence.Get()), 1)); }); + const bool w_parked = WaitForSingleObject(parked, 5000) == WAIT_OBJECT_0; + UINT64 v1 = 0; + std::thread ts([&] { + v1 = l1.submit(); // queue 1: the unchanged read of A, behind F on the desktop queue + SetEvent(s_returned); + }); + // With the order lock S cannot return while W is parked; without it, it returns at once. + const bool s_returned_while_parked = WaitForSingleObject(s_returned, 1000) == WAIT_OBJECT_0; + SetEvent(go); + tw.join(); + ts.join(); // bounded: W's park ends after 20 s at most, and S waits only for W + close_events(); + write(memory.buffer(), r0, B, words); + const UINT64 v2 = l2.submit_on(q2); // needs a refresh of B, which would wait for queue 1: must be refused + const bool q2_progress = poll_fence(q2.fence.Get(), v2, 3000); + const bool q1_pending = gpu.done->GetCompletedValue() < v1; + const X2wLinearBufferTotals mid = totals(); + const Tally refused = tally(gpu.read_output(2).data(), r0 / 4, key); + // The title's Signal through queue 2's wrapper releases queue 1. + const HRESULT signal_hr = static_cast<HRESULT>(invoke(q2.guest.Get(), 16, arg(fence.Get()), 1)); + const bool q1_done = poll_fence(gpu.done.Get(), v1, 3000); + const UINT64 refusals = mid.unsafe_refresh_refusals - before.unsafe_refresh_refusals; + std::string text = std::string("W ") + (w_parked ? "parked" : "DID NOT PARK") + " between its desktop Wait and its record (slot 17 -> " + + hex(wait_hr) + "); S's read of A on queue 1 " + + (s_returned_while_parked ? "RETURNED WHILE W WAS PARKED" : "waited for W") + "; after the CPU wrote B, queue 2's read was " + + (refusals == 1 ? "refused" : "NOT REFUSED") + " (refusals +" + std::to_string(refusals) + "), its slot " + + refused.text() + " (expected P), queue 2 " + (q2_progress ? "progressed" : "STUCK") + + "; the title's Signal on queue 2 (slot 16) -> " + hex(signal_hr) + ", queue 1 " + + (q1_done ? "completed" : "STILL PENDING"); + if (!q2_progress || !q1_done) { + // Cleanup: the CPU reaches F (fence slot 10), so both queues drain before the next case. + invoke(fence.Get(), 10, 1); + const bool drained = wait_fence(gpu.done.Get(), v1) && wait_fence(q2.fence.Get(), v2); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + return row(pool, name, false, + text + "; after a CPU Signal of F both " + (drained ? "drained" : "STILL DID NOT DRAIN") + ": queue 1 read " + t1.text() + + ", queue 2 read " + t2.text()); + } + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key); + // A later, safe submission: the refused recording again, with no submission behind a title Wait. + const UINT64 v3 = l2.submit_on(q2); + if (!wait_fence(q2.fence.Get(), v3)) return row(pool, name, false, text + "; fence timeout (queue 2, resubmission)"); + const Tally t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = w_parked && SUCCEEDED(wait_hr) && q1_pending && q2_progress && refusals == 1 && refused.count[P] == words && + SUCCEEDED(signal_hr) && t1.count[A] == words && t2.count[B] == words && + after.unsafe_refresh_refusals == mid.unsafe_refresh_refusals && !x.info.stale && x.info.refresh_failures == 0; + row(pool, name, pass, + text + " and read " + t1.text() + " (expected A); the refused recording resubmitted on queue 2 read " + t2.text() + + " (expected B), refusals +" + std::to_string(after.unsafe_refresh_refusals - mid.unsafe_refresh_refusals) + + (x.info.stale ? ", STALE" : "")); + } + + // order: two threads' refreshes of one buffer, driven through the pause hook. Thread A stages C and parks + // before its copy is executed; the CPU writes D; thread B stages D, executes its copy first (the lower + // internal value) and parks before publishing; A then executes (the higher value: the backing ends with C) + // and publishes; B publishes last. The next submission must refresh D, which the GPU then reads. + void case_order(Pool& pool) + { + const char* name = "order"; + Lane q2; + Memory memory; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A)) return row(pool, name, false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, la, lb, lc; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !la.begin(gpu) || !lb.begin(gpu) || !lc.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // A uploaded + la.read(x.backing.Get(), 1); + la.close(); + lb.read(x.backing.Get(), 2); + lb.close(); + lc.read(x.backing.Get(), 3); + lc.close(); + HANDLE staged = CreateEventW(nullptr, TRUE, FALSE, nullptr), staged_go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE executed = CreateEventW(nullptr, TRUE, FALSE, nullptr), executed_go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + const auto close_events = [&] { + x2w_d3d12_linear_buffer_test_pause(1, nullptr, nullptr); // disarm what no refresh reached + x2w_d3d12_linear_buffer_test_pause(2, nullptr, nullptr); + for (HANDLE h : {staged, staged_go, executed, executed_go}) + if (h) CloseHandle(h); + }; + if (!staged || !staged_go || !executed || !executed_go || !x2w_d3d12_linear_buffer_test_pause(1, staged, staged_go)) { + close_events(); + return row(pool, name, false, "pause hook not available"); + } + const X2wLinearBufferTotals before = totals(); + write(memory.buffer(), r0, C, words); + UINT64 va = 0, vb = 0; + std::thread ta([&] { va = la.submit(); }); + const bool a_parked = WaitForSingleObject(staged, 5000) == WAIT_OBJECT_0; + write(memory.buffer(), r0, D, words); + const bool armed = x2w_d3d12_linear_buffer_test_pause(2, executed, executed_go); + std::thread tb([&] { vb = lb.submit_on(q2); }); + const bool b_parked = armed && WaitForSingleObject(executed, 5000) == WAIT_OBJECT_0; + SetEvent(staged_go); // A executes after B and publishes first + ta.join(); + SetEvent(executed_go); // then B publishes + tb.join(); + close_events(); + if (!gpu.wait(va) || !wait_fence(q2.fence.Get(), vb)) return row(pool, name, false, "fence timeout"); + const UINT64 vc = lc.submit(); + if (!gpu.wait(vc)) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output(3).data(), r0 / 4, key); + refresh_info(x); + const X2wLinearBufferTotals after = totals(); + const bool pass = a_parked && b_parked && t.count[D] == words && after.reordered_publishes == before.reordered_publishes + 1 && + !x.info.stale && x.info.refresh_failures == 0; + row(pool, name, pass, + std::string("thread A staged C ") + (a_parked ? "and parked" : "BUT DID NOT PARK") + ", thread B staged D and executed first " + + (b_parked ? "and parked" : "BUT DID NOT PARK") + "; A executed and published, then B: the next submission read " + t.text() + + " (expected D: the older publish dropped the upload record); reordered publishes +" + + std::to_string(after.reordered_publishes - before.reordered_publishes)); + } + + // retire: a submission that reads Y snapshots both changed buffers X and Y and parks before staging; the + // title releases X and frees its pages; the submission resumes. X must be skipped as unreadable (no + // fault, no failed refresh); Y is refreshed and read. + void case_retire(Pool& pool) + { + const char* name = "retire"; + Memory mx, my; + // A private X gets an allocation of its own: the pool's range is pinned by the heap that the default + // backing opened on it (case b), so its pages cannot be decommitted. + if (!pool.xmem) { + mx.cpu = static_cast<std::uint8_t*>(VirtualAlloc(nullptr, alloc_pages * page, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (mx.cpu) { + write(mx.cpu, 0, neighbour, buffer_offset / 4); + write(mx.buffer(), 0, A, buffer_bytes / 4); + } + } + if ((pool.xmem ? !pool.allocate(mx, A) : !mx.cpu) || !pool.allocate(my, A)) return row(pool, name, false, "allocation failed"); + Placed x = place(gpu, mx.buffer(), false), y = place(gpu, my.buffer(), false); + TitleList l0, la; + if (FAILED(x.hr) || FAILED(y.hr) || !x.backing || !y.backing || !l0.begin(gpu) || !la.begin(gpu)) + return row(pool, name, false, "slot 133 -> " + hex(x.hr) + "/" + hex(y.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, name, false, "fence timeout"); // both uploaded + la.read(y.backing.Get(), 1); + la.close(); + HANDLE parked = CreateEventW(nullptr, TRUE, FALSE, nullptr), go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!parked || !go || !x2w_d3d12_linear_buffer_test_pause(0, parked, go)) { + if (parked) CloseHandle(parked); + if (go) CloseHandle(go); + return row(pool, name, false, "pause hook not available"); + } + write(mx.buffer(), r0, B, words); + write(my.buffer(), r0, C, words); + const X2wLinearBufferTotals before = totals(); + UINT64 va = 0; + std::thread ta([&] { va = la.submit(); }); + const bool was_parked = WaitForSingleObject(parked, 5000) == WAIT_OBJECT_0; + auto* x_wrapper = x.wrapper.Get(); + x.wrapper.Reset(); // release(): retire X + const bool freed = pool.xmem ? pool.release(mx) : VirtualFree(mx.cpu, 0, MEM_RELEASE) != FALSE; + SetEvent(go); + ta.join(); + x2w_d3d12_linear_buffer_test_pause(0, nullptr, nullptr); // disarm, if no refresh reached it + CloseHandle(parked); + CloseHandle(go); + if (!gpu.wait(va)) return row(pool, name, false, "fence timeout"); + const Tally t = tally(gpu.read_output(1).data(), r0 / 4, key); + X2wLinearBufferInfo xi{}; + x2w_d3d12_linear_buffer_info(x_wrapper, &xi); + refresh_info(y); + const X2wLinearBufferTotals after = totals(); + const bool pass = was_parked && freed && t.count[C] == words && after.unreadable == before.unreadable + 1 && + after.copy_faults == before.copy_faults && xi.refresh_failures == 0 && !y.info.stale; + row(pool, name, pass, + std::string("parked after the snapshot ") + (was_parked ? "" : "(DID NOT PARK) ") + "while the title released X and " + + (freed ? "freed" : "COULD NOT FREE") + " its pages: unreadable +" + std::to_string(after.unreadable - before.unreadable) + + " (expected 1), copy faults +" + std::to_string(after.copy_faults - before.copy_faults) + " (expected 0), X refresh failures " + + std::to_string(xi.refresh_failures) + "; Y read " + t.text()); + } + + // lease: with the mesh XMem lease path on, an XMem placement with console flags 0 is the lease path's: + // slot 133 keeps the default backing (not aliased) and records the deferral; a private one is copied. + void case_lease(Pool& pool) + { + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "lease", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, "lease", false, "slot 133 -> " + hex(p.hr)); + list.read(p.backing.Get()); + list.close(); + write(memory.buffer(), r0, B, words); + if (!gpu.wait(list.submit())) return row(pool, "lease", false, "fence timeout"); + const Tally t = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + std::string text = "slot 133 -> " + hex(p.hr) + ", " + backing_text(p) + "; GPU read " + t.text(); + bool pass; + if (pool.xmem) { + pass = kept_ok(p, HRESULT_FROM_WIN32(ERROR_BUSY), text) && t.zero == words; + text += " (deferred to the XMem lease path; old behaviour: not aliased)"; + } else { + pass = p.linear && p.info.path == 2 && t.count[B] == words; + } + row(pool, "lease", pass, text); + } + + // budget (share, copy): X2W_D3D12_BUDGET counts a shared buffer as placed memory on its heap and a + // copied one as a committed buffer, live while the title holds it and retained after its release. + void case_budget(Pool& pool) + { + Memory memory; + x2w_budget::Snapshot before{}, held{}, released{}; + if (!pool.allocate(memory, A) || !x2w_d3d12_budget_snapshot(&before, sizeof(before))) + return row(pool, "budget", false, "setup failed or X2W_D3D12_BUDGET not on"); + Placed p = place(gpu, memory.buffer(), false); + TitleList list; + if (FAILED(p.hr) || !p.backing || !list.begin(gpu)) return row(pool, "budget", false, "slot 133 -> " + hex(p.hr)); + list.read(p.backing.Get()); + list.close(); + if (!gpu.wait(list.submit())) return row(pool, "budget", false, "fence timeout"); + x2w_d3d12_budget_snapshot(&held, sizeof(held)); + const bool shared = p.linear && p.info.path == 1; + const int category = shared ? x2w_budget::placed : x2w_budget::buffer; + p.wrapper.Reset(); // the title's release + x2w_d3d12_budget_snapshot(&released, sizeof(released)); + const auto live = [&](const x2w_budget::Snapshot& snap) { return snap.live[category].objects; }; + const auto kept = [&](const x2w_budget::Snapshot& snap) { return snap.retained[category].objects; }; + const bool heap_live = !shared || held.live[x2w_budget::heap].objects >= 1; + const bool pass = p.linear && live(held) == live(before) + 1 && live(released) == live(before) && + kept(released) == kept(before) + 1 && heap_live && released.unmeasured == before.unmeasured; + row(pool, "budget", pass, + std::string(shared ? "shared: placed" : "copied: buffer") + " objects live " + std::to_string(live(before)) + " -> " + + std::to_string(live(held)) + " -> " + std::to_string(live(released)) + " after release, retained +" + + std::to_string(kept(released) - kept(before)) + (shared ? ", heap live " + std::to_string(held.live[x2w_budget::heap].objects) : "") + + ", unmeasured +" + std::to_string(released.unmeasured - before.unmeasured)); + } + + void case_xq(Pool& pool) + { + Lane q2; + Memory memory; + ComPtr<ID3D12Fence> title_fence; + if (!gpu.lane(q2, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(memory, A) || + FAILED(gpu.desktop->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&title_fence)))) + return row(pool, "xq", false, "setup failed"); + Placed x = place(gpu, memory.buffer(), false); + TitleList l0, l1, l2; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu) || !l1.begin(gpu) || !l2.begin(gpu)) + return row(pool, "xq", false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, "xq", false, "fence timeout"); + l1.read(x.backing.Get(), 1); + l1.close(); + l2.read(x.backing.Get(), 2); + l2.close(); + write(memory.buffer(), r0, B, words); + gpu.queue->Wait(title_fence.Get(), 1); // the title's own cross-queue dependency + const UINT64 v1 = l1.submit(); + const UINT64 v2 = l2.submit_on(q2); + q2.native->Signal(title_fence.Get(), 1); + const bool q2_done = wait_fence(q2.fence.Get(), v2), q1_done = gpu.wait(v1); + const Tally t1 = tally(gpu.read_output(1).data(), r0 / 4, key), t2 = tally(gpu.read_output(2).data(), r0 / 4, key); + const bool pass = q1_done && q2_done && t1.count[B] == words && t2.count[B] == words; + row(pool, "xq", pass, + std::string("queue 1 waits on a fence queue 2 signals after its list: queue 2 ") + (q2_done ? "completed" : "DID NOT COMPLETE") + + " and read " + t2.text() + ", queue 1 " + (q1_done ? "completed" : "DID NOT COMPLETE (deadlock?)") + " and read " + t1.text()); + } + + // contention: nothing waits behind a submission that waits for the only staging buffer. + void case_contention(Pool& pool) + { + using clock = std::chrono::steady_clock; + const auto ms = [](clock::duration d) { return static_cast<long long>(std::chrono::duration_cast<std::chrono::milliseconds>(d).count()); }; + Lane second; + Memory mx, mw; + if (!gpu.lane(second, D3D12_COMMAND_LIST_TYPE_DIRECT) || !pool.allocate(mx, A)) + return row(pool, "contention", false, "setup failed"); + Placed x = place(gpu, mx.buffer(), false); + TitleList l0; + if (FAILED(x.hr) || !x.backing || !l0.begin(gpu)) return row(pool, "contention", false, "slot 133 -> " + hex(x.hr)); + l0.read(x.backing.Get()); + l0.close(); + if (!gpu.wait(l0.submit())) return row(pool, "contention", false, "fence timeout"); // X uploaded: the staging buffer exists + if (!pool.allocate(mw, D)) return row(pool, "contention", false, "allocation failed"); + Placed w = place(gpu, mw.buffer(), false); + TitleList lw; + if (FAILED(w.hr) || !w.backing || !lw.begin(gpu)) return row(pool, "contention", false, "slot 133 -> " + hex(w.hr)); + lw.read(w.backing.Get()); + lw.close(); + if (!wait_fence(second.fence.Get(), lw.submit_on(second))) return row(pool, "contention", false, "fence timeout"); + const X2wLinearBufferTotals before = totals(); + + // S1 reads X behind the title gate; its refresh (B) is held on the internal queue and holds the + // only staging buffer. + gpu.hold(); + if (!gpu.hold_internal()) return row(pool, "contention", false, "internal refresh queue not available"); + write(mx.buffer(), r0, B, words); + TitleList s1, s2, probe; + if (!s1.begin(gpu) || !s2.begin(gpu) || !probe.begin(gpu)) return row(pool, "contention", false, "list"); + s1.read(x.backing.Get(), 1); + s1.close(); + s1.submit(); + // S2's refresh (C) must wait for that staging buffer's copy: on another thread. + write(mx.buffer(), r0, C, words); + s2.read(x.backing.Get(), 2); + s2.close(); + std::atomic<bool> done{false}; + UINT64 s2_value = 0; + const auto t1_start = clock::now(); + clock::duration t1_time{}; + std::thread waiter([&] { + s2_value = s2.submit(); + t1_time = clock::now() - t1_start; + done = true; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + const bool waiting_before = !done; + // Probes, each through mutex_: the info export, the title's release of X, a submission on another queue. + auto* x_wrapper = x.wrapper.Get(); + X2wLinearBufferInfo probe_info{}; + auto t = clock::now(); + x2w_d3d12_linear_buffer_info(w.wrapper.Get(), &probe_info); + const auto info_time = clock::now() - t; + t = clock::now(); + x.wrapper.Reset(); // release(): retire X + const auto release_time = clock::now() - t; + probe.read(w.backing.Get(), 3); + probe.close(); + t = clock::now(); + const bool probe_done = wait_fence(second.fence.Get(), probe.submit_on(second)); + const auto submit_time = clock::now() - t; + const bool waiting_after = !done; + const Tally w_read = tally(gpu.read_output(3).data(), r0 / 4, key); + // Let B land and the gated reads run. C's copy waits for S1, the earlier submission (the producer + // wait): S1 reads B, S2 then reads C, the CPU's last write. + gpu.open_internal(); + waiter.join(); + gpu.open_gate(); + const bool drained = gpu.drain_internal(); + if (!drained || !gpu.wait(s2_value)) return row(pool, "contention", false, "fence timeout after the gates"); + const Tally r1 = tally(gpu.read_output(1).data(), r0 / 4, key), r2 = tally(gpu.read_output(2).data(), r0 / 4, key); + X2wLinearBufferInfo xi{}; + x2w_d3d12_linear_buffer_info(x_wrapper, &xi); + const X2wLinearBufferTotals after = totals(); + const bool reused = after.staging_created == before.staging_created && after.staging_reused >= before.staging_reused + 2; + const bool pass = waiting_before && waiting_after && probe_done && w_read.count[D] == words && r1.count[B] == words && + r2.count[C] == words && !xi.stale && xi.refresh_failures == 0 && reused && + ms(t1_time) >= ms(info_time + release_time + submit_time); + char text[400]; + std::snprintf(text, sizeof(text), + "while S2's refresh waited (%s before, %s after the probes): info %lld ms, release %lld ms, other-queue submit " + "%lld ms (read %s); S2 returned after %lld ms; S1 read %s, S2 read %s; staging created %llu -> %llu, " + "refresh failures %llu", + waiting_before ? "waiting" : "NOT WAITING", waiting_after ? "waiting" : "DONE", ms(info_time), ms(release_time), + ms(submit_time), w_read.text().c_str(), ms(t1_time), r1.text().c_str(), r2.text().c_str(), + static_cast<unsigned long long>(before.staging_created), static_cast<unsigned long long>(after.staging_created), + static_cast<unsigned long long>(xi.refresh_failures)); + row(pool, "contention", pass, text); + } + + void case_d1(Pool& pool) + { + if (path == Path::default_backing || path == Path::untracked) return; + Memory memory; + if (!pool.allocate(memory, A)) return row(pool, "d1", false, "allocation failed"); + Placed p = place(gpu, memory.buffer(), false); + TitleList first, bypass, through; + if (FAILED(p.hr) || !first.begin(gpu) || !bypass.begin(gpu) || !through.begin(gpu)) + return row(pool, "d1", false, "slot 133 -> " + hex(p.hr)); + first.read(p.backing.Get()); + first.close(); + if (!gpu.wait(first.submit())) return row(pool, "d1", false, "fence timeout"); + write(memory.buffer(), r0, B, words); + bypass.read(p.backing.Get()); + bypass.close(); + if (!gpu.wait(bypass.submit_bypassing())) return row(pool, "d1", false, "fence timeout"); + const Tally missing = tally(gpu.read_output().data(), r0 / 4, key); + through.read(p.backing.Get()); + through.close(); + if (!gpu.wait(through.submit())) return row(pool, "d1", false, "fence timeout"); + const Tally refreshed = tally(gpu.read_output().data(), r0 / 4, key); + refresh_info(p); + const bool shared = !copied(pool); + const bool pass = (shared ? missing.count[B] == words : missing.count[A] == words) && refreshed.count[B] == words && + p.linear && p.info.path == (shared ? 1u : 2u); + row(pool, "d1", pass, std::string("past the wrapper (no refresh) ") + missing.text() + + (shared ? " (shared: no refresh needed)" : " (stale A expected: the oracle sees the missing refresh)") + + "; through the wrapper " + refreshed.text()); + } +}; +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 3) { + std::puts("usage: linear_buffer_backing_check <warp|hardware> <default|share|copy|refusal|untracked|stale|contention> [--mutate <name>]"); + return 2; + } + const bool warp = std::strcmp(argv[1], "warp") == 0; + if (!warp && std::strcmp(argv[1], "hardware") != 0) return 2; + Path path; + const std::string p = argv[2]; + if (p == "default") path = Path::default_backing; + else if (p == "share") path = Path::share; + else if (p == "copy") path = Path::copy; + else if (p == "refusal") path = Path::refusal; + else if (p == "untracked") path = Path::untracked; + else if (p == "stale") path = Path::stale; + else if (p == "contention") path = Path::contention; + else if (p == "lease") path = Path::lease; + else return 2; + std::string mutant; + if (argc == 5 && std::strcmp(argv[3], "--mutate") == 0) mutant = argv[4]; + else if (argc != 3) return 2; + + // The switches are read once, by the first call that needs them: set them before any. + SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_BUDGET", L"1"); // budget accounting (case budget); changes no backing + SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr + : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention || + path == Path::lease ? L"copy" : L"1"); + SetEnvironmentVariableW(L"X2W_TEST_EXISTING_HEAPS_UNSUPPORTED", path == Path::refusal ? L"1" : nullptr); + SetEnvironmentVariableW(L"X2W_TEST_SUBMIT_FENCE_FAIL", path == Path::untracked ? L"1" : nullptr); + SetEnvironmentVariableW(L"X2W_TEST_LINEAR_REFRESH_FAIL", path == Path::stale ? L"3" : nullptr); + SetEnvironmentVariableW(L"X2W_TEST_LINEAR_STAGING_LIMIT", path == Path::contention ? L"1" : nullptr); + SetEnvironmentVariableW(L"X2W_MESH86_XMEM_SRV", path == Path::lease ? L"1" : nullptr); + SetEnvironmentVariableA("X2W_TEST_LINEAR_BUFFER_MUTANT", mutant.empty() ? nullptr : mutant.c_str()); + { + // The DLL's log lines go to linear_buffer_backing_<path>_<adapter>[_<mutant>].log next to this executable. + wchar_t module[MAX_PATH]{}; + const DWORD n = GetModuleFileNameW(nullptr, module, MAX_PATH); + if (!n || n >= MAX_PATH) return 1; + log_path.assign(module, n); + log_path.resize(log_path.find_last_of(L"\\/") + 1); + const std::string name = std::string("linear_buffer_backing_") + path_name(path) + "_" + argv[1] + + (mutant.empty() ? "" : "_" + mutant) + ".log"; + log_path.append(name.begin(), name.end()); + DeleteFileW(log_path.c_str()); + SetEnvironmentVariableW(L"X2W_TRAP_LOG", log_path.c_str()); + } + + char debug_env[4]{}; + const bool debug_layer = GetEnvironmentVariableA("X2W_TEST_DEBUG_LAYER", debug_env, sizeof(debug_env)) && debug_env[0] == '1'; + if (debug_layer) { + ComPtr<ID3D12Debug> debug; + if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) { + std::puts("X2W_TEST_DEBUG_LAYER=1 but the debug layer is not installed"); + return 1; + } + debug->EnableDebugLayer(); + } + + Gpu gpu; + static ComPtr<ID3D12Device>* desktop_out = &gpu.desktop; + static DXGI_ADAPTER_DESC1 adapter_desc{}; + static LARGE_INTEGER driver{}; + const auto create = [](IUnknown* adapter, REFIID iid, void** out) -> HRESULT { + ComPtr<IDXGIAdapter1> a; + if (SUCCEEDED(adapter->QueryInterface(IID_PPV_ARGS(&a)))) { + a->GetDesc1(&adapter_desc); + a->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + } + const HRESULT hr = D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(desktop_out->ReleaseAndGetAddressOf())); + if (FAILED(hr)) return hr; + unsigned char parameters[64]{}; + return D3D12XboxCreateDevice(adapter, parameters, iid, out); + }; + bool unmatched = false; + gpu.guest = create_device(warp, unmatched, create); + if (!gpu.guest || !gpu.desktop) { + std::puts(warp ? "WARP device not created" : "no D3D12 hardware adapter"); + return warp || unmatched ? 1 : 77; + } + if (debug_layer) gpu.desktop.As(&gpu.info); + D3D12_FEATURE_DATA_EXISTING_HEAPS heaps{}; + const HRESULT heaps_hr = gpu.desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &heaps, sizeof(heaps)); + std::printf("adapter %04x:%04x %ls, driver %u.%u.%u.%u, D3D12_FEATURE_EXISTING_HEAPS %s supported=%d, debug layer %s, path %s%s%s\n", + adapter_desc.VendorId, adapter_desc.DeviceId, adapter_desc.Description, HIWORD(driver.HighPart), + LOWORD(driver.HighPart), HIWORD(driver.LowPart), LOWORD(driver.LowPart), hex(heaps_hr).c_str(), + heaps.Supported ? 1 : 0, debug_layer ? "on" : "off", path_name(path), mutant.empty() ? "" : ", mutant ", + mutant.c_str()); + if (!gpu.init()) { + std::puts("FAIL: fixture setup (queue, fences, pipeline)"); + return 1; + } + if (path == Path::share && (FAILED(heaps_hr) || !heaps.Supported)) { + std::puts("SKIP share: the adapter reports no existing-heap support; the refusal path covers it"); + return 77; + } + + Run run{gpu, path, SUCCEEDED(heaps_hr) && heaps.Supported != FALSE}; + for (const bool xmem : {true, false}) { + Pool pool(xmem); + if (!pool.init()) { + run.row(pool, "pool", false, "title memory could not be set up"); + continue; + } + if (path == Path::stale) { + run.case_stale(pool); + continue; + } + if (path == Path::contention) { + run.case_contention(pool); + continue; + } + if (path == Path::lease) { + run.case_lease(pool); + continue; + } + run.case_a(pool); + if (path == Path::share && xmem) run.case_a(pool, true); + run.case_b(pool, false); + run.case_c(pool); + run.case_d1(pool); + if (path != Path::default_backing) run.case_b(pool, true); + if (path == Path::copy) { + run.case_queues(pool); + run.case_gate2q(pool, false); + run.case_gate2q(pool, true); + run.case_xq(pool); + run.case_budget(pool); + run.case_gpuw(pool); + run.case_gpuw_discard(pool); + run.case_war(pool); + run.case_xq_write(pool); + run.case_xq_race(pool); + run.case_order(pool); + run.case_retire(pool); // last: it frees the pages of one buffer + } + run.probe_view_pin(pool); + if (path == Path::share) run.case_budget(pool); + } + const X2wLinearBufferTotals t = totals(); + std::printf("totals: placements %llu (shared %llu, copied %llu, kept default %llu), feature queries %llu, heap opens %llu " + "(failed %llu, cache hits %llu), placements failed %llu, submissions %llu, refreshes %llu, bytes copied %llu, " + "staging created %llu reused %llu, unreadable %llu, refresh failures %llu, consumer waits %llu, producer waits %llu " + "(unsafe refreshes refused %llu), gpu written %llu, reordered publishes %llu, copy faults %llu, last refusal %s, last refresh failure %s\n", + static_cast<unsigned long long>(t.placements), static_cast<unsigned long long>(t.shared), + static_cast<unsigned long long>(t.copied), static_cast<unsigned long long>(t.kept_default), + static_cast<unsigned long long>(t.feature_queries), static_cast<unsigned long long>(t.heap_opens), + static_cast<unsigned long long>(t.heap_open_failures), static_cast<unsigned long long>(t.heap_cache_hits), + static_cast<unsigned long long>(t.place_failures), static_cast<unsigned long long>(t.submissions), + static_cast<unsigned long long>(t.refreshes), static_cast<unsigned long long>(t.bytes_copied), + static_cast<unsigned long long>(t.staging_created), static_cast<unsigned long long>(t.staging_reused), + static_cast<unsigned long long>(t.unreadable), static_cast<unsigned long long>(t.refresh_failures), + static_cast<unsigned long long>(t.consumer_waits), static_cast<unsigned long long>(t.producer_waits), + static_cast<unsigned long long>(t.unsafe_refresh_refusals), static_cast<unsigned long long>(t.gpu_written), + static_cast<unsigned long long>(t.reordered_publishes), static_cast<unsigned long long>(t.copy_faults), + hex(t.last_refusal_hr).c_str(), hex(t.last_refresh_hr).c_str()); + { + Pool none(false); + if (path == Path::default_backing) { + // Opt-in off: no linear-buffer bookkeeping at all. + const bool untouched = !t.placements && !t.submissions && !t.feature_queries && !t.heap_opens; + run.row(none, "off", untouched, untouched ? "no linear-buffer code ran (all totals zero)" : "LINEAR-BUFFER CODE RAN"); + } else if (path == Path::stale) { + run.row(none, "totals", t.refresh_failures == 2 && t.last_refresh_hr == E_OUTOFMEMORY && t.kept_default == 0, + "refresh failures " + std::to_string(t.refresh_failures) + " (expected 2, one per pool), last " + hex(t.last_refresh_hr)); + } + if (path != Path::default_backing && path != Path::stale && path != Path::contention) { + run.row(none, "kept", t.kept_default == run.kept_rows, + "totals report " + std::to_string(t.kept_default) + " kept default backings for " + std::to_string(run.kept_rows) + + " refused placements, last refusal " + hex(t.last_refusal_hr)); + } + if (path == Path::refusal) { + run.row(none, "gate", t.feature_queries == 1 && t.heap_opens == 0, + "feature queries " + std::to_string(t.feature_queries) + ", heap opens " + std::to_string(t.heap_opens) + + " (expected 1 and 0: no open is attempted when D3D12_FEATURE_EXISTING_HEAPS reports no support)"); + } + } + const HRESULT removed = gpu.desktop->GetDeviceRemovedReason(); + if (FAILED(removed)) { + std::printf("FAIL: device removed %s\n", hex(removed).c_str()); + ++run.failures; + } + const unsigned errors = gpu.debug_errors(); + if (errors) { + std::printf("FAIL: %u debug-layer errors\n", errors); + run.failures += errors; + } + + if (!mutant.empty()) { + const char* target = mutant == "skip-refresh" ? "a" : mutant == "reuse-early" ? "c" : mutant == "copy-gpu-writes" ? "b" + : mutant == "ignore-feature" ? "gate" : mutant == "refusal-silent" ? "b" + : mutant == "hold-lock" ? "contention" : mutant == "skip-consumer-wait" ? "gate2q.held" + : mutant == "refresh-gpu-written" ? "gpuw" : mutant == "gpuw-at-record" ? "gpuw.discard" + : mutant == "skip-producer-wait" ? "war" : mutant == "publish-out-of-order" ? "order" + : mutant == "copy-after-retire" ? "retire" : mutant == "accept-unsafe-refresh" ? "xq.write" + : mutant == "unlocked-title-wait" ? "xq.race" : nullptr; + if (!target) return 2; + unsigned targeted = 0, failed = 0; + for (const auto& [name, pass] : run.results) + if (name == target) { + ++targeted; + failed += !pass; + } + std::printf("mutant %s: %u of %u targeted '%s' rows failed\n", mutant.c_str(), failed, targeted, target); + return targeted && failed == targeted ? 1 : 0; + } + std::printf("linear_buffer_backing %s %s: %s (%u failed)\n", argv[1], path_name(path), run.failures ? "FAIL" : "PASS", run.failures); + return run.failures ? 1 : 0; +} From b69a9b9b090d2ee2c3c09f08df56f1fc8816c6f6 Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 01:04:25 +0200 Subject: [PATCH 225/232] bcpack: extract main(argv) and add regular-file and packet size guards in bcpack_symbols with CLI suite (#2604) --- CMakeLists.txt | 3 + tests/bcpack_symbols_cli_check.py | 314 ++++++++++++++++++++++++++++++ tools/bcpack_symbols.py | 34 +++- 3 files changed, 341 insertions(+), 10 deletions(-) create mode 100644 tests/bcpack_symbols_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e86361468..4579d8b0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8816,6 +8816,9 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/bcpack_check.py") add_test(NAME bcpack_rans_symbols COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bcpack_symbols_check.py") + add_test(NAME bcpack_symbols_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/bcpack_symbols_cli_check.py") + set_tests_properties(bcpack_symbols_cli_check PROPERTIES TIMEOUT 60) add_test(NAME bcpack_tables COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bcpack_tables_check.py") add_test(NAME bcpack_probe_cli COMMAND "${INTAKE_PYTHON}" -B diff --git a/tests/bcpack_symbols_cli_check.py b/tests/bcpack_symbols_cli_check.py new file mode 100644 index 000000000..f1b100427 --- /dev/null +++ b/tests/bcpack_symbols_cli_check.py @@ -0,0 +1,314 @@ +"""Pure-Python CLI, file-guard, and error-handling suite for tools/bcpack_symbols.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import io +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "bcpack_symbols.py" +VECTORS = ROOT / "tools" / "_bcpack_rans" / "vectors" +sys.path.insert(0, str(ROOT / "tools")) + +import bcpack_symbols as symbols_mod # noqa: E402 +from _bcpack_rans import LEGAL, model # noqa: E402 + +BC1_WIDTHS = (8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8) + + +def _encode_single_lane(bits: int, q: int, values: list[int], *, narrow: int = 0, flush: bool = True) -> bytes: + """Encode one synthetic single-lane rANS fragment using the published model.""" + m = model(bits - 1 - narrow, q) + state = 1 << 24 + emitted = bytearray() + for value in reversed(values): + freq, start = m.forward(value) + if not freq: + raise ValueError("Zero-frequency symbol") + while state >= freq << 16: + emitted.append(state & 0xFF) + state >>= 8 + state = (state // freq << 16) + (state % freq) + start + payload = state.to_bytes(4, "big") + bytes(reversed(emitted)) + header = (narrow << 6) | (0x10 if flush else 0) | q + if len(payload) <= 256: + return bytes((header, len(payload) - 1)) + payload + return bytes((header | 0x20,)) + (len(payload) - 257).to_bytes(2, "little") + payload + + +class BcpackSymbolsCliTests(unittest.TestCase): + def _assert_main_exit( + self, + argv: list[str], + *, + expected_code: int | None = 1, + fragment: str = "", + prefix: str = "BCPack symbols: ", + ) -> str: + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + with self.assertRaises(SystemExit) as exc: + symbols_mod.main(argv) + if expected_code is None: + self.assertNotEqual(exc.exception.code, 0) + else: + self.assertEqual(exc.exception.code, expected_code) + self.assertEqual(stdout.getvalue(), "") + err = stderr.getvalue() + self.assertNotIn("Traceback", err) + self.assertTrue(err.strip(), f"expected stderr message for {argv!r}") + if prefix: + self.assertIn(prefix, err) + if fragment: + self.assertIn(fragment, err) + return err + + def test_main_argv_valid_single_and_multi_lane_packets(self): + values = [0, 1, 2, 3, 1, 0, 3, 2] * 3 + single_packet = _encode_single_lane(2, 0, values) + vector = json.loads((VECTORS / "synthetic_11.json").read_text(encoding="utf-8")) + multi_packet = bytes.fromhex(vector["chunk_hex"]) + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + single_path = root / "single.bin" + single_path.write_bytes(single_packet) + + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + rc = symbols_mod.main([ + str(single_path), + "--alphabet-bits", "2", + "--symbols", str(len(values)), + ]) + self.assertEqual(rc, 0) + self.assertEqual(stderr.getvalue(), "") + payload = json.loads(stdout.getvalue()) + self.assertEqual(payload["syms"], [values]) + self.assertEqual(payload["consumed"], len(single_packet)) + self.assertNotIn("order", payload) + self.assertTrue(all(lane["final"] in LEGAL for lane in payload["lanes"])) + + # Zero-padded packet up to the exact MAX_INPUT boundary succeeds. + exact_max_path = root / "exact_max.bin" + exact_max_path.write_bytes(single_packet.ljust(symbols_mod.MAX_INPUT, b"\x00")) + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + rc = symbols_mod.main([ + str(exact_max_path), + "--alphabet-bits", "2", + "--symbols", str(len(values)), + ]) + self.assertEqual(rc, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertEqual(json.loads(stdout.getvalue())["syms"], [values]) + + # Multi-lane synthetic vector decodes cleanly via main(argv). + multi_path = root / "multi.bin" + multi_path.write_bytes(multi_packet) + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + rc = symbols_mod.main([ + str(multi_path), + "--alphabet-bits", *[str(w) for w in BC1_WIDTHS], + "--symbols", str(vector["blocks"]), + ]) + self.assertEqual(rc, 0) + self.assertEqual(stderr.getvalue(), "") + multi_payload = json.loads(stdout.getvalue()) + self.assertEqual(multi_payload["syms"], vector["symbols"]) + self.assertEqual(multi_payload["consumed"], len(multi_packet)) + + # Bounded real subprocess check. + proc = subprocess.run( + [ + sys.executable, "-B", str(TOOL), + str(single_path), "--alphabet-bits", "2", "--symbols", str(len(values)), + ], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertEqual(json.loads(proc.stdout), payload) + + def test_upfront_file_and_size_guards_before_open(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing = root / "missing.bin" + folder = root / "packet_dir" + folder.mkdir() + empty = root / "empty.bin" + empty.write_bytes(b"") + oversize = root / "oversize.bin" + oversize.write_bytes(bytes(symbols_mod.MAX_INPUT + 1)) + + with mock.patch.object(Path, "open", side_effect=AssertionError("open must not run")): + self._assert_main_exit( + [str(missing), "--alphabet-bits", "1", "--symbols", "1"], + fragment=missing.name, + ) + self._assert_main_exit( + [str(folder), "--alphabet-bits", "1", "--symbols", "1"], + fragment=folder.name, + ) + self._assert_main_exit( + [str(empty), "--alphabet-bits", "1", "--symbols", "1"], + fragment="Expected 1..2097152 bytes", + ) + self._assert_main_exit( + [str(oversize), "--alphabet-bits", "1", "--symbols", "1"], + fragment="Expected 1..2097152 bytes", + ) + + for target, expected in ( + (empty, "Expected 1..2097152 bytes"), + (folder, folder.name), + (missing, missing.name), + ): + with self.subTest(target=target.name): + proc = subprocess.run( + [ + sys.executable, "-B", str(TOOL), + str(target), "--alphabet-bits", "1", "--symbols", "1", + ], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertIn("BCPack symbols: ", proc.stderr) + self.assertIn(expected, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + def test_out_of_range_widths_and_symbols(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + packet = root / "valid.bin" + packet.write_bytes(_encode_single_lane(1, 0, [0, 1] * 4)) + + bad_cases = ( + (["--alphabet-bits", "0", "--symbols", "1"], "Expected integer symbol widths in 1..9"), + (["--alphabet-bits", "10", "--symbols", "1"], "Expected integer symbol widths in 1..9"), + (["--alphabet-bits", *["8"] * (symbols_mod.MAX_LANES + 1), "--symbols", "1"], "Expected 1..16 lane widths"), + (["--alphabet-bits", "8", "--symbols", "0"], "Expected a positive count"), + (["--alphabet-bits", "8", "--symbols", "-3"], "Expected a positive count"), + ( + ["--alphabet-bits", "8", "8", "--symbols", str(symbols_mod.MAX_SYMBOLS // 2 + 1)], + "at most 1048576 symbols", + ), + ) + for extra_args, fragment in bad_cases: + with self.subTest(args=extra_args): + self._assert_main_exit([str(packet), *extra_args], fragment=fragment) + + # Invalid --alphabet-bits must still report cleanly even when file exceeds MAX_INPUT. + oversize = root / "oversize.bin" + oversize.write_bytes(bytes(symbols_mod.MAX_INPUT + 1)) + self._assert_main_exit( + [str(oversize), "--alphabet-bits", "10", "--symbols", "1"], + fragment="Expected integer symbol widths in 1..9", + ) + + # Direct decode() guards for non-bytes and boolean inputs. + for bad_data in (b"", bytes(symbols_mod.MAX_INPUT + 1), [0], "text"): + with self.assertRaisesRegex(ValueError, "bytes"): + symbols_mod.decode(bad_data, [1], 1) + with self.assertRaisesRegex(ValueError, "1..9"): + symbols_mod.decode(b"\x10", [True], 1) + with self.assertRaisesRegex(ValueError, "positive count"): + symbols_mod.decode(b"\x10", [1], True) + + def test_corrupt_packet_and_nonzero_trailing_refusals(self): + values = [0, 1] * 7 + valid_bytes = _encode_single_lane(1, 0, values) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + + trailing = root / "trailing.bin" + trailing.write_bytes(valid_bytes + b"\x00\x01") + self._assert_main_exit( + [str(trailing), "--alphabet-bits", "1", "--symbols", str(len(values))], + fragment="Non-zero trailing data", + ) + + truncated = root / "truncated.bin" + truncated.write_bytes(valid_bytes[:-2]) + self._assert_main_exit( + [str(truncated), "--alphabet-bits", "1", "--symbols", str(len(values))], + ) + + illegal = root / "illegal.bin" + illegal.write_bytes(bytes.fromhex("10 03 01 00 00 02")) + self._assert_main_exit( + [str(illegal), "--alphabet-bits", "1", "--symbols", "1"], + fragment="illegal", + ) + + bad_header = root / "bad_header.bin" + bad_header.write_bytes(b"\xc0") + self._assert_main_exit( + [str(bad_header), "--alphabet-bits", "1", "--symbols", "1"], + ) + + # Decoded symbol shape mismatch from backend raises BCPackError cleanly. + with mock.patch.object( + symbols_mod, + "decode_lanes", + return_value={"syms": [[2]], "consumed": 1, "cycles": 1, "lanes": [], "order": []}, + ): + with self.assertRaisesRegex(symbols_mod.BCPackError, "lane shape"): + symbols_mod.decode(b"\x10", [1], 1) + self._assert_main_exit( + [str(bad_header), "--alphabet-bits", "1", "--symbols", "1"], + fragment="lane shape", + ) + + proc = subprocess.run( + [ + sys.executable, "-B", str(TOOL), + str(trailing), "--alphabet-bits", "1", "--symbols", str(len(values)), + ], + capture_output=True, + text=True, + timeout=30, + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertIn("BCPack symbols: Non-zero trailing data", proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + + def test_argparse_errors_py314_safe(self): + with tempfile.TemporaryDirectory() as tmp: + packet = Path(tmp) / "pkt.bin" + packet.write_bytes(b"\x10") + cases = ( + ([], "required"), + ([str(packet), "--symbols", "1"], "--alphabet-bits"), + ([str(packet), "--alphabet-bits", "1"], "--symbols"), + ([str(packet), "--alphabet-bits", "1", "--symbols", "abc"], "invalid int"), + ([str(packet), "--alphabet-bits", "bad", "--symbols", "1"], "invalid int"), + ) + for argv, fragment in cases: + with self.subTest(argv=argv): + self._assert_main_exit( + argv, + expected_code=None, + fragment=fragment, + prefix="", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bcpack_symbols.py b/tools/bcpack_symbols.py index a1cfbc7a8..c4a62111f 100644 --- a/tools/bcpack_symbols.py +++ b/tools/bcpack_symbols.py @@ -2,6 +2,7 @@ import argparse import json from pathlib import Path +import stat from _bcpack_rans import BCPackError, decode_lanes @@ -10,13 +11,8 @@ MAX_LANES = 16 -def decode(data, alphabet_bits, symbols): - """Decode one stream with caller-established lane widths and symbols per lane. - - alphabet_bits contains actual symbol widths (1..9), not hardware indices. - Return symbols, consumed byte count and lane state/fragment diagnostics. - Zero padding may follow the stream; other trailing data is rejected. - """ +def _validate_shape(alphabet_bits, symbols): + """Validate lane widths (1..9) and bounded symbol count per lane.""" widths = tuple(alphabet_bits) if not 1 <= len(widths) <= MAX_LANES: raise ValueError("Expected 1..16 lane widths") @@ -24,6 +20,17 @@ def decode(data, alphabet_bits, symbols): raise ValueError("Expected integer symbol widths in 1..9") if type(symbols) is not int or not 1 <= symbols <= MAX_SYMBOLS // len(widths): raise ValueError("Expected a positive count, at most 1048576 symbols across all lanes") + return widths + + +def decode(data, alphabet_bits, symbols): + """Decode one stream with caller-established lane widths and symbols per lane. + + alphabet_bits contains actual symbol widths (1..9), not hardware indices. + Return symbols, consumed byte count and lane state/fragment diagnostics. + Zero padding may follow the stream; other trailing data is rejected. + """ + widths = _validate_shape(alphabet_bits, symbols) if not isinstance(data, bytes) or not 1 <= len(data) <= MAX_INPUT: raise ValueError("Expected 1..2097152 bytes") result = decode_lanes(data, [bits - 1 for bits in widths], [symbols] * len(widths)) @@ -37,21 +44,28 @@ def decode(data, alphabet_bits, symbols): return result -def main(): +def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("packet", type=Path) parser.add_argument("--alphabet-bits", type=int, nargs="+", required=True, help="Actual symbol widths, one per lane (1..9)") parser.add_argument("--symbols", type=int, required=True, help="Symbols per lane") - args = parser.parse_args() + args = parser.parse_args(argv) try: + info = args.packet.stat() + if not stat.S_ISREG(info.st_mode): + raise ValueError(f"Expected a regular packet file: {args.packet}") + _validate_shape(args.alphabet_bits, args.symbols) + if not 1 <= info.st_size <= MAX_INPUT: + raise ValueError(f"Expected 1..{MAX_INPUT} bytes") with args.packet.open("rb") as stream: data = stream.read(MAX_INPUT + 1) result = decode(data, args.alphabet_bits, args.symbols) except (OSError, ValueError, BCPackError) as error: parser.exit(1, f"BCPack symbols: {error}\n") print(json.dumps(result, indent=2)) + return 0 if __name__ == "__main__": - main() + raise SystemExit(main()) From cece3a364f103085d68f6a80031a6ef8c4388714 Mon Sep 17 00:00:00 2001 From: RavenCurseBurg <lycqay@gmail.com> Date: Thu, 26 Nov 2026 07:05:03 +0800 Subject: [PATCH 226/232] mesh: preserve a scalar shift across a wave64 EXEC-zero branch (#2601) * mesh: preserve a scalar shift across a wave64 EXEC-zero branch Prove the post-count thread-prefix mask, then test the partial and empty waves against the CPU image and a per-lane control. * tests: use the wave64 VCC operand in the mesh assembly fixture --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- CMakeLists.txt | 4 ++ docs/experiments.md | 11 ++++ tests/startup_mesh57_skeleton_check.py | 83 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 24 +++++++- 4 files changed, 119 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4579d8b0e..d7c5d52dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8922,6 +8922,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" draw "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) set_tests_properties(startup_mesh57_skeleton_draw_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME startup_mesh57_skeleton_wave_shift_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" shift "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_mesh57_skeleton_wave_shift_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME startup_mesh57_formatted_load_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py" formatted "${DXC_EXECUTABLE}" "$<TARGET_FILE:offscreen_check>" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index f98cf844a..788af30db 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9515,6 +9515,17 @@ VGPR source, a different VCC write, or a narrowed EXEC at the branch invalidates the proof. The CPU-reference draws cover both outcomes for each branch polarity and a VCC-zero branch after a join. +The `startup_mesh57_skeleton_wave_shift_{warp,hardware}` tests cover a single +`s_lshl_b32` behind a forward EXEC-zero branch after the count exchange. From +full EXEC a compare selects the threads with index below an unsigned constant. +Each guest wave of 64 threads takes the shift if its first thread is below that +limit. At the join the program restores full EXEC and uses the scalar as +vertex red. The draw checks a vertex in the upper half of a partially active +wave and vertices in a second, empty wave that retain the previous value. +It also compiles a per-lane branch and checks its different image. The proof +requires a straight path from the count exchange and an immediate EXEC +restore. Scalar memory operations in the skipped region remain unsupported. + The `startup_mesh57_formatted_load_{warp,hardware}` tests use one `buffer_load_format_x` to set vertex red. The fixture supplies descriptor word 3 in the constant slot published as `descword3` for SRV 0. It draws the same mesh diff --git a/tests/startup_mesh57_skeleton_check.py b/tests/startup_mesh57_skeleton_check.py index cd00dec9b..563545090 100644 --- a/tests/startup_mesh57_skeleton_check.py +++ b/tests/startup_mesh57_skeleton_check.py @@ -4,6 +4,7 @@ startup_mesh57_skeleton_check.py binary <llvm-mc> startup_mesh57_skeleton_check.py draw <dxc> <offscreen_check> <warp|hardware> startup_mesh57_skeleton_check.py formatted <dxc> <offscreen_check> <warp|hardware> + startup_mesh57_skeleton_check.py shift <dxc> <offscreen_check> <warp|hardware> startup_mesh57_skeleton_check.py exchange <dxc> <offscreen_check> <warp|hardware> <publisher> The fixture (tests/startup_mesh57_skeleton.s, source-built) holds the accepted shape: lane 0 of wave 0 stores a @@ -90,6 +91,18 @@ def masked_vertex_red(): return mesh[:at] + ['bf880004'] + mesh[at:] # s_cbranch_execz skips both vertex exports +# The first six threads select the shift for their entire guest wave. The second wave keeps 64/255. +SHIFT_ASM = """s_mov_b32 s40, 0x3e808081 +v_cmp_gt_u32_e32 vcc, 6, v0 +s_and_saveexec_b64 s[20:21], vcc +s_cbranch_execz 2 +s_lshl_b32 s40, 0x1fc00000, 1 +s_mov_b64 exec, -1 +v_mov_b32 v7, s40""" +SHIFT_WORDS = 'bea803ff 3e808081 7d880086 be94246a bf880002 8f2881ff 1fc00000 befe04c1 7e0e0228' +SHIFT_MESH = vertex_red(SHIFT_WORDS) + + # s_mov_b32 s40, 0.5; v_cmp_ge_f32_e64 vcc_lo, s40, 1.0 VCC_COMPARE = 'bea803f0 d406006a 0001e428' @@ -246,6 +259,17 @@ def expect(what, got, want): # s_mov_b32 s40, 1 replaces the then-arm v_mov inside the s_cbranch_execz range. ('an EXEC-zero branch that skips a scalar write', mutate('7e0e02f2', 'bea80381', mesh=masked_vertex_red()), 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), + ('EXEC-zero skips a scalar memory load', vertex_red(SHIFT_WORDS.replace('8f2881ff 1fc00000', 'f4000a00 fa000000')), + 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), + ('a shift with a mask from an unproven thread register', + vertex_red(SHIFT_WORDS.replace('7d880086', '7e100300 7d881086')), # v_mov v8,v0; compare against v8 + 'slot 57 mesh: scalar shift needs a proven wave EXEC predicate'), + ('a path enters the scalar shift without the compare or saveexec', + vertex_red(SHIFT_WORDS.replace('7d880086', 'bf008080 bf850003 7d880086')), + 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), + ('a shift without an immediate full EXEC restore', + vertex_red(SHIFT_WORDS.replace('befe04c1', 'bf800000 befe04c1')), # branch to s_nop before the restore + 'slot 57 mesh: s_cbranch_execz skips code with effects outside active lanes'), # s_cmp_eq_i32 0, 0; s_cbranch_scc1 .end (over the two-dword primitive export). ('a uniform branch that skips the primitive export', MESH[:PRIMITIVE_EXPORT] + ['bf008080', 'bf850002'] + MESH[PRIMITIVE_EXPORT:], @@ -386,6 +410,9 @@ def binary(mc): expect('rewritten descriptor words match llvm-mc', assemble(mc, mesh.replace(COLOUR_LOAD, COLOUR_LOAD + '\ns_mov_b32 s19, 0\n' + FORMAT_LOAD)), REWRITTEN_FORMAT) expect('pixel words match llvm-mc', assemble(mc, PIXEL_ASM), PIXEL) + shift = mesh.replace('v_cmpx_gt_i32 s14, v0', SHIFT_ASM + '\nv_cmpx_gt_i32 s14, v0') + shift = shift.replace('exp pos0', 'v_mov_b32 v20, v7\nexp pos0') + expect('scalar shift mesh words match llvm-mc', assemble(mc, shift), SHIFT_MESH) # ---- draw: four triangles in a 32x32 target, vertices stored out of order ---------------------- @@ -605,6 +632,60 @@ def draw_formatted(dxc, renderer, adapter): return 0 +def draw_shift(dxc, renderer, adapter): + os.environ['X2W_DXC'] = dxc + os.environ.pop('X2W_FXC', None) + points, colours, indices = geometry() + # The first provoking vertex (thread 39) shares a guest wave with active thread 5 across the + # host's possible 32-lane boundary. The last two triangles are in the all-empty guest wave. + triangles = [tuple(slot + offset for slot in tri) for tri, offset in zip(indices, (32, 0, 64, 64))] + words = [a | b << 10 | c << 20 for a, b, c in triangles] + with tempfile.TemporaryDirectory() as tmp: + key, status = request(tmp, SHIFT_MESH) + if status != 'ok': + raise AssertionError(status) + base = Path(tmp) / ('%016x' % key) + pipe = G.MeshPipeline(code(SHIFT_MESH), code(PIXEL), root()) + constants = bytearray(1024) + for slot, count in enumerate((len(triangles), 128)): + struct.pack_into('<I', constants, 4 * pipe.uds.index(('rootconst', 0, slot)), count) + head = bytes(constants) + buffer(points, colours, words) + b'\xcd' * 80 + + def reference(per_lane): + red = list(colours) + for tri in triangles: + for tid in tri: + active = tid < 6 if per_lane else tid // 64 == 0 + slot = tid % 16 + red[slot] = (255 if active else 64, *colours[slot][1:]) + return rasterise(points, red, triangles, 128, len(triangles)) + + correct, per_lane = reference(False), reference(True) + different = sum(a != b for a, b in zip(correct, per_lane)) + assert different > 0 + source = base.with_suffix('.ms57.hlsl').read_text() + predicate = '(tid & ~63u) >= 6u' + assert source.count(predicate) == 1 + mutated = Path(tmp) / 'per-lane.hlsl' + mutated.write_text(source.replace(predicate, '(exec & 1) == 0')) + mutant = Path(tmp) / 'per-lane.cso' + subprocess.run([dxc, '-T', 'ms_6_5', '-E', 'main', '-Fo', mutant, mutated], check=True) + case = Path(tmp) / 'shift.bin' + for shader, image, mismatch in ((base.with_suffix('.ms57.cso'), correct, 0), + (mutant, correct, different), (mutant, per_lane, 0)): + case.write_bytes(head + b''.join(map(bytes, image))) + run = subprocess.run([renderer, adapter, '--mesh-indexed', shader, base.with_suffix('.ps57.cso'), case], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + return 77 + if (run.returncode != int(bool(mismatch)) + or not re.search(rf'\bpixels={SIDE * SIDE} mismatches={mismatch}\b', run.stdout)): + raise AssertionError(run.stdout + run.stderr) + print(f'{shader.name}: {mismatch} pixels differ from the reference') + return 0 + + def main(argv): status = 0 if argv[1:2] == ['binary'] and len(argv) == 3: @@ -613,6 +694,8 @@ def main(argv): status = draw(*argv[2:]) elif argv[1:2] == ['formatted'] and len(argv) == 5: status = draw_formatted(*argv[2:]) + elif argv[1:2] == ['shift'] and len(argv) == 5: + status = draw_shift(*argv[2:]) elif argv[1:2] == ['exchange'] and len(argv) == 6: status = draw(*argv[2:]) elif len(argv) == 1: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index ab77ba394..9e25a5095 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1338,7 +1338,7 @@ def mesh_run(ins, at, what, patterns, env): VCC_KEYS = {'vcc', 'vcc_hi'} -def mesh_skeleton(ins, vcc_branches): +def mesh_skeleton(ins, vcc_branches, wave_limits): """Prove the one accepted group-memory shape of a slot 57 mesh program and replace it by per-thread instructions. Accepted shape, in program order (anything else is refused with its own message): @@ -1412,8 +1412,15 @@ def lands(key, index, what): targets = set(edges.values()) no_effect = lambda i: ins[i][2].startswith(('s_nop', 's_waitcnt', 's_clause')) + first_post_count_branch = next((i for i in edges if i >= b_end), None) + shift_branch = None for source, target in edges.items(): if ins[source][2] == 's_cbranch_execz': + # A single scalar shift followed by a full EXEC restore has a separate wave-level proof below. + if (source == first_post_count_branch and source >= b_end + 2 and target == source + 2 + and ins[source + 1][2] == 's_lshl_b32' and ins[target][3] == 's_mov_b64 exec, -1'): + shift_branch = source + continue # The model skips per lane, while the guest skips per wave. The difference is invisible when # lanes with clear EXEC can only bypass predicated writes before the paths meet. A skipped # s_branch may land at the execz target or past it over instructions without effect (the @@ -1503,6 +1510,13 @@ def lands(key, index, what): if index in edges: if scc_stale and reads_scc(name, asm): raise Unsupported('slot 57 mesh: an unmodelled SCC is read by a branch') + if index == shift_branch: + # Under full EXEC the preceding thread < limit comparison selects a contiguous prefix. + # A guest wave64 has any active lane exactly when its first thread is below the limit. + cmp = re.fullmatch(r'v_cmp_gt_u32_e32 vcc_lo, (0x[0-9a-f]+|[0-9]+), v(\d+)', ins[index - 2][3]) + if mask != index - 1 or not cmp or int(cmp[2]) != thread: + raise Unsupported('slot 57 mesh: scalar shift needs a proven wave EXEC predicate') + wave_limits[off] = int(cmp[1], 0) if name in MESH_VCC_BRANCHES: if mask is not None or not vcc_compares: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) @@ -1649,7 +1663,8 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): self.ins = decode(self.raw_code, refusals) if decoded is None else decoded if kind == 'ms': self.mesh_vcc_branches = {} - self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches) + self.mesh_wave_limits = {} + self.ins = mesh_skeleton(self.ins, self.mesh_vcc_branches, self.mesh_wave_limits) # A loop header is translated before the back edges into it, so whether a back edge brings the symbol kept # there is known only afterwards: translate again with that register read at run time or refused there. A # register only moves from kept to 'run' to 'refuse', so this ends. @@ -2378,6 +2393,7 @@ def after(block): # blocks reached from block over at least one edge def translate(self): refusals = getattr(self, 'refusals', None) # unit probes build a Stage without __init__ vcc_branches = getattr(self, 'mesh_vcc_branches', {}) + wave_limits = getattr(self, 'mesh_wave_limits', {}) vcc_compares = set().union(*vcc_branches.values()) try: self.calculated_pc = calculated_pc_proof(self.ins, getattr(self, 'kind', None)) @@ -2592,7 +2608,7 @@ def translate(self): uniform_vcc_compares.add(off) if base.startswith('s_cbranch_'): cond = base[10:] - cond_uniform = cond in ('scc0', 'scc1') and self.scc_uniform + cond_uniform = (cond in ('scc0', 'scc1') and self.scc_uniform) or off in wave_limits if off in vcc_branches: if not vcc_branches[off] <= uniform_vcc_compares: raise Unsupported('slot 57 mesh: %s on a wave-wide condition is not covered' % name) @@ -2606,6 +2622,8 @@ def translate(self): for tgt_off in affected: bad_at_target.setdefault(tgt_off, set()).update(regs) term = self.one(name, asm) + if off in wave_limits: + term = ('branch', '(tid & ~63u) >= %du' % wave_limits[off], term[2]) except Unsupported as reason: if refusals is None: if not hasattr(reason, 'instruction'): From e4e2b46d7b10815d18844a7dbc44a51031b31d91 Mon Sep 17 00:00:00 2001 From: NiiRoZz <simonin.remi25@gmail.com> Date: Thu, 26 Nov 2026 00:10:16 +0100 Subject: [PATCH 227/232] shader: lower compute buffer_store_format_xyzw in gfx2hlsl (#2530) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * shader: lower compute buffer_store_format_d16_x in gfx2hlsl Refs #2274. Adds compute-stage MUBUF buffer_store_format_d16_x (opcode 0x84) lowering to tools/startup/gfx2hlsl.py: - Validates four untouched descriptor words from a fixed native table entry (refusing modified descriptors including stride clears, shared load/store descriptors, missing local table provenance after branches, non-compute stages, lane-mask soffset, illegal binary lds/reserved MUBUF bits, bad operand shapes, and unsupported modifiers glc/slc/dlc/tfe/lds). - Emits uav <slot> table <param> <offset> plus udsrc entries uav_descword3, uav_stride (unmasked DW1 >> 16, so stride > 0x3fffu rejects DW1[31:30] CACHE_SWIZZLE/SWIZZLE_ENABLE) and uav_numrecords, under an if (exec & 1) guard when EXEC is not proven entry-full. - Supports 1-channel formats BUF_FMT_32_FLOAT (22), BUF_FMT_16_FLOAT (13), BUF_FMT_16_UNORM (7), BUF_FMT_16_SNORM (8), BUF_FMT_16_UINT (11) and BUF_FMT_16_SINT (12) in both GFX10 unified and legacy DFMT/NFMT encodings, checking DST_SEL_X == 4, zero reserved/swizzle/ADD_TID_ENABLE/TYPE flags, and RDNA 2 ISA §8.1.5 Table 35 bounds modes: OOB_SELECT 0 (structured, stride != 0, rec_off = voff + imm_off checked against stride while soffset adds to base) and OOB_SELECT 3 (raw, stride == 0, soffset + rec_off + elem_bytes <= num_records). OOB_SELECT 1/2, mismatched stride/OOB_SELECT, 32-bit overflow, misaligned addresses, unsupported formats/flags and OOB lanes are no-ops. - Uses 4-byte aligned Store for BUF_FMT_32_FLOAT and a lock-free InterlockedCompareExchange CAS loop for 2-byte aligned 16-bit formats. Adds tests/startup_compute_store_d16_x_check.py wired in CMakeLists.txt, .github/workflows/windows.yml and docs/experiments.md. AI-assisted: implementation and tests drafted and verified with an AI coding assistant. * shader: guard buffer_store_format_d16_x against host UAV bounds * shader: lower compute buffer_store_format_xyzw in gfx2hlsl Refs #2274. Depends on #2478, whose descriptor, entry-constant, bounds and EXEC handling this reuses. Lowers compute MUBUF buffer_store_format_xyzw (0x07) in the idxen form with a non-negative inline soffset and optional offset:. FORMAT, stride and num_records are read at dispatch from uav_descword3, uav_stride and uav_numrecords, with the OOB_SELECT 0/3 bounds of buffer_store_format_d16_x (the bounds lines are checked identical). Only the 4-channel formats of tools/compute_store_aot.py write (32x4 UINT/FLOAT, 16x4 FLOAT through pack16_rne, 8_8_8_8 and 2_10_10_10 UNORM, unified and legacy encodings, identity DST_SEL); as in that tool, a format of another channel count writes nothing. offen, off, register soffset, cache/tfe/lds modifiers and non-compute stages are refused by name. Adds tests/startup_compute_store_format_xyzw_check.py, registered in CMakeLists.txt, .github/workflows/windows.yml and AGENTS.md, and a docs/experiments.md entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * shader: keep the unknown-op refusal for xyzw stores outside compute Outside a compute stage buffer_store_format_xyzw keeps the bare mnemonic, as buffer_store_format_d16_x and buffer_store_dword do. The index and data are evaluated before the UAV and its entry constants are registered. The experiments entry drops a claim about captured programs and names the prebuilt WARP runner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * shader: guard buffer_store_format_xyzw against host UAV bounds The xyzw helper now takes the host-view check that #2478 added to the d16_x helper: after the guest bounds and the alignment check it reads the bound view size with GetDimensions and drops an element that would pass its end. The expected helper text and the experiments entry follow; the entry also corrects the case count to 19. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: dispatch xyzw stores through sized descriptor-table views The helper reads the bound view size with GetDimensions, which has no defined result on a root descriptor. Dispatch through --compute-store-sized-case, as the d16_x check does. The experiments entry records which runner mode produced the local WARP result. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Vladimir <39053957+Vladimir-Human@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: tedin7 <110300616+tedin7@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 16 + docs/experiments.md | 16 + ...startup_compute_store_format_xyzw_check.py | 528 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 161 ++++++ 6 files changed, 724 insertions(+) create mode 100644 tests/startup_compute_store_format_xyzw_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index eec590bdf..71eb71905 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -102,6 +102,7 @@ jobs: (["tests/startup_compute_gather_l_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_buffer_atomics_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_compute_store_d16_x_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_compute_store_format_xyzw_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_gather_c_lz_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_sample_c_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_image_3d_check.py", "binary", "llvm-mc-15"], {}), @@ -228,6 +229,7 @@ jobs: tests/startup_compute_gather_l_check.py \ tests/startup_compute_buffer_atomics_check.py \ tests/startup_compute_store_d16_x_check.py \ + tests/startup_compute_store_format_xyzw_check.py \ tests/startup_image_gather_c_lz_check.py \ tests/startup_image_sample_c_check.py \ tests/startup_image_3d_check.py \ diff --git a/AGENTS.md b/AGENTS.md index f17a5c5dc..89516ec2a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,6 +170,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_compute_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_check.py ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py +./out/pe-env/bin/python -B tests/startup_compute_store_format_xyzw_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index d7c5d52dc..121592e05 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3706,6 +3706,22 @@ if(EXISTS "${INTAKE_PYTHON}") PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") endforeach() endforeach() + # gfx2hlsl compute buffer_store_format_xyzw: 4-channel formats, bounds/OOB, channel-count no-op and EXEC guard (Refs #2274). + add_test(NAME startup_compute_store_format_xyzw_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_format_xyzw_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_compute_store_format_xyzw_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_format_xyzw_check.py" dispatch "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_compute_store_format_xyzw_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + foreach(control IN ITEMS x-drop-store x-swap-xy x-drop-index-oob unorm8-trunc unorm10-w-scale f16-drop-odd mismatch-writes r-drop-soffset e-drop-exec) + add_test(NAME startup_compute_store_format_xyzw_${control}_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_compute_store_format_xyzw_check.py" control ${control} "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter}) + set_tests_properties(startup_compute_store_format_xyzw_${control}_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77 + PASS_REGULAR_EXPRESSION "control ${control}: rejected at word=[0-9]+ ") + endforeach() + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 788af30db..91389bc39 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14877,6 +14877,22 @@ python -B tests/startup_compute_store_d16_x_check.py binary llvm-mc-15 Not covered here: `llvm-mc-15` assembly step on Linux CI (`binary`), `OOB_SELECT=3` with nonzero stride, multi-channel `buffer_store_format_d16_{xy,xyz,xyzw}`, `buffer_store_format_d16_hi_x`, and live runtime slot-67 dispatch binding of `uav_descword3`/`uav_stride`/`uav_numrecords`. +### Startup compute formatted four-component buffer stores + +[The startup translator](../tools/startup/gfx2hlsl.py) (`op_buffer_store_format_xyzw`, refs `#2274`) lowers compute MUBUF `buffer_store_format_xyzw` (`0x07`) in the `idxen` form with a non-negative inline `soffset` and an optional `offset:`. The descriptor rules, entry constants (`uav_descword3`, `uav_stride`, `uav_numrecords`), RDNA 2 `OOB_SELECT` 0/3 bounds and the `if (exec & 1)` guard are those of `buffer_store_format_d16_x` above; the bounds lines of the two helpers are checked to be identical, and the same host-view guard (`GetDimensions`) drops an element that would pass the bound UAV. FORMAT is read at dispatch. Only the 4-channel formats of [`compute_store_aot.py`](../tools/compute_store_aot.py) write, with its conversions: `BUF_FMT_32_32_32_32_UINT`/`FLOAT` (75/77, `Store4`), `BUF_FMT_16_16_16_16_FLOAT` (71, binary32 to binary16 round to nearest even through `pack16_rne`), `BUF_FMT_8_8_8_8_UNORM` (56) and `BUF_FMT_2_10_10_10_UNORM` (50, x in bits 9:0), UNORM by the Direct3D half-away-from-zero rule with NaN to 0, in the unified and legacy `DFMT`/`NFMT` encodings, with identity `DST_SEL` `0xfac`. As in that tool, a format of another channel count writes nothing: what the format unit does with the extra components is not established here. All writes are whole aligned dwords, so no read-modify-write is needed. `offen`, `idxen offen`, `off`, a register `soffset`, `glc`/`slc`/`dlc`/`tfe`/`lds` and the descriptor cases refused for `d16_x` are refused by name; outside compute the opcode keeps the unknown-op refusal. + +[The `buffer_store_format_xyzw` check](../tests/startup_compute_store_format_xyzw_check.py) runs a CPU reference of the conversions (every binary16 value round-trips, every UNORM code of 2, 8 and 10 bits reads back, named ties and overflows), checks that the format set equals the 4-channel subset of `compute_store_aot.py`, the word 3 validator over every FORMAT field in both encodings, the exact emitted helper, calls and manifests (including separate entry constants for a second UAV), 32 translator refusals, and translator mutations (handler removed, legacy table changed, EXEC guard dropped) that turn it red. It dispatches three source-built `gfx1013` programs in 19 cases: `X` (six writing format cases and nine descriptors that must write nothing: 1- and 2-channel formats, `OOB_SELECT` 1/2, swapped `DST_SEL`, stride/OOB mismatches, `SWIZZLE_ENABLE`, element larger than the stride), `R` (`soffset` 4 and `offset:12` under raw and structured bounds) and `E` (`s_and_saveexec_b32` lane guard). On WARP (`Microsoft Basic Render Driver` `1414:008c`, driver `10.0.26100.10068`) with the D3D12 debug layer, through an `offscreen_check` built from an earlier tree and its root-descriptor `--compute-store-case` mode, all 19 cases matched all `320` words (`mismatches=0`, `debug_errors=0 debug_warnings=0`), and all nine shader mutants were rejected (`x-drop-store`, `x-swap-xy`, `x-drop-index-oob`, `unorm8-trunc`, `unorm10-w-scale`, `f16-drop-odd`, `mismatch-writes`, `r-drop-soffset`, `e-drop-exec`). The check now dispatches through `--compute-store-sized-case`, as the `d16_x` check does, because `GetDimensions` has no defined size on a root descriptor; that runner mode needs the per-case root constants of the `d16_x` change and was not run here. + +```powershell +. .\tools\dev.ps1 +cmake --preset release +cmake --build --preset release --target offscreen_check +ctest --preset release --no-tests=error -j 1 -R "^startup_compute_store_format_xyzw" -V +python -B tests/startup_compute_store_format_xyzw_check.py binary llvm-mc-15 +``` + +Not covered here: hardware adapters, the `llvm-mc-15` `binary` step, formats with fewer than four channels (they write nothing), `OOB_SELECT` 1, a dispatch against a host view shorter than the guest range (the guard is checked only as emitted text), and runtime binding of the three entry constants. + ### First active lane at compute entry The startup compute translator accepts `s_ff1_i32_b32 sN, exec_lo` in the diff --git a/tests/startup_compute_store_format_xyzw_check.py b/tests/startup_compute_store_format_xyzw_check.py new file mode 100644 index 000000000..5886077df --- /dev/null +++ b/tests/startup_compute_store_format_xyzw_check.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Verify compute buffer_store_format_xyzw lowering in tools/startup/gfx2hlsl.py (Refs #2274). + + (no arguments) pure-Python unit, format, bounds and refusal checks + binary <llvm-mc> reassemble fixture sources and verify machine words + dispatch <dxc> <offscreen_check> <warp|hardware> translate, compile DXC cs_6_0, dispatch and verify readback + control <name> <dxc> <offscreen_check> <adapter> dispatch a mutated translation that must mismatch + +The fixtures are source-built gfx1013 compute programs. Each lane reads four words from t0 and stores them with +`buffer_store_format_xyzw ... idxen`, the only address form the lowering models: +- Program X: `v[4:7], v0, s[16:19], 0 idxen` (16 lanes). Dispatched for the five 4-channel formats (32_32_32_32 FLOAT + and UINT, 8_8_8_8_UNORM, 2_10_10_10_UNORM, 16_16_16_16_FLOAT; unified and legacy encodings) with structured + OOB_SELECT 0 bounds, plus descriptors that must write nothing: 1- and 2-channel formats (channel count mismatch), + OOB_SELECT 1/2, non-identity DST_SEL, stride 0 or nonzero against the OOB mode, DW1 swizzle bits and a stride + smaller than the element. +- Program R: inline soffset 4 and `offset:12`, under raw OOB_SELECT 3 (stride 0; every lane writes the same element + with the same data) and structured OOB_SELECT 0 (soffset added to the base, not checked against the stride). +- Program E: `s_and_saveexec_b32` narrows EXEC to lanes 0..5 before the store, so the store is lane guarded. +""" + +import math +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / 'tools')) +sys.path.insert(0, str(ROOT / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) + +import gfx2hlsl as G # noqa: E402 +import compute_store_aot as A # noqa: E402 +from startup_gfx2hlsl_compute_check import SENTINEL, USER7, WORDS, patch, refused, root_blob # noqa: E402 +from startup_compute_store_d16_x_check import PREAMBLE_X8, encode_mubuf # noqa: E402 + +MUBUF_STORE_FORMAT_XYZW = 0x07 +STORE_X = '00201ce000040480' # buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen + +SOURCE_X = PREAMBLE_X8 + """\ +v_lshlrev_b32 v4, 4, v0 +buffer_load_dwordx4 v[4:7], v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen +s_endpgm +""" +LOAD_X = '06038abe' '80038bbe' '05030cf4000000fa' '7fc08cbf' '84000834' '001038e004040380' '703f8cbf' +WORDS_X = bytes.fromhex(LOAD_X + STORE_X + '000081bf') + +SOURCE_R = SOURCE_X.replace('0 idxen\n', '4 idxen offset:12\n') +WORDS_R = bytes.fromhex(LOAD_X + '0c201ce000040484' '000081bf') + +SOURCE_E = SOURCE_X.replace('buffer_store', 'v_cmp_gt_u32 vcc_lo, 6, v0\ns_and_saveexec_b32 s0, vcc_lo\nbuffer_store') +WORDS_E = bytes.fromhex(LOAD_X + '8600887d' '6a3c80be' + STORE_X + '000081bf') + +# A second UAV through s[20:23] (table offset 0x20): its d16_x store and the xyzw store get separate entry constants. +SOURCE_D = SOURCE_X.replace('s_waitcnt lgkmcnt', 's_load_dwordx4 s[20:23], s[10:11], 0x20\ns_waitcnt lgkmcnt', 1).replace( + 'buffer_store', 'buffer_store_format_d16_x v4, v0, s[20:23], 0 idxen\nbuffer_store') +WORDS_D = bytes.fromhex('06038abe' '80038bbe' '05030cf4000000fa' '050508f4200000fa' '7fc08cbf' '84000834' + '001038e004040380' '703f8cbf' '002010e200040580' + STORE_X + '000081bf') + +VERIFIED_SNIPPETS = { + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen': STORE_X, + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 4 idxen offset:12': '0c201ce000040484', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 offen': '00101ce000040480', + 'buffer_store_format_xyzw v[4:7], v[0:1], s[16:19], 0 idxen offen': '00301ce000040480', + 'buffer_store_format_xyzw v[4:7], off, s[16:19], 0': '00001ce000040480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], s4 idxen': '00201ce000040404', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen glc': '00601ce000040480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen slc': '00201ce000044480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen dlc': '00a01ce000040480', + 'buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen tfe': '00201ce000048480', +} + +PROGRAMS = { + 'X': (SOURCE_X, WORDS_X, USER7, (16, 1, 1), (1, 1, 1)), + 'R': (SOURCE_R, WORDS_R, USER7, (16, 1, 1), (1, 1, 1)), + 'E': (SOURCE_E, WORDS_E, USER7, (16, 1, 1), (1, 1, 1)), + 'D': (SOURCE_D, WORDS_D, USER7, (16, 1, 1), (1, 1, 1)), +} + +EXPECTED_HELPER = """\ +uint store_unorm(uint bits, float scale) { + float x = asfloat(bits); + if (isnan(x)) return 0u; + precise float saturated = saturate(x); + precise float scaled = saturated * scale; + return (uint)floor(scaled + 0.5f); +} +void store_format_xyzw(RWByteAddressBuffer buf, uint word3, uint stride, uint num_records, uint idx, uint voff, \ +uint soff, uint imm_off, uint4 v) { + if ((word3 & 0xcef80000u) != 0u || (word3 & 0xfffu) != 0xfacu) return; + uint oob_sel = (word3 >> 28u) & 3u; + if ((oob_sel != 0u && oob_sel != 3u) || stride > 0x3fffu) return; + uint field = (word3 >> 12u) & 127u; + uint fmt = 0u; + if (((word3 >> 24u) & 1u) != 0u) { + fmt = field; + } else { + if (field == 72u) fmt = 50u; + else if (field == 80u) fmt = 56u; + else if (field == 103u) fmt = 71u; + else if (field == 116u) fmt = 75u; + else if (field == 119u) fmt = 77u; + } + uint elem_bytes = (fmt == 75u || fmt == 77u) ? 16u : fmt == 71u ? 8u : (fmt == 50u || fmt == 56u) ? 4u : 0u; + if (elem_bytes == 0u) return; +BOUNDS if ((addr & 3u) != 0u) return; + uint uav_bytes = 0u; + buf.GetDimensions(uav_bytes); + if (uav_bytes < elem_bytes || addr > uav_bytes - elem_bytes) return; + if (elem_bytes == 16u) { + buf.Store4(addr, v); + } else if (fmt == 71u) { + buf.Store2(addr, uint2(pack16_rne(asfloat(v.x)) | (pack16_rne(asfloat(v.y)) << 16u), \ +pack16_rne(asfloat(v.z)) | (pack16_rne(asfloat(v.w)) << 16u))); + } else if (fmt == 56u) { + buf.Store(addr, store_unorm(v.x, 255.0f) | (store_unorm(v.y, 255.0f) << 8u) \ +| (store_unorm(v.z, 255.0f) << 16u) | (store_unorm(v.w, 255.0f) << 24u)); + } else { + buf.Store(addr, store_unorm(v.x, 1023.0f) | (store_unorm(v.y, 1023.0f) << 10u) \ +| (store_unorm(v.z, 1023.0f) << 20u) | (store_unorm(v.w, 3.0f) << 30u)); + } +} +""" +# Bounds and OOB_SELECT lines shared with buffer_store_format_d16_x: taken from its helper so the two cannot drift. +BOUNDS_FIRST, BOUNDS_LAST = ' if (voff > 0xffffffffu - imm_off) return;\n', ' addr = elem_addr + soff;\n }\n' + + +def desc_word3(code, *, legacy=False, oob_select=0, dst_sel=0xfac): + if legacy: + field, level = next(k for k, v in G.STORE_FORMAT_XYZW_LEGACY_FORMATS.items() if v == code), 0 + else: + field, level = code, 1 + return ((oob_select & 3) << 28) | (level << 24) | ((field & 0x7f) << 12) | (dst_sel & 0xfff) + + +# --- CPU reference of the format conversions --------------------------------------------------------------------- + +def f32(bits): + return struct.unpack('<f', struct.pack('<I', bits & 0xffffffff))[0] + + +def bits32(value): + return struct.unpack('<I', struct.pack('<f', value))[0] + + +def round_f32(value): + return struct.unpack('<f', struct.pack('<f', value))[0] + + +def unorm(bits, scale): + """saturate, multiply and add 0.5 in binary32, then floor (Direct3D half away from zero); NaN gives 0.""" + x = f32(bits) + if math.isnan(x): + return 0 + return int(math.floor(round_f32(round_f32(min(1.0, max(0.0, x)) * scale) + 0.5))) + + +def f16_rne(bits): + """binary32 to binary16, round to nearest even (CPython's binary16 pack), NaN to a quiet NaN keeping the sign.""" + sign = (bits >> 16) & 0x8000 + x = f32(bits) + if math.isnan(x): + return sign | 0x7e00 + try: + return struct.unpack('<H', struct.pack('<e', x))[0] + except OverflowError: + return sign | 0x7c00 + + +def pack_element(code, words): + """Bytes the store writes for one element of a 4-channel format code.""" + if code in (75, 77): + return struct.pack('<4I', *words) + if code == 71: + return struct.pack('<4H', *(f16_rne(w) for w in words)) + if code == 56: + return struct.pack('<I', sum(unorm(w, 255.0) << (8 * i) for i, w in enumerate(words))) + if code == 50: + return struct.pack('<I', unorm(words[0], 1023.0) | (unorm(words[1], 1023.0) << 10) + | (unorm(words[2], 1023.0) << 20) | (unorm(words[3], 3.0) << 30)) + raise KeyError(code) + + +def check_reference(): + # Every binary16 value survives binary16 -> binary32 -> f16_rne (NaN becomes the quiet NaN of its sign). + for h in range(0x10000): + x = struct.unpack('<e', struct.pack('<H', h))[0] + want = (h & 0x8000) | 0x7e00 if math.isnan(x) else h + assert f16_rne(bits32(x)) == want, hex(h) + # Every UNORM code n reads back from n / (2^k - 1) in binary32. + for scale in (3.0, 255.0, 1023.0): + for n in range(int(scale) + 1): + assert unorm(bits32(n / scale), scale) == n, (scale, n) + for bits, scale, want in ((0x3f000000, 255.0, 128), (0x3f000000, 1023.0, 512), (0x3f000000, 3.0, 2), + (0x7fc00000, 255.0, 0), (0xff800000, 255.0, 0), (0x7f800000, 255.0, 255), + (0xbf800000, 1023.0, 0), (0x00000001, 255.0, 0)): + assert unorm(bits, scale) == want, (hex(bits), scale) + for bits, want in ((0x3f801000, 0x3c00), (0x3f803000, 0x3c02), (0x3f801001, 0x3c01), (0x477fefff, 0x7bff), + (0x477ff000, 0x7c00), (0xc77ff000, 0xfc00), (0x33000000, 0x0000), (0x33000001, 0x0001), + (0x33c00000, 0x0002), (0x7f800001, 0x7e00), (0xffc00000, 0xfe00)): + assert f16_rne(bits) == want, hex(bits) + + +# --- dispatch cases ---------------------------------------------------------------------------------------------- + +UNORM_EDGES = (0x00000000, 0x80000000, 0x3f800000, 0xbf800000, 0x3f000000, 0x40000000, 0x7fc00000, 0xffc00000, + 0x7f800000, 0xff800000, 0x3b808081, 0x3e800000, 0x3f400000, 0x3eff7cee, 0x00000001, 0x3f7f7f7f) +F16_EDGES = (0x3f800000, 0x3f801000, 0x3f803000, 0x3f801001, 0x477fe000, 0x477fefff, 0x477ff000, 0xc77ff000, + 0x7fc00001, 0xffc00000, 0x7f800001, 0x7f800000, 0x33800000, 0x33000000, 0x33000001, 0x33c00000) +RAW_WORDS = tuple((0x9e3779b9 * (i + 1)) & 0xffffffff for i in range(48)) + ( + 0x7fc00001, 0xff800001, 0x80000000, 0x00000001, 0xffffffff, 0x00000000, 0x7f7fffff, 0x0000ffff, + 0x80000001, 0x7f800001, 0xfffffffe, 0x12345678, 0x3f800000, 0xbf800000, 0x00800000, 0x807fffff) + + +def lane_words(kind): + if kind == 'raw': + flat = RAW_WORDS + else: + edges = UNORM_EDGES if kind == 'unorm' else F16_EDGES + flat = tuple(edges[(lane * 5 + c * 3) % 16] if lane < 8 else edges[(lane * 4 + c) % 16] + for lane in range(16) for c in range(4)) + return [flat[4 * lane:4 * lane + 4] for lane in range(16)] + + +# name: (word3, uav_stride, num_records, kind, writes) +X_VARIANTS = { + 'X-f32': (desc_word3(77), 16, 12, 'raw', True), + 'X-u32-legacy': (desc_word3(75, legacy=True), 20, 10, 'raw', True), + 'X-unorm8': (desc_word3(56), 4, 16, 'unorm', True), + 'X-unorm10-legacy': (desc_word3(50, legacy=True), 8, 14, 'unorm', True), + 'X-f16': (desc_word3(71), 8, 16, 'f16', True), + 'X-f16-legacy': (desc_word3(71, legacy=True), 12, 15, 'f16', True), + # Descriptors that must write nothing (all 320 sentinel words survive): + 'X-1ch': ((1 << 24) | (22 << 12) | 0xfac, 4, 16, 'raw', False), # BUF_FMT_32_FLOAT: channel mismatch + 'X-2ch': ((1 << 24) | (64 << 12) | 0xfac, 8, 16, 'raw', False), # BUF_FMT_32_32_FLOAT: channel mismatch + 'X-oob1': (desc_word3(77, oob_select=1), 16, 12, 'raw', False), + 'X-oob2': (desc_word3(77, oob_select=2), 16, 12, 'raw', False), + 'X-dst-sel': (desc_word3(77, dst_sel=0xfa5), 16, 12, 'raw', False), # X and Y selects swapped + 'X-oob0-stride0': (desc_word3(77), 0, 256, 'raw', False), + 'X-oob3-stride16': (desc_word3(77, oob_select=3), 16, 256, 'raw', False), + 'X-swizzle-en': (desc_word3(77), 16 | 0x8000, 12, 'raw', False), + 'X-stride8': (desc_word3(77), 8, 12, 'raw', False), # element larger than the stride +} +DISPATCH_CASES = (*X_VARIANTS, 'R-raw', 'R-raw-oob', 'R-struct', 'E') + + +def case_inputs(name): + """Return (program key, t0 bytes, 16 entry constants, expected 320 words).""" + out = bytearray(struct.pack('<%dI' % WORDS, *([SENTINEL] * WORDS))) + if name in X_VARIANTS: + word3, stride, num_records, kind, writes = X_VARIANTS[name] + lanes = lane_words(kind) + if writes: + code = G.validate_store_format_xyzw_word3(word3)[0] + for lane in range(min(16, num_records)): + element = pack_element(code, lanes[lane]) + out[lane * stride:lane * stride + len(element)] = element + prog = 'X' + elif name.startswith('R-'): + lanes = lane_words('raw') + if name == 'R-struct': + word3, stride, num_records = desc_word3(77), 32, 8 + for lane in range(num_records): # base = idx * stride + offset:12 + soffset 4 + out[lane * 32 + 16:lane * 32 + 32] = pack_element(77, lanes[lane]) + else: # raw: stride 0, every lane writes bytes 16..31 with the same data + lanes = [lanes[3]] * 16 + word3, stride, num_records = desc_word3(77, oob_select=3), 0, 32 if name == 'R-raw' else 31 + if name == 'R-raw': + out[16:32] = pack_element(77, lanes[0]) + prog = 'R' + elif name == 'E': + lanes = lane_words('raw') + word3, stride, num_records = desc_word3(75), 16, 16 + for lane in range(6): + out[lane * 16:lane * 16 + 16] = pack_element(75, lanes[lane]) + prog = 'E' + else: + raise KeyError(name) + source = [0] * WORDS + for lane, words in enumerate(lanes): + source[4 * lane:4 * lane + 4] = words + constants = [0, 0, word3, stride, num_records] + [0] * 11 + return prog, struct.pack('<%dI' % WORDS, *source), constants, list(struct.unpack('<%dI' % WORDS, out)) + + +def translate(prog_key, code=None): + _, words, rsrc2, group, _ = PROGRAMS[prog_key] + return G.ComputePipeline(words if code is None else code, root_blob(), rsrc2, group) + + +def emitted_text_problems(): + """Exact emitted text of the lowering; returns the mismatches (empty when the translator is as reviewed).""" + problems = [] + pipe = translate('X') + hlsl = pipe.hlsl_cs() + d16 = translate('D').hlsl_cs() + bounds = d16[d16.index(BOUNDS_FIRST):d16.index(BOUNDS_LAST, d16.index(BOUNDS_FIRST)) + len(BOUNDS_LAST)] + helper = EXPECTED_HELPER.replace('BOUNDS', bounds) + if helper not in hlsl: + problems.append('helper text') + if 'uint pack16_rne(float value) {' not in hlsl or hlsl.index('uint pack16_rne(') > hlsl.index('void store_format_xyzw('): + problems.append('pack16_rne not defined before the helper') + expected_manifest = ('x2w-manifest 2\nstage cs\ngroup 16 1 1\nud 5\n' + 'udsrc 0 rootconst 0 0\nudsrc 1 rootconst 0 1\n' + 'udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n' + 'srv 0 buf table 1 0\nuav 0 table 1 16\n') + if pipe.manifest() != expected_manifest: + problems.append('manifest X') + for prog, line in (('X', '\n store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 0u, 0u, uint4(v4, v5, v6, v7));\n'), + ('R', '\n store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 4u, 12u, uint4(v4, v5, v6, v7));\n'), + ('E', '\n if (exec & 1) store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 0u, 0u, ' + 'uint4(v4, v5, v6, v7));\n')): + if line not in translate(prog).hlsl_cs(): + problems.append('call %s' % prog) + two = translate('D') + if ('udsrc 2 uav_descword3 0\nudsrc 3 uav_stride 0\nudsrc 4 uav_numrecords 0\n' + 'udsrc 5 uav_descword3 1\nudsrc 6 uav_stride 1\nudsrc 7 uav_numrecords 1\n') not in two.manifest() or \ + '\n store_format_xyzw(u1, ud5, ud6, ud7, v0, 0u, 0u, 0u, uint4(v4, v5, v6, v7));\n' not in d16: + problems.append('second UAV entry constants') + return problems + + +def check_controls(): + check_reference() + + # 1. Decoder round trip of every recorded encoding. + for line, hex_words in VERIFIED_SNIPPETS.items(): + (_, size, op, asm), = G.decode(bytes.fromhex(hex_words)) + assert (size, op, asm) == (8, 'buffer_store_format_xyzw', line), (line, size, op, asm) + for line, fields in ((STORE_X, dict(idxen=True)), ('0c201ce000040484', dict(idxen=True, offset=12))): + soffset = 0x84 if fields.get('offset') else 0x80 + assert encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, soffset, **fields).hex() == line + + # 2. The format set is the 4-channel subset of compute_store_aot's reviewed tables, in both encodings. + four = {code for code, (_, channels) in A.DESCRIPTOR_STORE_FORMATS.items() if channels == 4} + assert set(G.STORE_FORMAT_XYZW_FORMATS) == four, (sorted(G.STORE_FORMAT_XYZW_FORMATS), sorted(four)) + assert G.STORE_FORMAT_XYZW_LEGACY_FORMATS == {f: c for f, c in A.LEGACY_DESCRIPTOR_FORMATS.items() if c in four} + + # 3. Word 3 validator: exhaustive over the FORMAT field in both encodings and both OOB modes. + for level in (0, 1): + for field in range(128): + code = field if level else G.STORE_FORMAT_XYZW_LEGACY_FORMATS.get(field) + for oob in (0, 3): + w3 = (oob << 28) | (level << 24) | (field << 12) | 0xfac + if code in G.STORE_FORMAT_XYZW_FORMATS: + assert G.validate_store_format_xyzw_word3(w3) == (code, *G.STORE_FORMAT_XYZW_FORMATS[code]) + else: + refused('is not a handled 4-channel format', lambda w=w3: G.validate_store_format_xyzw_word3(w)) + for bad, fragment in ((desc_word3(77, dst_sel=0xfa5), 'non-identity DST_SEL 0xfa5'), + (desc_word3(77, dst_sel=0xfa4), 'non-identity DST_SEL'), + (desc_word3(77, oob_select=1), 'OOB_SELECT 1'), (desc_word3(77, oob_select=2), 'OOB_SELECT 2'), + (desc_word3(77) | (1 << 23), 'flags'), (desc_word3(77) | (1 << 21), 'flags'), + (desc_word3(77) | (1 << 30), 'flags'), (desc_word3(77) | (1 << 25), 'flags'), + (-1, 'invalid descriptor word 3'), (True, 'invalid descriptor word 3'), + (1 << 32, 'invalid descriptor word 3')): + refused(fragment, lambda w=bad: G.validate_store_format_xyzw_word3(w)) + + # 4. Exact emitted text, entry constants, helper only when used. + problems = emitted_text_problems() + assert not problems, problems + plain = G.ComputePipeline(bytes.fromhex('000081bf'), root_blob(), USER7, (1, 1, 1)).hlsl_cs() + assert 'store_format_xyzw' not in plain and 'store_unorm' not in plain + + # 5. Refusals naming the unmodelled shape (negative controls). + for hex_word, fragment in ( + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 offen'], 'offen address form'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v[0:1], s[16:19], 0 idxen offen'], 'offen address form'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], off, s[16:19], 0'], 'without idxen'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], s4 idxen'], + 'soffset s4 (only a non-negative inline constant is modelled)'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen glc'], 'modifier glc'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen slc'], 'modifier slc'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen dlc'], 'modifier dlc'), + (VERIFIED_SNIPPETS['buffer_store_format_xyzw v[4:7], v0, s[16:19], 0 idxen tfe'], 'modifier tfe'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, 0x80, idxen=True, lds=True).hex(), 'illegal MUBUF encoding'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, 0x80, idxen=True, w0_rsvd=True).hex(), 'illegal MUBUF'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 16, 0x80, idxen=True, w1_rsvd=True).hex(), 'illegal MUBUF'), + (encode_mubuf(MUBUF_STORE_FORMAT_XYZW, 4, 0, 12, 0x80, idxen=True).hex(), 'used for a load and a store'), + ): + refused(fragment, lambda hw=hex_word: translate('X', code=patch(WORDS_X, STORE_X, hw)).hlsl_cs()) + for inserted, fragment in (('800392be', 'modified descriptor'), # s_mov_b32 s18, 0 + ('11ff1187ffff00c0', 'modified descriptor'), # s_and_b32 s17, s17, 0xc000ffff + ('10841080', 'modified descriptor'), # s_add_u32 s16, s16, 4 + ('000082bf', 'local table load')): # s_branch +0, no local reload + refused(fragment, lambda i=inserted: translate('X', code=patch(WORDS_X, STORE_X, i + STORE_X)).hlsl_cs()) + for kind in ('ps', 'vs'): # outside compute: the unknown-op refusal, the bare mnemonic + stage = G.Stage.__new__(G.Stage) + stage.kind = kind + try: + stage.op_buffer_store_format_xyzw(['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen']) + except G.Unsupported as reason: + assert str(reason) == 'buffer_store_format_xyzw', str(reason) + else: + raise AssertionError('%s stage accepted buffer_store_format_xyzw' % kind) + cs = translate('X').cs + cs.raw_code = b'' # synthetic operand lists below + for ops, mods, fragment in ( + (['v[4:7]', 'v0', 's[16:19]'], ['idxen'], 'with 3 operands, expected 4'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'idxen'], 'modifier idxen'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'offset:4', 'offset:8'], 'modifier offset:8'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'offset:4096'], 'modifier offset:4096'), + (['v[4:7]', 'v0', 's[16:19]', '0'], ['idxen', 'lds'], 'modifier lds'), + (['v[4:6]', 'v0', 's[16:19]', '0'], ['idxen'], 'data v[4:6]'), + (['v[253:256]', 'v0', 's[16:19]', '0'], ['idxen'], 'data v[253:256]'), + (['s[4:7]', 'v0', 's[16:19]', '0'], ['idxen'], 'data s[4:7]'), + (['v[4:7]', 'v[0:1]', 's[16:19]', '0'], ['idxen'], 'vaddr v[0:1] for idxen'), + (['v[4:7]', 's0', 's[16:19]', '0'], ['idxen'], 'vaddr s0 for idxen'), + (['v[4:7]', 'v0', 's[16:19]', '-1'], ['idxen'], 'soffset -1'), + (['v[4:7]', 'v0', 's[16:19]', 'v1'], ['idxen'], 'soffset v1'), + (['v[4:7]', 'v0', 's[16:17]', '0'], ['idxen'], 'descriptor s[16:17]'), + (['v[4:7]', 'v0', 's[104:107]', '0'], ['idxen'], 'descriptor s[104:107]'), + ): + refused(fragment, lambda o=ops, m=mods: cs.op_buffer_store_format_xyzw(o, m)) + + # 6. Translator mutations turn the checks red. + saved = G.Stage.op_buffer_store_format_xyzw + try: + delattr(G.Stage, 'op_buffer_store_format_xyzw') + refused('buffer_store_format_xyzw', lambda: translate('X').hlsl_cs()) + finally: + G.Stage.op_buffer_store_format_xyzw = saved + legacy = dict(G.STORE_FORMAT_XYZW_LEGACY_FORMATS) + for mutation in ({**legacy, (14 << 3) | 4: 77}, {k: v for k, v in legacy.items() if v != 50}): + G.STORE_FORMAT_XYZW_LEGACY_FORMATS = mutation + try: + assert 'helper text' in emitted_text_problems(), mutation + finally: + G.STORE_FORMAT_XYZW_LEGACY_FORMATS = legacy + saved_emit = G.Stage.emit + try: # dropping the EXEC guard + G.Stage.emit = lambda self, line: saved_emit(self, line.replace('if (exec & 1) store_format_xyzw', 'store_format_xyzw')) + assert 'call E' in emitted_text_problems() + finally: + G.Stage.emit = saved_emit + + # 7. Dispatch inputs are self-consistent: writing cases change words, no-op cases keep every sentinel. + for name in DISPATCH_CASES: + _, _, _, expected = case_inputs(name) + writes = X_VARIANTS[name][4] if name in X_VARIANTS else name != 'R-raw-oob' + assert (expected != [SENTINEL] * WORDS) == writes, name + + print('buffer_store_format_xyzw reference, format, bounds, provenance, refusal and mutation checks pass') + + +def check_binary(llvm_mc): + from startup_flat_param_check import assemble + for name, (source, words, *_rest) in PROGRAMS.items(): + built = assemble(llvm_mc, source) + assert built == words, '%s: assembled %s, recorded %s' % (name, built.hex(), words.hex()) + for line, hex_words in VERIFIED_SNIPPETS.items(): + built = assemble(llvm_mc, line + '\n').hex() + assert built == hex_words, '%s: assembled %s, recorded %s' % (line, built, hex_words) + print('buffer_store_format_xyzw fixture words match llvm-mc (%d programs, %d snippets)' + % (len(PROGRAMS), len(VERIFIED_SNIPPETS))) + + +CONTROLS = { + 'x-drop-store': ('X-f32', ' store_format_xyzw(u0, ud2, ud3, ud4, v0, 0u, 0u, 0u, uint4(v4, v5, v6, v7));\n', ''), + 'x-swap-xy': ('X-f32', 'buf.Store4(addr, v);', 'buf.Store4(addr, v.yxzw);'), + 'x-drop-index-oob': ('X-f32', + 'if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;', + 'if (elem_bytes > stride || rec_off > stride - elem_bytes) return;'), + 'unorm8-trunc': ('X-unorm8', 'return (uint)floor(scaled + 0.5f);', 'return (uint)floor(scaled);'), + 'unorm10-w-scale': ('X-unorm10-legacy', '(store_unorm(v.w, 3.0f) << 30u)', '(store_unorm(v.w, 1.0f) << 30u)'), + 'f16-drop-odd': ('X-f16', 'pack16_rne(asfloat(v.x)) |', '(pack16_rne(asfloat(v.x)) & 0xfffeu) |'), + 'mismatch-writes': ('X-1ch', '(fmt == 50u || fmt == 56u) ? 4u : 0u', '(fmt == 50u || fmt == 56u || fmt == 22u) ? 4u : 0u'), + 'r-drop-soffset': ('R-struct', 'v0, 0u, 4u, 12u, uint4', 'v0, 0u, 0u, 12u, uint4'), + 'e-drop-exec': ('E', 'if (exec & 1) store_format_xyzw(', 'store_format_xyzw('), +} + + +def run_case(name, dxc, runner, adapter, directory, control=None): + prog, source, constants, expected = case_inputs(name) + hlsl = translate(prog).hlsl_cs() + if control: + _, old, new = CONTROLS[control] + assert hlsl.count(old) == 1, (control, old) + hlsl = hlsl.replace(old, new) + src, cso, case = (directory / ('%s.%s' % (name, ext)) for ext in ('hlsl', 'cso', 'case')) + src.write_text(hlsl, encoding='ascii', newline='\n') + subprocess.run([dxc, '-Gis', '-T', 'cs_6_0', '-E', 'main', '-Fo', str(cso), str(src)], check=True) + groups = PROGRAMS[prog][4] + case.write_bytes(struct.pack('<I', groups[0] | (groups[1] << 8) | (groups[2] << 16)) + + struct.pack('<%dI' % WORDS, *expected) + struct.pack('<16I', *constants) + source) + # The helper's GetDimensions needs a descriptor-table view; root descriptors carry no size. + return subprocess.run([runner, adapter, '--compute-store-sized-case', str(cso), str(case)], + capture_output=True, text=True) + + +def check_dispatch(dxc, runner, adapter, control=None): + runner = str(Path(runner).resolve()) + out = ROOT / 'out' + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as tmp: + runs = [(CONTROLS[control][0], control)] if control else [(name, None) for name in DISPATCH_CASES] + for name, mutation in runs: + run = run_case(name, dxc, runner, adapter, Path(tmp), mutation) + print(run.stdout, end='') + if run.returncode == 77: + return 77 + diagnostics = [line for line in run.stderr.splitlines() + if not (adapter == 'hardware' and line.startswith('XBOX2WINDOWS_ADAPTER: skipping '))] + if mutation: + if run.returncode != 1 or not any('expected=' in line for line in diagnostics): + raise AssertionError('control %s: not rejected (exit %d) %s' % (mutation, run.returncode, run.stderr)) + print('control %s: rejected at %s' % (mutation, diagnostics[0])) + elif run.returncode or diagnostics: + raise AssertionError('case %s: %s' % (name, run.stderr or 'exit %d' % run.returncode)) + else: + print('case %s: all %d words match' % (name, WORDS)) + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 1: + check_controls() + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + check_binary(sys.argv[2]) + elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + sys.exit(check_dispatch(*sys.argv[2:])) + elif len(sys.argv) == 6 and sys.argv[1] == 'control': + sys.exit(check_dispatch(*sys.argv[3:], control=sys.argv[2])) + else: + sys.exit(__doc__) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 9e25a5095..3e2051257 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -215,6 +215,46 @@ def validate_store_d16_x_word3(word3): raise Unsupported('buffer_store_format_d16_x unsupported descriptor FORMAT %d' % field) return code, info[0], info[1] + +# Compute buffer_store_format_xyzw (MUBUF 0x07) writes only formats with exactly four channels, the set and +# conversions of tools/compute_store_aot.py: a channel-count mismatch writes nothing, since what the format unit +# does with the extra components is not established here. Word 3 bounds and OOB_SELECT checks are those of +# buffer_store_format_d16_x above; DST_SEL must be the identity X, Y, Z, W (0xfac). +STORE_FORMAT_XYZW_FORMATS = { + 50: ('BUF_FMT_2_10_10_10_UNORM', 4), + 56: ('BUF_FMT_8_8_8_8_UNORM', 4), + 71: ('BUF_FMT_16_16_16_16_FLOAT', 8), + 75: ('BUF_FMT_32_32_32_32_UINT', 16), + 77: ('BUF_FMT_32_32_32_32_FLOAT', 16), +} +STORE_FORMAT_XYZW_LEGACY_FORMATS = { + (9 << 3) | 0: 50, # DFMT_2_10_10_10 + NFMT_UNORM + (10 << 3) | 0: 56, # DFMT_8_8_8_8 + NFMT_UNORM + (12 << 3) | 7: 71, # DFMT_16_16_16_16 + NFMT_FLOAT + (14 << 3) | 4: 75, # DFMT_32_32_32_32 + NFMT_UINT + (14 << 3) | 7: 77, # DFMT_32_32_32_32 + NFMT_FLOAT +} + + +def validate_store_format_xyzw_word3(word3): + """Validate V# word 3 for compute buffer_store_format_xyzw and return (code, name, elem_bytes).""" + name = 'buffer_store_format_xyzw' + if not isinstance(word3, int) or isinstance(word3, bool) or not 0 <= word3 <= 0xffffffff: + raise Unsupported('%s invalid descriptor word 3 %r' % (name, word3)) + if word3 & STORE_D16_X_WORD3_ZERO_MASK: + raise Unsupported('%s unsupported descriptor word 3 flags 0x%08x' % (name, word3)) + if (word3 & 0xfff) != 0xfac: + raise Unsupported('%s non-identity DST_SEL 0x%03x' % (name, word3 & 0xfff)) + oob_select = (word3 >> 28) & 3 + if oob_select not in (0, 3): + raise Unsupported('%s unsupported OOB_SELECT %d' % (name, oob_select)) + field = (word3 >> DESC_FORMAT_SHIFT) & DESC_FORMAT_MASK + code = field if ((word3 >> 24) & 1) else STORE_FORMAT_XYZW_LEGACY_FORMATS.get(field) + info = STORE_FORMAT_XYZW_FORMATS.get(code) + if info is None: + raise Unsupported('%s descriptor FORMAT %d is not a handled 4-channel format' % (name, field)) + return code, info[0], info[1] + def starts_with_fetch_call(code): return len(code) >= 4 and struct.unpack_from('<I', code)[0] == FETCH_CALL @@ -4672,6 +4712,66 @@ def op_buffer_store_format_d16_x(self, ops, mods): uav, word3, stride, num_records, idx_expr, voff_expr, soff_expr, imm_offset, val_expr) self.emit(call if self.exec_known else 'if (exec & 1) ' + call) + def op_buffer_store_format_xyzw(self, ops, mods): + """Lower compute MUBUF buffer_store_format_xyzw (opcode 0x07) in the idxen form with an inline soffset. + + FORMAT, stride and num_records are read at dispatch from the same entry constants as + buffer_store_format_d16_x, with its bounds and OOB_SELECT rules. Only 4-channel formats write + (STORE_FORMAT_XYZW_FORMATS); any other descriptor makes the store a no-op. + """ + name = 'buffer_store_format_xyzw' + if self.kind != 'cs': + raise Unsupported(name) # the unknown-op refusal + raw = getattr(self, 'raw_code', b'') + pc = getattr(self, 'pc', None) + if raw and pc is not None and pc + 8 <= len(raw): + w0, w1 = struct.unpack_from('<II', raw, pc) + if (w0 & 0x00030000) or (w1 & 0x00200000): + raise Unsupported('%s illegal MUBUF encoding bits (lds/reserved)' % name) + if len(ops) != 4: + raise Unsupported('%s with %d operands, expected 4' % (name, len(ops))) + idxen = False + imm_offset = None + for m in mods: + if m == 'idxen' and not idxen: + idxen = True + elif m == 'offen': + raise Unsupported('%s offen address form (only idxen is modelled)' % name) + elif m.startswith('offset:') and imm_offset is None and re.fullmatch(r'0x[0-9a-f]+|\d+', m[7:]): + imm_offset = int(m[7:], 0) + if imm_offset > 0xfff: + raise Unsupported('%s modifier %s' % (name, m)) + else: + raise Unsupported('%s modifier %s' % (name, m)) + if not idxen: + raise Unsupported('%s without idxen (only the idxen address form is modelled)' % name) + src = reg_range(ops[0]) + if not src or src[0] != 'v' or src[2] - src[1] != 3 or src[2] > 255: + raise Unsupported('%s data %s' % (name, ops[0])) + vaddr = reg_range(ops[1]) + if not vaddr or vaddr[0] != 'v' or vaddr[1] != vaddr[2] or vaddr[1] > 255: + raise Unsupported('%s vaddr %s for idxen' % (name, ops[1])) + if not re.fullmatch(r'0x[0-9a-f]+|\d+', ops[3]): + raise Unsupported('%s soffset %s (only a non-negative inline constant is modelled)' % (name, ops[3])) + rsrc = reg_range(ops[2]) + if not rsrc or rsrc[0] != 's' or rsrc[2] - rsrc[1] != 3 or rsrc[2] > 105: + raise Unsupported('%s descriptor %s' % (name, ops[2])) + key = self.store_descriptor(ops[2], 4, name, stride0_ok=False) + first = self.sym.get(rsrc[1]) + if getattr(self, 'past_entry', False) and not self.formatted_descriptor_from_block(rsrc, first): + raise Unsupported('%s requires descriptor words proven in the entry block or a local table load' % name) + idx = self.u(ops[1]) + data = 'uint4(%s)' % ', '.join(self.u('v%d' % n) for n in range(src[1], src[2] + 1)) + uav = self.pipe.uav(key, 'raw') + uav_index = self.pipe.uavs[key]['index'] + word3 = 'ud%d' % self.pipe.ud(('uav_descword3', uav_index)) + stride = 'ud%d' % self.pipe.ud(('uav_stride', uav_index)) + num_records = 'ud%d' % self.pipe.ud(('uav_numrecords', uav_index)) + self.pipe.uses_store_format_xyzw = self.pipe.uses_pack16_rne = True + call = 'store_format_xyzw(%s, %s, %s, %s, %s, 0u, %du, %du, %s);' % ( + uav, word3, stride, num_records, idx, int(ops[3], 0), imm_offset or 0, data) + self.emit(call if self.exec_known else 'if (exec & 1) ' + call) + def op_tbuffer_load_format_x(self, ops, mods): self.tbuffer(ops, mods, 1) @@ -6592,6 +6692,7 @@ class Pipeline: uses_gather_2d_lod = False uses_store_d16_x = False uses_sad = () + uses_store_format_xyzw = False srv_formats = () uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store @@ -6622,6 +6723,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_sad = set() + self.uses_store_format_xyzw = False self.resources = {} # key -> dict(index, kind) self.samplers = {} # key -> index self.uds = [] # entry-constant sources @@ -6973,6 +7075,65 @@ def common(self): out.append( 'uint sad_u32(uint a, uint b, uint c) {' ' return (a > b ? a - b : b - a) + c; }') + if self.uses_store_format_xyzw: + legacy = [' %sif (field == %du) fmt = %du;' % ('' if i == 0 else 'else ', field, code) + for i, (field, code) in enumerate(sorted(STORE_FORMAT_XYZW_LEGACY_FORMATS.items()))] + out.extend(( + 'uint store_unorm(uint bits, float scale) {', + ' float x = asfloat(bits);', + ' if (isnan(x)) return 0u;', + ' precise float saturated = saturate(x);', + ' precise float scaled = saturated * scale;', + ' return (uint)floor(scaled + 0.5f);', + '}', + 'void store_format_xyzw(RWByteAddressBuffer buf, uint word3, uint stride, uint num_records, ' + 'uint idx, uint voff, uint soff, uint imm_off, uint4 v) {', + ' if ((word3 & 0xcef80000u) != 0u || (word3 & 0xfffu) != 0xfacu) return;', + ' uint oob_sel = (word3 >> 28u) & 3u;', + ' if ((oob_sel != 0u && oob_sel != 3u) || stride > 0x3fffu) return;', + ' uint field = (word3 >> 12u) & 127u;', + ' uint fmt = 0u;', + ' if (((word3 >> 24u) & 1u) != 0u) {', + ' fmt = field;', + ' } else {', + *legacy, + ' }', + ' uint elem_bytes = (fmt == 75u || fmt == 77u) ? 16u : fmt == 71u ? 8u : (fmt == 50u || fmt == 56u) ? 4u : 0u;', + ' if (elem_bytes == 0u) return;', + ' if (voff > 0xffffffffu - imm_off) return;', + ' uint rec_off = voff + imm_off;', + ' uint addr = 0u;', + ' if (oob_sel == 3u) {', + ' if (stride != 0u) return;', + ' if (soff > 0xffffffffu - rec_off) return;', + ' addr = soff + rec_off;', + ' if (elem_bytes > num_records || addr > num_records - elem_bytes) return;', + ' } else {', + ' if (stride == 0u) return;', + ' if (idx >= num_records || elem_bytes > stride || rec_off > stride - elem_bytes) return;', + ' if (idx > (0xffffffffu - rec_off) / stride) return;', + ' uint elem_addr = idx * stride + rec_off;', + ' if (soff > 0xffffffffu - elem_addr) return;', + ' addr = elem_addr + soff;', + ' }', + ' if ((addr & 3u) != 0u) return;', + ' uint uav_bytes = 0u;', + ' buf.GetDimensions(uav_bytes);', + ' if (uav_bytes < elem_bytes || addr > uav_bytes - elem_bytes) return;', + ' if (elem_bytes == 16u) {', + ' buf.Store4(addr, v);', + ' } else if (fmt == 71u) {', + ' buf.Store2(addr, uint2(pack16_rne(asfloat(v.x)) | (pack16_rne(asfloat(v.y)) << 16u), ' + 'pack16_rne(asfloat(v.z)) | (pack16_rne(asfloat(v.w)) << 16u)));', + ' } else if (fmt == 56u) {', + ' buf.Store(addr, store_unorm(v.x, 255.0f) | (store_unorm(v.y, 255.0f) << 8u) ' + '| (store_unorm(v.z, 255.0f) << 16u) | (store_unorm(v.w, 255.0f) << 24u));', + ' } else {', + ' buf.Store(addr, store_unorm(v.x, 1023.0f) | (store_unorm(v.y, 1023.0f) << 10u) ' + '| (store_unorm(v.z, 1023.0f) << 20u) | (store_unorm(v.w, 3.0f) << 30u));', + ' }', + '}', + )) return out def interface(self, for_pixel): From a696744692b2ecc65b72e100be0be8393373bceb Mon Sep 17 00:00:00 2001 From: Ammar Abdelfattah <a.mmar067a.mmar067@gmail.com> Date: Thu, 26 Nov 2026 01:11:57 +0200 Subject: [PATCH 228/232] cpu: harden atomic writes, path validation, and subprocess error handling in exe_aot with CLI suite (#2605) --- CMakeLists.txt | 3 + tests/cpu_exe_aot_cli_check.py | 750 +++++++++++++++++++++++++++++++++ tools/exe_aot.py | 159 +++++-- 3 files changed, 871 insertions(+), 41 deletions(-) create mode 100644 tests/cpu_exe_aot_cli_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 121592e05..e94442942 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7885,6 +7885,9 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:cpu_crc_line>" "$<TARGET_FILE:cpu_crc_castagnoli>" "$<TARGET_FILE:cpu_exe_original>" "$<TARGET_FILE:cpu_exe_io>") set_tests_properties(cpu_exe_aot_convert PROPERTIES TIMEOUT 300) + add_test(NAME cpu_exe_aot_cli_check COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/cpu_exe_aot_cli_check.py") + set_tests_properties(cpu_exe_aot_cli_check PROPERTIES TIMEOUT 60) add_library(cpu_exe_second_provider SHARED tests/cpu/exe_second_provider.cpp) target_link_libraries(cpu_exe_second_provider PRIVATE cpu_exe_io) foreach(variant IN ITEMS original inverted pair swapped framed image two_providers nested nested_bypass) diff --git a/tests/cpu_exe_aot_cli_check.py b/tests/cpu_exe_aot_cli_check.py new file mode 100644 index 000000000..7b8cd4806 --- /dev/null +++ b/tests/cpu_exe_aot_cli_check.py @@ -0,0 +1,750 @@ +"""CLI, atomic write, path validation, subprocess error, and mutation suite for tools/exe_aot.py.""" + +from contextlib import redirect_stderr, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import runpy +import struct +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "exe_aot.py" +sys.path.insert(0, str(ROOT / "tools")) + +import cpu_stdio_exe_aot # noqa: E402 +import exe_aot as tool # noqa: E402 + + +IMAGE_BASE = 0x140000000 +RAW_OFFSET = 0x200 +SECTION_ALIGN = 0x1000 +TEXT_RVA = 0x1000 +RDATA_RVA = 0x2000 +SECTION_SIZE = 0x1000 + + +def _rel32(next_ip: int, target: int) -> bytes: + return struct.pack("<i", target - next_ip) + + +def build_console_exe( + *, + machine: int = 0x8664, + magic: int = 0x20B, + subsystem: int = 3, + characteristics: int = 0x0022, + include_finish_exe: bool = False, + extra_imports: list[tuple[bytes, list[bytes | int]]] | None = None, + entry_mode: str = "stdio", + export_native_entry: bool = True, + register_entry_pdata: bool = True, +): + """Build a minimal synthetic AMD64 PE32+ console EXE for exe_aot CLI tests.""" + text = bytearray(SECTION_SIZE) + rdata = bytearray(SECTION_SIZE) + text_cursor = 0 + rdata_cursor = 0 + + def emit_text(blob: bytes, align: int = 16) -> int: + nonlocal text_cursor + text_cursor = (text_cursor + align - 1) & ~(align - 1) + rva = TEXT_RVA + text_cursor + text[text_cursor:text_cursor + len(blob)] = blob + text_cursor += len(blob) + return rva + + def alloc_rdata(size: int, align: int = 8) -> int: + nonlocal rdata_cursor + rdata_cursor = (rdata_cursor + align - 1) & ~(align - 1) + rva = RDATA_RVA + rdata_cursor + rdata_cursor += size + return rva + + def put_rdata(rva: int, blob: bytes) -> None: + offset = rva - RDATA_RVA + rdata[offset:offset + len(blob)] = blob + + stdio_symbols: list[bytes | int] = [b"getchar", b"putchar", b"fflush"] + modules: list[tuple[bytes, list[bytes | int]]] = [ + (cpu_stdio_exe_aot.STDIO.encode("ascii"), stdio_symbols), + ] + if include_finish_exe: + modules.append((b"cpu_exe_io.dll", [b"finish_exe"])) + if extra_imports: + modules.extend(extra_imports) + + import_size = 20 * (len(modules) + 1) + import_rva = alloc_rdata(import_size, 4) + iat_slots: dict[tuple[bytes, bytes | int], int] = {} + + for idx, (dll_name, symbols) in enumerate(modules): + dll_rva = alloc_rdata(len(dll_name) + 1, 2) + put_rdata(dll_rva, dll_name + b"\0") + entries: list[int] = [] + for sym in symbols: + if isinstance(sym, int): + entries.append(0x8000000000000000 | sym) + else: + hint_rva = alloc_rdata(2 + len(sym) + 1, 2) + put_rdata(hint_rva, b"\0\0" + sym + b"\0") + entries.append(hint_rva) + table_bytes = struct.pack(f"<{len(entries) + 1}Q", *entries, 0) + ilt_rva = alloc_rdata(len(table_bytes), 8) + put_rdata(ilt_rva, table_bytes) + iat_rva = alloc_rdata(len(table_bytes), 8) + put_rdata(iat_rva, table_bytes) + for sym_idx, sym in enumerate(symbols): + iat_slots[(dll_name.lower(), sym)] = iat_rva + sym_idx * 8 + put_rdata(import_rva + idx * 20, struct.pack("<5I", ilt_rva, 0, 0, dll_rva, iat_rva)) + + getchar_slot = iat_slots[(cpu_stdio_exe_aot.STDIO.encode("ascii"), b"getchar")] + putchar_slot = iat_slots[(cpu_stdio_exe_aot.STDIO.encode("ascii"), b"putchar")] + fflush_slot = iat_slots[(cpu_stdio_exe_aot.STDIO.encode("ascii"), b"fflush")] + + code = bytearray() + entry_rva = TEXT_RVA + ((text_cursor + 15) & ~15) + if entry_mode == "stdio": + code += b"\x48\x83\xEC\x28" + code += b"\xFF\x15" + _rel32(entry_rva + len(code) + 6, getchar_slot) + code += b"\x89\xC1" + code += b"\xFF\x15" + _rel32(entry_rva + len(code) + 6, putchar_slot) + code += b"\x31\xC9" + code += b"\xFF\x15" + _rel32(entry_rva + len(code) + 6, fflush_slot) + code += b"\x48\x83\xC4\x28\xC3" + elif entry_mode == "cpuid": + code += b"\x0F\xA2\x31\xC0\xC3" + else: + raise ValueError(f"unknown entry_mode {entry_mode!r}") + + actual_entry = emit_text(bytes(code)) + assert actual_entry == entry_rva + entry_end = entry_rva + len(code) + + export_rva = 0 + export_size = 0 + if export_native_entry: + exp_dll_rva = alloc_rdata(len(b"synthetic_console.exe\0"), 2) + put_rdata(exp_dll_rva, b"synthetic_console.exe\0") + exp_name_rva = alloc_rdata(len(b"native_entry\0"), 2) + put_rdata(exp_name_rva, b"native_entry\0") + eat_rva = alloc_rdata(4, 4) + put_rdata(eat_rva, struct.pack("<I", entry_rva)) + ent_rva = alloc_rdata(4, 4) + put_rdata(ent_rva, struct.pack("<I", exp_name_rva)) + eot_rva = alloc_rdata(2, 2) + put_rdata(eot_rva, struct.pack("<H", 0)) + export_size = 40 + export_rva = alloc_rdata(export_size, 4) + put_rdata( + export_rva, + struct.pack( + "<IIHHIIIIIII", + 0, 0, 0, 0, exp_dll_rva, 1, 1, 1, eat_rva, ent_rva, eot_rva, + ), + ) + + pdata_rva = 0 + pdata_size = 0 + if register_entry_pdata: + unwind_rva = alloc_rdata(4, 4) + put_rdata(unwind_rva, b"\x01\x00\x00\x00") + pdata_size = 12 + pdata_rva = alloc_rdata(pdata_size, 4) + put_rdata(pdata_rva, struct.pack("<III", entry_rva, entry_end, unwind_rva)) + + buf = bytearray(RAW_OFFSET + SECTION_SIZE * 2) + buf[0:2] = b"MZ" + pe_off = 0x80 + struct.pack_into("<I", buf, 60, pe_off) + buf[pe_off:pe_off + 4] = b"PE\0\0" + struct.pack_into("<HHIIIHH", buf, pe_off + 4, machine, 2, 0, 0, 0, 0xF0, characteristics) + opt = pe_off + 24 + struct.pack_into( + "<HBBIIIIIQIIHHHHHHIIIIHHQQQQII", + buf, + opt, + magic, 14, 0, SECTION_SIZE, SECTION_SIZE, 0, entry_rva, TEXT_RVA, IMAGE_BASE, + SECTION_ALIGN, 0x200, 6, 0, 0, 0, 6, 0, 0, 0x3000, RAW_OFFSET, 0, subsystem, + 0x160, 0x100000, 0x1000, 0x100000, 0x1000, 0, 16, + ) + dd = opt + 112 + if export_size: + struct.pack_into("<II", buf, dd + 0 * 8, export_rva, export_size) + struct.pack_into("<II", buf, dd + 1 * 8, import_rva, import_size) + if pdata_size: + struct.pack_into("<II", buf, dd + 3 * 8, pdata_rva, pdata_size) + + sections_off = opt + 0xF0 + sections = [ + (b".text\0\0\0", SECTION_SIZE, TEXT_RVA, SECTION_SIZE, RAW_OFFSET, 0x60000020), + (b".rdata\0\0", SECTION_SIZE, RDATA_RVA, SECTION_SIZE, RAW_OFFSET + SECTION_SIZE, 0x40000040), + ] + for idx, (name, vsize, va, rsize, roff, chars) in enumerate(sections): + struct.pack_into("<8sIIIIIIHHI", buf, sections_off + idx * 40, name, vsize, va, rsize, roff, 0, 0, 0, 0, chars) + + buf[RAW_OFFSET:RAW_OFFSET + SECTION_SIZE] = text + buf[RAW_OFFSET + SECTION_SIZE:RAW_OFFSET + SECTION_SIZE * 2] = rdata + return bytes(buf), {"entry_rva": entry_rva, "import_rva": import_rva} + + +def _run_main(argv): + stdout = io.StringIO() + stderr = io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + try: + code = tool.main(argv) + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 2 + return code, stdout.getvalue(), stderr.getvalue() + + +def _run_subprocess(*args): + return subprocess.run( + [sys.executable, "-B", str(TOOL), *args], + capture_output=True, + text=True, + timeout=15, + ) + + +class ExeAotCliPositiveTests(unittest.TestCase): + def test_no_build_atomic_writes_provenance_and_entrypoints(self): + raw, _ = build_console_exe(include_finish_exe=True) + digest = hashlib.sha256(raw).hexdigest() + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + image = root / "sample.exe" + image.write_bytes(raw) + out_dir = root / "out" + out_dir.mkdir() + # Pre-seed stale build artifacts that must be cleared once --no-build succeeds. + for ext in (".exe", ".obj", ".lib", ".exp"): + (out_dir / f"sample_aot{ext}").write_bytes(b"stale") + + seen_replaces = [] + real_replace = os.replace + + def tracking_replace(src, dst): + src_path, dst_path = Path(src), Path(dst) + seen_replaces.append((src_path, dst_path)) + self.assertEqual(src_path.parent.parent.resolve(), dst_path.parent.resolve()) + self.assertEqual(src_path.name, dst_path.name) + return real_replace(src, dst) + + with mock.patch.object(tool.os, "replace", side_effect=tracking_replace): + code, out, err = _run_main([str(image), str(out_dir), "--entry-export", "native_entry", "--no-build"]) + + self.assertIs(type(code), int) + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("translated with profile console-stdio:", out) + self.assertEqual(len(seen_replaces), 2) + self.assertEqual([dst.name for _, dst in seen_replaces], ["sample_aot.cpp", "report.json"]) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json", "sample_aot.cpp"]) + + report = json.loads((out_dir / "report.json").read_text(encoding="utf-8")) + self.assertEqual(report["status"], "translated") + self.assertEqual(report["profile"], "console-stdio") + self.assertEqual(report["sha256"], digest) + self.assertEqual(report["entry_export"], "native_entry") + self.assertNotIn("exe", report) + self.assertEqual( + (out_dir / "sample_aot.cpp").read_text(encoding="ascii"), + cpu_stdio_exe_aot.translate(image, entry_export="native_entry"), + ) + + # Verify sys.argv main(None), runpy __main__, and subprocess invocation on plain EXE. + raw_plain, _ = build_console_exe(include_finish_exe=False) + plain_image = root / "plain.exe" + plain_image.write_bytes(raw_plain) + out_sub = root / "nested" / "plain_out" + cli_argv = [str(TOOL), str(plain_image), str(out_sub), "--no-build"] + with mock.patch.object(sys, "argv", cli_argv): + code_none, out_none, err_none = _run_main(None) + self.assertEqual(code_none, 0, err_none) + self.assertIn("translated with profile console-stdio:", out_none) + + out_runpy = root / "runpy_out" + stdout, stderr = io.StringIO(), io.StringIO() + with ( + mock.patch.object(sys, "argv", [str(TOOL), str(plain_image), str(out_runpy), "--no-build"]), + redirect_stdout(stdout), + redirect_stderr(stderr), + ): + with self.assertRaises(SystemExit) as exited: + runpy.run_path(str(TOOL), run_name="__main__") + self.assertEqual(exited.exception.code, 0) + self.assertEqual(stderr.getvalue(), "") + self.assertIn("translated with profile console-stdio:", stdout.getvalue()) + + out_proc = root / "proc_out" + proc = _run_subprocess(str(plain_image), str(out_proc), "--no-build") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stderr, "") + self.assertIn("translated with profile console-stdio:", proc.stdout) + self.assertEqual(sorted(p.name for p in out_proc.iterdir()), ["plain_aot.cpp", "report.json"]) + + def test_build_success_with_mocked_compiler_passes_bounded_timeout(self): + raw, _ = build_console_exe(include_finish_exe=False) + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + image = root / "app.exe" + image.write_bytes(raw) + out_dir = root / "build_out" + captured = {} + + def fake_run(cmd, **kwargs): + captured["cmd"] = cmd + captured["kwargs"] = kwargs + (Path(kwargs["cwd"]) / "app_aot.exe").write_bytes(b"MZ-fake-exe") + return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="") + + with ( + mock.patch.object(tool.shutil, "which", return_value=r"C:\fake\cl.exe"), + mock.patch.object(tool.subprocess, "run", side_effect=fake_run), + ): + code, out, err = _run_main([str(image), str(out_dir), "--cxx", "custom-cl"]) + + self.assertEqual(code, 0, err) + self.assertEqual(err, "") + self.assertIn("built with profile console-stdio:", out) + self.assertEqual(captured["cmd"][0], r"C:\fake\cl.exe") + self.assertIn("/NOIMPLIB", captured["cmd"]) + self.assertIn("/NOEXP", captured["cmd"]) + self.assertEqual(captured["kwargs"]["timeout"], tool.BUILD_TIMEOUT_S) + self.assertGreater(captured["kwargs"]["timeout"], 0) + self.assertEqual(captured["kwargs"]["cwd"], out_dir.resolve()) + self.assertEqual(captured["kwargs"]["stdin"], subprocess.DEVNULL) + report = json.loads((out_dir / "report.json").read_text(encoding="utf-8")) + self.assertEqual(report["status"], "built") + self.assertEqual(report["compiler"], "cl.exe") + self.assertEqual(Path(report["exe"]).name, "app_aot.exe") + + +class ExeAotCliRefusalTests(unittest.TestCase): + def test_header_imports_and_translate_refusals_clear_stale_outputs(self): + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + # 1) Corrupt non-PE and truncated PE header -> header refusal. + non_pe = root / "bad.exe" + non_pe.write_bytes(b"not a PE image\n") + + raw_pe, _ = build_console_exe() + trunc_pe = root / "trunc_hdr.exe" + trunc_pe.write_bytes(raw_pe[:0x90]) + + for bad_img in (non_pe, trunc_pe): + out_dir = root / f"out_{bad_img.stem}" + out_dir.mkdir() + (out_dir / f"{bad_img.stem}_aot.cpp").write_text("stale\n", encoding="ascii") + (out_dir / f"{bad_img.stem}_aot.exe").write_bytes(b"stale") + code, _, err = _run_main([str(bad_img), str(out_dir), "--no-build"]) + self.assertEqual(code, 1) + self.assertIn("refused at header:", err) + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["report.json"]) + rep = json.loads((out_dir / "report.json").read_text(encoding="utf-8")) + self.assertEqual((rep["status"], rep["refusal"]["stage"]), ("refused", "header")) + + # PEFormatError during parse_data_directories -> header refusal without traceback. + valid_img = root / "valid_pe.exe" + valid_img.write_bytes(raw_pe) + with mock.patch.object(tool.pefile.PE, "parse_data_directories", + side_effect=tool.pefile.PEFormatError("corrupt import table")): + code, _, err = _run_main([str(valid_img), str(root / "out_corrupt_dd"), "--no-build"]) + self.assertEqual(code, 1) + self.assertIn("refused at header: not a PE image:", err) + self.assertIn("corrupt import table", err) + + # 2) Header field refusals: machine, magic, DLL, unlinked. + for label, kwargs in ( + ("machine", dict(machine=0x014C)), + ("magic", dict(magic=0x10B)), + ("dll", dict(characteristics=0x2022)), + ("unlinked", dict(characteristics=0x0000)), + ): + with self.subTest(header_case=label): + raw, _ = build_console_exe(**kwargs) + img = root / f"{label}.exe" + img.write_bytes(raw) + code, _, err = _run_main([str(img), str(root / f"out_{label}"), "--no-build"]) + self.assertEqual(code, 1) + self.assertIn("refused at header:", err) + + # 3) Imports refusal with multiple unbound imports prints "also unbound:" lines. + raw_unbound, _ = build_console_exe(extra_imports=[(b"kernel32.dll", [b"ExitProcess", 42])]) + unbound_img = root / "unbound.exe" + unbound_img.write_bytes(raw_unbound) + code, _, err = _run_main([str(unbound_img), str(root / "out_unbound"), "--no-build"]) + self.assertEqual(code, 1) + self.assertIn("refused at imports:", err) + self.assertIn("kernel32.dll!ExitProcess", err) + self.assertIn("also unbound: kernel32.dll!#42", err) + + # 4) Translate refusal (cpuid) removes stale cpp/exe and records rva. + raw_cpuid, meta_cpuid = build_console_exe(entry_mode="cpuid") + cpuid_img = root / "cpuid.exe" + cpuid_img.write_bytes(raw_cpuid) + out_cpuid = root / "out_cpuid" + out_cpuid.mkdir() + (out_cpuid / "cpuid_aot.cpp").write_text("stale\n", encoding="ascii") + (out_cpuid / "cpuid_aot.exe").write_bytes(b"stale") + code, _, err = _run_main([str(cpuid_img), str(out_cpuid), "--no-build"]) + self.assertEqual(code, 1) + self.assertIn("refused at translate:", err) + self.assertIn("cpuid", err) + self.assertEqual(sorted(p.name for p in out_cpuid.iterdir()), ["report.json"]) + rep_cpuid = json.loads((out_cpuid / "report.json").read_text(encoding="utf-8")) + self.assertEqual(rep_cpuid["refusal"]["rva"], f"{meta_cpuid['entry_rva']:#x}") + + def test_build_refusals_handle_missing_timeout_oserror_and_subprocess_error(self): + raw, _ = build_console_exe() + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + image = root / "app.exe" + image.write_bytes(raw) + + # 1) Missing compiler -> refused at build, C++ kept, no EXE. + out_missing = root / "out_missing" + with mock.patch.object(tool.shutil, "which", return_value=None): + code, _, err = _run_main([str(image), str(out_missing), "--cxx", "no-such-cl"]) + self.assertEqual(code, 1) + self.assertIn("refused at build:", err) + self.assertIn("not found", err) + self.assertEqual(sorted(p.name for p in out_missing.iterdir()), ["app_aot.cpp", "report.json"]) + + # 2) Non-zero exit code + partial EXE removed -> refused at build, tail lines reported. + out_fail = root / "out_fail" + + def fail_compile(cmd, **kwargs): + (Path(kwargs["cwd"]) / "app_aot.exe").write_bytes(b"partial") + return subprocess.CompletedProcess(cmd, 2, stdout="fatal error C1001\n", stderr="detail line\n") + + with ( + mock.patch.object(tool.shutil, "which", return_value=r"C:\fake\cl.exe"), + mock.patch.object(tool.subprocess, "run", side_effect=fail_compile), + ): + code, _, err = _run_main([str(image), str(out_fail)]) + self.assertEqual(code, 1) + self.assertIn("refused at build: cl.exe exited 2", err) + self.assertIn("fatal error C1001", err) + self.assertEqual(sorted(p.name for p in out_fail.iterdir()), ["app_aot.cpp", "report.json"]) + + # 3) TimeoutExpired (bytes stdout/stderr) -> Refusal('build', ... timed out ...). + out_timeout = root / "out_timeout" + timeout_exc = subprocess.TimeoutExpired( + ["cl.exe"], tool.BUILD_TIMEOUT_S, output=b"compiling...\n", stderr=b"hung\n" + ) + with ( + mock.patch.object(tool.shutil, "which", return_value=r"C:\fake\cl.exe"), + mock.patch.object(tool.subprocess, "run", side_effect=timeout_exc), + ): + code, _, err = _run_main([str(image), str(out_timeout)]) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("refused at build: cl.exe timed out", err) + self.assertIn("compiling...", err) + rep_to = json.loads((out_timeout / "report.json").read_text(encoding="utf-8")) + self.assertEqual((rep_to["status"], rep_to["refusal"]["stage"]), ("refused", "build")) + + # 4) OSError & SubprocessError in subprocess.run -> Refusal('build', ...). + for exc, label in ( + (OSError("exec format failure"), "oserror"), + (subprocess.SubprocessError("generic subprocess failure"), "subproc"), + ): + with self.subTest(build_exc=label): + out_err = root / f"out_{label}" + with ( + mock.patch.object(tool.shutil, "which", return_value=r"C:\fake\cl.exe"), + mock.patch.object(tool.subprocess, "run", side_effect=exc), + ): + code, _, err = _run_main([str(image), str(out_err)]) + self.assertEqual(code, 1) + self.assertNotIn("Traceback", err) + self.assertIn("refused at build: failed to run cl.exe:", err) + self.assertIn(str(exc), err) + self.assertEqual(sorted(p.name for p in out_err.iterdir()), ["app_aot.cpp", "report.json"]) + + +class ExeAotCliGuardAndMutationTests(unittest.TestCase): + def _assert_exit_2_clean(self, argv, expected_fragment, *, check_subprocess=True): + code, out, err = _run_main(argv) + self.assertEqual(code, 2, err) + self.assertEqual(out, "") + self.assertNotIn("Traceback", err) + self.assertIn(expected_fragment, err) + if check_subprocess: + proc = _run_subprocess(*argv) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertEqual(proc.stdout, "") + self.assertNotIn("Traceback", proc.stderr) + self.assertIn(expected_fragment, proc.stderr) + + def test_argparse_errors_exit_nonzero_cleanly(self): + for bad_argv, fragment in ( + ([], "required"), + (["only_one_arg"], "required"), + (["img.exe", "out_dir", "--no-such-flag"], "unrecognized"), + ): + with self.subTest(bad_argv=bad_argv): + stdout, stderr = io.StringIO(), io.StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): + with self.assertRaises(SystemExit) as exited: + tool.main(bad_argv) + self.assertNotEqual(exited.exception.code, 0) + self.assertNotIn("Traceback", stderr.getvalue()) + self.assertIn(fragment, stderr.getvalue()) + + def test_upfront_image_and_out_dir_guards_kill_mutations(self): + raw, _ = build_console_exe() + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + valid_img = root / "valid.exe" + valid_img.write_bytes(raw) + img_dir = root / "img_dir" + img_dir.mkdir() + missing_img = root / "missing.exe" + ghost_out = root / "ghost_out" + + # 1) Missing image -> exit 2, out_dir not even created. + self._assert_exit_2_clean([str(missing_img), str(ghost_out), "--no-build"], "not found") + self.assertFalse(ghost_out.exists()) + + # 2) Image is a directory (and empty string via Path("") -> ".") -> exit 2, out_dir not created. + self._assert_exit_2_clean([str(img_dir), str(ghost_out), "--no-build"], "directory") + self.assertFalse(ghost_out.exists()) + self._assert_exit_2_clean(["", str(ghost_out), "--no-build"], "directory", check_subprocess=False) + self.assertFalse(ghost_out.exists()) + + # 3) Direct convert() with empty strings or non-regular image. + with self.assertRaises(ValueError): + tool.convert("", ghost_out, compile_exe=False) + with self.assertRaises(ValueError): + tool.convert(valid_img, "", compile_exe=False) + with mock.patch.object(Path, "exists", return_value=True), \ + mock.patch.object(Path, "is_dir", return_value=False), \ + mock.patch.object(Path, "is_file", return_value=False): + with self.assertRaisesRegex(ValueError, "not a regular file"): + tool.convert(valid_img, ghost_out, compile_exe=False) + + # 4) out_dir is an existing regular file -> exit 2, regular file bytes preserved. + out_file = root / "existing_file" + out_file.write_bytes(b"keep-file-intact") + self._assert_exit_2_clean([str(valid_img), str(out_file), "--no-build"], "not a directory") + self.assertEqual(out_file.read_bytes(), b"keep-file-intact") + + # 5) out_dir whose parent is a file -> mkdir raises OSError -> exit 2 cleanly. + self._assert_exit_2_clean([str(valid_img), str(out_file / "child"), "--no-build"], "") + + # 6) out_dir is a broken/non-dir symlink (real if allowed + mocked). + with mock.patch.object(Path, "is_symlink", autospec=True, + side_effect=lambda p: p.resolve() == ghost_out.resolve()): + self._assert_exit_2_clean( + [str(valid_img), str(ghost_out), "--no-build"], + "not a directory", + check_subprocess=False, + ) + + def test_collision_directory_and_symlink_output_guards_kill_mutations(self): + raw, _ = build_console_exe() + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + # 1) Collision with report.json directly and via hardlink alias. + col_dir = root / "col" + col_dir.mkdir() + report_input = col_dir / "report.json" + report_input.write_bytes(b'{"sentinel":1}\n') + self._assert_exit_2_clean( + [str(report_input), str(col_dir), "--no-build"], + "output would overwrite the input", + ) + self.assertEqual(report_input.read_bytes(), b'{"sentinel":1}\n') + + hardlink_img = root / "alias_input.exe" + hardlink_img.hardlink_to(report_input) + self._assert_exit_2_clean( + [str(hardlink_img), str(col_dir), "--no-build"], + "output would overwrite the input", + ) + self.assertEqual(hardlink_img.read_bytes(), b'{"sentinel":1}\n') + + # 2) Collision with source (_aot.cpp) via hardlink alias. + src_alias_dir = root / "src_alias" + src_alias_dir.mkdir() + src_target = src_alias_dir / "probe_aot.cpp" + src_target.write_bytes(b"sentinel-cpp") + probe_img = root / "probe.exe" + probe_img.hardlink_to(src_target) + self._assert_exit_2_clean( + [str(probe_img), str(src_alias_dir), "--no-build"], + "output would overwrite the input", + ) + self.assertEqual(src_target.read_bytes(), b"sentinel-cpp") + + # 3) report.json or source or exe is an existing directory -> exit 2, prior files intact. + dir_guard = root / "dir_guard" + dir_guard.mkdir() + img = root / "target.exe" + img.write_bytes(raw) + prior_src = dir_guard / "target_aot.cpp" + prior_src.write_text("prior-cpp\n", encoding="ascii") + (dir_guard / "report.json").mkdir() + self._assert_exit_2_clean([str(img), str(dir_guard), "--no-build"], "report path is a directory") + self.assertEqual(prior_src.read_text(encoding="ascii"), "prior-cpp\n") + (dir_guard / "report.json").rmdir() + + prior_src.unlink() + (dir_guard / "target_aot.cpp").mkdir() + prior_rep = dir_guard / "report.json" + prior_rep.write_text("prior-report\n", encoding="utf-8") + self._assert_exit_2_clean([str(img), str(dir_guard), "--no-build"], "source path is a directory") + self.assertEqual(prior_rep.read_text(encoding="utf-8"), "prior-report\n") + (dir_guard / "target_aot.cpp").rmdir() + + (dir_guard / "target_aot.exe").mkdir() + self._assert_exit_2_clean([str(img), str(dir_guard), "--no-build"], "artifact path is a directory") + self.assertEqual(prior_rep.read_text(encoding="utf-8"), "prior-report\n") + (dir_guard / "target_aot.exe").rmdir() + + # 4) Symlink guards on report.json and source (real symlink if permitted, plus mock fallback). + sym_dir = root / "sym_guard" + sym_dir.mkdir() + real_target = root / "real_target.txt" + real_target.write_text("do-not-touch\n", encoding="utf-8") + for label, target_name in (("report", "report.json"), ("source", "target_aot.cpp")): + candidate = sym_dir / target_name + try: + candidate.symlink_to(real_target) + created_real = True + except OSError as exc: + if getattr(exc, "winerror", None) != 1314: + raise + created_real = False + + if created_real: + self._assert_exit_2_clean( + [str(img), str(sym_dir), "--no-build"], + f"{label} path is a symbolic link", + ) + candidate.unlink() + else: + with mock.patch.object(Path, "is_symlink", autospec=True, + side_effect=lambda p, expected=candidate: p.resolve() == expected.resolve()): + self._assert_exit_2_clean( + [str(img), str(sym_dir), "--no-build"], + f"{label} path is a symbolic link", + check_subprocess=False, + ) + self.assertEqual(real_target.read_text(encoding="utf-8"), "do-not-touch\n") + + def test_atomic_write_failures_preserve_prior_files_and_leave_zero_temp_dirs(self): + raw, _ = build_console_exe() + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + image = root / "app.exe" + image.write_bytes(raw) + out_dir = root / "atomic_out" + out_dir.mkdir() + src_path = out_dir / "app_aot.cpp" + exe_path = out_dir / "app_aot.exe" + rep_path = out_dir / "report.json" + + # 1) os.replace fails on source write -> preserves prior source, exe, report; zero temp dirs. + src_path.write_text("prior-source\n", encoding="ascii") + exe_path.write_bytes(b"prior-exe") + rep_path.write_text("prior-report\n", encoding="utf-8") + + def fail_first_replace(src, dst): + self.assertEqual(Path(dst).resolve(), src_path.resolve()) + self.assertTrue(Path(src).is_file()) + self.assertEqual(Path(src).parent.parent.resolve(), out_dir.resolve()) + raise OSError("simulated source replace failure") + + with mock.patch.object(tool.os, "replace", side_effect=fail_first_replace): + self._assert_exit_2_clean( + [str(image), str(out_dir), "--no-build"], + "simulated source replace failure", + check_subprocess=False, + ) + self.assertEqual(src_path.read_text(encoding="ascii"), "prior-source\n") + self.assertEqual(exe_path.read_bytes(), b"prior-exe") + self.assertEqual(rep_path.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["app_aot.cpp", "app_aot.exe", "report.json"]) + + # 2) Staging write_text fails on source -> os.replace never called, prior files intact, zero temp dirs. + with ( + mock.patch.object(tool.os, "replace") as replace_mock, + mock.patch.object(Path, "write_text", side_effect=OSError("simulated stage source failure")), + ): + self._assert_exit_2_clean( + [str(image), str(out_dir), "--no-build"], + "simulated stage source failure", + check_subprocess=False, + ) + replace_mock.assert_not_called() + self.assertEqual(src_path.read_text(encoding="ascii"), "prior-source\n") + self.assertEqual(rep_path.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["app_aot.cpp", "app_aot.exe", "report.json"]) + + # 3) os.replace fails on report.json write (succeeds on source) -> preserves prior report.json, zero temp dirs. + real_replace = os.replace + + def fail_report_replace(src, dst): + if Path(dst).resolve() == rep_path.resolve(): + self.assertTrue(Path(src).is_file()) + self.assertEqual(Path(src).parent.parent.resolve(), out_dir.resolve()) + raise OSError("simulated report replace failure") + return real_replace(src, dst) + + with mock.patch.object(tool.os, "replace", side_effect=fail_report_replace): + self._assert_exit_2_clean( + [str(image), str(out_dir), "--no-build"], + "simulated report replace failure", + check_subprocess=False, + ) + self.assertEqual(rep_path.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["app_aot.cpp", "report.json"]) + + # 4) Staging write_text fails on report.json -> preserves prior report.json, zero temp dirs. + real_write_text = Path.write_text + + def fail_report_stage(path_self, data, *args, **kwargs): + if path_self.name == "report.json": + raise OSError("simulated stage report failure") + return real_write_text(path_self, data, *args, **kwargs) + + with mock.patch.object(Path, "write_text", autospec=True, side_effect=fail_report_stage): + self._assert_exit_2_clean( + [str(image), str(out_dir), "--no-build"], + "simulated stage report failure", + check_subprocess=False, + ) + self.assertEqual(rep_path.read_text(encoding="utf-8"), "prior-report\n") + self.assertEqual(sorted(p.name for p in out_dir.iterdir()), ["app_aot.cpp", "report.json"]) + + def test_main_catches_oserror_valueerror_and_subproc_error_without_traceback(self): + with TemporaryDirectory() as tmp: + root = Path(tmp).resolve() + out_dir = root / "out" + for exc in ( + OSError("simulated io error"), + ValueError("simulated value error"), + subprocess.SubprocessError("simulated subprocess error"), + ): + with self.subTest(exc=type(exc).__name__): + with mock.patch.object(tool, "convert", side_effect=exc): + self._assert_exit_2_clean( + ["any.exe", str(out_dir)], + str(exc), + check_subprocess=False, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/exe_aot.py b/tools/exe_aot.py index c462657cd..7a00cc1b2 100644 --- a/tools/exe_aot.py +++ b/tools/exe_aot.py @@ -9,11 +9,13 @@ import argparse import hashlib import json +import os from pathlib import Path import re import shutil import subprocess import sys +import tempfile import pefile @@ -27,6 +29,7 @@ OPTIONAL_IMPORTS = {cpu_stdio_exe_aot.STARTUP_ONLY} FIRST_RVA = re.compile(r"\bRVA (0x[0-9a-f]+)") CXX_FLAGS = ("/nologo", "/std:c++17", "/O2", "/MT", "/EHsc") +BUILD_TIMEOUT_S = 120 class Refusal(Exception): @@ -39,28 +42,28 @@ def __init__(self, stage, message, **details): def read_header(data): try: pe = pefile.PE(data=data, fast_load=True) + with pe: + header, opt = pe.FILE_HEADER, pe.OPTIONAL_HEADER + if header.Machine != 0x8664 or opt.Magic != 0x20b: + raise Refusal("header", f"expected an AMD64 PE32+ image, found machine {header.Machine:#x} " + f"and optional-header magic {opt.Magic:#x}") + if header.Characteristics & 0x2000 or not header.Characteristics & 2: + raise Refusal("header", "expected an executable image, found a DLL or an unlinked image") + directories = opt.DATA_DIRECTORY + pe.parse_data_directories(directories=[1]) + imports = [] + for module in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []): + dll = module.dll.decode("ascii", "replace").lower() + for imp in module.imports: + imports.append((dll, imp.name if imp.name else imp.ordinal)) + return { + "subsystem": opt.Subsystem, + "entry_rva": f"{opt.AddressOfEntryPoint:#x}", + "tls_directory": len(directories) > 9 and bool(directories[9].VirtualAddress), + "delay_imports": len(directories) > 13 and bool(directories[13].VirtualAddress), + }, imports except pefile.PEFormatError as exc: raise Refusal("header", f"not a PE image: {exc}") from exc - with pe: - header, opt = pe.FILE_HEADER, pe.OPTIONAL_HEADER - if header.Machine != 0x8664 or opt.Magic != 0x20b: - raise Refusal("header", f"expected an AMD64 PE32+ image, found machine {header.Machine:#x} " - f"and optional-header magic {opt.Magic:#x}") - if header.Characteristics & 0x2000 or not header.Characteristics & 2: - raise Refusal("header", "expected an executable image, found a DLL or an unlinked image") - directories = opt.DATA_DIRECTORY - pe.parse_data_directories(directories=[1]) - imports = [] - for module in getattr(pe, "DIRECTORY_ENTRY_IMPORT", []): - dll = module.dll.decode("ascii", "replace").lower() - for imp in module.imports: - imports.append((dll, imp.name if imp.name else imp.ordinal)) - return { - "subsystem": opt.Subsystem, - "entry_rva": f"{opt.AddressOfEntryPoint:#x}", - "tls_directory": len(directories) > 9 and bool(directories[9].VirtualAddress), - "delay_imports": len(directories) > 13 and bool(directories[13].VirtualAddress), - }, imports def import_label(dll, name): @@ -78,35 +81,104 @@ def choose_profile(imports, entry_export): return best -def build(cxx, source, exe): +def _tail_lines(output): + if isinstance(output, bytes): + output = output.decode("utf-8", errors="replace") + return output.strip().splitlines()[-10:] if output else [] + + +def _same_path(left, right): + if left == right: + return True + if left.exists() and right.exists() and left.samefile(right): + return True + try: + return left.resolve() == right.resolve() + except OSError: + return False + + +def _atomic_write_text(path, text, *, encoding): + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=path.parent) as staging_dir: + staged = Path(staging_dir) / path.name + staged.write_text(text, encoding=encoding) + os.replace(staged, path) + + +def _validate_paths(image, out_dir): + if not str(image): + raise ValueError("input image path must not be empty") + if not str(out_dir): + raise ValueError("output directory path must not be empty") + raw_image = Path(image) + if not raw_image.exists(): + raise FileNotFoundError(f"input image not found: {raw_image}") + if raw_image.is_dir(): + raise IsADirectoryError(f"input image is a directory: {raw_image}") + if not raw_image.is_file(): + raise ValueError(f"input image is not a regular file: {raw_image}") + raw_out_dir = Path(out_dir) + if (raw_out_dir.exists() or raw_out_dir.is_symlink()) and not raw_out_dir.is_dir(): + raise ValueError(f"output directory path is not a directory: {raw_out_dir}") + + resolved_image = raw_image.resolve() + resolved_out_dir = raw_out_dir.resolve() + source = resolved_out_dir / f"{resolved_image.stem}_aot.cpp" + exe = resolved_out_dir / f"{resolved_image.stem}_aot.exe" + report_path = resolved_out_dir / "report.json" + artifacts = (source, exe, *(exe.with_suffix(suffix) for suffix in (".obj", ".lib", ".exp"))) + if any(_same_path(path, resolved_image) for path in (*artifacts, report_path)): + raise ValueError(f"output would overwrite the input {resolved_image}") + for label, path in (("source", source), ("report", report_path), + *(("artifact", item) for item in artifacts[1:])): + if path.is_symlink(): + raise ValueError(f"{label} path is a symbolic link: {path}") + if path.is_dir(): + raise ValueError(f"{label} path is a directory: {path}") + return resolved_image, resolved_out_dir, source, exe, report_path, artifacts + + +def build(cxx, source, exe, *, timeout=BUILD_TIMEOUT_S): compiler = shutil.which(str(cxx)) if cxx else shutil.which("cl") if compiler is None: raise Refusal("build", f"C++ compiler {cxx or 'cl'} not found; run tools/dev.ps1 or pass --cxx") # The provenance export would otherwise make the linker write an import library and .exp file. command = [compiler, *CXX_FLAGS, source.name, f"/Fe{exe.name}", f"/Fo{source.stem}.obj", "/link", "/NOIMPLIB", "/NOEXP"] - result = subprocess.run(command, cwd=source.parent, capture_output=True, text=True, errors="replace") + try: + result = subprocess.run( + command, + cwd=source.parent, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + errors="replace", + timeout=timeout, + ) + except subprocess.TimeoutExpired as exc: + combined = "".join( + chunk.decode("utf-8", errors="replace") if isinstance(chunk, bytes) else (chunk or "") + for chunk in (exc.stdout, exc.stderr) + ) + raise Refusal( + "build", + f"{Path(compiler).name} timed out after {exc.timeout}s", + output=_tail_lines(combined), + ) from exc + except (OSError, subprocess.SubprocessError) as exc: + raise Refusal("build", f"failed to run {Path(compiler).name}: {exc}") from exc if result.returncode or not exe.is_file(): - tail = (result.stdout + result.stderr).strip().splitlines()[-10:] + tail = _tail_lines((result.stdout or "") + (result.stderr or "")) raise Refusal("build", f"{Path(compiler).name} exited {result.returncode}", output=tail) return Path(compiler).name def convert(image, out_dir, *, entry_export=None, cxx=None, compile_exe=True): - image = Path(image).resolve() - out_dir = Path(out_dir).resolve() - out_dir.mkdir(parents=True, exist_ok=True) - source = out_dir / f"{image.stem}_aot.cpp" - exe = out_dir / f"{image.stem}_aot.exe" - report_path = out_dir / "report.json" - artifacts = (source, exe, *(exe.with_suffix(suffix) for suffix in (".obj", ".lib", ".exp"))) - if any(path == image or (path.exists() and image.samefile(path)) for path in (*artifacts, report_path)): - raise ValueError(f"output would overwrite the input {image}") - if report_path.is_symlink(): - raise ValueError(f"report path is a symbolic link: {report_path}") + image, out_dir, source, exe, report_path, artifacts = _validate_paths(image, out_dir) data = image.read_bytes() - for stale in artifacts: - stale.unlink(missing_ok=True) + out_dir.mkdir(parents=True, exist_ok=True) + build_artifacts = artifacts[1:] report = {"input": str(image), "sha256": hashlib.sha256(data).hexdigest(), "entry_export": entry_export} try: @@ -120,23 +192,28 @@ def convert(image, out_dir, *, entry_export=None, cxx=None, compile_exe=True): bindings, host, translate = PROFILES[profile] try: text = translate(image, bindings, host, entry_export=entry_export) - except ValueError as exc: + except (ValueError, pefile.PEFormatError) as exc: match = FIRST_RVA.search(str(exc)) raise Refusal("translate", str(exc), rva=match and match.group(1)) from exc - source.write_text(text, encoding="ascii") + _atomic_write_text(source, text, encoding="ascii") report["source"] = str(source) + for stale in build_artifacts: + stale.unlink(missing_ok=True) if compile_exe: report["compiler"] = build(cxx, source, exe) report["exe"] = str(exe) report["status"] = "built" if compile_exe else "translated" except Refusal as refusal: + to_unlink = build_artifacts if refusal.stage == "build" else artifacts + for stale in to_unlink: + stale.unlink(missing_ok=True) report["status"] = "refused" report["refusal"] = {"stage": refusal.stage, "message": str(refusal), **refusal.details} - report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + _atomic_write_text(report_path, json.dumps(report, indent=2) + "\n", encoding="utf-8") return report -def main(argv=None): +def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("image", type=Path, help="PE32+ x64 executable to convert") parser.add_argument("out_dir", type=Path, help="directory for the generated C++, EXE and report.json") @@ -147,7 +224,7 @@ def main(argv=None): try: report = convert(args.image, args.out_dir, entry_export=args.entry_export, cxx=args.cxx, compile_exe=not args.no_build) - except (OSError, ValueError) as exc: + except (OSError, ValueError, subprocess.SubprocessError) as exc: parser.exit(2, f"{exc}\n") if report["status"] == "refused": refusal = report["refusal"] From 8298ec668ed13f6659d5f947cfcccfdbdf2264f9 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:15:16 +0100 Subject: [PATCH 229/232] tests: run the six integer-format MRT cases in parallel (#2588) * tests: run the six integer-format MRT cases in parallel private caches Part of #448 * tests: check legacy cache hits in the populated integer-format session --------- Co-authored-by: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- tests/startup_mrt_check.py | 147 ++++++++++++++++++++++--------------- 1 file changed, 86 insertions(+), 61 deletions(-) diff --git a/tests/startup_mrt_check.py b/tests/startup_mrt_check.py index e4a48f226..993e590b8 100644 --- a/tests/startup_mrt_check.py +++ b/tests/startup_mrt_check.py @@ -1,4 +1,5 @@ """Check typed gfx1013 colour exports through the wrapped draw and offline cache.""" +from concurrent.futures import ThreadPoolExecutor import os from pathlib import Path import re @@ -6,6 +7,7 @@ import subprocess import sys import tempfile +from types import SimpleNamespace from startup_stream_check import container, gfx2hlsl from startup_stream_draw_check import vertex, vop1 @@ -59,91 +61,114 @@ def check(work, consumer, backend, kind, dxc, fxc): if not Path(compiler).is_file(): print(f'{kind} compiler unavailable') return 77 - cache = work / 'cache' - cache.mkdir() - vs, ps, root, output = (work / name for name in ('vs', 'ps', 'root', 'pixels')) + vs, ps = work / 'vs', work / 'ps' vs.write_bytes(vertex()) - env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', - X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache), X2W_FXC=fxc if kind == 'fxc' else '') - args = [consumer, vs, ps, root, backend, output] - - def draw(fmt, word=0, wanted_draw=True): - result = subprocess.run(args + [str(fmt), str(word)], env=env, capture_output=True, text=True) - if result.returncode == 77: - raise SystemExit(77) - print(result.stdout, end='') - debug = next((line for line in result.stderr.splitlines() if 'debug layer:' in line), '') - assert debug, result.stderr - print(debug) - assert not re.search(r'x2w-d3d12-debug.*sev=[012]\b', result.stderr), result.stderr - actual_draw = '-> drawn;' in result.stderr - assert result.returncode == 0 and actual_draw == wanted_draw, result.stderr - return output.read_bytes(), result.stderr - - def queue_request(fmt, formats): - pixels, log = draw(fmt, wanted_draw=False) - assert 'no RTV translation' in log, log - base = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) - line = 'rtv1 ' + ' '.join(map(str, (base, *formats))) - key = f'{gfx2hlsl.fnv(line.encode("ascii")):016x}' - assert (cache / f'req_{key}.rtv').read_text() == line - return key, line, pixels - - def request(fmt, formats): - key, line, pixels = queue_request(fmt, formats) - subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) - assert (cache / f'{key}.txt').read_text().splitlines()[-1] == line - return key, pixels - - def compile_pair(key): - for stage in ('vs', 'ps'): - compile_shader(compiler, kind, stage, cache / f'{key}.{stage}.hlsl', cache / f'{key}.{stage}.cso', - cache / f'{key}.{stage}.asm') - return signature(cache / f'{key}.ps.asm') + + def session(name): + """Private cache, root and output files, so sessions can run side by side.""" + cache = work / name + cache.mkdir() + root, output = cache / 'root', cache / 'pixels' + env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', + X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache), X2W_FXC=fxc if kind == 'fxc' else '') + args = [consumer, vs, ps, root, backend, output] + + def draw(fmt, word=0, wanted_draw=True): + result = subprocess.run(args + [str(fmt), str(word)], env=env, capture_output=True, text=True) + if result.returncode == 77: + raise SystemExit(77) + print(result.stdout, end='') + debug = next((line for line in result.stderr.splitlines() if 'debug layer:' in line), '') + assert debug, result.stderr + print(debug) + assert not re.search(r'x2w-d3d12-debug.*sev=[012]\b', result.stderr), result.stderr + actual_draw = '-> drawn;' in result.stderr + assert result.returncode == 0 and actual_draw == wanted_draw, result.stderr + return output.read_bytes(), result.stderr + + def queue_request(fmt, formats): + pixels, log = draw(fmt, wanted_draw=False) + assert 'no RTV translation' in log, log + base = gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()) + line = 'rtv1 ' + ' '.join(map(str, (base, *formats))) + key = f'{gfx2hlsl.fnv(line.encode("ascii")):016x}' + assert (cache / f'req_{key}.rtv').read_text() == line + return key, line, pixels + + def request(fmt, formats): + key, line, pixels = queue_request(fmt, formats) + subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', cache], env=env, check=True) + assert (cache / f'{key}.txt').read_text().splitlines()[-1] == line + return key, pixels + + def compile_pair(key): + for stage in ('vs', 'ps'): + compile_shader(compiler, kind, stage, cache / f'{key}.{stage}.hlsl', cache / f'{key}.{stage}.cso', + cache / f'{key}.{stage}.asm') + return signature(cache / f'{key}.ps.asm') + + return SimpleNamespace(cache=cache, root=root, output=output, env=env, draw=draw, + queue_request=queue_request, request=request, compile_pair=compile_pair) + + main = session('cache') + cache, root, output, env = main.cache, main.root, main.output, main.env + draw, queue_request, request, compile_pair = main.draw, main.queue_request, main.request, main.compile_pair ps.write_bytes(pixel((INTEGER_WORD, 2, 3, 4), unorm=True)) - variants = {} - for fmt, expected_type, channels in INTEGER_FORMATS: - key, cleared = request(fmt, (fmt, 28)) - variants[fmt] = key + integer_sessions = {fmt: session(f'int{fmt}') for fmt, _, _ in INTEGER_FORMATS} + + def integer_format(fmt, expected_type, channels): + s = integer_sessions[fmt] + key, cleared = s.request(fmt, (fmt, 28)) # The harness clears every target to (0, 0, 1, 1); integer channels hold those values as words. assert cleared == struct.pack(f'<{channels}I', *(0, 0, 1, 1)[:channels]) + bytes.fromhex('0000ffff'), cleared.hex() - outputs = compile_pair(key) + outputs = s.compile_pair(key) assert outputs == {'0': expected_type, '1': 'float'}, outputs - manifest = cache / f'{key}.txt' + manifest = s.cache / f'{key}.txt' manifest.rename(str(manifest) + '.pending') - env['X2W_TEST_PUBLISH_MANIFEST'] = str(manifest) - pixels, log = draw(fmt) - del env['X2W_TEST_PUBLISH_MANIFEST'] - assert Path(str(output) + '.first').read_bytes() == cleared + s.env['X2W_TEST_PUBLISH_MANIFEST'] = str(manifest) + pixels, log = s.draw(fmt) + del s.env['X2W_TEST_PUBLISH_MANIFEST'] + assert Path(str(s.output) + '.first').read_bytes() == cleared assert f'2 targets (format {fmt}) -> 0x00000000' in log, log words = (INTEGER_WORD, 2, 3, 4)[:channels] assert pixels == struct.pack(f'<{channels}I4B', *words, 255, 0, 0, 255), pixels.hex() print(f'{kind} {backend} {expected_type} format {fmt} MRT0={pixels[:4 * channels].hex()}; UNORM MRT1=ff0000ff') if fmt == 42: for unverified in REFUSED_INTEGER_FORMATS: - line = f'rtv1 {gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes())} {unverified} 28' + line = f'rtv1 {gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), s.root.read_bytes())} {unverified} 28' refused = f'{gfx2hlsl.fnv(line.encode("ascii")):016x}' - marker = cache / f'req_{refused}.rtv' + marker = s.cache / f'req_{refused}.rtv' marker.write_text(line) - result = gfx2hlsl.translate_request(cache, int(refused, 16)) + result = gfx2hlsl.translate_request(s.cache, int(refused, 16)) assert re.fullmatch(rf'unsupported: unverified (UINT|SINT) RTV format {unverified}', result), result - assert not (cache / f'{refused}.txt').exists() + assert not (s.cache / f'{refused}.txt').exists() # Later --pending runs would retry this synthetic request on every valid format. marker.unlink() print(f'{kind} {backend} three-channel integer formats {REFUSED_INTEGER_FORMATS} refused at translation') # A pre-existing base translation may lack its original request files. - base = f'{gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), root.read_bytes()):016x}' - compile_pair(base) + base = f'{gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), s.root.read_bytes()):016x}' + s.compile_pair(base) for ext in ('a', 'b', 'root'): - (cache / f'req_{base}.{ext}').unlink() + (s.cache / f'req_{base}.{ext}').unlink() + return key + + # Each format needs two device creations and two compiles; run them side by side in private caches. + with ThreadPoolExecutor(max_workers=len(INTEGER_FORMATS)) as pool: + futures = [pool.submit(integer_format, *entry) for entry in INTEGER_FORMATS] + variants = {entry[0]: future.result() for entry, future in zip(INTEGER_FORMATS, futures)} assert len({variants[f] for f, _, _ in INTEGER_FORMATS}) == len(INTEGER_FORMATS) - # A SINT artifact under the UINT cache key must be refused before PSO creation. - unsigned = cache / f'{variants[42]}.txt' - unsigned.write_bytes((cache / f'{variants[43]}.txt').read_bytes()) - pixels, log = draw(42, wanted_draw=False) + # This cache still has the compiled base and UINT pair. Substitute only the signed manifest. + # On a base hit the runtime must also republish the three source blobs removed above. + uint = integer_sessions[42] + unsigned = uint.cache / f'{variants[42]}.txt' + unsigned.write_bytes((integer_sessions[43].cache / f'{variants[43]}.txt').read_bytes()) + pixels, log = uint.draw(42, wanted_draw=False) assert 'RTV manifest mismatch' in log and 'desktop pipeline for' not in log, log assert pixels.hex() == '000000000000ffff', pixels.hex() + base = f'{gfx2hlsl.pipeline_key(vs.read_bytes(), ps.read_bytes(), uint.root.read_bytes()):016x}' + for ext, source in (('a', vs), ('b', ps), ('root', uint.root)): + assert (uint.cache / f'req_{base}.{ext}').read_bytes() == source.read_bytes(), ext print(f'{kind} {backend} stale signedness control: refused before PSO creation') def low_bits_control(key, fmt, trunc, expected): From 444bf3a8d3bcccf03ea59022ddee7f2fe55b955d Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:15:31 +0100 Subject: [PATCH 230/232] tests: accept a heartbeat peak commit that rose between samples (#2567) * fix: let the heartbeat test accept a peak commit that rose between samples * test: shorten the heartbeat and storage worker waits The heartbeat thread reads X2W_HEARTBEAT_INTERVAL_MS (1000 to 10000, default 10000) so startup_heartbeat_commit takes about 3 s instead of 30 s. The storage worker test polls every 1 ms instead of 5 ms. * test: check the heartbeat interval override takes effect * test: add negative controls for the heartbeat peak check * test: keep the storage worker poll interval (no measured gain) On Win2025 the test took 37.5 s with 5 ms polls and 37.1 to 40.4 s with 1 ms polls, so the change is dropped. --- src/startup_stubs/xcrdapi.cpp | 18 ++++++++++++++++-- tests/startup_heartbeat_check.py | 24 +++++++++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index a6d013a71..50d543a16 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -1507,6 +1507,18 @@ MemorySample memory_sample() noexcept return sample; } +// The heartbeat interval in ms: 10000 unless X2W_HEARTBEAT_INTERVAL_MS holds a whole number from 1000 +// to 10000. Only tests set it, to see a sample without waiting 10 s; anything else keeps the default. +DWORD heartbeat_interval_ms() noexcept +{ + char text[16]; + const DWORD length = GetEnvironmentVariableA("X2W_HEARTBEAT_INTERVAL_MS", text, sizeof(text)); + if (length == 0 || length >= sizeof(text)) return 10000; + char* end = nullptr; + const unsigned long value = std::strtoul(text, &end, 10); + return (*end == '\0' && value >= 1000 && value <= 10000) ? static_cast<DWORD>(value) : 10000; +} + } // namespace extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) @@ -1527,8 +1539,10 @@ extern "C" long __stdcall DStorageGetFactory(const GUID* riid, void** out) static HANDLE heartbeat = CreateThread(nullptr, 0, [](void*) -> DWORD { LONG last = -1; MemorySample last_memory; - for (int second = 10;; second += 10) { - Sleep(10000); + const DWORD interval_ms = heartbeat_interval_ms(); + for (DWORD elapsed_ms = interval_ms;; elapsed_ms += interval_ms) { + const int second = static_cast<int>(elapsed_ms / 1000); + Sleep(interval_ms); // Sample the counters once for every line of this report, even while the worker is reporting // new failures. StorageFailureCounts failure_counts; diff --git a/tests/startup_heartbeat_check.py b/tests/startup_heartbeat_check.py index aa180c54d..451b0ba13 100644 --- a/tests/startup_heartbeat_check.py +++ b/tests/startup_heartbeat_check.py @@ -61,10 +61,25 @@ def wait_for_sample(log, predicate): raise AssertionError("no matching heartbeat sample: " + log.read_text(errors="replace")[-1200:]) +def released_is_valid(peak_mib, current_mib, released): + """After the extra commit is freed: the peak never falls, and the commit drops by at least 8 MiB.""" + return released[1] >= peak_mib and released[2] <= current_mib - 8 + + +def controls(): + """Negative controls: the check above must reject a fallen peak and a commit that did not drop.""" + assert released_is_valid(100, 50, (3, 100, 40)), "equal peak must pass" + assert released_is_valid(100, 50, (3, 120, 40)), "a peak raised by the heartbeat thread must pass" + assert not released_is_valid(100, 50, (3, 99, 40)), "a falling peak must fail" + assert not released_is_valid(100, 50, (3, 100, 45)), "a commit that dropped less than 8 MiB must fail" + print("controls ok") + + def main(xmem_path, xcrdapi_path): log = Path(tempfile.gettempdir()) / f"x2w-heartbeat-{os.getpid()}.txt" log.write_bytes(b"") os.environ["X2W_TRAP_LOG"] = str(log) + os.environ["X2W_HEARTBEAT_INTERVAL_MS"] = "1000" # three samples in about 3 s, not 30 s xcrdapi = C.WinDLL(str(Path(xcrdapi_path).resolve()), use_last_error=True, winmode=0x900) kernel = C.WinDLL("kernelbase.dll", use_last_error=True) pointer, number = C.c_void_p, C.c_size_t @@ -72,6 +87,7 @@ def main(xmem_path, xcrdapi_path): factory = pointer() assert get_factory(None, C.byref(factory)) == 0 and factory.value, "DStorageGetFactory failed" first_sample = wait_for_sample(log, lambda sample: sample[3] == "unknown") + assert first_sample[0] < 10, f"the interval override was ignored: first sample at {first_sample[0]} s" library = C.WinDLL(str(Path(xmem_path).resolve()), use_last_error=True, winmode=0x900) allocate = bind(library, "XMemAllocatePhysicalPages", [number, C.POINTER(number), C.POINTER(number)], C.c_int) release = bind(library, "XMemFreePhysicalPages", [number, C.POINTER(number)], C.c_int) @@ -106,9 +122,9 @@ def main(xmem_path, xcrdapi_path): assert free(extra, 0, WIN_RELEASE), C.get_last_error() extra = None released = wait_for_sample(log, lambda sample: sample[0] > second_mark and sample[3] == "2") - assert released[1] == peak_mib and released[2] <= current_mib - 8, (peak_mib, current_mib, released) + assert released_is_valid(peak_mib, current_mib, released), (peak_mib, current_mib, released) print(f"sections unknown at {first_sample[0]} s, then {sections} at {second_mark} s; " - f"commit fell from {current_mib} to {released[2]} MiB at unchanged peak {peak_mib} MiB") + f"commit fell from {current_mib} to {released[2]} MiB with peak {peak_mib} MiB then {released[1]} MiB") finally: if extra: free(extra, 0, WIN_RELEASE) @@ -125,4 +141,6 @@ def main(xmem_path, xcrdapi_path): if __name__ == "__main__": - main(sys.argv[1], sys.argv[2]) + controls() + if sys.argv[1:] != ["controls"]: + main(sys.argv[1], sys.argv[2]) From 24cfd7c0f6b734e71547f086f24a469c3f9c7c40 Mon Sep 17 00:00:00 2001 From: tedin7 <110300616+tedin7@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:18:44 +0100 Subject: [PATCH 231/232] shader: lower 24-bit multiply, xnor, alignbit and alignbyte in gfx2hlsl (Part of #1723) (#2077) * feat: translate 24-bit multiplies, v_xnor_b32 and the funnel shifts in gfx2hlsl Part of #1723. Adds v_mul_i32_i24, v_mul_hi_i32_i24, v_mul_hi_u32_u24, v_mad_i32_i24, v_xnor_b32, v_alignbit_b32 and v_alignbyte_b32 with a CPU-evaluated check against an unbounded-integer reference. * test: draw 24-bit multiplies, xnor and funnel shifts on D3D12 WARP against an integer reference * fix: read the unsigned 24-bit fields with a shift pair so FXC keeps the high product * fix: simplify the high 24-bit product lowering * fix: build the unsigned 24-bit high product from the signed shift pair; run both compilers before failing * fix: refuse v_mul_hi_u32_u24 instead of translating it to a zero that FXC folds; document the 24-bit multiplies * docs: record the FXC denormal float-output fold behind the v_mul_hi_u32_u24 refusal * fix: keep main's v_mul_i32_i24/v_mad_i32_i24 lowering so the i24 mutation test still matches --------- Co-authored-by: Royoo <3230853833@qq.com> --- CMakeLists.txt | 12 ++ docs/experiments.md | 8 ++ tests/startup_gfx2hlsl_mul24_align_check.py | 82 ++++++++++++++ ...startup_gfx2hlsl_mul24_align_draw_check.py | 104 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 37 +++++++ 5 files changed, 243 insertions(+) create mode 100644 tests/startup_gfx2hlsl_mul24_align_check.py create mode 100644 tests/startup_gfx2hlsl_mul24_align_draw_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index e94442942..24284bdd8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3611,6 +3611,18 @@ if(EXISTS "${INTAKE_PYTHON}") "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) set_tests_properties(startup_gfx2hlsl_sgpr_spill_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl 24-bit multiplies, v_xnor_b32 and the funnel shifts: CPU evaluation of the translated text + # against an independent reference built from unbounded integers. + add_test(NAME startup_gfx2hlsl_mul24_align COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul24_align_check.py") + set_tests_properties(startup_gfx2hlsl_mul24_align PROPERTIES TIMEOUT 120) + # The same lowerings drawn on D3D12 (FXC 5_1 and DXC 6_0), GPU readback against the same reference. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_mul24_align_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_mul24_align_draw_check.py" draw "${DXC_EXECUTABLE}" + "$<TARGET_FILE:offscreen_check>" ${adapter} $<$<BOOL:${STARTUP_FXC}>:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_mul24_align_${adapter} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 16-bit vector ALU (#1723): the translated pairs drawn on WARP and hardware (FXC 5_1 and DXC 6_0), # four result words per draw against an exact binary16 reference. add_test(NAME startup_gfx2hlsl_f16_alu_draw_controls COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 91389bc39..a7f93e88b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -15676,6 +15676,14 @@ The [MASM fixture](../tests/cpu/switch_sal.asm) emits explicit `/6` byte sequenc Not covered by this experiment: `SAL` outside leaf/switch-lifted functions, and title CPU code execution. +### Startup 24-bit multiplies, v_xnor_b32 and the funnel shifts + +`tools/startup/gfx2hlsl.py` translates `v_mul_i32_i24`, `v_mad_i32_i24`, `v_mul_hi_i32_i24`, `v_xnor_b32`, `v_alignbit_b32` and `v_alignbyte_b32` (VOP2 and VOP3 spellings) in 32-bit integer arithmetic, with no 64-bit type. The signed forms sign-extend the low 24 bits of each source with a left shift of 8 and an arithmetic right shift; the high product is assembled from 12-bit halves so that it stays inside 32 bits. + +`v_mul_hi_u32_u24` is refused (`Unsupported`), in the VOP2 and the `_e64` spelling. The exact lowering was written and passes the CPU check, but FXC 10.0.26100 (the compiler the startup path uses, `ps_5_1`) folds it to a constant zero and the draw reads `00000000` for every lane, on WARP and on an RTX 3070 Ti, while DXC compiles the same text correctly. Reported in #2077 by independent runs on an RX 9070 XT, WARP and an RTX 3070 Ti. The cause is not the multiply: the result is at most `0xffff`, so read as a float output word it is always a binary32 denormal, and FXC folds a float output whose provable range lies below `0x00800000` to a constant zero. A compile-only run in #2077 (FXC `ps_5_1`; `/Gis` does not help) showed the fold also for a bare `F(v0 >> 9)` (maximum `0x7fffff`), no fold for `F(v0 >> 8)` (maximum `0xffffff`), and no fold for the same arithmetic written to a `uint4` output. Those variants were compiled, not drawn, and only one FXC version was tried. This replaces an earlier claim that three unsigned variants folded because of how they were written. Small words that FXC cannot prove small survive on hardware (`v_mul_hi_i32_i24` reads back `00003fff,00004000,00000000,ffffc000`). The instruction is therefore refused instead of translated into zeros that look like a result. Any other lowering whose float output word is provably below `0x00800000` would meet the same fold. A lowering FXC keeps can replace the refusal later. + +`tests/startup_gfx2hlsl_mul24_align_check.py` translates each instruction, evaluates the emitted text on the CPU against a reference written with unbounded integers, and checks that `v_mul_hi_u32_u24` is refused. Run with `python3 -B tests/startup_gfx2hlsl_mul24_align_check.py` (`ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_mul24_align$' -V`). `tests/startup_gfx2hlsl_mul24_align_draw_check.py` draws the six translated instructions through FXC `ps_5_1` and DXC `ps_6_0` and compares the GPU readback with the same reference (`startup_gfx2hlsl_mul24_align_warp` and `_hardware`); both compilers run before the test fails, so one compiler's failure does not hide the other's result. The draw covers the six translated instructions only. + ## Non-constant scalar symbols at branch targets in the startup translator Follow-up to #2279, which drops scalar constants at a join that another path writes, over the textual range between diff --git a/tests/startup_gfx2hlsl_mul24_align_check.py b/tests/startup_gfx2hlsl_mul24_align_check.py new file mode 100644 index 000000000..dfb440330 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul24_align_check.py @@ -0,0 +1,82 @@ +"""24-bit multiplies, v_xnor_b32 and the funnel shifts in tools/startup/gfx2hlsl.py: v_mul_i32_i24, +v_mul_hi_i32_i24, v_mad_i32_i24, v_xnor_b32, v_alignbit_b32 and v_alignbyte_b32. + +Each instruction is translated by the real translator, the emitted 32-bit HLSL text is evaluated on the CPU with the +integer evaluator of startup_gfx2hlsl_bit_alu_check.py, and the result is compared with a reference written from the +ISA description with Python's unbounded integers (a 48-bit product, a 64-bit concatenation), not with the lowering's +own expressions. Run with no arguments; exits non-zero on the first mismatch. +""" +import itertools +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Expr, Probe, refused # noqa: E402 + +MASK = 0xffffffff + + +def s24(x): + x &= 0xffffff + return x - (1 << 24) if x >> 23 else x + + +REFERENCE = { + 'v_mul_i32_i24': (2, lambda a, b, c: (s24(a) * s24(b)) & MASK), + 'v_mad_i32_i24': (3, lambda a, b, c: (s24(a) * s24(b) + c) & MASK), + 'v_mul_hi_i32_i24': (2, lambda a, b, c: ((s24(a) * s24(b)) >> 32) & MASK), + 'v_xnor_b32': (2, lambda a, b, c: ~(a ^ b) & MASK), + 'v_alignbit_b32': (3, lambda a, b, c: (((a << 32) | b) >> (c & 31)) & MASK), + 'v_alignbyte_b32': (3, lambda a, b, c: (((a << 32) | b) >> (8 * (c & 3))) & MASK), +} + +FIELD = [0, 1, 2, 0xfff, 0x1000, 0x7fffff, 0x800000, 0x800001, 0xffffff, 0xfffffe, 0x555555, 0xaaaaaa, 0x123456] +WORDS = [0, 1, 0x7fffffff, 0x80000000, MASK, 0x12345678, 0xdeadbeef, 0xff000001, 0x01ffffff, 0xff800000, + 0x00ffffff, 0xfffffffe, 0x89abcdef] +INPUTS = { + 'mul24': [(a | h, b | k, c) for a, b in itertools.product(FIELD, FIELD) for h, k in ((0, 0), (0xab000000, 0x5c000000)) + for c in (0, 1, MASK, 0x80000000, 0x12345678)], + 'bits': [(a, b, c) for a in WORDS for b in WORDS for c in list(range(0, 36)) + [0x80000003, MASK]], +} + + +def lowered(op, arity): + sources = ['v%d' % (2 + i) for i in range(arity)] + probe = Probe() + probe.one(op, '%s v1, %s' % (op, ', '.join(sources))) + assert len(probe.lines) == 1 and probe.lines[0].startswith('v1 = '), probe.lines + return Expr(probe.lines[0][len('v1 = '):-1]), sources + + +def main(): + failures = 0 + for op, (arity, reference) in REFERENCE.items(): + expr, sources = lowered(op, arity) + grid = INPUTS['mul24' if '24' in op else 'bits'] + bad = None + for a, b, c in grid: + got = expr.run(dict(zip(sources, (a, b, c))))[0] + if got != reference(a, b, c): + bad = (a, b, c, got, reference(a, b, c)) + break + print('%s: %d inputs %s' % (op, len(grid), 'ok' if bad is None else 'MISMATCH %s' % (bad,))) + failures += bad is not None + # the _e64 spelling of a VOP2 operation reaches the same lowering + for op, e64 in (('v_mul_i32_i24', 'v_mul_i32_i24_e64'), ('v_xnor_b32', 'v_xnor_b32_e64')): + a, b = lowered(op, 2), lowered(e64, 2) + same = a[0].tokens == b[0].tokens + print('%s: e64 spelling lowers the same %s' % (op, 'ok' if same else 'MISMATCH')) + failures += not same + # v_mul_hi_u32_u24 is refused in both spellings (FXC folds every unsigned lowering to zero; see gfx2hlsl.py) + for assembly in ('v_mul_hi_u32_u24 v1, v2, v3', 'v_mul_hi_u32_u24_e64 v1, v2, v3'): + ok = refused(assembly) + print('%s: refused %s' % (assembly.split(' ', 1)[0], 'ok' if ok else 'MISMATCH')) + failures += not ok + return 1 if failures else 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tests/startup_gfx2hlsl_mul24_align_draw_check.py b/tests/startup_gfx2hlsl_mul24_align_draw_check.py new file mode 100644 index 000000000..0e17a3189 --- /dev/null +++ b/tests/startup_gfx2hlsl_mul24_align_draw_check.py @@ -0,0 +1,104 @@ +"""D3D12 draw of the translated 24-bit multiplies, v_xnor_b32 and the funnel shifts (see +startup_gfx2hlsl_mul24_align_check.py for the CPU evaluation of the same lowerings). + + binary <llvm-mc> reassemble the fixture bodies below and compare them with llvm-mc + draw <dxc> <offscreen_check> <warp|hardware> [fxc] + compile the translated pair with FXC ps_5_1 when given and with DXC ps_6_0, + draw one pixel per four input sets and compare the four result words with the + reference built from unbounded integers + +The pixel fixture and the vertex stage are the ones of startup_gfx2hlsl_bit_alu_check.py: three flat parameters +(v0..v3, v4..v7, v8..v11) hold one operation's sources for four lanes, the operation (VOP3 spelling) writes v12..v15 +and the pixel stage exports them to mrt0. The vertex stage places the inputs in the parameters, so the pixel stage +cannot fold them. +""" +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +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, compile_hlsl, draw, root_blob # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import POST_WORDS, PRE_WORDS, vs_source, vs_words, words_text # noqa: E402 +from startup_gfx2hlsl_mul24_align_check import MASK, REFERENCE # noqa: E402 + +BODY_WORDS = { + 'v_mul_i32_i24': '0c0009d5000902000d0009d5010b02000e0009d5020d02000f0009d5030f0200', + 'v_mad_i32_i24': '0c0042d5000922040d0042d5010b26040e0042d5020d2a040f0042d5030f2e04', + 'v_mul_hi_i32_i24': '0c000ad5000902000d000ad5010b02000e000ad5020d02000f000ad5030f0200', + 'v_xnor_b32': '0c001ed5000902000d001ed5010b02000e001ed5020d02000f001ed5030f0200', + 'v_alignbit_b32': '0c004ed5000922040d004ed5010b26040e004ed5020d2a040f004ed5030f2e04', + 'v_alignbyte_b32': '0c004fd5000922040d004fd5010b26040e004fd5020d2a040f004fd5030f2e04', +} +MUL = [(0x7fffff, 0x7fffff, 0), (0x800000, 0x800000, 1), (0xffffff, 0xffffff, MASK), (0x800001, 0x7fffff, 5), + (0x123456, 0xfedcba, 0x80000000), (0xab123456, 0x5cfedcba, 7), (0x1000, 0xfff, 0), (0xfff, 0x1000, 2), + (0x555555, 0xaaaaaa, 0x12345678), (1, 0xffffff, 0), (0xfffffe, 0x800000, 3), (0x7fffff, 0x800000, 0)] +BITS = [(0x12345678, 0x9abcdef0, 0), (0x12345678, 0x9abcdef0, 4), (0xdeadbeef, 0x01234567, 31), (MASK, 0, 17), + (0x80000000, 1, 1), (0x80000001, MASK, 0x80000003), (0xff000001, 0x00ffffff, 8), (0, MASK, 24), + (0xdeadbeef, 0x89abcdef, 3), (1, 0x80000000, 32), (0x7fffffff, 0x80000000, 2), (MASK, MASK, 19)] +DRAW = {op: BITS if op[2:].startswith(('xnor', 'align')) else MUL for op in REFERENCE} + + +def source_count(op): + return REFERENCE[op][0] + + +def body_source(op): + return ''.join('%s_e64 v%d, %s\n' % (op, 12 + lane, ', '.join('v%d' % (4 * s + lane) for s in range(source_count(op)))) + for lane in range(4)) + + +def ps_words(op): + return PRE_WORDS + bytes.fromhex(BODY_WORDS[op]) + POST_WORDS + + +def check_binary(llvm_mc): + for op in REFERENCE: + built = assemble(llvm_mc, body_source(op)) + if built != bytes.fromhex(BODY_WORDS[op]): + raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), BODY_WORDS[op])) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter, fxc=None): + compilers = ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + failures = [] + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + for op, sets in DRAW.items(): + reference = REFERENCE[op][1] + text = G.Pipeline(vs_words([(0, 0, 0)] * 4), ps_words(op), root_blob()).hlsl_ps() + ps = compile_hlsl(compiler, kind, text, 'ps_%s_%s' % (op, kind), ps_profile, directory) + for index in range(0, len(sets), 4): + chunk = sets[index:index + 4] + vs_text = G.Pipeline(vs_words(chunk), ps_words(op), root_blob()).hlsl_vs() + vs = compile_hlsl(compiler, kind, vs_text, 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + expected = words_text(reference(*x) for x in chunk) + run = draw(renderer, adapter, vs, ps, expected) + if run.returncode: + # Keep going so one compiler's failure does not hide the other compiler's result. + failures.append('%s %s inputs %s\n%s\n%s' % (kind, op, chunk, run.stdout, run.stderr)) + break + print('%s %s %s: %s' % (kind, op, [tuple('%x' % v for v in x[:source_count(op)]) for x in chunk], + expected), flush=True) + if failures: + raise AssertionError('\n'.join(failures)) + + +def main(): + if len(sys.argv) < 2: + raise SystemExit(__doc__) + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3e2051257..a74611537 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6528,6 +6528,43 @@ def declarations(self): 'v_cvt_pk_i16_i32': (2, '(asuint(clamp(asint({0}), -32768, 32767)) & 0xffffu) | ' '(asuint(clamp(asint({1}), -32768, 32767)) << 16u)'), } + + +def _mul24_hi_i32(): + """High 32 bits of the 48-bit product of two signed 24-bit fields, in 32-bit integer arithmetic. + + With a = ah * 2^12 + al (al in 0..4095, ah the sign-extended top 12 bits) the product is + hh * 2^24 + mid * 2^12 + lo, so p >> 12 = hh * 2^12 + t with t = mid + (lo >> 12), and + p >> 32 = (hh + (t >> 12)) >> 8 exactly (floor division nests), which stays inside 32 bits. + """ + def top(n): + return '(asint({%d} << 8) >> 20)' % n + + def low(n): + return 'asint({%d} & 0xfffu)' % n + hh = '(%s * %s)' % (top(0), top(1)) + mid = '(%s * %s + %s * %s)' % (top(0), low(1), low(0), top(1)) + t = '(%s + ((%s * %s) >> 12))' % (mid, low(0), low(1)) + return 'asuint(((%s + (%s >> 12)) >> 8))' % (hh, t) + + +VEC_U.update({ + # AMD RDNA 2 ISA reference: the 24-bit multiplies read the low 24 bits of each source, the signed forms as a + # two's complement field. The mul and mad forms keep the low 32 bits of the product; the hi forms keep bits 63..32 + # of the 48-bit product. The 24-bit field is sign-extended with a left shift of 8 and an arithmetic right shift. + # v_mul_hi_u32_u24 is deliberately not lowered. Its result is at most 0xffff, so as a float output word it is + # always a binary32 denormal, and FXC 10.0.26100 at ps_5_1 (the startup path) folds a float output whose + # provable range lies below 0x00800000 to a constant zero (any form tried, even a plain shift without a + # product). The same words through a uint4 output survive, and DXC keeps them. v_mul_hi_i32_i24 can reach + # the whole 32-bit range, so FXC keeps it. A refusal is visible; zeros are not. + 'v_mul_hi_i32_i24': (2, _mul24_hi_i32()), + 'v_xnor_b32': (2, '~({0} ^ {1})'), + # v_alignbit_b32 takes bits [S2[4:0] + 31 : S2[4:0]] of the 64-bit value {S0, S1}; a zero shift returns S1 and + # the guard avoids a shift by 32. v_alignbyte_b32 does the same with S2[1:0] * 8 bits. + 'v_alignbit_b32': (3, '(({2} & 31u) == 0u ? {1} : (({1} >> ({2} & 31u)) | ({0} << (32u - ({2} & 31u)))))'), + 'v_alignbyte_b32': (3, '(({2} & 3u) == 0u ? {1} : (({1} >> (({2} & 3u) * 8u)) | ({0} << (32u - ({2} & 3u) * 8u))))'), +}) + VOP3_ONLY_VEC_U = frozenset(('v_cvt_pk_u16_u32', 'v_cvt_pk_i16_i32')) # scalar ops: (expression over uint sources, SCC rule with $ for the result or None) # Scalar ops that write SCC on the hardware (carry, overflow, or which source was selected) but have From 5366e34d50f401900788e606a5af593385251e32 Mon Sep 17 00:00:00 2001 From: Cursor Agent <cursoragent@cursor.com> Date: Wed, 25 Nov 2026 23:23:15 +0000 Subject: [PATCH 232/232] tests: add source-built mesh57 loop refusal fixture (#2413 T6) Prove tip translate_mesh57 refuses a back-edge outside the accepted group-memory exchanges by the named loop reason, with a mutant that drops the back-edge and an exact-string oracle. Co-authored-by: SimSalabimse <SimSalabimse@users.noreply.github.com> --- .github/workflows/windows.yml | 2 + AGENTS.md | 1 + CMakeLists.txt | 3 + docs/experiments.md | 10 ++ tests/startup_mesh57_loop_refusal.s | 74 ++++++++++++ tests/startup_mesh57_loop_refusal_check.py | 128 +++++++++++++++++++++ 6 files changed, 218 insertions(+) create mode 100644 tests/startup_mesh57_loop_refusal.s create mode 100644 tests/startup_mesh57_loop_refusal_check.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 71eb71905..e92b40e69 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -86,6 +86,7 @@ jobs: (["tests/startup_gfx2hlsl_scalar_m0_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_waitcnt_depctr_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_mesh57_skeleton_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_mesh57_loop_refusal_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_u8_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_cvt_pk_int16_check.py", "binary", "llvm-mc-15"], {}), @@ -267,6 +268,7 @@ jobs: tests/startup_gfx2hlsl_scalar_m0_check.py \ tests/startup_gfx2hlsl_waitcnt_depctr_check.py \ tests/startup_mesh57_skeleton_check.py \ + tests/startup_mesh57_loop_refusal_check.py \ tests/startup_gfx2hlsl_scalar_shift64_bfe_check.py \ tests/startup_gfx2hlsl_readfirstlane_uniform_check.py \ tests/startup_gfx2hlsl_loop_constants_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 89516ec2a..cc50184e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -191,6 +191,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_m0_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_waitcnt_depctr_check.py ./out/pe-env/bin/python -B tests/startup_mesh57_skeleton_check.py +./out/pe-env/bin/python -B tests/startup_mesh57_loop_refusal_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_readfirstlane_uniform_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_loop_constants_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_join_symbols_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 24284bdd8..566fa905a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3281,6 +3281,9 @@ if(EXISTS "${INTAKE_PYTHON}") # Slot 57 mesh requests (#2413): the one accepted group-memory shape translates; each mutation is refused. add_test(NAME startup_mesh57_skeleton COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_skeleton_check.py") + # Slot 57 mesh loop refusal outside the accepted exchanges (#2413 T6); mutant drops the back-edge. + add_test(NAME startup_mesh57_loop_refusal COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh57_loop_refusal_check.py") # Scalar SOPK accumulate: s_addk_i32 signed-overflow SCC and s_mulk_i32 against an integer reference. add_test(NAME startup_gfx2hlsl_sopk_accum COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_sopk_accum_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index a7f93e88b..8d1ae76c3 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9508,6 +9508,16 @@ and unproven wave masks remain unsupported. Use Append `draw <dxc> <offscreen_check> <warp|hardware>` for CPU-reference readback of the SCC paths and lane-masked if/else. +The `startup_mesh57_loop_refusal` check is a source-built program with the same +exchanges plus one deliberate back-edge after the count exchange +(`tests/startup_mesh57_loop_refusal.s`). Tip refuses it with +`slot 57 mesh: a loop outside the group-memory exchanges is not covered`. The +mutant replaces that back-edge with a second `s_nop` and must not stop on that +loop message. The oracle is an exact string match; a stub that only checks for +any `unsupported:` result would accept a wrong reason and is rejected by the +check. Host-only (no WARP/hardware draw). Run +`python -B tests/startup_mesh57_loop_refusal_check.py`, or the matching CTest. + A forward `s_cbranch_vccz` or `s_cbranch_vccnz` can also branch on the lane's VCC bit when EXEC is full and every incoming path last wrote VCC with a full-EXEC `v_cmp_*` from wave-uniform SGPRs or constants. A compare with a diff --git a/tests/startup_mesh57_loop_refusal.s b/tests/startup_mesh57_loop_refusal.s new file mode 100644 index 000000000..4303b7941 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal.s @@ -0,0 +1,74 @@ +// Source-built slot 57 mesh fixture for #2413 item T6: the accepted group-memory exchanges plus one +// deliberate back-edge outside them. Tip translate_mesh57 must refuse that loop by name. +// Entry and buffer layout match tests/startup_mesh57_skeleton.s. +s_inst_prefetch 0x3 +s_mov_b64 exec, 1 +s_mov_b64 s[4:5], exec +s_and_b32 s6, s3, 0xf000000 +s_cbranch_scc1 7 // to the reading waves +v_lshrrev_b32 v5, 7, v5 +v_mov_b32 v6, 0 +ds_write_b32 v6, v5 offset:8 +s_waitcnt_depctr 0xffe3 +s_barrier +s_branch 4 // past the reading waves +s_barrier +v_mov_b32 v6, 0 +ds_read_b32 v5, v6 offset:8 +s_mov_b64 exec, -1 +s_bfe_u32 s6, s3, 0x40018 +s_lshl_b32 s7, s6, 6 +v_mbcnt_lo_u32_b32 v0, -1, s7 +v_mbcnt_hi_u32_b32 v0, -1, v0 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s12, v5 +s_load_dwordx4 s[16:19], s[10:11], 0 +s_mov_b32 s13, s8 +s_mov_b32 s14, s9 +s_barrier +s_cmp_eq_i32 s6, 0 +s_cbranch_scc0 16 // to the reading waves +s_mov_b64 exec, s[4:5] +s_cbranch_execz 7 // never taken: the saved mask is 1 +v_mov_b32 v1, s13 +v_mov_b32 v2, 0 +v_mov_b32 v3, s14 +ds_write_b32 v2, v1 +ds_write_b32 v2, v3 offset:4 +s_mov_b64 exec, -1 +s_waitcnt_depctr 0xffe3 +s_barrier +s_lshl_b32 s4, s13, 12 +s_or_b32 m0, s4, s14 +s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) +s_branch 13 // past the reading waves +s_barrier +s_mov_b64 exec, s[4:5] +s_cbranch_execz 9 // never taken: the saved mask is 1 +v_mov_b32 v2, 0 +ds_read_b32 v1, v2 +ds_read_b32 v3, v2 offset:4 +s_waitcnt lgkmcnt(1) +v_readfirstlane_b32 s13, v1 +s_waitcnt lgkmcnt(0) +v_readfirstlane_b32 s14, v3 +s_mov_b64 exec, -1 +// Back-edge outside both modelled exchanges: s_branch -2 retargets the preceding s_nop. +s_nop 0 +s_branch -2 +v_cmpx_gt_i32 s14, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 4, v4 +buffer_load_dwordx4 v[16:19], v4, s[16:19], 0 offen +buffer_load_dwordx4 v[20:23], v4, s[16:19], 0 offen offset:192 +s_waitcnt vmcnt(0) +exp pos0 v16, v17, v18, v19 done +exp param0 v20, v21, v22, v23 +s_mov_b64 exec, -1 +v_cmpx_gt_i32 s13, v0 +v_and_b32 v4, 15, v0 +v_lshlrev_b32 v4, 2, v4 +buffer_load_dword v24, v4, s[16:19], 0 offen offset:384 +s_waitcnt vmcnt(0) +exp prim v24, off, off, off done +s_endpgm diff --git a/tests/startup_mesh57_loop_refusal_check.py b/tests/startup_mesh57_loop_refusal_check.py new file mode 100644 index 000000000..83f8da976 --- /dev/null +++ b/tests/startup_mesh57_loop_refusal_check.py @@ -0,0 +1,128 @@ +"""Slot 57 mesh loop refusal outside the accepted group-memory exchanges (#2413 T6). + +usage: startup_mesh57_loop_refusal_check.py + startup_mesh57_loop_refusal_check.py binary <llvm-mc> + +The source-built fixture (tests/startup_mesh57_loop_refusal.s) keeps the skeleton exchanges and inserts one +back-edge after the count exchange. Tip translate_mesh57 must refuse it with the named loop message. The mutant +replaces that back-edge with a second s_nop so the request no longer stops on the loop refusal (it translates +through the source-only path). A stubbed comparator that ignores the refusal string would accept a different +unsupported reason; this check uses an exact match so that stub fails. +""" +import os +from pathlib import Path +import re +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools')) +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +LOOP_REASON = 'slot 57 mesh: a loop outside the group-memory exchanges is not covered' +# Skeleton words through the count-exchange join (s_mov_b64 exec, -1), then s_nop; s_branch -2; then the body. +MESH = ( + 'bfa00003 befe0481 be84047e 8706ff03 0f000000 bf850007 2c0a0a87 7e0c0280 d8340008 00000506' + ' bfa3ffe3 bf8a0000 bf820004 bf8a0000 7e0c0280 d8d80008 05000006 befe04c1 9386ff03 00040018' + ' 8f078606 d7650000 00000ec1 d7660000 000200c1 bf8cc07f 7e180505 f4080405 fa000000 be8d0308' + ' be8e0309 bf8a0000 bf008006 bf840010 befe0404 bf880007 7e02020d 7e040280 7e06020e d8340000' + ' 00000102 d8340004 00000302 befe04c1 bfa3ffe3 bf8a0000 8f048c0d 887c0e04 bf900009 bf82000d' + ' bf8a0000 befe0404 bf880009 7e040280 d8d80000 01000002 d8d80004 03000002 bf8cc17f 7e1a0501' + ' bf8cc07f 7e1c0503 befe04c1 bf800000 bf82fffe 7d28000e 3608008f 34080884 e0381000 80041004' + ' e03810c0 80041404 bf8c3f70 f80008cf 13121110 f800020f 17161514 befe04c1 7d28000d 3608008f' + ' 34080882 e0301180 80041804 bf8c3f70 f8000941 00000018 bf810000').split() +# Mutant: the same program with the back-edge replaced by a second s_nop. +MUTANT = MESH[: MESH.index('bf82fffe')] + ['bf800000'] + MESH[MESH.index('bf82fffe') + 1:] +PIXEL = 'c8020002 c8060102 c80a0202 c80e0302 f800180f 03020100 bf810000'.split() + +FAILED = [] + + +def expect(what, got, want): + if got != want: + FAILED.append(what) + print('FAIL %s: got %r, want %r' % (what, got, want)) + + +def code(words): + return b''.join(struct.pack('<I', int(word, 16)) for word in words) + + +def root(): + rts0 = (struct.pack('<6I', 2, 2, 24, 0, 0, 0) + struct.pack('<3I', 1, 0, 48) + struct.pack('<3I', 0, 0, 60) + + struct.pack('<3I', 0, 0, 2) + struct.pack('<2I', 0, 0)) + return b'DXBC' + bytes(16) + struct.pack('<4I', 1, 44 + len(rts0), 1, 36) + b'RTS0' + struct.pack('<I', len(rts0)) + rts0 + + +def request(directory, mesh): + ms, ps, blob = code(mesh), code(PIXEL), root() + key = G.mesh57_key(ms, ps, blob) + for ext, data in (('.root', blob), ('.ps57', ps), ('.m57', ms)): + (Path(directory) / ('req_%016x%s' % (key, ext))).write_bytes(data) + return key, G.translate_request(str(directory), key) + + +def ignores_refusal_string(got, _want): + """Stubbed comparator: any unsupported result matches, regardless of the named reason.""" + return isinstance(got, str) and got.startswith('unsupported:') + + +def assemble(mc, text): + r = subprocess.run([mc, '-arch=amdgcn', '-mcpu=gfx1013', '-mattr=+wavefrontsize64,-wavefrontsize32', '-show-encoding'], + input=text, capture_output=True, text=True, check=True) + data = b''.join(bytes(int(b, 16) for b in m.split(',')) for m in re.findall(r'encoding: \[([^\]]*)\]', r.stdout)) + return ['%08x' % word for word in struct.unpack('<%dI' % (len(data) // 4), data)] + + +def binary(mc): + text = (HERE / 'startup_mesh57_loop_refusal.s').read_text() + expect('loop fixture words match llvm-mc', assemble(mc, text), MESH) + mutant_text = text.replace('s_nop 0\ns_branch -2\n', 's_nop 0\ns_nop 0\n') + expect('mutant words match llvm-mc', assemble(mc, mutant_text), MUTANT) + + +def main(): + os.environ['X2W_FXC'] = '' # sources and manifest only; the refusal is raised before DXC + want = 'unsupported: ' + LOOP_REASON + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MESH) + expect('loop fixture refuses by name', result, want) + expect('loop fixture publishes only the .fail', + sorted(p.name for p in Path(tmp).iterdir() if not p.name.startswith('req_')), + ['%016x.fail' % key]) + if result == want: + expect('loop .fail text', (Path(tmp) / ('%016x.fail' % key)).read_text(), LOOP_REASON + '\n') + + with tempfile.TemporaryDirectory() as tmp: + key, result = request(tmp, MUTANT) + expect('mutant does not report the loop refusal', result.startswith('unsupported: ' + LOOP_REASON), False) + expect('mutant translates through the source-only path', result, 'ok') + if result == 'ok': + names = sorted(p.name[16:] for p in Path(tmp).iterdir() if not p.name.startswith('req_')) + expect('mutant publishes mesh and pixel sources', names, + ['.ms57.hlsl', '.ms57.txt', '.ps57.hlsl']) + + # A stub that ignores the refusal string would accept a different unsupported reason for this oracle. + other = 'unsupported: slot 57 mesh: a branch enters or crosses a group-memory exchange' + expect('stubbed comparator would accept a wrong reason', ignores_refusal_string(other, want), True) + expect('exact oracle rejects that wrong reason', other == want, False) + expect('exact oracle matches the named loop refusal', want == 'unsupported: ' + LOOP_REASON, True) + + if FAILED: + print('startup_mesh57_loop_refusal: %d failed' % len(FAILED)) + return 1 + print('startup_mesh57_loop_refusal: ok') + return 0 + + +if __name__ == '__main__': + if len(sys.argv) == 3 and sys.argv[1] == 'binary': + binary(sys.argv[2]) + raise SystemExit(1 if FAILED else 0) + if len(sys.argv) != 1: + print(__doc__.strip(), file=sys.stderr) + raise SystemExit(2) + raise SystemExit(main())