From 627d66e8d5c45b176e88ee53bb6037021b0d9fbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 21:03:00 +0300 Subject: [PATCH] startup: draw the gfx2hlsl reciprocal, root, exp2 and log2 operations The VEC_F table lowers v_rcp_f32, v_rcp_iflag_f32, v_sqrt_f32, v_rsq_f32, v_exp_f32 and v_log_f32 to 1.0 / x, sqrt, rsqrt, exp2 and log2, and no check ran any of them. tests/startup_gfx2hlsl_float_transcendental_check.py draws them with the shared per-lane runner (byte-identical copy of tests/startup_gfx2hlsl_lane_alu.py) on powers of two (and 0 and 9 for the square root), so every result is exact and the draw checks which function and which base each operation is lowered to, not its precision. Each operation has a mutated lowering whose first draw must read its own words. All 24 draws match on WARP and an RX 6600 through FXC ps_5_1 and DXC ps_6_0, and the 12 mutated draws read their mutated words. --- .github/workflows/windows.yml | 2 + CMakeLists.txt | 11 ++ docs/experiments.md | 14 ++ ...tup_gfx2hlsl_float_transcendental_check.py | 84 +++++++++ tests/startup_gfx2hlsl_lane_alu.py | 172 ++++++++++++++++++ 5 files changed, 283 insertions(+) create mode 100644 tests/startup_gfx2hlsl_float_transcendental_check.py create mode 100644 tests/startup_gfx2hlsl_lane_alu.py diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 7817ba0896..29463ba402 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -75,6 +75,7 @@ jobs: (["tests/startup_image_load_mip_check.py", "--llvm-mc", "llvm-mc-15"], {}), (["tests/startup_image_2d_array_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_flat_param_check.py", "binary", "llvm-mc-15"], {}), + (["tests/startup_gfx2hlsl_float_transcendental_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_gfx2hlsl_bit_alu_check.py", "binary", "llvm-mc-15"], {}), (["tests/startup_inline_sampler_check.py", "binary", "llvm-mc-15"], {}), (["tests/compute_entry_layout_check.py", "binary", "llvm-mc-15"], {}), @@ -178,6 +179,7 @@ jobs: tests/startup_triage_run_check.py \ tests/startup_run_ps1_check.py \ tests/startup_flat_param_check.py \ + tests/startup_gfx2hlsl_float_transcendental_check.py \ tests/startup_gfx2hlsl_bit_alu_check.py \ tests/startup_inline_sampler_check.py \ tests/compute_entry_layout_check.py \ diff --git a/CMakeLists.txt b/CMakeLists.txt index f53e8843ea..d9e4ec6cf2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1741,6 +1741,17 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter} $<$:${STARTUP_FXC}>) set_tests_properties(startup_inline_sampler_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl binary32 reciprocal, roots, exp2 and log2 (VEC_F) on exact inputs: translation controls, then a + # draw of the translated pairs with reference words and one mutated lowering per operation. + add_test(NAME startup_gfx2hlsl_float_transcendental_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_transcendental_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_float_transcendental_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_float_transcendental_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter} $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_float_transcendental_${adapter} PROPERTIES TIMEOUT 300 + SKIP_RETURN_CODE 77) + endforeach() add_test(NAME startup_xg_bc7_layout COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_xg_bc7_layout_check.py" "$") set_tests_properties(startup_xg_bc7_layout PROPERTIES TIMEOUT 30 diff --git a/docs/experiments.md b/docs/experiments.md index 1114f5beb0..c9a5e45277 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10855,6 +10855,20 @@ The [MASM fixture](../tests/cpu/vex_parity.asm) and [differential check](../test ctest --preset release --no-tests=error -R '^cpu_aot_vex_parity$' -V ``` +## Startup translator: reciprocal, roots, exp2 and log2 + +The `VEC_F` table of `tools/startup/gfx2hlsl.py` lowers six operations to HLSL with no check that ran them before: `v_rcp_f32` and `v_rcp_iflag_f32` to `1.0 / x`, `v_sqrt_f32` to `sqrt`, `v_rsq_f32` to `rsqrt`, `v_exp_f32` to `exp2` and `v_log_f32` to `log2`. `tests/startup_gfx2hlsl_float_transcendental_check.py` draws them with the shared runner `tests/startup_gfx2hlsl_lane_alu.py`. Each draw applies one operation per lane on flat inputs, alternates the `_e32` and `_e64` spellings, and compares the four result words exactly. + +Every input is a power of two, or 0 and 9 for the square root, so every result is exact. The check therefore tests which function each operation is lowered to and the base 2 of `v_exp_f32` and `v_log_f32`. It does not test how many ulps an adapter's approximation may be off. + +Each operation has a wrong lowering whose first draw must read its own mutated words: +- `2.0 / x` for the reciprocals; +- sqrt and rsqrt exchanged; +- the exponent off by one; +- the logarithm plus one. + +On WARP 10.0.26100.9818 and on an AMD Radeon RX 6600 (driver 32.0.21045.29003), all 24 draws matched through FXC `ps_5_1` and DXC `ps_6_0`, and all 12 mutated draws read their mutated words. `v_sin_f32` and `v_cos_f32` are not covered: their results at the few exact points depend on the approximation. Tests: `startup_gfx2hlsl_float_transcendental_controls`, `startup_gfx2hlsl_float_transcendental_warp` and `startup_gfx2hlsl_float_transcendental_hardware`. + ## Startup root constant buffer views Command-list slot 42 records the address of a root parameter declared as a CBV, so a translated shader reading through its root pointer sees it. The fixture (`tests/startup_root_cbv.cpp`, driven by `tests/startup_root_cbv_check.py`) is synthetic only: it uses generated command streams and no title data, and the slot number is derived from the desktop order and the console shift, not seen in a title log. It checks a bound call, an unbound call, a null overwrite that clears the slot, a wrong-type call that is ignored with `root CBV N ignored`, a redundant root bind that preserves the address, and a signature switch that clears it. Details are in [startup-runtime.md](startup-runtime.md#root-constant-buffer-views). diff --git a/tests/startup_gfx2hlsl_float_transcendental_check.py b/tests/startup_gfx2hlsl_float_transcendental_check.py new file mode 100644 index 0000000000..adc1b5bc26 --- /dev/null +++ b/tests/startup_gfx2hlsl_float_transcendental_check.py @@ -0,0 +1,84 @@ +"""Binary32 reciprocal, root, exponential and logarithm of tools/startup/gfx2hlsl.py (its VEC_F table). + + (no arguments) translation controls, pure Python + binary reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +Covers v_rcp_f32, v_rcp_iflag_f32, v_sqrt_f32, v_rsq_f32, v_exp_f32 and v_log_f32, which no check ran before. They +lower to 1.0 / x, sqrt, rsqrt, exp2 and log2. The fixture and runner are startup_gfx2hlsl_lane_alu.py: one operation +per lane, alternating the e32 and e64 spellings, on flat parameters the compilers cannot fold. The references follow +the AMD RDNA 2 ISA reference (v_exp_f32 and v_log_f32 are base 2). Every input is a power of two, or 0 and 9 for the +square root, so every result is exact and the comparison does not depend on how many ulps an adapter's +approximation may be off: it checks which function each operation is lowered to, not its precision. +""" +import math +import struct +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from startup_gfx2hlsl_lane_alu import main, words # noqa: E402 + + +def f(value): + return struct.unpack(' reassemble the pixel bodies and compare them with the recorded words + draw [fxc] + draw one pixel per four input sets and compare the four result words + +The pixel fixture is the one of startup_gfx2hlsl_bit_alu_check.py: it reads three flat parameters (v0..v3, v4..v7, +v8..v11), applies one operation per lane with sources v(4s + lane) and exports v12..v15 to mrt0, whose words the +renderer compares exactly. The vertex stage places the inputs in the parameters, so the compilers cannot fold them. + +A family is a dict with: + ops: mnemonic -> (source count, reference over ints, VOP2 or VOP1 so the e32 and e64 spellings both exist) + draw: mnemonic -> input sets (src0, src1, src2), a multiple of four + mutations: mnemonic -> (pattern in the translated pixel text, replacement, reference of the mutated lowering) + body: mnemonic -> the recorded pixel body words (llvm-mc -mcpu=gfx1013) + refused: assembly lines that must stay refused + accepted: assembly lines that must translate (one instruction, no pipeline) +Every reference is written from the ISA description with plain integer arithmetic, not from the lowering. +""" +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 (POST_SOURCE, POST_WORDS, PRE_SOURCE, PRE_WORDS, Probe, # noqa: E402 + vs_source, vs_words, words_text) + +MASK = 0xffffffff + + +def body_source(family, op): + arity, _, alternate = family['ops'][op] + lines = [] + for lane in range(4): + sources = ', '.join('v%d' % (4 * s + lane) for s in range(arity)) + lines.append('%s%s v%d, %s\n' % (op, '_e64' if alternate and lane % 2 else '', 12 + lane, sources)) + return ''.join(lines) + + +def translate(family, op, mutate=False): + pipe = G.Pipeline(vs_words([(0, 0, 0)] * 4), PRE_WORDS + family['body'][op] + POST_WORDS, root_blob()) + text = pipe.hlsl_ps() + if mutate: + pattern, replacement, _ = family['mutations'][op] + mutated, count = re.subn(pattern, replacement, text) + assert count == 4 and mutated != text, (op, count) + text = mutated + return pipe, text + + +def refused(assembly): + try: + Probe().one(assembly.split(' ', 1)[0], assembly) + except G.Unsupported: + return True + return False + + +def check(label, ok): + print('%s: %s' % (label, 'ok' if ok else 'MISMATCH')) + if not ok: + raise AssertionError(label) + + +def expected(family, op, sets, mutated=False): + arity, reference, _ = family['ops'][op] + function = family['mutations'][op][2] if mutated else reference + return [function(*x[:arity]) & MASK for x in sets] + + +def controls(family): + for op, (arity, _, _) in family['ops'].items(): + _, text = translate(family, op) + lanes = re.findall(r'^\s*v(1[2-5]) = (.*);$', text, re.M) + check('%s: four lanes translated' % op, [lane for lane, _ in lanes] == ['12', '13', '14', '15']) + translate(family, op, True) + sets = family['draw'][op] + check('%s: %d draw sets' % (op, len(sets)), sets and len(sets) % 4 == 0) + # Each mutation reads a wrong word in the first draw, so the mutated draw cannot pass by accident. + first = sets[:4] + check('%s: mutation changes draw set 0' % op, + expected(family, op, first, True) != expected(family, op, first)) + check('accepted forms translate', not any(refused(a) for a in family['accepted'])) + check('refused forms stay refused', all(refused(a) for a in family['refused'])) + + +def check_binary(family, llvm_mc): + for op in family['ops']: + built = assemble(llvm_mc, body_source(family, op)) + if built != family['body'][op]: + raise AssertionError('%s: assembled %s, recorded %s' % (op, built.hex(), family['body'][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, sets in family['draw'].items(): + for i in range(0, len(sets), 4): + if assemble(llvm_mc, vs_source(sets[i:i + 4])) != vs_words(sets[i:i + 4]): + raise AssertionError('vertex fixture for %s %s differs from llvm-mc' % (op, sets[i:i + 4])) + print('fixture words match llvm-mc') + + +def check_draw(family, dxc, renderer, adapter, fxc=None): + controls(family) + 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: + for op, sets in family['draw'].items(): + arity = family['ops'][op][0] + good = compile_hlsl(compiler, kind, translate(family, op)[1], 'ps_%s_%s' % (op, kind), ps_profile, + directory) + for index in range(0, len(sets), 4): + chunk = sets[index:index + 4] + vs = compile_hlsl(compiler, kind, G.Pipeline(vs_words(chunk), PRE_WORDS + family['body'][op] + + POST_WORDS, root_blob()).hlsl_vs(), + 'vs_%s_%d_%s' % (op, index, kind), vs_profile, directory) + want = words_text(expected(family, op, chunk)) + run = draw(renderer, adapter, vs, good, want) + if run.returncode: + raise AssertionError('%s %s inputs %s\n%s\n%s' % (kind, op, chunk, run.stdout, run.stderr)) + draws += 1 + print('%s %s %s: %s' % (kind, op, [tuple('%x' % v for v in x[:arity]) for x in chunk], want), + flush=True) + if index: + continue + # The same draw with the mutated lowering must read the mutated words, not the reference. + wrong = words_text(expected(family, op, chunk, True)) + bad = compile_hlsl(compiler, kind, translate(family, op, True)[1], 'mutated_%s_%s' % (op, kind), + ps_profile, directory) + run = draw(renderer, adapter, vs, bad, want) + 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)) + mutations += 1 + print('%s %s mutation: fails as expected, reads %s' % (kind, op, wrong), flush=True) + print('%s: %d draws matched, %d mutated draws read their mutated words' % (adapter, draws, mutations)) + + +def main(family, doc): + if len(sys.argv) == 1: + controls(family) + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(family, *args) + elif mode == 'draw': + check_draw(family, *args) + else: + raise SystemExit(doc) + + +def words(hex_text): + return bytes.fromhex(hex_text) + + +def signed(v): + return v - (1 << 32) if v >> 31 else v + + +def body_words(family, llvm_mc): + """Development aid: print the body words llvm-mc gives for every operation of a family.""" + for op in family['ops']: + print(" '%s': words('%s')," % (op, assemble(llvm_mc, body_source(family, op)).hex()))