From 933b8e6926149a7127d46227c6e22173320a83ed Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Mon, 30 Nov 2026 05:57:28 +0000 Subject: [PATCH] shader: lower binary16 VOP1 reciprocal square root and exponent --- CMakeLists.txt | 6 + docs/experiments.md | 4 + tests/form_coverage_check.py | 38 +++ tests/pixel_aot_check.py | 446 +++++++++++++++++++++++++++++- tests/rdna2_tools_check.py | 11 +- tools/pixel_aot.py | 172 +++++++++++- tools/scan_unsupported_shaders.py | 2 +- 7 files changed, 653 insertions(+), 26 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 57c821c564..03b30a9d31 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11372,6 +11372,10 @@ if(EXISTS "${INTAKE_PYTHON}") "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-rcp-sqrt "${DXC_EXECUTABLE}" "$" ${adapter}) set_tests_properties(pixel_aot_f16_rcp_sqrt_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) + add_test(NAME pixel_aot_f16_rsq_exp_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-rsq-exp "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(pixel_aot_f16_rsq_exp_${adapter} PROPERTIES TIMEOUT 60 SKIP_RETURN_CODE 77) add_test(NAME pixel_aot_f16_fmac_ldexp_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/pixel_aot_check.py" draw-f16-fmac-ldexp "${DXC_EXECUTABLE}" "$" ${adapter}) @@ -11660,6 +11664,8 @@ if(EXISTS "${INTAKE_PYTHON}") ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_round_${adapter}.txt") set_tests_properties(pixel_aot_f16_rcp_sqrt_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rcp_sqrt_${adapter}.txt") + set_tests_properties(pixel_aot_f16_rsq_exp_${adapter} PROPERTIES + ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_rsq_exp_${adapter}.txt") set_tests_properties(pixel_aot_f16_fmac_ldexp_${adapter} PROPERTIES ENVIRONMENT "FORM_COVERAGE_RECORD=${CMAKE_BINARY_DIR}/form_coverage/pixel_aot_f16_fmac_ldexp_${adapter}.txt") set_tests_properties(pixel_aot_f16_cvt_int16_${adapter} PROPERTIES diff --git a/docs/experiments.md b/docs/experiments.md index 799b08847d..bd3fa70a5b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9003,6 +9003,10 @@ Plain binary16 `VOP1` reciprocal and square root (issue #839) `v_rcp_f16` and `v The controls (`check_f16_rcp_sqrt_controls`, no GPU) cover the bare, `_e32` and `_e64` spellings, every source kind, the finite, register, modifier, mode, scheduling, sample and reader refusals, and chains of both operations. The Python reference (`f16_rcp_sqrt_reference`) applies the same two rounds from the semantics without `pixel_aot`, handles the binary16 overflow threshold and compares with the translator's `f16_rcp_sqrt_result` on every finite encoding. The draw (`tests/pixel_aot_check.py draw-f16-rcp-sqrt`, tests `pixel_aot_f16_rcp_sqrt_hardware` and `pixel_aot_f16_rcp_sqrt_warp`, 60 s limit, capability skip 77) runs five baked programs over 20 source values through both ops in a rotation of e32, e64, SGPR and literal forms and packs two results per word with SDWA `WORD_0` and `WORD_1`; four reader programs and two chains read both result tags. Bits 31:16 of every source word hold junk. The lossless `R32G32B32A32_UINT` readback is compared with the Python reference. Two deviations must each mismatch, one batch per mutation with the statuses printed (reciprocal and square root swapped, and a source read from bits 31:16), and a source with no finite proof is refused at translation. Both tests passed on WARP and on the RX 9060 XT. In `gfx1013.tsv` and `rdna2.tsv` the two operations add their VOP1 and VOP3 rows, so the fixture records four newly covered forms (rcp and sqrt, each e32 and e64); the two operations themselves are the +2. `tests/form_coverage_check.py check_f16_rcp_sqrt_forms` pins that the DPP, SDWA and rsq neighbours stay uncovered. `tools/scan_unsupported_shaders.py` accepts the syntactic source forms and `tests/rdna2_tools_check.py test_binary16_e64_scanner_translator_agreement` checks that its acceptance agrees with `pixel_aot.lower`. Not measured: the high half of the destination, the console's denormal and rounding state beyond the declared nearest-even entry profile, NaN payloads and special-function results beyond the modelled infinities, runtime sources, the DPP and SDWA spellings, the hardware behaviour of integer inline constants on binary16 operands, and whether any title executes these paths. +Plain binary16 `VOP1` reciprocal square root and exponent (issue #839), `v_rsq_f16` and `v_exp_f16`, extend the unary entry above: the unsuffixed, `_e32` and `_e64` spellings widen the low half with `widen16`, evaluate the direct compute path's `rsqrt` or `exp2` in binary32, narrow with `narrow16`, and then select RDNA 2's special results from the source half. `v_rsq_f16` maps any source above `+infinity` (every negative finite encoding) to the canonical quiet NaN `0x7e00`, `+infinity` to zero and a zero magnitude to `source | 0x7c00`, so `-0` gives `-infinity`; `v_exp_f16` applies the 70 midpoint corrections of `exp_f16_midpoints` from `src/gfx1013_direct_compute.inl`, maps `2^-25` (`0xce40`) to zero and a magnitude above `+infinity` to `0x7e00`. The emitted helpers are `f16_rsq_result` and `f16_exp2_result`, and `tools/pixel_aot.py` carries the same table as `EXP_F16_MIDPOINTS`. The translator tracks each result with `f16_rsq_exp_result`: a positive finite reciprocal square root is rounded exactly to binary16 with a 90-digit reference, a negative one is the canonical NaN above, and `exp` rounds the exact `2^S0` after the table corrections. Every finite source therefore has a modelled result and the function does not return None; its signature keeps the None contract for a future unmodelled NaN. The source proof, entry profile, destination range and sample scheduling are those of the reciprocal and square root entry; the same modifiers, `clamp`, `mul:`, `div:`, `op_sel`, DPP, SDWA and extra operands stay refused, and `v_log_f16`, `v_sin_f16` and `v_cos_f16` remain unlowered. + +The controls (`check_f16_rsq_exp_controls`, no GPU) cover every spelling, operand kind, refusal, mode, scheduling and reader, compare the Python reference with `f16_rsq_exp_result` on all 65,536 finite encodings, and pin `pixel_aot.EXP_F16_MIDPOINTS` to the C++ `exp_f16_midpoints` array through `tests/f16_exp_midpoints.py check_cpp_table`. The draw (`tests/pixel_aot_check.py draw-f16-rsq-exp`, tests `pixel_aot_f16_rsq_exp_hardware` and `pixel_aot_f16_rsq_exp_warp`, 60 s limit, capability skip 77) runs six baked programs over 24 sources in a rotation of e32, e64, SGPR and literal forms, packs `rsq | exp << 16` with SDWA `WORD_0` and `WORD_1`, and adds four reader programs and two chains; the values cover exact roots and powers, inexact results, both signed zeros, subnormals, the largest finite half, `2^-25`, two midpoint-table rows, an overflow and the canonical negative-root NaN, and the chosen positive roots avoid the 8 f32 ULP window where the D3D `rsqrt` error allows either binary16 encoding. The lossless `R32G32B32A32_UINT` readback is compared with `f16_rsq_exp_reference`, an exact grid search and 90-digit `2^S0` without `pixel_aot`. Two deviations must each mismatch, one batch per mutation with the statuses printed (the two mnemonics swapped at translation, and a source read from bits 31:16), and a source with no finite proof is refused at translation. `tests/form_coverage_check.py check_f16_rsq_exp_forms` pins the four newly covered forms (rsq and exp, each e32 and e64) and leaves the DPP, SDWA, log, sin and cos neighbours uncovered; the four forms take the measured totals from 1546/1968 and 1537/1863 to 1550/1968 and 1541/1863. Both tests passed on WARP and on the RX 9060 XT (driver 32.0.32029.2010), Windows 11 build 10.0.26300.10075. Not measured: the high half of the destination, the D3D `rsqrt` and `exp2` error windows beyond the modelled midpoint corrections and the exact reference, runtime sources, NaN and infinity constants (refused before lowering), the DPP and SDWA spellings, the console's special-function behaviour, the remaining log, sin and cos forms, and whether any title executes these paths. + Plain binary16 fused multiply-accumulate and power-of-two scaling (issue #839), `v_fmac_f16` and `v_ldexp_f16` in the unsuffixed and `_e32` spellings, under the rules of the `VOP2` arithmetic above. The AMD RDNA 2 ISA reference gives `D.f16 = S0.f16 * S1.f16 + D.f16` for the first and `D.f16 = S0.f16 * 2.0 ^ S1.i16` for the second (LLVM 15.0.7 `VOP2Instructions.td` types the exponent as `i16`); the multiply-accumulate is fused, so the exact product and sum are rounded once to nearest even. The fused form reads the destination as a third operand, so the accumulator must already hold a statically proven finite half (a copy of a constant, or the result of an earlier accepted binary16 op); it is rounded with the existing integer routine `fma16_rne`, whose result must not overflow. `v_ldexp_f16` needs a statically known exponent, read as the signed low 16 bits of a VGPR (bits 31:16 are never read) and limited to -64..64: the binary32 product of the exactly widened half and a power of two is exact, because both the multiplier and the product are binary32 normals, and `narrow16` rounds it once, so a result below the smallest subnormal becomes a signed zero and a tie goes to the even encoding. The translator evaluates both results with exact rational arithmetic (`f16_pk_fmac_lane_result` for the fused form and `f16_ldexp_result`), so a chain stays proven and an overflow is refused with `binary16 result overflows: v_fmac_f16` or `v_ldexp_f16`; the exponent refusals are `binary16 ldexp exponent lacks a proof: ` and `binary16 ldexp exponent out of range: `. The source proof, the entry profile, the `("half16", alu)` result tag and the audited readers are those of the `VOP2` arithmetic. src1 must be a VGPR in the e32 encoding; the `_e64`, DPP and SDWA spellings, `clamp`, `mul:`, `op_sel` and source modifiers are refused. The controls (`check_f16_fmac_ldexp_controls`, no GPU) pin worked rows of an independent reference, which finds the nearest binary16 value on the sorted grid of exact values and shares no formula with the translator, and compare it with the translator's copies on a deterministic sample; they also cover every operand kind, the proof, overflow, exponent and mode refusals, the scheduling and mask checks and the readers. The draw (`tests/pixel_aot_check.py draw-f16-fmac-ldexp`, tests `pixel_aot_f16_fmac_ldexp_hardware` and `pixel_aot_f16_fmac_ldexp_warp`, 120 s limit, capability skip 77) bakes every operand into the program: six programs run 24 triples through `v_fmac_f16` (a cancellation, rows where rounding the product first gives another result, signed-zero sums, ties into the subnormals, the carry into `0x0400`, a product that only sets a sticky bit, 65504 and the values just below the overflow threshold) and six run 24 scalings (the binade edges, ties to even into the subnormals, subnormal to normal, signed zeros and exponents from -64 to 64), with src0 in a VGPR, an SGPR or a literal in rotation, and two chains feed a result into the next op as source, accumulator or scaled operand. Bits 31:16 of every source word hold junk, and the exponent words carry junk in the high half. The readback is the lossless `R32G32B32A32_UINT` target against the independent reference; the programs with a subnormal source or result also run under a binary32 `-denorm ftz` build and must still pass. Seven deviations must each mismatch, one batch per mutation with the statuses printed (the product rounded before the sum, the accumulator ignored, the multiplicand and the accumulator swapped, a source read from bits 31:16 in the fused form and again in the scaling form, the exponent negated, and subnormal results flushed to a signed zero), and a Python pre-check requires that each changes an expected word of some program and leaves unrelated rows alone. Not measured: the high half of the destination, the console's denormal state, NaN and infinity operands, runtime operands and exponents, exponents beyond 64 in magnitude (the ISA reference does not state a clamp), and the hardware reading of integer inline constants on binary16 operands. The shaders were not run on a GPU for this entry; the arithmetic of both lowerings was checked against the reference with a line-by-line Python transliteration only. `tools/scan_unsupported_shaders.py` reports the `_e64` spelling of the four `VOP2` arithmetic ops and the four `VOP1` rounding ops above as supported, matching what `tools/pixel_aot.py` lowers: two sources of the `_e32` source set (a binary16 inline constant, 0, a 16-bit literal, a VGPR or an SGPR; the `_e64` src1 need not be a VGPR) or one source for the rounding ops, with no modifier, `clamp`, `mul:`, `div:` or `op_sel`. The `_e64` spellings of `v_cvt_f16_i16` and `v_cvt_f16_u16` and of `v_fract_f16` stay unsupported. This is a syntactic match only: whether a source is statically proven finite is decided by the translator. `tests/rdna2_tools_check.py` (`test_binary16_e64_scanner_translator_agreement`) lowers each accepted and each refused form through `pixel_aot.lower` and requires the scanner to agree with it. No lowering changed here, so this adds no new shader readback; the existing binary16 draws in `tests/pixel_aot_check.py` already cover the `_e64` lowering. It shows scanner and translator agreement, not that any title runs. diff --git a/tests/form_coverage_check.py b/tests/form_coverage_check.py index 752413a081..0ed8799184 100644 --- a/tests/form_coverage_check.py +++ b/tests/form_coverage_check.py @@ -721,6 +721,43 @@ def check_f16_rcp_sqrt_forms(): pixel.ACCEPTED.update(saved) +def check_f16_rsq_exp_forms(): + """The four plain binary16 VOP1 reciprocal-square-root and exponent forms (e32 and e64 spellings of rsq and + exp) count as covered once the translator accepts their fixtures; the DPP and SDWA spellings and log, sin and + cos stay uncovered.""" + import pixel_aot_check as pixel + saved = set(pixel.ACCEPTED) + pixel.ACCEPTED.clear() + try: + for key in pixel.F16_RSQ_EXP_PROGRAMS: + pixel.translate_f16(pixel.f16_rsq_exp_program(*key)) + ops = ("rsq", "exp") + forms = {("VOP1", f"v_{op}_f16") for op in ops} | {("VOP3", f"v_{op}_f16_e64") for op in ops} + assert len(forms) == 4 + neighbours = { + ("VOP1", "v_log_f16"), ("VOP3", "v_log_f16_e64"), + ("VOP1", "v_sin_f16"), ("VOP3", "v_cos_f16_e64"), + ("DPP16", "v_rsq_f16_dpp"), ("DPP16", "v_exp_f16_dpp"), + ("DPP8", "v_rsq_f16_dpp"), ("DPP8", "v_exp_f16_dpp"), + ("SDWA", "v_rsq_f16_sdwa"), ("SDWA", "v_exp_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)) + # Without the rsq/exp fixtures none of the four forms is covered, not even through the other unary ones. + pixel.ACCEPTED.clear() + for body in pixel.F16_EXACT_EXTRA_PROGRAMS.values(): + pixel.translate_f16(pixel.uncompressed_export(body)) + assert not forms & fc.gfx_forms(pixel.ACCEPTED, fc.load_reference("gfx1013.tsv")) + finally: + pixel.ACCEPTED.clear() + pixel.ACCEPTED.update(saved) + + def check_f16_fmac_ldexp_forms(): """The two plain e32 binary16 forms v_fmac_f16 and v_ldexp_f16 count as covered once the translator accepts their fixtures; their e64, DPP and SDWA spellings and the arithmetic they resemble stay uncovered.""" @@ -1803,6 +1840,7 @@ def check_f16_cvt_norm_forms(): check_f16_arith_forms() check_f16_round_forms() check_f16_rcp_sqrt_forms() + check_f16_rsq_exp_forms() check_f16_fmac_ldexp_forms() check_f16_cvt_int16_forms() check_f16_to_int16_forms() diff --git a/tests/pixel_aot_check.py b/tests/pixel_aot_check.py index 79b3f37e25..99ba08801d 100644 --- a/tests/pixel_aot_check.py +++ b/tests/pixel_aot_check.py @@ -1,4 +1,5 @@ """Exercise offline pixel translation with independently assembled test programs.""" +from decimal import Decimal, localcontext from fractions import Fraction from pathlib import Path import bisect @@ -7824,7 +7825,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_rsq_f16_e64 v24, v18"): + "v_log_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") @@ -16906,8 +16907,8 @@ def refuse(line, message, translator=translate_f16): 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_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_rsq_f16_e64 v24, v18", - "v_exp_f16_e32 v24, v18"): + "v_add_f16 v24, v18, v19, v19", "v_add_f16 v24, v18", "v_log_f16_e64 v24, v18", + "v_log_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. @@ -17735,8 +17736,8 @@ def refuse(line, message, translator=translate_f16): "v_floor_f16_e64 v24, -v18 clamp", "v_floor_f16_e32 v24, v18 clamp", "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_rsq_f16_e32 v24, v18", - "v_rsq_f16_e64 v24, v18", "v_exp_f16_e64 v24, v18"): + "v_floor_f16 v24, v18, v19", "v_floor_f16 v24", "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", + "v_sin_f16_e32 v24, v18", "v_cos_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. @@ -17961,7 +17962,7 @@ def check_f16_rcp_sqrt_reference(): assert theirs is None, (op, hex(half), theirs) else: assert ours == theirs, (op, hex(half), hex(ours), theirs) - assert len(pixel_aot.VOP1_F16_UNARY) == 2 + assert len(pixel_aot.VOP1_F16_UNARY) == 4 def check_f16_rcp_sqrt_mutation_coverage(): @@ -18058,8 +18059,8 @@ def refuse(line, message, translator=translate_f16): "v_rcp_f16_e64 v24, v18 mul:4", "v_sqrt_f16_e64 v24, v18 op_sel:[0,1]", "v_rcp_f16_e32 v24, v18 clamp", "v_rcp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", "v_sqrt_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", "v_rsq_f16_e32 v24, v18", - "v_exp_f16_e64 v24, v18", "v_log_f16_e32 v24, v18"): + "v_rcp_f16 v24, v18, v19", "v_sqrt_f16 v24", "v_log_f16_e32 v24, v18", + "v_log_f16_e64 v24, v18", "v_sin_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. @@ -18101,6 +18102,375 @@ def float_f16(instructions): expect_value_error(translate_f16, program(*produced, line), message) +# Plain binary16 VOP1 reciprocal square root and exponent (issue #839): v_rsq_f16 and v_exp_f16, e32 and e64. The +# lowering follows the direct compute path: widen16, one binary32 rsqrt or exp2, narrow16, then the RDNA 2 special +# selects from the source half (rsq: above +infinity to 0x7e00, +infinity to zero, zero magnitude to source | 0x7c00; +# exp: the 70 midpoint corrections, 2^-25 to zero, a magnitude above +infinity to 0x7e00). The Python reference +# evaluates the exact reciprocal square root and 2^S0 without pixel_aot. The chosen rsq sources avoid the 8 f32 ULP +# window of a binary16 rounding midpoint where the D3D rsqrt error allows either encoding. +F16_RSQ_EXP_OPS = ("rsq", "exp") +F16_RSQ_EXP_VALUES = ( + 0x3c00, 0x4400, 0xbc00, 0x0000, # 1 and 4 are exact roots; -1 is the canonical NaN; +0 is +infinity + 0x8000, 0x4000, 0x3800, 0xb800, # -0 gives -infinity; 2 and 0.5 are inexact; -0.5 is the canonical NaN + 0x0001, 0x0400, 0x7bff, 0x8001, # smallest subnormal, smallest normal, largest finite, -subnormal + 0x4900, 0x5100, 0x5b00, 0x6400, # 10, 40, 112 and 1024: exp overflows from 40 on + 0xce40, 0xc500, 0x11c3, 0x8dc6, # 2^-25 (exact tie to zero), -5, and two exp midpoint table rows + 0x4bff, 0x4c00, 0x3bff, 0x3c01, # just below 16, 16, 1 - ulp and 1 + ulp +) +F16_RSQ_EXP_READER_VALUES = (0x4400, 0x3c00, 0x0400, 0x0001) +# Chains (a, b): rsq(a), exp(rsq(a)), exp(b), rsq(exp(b)). Both orders stay finite in either operation order. +F16_RSQ_EXP_CHAINS = ((0x4400, 0x3c00), (0x3c00, 0x4000)) +F16_RSQ_EXP_MUTATIONS = ("ops_swapped", "src_high") + +_F16_EXP_MIDPOINT_CACHE = None + + +def f16_exp2_midpoints(): + """The direct compute exp2 midpoint corrections, generated by tests/f16_exp_midpoints.py.""" + global _F16_EXP_MIDPOINT_CACHE + if _F16_EXP_MIDPOINT_CACHE is None: + from f16_exp_midpoints import exp_f16_midpoints + _F16_EXP_MIDPOINT_CACHE = exp_f16_midpoints() + return _F16_EXP_MIDPOINT_CACHE + + +def f16_rsq_exp_reference(op, word, *, mutation=None): + """Binary16 result bits of v_rsq_f16 or v_exp_f16 on the low half of word, from the semantics only. + + The positive reciprocal square root is decided on the binary16 grid by exact integer comparisons (the search + boundary and every midpoint are squared against the source), so no rounding formula is shared with the + translator. A negative finite source is the canonical quiet NaN the direct compute path selects. Exp2 uses a + 90-digit reference and the same 70 midpoint corrections as the direct compute array; 2^-25 is the exact tie to + zero and 2^16 overflows. mutation models a deliberate deviation of the draw's mutated shaders. + """ + if mutation == "ops_swapped": + op = "exp" if op == "rsq" else "rsq" + half = (word >> 16 if mutation == "src_high" else word) & 0xffff + if op == "rsq": + if (half & 0x7fff) == 0: + return half | 0x7c00 + if half & 0x8000: + return 0x7e00 + source = f16_grid_value(half) + + def below(value): + return source * value * value < 1 + + low, high = 0x0400, 0x6c01 + while high - low > 1: + middle = (low + high) // 2 + if below(f16_grid_value(middle)): + low = middle + else: + high = middle + if source * f16_grid_value(high) ** 2 == 1: + return high + midpoint = (f16_grid_value(low) + f16_grid_value(high)) / 2 + if source * midpoint ** 2 == 1: + return low if low % 2 == 0 else high + return high if below(midpoint) else low + assert op == "exp" and (half & 0x7fff) < 0x7c00, hex(half) + if half == 0xce40: + return 0 + entry = f16_exp2_midpoints().get(half) + if entry is not None: + return entry + value = f16_grid_value(half) + if value >= 16: + return 0x7c00 + if value <= -25: + return 0 + with localcontext() as context: + context.prec = 90 + exponent = Decimal(value.numerator) / Decimal(value.denominator) + exact = Fraction((exponent * Decimal(2).ln()).exp()) + result = f16_grid_nearest(exact) + assert result is not None + return result + + +def f16_rsq_exp_word(index, slot): + """The 32-bit source word of F16_RSQ_EXP_VALUES[4 * index + slot], with junk in bits 31:16.""" + value = 4 * index + slot + return (F16_ARITH_JUNK[value % 4] << 16) | F16_RSQ_EXP_VALUES[value] + + +def f16_widen_any(bits): + """The binary32 encoding of any binary16 encoding as the widen16 helper reads it: finite exact, NaN payload + shifted into bits 22:13.""" + sign, exponent, mantissa = bits >> 15, (bits >> 10) & 31, bits & 1023 + if exponent == 0x1f: + return (sign << 31) | 0x7f800000 | (mantissa << 13) + return f16_widen_word(bits) + + +def f16_rsq_exp_program(kind, index): + """One draw program. Kinds: main (four values, both ops, two results packed per word), reader (one value through + the four readers) and chain (both ops in both orders).""" + pack = "v_mov_b32_sdwa v{dst}, v{src} dst_sel:{sel} dst_unused:{unused} src0_sel:WORD_0" + body = [] + if kind == "main": + for slot in range(4): + value = 4 * index + slot + word = f16_rsq_exp_word(index, slot) + reg, sgpr = 18 + slot, 60 + slot + body += [f"v_mov_b32_e32 v{reg}, {word:#x}", f"s_mov_b32 s{sgpr}, {word:#x}"] + literal = f16_arith_token(word & 0xffff) + for k, op in enumerate(F16_RSQ_EXP_OPS): + dst, form = 24 + 2 * slot + k, (value + k) % 4 + if form == 3 and literal is None: + form = 0 + body.append([f"v_{op}_f16_e32 v{dst}, v{reg}", f"v_{op}_f16_e64 v{dst}, v{reg}", + f"v_{op}_f16_e64 v{dst}, s{sgpr}", f"v_{op}_f16_e32 v{dst}, {literal}"][form]) + for word in range(4): + body.append(pack.format(dst=12 + word, src=24 + 2 * word, sel="WORD_0", unused="UNUSED_PAD")) + body.append(pack.format(dst=12 + word, src=25 + 2 * word, sel="WORD_1", unused="UNUSED_PRESERVE")) + elif kind == "reader": + word = (F16_ARITH_JUNK[index] << 16) | F16_RSQ_EXP_READER_VALUES[index] + body += [f"v_mov_b32_e32 v18, {word:#x}", "v_rsq_f16_e32 v24, v18", "v_exp_f16_e64 v25, v18"] + body += [line.format(24 + (r + index) % 2) for r, line in enumerate(F16_ROUND_READERS)] + else: + word_a, word_b = ((F16_ARITH_JUNK[k] << 16) | half for k, half in enumerate(F16_RSQ_EXP_CHAINS[index])) + body += [f"v_mov_b32_e32 v18, {word_a:#x}", f"v_mov_b32_e32 v19, {word_b:#x}", + "v_rsq_f16_e32 v24, v18", "v_exp_f16_e64 v25, v24", + "v_exp_f16_e32 v26, v19", "v_rsq_f16_e64 v27, v26"] + body += [f"v_cvt_f32_f16_e32 v{12 + slot}, v{24 + slot}" for slot in range(4)] + return uncompressed_export(body) + + +def f16_rsq_exp_source_halves(kind, index): + """The binary16 source encodings of one draw program.""" + if kind == "main": + return list(F16_RSQ_EXP_VALUES[4 * index:4 * index + 4]) + return [F16_RSQ_EXP_READER_VALUES[index]] if kind == "reader" else list(F16_RSQ_EXP_CHAINS[index]) + + +def f16_rsq_exp_expected(kind, index, mutation=None): + """The four exported words of f16_rsq_exp_program(kind, index).""" + def result(op, word): + return f16_rsq_exp_reference(op, word, mutation=mutation) + + if kind == "main": + results = [] + for slot in range(4): + results += [result(op, f16_rsq_exp_word(index, slot)) for op in F16_RSQ_EXP_OPS] + return tuple(results[2 * word] | results[2 * word + 1] << 16 for word in range(4)) + if kind == "reader": + word = (F16_ARITH_JUNK[index] << 16) | F16_RSQ_EXP_READER_VALUES[index] + results = [result(op, word) for op in F16_RSQ_EXP_OPS] + chosen = [results[(r + index) % 2] for r in range(4)] + return (*(f16_widen_any(bits) for bits in chosen[:3]), chosen[3]) + word_a, word_b = ((F16_ARITH_JUNK[k] << 16) | half for k, half in enumerate(F16_RSQ_EXP_CHAINS[index])) + root = result("rsq", word_a) + other_exp = result("exp", word_b) + return tuple(f16_widen_any(bits) for bits in (root, result("exp", root), other_exp, result("rsq", other_exp))) + + +F16_RSQ_EXP_PROGRAMS = (*(('main', i) for i in range(len(F16_RSQ_EXP_VALUES) // 4)), + *(('reader', i) for i in range(len(F16_RSQ_EXP_READER_VALUES))), + *(('chain', i) for i in range(len(F16_RSQ_EXP_CHAINS)))) + + +def f16_rsq_exp_mutated(mutation, program): + """The lowered source of program with one deviation applied.""" + if mutation == "ops_swapped": + swapped = [re.sub(r"v_(rsq|exp)_f16", lambda m: "v_exp_f16" if m[1] == "rsq" else "v_rsq_f16", line) + for line in program] + assert swapped != program, mutation + return translate_f16(swapped) + text = translate_f16(program) + mutated = re.sub(r"uint (hf\d+_0) = \((.+)\) & 0xffffu;", r"uint \1 = ((\2) >> 16u) & 0xffffu;", text) + assert mutated != text, mutation + return mutated + + +def f16_rsq_exp_detecting_program(mutation): + """The first program whose expected words the modelled mutation changes.""" + for kind, index in F16_RSQ_EXP_PROGRAMS: + if f16_rsq_exp_expected(kind, index, mutation) != f16_rsq_exp_expected(kind, index): + return kind, index + raise AssertionError(f"No program separates {mutation}") + + +def check_f16_rsq_exp_reference(): + """Pinned rows, the exp2 midpoint table against the direct compute source, and the translator's own result on + every finite binary16 source (all 65,536 encodings).""" + from f16_exp_midpoints import check_cpp_table + check_cpp_table() + table = f16_exp2_midpoints() + assert len(table) == 70 and pixel_aot.EXP_F16_MIDPOINTS == table + assert len(F16_RSQ_EXP_VALUES) == 24 and len(set(F16_RSQ_EXP_VALUES)) == 24 + assert all((half >> 10) & 31 != 31 for half in F16_RSQ_EXP_VALUES + F16_RSQ_EXP_READER_VALUES) + for op, half, expected in ( + ("rsq", 0x3c00, 0x3c00), ("rsq", 0x4400, 0x3800), ("rsq", 0x4000, 0x39a8), + ("rsq", 0x0400, 0x5800), ("rsq", 0x0001, 0x6c00), ("rsq", 0x7bff, 0x1c00), + ("rsq", 0x0000, 0x7c00), ("rsq", 0x8000, 0xfc00), ("rsq", 0x8001, 0x7e00), + ("rsq", 0xbc00, 0x7e00), + ("exp", 0x0000, 0x3c00), ("exp", 0x8000, 0x3c00), ("exp", 0x3c00, 0x4000), + ("exp", 0xbc00, 0x3800), ("exp", 0x3bff, 0x3fff), ("exp", 0x3c01, 0x4001), + ("exp", 0x4c00, 0x7c00), ("exp", 0xce40, 0x0000), ("exp", 0x11c3, 0x3c00), + ("exp", 0x8dc6, 0x3bff)): + assert f16_rsq_exp_reference(op, 0xa5c3_0000 | half) == expected, (op, hex(half), hex(expected)) + for half in range(0x10000): + if (half >> 10) & 31 == 31: + continue + for op in F16_RSQ_EXP_OPS: + ours = f16_rsq_exp_reference(op, 0x1234_0000 | half) + theirs = pixel_aot.f16_rsq_exp_result(op, half) + assert ours == theirs, (op, hex(half), hex(ours), theirs) + assert len(pixel_aot.VOP1_F16_UNARY) == 4 + + +def check_f16_rsq_exp_mutation_coverage(): + """Every deviation changes an expected word of some program.""" + for kind, index in F16_RSQ_EXP_PROGRAMS: + assert len(f16_rsq_exp_expected(kind, index)) == 4, (kind, index) + for mutation in F16_RSQ_EXP_MUTATIONS: + f16_rsq_exp_detecting_program(mutation) + assert f16_rsq_exp_reference("rsq", 0x4400) == 0x3800 + assert f16_rsq_exp_reference("rsq", 0x4400, mutation="ops_swapped") == 0x4c00 + assert f16_rsq_exp_reference("exp", 0x3c00) == 0x4000 + assert f16_rsq_exp_reference("exp", 0x3c00, mutation="ops_swapped") == 0x3c00 + assert f16_widen_any(0x7e00) == 0x7fc00000 and f16_widen_any(0x7c00) == 0x7f800000 + + +def check_f16_rsq_exp_controls(): + """Lowering, spelling, input proof, mode, modifier, special-result and reader refusals of v_rsq_f16 and + v_exp_f16.""" + check_f16_rsq_exp_reference() + check_f16_rsq_exp_mutation_coverage() + prefix = ["v_mov_b32_e32 v18, 0x35554000", "v_mov_b32_e32 v19, 0xd1a74400", "s_mov_b32 s60, 0x35550400"] + calls = {"rsq": "rsqrt(", "exp": "exp2("} + helpers = {"rsq": "f16_rsq_result(", "exp": "f16_exp2_result("} + + def program(*lines): + return uncompressed_export([*prefix, *lines]) + + def refuse(line, message, translator=translate_f16): + expect_value_error(translator, program(line), message) + + # Lowering and spelling: the bare, _e32 and _e64 spellings are one lowering, with the special-result select. + for op in F16_RSQ_EXP_OPS: + spelled = [translate_f16(program(f"v_{op}_f16{suffix} v24, v18")) for suffix in ("", "_e32", "_e64")] + assert spelled[0] == spelled[1] == spelled[2], op + body = spelled[0].split("uint4 main", 1)[1] + assert calls[op] + "widen16(hf" in body, (op, body) + assert "narrow16(hs" in body and helpers[op] in body, op + for forbidden in ("f32tof16", "f16tof32", "float16_t", "half ", "0xffff0000u"): + assert forbidden not in body, (op, forbidden) + # Operand kinds: VGPR, SGPR, every binary16 inline constant, zero and 16-bit literals. + for token, bits in (*pixel_aot.INLINE_F16.items(), ("0", 0), ("0x3555", 0x3555), ("0x8000", 0x8000), + ("0x7bff", 0x7bff)): + for op in F16_RSQ_EXP_OPS: + for encoding in ("_e32", "_e64"): + assert f"_0 = ({bits}u) & 0xffffu;" in translate_f16(program(f"v_{op}_f16{encoding} v24, {token}")), token + for line in ("v_rsq_f16_e64 v24, s60", "v_exp_f16_e32 v24, s60", "v_rsq_f16_e32 v24, v18"): + translate_f16(program(line)) + # A finite source is enough even when the result is not finite: rsq(0) is a signed infinity, rsq(-1) the + # canonical NaN and exp(16) an infinity; the canonical NaN can be read but does not stay a proven source. + for op, token in (("rsq", "0x0001"), ("rsq", "0"), ("rsq", "0x8000"), ("rsq", "-2.0"), + ("exp", "0x4c00"), ("exp", "0xce40"), ("exp", "0x7bff"), ("exp", "-2.0")): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + translate_f16(program("v_mov_b32_e32 v20, v18", "v_rsq_f16 v24, v20")) + translate_f16(program("s_mov_b32 s61, s60", "v_exp_f16_e64 v24, s61")) + translate_f16(program("v_rsq_f16 v24, 0x4400", "v_exp_f16 v25, v24", "v_mov_b32_sdwa v12, v25 " + "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0")) + translate_f16(program("v_exp_f16 v24, 0xce40", "v_rsq_f16 v25, v24")) + expect_value_error(translate_f16, program("v_rsq_f16 v24, 0", "v_exp_f16 v25, v24"), + "binary16 operand is not finite: v24") + expect_value_error(translate_f16, program("v_exp_f16 v24, 0xce40", "v_rsq_f16 v25, v24", "v_exp_f16 v26, v25"), + "binary16 operand is not finite: v25") + expect_value_error(translate_f16, program("v_rsq_f16 v24, 0xbc00", "v_exp_f16 v25, v24"), + "binary16 operand is not finite: v24") + # Entry profile: unknown or an unsupported declaration refuses every spelling. + for op in F16_RSQ_EXP_OPS: + for suffix in ("", "_e32", "_e64"): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True), + program(f"v_{op}_f16{suffix} v24, v18"), "binary16 denormal mode unknown at entry") + for state in ("flush", "ftz", "", False): + expect_value_error(lambda p: lower(p, 20, 24, [1, 2, 3, 4], constant_descriptor=64, integer_export=True, + half_denorm=state), program("v_rsq_f16 v24, v18"), + "Invalid binary16 denormal entry state") + # No finite proof: a constant-buffer word, an uninitialized register, a sample and an integer result. + for line, token in (("v_rsq_f16_e64 v24, s44", "s44"), ("v_exp_f16 v24, v30", "v30"), + ("v_rsq_f16_e64 v24, v12", "v12")): + refuse(line, f"binary16 operand lacks a finite proof: {token}") + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, s44", "v_exp_f16 v24, v20"), + "binary16 operand lacks a finite proof: v20") + expect_value_error(translate_f16, program("v_add_nc_u16 v25, v18, v19", "v_rsq_f16 v24, v25"), + "binary16 operand lacks a finite proof: v25") + # NaN and infinity are refused wherever the proof finds them; the largest finite values and subnormals are not. + for op in F16_RSQ_EXP_OPS: + for token in ("0x7c00", "0xfc00", "0x7e00", "0x7c01", "0xffff"): + refuse(f"v_{op}_f16_e64 v24, {token}", f"binary16 operand is not finite: {token}") + for token in ("0x7bff", "0xfbff", "0x0001", "0x8001", "0x0400", "-2.0", "-0.5", "0"): + translate_f16(program(f"v_{op}_f16_e64 v24, {token}")) + expect_value_error(translate_f16, program("v_mov_b32_e32 v20, 0x7e00", "v_exp_f16 v24, v20"), + "binary16 operand is not finite: v20") + # Source modifiers, integer inline constants, floats and other operands. + for token in ("-v18", "|v18|", "abs(v18)", "neg(v18)", "-|v18|", "-s60", "-3.0"): + refuse(f"v_rsq_f16_e64 v24, {token}", f"Unsupported binary16 source modifier {token}") + refuse(f"v_exp_f16_e32 v24, {token}", f"Unsupported binary16 source modifier {token}") + for token in ("1", "64", "-1", "-16", "5"): + refuse(f"v_exp_f16_e64 v24, {token}", f"Unsupported binary16 integer inline constant {token}") + for token in ("3.0", "0.25", "vcc_lo", "m0", "exec_lo", "null", "v[18:19]"): + refuse(f"v_rsq_f16_e64 v24, {token}", f"Unsupported binary16 operand {token}") + refuse("v_exp_f16_e64 v24, 0x10000", "16-bit literal out of range: 0x10000") + refuse("v_rsq_f16_e64 v256, 1.0", "Register out of range: v256") + refuse("v_exp_f16_e64 v24, v256", "Register out of range: v256") + refuse("v_rsq_f16_e64 v24, s106", "Register out of range: s106") + # Unmodelled modifiers and neighbouring forms fall through to the generic refusal. + for line in ("v_rsq_f16_e64 v24, v18 clamp", "v_exp_f16_e64 v24, v18 clamp", + "v_rsq_f16_e64 v24, v18 mul:2", "v_exp_f16_e64 v24, v18 div:2", + "v_rsq_f16_e64 v24, v18 mul:4", "v_exp_f16_e64 v24, v18 op_sel:[0,1]", + "v_rsq_f16_e32 v24, v18 clamp", "v_exp_f16_e32 v24, v18 clamp", + "v_rsq_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_exp_f16_dpp v24, v18 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf", + "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_exp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_rsq_f16 v24, v18, v19", "v_exp_f16 v24", "v_log_f16_e32 v24, v18", + "v_log_f16_e64 v24, v18", "v_sin_f16_e32 v24, v18", "v_cos_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. + def float_f16(instructions): + return lower(instructions, 20, 24, [1, 2, 3, 4], constant_descriptor=64, half_denorm=pixel_aot.HALF_DENORM_PRESERVE) + + base = with_constants([]) + load = next(i for i, line in enumerate(base) if line.startswith("s_buffer_load_dwordx4")) + sample = next(i for i, line in enumerate(base) if line.startswith("image_sample")) + expect_value_error(float_f16, base[:load + 1] + ["v_rsq_f16_e64 v24, s44"] + base[load + 1:], + "Constant read before load completion") + expect_value_error(float_f16, base[:sample + 1] + ["v_exp_f16_e64 v12, 1.0"] + base[sample + 1:], + "Write overlaps an outstanding sample") + expect_value_error(float_f16, base[:sample + 1] + ["v_rsq_f16_e64 v24, v12"] + base[sample + 1:], + "Sample used before vmcnt wait") + float_f16(base[:sample + 1] + ["v_exp_f16_e64 v20, 1.0"] + base[sample + 1:]) + masked = base.index("s_wqm_b64 exec, exec") + 1 + expect_value_error(float_f16, base[:masked] + ["v_rsq_f16_e64 v24, 1.0"] + base[masked:], + "Invalid binary16 unary operation") + # Mode: every spelling is refused under round toward zero, a restored mode lowers like no write at all. + for spelling in (f"v_{op}_f16{suffix}" for op in F16_RSQ_EXP_OPS for suffix in ("_e32", "_e64")): + line = f"{spelling} v24, v18" + expect_value_error(translate_f16, uncompressed_export([HALF_RTZ, *prefix, line]), + f"under round toward zero: {spelling}") + assert translate_f16(uncompressed_export([HALF_RTZ, HALF_RNE, *prefix, line])) == translate_f16( + uncompressed_export(["s_nop 0", "s_nop 0", *prefix, line])) + # Readers. The audited ones read a unary result; every other reader of the tag refuses it. + produced = [*prefix, "v_rsq_f16_e32 v24, v18", "v_exp_f16_e64 v25, v18"] + for register in (24, 25): + for line in (f"v_cvt_f32_f16_e32 v12, v{register}", f"v_cvt_f32_f16_e64 v12, v{register}", + f"v_cvt_f32_f16_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + f"v_mov_b32_sdwa v12, v{register} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0"): + translate_f16(program(*produced, line)) + sdwa = "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:" + for line, message in ((f"v_cvt_f32_f16_sdwa v12, v{register} {sdwa}WORD_1", + "Reads the undefined high half of a 16-bit result"), + (f"v_mov_b32_e32 v12, v{register}", "Expected a numeric register"), + (f"v_add_nc_u16 v12, v{register}, v18", "Expected a numeric register")): + expect_value_error(translate_f16, program(*produced, line), message) + + # Integer to binary16 (issue #839): v_cvt_f16_i16 and v_cvt_f16_u16, e32 and e64 (LLVM 15.0.7 VOP1Instructions.td L432-433: # sint_to_fp and uint_to_fp, round to nearest even). The source is the low 16 bits through the audited low-16 integer # reader: a runtime i16 source needs no proof (every i16 is finite) but its result carries no known value; a u16 source must @@ -18462,9 +18832,9 @@ def refuse(line, message, translator=translate_f16): "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_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_log_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_rsq_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", + "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", "v_cvt_f16_i32 v24, v18", "v_cvt_f16_f16_e32 v24, v18"): refuse(line, "Unsupported instruction") @@ -18825,9 +19195,9 @@ def refuse(line, message, translator=translate_f16): "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_rcp_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_rsq_f16_sdwa v24, v18 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", + "v_log_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_rsq_f16_e32 v24, v18", "v_rsq_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): + "v_log_f16_e32 v24, v18", "v_log_f16_e64 v24, v18", "v_cvt_i32_f16 v24, v18"): refuse(line, "Unsupported instruction") # Entry profile: unknown or an unsupported declaration refuses every spelling of both kinds. for kind in ("i16", "u16"): @@ -19732,9 +20102,9 @@ 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_rsq_f16_e32 v12, v18"), + for old, new in (("v_ceil_f32_e32 v12, v18", "v_log_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_rsq_f16_e32 v13, v19"), + ("v_rndne_f32_e32 v13, v19", "v_log_f16_e32 v13, v19"), ("v_rndne_f32_e32 v13, v19", "v_rndne_f32_e32 v13, v19, v18"), ("v_rndne_f32_e64 v14, s45", "v_rndne_f32_e64 v14, s45 mul:2"), ("v_ceil_f32_e64 v15, -s46", "v_ceil_f32_e64 v15, -s46 div:2"), @@ -20992,6 +21362,7 @@ def _check_controls_inline(directory): "check_f16_arith_controls", "check_f16_round_controls", "check_f16_rcp_sqrt_controls", + "check_f16_rsq_exp_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -21001,6 +21372,7 @@ def _check_controls_inline(directory): "check_s_version", "check_f16_round_controls", "check_f16_rcp_sqrt_controls", + "check_f16_rsq_exp_controls", "check_f16_fmac_ldexp_controls", "check_f16_cvt_int_controls", "check_f16_to_int_controls", @@ -28111,6 +28483,49 @@ def case(kind, index, tag): "binary16 operand lacks a finite proof: s44") +def check_f16_rsq_exp_draw(directory, compiler, renderer, backend): + """v_rsq_f16 and v_exp_f16 against the Python reference, through the lossless R32G32B32A32_UINT readback. + + Six baked programs run 24 sources through both ops in a rotation of e32, e64, SGPR and literal forms and pack two + results per word; four reader programs and two chains cover the audited readers and both result orders. The values + cover exact roots and powers, inexact results, signed zeros, subnormals, the largest finite half, the 2^-25 underflow + tie, two exp2 midpoint corrections, an overflowing exp and the canonical negative-root NaN. Two deviations must + each mismatch (one batch per mutation; the statuses are printed): rsq and exp swapped, and a source read from bits + 31:16. A source nothing proves is refused at translation. + + Only the zero-extended low half of each result is observed. Whether hardware keeps or zeroes the destination's + high half is not measured here; the source-high mutation is the high-half control for the sources. + """ + check_f16_rsq_exp_mutation_coverage() + source = directory / "f16_rsq_exp.hlsl" + shader = directory / "f16_rsq_exp.cso" + constants = bytes(256) + + def build(text): + source.write_text(text, encoding="ascii") + compile_shader(compiler, source, shader) + + def case(kind, index, tag): + path = directory / f"f16_rsq_exp-{tag}-{kind}-{index}.case" + write_case(path, constants, tuple(as_float(word) for word in f16_rsq_exp_expected(kind, index)), integer_rt=True) + return path + + programs = {key: f16_rsq_exp_program(*key) for key in F16_RSQ_EXP_PROGRAMS} + for key in F16_RSQ_EXP_PROGRAMS: + build(translate_f16(programs[key])) + run_pixel_batch(renderer, backend, shader, [(case(*key, "ref"), "pass")]) + for mutation in F16_RSQ_EXP_MUTATIONS: + key = f16_rsq_exp_detecting_program(mutation) + build(f16_rsq_exp_mutated(mutation, programs[key])) + statuses, _ = run_pixel_batch_statuses(renderer, backend, shader, [case(*key, "mut")]) + print(f"f16_rsq_exp mutation {mutation}: program {key} statuses {statuses}") + if "mismatch" not in statuses: + raise AssertionError(f"Mutating {mutation} escaped detection") + for op in F16_RSQ_EXP_OPS: + expect_value_error(translate_f16, uncompressed_export([f"v_{op}_f16_e64 v24, s44"]), + "binary16 operand lacks a finite proof: s44") + + def check_f16_fmac_ldexp_draw(directory, compiler, renderer, backend): """v_fmac_f16 and v_ldexp_f16 against the independent Python reference: 24 baked fused multiply-accumulate rows (cancellation, rows where rounding the product first gives another result, signed zero results, ties into the @@ -28372,7 +28787,7 @@ def main(): "draw-title-loads", "draw-ds-swizzle", "draw-exec-regions", "draw-cmpx-regions", "draw-cmpx-e64", "draw-cmpx-sdwa", "draw-scc-skip", "draw-s-call", "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-rcp-sqrt", "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-f16-arith", "draw-f16-round", "draw-f16-rcp-sqrt", "draw-f16-rsq-exp", "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-f16-cvt-norm", "draw-sdwa-cvt", "draw-dpp-extra", "draw-pk-fmac"): try: draw = {"draw-blend-scalar": check_blend_and_scalar_draws, @@ -28410,6 +28825,7 @@ def main(): "draw-f16-arith": check_f16_arith_draw, "draw-f16-round": check_f16_round_draw, "draw-f16-rcp-sqrt": check_f16_rcp_sqrt_draw, + "draw-f16-rsq-exp": check_f16_rsq_exp_draw, "draw-f16-fmac-ldexp": check_f16_fmac_ldexp_draw, "draw-f16-cvt-int16": check_f16_cvt_int16_draw, "draw-f16-to-int16": check_f16_to_int16_draw, diff --git a/tests/rdna2_tools_check.py b/tests/rdna2_tools_check.py index bcd6178a77..479fa95654 100644 --- a/tests/rdna2_tools_check.py +++ b/tests/rdna2_tools_check.py @@ -6282,7 +6282,7 @@ def test_low16_binary16_e32_scanner_support(self): f"v_{op}_f16_e32 v24, 0x3c00, v19", f"v_{op}_f16_e32 v24, 0, v19"] for op in ("floor", "ceil", "trunc", "rndne"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] - for op in ("rcp", "sqrt"): + for op in ("rcp", "sqrt", "rsq", "exp"): supported += [f"v_{op}_f16_e32 v24, v18", f"v_{op}_f16_e32 v24, 2.0", f"v_{op}_f16_e32 v24, 0x4248"] for kind in ("i16", "u16"): supported += [f"v_cvt_f16_{kind}_e32 v24, v18", f"v_cvt_f16_{kind}_e32 v24, s45", @@ -6312,6 +6312,8 @@ def test_low16_binary16_e32_scanner_support(self): "v_floor_f16_e32 v24, v18 clamp", "v_rcp_f16_e32 v24, -v18", "v_sqrt_f16_e32 v24, v18 clamp", + "v_rsq_f16_e32 v24, -v18", + "v_exp_f16_e32 v24, v18 clamp", "v_fract_f16_e32 v24, v18", "v_cvt_f16_i16_e32 v24, 65", "v_cvt_f16_u16_e32 v24, 0x10000", @@ -6322,6 +6324,7 @@ def test_low16_binary16_e32_scanner_support(self): for line in refused: self.assertFalse(is_instruction_supported(line), line) for opcode in ("v_add_f16", "v_subrev_f16", "v_rndne_f16", "v_rcp_f16", "v_sqrt_f16", + "v_rsq_f16", "v_exp_f16", "v_cvt_f16_u16", "v_fmac_f16", "v_ldexp_f16"): self.assertIn(opcode, KNOWN_RDNA2_BASE_OPCODES) @@ -6350,7 +6353,7 @@ def translator_accepts(line): for op in ("floor", "ceil", "trunc", "rndne"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] - for op in ("rcp", "sqrt"): + for op in ("rcp", "sqrt", "rsq", "exp"): accepted += [f"v_{op}_f16_e64 v24, v18", f"v_{op}_f16_e64 v24, s60", f"v_{op}_f16_e64 v24, 2.0", f"v_{op}_f16_e64 v24, 0x4248"] refused = [ @@ -6361,12 +6364,14 @@ 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_rsq_f16_e64 v24, v18", "v_mul_f16_e64 v24, v18, v19 clamp", + "v_fma_f16_e64 v24, v18, v19, v19", "v_log_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", "v_rcp_f16_e64 v24, -v18", "v_sqrt_f16_e64 v24, |v18|", "v_rcp_f16_e64 v24, v18 clamp", "v_sqrt_f16_e64 v24, v18 mul:2", "v_rcp_f16_e64 v24, 3", "v_sqrt_f16_e64 v24, 0x10000", + "v_rsq_f16_e64 v24, -v18", "v_exp_f16_e64 v24, |v18|", "v_rsq_f16_e64 v24, v18 clamp", + "v_exp_f16_e64 v24, v18 mul:2", "v_rsq_f16_e64 v24, 3", "v_exp_f16_e64 v24, 0x10000", ] for line in accepted: self.assertTrue(is_instruction_supported(line), line) diff --git a/tools/pixel_aot.py b/tools/pixel_aot.py index 9ad32beaea..30def60a3d 100644 --- a/tools/pixel_aot.py +++ b/tools/pixel_aot.py @@ -1,6 +1,7 @@ """Offline lowering for selected gfx1013 and gfx1030 pixel shaders.""" import argparse import ctypes as C +from decimal import Decimal, localcontext from fractions import Fraction import hashlib import json @@ -1089,6 +1090,59 @@ def check_vopc_e32_dst(enc, dst): " return sa > sb ? (a & 0xffffu) : (b & 0xffffu);\n" "}" ), + # The RDNA 2 special results of v_rsq_f16 and v_exp_f16 from the source half bits, as the direct compute path + # selects them after packed_half_rne. The exp2 corrections are the 70 sources whose exact 2^S0 lies within the + # D3D exp2 error window of a binary16 rounding midpoint. + "f16_rsq_result": ( + "uint f16_rsq_result(uint source, uint rounded) {\n" + " if ((source & 0x7fffu) == 0u) return source | 0x7c00u;\n" + " if (source == 0x7c00u) return 0u;\n" + " if (source > 0x7c00u) return 0x7e00u;\n" + " return rounded;\n" + "}" + ), + "f16_exp2_result": ( + "uint f16_exp2_result(uint source, uint rounded) {\n" + " if (source == 0x11c3u) return 0x3c00u; if (source == 0x11c4u) return 0x3c00u;\n" + " if (source == 0x11c5u) return 0x3c01u; if (source == 0x11c6u) return 0x3c01u;\n" + " if (source == 0x11c7u) return 0x3c01u; if (source == 0x1853u) return 0x3c01u;\n" + " if (source == 0x1b34u) return 0x3c02u; if (source == 0x1b35u) return 0x3c03u;\n" + " if (source == 0x1e7au) return 0x3c04u; if (source == 0x1feau) return 0x3c06u;\n" + " if (source == 0x2164u) return 0x3c08u; if (source == 0x221bu) return 0x3c08u;\n" + " if (source == 0x2389u) return 0x3c0au; if (source == 0x2bdbu) return 0x3c2cu;\n" + " if (source == 0x2e7cu) return 0x3c4au; if (source == 0x2ea7u) return 0x3c4cu;\n" + " if (source == 0x2fe7u) return 0x3c5bu; if (source == 0x36b6u) return 0x3d5au;\n" + " if (source == 0x3863u) return 0x3dd9u; if (source == 0x39f8u) return 0x3eb5u;\n" + " if (source == 0x3a8au) return 0x3f0cu; if (source == 0x3b12u) return 0x3f62u;\n" + " if (source == 0x3b82u) return 0x3faau; if (source == 0x3efcu) return 0x42b5u;\n" + " if (source == 0x3f45u) return 0x430cu; if (source == 0x3f89u) return 0x4362u;\n" + " if (source == 0x3fc1u) return 0x43aau; if (source == 0x417eu) return 0x46b5u;\n" + " if (source == 0x437eu) return 0x4ab5u; if (source == 0x44bfu) return 0x4eb5u;\n" + " if (source == 0x45bfu) return 0x52b5u; if (source == 0x46bfu) return 0x56b5u;\n" + " if (source == 0x47bfu) return 0x5ab5u; if (source == 0x8dc3u) return 0x3c00u;\n" + " if (source == 0x8dc4u) return 0x3c00u; if (source == 0x8dc5u) return 0x3c00u;\n" + " if (source == 0x8dc6u) return 0x3bffu; if (source == 0x8dc7u) return 0x3bffu;\n" + " if (source == 0x8dc8u) return 0x3bffu; if (source == 0x9454u) return 0x3bffu;\n" + " if (source == 0x9455u) return 0x3bfeu; if (source == 0x9738u) return 0x3bfdu;\n" + " if (source == 0x990eu) return 0x3bfcu; if (source == 0x9a80u) return 0x3bfbu;\n" + " if (source == 0x9bf2u) return 0x3bfbu; if (source == 0x9e25u) return 0x3bf7u;\n" + " if (source == 0x9f98u) return 0x3bf5u; if (source == 0xa2b4u) return 0x3bedu;\n" + " if (source == 0xa52du) return 0x3be3u; if (source == 0xa86du) return 0x3bd0u;\n" + " if (source == 0xa8b4u) return 0x3bccu; if (source == 0xa9d1u) return 0x3bc0u;\n" + " if (source == 0xabe0u) return 0x3baau; if (source == 0xaf57u) return 0x3b63u;\n" + " if (source == 0xaf70u) return 0x3b62u; if (source == 0xb1d8u) return 0x3b0cu;\n" + " if (source == 0xb410u) return 0x3ab5u; if (source == 0xb4dbu) return 0x3a7cu;\n" + " if (source == 0xb73au) return 0x39d9u; if (source == 0xb8a5u) return 0x395au;\n" + " if (source == 0xbc3fu) return 0x37aau; if (source == 0xbc77u) return 0x3762u;\n" + " if (source == 0xbcbbu) return 0x370cu; if (source == 0xbd04u) return 0x36b5u;\n" + " if (source == 0xc082u) return 0x32b5u; if (source == 0xc282u) return 0x2eb5u;\n" + " if (source == 0xc441u) return 0x2ab5u; if (source == 0xc541u) return 0x26b5u;\n" + " if (source == 0xc641u) return 0x22b5u; if (source == 0xc741u) return 0x1eb5u;\n" + " if (source == 0xce40u) return 0u;\n" + " if ((source & 0x7fffu) > 0x7c00u) return 0x7e00u;\n" + " return rounded;\n" + "}" + ), "frexp_mant_f16": ( "uint frexp_mant_f16(uint bits) {\n" " uint h = bits & 0xffffu;\n" @@ -2109,8 +2163,34 @@ def pk_fmac_f16_source(token, scalar, vector, pending, sample_dest, known_ssa_bi # Plain binary16 VOP1 unary arithmetic (issue #839). These follow the direct compute lowering: widen the low half # exactly, evaluate one binary32 operation, then narrow with the same integer nearest-even conversion v_cvt_f16_f32 -# uses. AMD RDNA 2 section 12.8 defines D.f16 = 1.0 / S0.f16 and D.f16 = sqrt(S0.f16). -VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})"} +# uses. AMD RDNA 2 section 12.8 defines D.f16 = 1.0 / S0.f16, sqrt(S0.f16), 1.0 / sqrt(S0.f16) and 2^S0.f16. The +# rsqrt and exp2 approximations have a measured error window, so the lowered shader also applies the special-result +# and midpoint corrections of src/gfx1013_direct_compute.inl to the narrowed half. +VOP1_F16_UNARY = {"rcp": "(1.0f / {0})", "sqrt": "sqrt({0})", "rsq": "rsqrt({0})", "exp": "exp2({0})"} + +# The 70 finite binary16 sources whose exact 2^S0 lies within the D3D exp2 error window of a binary16 rounding +# midpoint, with the RDNA 2 result. This is the exp_f16_midpoints table of src/gfx1013_direct_compute.inl; +# tests/f16_exp_midpoints.py regenerates the C++ array, and check_f16_rsq_exp_reference pins this copy to it. +EXP_F16_MIDPOINTS = { + 0x11c3: 0x3c00, 0x11c4: 0x3c00, 0x11c5: 0x3c01, 0x11c6: 0x3c01, + 0x11c7: 0x3c01, 0x1853: 0x3c01, 0x1b34: 0x3c02, 0x1b35: 0x3c03, + 0x1e7a: 0x3c04, 0x1fea: 0x3c06, 0x2164: 0x3c08, 0x221b: 0x3c08, + 0x2389: 0x3c0a, 0x2bdb: 0x3c2c, 0x2e7c: 0x3c4a, 0x2ea7: 0x3c4c, + 0x2fe7: 0x3c5b, 0x36b6: 0x3d5a, 0x3863: 0x3dd9, 0x39f8: 0x3eb5, + 0x3a8a: 0x3f0c, 0x3b12: 0x3f62, 0x3b82: 0x3faa, 0x3efc: 0x42b5, + 0x3f45: 0x430c, 0x3f89: 0x4362, 0x3fc1: 0x43aa, 0x417e: 0x46b5, + 0x437e: 0x4ab5, 0x44bf: 0x4eb5, 0x45bf: 0x52b5, 0x46bf: 0x56b5, + 0x47bf: 0x5ab5, 0x8dc3: 0x3c00, 0x8dc4: 0x3c00, 0x8dc5: 0x3c00, + 0x8dc6: 0x3bff, 0x8dc7: 0x3bff, 0x8dc8: 0x3bff, 0x9454: 0x3bff, + 0x9455: 0x3bfe, 0x9738: 0x3bfd, 0x990e: 0x3bfc, 0x9a80: 0x3bfb, + 0x9bf2: 0x3bfb, 0x9e25: 0x3bf7, 0x9f98: 0x3bf5, 0xa2b4: 0x3bed, + 0xa52d: 0x3be3, 0xa86d: 0x3bd0, 0xa8b4: 0x3bcc, 0xa9d1: 0x3bc0, + 0xabe0: 0x3baa, 0xaf57: 0x3b63, 0xaf70: 0x3b62, 0xb1d8: 0x3b0c, + 0xb410: 0x3ab5, 0xb4db: 0x3a7c, 0xb73a: 0x39d9, 0xb8a5: 0x395a, + 0xbc3f: 0x37aa, 0xbc77: 0x3762, 0xbcbb: 0x370c, 0xbd04: 0x36b5, + 0xc082: 0x32b5, 0xc282: 0x2eb5, 0xc441: 0x2ab5, 0xc541: 0x26b5, + 0xc641: 0x22b5, 0xc741: 0x1eb5, +} def _f16_fraction(bits): @@ -2239,6 +2319,76 @@ def f16_rcp_sqrt_result(name, bits): return _fraction_to_f16(_f32_fraction(_f32_sqrt_bits(value))) +_F16_LN2 = None + + +def _f16_ln2(): + """ln(2) to 90 significant digits, computed once for the exact exp2 references.""" + global _F16_LN2 + if _F16_LN2 is None: + with localcontext() as context: + context.prec = 90 + _F16_LN2 = Decimal(2).ln() + return _F16_LN2 + + +def _f16_rsq_result(value): + """Binary16 encoding nearest to 1/sqrt(value) for a positive finite Fraction, ties to even. + + No positive finite binary16 has a reciprocal square root that is exactly a binary16 rounding midpoint, so a + 90-digit reference decides every encoding; the rounding itself uses the translator's integer narrow16 rule. + """ + with localcontext() as context: + context.prec = 90 + root = (Decimal(value.numerator) / Decimal(value.denominator)).sqrt() + return _fraction_to_f16(Fraction(1 / root)) + + +def _f16_exp2_result(value): + """Binary16 encoding nearest to 2^value for a finite Fraction whose result is finite and nontrivial. + + The exact power is evaluated with a 90-digit Decimal instead of the binary32 exp2 intrinsic; the 70 sources + whose exact result lies inside that intrinsic's error window of a rounding midpoint are corrected from + EXP_F16_MIDPOINTS before this call, so every remaining source rounds deterministically. + """ + if value >= 16: + return 0x7c00 + if value <= -25: + return 0 + with localcontext() as context: + context.prec = 90 + exponent = Decimal(value.numerator) / Decimal(value.denominator) + return _fraction_to_f16(Fraction((exponent * _f16_ln2()).exp())) + + +def f16_rsq_exp_result(name, bits): + """Binary16 result bits of v_rsq_f16 or v_exp_f16 on a finite operand. + + The direct compute lowering widens with widen16, calls unary.f32 opcode 25 (rsqrt) or 21 (exp2), narrows with + packed_half_rne and then applies the RDNA 2 special results from the source half: rsq maps a source above + +infinity to 0x7e00, +infinity to zero and a zero magnitude to source | 0x7c00; exp pins the 70 midpoint + sources, 2^-25 to zero and a magnitude above +infinity to 0x7e00. The two approximations are not reproduced + bit for bit: every other rsq source rounds the exact reciprocal square root, and every other exp source rounds + the exact 2^S0, which is what the error windows guarantee after the midpoint corrections. The negative + reciprocal square root is the direct compute path's canonical quiet NaN, so both operations have a modelled + result on every finite source; None is never returned today. + """ + value = _f16_fraction(bits) + if name == "rsq": + if value == 0: + return bits | 0x7c00 + if value < 0: + return 0x7e00 + return _f16_rsq_result(value) + assert name == "exp" + if bits == 0xce40: + return 0 + entry = EXP_F16_MIDPOINTS.get(bits) + if entry is not None: + return entry + return _f16_exp2_result(value) + + def f16_round_result(name, bits): """Exact binary16 result bits of one VOP1_F16_ROUND op on a finite operand. @@ -7930,9 +8080,11 @@ def known_sample_float(reg): vector[dst] = ("half16", f"alu{i}") known_half[f"alu{i}"] = result elif m := match(rf"v_({'|'.join(VOP1_F16_UNARY)})_f16(_e32|_e64)? (v\d+), ([^,\s]+)"): - # Plain binary16 VOP1 reciprocal and square root under the rules of the VOP2 arithmetic above: a statically - # proven finite source, the declared entry profile, no modifier, clamp or omod. These match the direct - # compute lowering: widen16, one binary32 division or sqrt, then narrow16. The result is ("half16", alu). + # Plain binary16 VOP1 reciprocal, square root, reciprocal square root and exponent under the rules of the + # VOP2 arithmetic above: a statically proven finite source, the declared entry profile, no modifier, clamp + # or omod. These match the direct compute lowering: widen16, one binary32 division, sqrt, rsqrt or exp2, + # then narrow16. rsq and exp additionally select the RDNA 2 special results from the source half bits. + # The result is ("half16", alu). name, encoding, dst, token = m.groups() if mask != "entry": raise ValueError("Invalid binary16 unary operation") @@ -7943,10 +8095,16 @@ def known_sample_float(reg): 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_rcp_sqrt_result(name, proven) + result = (f16_rcp_sqrt_result(name, proven) if name in ("rcp", "sqrt") + else f16_rsq_exp_result(name, proven)) lines.append(f" uint hf{i}_0 = ({word}) & 0xffffu;") lines.append(f" precise float hs{i} = {VOP1_F16_UNARY[name].format(f'widen16(hf{i}_0)')};") - lines.append(f" precise float alu{i} = asfloat(narrow16(hs{i}));") + if name in ("rsq", "exp"): + helper = "f16_rsq_result" if name == "rsq" else "f16_exp2_result" + helpers.add(helper) + lines.append(f" precise float alu{i} = asfloat({helper}(hf{i}_0, narrow16(hs{i})));") + else: + 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 diff --git a/tools/scan_unsupported_shaders.py b/tools/scan_unsupported_shaders.py index c376543339..02a562c0e0 100644 --- a/tools/scan_unsupported_shaders.py +++ b/tools/scan_unsupported_shaders.py @@ -473,7 +473,7 @@ def lower_rejection_causes(results: list[dict]) -> dict: # Decoding only: no translator lowers these binary16 VOP1/VOP2 forms. "v_cvt_u16_f16", "v_cvt_i16_f16", "v_fract_f16", "v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16", - "v_rsq_f16", "v_log_f16", "v_exp_f16", "v_sin_f16", "v_cos_f16", + "v_log_f16", "v_sin_f16", "v_cos_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_fmac_f16", "v_max_f16", "v_min_f16", "v_ldexp_f16", "v_pk_fmac_f16", }