diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 1865740c65..937ba2d44d 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -273,6 +273,7 @@ jobs: tests/startup_compute_lds_b64_check.py \ tests/startup_compute_translate_check.py \ tests/startup_gfx2hlsl_swap_check.py \ + tests/startup_gfx2hlsl_fma_mix_check.py \ tests/startup_gfx2hlsl_shift64_check.py \ tests/startup_gfx2hlsl_mul_mad_i24_check.py \ tests/startup_gfx2hlsl_vopc_sdwa_check.py \ diff --git a/AGENTS.md b/AGENTS.md index 6aeaaa4686..28e2f1cb54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -170,6 +170,7 @@ python3 -m venv out/pe-env ./out/pe-env/bin/python -B tests/startup_compute_image_store_d16_check.py ./out/pe-env/bin/python -B tests/startup_compute_translate_check.py ./out/pe-env/bin/python -B tests/startup_gfx2hlsl_swap_check.py +./out/pe-env/bin/python -B tests/startup_gfx2hlsl_fma_mix_check.py ./out/pe-env/bin/python -B tests/startup_image_2d_array_check.py ./out/pe-env/bin/python -B tests/startup_image_sample_a16_check.py ./out/pe-env/bin/python -B tests/startup_image_load_d16_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f1f43f9c9..d8b99e14e3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3059,6 +3059,9 @@ if(EXISTS "${INTAKE_PYTHON}") # them as an index error before it checked the count. add_test(NAME startup_gfx2hlsl_image_arity COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_image_arity_check.py") + # gfx2hlsl lowers v_fma_mix_f32 and selects binary16 source halves on all three mixed-precision FMAs. + add_test(NAME startup_gfx2hlsl_fma_mix COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py") # VOP1/VOP2 sub-dword addressing (SDWA) in the translator (#1141), checked against the pixel AOT # lowering of the same selections. add_test(NAME startup_gfx2hlsl_sdwa COMMAND "${INTAKE_PYTHON}" -B @@ -3161,6 +3164,11 @@ if(EXISTS "${INTAKE_PYTHON}") # gfx2hlsl run-time sampler heap indexing (#1143): translation controls, then a desktop draw with # DXC ps_6_0 and, when the Windows SDK's FXC is found, the ps_5_1 the startup tools compile with. find_program(STARTUP_FXC fxc HINTS "${DXC_BIN_DIR}") + if(STARTUP_FXC) + # The v_fma_mix* translations from startup_gfx2hlsl_fma_mix, compiled for ps_5_1. + add_test(NAME startup_gfx2hlsl_fma_mix_fxc COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py" fxc "${STARTUP_FXC}") + endif() # gfx2hlsl conversion operations: translation controls, then a draw of the translated pairs with # reference words and one mutated lowering per operation (v_cvt_f16_f32 through DXC only). # Compute translator: integer inequality lane guards. @@ -3487,6 +3495,15 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_gfx2hlsl_mad_dispatch_${adapter} startup_gfx2hlsl_mad_preserve_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl v_fma_mix*: every translated form dispatched against a CPU reference that decodes the VOP3P + # word itself, plus a control that drops the high-half shift. + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_fma_mix_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_fma_mix_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_fma_mix_dispatch_${adapter} + PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl compute stage: entry registers, numthreads and the offen buffer store, dispatched on a plain device (#1412). add_test(NAME startup_gfx2hlsl_compute_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_gfx2hlsl_compute_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index c7efb0451e..274acf858a 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -14299,6 +14299,35 @@ The binary32 table (`VEC_F`) applies the same operand-count rule. Before this ch `tests/startup_gfx2hlsl_swap_check.py` (`startup_gfx2hlsl_swap`) decodes the documented VOP1 words, evaluates the translated text of seven programs on the CPU against a plain exchange of two list entries, and checks the refusals. Two mutations (write before read, only one destination written) are loaded from the translator source and must fail the fixtures. `python -B tests/startup_gfx2hlsl_swap_check.py binary llvm-mc-15` also reassembles the source lines. This is translation only; no draw was run. +## Startup translator: v_fma_mix_f32 + +`tools/startup/gfx2hlsl.py` now lowers `v_fma_mix_f32` (VOP3P, opcode 0x20), which it used to refuse. It shares one handler with `v_fma_mixlo_f16` and `v_fma_mixhi_f16`. Each source is read as LLVM 15 selects it (`SelectVOP3PMadMixModsImpl`): `op_sel_hi` set means a binary16 source, and `op_sel` then picks its high half. abs and then neg apply after widening. The binary32 result is written to the whole VGPR, with optional `clamp`. + +The shared handler now also: + +- reads the high half of a binary16 source with `op_sel` (previously refused on all three forms); +- accepts `-` and `|...|` on binary16 register sources; +- still refuses `op_sel` on a binary32 source, including a negated inline zero (it was refused on every source before); +- refuses any other modifier it does not model (previously ignored); +- reads only bits 15:0 of a low-half binary16 source, so a register left with undefined upper bits by an odd-dmask D16 `image_load` stays usable there; a high-half read is still refused for such a register; +- reads a literal on a binary16 source through the selected half, so `0x40003c00` gives 1.0 from the low half and 2.0 from the high half; +- accepts inline `0.5` on a low-half binary16 source and refuses the high half of an inline constant and every other inline float there. Before, `mixlo`/`mixhi` passed the binary32 bits of an inline float such as `1.0` through `f16tof32`, which reads 0; +- reads a negated inline zero (`-0`) as `-0.0` on any source, so a `-0` product stays `-0`; +- emits neg on a negative inline float (printed `--0.5`) as `(-(-0.5))`. Before, `(--0.5)` was an HLSL decrement and did not compile; +- refuses a binary32 source printed as a negative integer or literal (`-1`, `-17`, `-0x…`). The decoder prints neg on inline 1..64 or on a literal that way, and reading it as an integer loses the sign-bit flip: neg on inline 1 is `0x80000001`, not `0xffffffff`. Inline `-1` prints the same text as neg on inline 1, so it is refused too until the decoder resolves the operand from the encoding, as it does for `v_cndmask_b32_e64` (#1932). + +`tests/startup_gfx2hlsl_fma_mix_check.py` (`startup_gfx2hlsl_fma_mix`) builds VOP3P words from the decoder layout. It first checks that its encoder reproduces two `llvm-mc`-assembled words already pinned in `tests/rdna2_tools_check.py`. It then checks the decoded text and pins the translation of seventeen forms. They include a register with undefined upper bits read through its low half, both halves of one literal, and inline `0.5` on a low half. Two controls check that flipping `op_sel` and `op_sel_hi` changes the output, a third checks that an unnegated literal still translates, and eleven forms must be refused. On the translator before this change the check fails at the first form. + +With `fxc `, the check also compiles all seventeen translated lines for ps_5_1, the profile the startup tools use. CMake registers that mode as `startup_gfx2hlsl_fma_mix_fxc` when it finds FXC. As a control, putting back the earlier `(--0.5)` text makes FXC fail with error X3025. The refusal census was not re-measured. + +With `dispatch warp|hardware`, all seventeen translated lines run in one DXC cs_6_0 thread. CMake registers this as `startup_gfx2hlsl_fma_mix_dispatch_warp` and `_hardware`. Each case loads its register words through the raw UAV fill pattern, so the compiler cannot fold them, runs the line and stores the destination. The check compares each word with a CPU reference that decodes the VOP3P word itself, without the decoder or the translator. The reference applies the LLVM 15 reading: binary16 if `op_sel_hi`, high half if `op_sel`, abs then neg, clamp. Inputs have short mantissas, so a fused and an unfused multiply-add give the same word; this check does not separate the two. A control drops the high-half shift from the emitted lines. Its readback must then follow a reference with `op_sel` cleared, and must differ from the correct result in at least one case. It differs in 3 of 4: the `-0` case has a zero product, so the half it reads does not show. + +Measured at `741ff02c` plus the dispatch mode, `dev` preset, Windows 11 26300.9974. On WARP (Microsoft Basic Render Driver, 1414:008c) and on an NVIDIA GeForce RTX 4090 (10de:2684, driver 32.0.16.1088), 17 of 17 words matched the reference, and the control read the low half in all 4 high-half cases. Neither run reported a capability skip. The fixture does not report D3D12 debug-layer status. + +```powershell +ctest --preset dev --no-tests=error -j1 -R '^startup_gfx2hlsl_fma_mix(_fxc|_dispatch_(warp|hardware))?$' -V +``` + ## Non-fused multiply-add in the startup translator The gfx1013 `v_mad_f32`, `v_mac_f32`, `v_madmk_f32`, `v_madak_f32` and diff --git a/tests/startup_gfx2hlsl_fma_mix_check.py b/tests/startup_gfx2hlsl_fma_mix_check.py new file mode 100644 index 0000000000..b2f25cc64f --- /dev/null +++ b/tests/startup_gfx2hlsl_fma_mix_check.py @@ -0,0 +1,452 @@ +"""Mixed-precision VOP3P FMA (`v_fma_mix_f32`, `v_fma_mix{lo,hi}_f16`) in tools/startup/gfx2hlsl.py. + +usage: startup_gfx2hlsl_fma_mix_check.py [fxc | dispatch warp|hardware] + +With `fxc`, every translated line is also compiled for ps_5_1 (the profile the startup tools use), +so emitted text that is not valid HLSL fails here and not only in a later draw. With `dispatch`, every +translated line runs in a DXC cs_6_0 shader on WARP or a hardware adapter, and each result word is +compared with a CPU reference that decodes the VOP3P word itself. Exit code 77 is a capability skip. + +`v_fma_mix_f32` was refused outright (58 code pairs in the #1723 refusal snapshot). It now shares +`Stage.mix()` with the two binary16-destination forms. + +Source selection follows LLVM 15 (`AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl`, llvmorg-15.0.7): +"If the source's op_sel_hi is set, it indicates to do a conversion from fp16. If the sources's op_sel +is set, it picks the high half of the source register." `AMDGPUInstPrinter::printOpSelHi` prints +`SISrcMods::OP_SEL_1`, the bit that function sets for an fp16 source. abs, then neg, apply after +the conversion. + +The instruction bytes are **constructed here** from the VOP3P layout the checked-in decoder reads +(`tools/disasm_rdna2.py`, VOP3P branch): + w0: [31:23] = 0b110011000, [22:16] opcode, [15] clamp, [14] op_sel_hi[2], [13:11] op_sel, + [10:8] abs (neg_hi on other VOP3P), [7:0] vdst + w1: [8:0] src0, [17:9] src1, [26:18] src2, [28:27] op_sel_hi[1:0], [31:29] neg (neg_lo) +""" +import os +import re +import struct +import subprocess +import sys +import tempfile + +here = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(here, '..', 'tools')) +sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup')) +import gfx2hlsl as G # noqa: E402 + +failures = [] +translated = [] # every emitted line, compiled together in fxc mode +cases = [] # (label, encoding, emitted line), run in dispatch mode + +MIX_F32, MIXLO_F16, MIXHI_F16 = 0x20, 0x21, 0x22 +V = 0x100 # VGPR source base +S5 = 5 +ZERO = 128 # inline integer 0 +ONE = 129 # inline integer 1 +SEVENTEEN = 145 # inline integer 17 +MINUS_ONE = 193 # inline integer -1 +MINUS_HALF_F = 241 # inline float -0.5 +ONE_F = 242 # inline float 1.0 +LITERAL = 255 + + +def check(label, condition, detail=''): + print(f"{label}: {'ok' if condition else 'MISMATCH'}") + if not condition: + failures.append(label) + if detail: + print(' ' + detail) + + +def encode(op, vdst, srcs, *, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0), abs_bits=(0, 0, 0), + neg=(0, 0, 0), clamp=0, literal=None): + w0 = (0b110011000 << 23) | (op << 16) | (clamp << 15) | (op_sel_hi[2] << 14) | (vdst & 0xff) + w1 = srcs[0] | (srcs[1] << 9) | (srcs[2] << 18) | (op_sel_hi[0] << 27) | (op_sel_hi[1] << 28) + for i in range(3): + w0 |= op_sel[i] << (11 + i) + w0 |= abs_bits[i] << (8 + i) + w1 |= neg[i] << (29 + i) + code = struct.pack('> 16) * F(v3) + F(v4));') +check('control: op_sel changes the selected half', low != high) +check('control: op_sel_hi changes the source format', plain != low) +expect('abs then neg after widening a high half, scalar source, clamp', + encode(MIX_F32, 1, (v2, S5, v4), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), + abs_bits=(0, 1, 0), neg=(0, 1, 0), clamp=1), + 'v_fma_mix_f32 v1, v2, -|s5|, v4 op_sel:[0,1,0] op_sel_hi:[0,1,0] clamp', + 'v1 = U(saturate(F(v2) * (-abs(f16tof32(s5 >> 16))) + F(v4)));') +expect('inline 0 as a binary16 addend', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1)), + 'v_fma_mix_f32 v1, v2, v3, 0 op_sel_hi:[1,1,1]', + 'v1 = U(f16tof32(v2) * f16tof32(v3) + 0.0);') +expect('negated inline 0 addend keeps a -0 product', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 1, 0), op_sel_hi=(0, 1, 0), neg=(0, 0, 1)), + 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,1,0] op_sel_hi:[0,1,0]', + 'v1 = U(F(v2) * f16tof32(v3 >> 16) + (-0.0));') +expect('inline float on a binary32 source', + encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(v2) * 1.0 + F(v4));') +# neg on inline -0.5 prints as `--0.5`; `(--0.5)` would be an HLSL decrement (review on #2055). +expect('negated negative inline float', + encode(MIX_F32, 1, (MINUS_HALF_F, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, --0.5, v3, v4', + 'v1 = U((-(-0.5)) * F(v3) + F(v4));') +expect('control: an unnegated literal on a binary32 source still translates', + encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x3f800000), + 'v_fma_mix_f32 v1, 0x3f800000, v3, v4', + 'v1 = U(F(0x3f800000u) * F(v3) + F(v4));') + +# --- the binary16-destination forms keep their packing -------------------------------------------- +expect('mixlo writes the low half', + encode(MIXLO_F16, 1, (v2, v3, v4), op_sel_hi=(1, 1, 0)), + 'v_fma_mixlo_f16 v1, v2, v3, v4 op_sel_hi:[1,1,0]', + 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + F(v4));') +expect('mixlo with a negated inline 0 on a binary16 source', + encode(MIXLO_F16, 1, (v2, v3, ZERO), op_sel_hi=(1, 1, 1), neg=(0, 0, 1)), + 'v_fma_mixlo_f16 v1, v2, v3, -0 op_sel_hi:[1,1,1]', + 'v1 = (v1 & 0xffff0000u) | f32tof16(f16tof32(v2) * f16tof32(v3) + (-0.0));') +expect('mixhi writes the high half from a high-half source', + encode(MIXHI_F16, 1, (v2, v3, v4), op_sel=(0, 0, 1), op_sel_hi=(0, 0, 1)), + 'v_fma_mixhi_f16 v1, v2, v3, v4 op_sel:[0,0,1] op_sel_hi:[0,0,1]', + 'v1 = (v1 & 0xffffu) | (f32tof16(F(v2) * F(v3) + f16tof32(v4 >> 16)) << 16);') + +# A register whose upper 16 bits are undefined (odd-dmask D16 image_load) can feed a low-half read. +expect('low half of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(v2) * F(v3) + F(v4));', low16_only_v={2}) + +# --- refusals ------------------------------------------------------------------------------------- +expect_refused('high half of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]', low16_only_v={2}) +expect_refused('binary32 use of a register with undefined upper bits', + encode(MIX_F32, 1, (v2, v3, v4)), + 'v_fma_mix_f32 v1, v2, v3, v4', low16_only_v={2}) +expect_refused('op_sel on a binary32 negated inline 0', + encode(MIX_F32, 1, (v2, v3, ZERO), op_sel=(0, 0, 1), neg=(0, 0, 1)), + 'v_fma_mix_f32 v1, v2, v3, -0 op_sel:[0,0,1]') +expect_refused('op_sel without op_sel_hi (high half of a binary32 source)', + encode(MIX_F32, 1, (v2, v3, v4), op_sel=(1, 0, 0)), + 'v_fma_mix_f32 v1, v2, v3, v4 op_sel:[1,0,0]') +# The binary16 encoding of an inline float on a half source is unverified. The old mixlo/mixhi path +# read the binary32 bits of 1.0 through f16tof32, i.e. 0.0; it is now refused rather than wrong. +expect_refused('inline float on a binary16 source', + encode(MIX_F32, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), + 'v_fma_mix_f32 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') +expect_refused('inline float on a binary16 source of mixlo', + encode(MIXLO_F16, 1, (v2, ONE_F, v4), op_sel_hi=(0, 1, 0)), + 'v_fma_mixlo_f16 v1, v2, 1.0, v4 op_sel_hi:[0,1,0]') +expect('literal on a binary16 source', + encode(MIX_F32, 1, (LITERAL, v3, v4), op_sel_hi=(1, 0, 0), literal=0x3c00), + 'v_fma_mix_f32 v1, 0x3c00, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(f16tof32(0x3c00u) * F(v3) + F(v4));') +# The decoder prints neg on inline 1..64 or a literal as a negative integer. Read as an integer, the +# sign-bit flip is lost (neg on inline 1 is 0x80000001, not 0xffffffff), so these stay refused. +# Inline -1 prints the same text as neg on inline 1, so it is refused too. +expect_refused('neg on inline 1 (binary32)', + encode(MIX_F32, 1, (ONE, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, -1, v3, v4') +expect_refused('inline -1 (same text as neg on inline 1)', + encode(MIX_F32, 1, (MINUS_ONE, v3, v4)), + 'v_fma_mix_f32 v1, -1, v3, v4') +expect_refused('neg on inline 17 (binary32)', + encode(MIX_F32, 1, (SEVENTEEN, v3, v4), neg=(1, 0, 0)), + 'v_fma_mix_f32 v1, -17, v3, v4') +expect_refused('neg on a literal (binary32)', + encode(MIX_F32, 1, (LITERAL, v3, v4), neg=(1, 0, 0), literal=0x3f800000), + 'v_fma_mix_f32 v1, -0x3f800000, v3, v4') + +# Both halves contain normal binary16 numbers: 1.0 in the low word and 2.0 in the high word. +for high, bits in ((0, 0x3c00), (1, 0x4000)): + raw = encode(MIX_F32, 1, (LITERAL, v3, v4), literal=0x40003c00, + op_sel=(high, 0, 0), op_sel_hi=(1, 0, 0)) + suffix = (' op_sel:[1,0,0]' if high else '') + ' op_sel_hi:[1,0,0]' + expect('select literal half %d' % high, raw, + 'v_fma_mix_f32 v1, 0x40003c00, v3, v4' + suffix, + 'v1 = U(f16tof32(0x%04xu) * F(v3) + F(v4));' % bits) + +expect('inline half on a low binary16 source', + encode(MIX_F32, 1, (240, v3, v4), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel_hi:[1,0,0]', + 'v1 = U(0.5 * F(v3) + F(v4));') +expect_refused('unverified high half of inline constant', + encode(MIX_F32, 1, (240, v3, v4), op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)), + 'v_fma_mix_f32 v1, 0.5, v3, v4 op_sel:[1,0,0] op_sel_hi:[1,0,0]') + + +def compile_translated(fxc): + """Compile every translated line in one ps_5_1 entry point; returns FXC's exit status and output.""" + regs = sorted({int(n) for line in translated for n in re.findall(r'\bv(\d+)\b', line)}) + body = ['#define F asfloat', '#define U asuint', + 'uint main(nointerpolation uint4 p : TEXCOORD0) : SV_Target {', + ' uint s5 = p.y;'] + body += [' uint v%d = p.x + %du;' % (r, r) for r in regs] + body += [' ' + line for line in translated] + body += [' return %s;' % ' ^ '.join('v%d' % r for r in regs), '}'] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, 'fma_mix.hlsl') + with open(src, 'w') as fh: + fh.write('\n'.join(body) + '\n') + run = subprocess.run([fxc, '/nologo', '/T', 'ps_5_1', '/E', 'main', '/Fo', os.path.join(d, 'fma_mix.cso'), src], + capture_output=True, text=True) + return run.returncode, (run.stdout + run.stderr).strip() + + +# --- dispatch mode: run the translated lines on a D3D12 device and compare with a CPU reference ---- +# +# The reference decodes each VOP3P word itself (layout in the module docstring), without +# tools/disasm_rdna2.py or gfx2hlsl, and applies the LLVM 15 reading: op_sel_hi = binary16 source, +# op_sel = its high half, abs then neg after widening, clamp = saturate. Inputs have short mantissas, +# so the product and sum are exact in binary32 and binary16, and a fused and an unfused multiply-add +# give the same word. + +INLINE_F32 = {240: 0.5, 241: -0.5, 242: 1.0, 243: -1.0, 244: 2.0, 245: -2.0, 246: 4.0, 247: -4.0} +F32_INPUT = {'v2': 1.25, 'v3': -0.75, 'v4': 3.0, 's5': 0.5} # binary32 reads +F16_INPUT = {'v2': (1.5, -2.5), 'v3': (0.75, 4.0), 'v4': (-1.25, 0.5), 's5': (2.0, -3.0)} # (low, high) +V1_BEFORE = 0x13579bdf # mixlo/mixhi keep one half of the destination +# The -0 case needs a zero product: a +0 addend would give +0, the -0 addend keeps -0. +OVERRIDES = {'negated inline 0 addend keeps a -0 product': {'v2': 0x80000000}} + + +def f32_word(value): + return struct.unpack('= 12 else None + return { + 'op': (w0 >> 16) & 0x7f, 'clamp': (w0 >> 15) & 1, + 'srcs': [w1 & 0x1ff, (w1 >> 9) & 0x1ff, (w1 >> 18) & 0x1ff], + 'op_sel': [(w0 >> (11 + i)) & 1 for i in range(3)], + 'op_sel_hi': [(w1 >> 27) & 1, (w1 >> 28) & 1, (w0 >> 14) & 1], + 'abs': [(w0 >> (8 + i)) & 1 for i in range(3)], + 'neg': [(w1 >> (29 + i)) & 1 for i in range(3)], + 'literal': literal, + } + + +def is_register(src): + return src >= V or src < 106 + + +def register_name(src): + return 'v%d' % (src - V) if src >= V else 's%d' % src + + +def case_inputs(label, fields): + """Register words for one case: each source register gets a value in the format it is read as.""" + words = {'v1': V1_BEFORE} + for src, half in zip(fields['srcs'], fields['op_sel_hi']): + if is_register(src): + name = register_name(src) + if half: + low, high = F16_INPUT[name] + words[name] = f16_word(low) | (f16_word(high) << 16) + else: + words[name] = f32_word(F32_INPUT[name]) + words.update(OVERRIDES.get(label, {})) + return words + + +def source_value(src, half, high, words, literal): + if is_register(src): + word = words[register_name(src)] + elif src == 255: + word = literal + elif src == 128: + return 0.0 + elif src in INLINE_F32: + assert not high, 'the translator refuses the high half of an inline constant' + return INLINE_F32[src] + else: + raise ValueError('source %d has no reference' % src) + if half: + return struct.unpack('> (16 * high)) & 0xffff))[0] + return struct.unpack('> 16)', ')') for line in lines] + changed = [i for i, (a, b) in enumerate(zip(lines, mutated)) if a != b] + control = run_dispatch(dxc, runner, adapter, dispatch_source(rows, mutated), len(rows) * 6, directory, + 'fma_mix_control') + low_reads = [] + for i in changed: + fields = decode_mix(cases[i][1]) + fields['op_sel'] = [0, 0, 0] + low_reads.append(reference(fields, rows[i][1])) + follows = all(control[i * 6 + 5] == want for i, want in zip(changed, low_reads)) + caught = [i for i in changed if control[i * 6 + 5] != expected[i]] + check('%s: control without the high-half shift reads the low half in all %d high-half cases' + % (adapter, len(changed)), bool(changed) and follows) + check('%s: control changes %d of %d high-half results' % (adapter, len(caught), len(changed)), + len(caught) > 0) + + +if len(sys.argv) == 3 and sys.argv[1] == 'fxc': + status, output = compile_translated(sys.argv[2]) + check(f'fxc ps_5_1 compiles all {len(translated)} translated lines', status == 0, output) +elif len(sys.argv) == 5 and sys.argv[1] == 'dispatch': + check_dispatch(*sys.argv[2:]) +elif len(sys.argv) != 1: + print(__doc__) + sys.exit(2) + +if failures: + print(f'FAILED: {len(failures)} check(s): {", ".join(failures)}') + sys.exit(1) +print('all fma_mix checks passed') diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6957344fd2..b8467ed2c3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -4894,34 +4894,85 @@ def note_attr(self, tok, how): self.attrs.setdefault(attr, set()).add(how) return attr, component - def mix(self, ops, mods, high): - """v_fma_mix{lo,hi}_f16: fma of operands that are f32 or f16 halves; the f16 result goes to one half.""" - sel = [0, 0, 0] + def mix(self, ops, mods, dest): + """v_fma_mix_f32 / v_fma_mix{lo,hi}_f16: fma of sources that are binary32 words or binary16 halves. + + Per source (LLVM 15 SelectVOP3PMadMixModsImpl): op_sel_hi set means the source is binary16, and + op_sel set picks its high half. abs, then neg, apply after widening. dest is 'f32', 'lo' or 'hi'. + """ + half, hi, clamp = [0, 0, 0], [0, 0, 0], False for m in mods: - if m.startswith('op_sel_hi:'): - sel = [int(x) for x in m[11:-1].split(',')] - elif m.startswith('op_sel:'): - raise Unsupported('op_sel on fma_mix') - def operand(tok, is_half): - if not is_half or tok in ('-0', '0'): + if m.startswith('op_sel_hi:['): + half = [int(x) for x in m[11:-1].split(',')] + elif m.startswith('op_sel:['): + hi = [int(x) for x in m[8:-1].split(',')] + elif m == 'clamp': + clamp = True + else: + raise Unsupported('fma_mix modifier %s' % m) + + def operand(tok, is_half, is_hi): + if not is_half and is_hi: + raise Unsupported('op_sel on a binary32 fma_mix source %s' % tok) + if tok == '-0': + # neg on inline 0 is -0.0 in either format; f() would print +0.0, which changes a -0 product. + return '(-0.0)' + if not is_half: + if tok.startswith('--') and tok[1:] in FLOATS: + # neg on a negative inline float prints as `--0.5`; `(--0.5)` is an HLSL decrement. + return '(-(%s))' % self.f(tok[1:]) + if re.fullmatch(r'-(\d+|0x[0-9a-fA-F]+)', tok): + # The decoder prints neg on inline 1..64 or a literal as a negative integer, which f() + # reads without the sign-bit flip. Refuse until the decoder resolves it from the encoding. + raise Unsupported('negated integer or literal fma_mix source %s' % tok) return self.f(tok) - return 'f16tof32(%s)' % self.u(tok, low16_only=True) - expr = '%s * %s + %s' % tuple(operand(t, s) for t, s in zip(ops[1:4], sel)) - if 'clamp' in mods: + neg = tok.startswith('-') and not re.match(r'-[\d.]', tok) + if neg: + tok = tok[1:] + absolute = tok.startswith('|') and tok.endswith('|') + if absolute: + tok = tok[1:-1] + r = reg_range(tok) + if tok == '0': + text = '0.0' + elif re.fullmatch(r'0x[0-9a-fA-F]{1,8}', tok): + word = (int(tok, 16) >> (16 if is_hi else 0)) & 0xffff + text = 'f16tof32(0x%04xu)' % word + elif tok == '0.5' and not is_hi: + text = '0.5' + elif r and r[1] == r[2]: + # Only a high-half read needs the upper 16 bits defined. + text = 'f16tof32(%s%s)' % (self.u(tok, low16_only=not is_hi), ' >> 16' if is_hi else '') + else: + raise Unsupported('binary16 fma_mix source %s' % tok) + if absolute: + text = 'abs(%s)' % text + return '(-%s)' % text if neg else text + + # v_fma_mix* is fused, but HLSL may round `a * b` before the add, so binary32 sources with long + # mantissas can differ from the hardware by 1 ULP (same as v_fma_f32 in VEC_F). + expr = '%s * %s + %s' % tuple(operand(*a) for a in zip(ops[1:4], half, hi)) + if clamp: expr = 'saturate(%s)' % expr d = reg_range(ops[0])[1] + if dest == 'f32': + self.set_v(d, 'U(%s)' % expr) + return self.used_v.add(d) - if high: + if dest == 'hi': self.set_v(d, '(v%d & 0xffffu) | (f32tof16(%s) << 16)' % (d, expr)) else: keep_low16 = d in self.low16_only_v self.set_v(d, '(v%d & 0xffff0000u) | f32tof16(%s)' % (d, expr), low16_only=keep_low16) + def op_v_fma_mix_f32(self, ops, mods): + self.mix(ops, mods, 'f32') + def op_v_fma_mixlo_f16(self, ops, mods): - self.mix(ops, mods, False) + self.mix(ops, mods, 'lo') def op_v_fma_mixhi_f16(self, ops, mods): - self.mix(ops, mods, True) + self.mix(ops, mods, 'hi') def cube(self, kind, ops, mods): """v_cube{id,sc,tc,ma}_f32: LLVM's ConstantFoldAMDGCNCubeIntrinsic.