diff --git a/docs/design.md b/docs/design.md index 25fb9a0703..972b132938 100644 --- a/docs/design.md +++ b/docs/design.md @@ -353,7 +353,7 @@ How the generated SPIR-V expects the runtime to work: | `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. | | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | +| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--f16-interp-fallback` without `--bary-fallback` (no per-vertex inputs; the decoded-half read would otherwise drop the computed weights; with `--bary-fallback`, alone or with it, the geometry shader supplies the three vertices' values: "Barycentric fallback" below), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does (RTX 4090, driver 621.24, Windows 11: `runtime/test/shaders/cs_div_fmas_f64.asm`, `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) gives the split 0 instead of 2^-60, while the f32 `cs_fma_fused` fuses 8/8). `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | | `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | @@ -386,7 +386,7 @@ How the generated SPIR-V expects the runtime to work: | Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | -| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | +| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. **Computed I/J pairs** (SHADER-177, row above) need the three vertices' values of the attribute, which are `PerVertexKHR` inputs without the fallback. Under it the attribute is a `Flat` `vec4[3]` at the lowest three consecutive locations no other input uses (its own location is free, since every read of it goes through the array), and the index lists it as `bary_fallback_input.per_vertex` (attribute → first location; `inputs` keeps the attribute's own number, the producer's location). The geometry shader writes vertex k's value into element k at each of the three vertices it emits, so the flat value is the triangle's three values whatever the provoking vertex, and the PS weights them exactly as on the `PerVertexKHR` path: P0 + I·(P1 − P0) + J·(P2 − P0) with the program's I/J. With `--f16-interp-fallback` too (NVIDIA Pascal takes both: `make_game.py` turns it on where `per_vertex_inputs` is false), a computed attribute's 16-bit reads decode these raw words rather than the producer's decoded halves, and it leaves `f16_halves`. On the game's 10,277 PS that use `v_interp` (measured at 4947579), `--bary-fallback` used to refuse 207 (every one of them a computed pair); it now translates all 10,277 (207 with `per_vertex`: 8 with one attribute, 198 with two, 1 with three; the arrays end by location 15), and the geometry shader builds and passes `spirv-val` for all 527 PS that have `bary_fallback_input`. With both fallbacks, 10,011 translate (9,804 before). Every other module is byte-identical to before in all three modes (no fallback, `--bary-fallback`, both). GPU-checked on the GTX 1060 (driver 560.94): `ps_ij_computed` passes through its geometry shader with `LEONIDA_BARY_FALLBACK=1`, with the f16 fallback on (the default there) and off. Checked in `tests/semantic/test_interp_computed_ij.py` (`ComputedIJBaryFallback`: the same values as the `PerVertexKHR` path for every computed form, the f16 pair under both fallbacks, the locations, the geometry shader). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/docs/testing.md b/docs/testing.md index 34cb420af7..342fa76c8b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -440,7 +440,9 @@ llvmpipe and some other drivers. Where the device lacks it those four are skippe To test the fallback that runs them anyway, set `LEONIDA_BARY_FALLBACK=1`, **for both `build.py` and `check.py`** (or for `run_gpu_tests.py`; CI does this on llvmpipe). The shaders are then translated with `--bary-fallback` and drawn through a pass-through geometry shader that supplies the barycentrics (`docs/design.md`, "Barycentric -fallback"), so the device needs geometry shaders instead. +fallback"), so the device needs geometry shaders instead. `ps_ij_computed` (a computed I/J pair) also +runs that way: the geometry shader passes it the three vertices' values of the attribute, with or without +`LEONIDA_F16_INTERP_FALLBACK`; only that fallback on its own (Macs) skips it. `ps_interp_f16_high` and `ms_f16_pack` read 16-bit interpolants as `PerVertexKHR` inputs, which need the extension too and which `--bary-fallback` can't express. With `LEONIDA_F16_INTERP_FALLBACK=1` they read halves the producer @@ -584,6 +586,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `check.py`'s `cs_fma_fused` fails on a Mac with MoltenVK 1.4.2: word 7 reads `15360` (`0x3c00`), want `29521` (`0x7351`) | The f16 multiply-add (round to odd). The MSL of 1.4.2 and of MoltenVK `main` differ only in SPIRV-Cross's precise-arithmetic helpers (`[[clang::optnone]]` and `fma(l, r, 0)` against `math_mode(safe)` and `fma(l, r, -0.0)`, the SHADER-182 / SHADER-234 change) | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` | | `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | | With `LEONIDA_W64_EMULATE=1` on llvmpipe, the `ms_*` tests fail. Measured with Mesa 26.3.1: on x86_64 at 256-bit vectors (the default there) all six abort with "LLVM ERROR: Cannot emit physreg copy instruction"; on arm64 (128-bit) `ms_tri` draws nothing (the frame stays at the clear color); on x86_64 at 128 bits (`LP_NATIVE_VECTOR_WIDTH=128`) `ms_tri` happened to draw correctly, but with Mesa 26.0.3 `ms_wave_info_s3` and `ms_v5_workgroup` draw nothing there (4 of 6 pass, [measured by @TreXito](https://github.com/ItsNotRexed/Leonida/pull/3838#issuecomment-7086696759)) ([measured runs](https://github.com/ItsNotRexed/Leonida/issues/3127#issuecomment-7086469679)) | An llvmpipe bug: a mesh shader's runtime `CullPrimitiveEXT` is stored through an invalid `bitcast to ` (TEST-782, #3127; see "Without a GPU: Mesa llvmpipe") | Run the mesh tests on llvmpipe without `LEONIDA_W64_EMULATE`, or add `LEONIDA_MESH_COMPUTE=1` (the compute fallback): with it all 6 `ms_*` pass emulated on llvmpipe (x86_64, 256-bit) | +| `ps_ij_computed` is skipped on a Mac, with or without `LEONIDA_BARY_FALLBACK=1` ("computed I/J pairs need per-vertex inputs", or `unsupported: no geometryShader`) | A computed I/J pair needs the three vertices' values of the attribute: `PerVertexKHR` inputs, or under `--bary-fallback` the geometry shader that passes them (`docs/design.md`, "Barycentric fallback"). MoltenVK has neither, and `--f16-interp-fallback` alone has no per-vertex inputs | Expected; nothing to do. Devices with geometry shaders (NVIDIA Pascal, for one) run it with `LEONIDA_BARY_FALLBACK=1` | | On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | A pixel shader exporting non-canonical f32 NaNs reads back `0x7fc00000` from an RGBA32F color attachment | KosmicKrisp (Mesa 26.3.1), reproduced on Apple M3 Max, M2 Ultra and M1 Pro ([#3125](https://github.com/ItsNotRexed/Leonida/issues/3125)): `nir_to_msl` emits `(NAN)` for `float`-typed NaN constants (`MESA_KK_DEBUG=msl`); MoltenVK 1.4.2 preserved both tested payloads on the same hardware | `ps_nan_payload` allows the measured canonical word only for the NaN channels and only when `vk_harness` reports `driver: KosmicKrisp`. Finite channels and other drivers still require exact words. Integer or storage-buffer readback still canonicalizes constants that NIR infers as `float` (see the `cs_bvh` row below). | | `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words | diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index c9fd70e4a0..42746bed89 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -22,8 +22,9 @@ With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and each gets a pass-through geometry shader, .bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). With the variable unset, build.py/check.py follow the Mesa ANV probe automatically. -Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR -inputs, and check.py reports it as SKIP. +A PS with a computed I/J pair (ps_ij_computed) also reads the three vertices' values of the attribute through that +geometry shader. Under LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs the +per-vertex values, which that fallback doesn't have, and check.py reports it as SKIP. With LEONIDA_PC_TAIL_UBO=1, every shader is translated with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the heap base and code base in a uniform block at set 1), for devices whose maxPushConstantsSize is 128; set it for check.py too, whose test programs then bind that block (runtime/test/vk_pc_tail.h). @@ -45,7 +46,7 @@ MC = mc_command.mc_command() RSRC2, GROUP = 0x8088, (64, 1, 1) -# Not built under LEONIDA_BARY_FALLBACK=1 or LEONIDA_F16_INTERP_FALLBACK=1 (see main). +# Not built under LEONIDA_F16_INTERP_FALLBACK=1 (see main). NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",) sys.path.insert(0, HERE) # this script is also run with python -I from compute_fixture import compute_header, shift_user_data, user_data_shift # noqa: E402 @@ -224,12 +225,13 @@ def main(): if skipped: print("not built (need a DXBC container with signatures):", ", ".join(skipped)) names = [n for n in names if n not in skipped] - # A computed I/J pair needs PerVertexKHR inputs, which both fallbacks take away: the translator refuses it there, - # and check.py and run_gpu_tests.py report it as SKIP. Leave it out instead of losing the whole batch. - if barycentric_fallback() or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": + # A computed I/J pair needs the three vertices' values, which --f16-interp-fallback doesn't have (--bary-fallback + # gets them from its geometry shader): the translator refuses it there, and check.py and run_gpu_tests.py report + # it as SKIP. Leave it out instead of losing the whole batch. + if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" and not barycentric_fallback(): per_vertex = [n for n in names if n in NEEDS_PER_VERTEX_INPUTS] if per_vertex: - print("not built (computed I/J pairs need PerVertexKHR inputs, off under the fallback):", + print("not built (computed I/J pairs need per-vertex inputs, off under --f16-interp-fallback):", ", ".join(per_vertex)) names = [n for n in names if n not in per_vertex] if not names: diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 9be55b3667..907825937c 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -374,7 +374,8 @@ def heap_init_env(): # LEONIDA_BARY_FALLBACK=1/0 overrides the device probe for raw barycentrics. Unset, Mesa ANV selects the fallback. BARY_FALLBACK = barycentric_fallback() # LEONIDA_F16_INTERP_FALLBACK=1 (as build.py reads it): *_f16 interps were translated from decoded-half inputs, with no -# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there. +# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there. (--bary-fallback +# translates it: its geometry shader passes the three vertices' values.) F16_HALVES = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), @@ -1664,9 +1665,9 @@ def nan_payload_problem(px, out): def pixel_test(tools, spirv, name): path = os.path.join(spirv, name + ".spv") - if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair (no .spv). - return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)") + if name == "ps_ij_computed" and F16_HALVES and not BARY_FALLBACK: + # Before the .spv check: without per-vertex inputs the translator refuses a computed I/J pair (no .spv). + return Skip("SKIP (computed I/J pairs need per-vertex inputs: --f16-interp-fallback without --bary-fallback)") if not os.path.isfile(path): return f"missing {name}.spv" if name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"): diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 3e4b17ffa9..8b63945885 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -956,11 +956,12 @@ def run_suite(a, work: str) -> int: for fname in asm_files: name = os.path.splitext(fname)[0] spv = os.path.join(spirv_dir, f"{name}.spv") - if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there - # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). - results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: " - "no --bary-fallback / --f16-interp-fallback)")) + if name == "ps_ij_computed" and f16_interp_fallback() and not bary_fallback(): + # Before the .spv check: without per-vertex inputs the translator refuses a computed I/J pair, so there + # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). Under + # --bary-fallback the geometry shader passes the three vertices' values, so it runs. + results.append((name, None, "SKIP (computed I/J pairs need per-vertex inputs: " + "--f16-interp-fallback without --bary-fallback)")) continue if not os.path.isfile(spv): results.append((name, False, "missing .spv (translation failed)")) diff --git a/tests/semantic/support.py b/tests/semantic/support.py index 950890271e..dd8032fbbd 100644 --- a/tests/semantic/support.py +++ b/tests/semantic/support.py @@ -72,12 +72,14 @@ def mrt0_words(spvasm, **run_options): def varyings(spvasm, attrs, bary): """Input values for a translated PS, given {attribute n: three per-vertex vec4s of the producer's raw 32-bit words} and the barycentric weights `bary` of vertices 0..2, as Vulkan hands them over: a PerVertexKHR input gets - the three vertices, a Flat one vertex 0, any other the words read as f32 and interpolated; %bary gets `bary`.""" + the three vertices, a Flat one vertex 0, any other the words read as f32 and interpolated; %bary gets `bary`. + A Flat vec4[3] (--bary-fallback's per-vertex attribute) gets the three vertices, as its geometry shader writes + them.""" f = lambda w: struct.unpack("/spirv: a module and an index entry per shader it validated.""" self.asked.append(list(names)) - fallback = any(os.environ.get(v) == "1" for v in FALLBACKS) + fallback = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" and os.environ.get("LEONIDA_BARY_FALLBACK") != "1" spirv = Path(work) / "spirv" spirv.mkdir(parents=True) index = {} @@ -79,17 +80,24 @@ def run_build(self, names, env): status = e.code return status, stdout.getvalue() - def test_each_fallback_builds_the_rest_without_ps_ij_computed(self): - for var in FALLBACKS: - with self.subTest(fallback=var): + def test_the_f16_fallback_builds_the_rest_without_ps_ij_computed(self): + status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_F16_INTERP_FALLBACK": "1"}) + self.assertEqual(status, 0, printed) + self.assertEqual(self.asked, [["cs_store"]]) + self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) + self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) + self.assertIn("ps_ij_computed", printed) + self.assertIn("per-vertex inputs", printed) + + def test_the_bary_fallback_builds_ps_ij_computed(self): + for env in ({"LEONIDA_BARY_FALLBACK": "1"}, {"LEONIDA_BARY_FALLBACK": "1", "LEONIDA_F16_INTERP_FALLBACK": "1"}): + with self.subTest(env=env): self.fresh() - status, printed = self.run_build(["cs_store", "ps_ij_computed"], {var: "1"}) + status, printed = self.run_build(["cs_store", "ps_ij_computed"], env) self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store"]]) - self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) - self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) - self.assertIn("ps_ij_computed", printed) - self.assertIn("PerVertexKHR", printed) + self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) + self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) + self.assertNotIn("not built (computed", printed) def test_the_whole_list_builds_under_a_fallback(self): # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty /spirv. diff --git a/tools/bary_fallback_gs.py b/tools/bary_fallback_gs.py index 19203b0ef2..8048e045ca 100644 --- a/tools/bary_fallback_gs.py +++ b/tools/bary_fallback_gs.py @@ -8,6 +8,10 @@ vertices. Default (perspective) interpolation of those gives the perspective-correct barycentrics, the value BaryCoordKHR has, so the pixel shader's .y/.z are AMD's i/j. +An attribute a computed I/J pair reads (SHADER-177) is listed in "bary_fallback_input" under "per_vertex", with the +first of three locations: the geometry shader writes the three vertices' values of the attribute there, as a Flat +vec4[3] (element k = vertex k) at every vertex it emits, which the pixel shader weights with its own I/J. + python -I tools/bary_fallback_gs.py # .bary_gs.spv per such PS in index.json python -I tools/bary_fallback_gs.py --pair VS PS @@ -28,14 +32,24 @@ SUFFIX = ".bary_gs" # .bary_gs.spvasm / .spv next to the pixel shader -def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0): +def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0, per_vertex=None): """SPIR-V assembly for a triangle pass-through GS: Position and the vec4 inputs at `locations`, copied per vertex, - plus the one-hot barycentric vec3 at `bary_location`.""" - locations = sorted(set(int(n) for n in locations)) + plus the one-hot barycentric vec3 at `bary_location`. `per_vertex` maps an attribute (an input location) to the + first of three output locations that get its three vertices' values as a Flat vec4[3] instead of a copy.""" + per_vertex = {int(n): int(b) for n, b in (per_vertex or {}).items()} + locations = sorted(set(int(n) for n in locations) - set(per_vertex)) if bary_location in locations: raise ValueError(f"bary location {bary_location} collides with a pass-through location") + claimed = set(locations) | {int(bary_location)} + for n, b in sorted(per_vertex.items()): + block = {b, b + 1, b + 2} + if b < 0 or block & claimed: + raise ValueError(f"per-vertex locations {b}..{b + 2} of attribute {n} collide with another output") + claimed |= block ins = [f"%in{n}" for n in locations] outs = [f"%out{n}" for n in locations] + pv_ins = [f"%pvin{n}" for n in sorted(per_vertex)] + pv_outs = [f"%pvout{n}" for n in sorted(per_vertex)] if type(clip_count) is not int or not 0 <= clip_count <= 8: raise ValueError("clip distance count must be an integer from 0 to 8") if type(cull_count) is not int or not 0 <= cull_count <= 8: @@ -46,7 +60,7 @@ def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0 kind = "cull" if cull_count else "clip" builtin = kind.title() + "Distance" distance_iface = [f"%in_{kind}", f"%out_{kind}"] if count else [] - iface = " ".join(["%in_pos", "%out_pos", *ins, *outs, "%out_bary", *distance_iface]) + iface = " ".join(["%in_pos", "%out_pos", *ins, *outs, *pv_ins, *pv_outs, "%out_bary", *distance_iface]) lines = [ "OpCapability Geometry", *([f"OpCapability {builtin}"] if count else []), @@ -62,6 +76,9 @@ def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0 if count else []), *[f"OpDecorate %in{n} Location {n}" for n in locations], *[f"OpDecorate %out{n} Location {n}" for n in locations], + *[f"OpDecorate %pvin{n} Location {n}" for n in sorted(per_vertex)], + *[d for n, b in sorted(per_vertex.items()) + for d in (f"OpDecorate %pvout{n} Location {b}", f"OpDecorate %pvout{n} Flat")], f"OpDecorate %out_bary Location {int(bary_location)}", "%void = OpTypeVoid", "%fn = OpTypeFunction %void", @@ -76,6 +93,7 @@ def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0 "%ptr_in_v4 = OpTypePointer Input %v4float", "%ptr_out_v4 = OpTypePointer Output %v4float", "%ptr_out_v3 = OpTypePointer Output %v3float", + *(["%ptr_out_arr = OpTypePointer Output %arr"] if per_vertex else []), *([f"%{kind}_count = OpConstant %uint {count}", f"%{kind} = OpTypeArray %float %{kind}_count", f"%triangle_{kind} = OpTypeArray %{kind} %uint_3", @@ -92,6 +110,8 @@ def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0 "%out_pos = OpVariable %ptr_out_v4 Output", *[f"{v} = OpVariable %ptr_in_arr Input" for v in ins], *[f"{v} = OpVariable %ptr_out_v4 Output" for v in outs], + *[f"{v} = OpVariable %ptr_in_arr Input" for v in pv_ins], + *[f"{v} = OpVariable %ptr_out_arr Output" for v in pv_outs], "%out_bary = OpVariable %ptr_out_v3 Output", *([f"%in_{kind} = OpVariable %ptr_in_triangle_{kind} Input", f"%out_{kind} = OpVariable %ptr_out_{kind} Output"] if count else []), @@ -103,6 +123,11 @@ def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0 p, x = f"%p{v}_{src[1:]}", f"%x{v}_{src[1:]}" lines += [f"{p} = OpAccessChain %ptr_in_v4 {src} %int_{v}", f"{x} = OpLoad %v4float {p}", f"OpStore {dst} {x}"] + for src, dst in zip(pv_ins, pv_outs): # the triangle's three values, the same at every vertex + for k in range(3): + p, x, q = f"%p{v}_{src[1:]}_{k}", f"%x{v}_{src[1:]}_{k}", f"%q{v}_{dst[1:]}_{k}" + lines += [f"{p} = OpAccessChain %ptr_in_v4 {src} %int_{k}", f"{x} = OpLoad %v4float {p}", + f"{q} = OpAccessChain %ptr_out_v4 {dst} %int_{k}", f"OpStore {q} {x}"] if count: lines += [f"%{kind}_ptr{v} = OpAccessChain %ptr_in_{kind} %in_{kind} %int_{v}", f"%distances{v} = OpLoad %{kind} %{kind}_ptr{v}", f"OpStore %out_{kind} %distances{v}"] @@ -154,7 +179,7 @@ def distance_count(kind): if not fb: continue path = os.path.join(spirv_dir, name + SUFFIX + suffix + ".spvasm") - shader = gs_spvasm(meta.get("inputs", []), fb["location"], clip_count, cull_count) + shader = gs_spvasm(meta.get("inputs", []), fb["location"], clip_count, cull_count, fb.get("per_vertex")) yield path, shader diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 4680062ace..038934e2b8 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -62,6 +62,11 @@ # VK_KHR_fragment_shader_barycentric. Whatever feeds the stage before the PS (a pass-through geometry shader) writes # (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices; interpolating those gives the perspective-correct # barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. +# An attribute a computed I/J pair reads (SHADER-177), which needs the three vertices' values, is a Flat vec4[3] +# input instead of PerVertexKHR, at three consecutive locations no other input uses ("per_vertex" in +# bary_fallback_input: attribute -> first location). The geometry shader writes vertex k's value of the attribute +# into element k at every vertex it emits, so the flat value is the triangle's three values whatever the provoking +# vertex; Gen.attribute then weights them as on the PerVertexKHR path. BARY_FALLBACK = False SHADER_CLOCK = False FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma @@ -258,6 +263,7 @@ def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): self.inputs = {} self.interpolated = set() # inputs read through v_interp_p1/p2; the rest are flat (v_interp_mov only) self.per_vertex = set() # PS: attribute numbers read by a *_f16 interp: PerVertexKHR, decoded per half + self.pv_fallback = {} # PS under --bary-fallback: per-vertex attribute -> first location of its vec4[3] self.f16_halves = set() # PS, --f16-interp-fallback: the same attributes, read from decoded-half inputs self.f16_half_locs = {} # PS/VS/MS, --f16-interp-fallback: attr/param n -> (low_loc, high_loc) self.param_max = -1 # VS/MS: the highest exp paramN (--f16-interp-fallback keeps halves above it) @@ -13559,6 +13565,11 @@ def pair_value(self, r): self.emit(f"{t} = OpBitcast %float {u}") return t + def pv_input(self, name): + """Whether input variable `name` is an attribute read per vertex (a vec4[3]: PerVertexKHR, or Flat under + --bary-fallback). By attribute number, since --bary-fallback moves such an input off its own location.""" + return name.startswith("%in_attr") and int(name[len("%in_attr"):]) in self.per_vertex + def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). @@ -14630,8 +14641,19 @@ def assemble(gen): if k.startswith("%in_f16h"): a_str, h_str = k[len("%in_f16h"):].split("_") gen.inputs[k] = gen.f16_half_locs[int(a_str)][int(h_str)] - used = set(gen.inputs.values()) - if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute + gen.pv_fallback = {} + if BARY_FALLBACK and gen.per_vertex: + # The per-vertex attributes become Flat vec4[3] inputs, each at the lowest three consecutive locations no + # other input uses (their own location is free: every read of such an attribute goes through the array). + taken = {v for k, v in gen.inputs.items() if not (k.startswith("%in_attr") and int(k[8:]) in gen.per_vertex)} + taken |= {loc for pair in gen.f16_half_locs.values() for loc in pair} + for n in sorted(gen.per_vertex): + base = next(b for b in range(len(taken) + 3) if not {b, b + 1, b + 2} & taken) + gen.pv_fallback[n] = base + gen.inputs[f"%in_attr{n}"] = base + taken |= {base, base + 1, base + 2} + used = set(gen.inputs.values()) | {b + k for b in gen.pv_fallback.values() for k in (1, 2)} + if len(set(gen.inputs.values())) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a # raw attribute at the location of a half this shader doesn't read is overwritten all the same. @@ -14798,7 +14820,9 @@ def assemble(gen): dec.append(f"OpDecorate {name} Location {int(''.join(ch for ch in tgt if ch.isdigit()))}") for name, n in gen.inputs.items(): dec.append(f"OpDecorate {name} Location {n}") - if n in gen.per_vertex: + if gen.pv_input(name) and gen.pv_fallback: + dec.append(f"OpDecorate {name} Flat") # --bary-fallback: the geometry shader's vec4[3] (BARY_FALLBACK) + elif gen.pv_input(name): dec.append(f"OpDecorate {name} PerVertexKHR") elif name not in gen.interpolated: dec.append(f"OpDecorate {name} Flat") @@ -15128,8 +15152,8 @@ def assemble(gen): gvars += ["%out_viewport = OpVariable %_ptr_Output_int Output"] if gen.per_vertex: # the three vertices' raw words for Gen.attribute types += [f"%arr_pv4 = OpTypeArray %v4float {gen.cu(3)}", "%_ptr_Input_pv4 = OpTypePointer Input %arr_pv4"] - gvars += [f"{n} = OpVariable {'%_ptr_Input_pv4' if k in gen.per_vertex else '%_ptr_Input_v4'} Input" - for n, k in gen.inputs.items()] + gvars += [f"{n} = OpVariable {'%_ptr_Input_pv4' if gen.pv_input(n) else '%_ptr_Input_v4'} Input" + for n in gen.inputs] if sg: gvars += ["%sg_lane = OpVariable %_ptr_Input_uint Input"] if tex: @@ -16062,10 +16086,9 @@ def partner(k, s): if s["src"] in (0, 1): g.frag_inputs[s["src"]] = ("bary_i", "bary_j")[s["src"]] attrs.add(s["attr"]) - if attrs and BARY_FALLBACK: - raise Unsupported("computed I/J pair under --bary-fallback: no PerVertexKHR inputs") - if attrs and F16_HALVES: - # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either + if attrs and F16_HALVES and not BARY_FALLBACK: + # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either. With + # --bary-fallback as well (NVIDIA Pascal), the geometry shader passes the three vertices' raw words instead. raise Unsupported("computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs") return attrs @@ -16665,7 +16688,9 @@ def translate(path): attr_reads[op].update(arg["a"] for arg in ins["args"] if arg["k"] == "attr") f16_read = attr_reads["v_interp_p1ll_f16"] | attr_reads["v_interp_p1lv_f16"] | attr_reads["v_interp_p2_f16"] mixed_f32 = attr_reads["v_interp_mov_f32"] & (attr_reads["v_interp_p1_f32"] | attr_reads["v_interp_p2_f32"]) - if mixed_f32 and (BARY_FALLBACK or F16_HALVES): + # Under --bary-fallback an attribute that a computed I/J pair also reads is a per-vertex array all the same + # (interp_ij_analysis below), whose element 0 is P0 for the MOV; the other mixed attributes are refused there. + if mixed_f32 and F16_HALVES and not BARY_FALLBACK: raise Unsupported("flat and interpolated reads of one f32 attribute need per-vertex inputs") mov_delta = {x["a"] for i in insns if base_op(i["op"]) == "v_interp_mov_f32" and any(x.get("k") == "interp" and x.get("t") in ("p10", "p20") for x in i["args"]) @@ -16733,7 +16758,13 @@ def translate(path): g.v_interp_copy = interp_copy_sources(insns) # before v_interp runs: I/J guards (SHADER-177) # SHADER-177: annotate v_interp sites whose I/J operand is a computed pair, and let those # attributes be read per-vertex (attribute() weights them with the operand values). - g.per_vertex |= interp_ij_analysis(insns, g) + computed = interp_ij_analysis(insns, g) + g.per_vertex |= computed + # --bary-fallback with --f16-interp-fallback: a computed attribute's f16 reads decode the per-vertex raw + # words (Gen.attribute) rather than the producer's decoded halves. + g.f16_halves -= computed + if BARY_FALLBACK and mixed_f32 - computed: + raise Unsupported("flat and interpolated reads of one f32 attribute need per-vertex inputs") if any("ij" in i for i in insns): # Computed v_interp sites load their I/J VGPRs at runtime; no_bary above stripped all # v_interp sources, so an untouched (or conditionally/EXEC-masked written) v0/v1 still @@ -17681,11 +17712,16 @@ def shader_meta(g, asm, src_path=None, fssm_path=None): if g.writes_depth: m["writes_depth"] = True if g.inputs: - m["inputs"] = sorted(g.inputs.values()) + # The locations the PS reads; under --bary-fallback a per-vertex attribute is listed by its own number (the + # producer's location), and bary_fallback_input says where the geometry shader puts it. + m["inputs"] = sorted(int(k[len("%in_attr"):]) if g.pv_input(k) else v for k, v in g.inputs.items()) if getattr(g, "bary_location", None) is not None: # --bary-fallback: the raw barycentrics are a perspective-interpolated vec3 at this location; the stage # before the PS must write (1,0,0), (0,1,0), (0,0,1) at the triangle's vertices (see BARY_FALLBACK). m["bary_fallback_input"] = {"location": g.bary_location} + if g.pv_fallback: + # Computed I/J pairs: attribute -> first of the three locations of its Flat vec4[3] (BARY_FALLBACK) + m["bary_fallback_input"]["per_vertex"] = {str(n): b for n, b in sorted(g.pv_fallback.items())} if F16_HALVES and g.stage in ("vs", "ms", "ps"): # --f16-interp-fallback: PS = the attributes whose f16 reads take decoded halves, VS/MS = the params that # export them; each as {n: [low-half location, high-half location]}. When a PS's canonical half slots would