From 9275a12375eb81a6758866450920a73d2d6ca713 Mon Sep 17 00:00:00 2001 From: Panam Date: Tue, 24 Nov 2026 23:48:18 +0100 Subject: [PATCH 1/2] 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. --- CMakeLists.txt | 4 + docs/experiments.md | 22 +++++ tests/startup_gfx2hlsl_fract_check.py | 113 ++++++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 8 +- 4 files changed, 146 insertions(+), 1 deletion(-) create mode 100644 tests/startup_gfx2hlsl_fract_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index b0b81b6544..65d29fbd6b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2406,6 +2406,10 @@ 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) 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 a80f055601..ec4855b076 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -12097,6 +12097,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/tests/startup_gfx2hlsl_fract_check.py b/tests/startup_gfx2hlsl_fract_check.py new file mode 100644 index 0000000000..7269fc6307 --- /dev/null +++ b/tests/startup_gfx2hlsl_fract_check.py @@ -0,0 +1,113 @@ +"""`v_fract_f32` lowers through the clamped helper `fract32` in tools/startup/gfx2hlsl.py (#1741). + +usage: startup_gfx2hlsl_fract_check.py + +Two NVIDIA reports fail `startup_gfx2hlsl_float_round_hardware` on the `v_fract_f32` input `0xb0800000` +(-2^-30): expected `0x3f7fffff`, actual `0x3f800000` (RTX 3070 Ti, driver 32.0.16.2101; Quadro M1000M +Maxwell, driver 32.0.15.7371). The same draw passes on WARP, on Intel HD Graphics 530 and on the RDNA 4 +card used here. The table used to emit a bare D3D `frac`, which has no upper cap and differs between +adapters, while `tools/pixel_aot.py` has always capped `x - floor(x)` at `0x3f7fffff` through `fract32`. + +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. +""" +import os +import re +import sys +from pathlib import Path + +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')) +sys.path.insert(0, here) +import gfx2hlsl as G # noqa: E402 +from startup_gfx2hlsl_bit_alu_check import Probe # 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 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'(?= 1.0f ? asfloat(0x3f7fffffu) : f' not in helper: + found.append('the clamp is not the comparison form pixel_aot writes') + if 'min(' in helper: + found.append('the clamp goes through min, which loses a NaN') + return found + + +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) + +# 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 two lowerings that caused the report, an uncapped +# frac and a cap written with min. 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('f >= 1.0f ? asfloat(0x3f7fffffu) : f', + '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)) + +if failures: + print('FAIL') + for text in failures: + print(' ' + text) + sys.exit(1) +print('PASS') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 168f16987f..cbd52fd31f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1857,7 +1857,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}))'), } @@ -2083,6 +2083,12 @@ 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. + 'float fract32(float value) {', + ' float f = frac(value);', + ' return f >= 1.0f ? asfloat(0x3f7fffffu) : f;', + '}', 'float med3(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }', # 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;' From 5eb8812708e16b82bc74ca2829507b29fc49e2f8 Mon Sep 17 00:00:00 2001 From: Panam Date: Wed, 25 Nov 2026 01:32:07 +0100 Subject: [PATCH 2/2] 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. --- CMakeLists.txt | 11 ++ src/startup_stubs/d3d12_draw.inl | 2 +- tests/startup_gfx2hlsl_fract_check.py | 98 +++++++++- tests/startup_gfx2hlsl_fract_draw_check.py | 205 +++++++++++++++++++++ tools/startup/gfx2hlsl.py | 7 +- 5 files changed, 312 insertions(+), 11 deletions(-) create mode 100644 tests/startup_gfx2hlsl_fract_draw_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 65d29fbd6b..e5a5155126 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2410,6 +2410,17 @@ if(EXISTS "${INTAKE_PYTHON}") 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() 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/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f12dd8038b..74db9e03e9 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -204,7 +204,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-7"; + constexpr char revision[] = "x2w-startup-shader-8"; 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. diff --git a/tests/startup_gfx2hlsl_fract_check.py b/tests/startup_gfx2hlsl_fract_check.py index 7269fc6307..c78de21ce7 100644 --- a/tests/startup_gfx2hlsl_fract_check.py +++ b/tests/startup_gfx2hlsl_fract_check.py @@ -8,21 +8,36 @@ card used here. The table used to emit a bare D3D `frac`, which has no upper cap and differs between adapters, while `tools/pixel_aot.py` has always capped `x - floor(x)` at `0x3f7fffff` through `fract32`. +The cap on a float comparison, `f >= 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. +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 = [] @@ -60,13 +75,22 @@ def problems(statement, helper): found.append('the instruction calls a bare frac(') if '0x3f7fffff' not in helper: found.append('the helper does not clamp at 0x3f7fffff') - if 'f >= 1.0f ? asfloat(0x3f7fffffu) : f' not in helper: - found.append('the clamp is not the comparison form pixel_aot writes') + if FLOAT_FORM in helper: + found.append('the helper clamps on the float comparison `%s`, which FXC folds to false and emits a bare ' + 'frc for: the cap is lost' % FLOAT_FORM) + elif BITS_FORM not in helper: + found.append('the clamp is not the bits equality `%s`' % BITS_FORM) if 'min(' in helper: found.append('the clamp goes through min, which loses a NaN') return found +def capped(word, test): + """The word the helper returns for one input word, under one comparison of the bits.""" + fire = {'==': word == ONE, '>': 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]) @@ -75,6 +99,8 @@ def problems(statement, helper): 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})'), @@ -94,16 +120,72 @@ def 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 two lowerings that caused the report, an uncapped -# frac and a cap written with min. The same problem list is used, so the controls cannot drift from it. +# 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('f >= 1.0f ? asfloat(0x3f7fffffu) : f', - 'min(frac(value), asfloat(0x3f7fffffu))')) +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-8, after the fix to the cap', + bool(seed and seed.group(1) == 'x2w-startup-shader-8'), 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-7'), key_from_seed('x2w-startup-shader-8') + check('the -7 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') diff --git a/tests/startup_gfx2hlsl_fract_draw_check.py b/tests/startup_gfx2hlsl_fract_draw_check.py new file mode 100644 index 0000000000..363a59df2f --- /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/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index cbd52fd31f..f5b75bae3f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2085,9 +2085,12 @@ def common(self): '}', # 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 f >= 1.0f ? asfloat(0x3f7fffffu) : f;', + ' 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)); }', # The ten binary32 classes v_cmp_class_f32 tests, from the raw encoding (#1795). @@ -2221,7 +2224,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-7')))) + key = fnv(root_blob, fnv(ps_code, fnv(vs_code, fnv(b'x2w-startup-shader-8')))) return fnv(layout, key) if layout else key