diff --git a/docs/design.md b/docs/design.md index fa7e34a4eb..b4bb36f9af 100644 --- a/docs/design.md +++ b/docs/design.md @@ -406,7 +406,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 CPU interpreter check both reads at two points of one triangle. [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, and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Without PerVertexKHR inputs a pair is still translated: under `--bary-fallback` (alone or with `--f16-interp-fallback`) the geometry shader supplies the three vertices' values ("Barycentric fallback" below), and under `--f16-interp-fallback` alone they come from quad derivatives ("Computed I/J barycentrics without `PerVertexKHR`" below). 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. The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). 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 on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--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). | @@ -441,7 +441,7 @@ How the generated SPIR-V expects the runtime to work: | 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.** | | Wave64 emulation: cross-lane reads of missing lanes | With `--wave64-emulate`, a read of another lane's exchange slot (`ds_swizzle_b32`, `ds_bpermute_b32`, `ds_permute_b32`'s targets and data, `v_readlane_b32`, `v_readfirstlane_b32`, DPP and the other reads behind `Gen.x_round`) gives 0 when the source lane doesn't exist in a partial last wave (`Gen.x_lane_word`: `x_wbase + lane < threads`, else 0), as a source lane that isn't running reads 0 on the hardware. The prologue still zeroes those slots, but a read must not depend on it: RADV (Mesa 26.3.1, gfx1036 iGPU and RX 7900 XTX) compiled the store, barrier and load of an exchange behind a branch into `masked_swizzle_amd` with `fetch_inactive` (`RADV_DEBUG=shaders`), so in a 40-thread group lanes 32-39 of `ds_swizzle_b32 offset:swizzle(SWAP,8)` read the missing lanes' registers, garbage that changed between runs. Workgroups whose size is a multiple of 64 emit the same module as before. Confirmed by `runtime/test/shaders/cs_w64x_partial_swizzle.asm` (40 threads: SWAP 8, BROADCAST 16,15 and `ds_bpermute_b32` from lanes 40-47; its 8 words measured natively on gfx1036 through `tools/hw_oracle`): emulated at subgroup 32 (RADV, Mesa 26.3.1), words 2 and 3 wrong before in 20 of 20 runs on the gfx1036 iGPU and 19 of 20 on the RX 7900 XTX, and all 8 words right in 20 of 20 runs on both after; native wave64 and emulated at subgroup 64 right both times. `scripts/run_gpu_tests.py` runs the partial-wave fixtures emulated at subgroup 32, as `check.py` does, since at RADV's default of 64 this fixture passed before the change too; by `crosslane_fuzz.py --wave 64 --ext --dpp --no-maskdata --programs 1000 --seed 48315`, emulated: on the gfx1036 iGPU 993 match and 7 hyp_only (all 40-thread groups, lanes 32-39 reading a swizzle source of 40-47) before, 1000/1000 after, and on the RX 7900 XTX 995 match and 5 hyp_only before, 1000/1000 after; and by `tests/semantic/test_w64x_partial_swizzle.py` (fixture `w64x_partial_swizzle.asm`, 40 and 104 threads, the prologue's zero stores replaced by a poison word in the workgroup interpreter; both cases fail before the change). | -| 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. `make_game.py` also selects it, together with `--f16-interp-fallback`, when the GPU has geometry shaders but `per_vertex_inputs` is false (no `fragmentShaderBarycentric`; #1285). A GPU without a geometry stage (MoltenVK) stays on `--f16-interp-fallback` alone. `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`. The runtime builds the same stage itself when a graphics PSO is created (`build_bary_fallback_gs` in `runtime/src/spirv_bary_fallback.h`, RT-BARY-FALLBACK-PER-VERTEX): it reads `per_vertex` from the index entry and writes the three vertices' values of each mapped attribute to its `Flat` `vec4[3]`, zero-filling an attribute the VS does not export. After `--f16-interp-fallback` linking it forwards only an output the VS exported before linking, so a decoded half that linking placed on a missing attribute's Location is not read as that attribute, and linking keeps halves off all three Locations of a block. A `vec4[3]` input the map does not name, or a block that runs into another input, is refused. Checked on the CPU by `spirv_bary_fallback` (the modules pass `spirv-val`) and on a GPU by `d3d12_bary_fallback`, which draws a synthetic computed-I/J PS with the block at its first locations and relocated next to an ordinary input (RTX 3060, NVIDIA 621.24, Windows 11, validation on: all 256 pixels of both draws; the same weights on any other order of the vertices would be at least 15 LSB away). **Unverified:** the game's 207 PS through the runtime builder, and a GPU that needs the fallback (this one has `fragmentShaderBarycentric`). 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). | | Wave64 emulation: a folded region at most one lane runs (SHADER-W64-ONE-LANE-FOLD) | A compute shader picks one thread for a tail (clear LDS, then after a barrier sum it up and store) with `v_cmpx_eq_u32 c, v0` or `v_cmp_eq_u32 m, c, v0` + `s_and_saveexec_b64 _, m`. `v0` is LocalInvocationId.x and a wave is 64 consecutive threads, so no two lanes of a wave share it when the group is one row (`size_y * size_z == 1`) or a row is whole waves (`size_x % 64 == 0`); then the compare is true in at most one lane. `_one_lane_in` in `tools/wave64_emulate_opt.py` proves per block, forward over the CFG with intersection at joins, that EXEC is at most one lane: `v0` must not have been written since entry, and the mask goes on through `s_mov_b64`, `s_and_b64` with anything, `s_andn2_b64` of it, a saveexec of it and any later compare (a compare is 0 in inactive lanes). A write of one half of EXEC (`exec_lo`/`exec_hi`, which the emitter writes as that half only) keeps the fact only when EXEC already had it and the half written is within it (a compare): the other half keeps its lanes, so `v_cmp_eq_u32 exec_lo, 0, v0` from a full EXEC leaves lanes 32-63 on. The assembler's short form `v_add_co_ci_u32 vD, src0, src1` (also `sub`, `subrev`) gets its VCC carry-out and carry-in operands when the listing is read (`explicit_carry_vcc` in `tools/rdna2spirv.py`), so every analysis sees the VCC it writes. Where `run` of an `s_cbranch_execz` region is proved so, `find_local_exec_folds` drops the one-store-per-domain and acyclic limits and marks the fold `one_lane` (the region's EXEC writes already must keep a skipped lane inactive, so it stays at most one lane): with one lane the lane's own order of its accesses is the wave's, so `x_memory_order` orders nothing inside it. A one-block region that branches back to itself is emitted as a loop through `cfg_structure.structure` like a multi-block region; emitted straight it ran once (also for a read-only loop, before this row). A `v_readfirstlane_b32` is allowed in such a fold when the region writes no EXEC at all: the lane runs the fold only when active, so it is the first lane of EXEC and the result is its own value (also into `vcc_lo`/`vcc_hi`). Confirmed on the CPU against the plain round emulation in both invocation orders: `tests/semantic/test_wave64_one_lane_fold.py` (128 threads; LDS writes, a barrier, first-lane reads and two stores to one address; a lane of wave 0, of wave 1, or none; the negatives `v_cmpx_eq` of a non-id VGPR, `v0` overwritten, `v_cmpx_gt`, and a 32 x 4 group are not marked one-lane; picks in lanes 32-63 of either wave; a one-block self-loop with and without a store, which ran once before; `v_cmp_eq_u32_e64 exec_lo, 0, v0` from a full EXEC, which was marked one-lane before; and the short and explicit `v_add_co_ci_u32` carry into VCC after a one-lane compare, whose short form was marked one-lane before). One 1024-thread library compute shader goes from 639 to 33 `OpSwitch` cases and passes `spirv-val`. **Not GPU-verified.** | | 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. | @@ -529,7 +529,7 @@ How the generated SPIR-V expects the runtime to work: | `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | | 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as the hardware does: the delta P1 − P0 (and P2 − P0) is rounded to f16 first — the SPI's P10/P20 words for a 16-bit channel are per-half f16 differences, measured below — and P0 + i·P10 + j·P20 is summed in f32 with i, j = `BaryCoordKHR`.y/.z (f32, not f16) before p2 clamps and narrows toward zero. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator sums P0 + i·P10 + j·P20 in f32 and narrows toward zero — SHADER-468: the driver's ISA runs the pair inside `s_round_mode 0x000c`, so the narrow is toward zero whatever the shader's own MODE writes are) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Measured on AMD hardware (SHADER-468, `tools/f16_interp_probe.py`; native 64×64 draws of a hand-written `f16vec2` varying through `vk_harness` on the Ryzen 5 7600 iGPU, gfx1036, AMD Windows driver 24.10.24, Vulkan 1.3.280; 12 draws, six value sets × orthographic and perspective, 98,304 samples):** the SPI writes P10/P20 as f16 differences of the two halves (round to nearest even) — a pair whose difference is 66,504, past the largest f16, interpolates to inf where the f32 difference stays finite — the sum is f32 (an f16 sum misses 11,385 of the 98,304 samples) and `v_interp_p2_f16` narrows **toward zero** (nearest even misses 36,078). The f16-delta model explains 98,274 of 98,304 samples, against 89,993 for the same model without the f16 delta, 86,919 for an f16 sum and 62,226 for nearest-even narrowing; until 2026-11-22 the translation used the f32 difference and nearest even, which is what the last number measures. The narrow follows MODE.FP16_ROUND, which every AMD compiler sets toward zero around this pair (LLVM `SIModeRegister`: "f16 interpolation instructions need double precision round to zero"; the Windows driver's ISA runs both ops inside `s_round_mode 0x000c`), so the translated p2 rounds toward zero whatever the shader's own MODE writes are. The weights are the SPI's f32 values, not f16: a perspective triangle (w = 1, 2, 4) quantized to f16 misses most samples, f32 matches. Confirmed by `tests/semantic/test_interp_f16_round.py` (both cases fail on the old translation). **Still unverified:** the 30 misses (26 where the exact value is a few 2^-24 — the hardware gives the smallest f16 subnormal where a plain toward-zero narrow gives zero — and 4 at an exact f16 grid boundary, where the vertex-0 weight is the SPI's own f32 value rather than 1 − i − j), f16 inf/NaN halves and `p1lv_f16`, and what a 32-bit `p1/p2_f32` read of a 16-bit-mode channel returns: with the LDS words holding f16 lanes that read cannot be the f16-rounded smooth value the "Pixel-shader interpolants" row assumes, but no Vulkan or D3D12 shader can ask for 16-bit mode and a 32-bit read of the same attribute, so it stays unmeasured. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | | 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations; native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | -| Computed I/J barycentrics without `PerVertexKHR` (`--f16-interp-fallback`) | Under `--f16-interp-fallback` (without `--bary-fallback`), pixel shaders have no `PerVertexKHR` `[3 x vec4]` attribute arrays (neither Metal/MoltenVK nor devices without `VK_KHR_fragment_shader_barycentric` support them; `tools/vk_subgroup_info.py` sets `per_vertex_inputs: false` there, causing `make_game.py` to pass `--f16-interp-fallback`). Previously, `interp_ij_analysis` in `tools/rdna2spirv.py` raised `Unsupported` on any computed `v_interp_p1/p2` `(I, J)` pair under `--f16-interp-fallback`, refusing all 207 computed-barycentric pixel shaders in the corpus (`26,296 / 26,503`). Neither `InterpolateAtOffset` (`OpCapability InterpolationFunction` requires `sampleRateShading`, which the runtime does not enable, and SPIRV-Cross MSL rejects `interpolate_at_offset` on `BuiltIn BaryCoordKHR`) nor a geometry shader is required: in real arithmetic, because `%bary` (`BuiltIn BaryCoordKHR`) carries perspective-correct barycentrics `(1 − I_c − J_c, I_c, J_c)`, every smooth attribute or decoded f16 half (`%in_attrN` / `%in_f16hN_{lo,hi}`) is affine in `(I, J)` across a 2x2 fragment quad (`P^(q) = P_0 + I^(q) P_10 + J^(q) P_20`) even under perspective foreshortening. `tools/rdna2spirv.py` (`Gen.ij_quad_eval` and `assemble`) declares `OpCapability FragmentBarycentricKHR` + `SPV_KHR_fragment_shader_barycentric` for `%bary` (recording `features: ["fragmentShaderBarycentric"]` in `index.json`, so the device must support `VK_KHR_fragment_shader_barycentric` for `BaryCoordKHR`, though not `PerVertexKHR` compilation: MoltenVK runs it natively, while drivers without `VK_KHR_fragment_shader_barycentric` such as KosmicKrisp skip it) alongside core Vulkan 1.0 `OpCapability DerivativeControl` (which adds no extra `VkPhysicalDeviceFeatures` bit and consumes zero extra `Location` slots), and hoists all `OpDPdxFine` / `OpDPdyFine` evaluations into the uniform `%entry` block (satisfying SPIR-V uniform control flow when `v_interp_p1/p2` sits inside divergent `EXEC` branches): `%entry` computes `(dI_x, dI_y)` and `(dJ_x, dJ_y)` of `%bc.y` / `%bc.z`, the 2x2 screen-quad Jacobian determinant `det = dI_x · dJ_y − dI_y · dJ_x`, and `(P_c, dP_x, dP_y)` for each computed `(input, component)`, while each computed site solves pixel steps `alpha = ((I − I_c) · dJ_y − (J − J_c) · dI_y) / det`, `beta = (dI_x · (J − J_c) − dJ_x · (I − I_c)) / det` and evaluates `P_c + alpha · dP_x + beta · dP_y`. **Shortcut (finite-difference amplification and `det == 0` fallback):** smooth fragment inputs and `BaryCoordKHR` arrive from the rasterizer quantized to binary32 (per-lane residual `\|e_q\| <= 0.5·ulp(P_q) + \|P_10\|·0.5·ulp(I_q) + \|P_20\|·0.5·ulp(J_q)`), and 1-pixel quad differences amplify that rounding by `1 + 2\|alpha\| + 2\|beta\|` (`alpha ~ (I − I_c) / (dI/dx)`, proportional to pixel step up to the primitive's pixel span): sub-pixel barycentric offsets (`\|alpha\|, \|beta\| <= 1` px) stay near input precision (`~2e-6` on `1920x1080` `W = (1, 2.5, 4)`), ~1,000-pixel constant jumps on `[-2.75, 10]` reach `1.09e-3` in IEEE binary32 (`2.04e-3` / `1` f16 ulp at `1.5 → 1.4990234375` on an RTX 4090, `@ecox982745`, NVIDIA `616.64`, #2239), and >1,100-pixel jumps to `(0, 0)` across a `2048`-pixel perspective triangle with `P in [1.5, 4096]` reach `0.358` (`>300` f16 ulps at `1.5`, bounded by `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp`). To guard degenerate zero-area, subnormal, infinite, or NaN determinants without `OpFDiv`-by-zero, `1 / det` overflow, or MoltenVK's `OpFOrdNotEqual` NaN bug (`!=` in SPIRV-Cross MSL), `%entry` checks `0x00800000 <= (OpBitcast_u32(det) & 0x7FFFFFFF) < 0x7F800000` in integer ops (`OpUGreaterThanEqual` / `OpULessThan`), clamping the divisor to `1.0` and returning `P_c` when outside the IEEE-754 normal f32 range (including 1D/line primitives where `J` is constant across the quad, `det == 0`, so computed `I` is ignored in favour of `P_c`). Like the non-computed path, `v_interp_p1lv_f16` takes `P_0` from the interpolated attribute (`vsrc2` is unread; the corpus has `0` computed `*_f16` ops), while `--bary-fallback`, `mixed_f32` (flat + smooth f32 on one location), `v_interp_mov_f32` `p10`/`p20`, and computed 32-bit reads of 16-bit-flagged interpolants remain `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VINTRP) and Khronos SPIR-V 1.3 (`OpDPdxFine`, `OpDPdyFine`, `DerivativeControl`). Confirmed across the full shader corpus: all `207 / 207` previously refused pixel shaders (`1,139` `v_interp_p1_f32` / `v_interp_p2_f32` computed pairs; `0` computed `*_f16` ops, `2` shaders also reading non-computed `*_f16` inputs) translate and pass `spirv-val --target-env vulkan1.2 --allow-offset-texture-operand` under `--f16-interp-fallback`, bringing `--f16-interp-fallback` corpus translation from `26,296 / 26,503` (`99.22%`) to `26,503 / 26,503` (`100%`), while default-flag outputs stay byte-identical across all 207 shaders. Checked on the CPU (`spirv_mini_interp` 2x2 quad evaluation across dyadic weights, `64x64`, `1920x1080`, and `2048`-pixel perspective `w` foreshortening with tight binary64 Jacobian and `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp` error bounds, non-uniform `EXEC`-masked branches, non-`v0`/`v1` operand registers, between-ops `J` writes, `v_interp_p1lv_f16` `vsrc2` invariance, line-primitive `det == 0` / subnormal / `±inf` / `NaN` determinants, and `f16_halves` metadata) and with `spirv-val` by `tests/semantic/test_interp_computed_ij_fallback.py` (`tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm`) and `tests/semantic/test_interp_computed_ij.py`. **GPU-verified through Vulkan** on `Apple M3` (`@EvgHaze`, MoltenVK `1.4.2`, #2239), `Apple M3 Pro` (`@wavehs`, MoltenVK `1.4.0`, #2239), `NVIDIA GeForce RTX 3090` (Windows driver `610.88`, Vulkan `1.4.341`, `VK_LAYER_KHRONOS_validation` `1.4.363`, `LEONIDA_F16_INTERP_FALLBACK=1`, `LEONIDA_BARY_FALLBACK=0`), and `NVIDIA GeForce RTX 5070` (`@lixonik`, Windows driver `610.88`, #2239): `runtime/test/shaders/ps_ij_computed.asm` drawn with `vs_ids` passes `vk_pipeline_check`, `runtime/test/shaders/check.py`, and `scripts/run_gpu_tests.py` (`4,096 / 4,096` pixels exact on RTX 3090/5070 and within `1e-6` natively on MoltenVK, `0` validation errors). | +| Computed I/J barycentrics without `PerVertexKHR` (`--f16-interp-fallback`) | Under `--f16-interp-fallback` (without `--bary-fallback`), pixel shaders have no `PerVertexKHR` `[3 x vec4]` attribute arrays (neither Metal/MoltenVK nor devices without `VK_KHR_fragment_shader_barycentric` support them; `tools/vk_subgroup_info.py` sets `per_vertex_inputs: false` there, causing `make_game.py` to pass `--f16-interp-fallback`). Previously, `interp_ij_analysis` in `tools/rdna2spirv.py` raised `Unsupported` on any computed `v_interp_p1/p2` `(I, J)` pair under `--f16-interp-fallback`, refusing all 207 computed-barycentric pixel shaders in the corpus (`26,296 / 26,503`). Neither `InterpolateAtOffset` (`OpCapability InterpolationFunction` requires `sampleRateShading`, which the runtime does not enable, and SPIRV-Cross MSL rejects `interpolate_at_offset` on `BuiltIn BaryCoordKHR`) nor a geometry shader is required: in real arithmetic, because `%bary` (`BuiltIn BaryCoordKHR`) carries perspective-correct barycentrics `(1 − I_c − J_c, I_c, J_c)`, every smooth attribute or decoded f16 half (`%in_attrN` / `%in_f16hN_{lo,hi}`) is affine in `(I, J)` across a 2x2 fragment quad (`P^(q) = P_0 + I^(q) P_10 + J^(q) P_20`) even under perspective foreshortening. `tools/rdna2spirv.py` (`Gen.ij_quad_eval` and `assemble`) declares `OpCapability FragmentBarycentricKHR` + `SPV_KHR_fragment_shader_barycentric` for `%bary` (recording `features: ["fragmentShaderBarycentric"]` in `index.json`, so the device must support `VK_KHR_fragment_shader_barycentric` for `BaryCoordKHR`, though not `PerVertexKHR` compilation: MoltenVK runs it natively, while drivers without `VK_KHR_fragment_shader_barycentric` such as KosmicKrisp skip it) alongside core Vulkan 1.0 `OpCapability DerivativeControl` (which adds no extra `VkPhysicalDeviceFeatures` bit and consumes zero extra `Location` slots), and hoists all `OpDPdxFine` / `OpDPdyFine` evaluations into the uniform `%entry` block (satisfying SPIR-V uniform control flow when `v_interp_p1/p2` sits inside divergent `EXEC` branches): `%entry` computes `(dI_x, dI_y)` and `(dJ_x, dJ_y)` of `%bc.y` / `%bc.z`, the 2x2 screen-quad Jacobian determinant `det = dI_x · dJ_y − dI_y · dJ_x`, and `(P_c, dP_x, dP_y)` for each computed `(input, component)`, while each computed site solves pixel steps `alpha = ((I − I_c) · dJ_y − (J − J_c) · dI_y) / det`, `beta = (dI_x · (J − J_c) − dJ_x · (I − I_c)) / det` and evaluates `P_c + alpha · dP_x + beta · dP_y`. **Shortcut (finite-difference amplification and `det == 0` fallback):** smooth fragment inputs and `BaryCoordKHR` arrive from the rasterizer quantized to binary32 (per-lane residual `\|e_q\| <= 0.5·ulp(P_q) + \|P_10\|·0.5·ulp(I_q) + \|P_20\|·0.5·ulp(J_q)`), and 1-pixel quad differences amplify that rounding by `1 + 2\|alpha\| + 2\|beta\|` (`alpha ~ (I − I_c) / (dI/dx)`, proportional to pixel step up to the primitive's pixel span): sub-pixel barycentric offsets (`\|alpha\|, \|beta\| <= 1` px) stay near input precision (`~2e-6` on `1920x1080` `W = (1, 2.5, 4)`), ~1,000-pixel constant jumps on `[-2.75, 10]` reach `1.09e-3` in IEEE binary32 (`2.04e-3` / `1` f16 ulp at `1.5 → 1.4990234375` on an RTX 4090, `@ecox982745`, NVIDIA `616.64`, #2239), and >1,100-pixel jumps to `(0, 0)` across a `2048`-pixel perspective triangle with `P in [1.5, 4096]` reach `0.358` (`>300` f16 ulps at `1.5`, bounded by `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp`). To guard degenerate zero-area, subnormal, infinite, or NaN determinants without `OpFDiv`-by-zero, `1 / det` overflow, or MoltenVK's `OpFOrdNotEqual` NaN bug (`!=` in SPIRV-Cross MSL), `%entry` checks `0x00800000 <= (OpBitcast_u32(det) & 0x7FFFFFFF) < 0x7F800000` in integer ops (`OpUGreaterThanEqual` / `OpULessThan`), clamping the divisor to `1.0` and returning `P_c` when outside the IEEE-754 normal f32 range (including 1D/line primitives where `J` is constant across the quad, `det == 0`, so computed `I` is ignored in favour of `P_c`). Like the non-computed path, `v_interp_p1lv_f16` takes `P_0` from the interpolated attribute (`vsrc2` is unread; the corpus has `0` computed `*_f16` ops), while `mixed_f32` (flat + smooth f32 on one location), `v_interp_mov_f32` `p10`/`p20`, and computed 32-bit reads of 16-bit-flagged interpolants remain `Unsupported` (with `--bary-fallback` the computed pair takes the geometry shader's per-vertex values instead: "Barycentric fallback"). Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VINTRP) and Khronos SPIR-V 1.3 (`OpDPdxFine`, `OpDPdyFine`, `DerivativeControl`). Confirmed across the full shader corpus: all `207 / 207` previously refused pixel shaders (`1,139` `v_interp_p1_f32` / `v_interp_p2_f32` computed pairs; `0` computed `*_f16` ops, `2` shaders also reading non-computed `*_f16` inputs) translate and pass `spirv-val --target-env vulkan1.2 --allow-offset-texture-operand` under `--f16-interp-fallback`, bringing `--f16-interp-fallback` corpus translation from `26,296 / 26,503` (`99.22%`) to `26,503 / 26,503` (`100%`), while default-flag outputs stay byte-identical across all 207 shaders. Checked on the CPU (`spirv_mini_interp` 2x2 quad evaluation across dyadic weights, `64x64`, `1920x1080`, and `2048`-pixel perspective `w` foreshortening with tight binary64 Jacobian and `(1 + 2\|alpha\| + 2\|beta\|)·m_ulp` error bounds, non-uniform `EXEC`-masked branches, non-`v0`/`v1` operand registers, between-ops `J` writes, `v_interp_p1lv_f16` `vsrc2` invariance, line-primitive `det == 0` / subnormal / `±inf` / `NaN` determinants, and `f16_halves` metadata) and with `spirv-val` by `tests/semantic/test_interp_computed_ij_fallback.py` (`tests/semantic/fixtures/ps_ij_computed_deriv_fallback.asm`) and `tests/semantic/test_interp_computed_ij.py`. **GPU-verified through Vulkan** on `Apple M3` (`@EvgHaze`, MoltenVK `1.4.2`, #2239), `Apple M3 Pro` (`@wavehs`, MoltenVK `1.4.0`, #2239), `NVIDIA GeForce RTX 3090` (Windows driver `610.88`, Vulkan `1.4.341`, `VK_LAYER_KHRONOS_validation` `1.4.363`, `LEONIDA_F16_INTERP_FALLBACK=1`, `LEONIDA_BARY_FALLBACK=0`), and `NVIDIA GeForce RTX 5070` (`@lixonik`, Windows driver `610.88`, #2239): `runtime/test/shaders/ps_ij_computed.asm` drawn with `vs_ids` passes `vk_pipeline_check`, `runtime/test/shaders/check.py`, and `scripts/run_gpu_tests.py` (`4,096 / 4,096` pixels exact on RTX 3090/5070 and within `1e-6` natively on MoltenVK, `0` validation errors). | | `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | | `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | | `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. The DX10 clamp operates on the rounded f16 word, preserving positive subnormals and mapping negative values and NaNs to +0. The same bit clamp is used by `v_div_fixup_f16`. The synthetic Vulkan fixture `cs_w32_cvt_f16_mods.asm` checks both clamp paths and f16-to-f32 conversion of SDWA subnormals and NaNs. | diff --git a/docs/testing.md b/docs/testing.md index d62a0cf995..ae46a1269e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -753,7 +753,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 @@ -915,6 +917,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `ps_imgatomic` fails in about two of three runs on a Mac with MoltenVK 1.4.2: 1 to 6 of the 256 image-atomic texels are wrong while the render target is exact, for example `2D umax texel 48: got 0x00000d45, want 0x00000dc7` | MoltenVK 1.4.2 lowers the four `OpAtomic*` on image texels to Metal's texture atomics (`atomic_fetch_max`, `atomic_fetch_min` and `atomic_fetch_or` on `access::read_write` textures), and the texels read back the way a read-modify-write that is not atomic between two groups of fragment threads leaves them. A wrong `umax` texel always holds the id of one of its own 64 pixels, the largest of only some of them: on an Apple M5 it was the last pixel of the texel's first four rows in 43 of 90 cases, with all 32 larger ids gone. A wrong `umin` texel mirrors that (the first pixel of its last four rows in 39 of 48). The `or` image did not differ in 150 runs there. It is not the translator's first-lane broadcast of the descriptor index (54 of 60 runs fail with the index used directly) and not the readback (42 of 60 fail with the copies in a submission of their own after the draw). Measured on an Apple M5 (macOS 27.2.1, 101 of 150 runs fail) and an M5 Pro (#543) | Expected with MoltenVK 1.4.2. KosmicKrisp passed the same module and binary 10 times of 10 on the M5 Pro (#543). The macOS CI job does not reach it: on the runner's paravirtual device the test skips because its bindless set does not fit the descriptor limits. Do not weaken the test's expected texels | | `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/make_game.py b/make_game.py index d0306e3422..682c9565b0 100644 --- a/make_game.py +++ b/make_game.py @@ -2054,6 +2054,15 @@ def runtime_gpu_barycentric_fallback(): return None +def runtime_gpu_geometry_shader(): + """geometryShader as tools/vk_subgroup_info.py answers for the GPU the runtime would use, or None.""" + try: + v = runtime_gpu_info().get("geometry_shader") + return v if isinstance(v, bool) else None + except (AttributeError, TypeError): + return None + + def barycentric_fallback_override(): """LEONIDA_BARY_FALLBACK=1/0 forces the same barycentric path as the GPU test runner; None leaves it automatic.""" v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() @@ -3542,6 +3551,7 @@ def main() -> int: a.mesh_compute = keep_recorded_fallback("--mesh-compute", work) emulate, keep_emulated = (wave64_settings(a.wave64_emulate, mesh_compute=a.mesh_compute) if "shaders" in stages else (False, a.wave64_emulate == "auto")) + per_vertex = None if "shaders" in stages and not a.f16_interp_fallback: per_vertex = runtime_gpu_per_vertex() if per_vertex is False: @@ -3564,11 +3574,19 @@ def main() -> int: a.bary_fallback = False else: bary_fallback = runtime_gpu_barycentric_fallback() - if bary_fallback is True: - log("shaders: this GPU's driver has a known BaryCoordKHR bug (Mesa ANV, or AMD's Windows driver " - "on gfx90c): translating with --bary-fallback") + # A GPU with geometry shaders but no PerVertexKHR inputs (no fragmentShaderBarycentric; #1285) + # needs the pass-through geometry shader, not only the f16-half fallback. MoltenVK has neither + # geometry shaders nor PerVertexKHR, so it stays on --f16-interp-fallback alone. + geometry = runtime_gpu_geometry_shader() if per_vertex is False else None + if bary_fallback is True or geometry is True: + if bary_fallback is True: + log("shaders: this GPU's driver has a known BaryCoordKHR bug (Mesa ANV, or AMD's Windows driver " + "on gfx90c): translating with --bary-fallback") + else: + log("shaders: the GPU the runtime would use has geometry shaders but can't take PerVertexKHR " + "inputs: translating with --bary-fallback") a.bary_fallback = True - elif bary_fallback is None: + elif bary_fallback is None or geometry is None and per_vertex is False: a.bary_fallback = keep_recorded_fallback("--bary-fallback", work) if "shaders" in stages and not a.pc_tail_ubo: need_pc = 152 if a.mesh_compute else 144 diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index c8aef7a5db..ff559ad7f2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1666,6 +1666,8 @@ if(BUILD_TESTING) add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test) add_executable(dual_source_fragment_test test/dual_source_fragment_test.cpp) add_test(NAME dual_source_fragment COMMAND dual_source_fragment_test) + add_executable(spirv_bary_fallback_test test/spirv_bary_fallback_test.cpp) + add_test(NAME spirv_bary_fallback COMMAND spirv_bary_fallback_test) # Optional: skips unless LEONIDA_SHADERS names a translated work folder (/shaders/spirv). add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) @@ -3640,6 +3642,14 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_f16_halves COMMAND d3d12_f16_halves_test) set_tests_properties(d3d12_f16_halves PROPERTIES SKIP_RETURN_CODE 77) + # Per-pipeline --bary-fallback GS synthesis (RT-BARY-FALLBACK-PSO): perspective barycentrics + ClipDistance + f16 halves. + add_executable(d3d12_bary_fallback_test test/d3d12_bary_fallback_test.cpp shims/d3d12_xs_device.cpp) + target_link_libraries(d3d12_bary_fallback_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_bary_fallback_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_bary_fallback_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_bary_fallback COMMAND d3d12_bary_fallback_test) + set_tests_properties(d3d12_bary_fallback PROPERTIES SKIP_RETURN_CODE 77) + # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels. add_executable(xbox_present_test test/xbox_present_test.cpp) target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index eaea4f648e..16efa8e772 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -118,6 +118,9 @@ struct VulkanDeviceInfo { bool push_constants_need_fallback = false; // Top location for relocated f16 halves (0: read from device limits; non-zero: override for testing low-limit devices). std::uint32_t f16_half_top_location = 0; + // Geometry shader per-vertex interface component limits (0: read from physical device; non-zero: test override). + std::uint32_t max_geometry_input_components = 0; + std::uint32_t max_geometry_output_components = 0; // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from // the physical device when the D3D12 device is created; a test sets smaller ones to simulate a device. VkDeviceSize max_buffer_size = 0; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 3d4fe7cc38..f8ff313ae6 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -72,6 +72,7 @@ #include "../src/title_texture_refresh.h" #include "title_gpu_placements.h" #include "../src/spirv_f16_halves.h" +#include "../src/spirv_bary_fallback.h" #include "../src/spirv_stores.h" #include "../src/title_va_alias.h" #include "../src/console_heap_slot_records.h" @@ -3119,6 +3120,10 @@ struct DeviceState { // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. UINT no_output_sample_counts = 0; std::uint32_t f16_half_top_location = 29; + std::uint32_t bary_f16_half_top_location = 29; + std::uint32_t max_geometry_input_components = 0; + std::uint32_t max_geometry_output_components = 0; + std::uint32_t max_geometry_total_output_components = 0; float max_sampler_lod_bias = 0; D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; bool conservative_post_depth_coverage = false; @@ -12618,19 +12623,57 @@ class PipelineState final Stage& vs_stage = stages[0]; Stage& gs_stage = stages[1]; Stage& ps_stage = stages[2]; + const bool bary_fallback = ps_stage.entry && ps_stage.entry->bary_fallback_location.has_value(); + if (bary_fallback) { + const int bary_loc = int(*ps_stage.entry->bary_fallback_location); + if (mesh) { + return stream_unsupported( + "--bary-fallback pixel shader needs a geometry stage, which a mesh PSO cannot include; location", + bary_loc); + } + if (gs_stage.entry) { + return stream_unsupported( + "--bary-fallback pixel shader cannot pair with an explicit geometry shader; location", bary_loc); + } + if (rect_list) { + return stream_unsupported( + "--bary-fallback pixel shader cannot pair with a rectangle-list geometry stage; location", + bary_loc); + } + if (!device_.info.features.geometryShader) { + return stream_unsupported( + "--bary-fallback pixel shaders need the Vulkan geometryShader feature; location", bary_loc); + } + if (desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a --bary-fallback geometry stage takes triangles; topology type", desc.PrimitiveTopologyType); + return E_INVALIDARG; + } + } if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); } + std::set raw_vs_locations; // the VS's raw outputs before f16 linking, for the bary GS if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { std::string link_error; if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, - &link_error)) { + &link_error, bary_fallback, &raw_vs_locations)) { + if (bary_fallback && device_.bary_f16_half_top_location < device_.f16_half_top_location) { + std::fprintf(stderr, + "[rt] d3d12: %s (%s + %s; --bary-fallback caps f16_halves top location at %u for " + "maxGeometryInputComponents=%u, maxGeometryOutputComponents=%u)\n", + link_error.c_str(), vs_stage.entry->name.c_str(), ps_stage.entry->name.c_str(), + device_.bary_f16_half_top_location, device_.max_geometry_input_components, + device_.max_geometry_output_components); + return stream_unsupported( + "--bary-fallback + --f16-interp-fallback exceeds geometry stage component limits"); + } std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } f16_linked_ = true; } + bary_fallback_ = bary_fallback; // A lazy pipeline keeps where each stage's words come from, not the words or a module: build() makes them // again, the same way, and drops them once the pipeline exists. lazy_ = !stubbed && lazy_graphics_pipelines(); // a lazy build reads its stages from the library again @@ -12685,8 +12728,8 @@ class PipelineState final module = shader_module(stage.words); if (!module) return E_FAIL; } - if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && device_.info.features.geometryShader && - topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + if (stage.bit == VK_SHADER_STAGE_VERTEX_BIT && !geometry && !bary_fallback && + device_.info.features.geometryShader && topology_type == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { rectangle_capable_ = true; if (!lazy_) rectangle_vertex_ = modules_.back(); } @@ -12719,6 +12762,88 @@ class PipelineState final info.pName = "main"; stage_infos.push_back(info); } + if (bary_fallback) { // the stage that supplies (1,0,0)/(0,1,0)/(0,0,1) at bary_fallback_input.location + std::vector words; + leonida::BaryFallbackGsInfo bary_info{}; + std::string bary_error; + if (!leonida::build_bary_fallback_gs(vs_stage.words, ps_stage.words, + *ps_stage.entry->bary_fallback_location, + ps_stage.entry->bary_fallback_per_vertex, words, &bary_info, + &bary_error, f16_linked_ ? &raw_vs_locations : nullptr)) { + std::fprintf(stderr, "[rt] d3d12: %s\n", bary_error.c_str()); + return E_FAIL; + } + if (bary_info.clip_count && !device_.info.features.shaderClipDistance) { + return stream_unsupported( + "--bary-fallback geometry stage forwards ClipDistance, which needs shaderClipDistance; count", + int(bary_info.clip_count)); + } + if (bary_info.cull_count && !device_.info.features.shaderCullDistance) { + return stream_unsupported( + "--bary-fallback geometry stage forwards CullDistance, which needs shaderCullDistance; count", + int(bary_info.cull_count)); + } + const char* vs_name = vs_stage.entry ? vs_stage.entry->name.c_str() : ""; + const char* ps_name = ps_stage.entry ? ps_stage.entry->name.c_str() : ""; + // The validation layer counts the built-ins (Position, Clip/CullDistance) on top of the Location end. + const std::uint32_t in_end = bary_info.max_input_location_components + bary_info.builtin_components; + const std::uint32_t out_end = bary_info.max_output_location_components + bary_info.builtin_components; + const std::uint32_t max_gs_in = device_.max_geometry_input_components; + if (max_gs_in && (in_end > max_gs_in || bary_info.input_components > max_gs_in)) { + if (in_end > max_gs_in) { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s reads Location %u " + "(component end %u + %u built-in > maxGeometryInputComponents %u); refusing " + "pipeline\n", + vs_name, ps_name, bary_info.max_input_location, + bary_info.max_input_location_components, bary_info.builtin_components, max_gs_in); + } else { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s uses %u input components " + "(> maxGeometryInputComponents %u); refusing pipeline\n", + vs_name, ps_name, bary_info.input_components, max_gs_in); + } + return stream_unsupported("--bary-fallback geometry stage exceeds maxGeometryInputComponents"); + } + const std::uint32_t max_gs_out = device_.max_geometry_output_components; + if (max_gs_out && (out_end > max_gs_out || bary_info.output_components > max_gs_out)) { + if (out_end > max_gs_out) { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s writes Location %u " + "(component end %u + %u built-in > maxGeometryOutputComponents %u); refusing " + "pipeline\n", + vs_name, ps_name, bary_info.max_output_location, + bary_info.max_output_location_components, bary_info.builtin_components, max_gs_out); + } else { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s uses %u output components " + "(> maxGeometryOutputComponents %u); refusing pipeline\n", + vs_name, ps_name, bary_info.output_components, max_gs_out); + } + return stream_unsupported("--bary-fallback geometry stage exceeds maxGeometryOutputComponents"); + } + const std::uint32_t max_gs_total_out = device_.max_geometry_total_output_components; + if (max_gs_total_out && 3u * bary_info.output_components > max_gs_total_out) { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s emits %u total output components " + "(> maxGeometryTotalOutputComponents %u); refusing pipeline\n", + vs_name, ps_name, 3u * bary_info.output_components, max_gs_total_out); + return stream_unsupported("--bary-fallback geometry stage exceeds maxGeometryTotalOutputComponents"); + } + if (trace_pipeline_compile()) stage_bytes_ += words.size() * sizeof(std::uint32_t); + VkShaderModule module = VK_NULL_HANDLE; + if (lazy_) { + sources_.push_back({StageSource::bary_fallback}); + } else { + module = shader_module(words); + if (!module) return E_FAIL; + } + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); if (words.empty()) return E_FAIL; @@ -13828,9 +13953,11 @@ class PipelineState final bool link_f16_halves(std::vector& vs_words, const leonida::ShaderEntry& vs_entry, std::vector& ps_words, const leonida::ShaderEntry& ps_entry, - std::string* error) const { - return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, - device_.f16_half_top_location); + std::string* error, bool bary_fallback = false, + std::set* raw_vs_locations = nullptr) const { + const std::uint32_t top_loc = + bary_fallback ? device_.bary_f16_half_top_location : device_.f16_half_top_location; + return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, top_loc, raw_vs_locations); } public: @@ -13861,9 +13988,11 @@ class PipelineState final if (source.slot == 0) vs = i; if (source.slot == 2) ps = i; } + std::set raw_vs_locations; // as in create_graphics: the VS's raw outputs before f16 linking if (f16_linked_) { if (vs == SIZE_MAX || ps == SIZE_MAX || - !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why)) + !link_f16_halves(words[vs], *sources_[vs].entry, words[ps], *sources_[ps].entry, &why, + bary_fallback_, &raw_vs_locations)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { @@ -13876,6 +14005,13 @@ class PipelineState final if (sources_[i].kind == StageSource::rect_list) { if (vs == SIZE_MAX) return false; words[i] = leonida::rect_list_geometry(words[vs], why); + } else if (sources_[i].kind == StageSource::bary_fallback) { + if (vs == SIZE_MAX || ps == SIZE_MAX || !sources_[ps].entry->bary_fallback_location || + !leonida::build_bary_fallback_gs(words[vs], words[ps], + *sources_[ps].entry->bary_fallback_location, + sources_[ps].entry->bary_fallback_per_vertex, words[i], nullptr, + &why, f16_linked_ ? &raw_vs_locations : nullptr)) + return false; } else if (sources_[i].kind == StageSource::depth_only) { words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); } else { @@ -13909,7 +14045,7 @@ class PipelineState final // Where a lazy graphics pipeline's stage modules come from, in recipe_.stages order (stage_words). struct StageSource { - enum Kind : std::uint8_t { library, rect_list, depth_only } kind = library; + enum Kind : std::uint8_t { library, rect_list, bary_fallback, depth_only } kind = library; std::uint8_t slot = 0; // library: the create_graphics stage table entry (0 VS or MS, 1 GS, 2 PS) bool depth24 = false; // library: the D24 fragment patch applies const leonida::ShaderEntry* entry = nullptr; // library: the translated shader @@ -13922,8 +14058,9 @@ class PipelineState final const leonida::ShaderEntry* compute_entry_ = nullptr; // compute: the translated shader build_compute reads bool compute_failed_ = false; // compute: could not be built; not retried std::atomic skip_logged_{false}; // compute: the skipped program's first dispatch was logged - bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) - bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked + bool lazy_ = false; // graphics: built at the first draw (lazy_graphics_pipelines) + bool f16_linked_ = false; // graphics: the VS and PS words had their f16 halves linked + bool bary_fallback_ = false; // graphics: synthesized --bary-fallback geometry stage leonida::Depth24Bias depth24_bias_{}; unsigned rgba4_mask_ = 0; // graphics: the B4G4R4A4 targets stored as RGBA8 that the pixel shader is quantised for bool dual_source_ = false; // graphics: a SRC1 blend factor; the pixel shader's SV_Target1 is Location 0, Index 1 @@ -15301,10 +15438,25 @@ class Device final VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; state_.no_output_sample_counts = static_cast(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); + state_.max_geometry_input_components = info.max_geometry_input_components != 0 + ? info.max_geometry_input_components + : props.limits.maxGeometryInputComponents; + state_.max_geometry_output_components = info.max_geometry_output_components != 0 + ? info.max_geometry_output_components + : props.limits.maxGeometryOutputComponents; + state_.max_geometry_total_output_components = props.limits.maxGeometryTotalOutputComponents; state_.f16_half_top_location = info.f16_half_top_location != 0 ? info.f16_half_top_location : leonida::f16_half_top_location( props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); + state_.bary_f16_half_top_location = state_.f16_half_top_location; + if (info.f16_half_top_location == 0 && + state_.max_geometry_input_components && state_.max_geometry_output_components) { + state_.bary_f16_half_top_location = std::min( + state_.f16_half_top_location, + leonida::f16_half_top_location(state_.max_geometry_input_components, + state_.max_geometry_output_components)); + } } if (const auto get_props2 = reinterpret_cast( info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index f19e56d718..4e75cde2c2 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -878,6 +879,12 @@ struct ShaderEntry { std::vector outputs; // pixel/vertex shaders: output locations written // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378). std::map> f16_halves; + // --bary-fallback: input location where a pass-through GS supplies one-hot barycentrics (RT-BARY-FALLBACK-PSO). + std::optional bary_fallback_location; + // --bary-fallback computed I/J pairs (SHADER-177): attribute (the producer's output location) -> first of the + // three consecutive PS input locations of its Flat vec4[3], from bary_fallback_input.per_vertex + // (RT-BARY-FALLBACK-PER-VERTEX). The pass-through GS writes the triangle's three values of the attribute there. + std::map bary_fallback_per_vertex; // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). std::vector> literal_samplers; @@ -1316,6 +1323,33 @@ class ShaderLibrary { e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; } } + if (const Json* bf = meta.find("bary_fallback_input"); bf && bf->kind == Json::Kind::object) { + if (const Json* loc = bf->find("location"); loc && loc->kind == Json::Kind::number && + loc->number >= 0.0 && loc->number <= 4294967295.0 && + double(std::uint32_t(loc->number)) == loc->number) { + e.bary_fallback_location = std::uint32_t(loc->number); + } + // "per_vertex": {"": , ...}. A malformed entry drops the whole map, so the + // GS builder refuses the PS's vec4[3] input instead of linking a partial mapping. + if (const Json* pv = bf->find("per_vertex"); pv && pv->kind == Json::Kind::object) { + std::map map; + bool ok = true; + for (const auto& [key, val] : pv->object) { + std::uint64_t attr = 0; + ok = !key.empty() && key.size() <= 10; + for (const char c : key) { + if (c < '0' || c > '9') ok = false; + if (!ok) break; + attr = attr * 10u + std::uint64_t(c - '0'); + } + ok = ok && attr <= UINT32_MAX && val.kind == Json::Kind::number && val.number >= 0.0 && + val.number <= 4294967293.0 && double(std::uint32_t(val.number)) == val.number && + map.emplace(std::uint32_t(attr), std::uint32_t(val.number)).second; + if (!ok) break; + } + if (ok) e.bary_fallback_per_vertex = std::move(map); + } + } if (const Json* l = meta.find("literal_samplers"); l && l->kind == Json::Kind::array) { for (const Json& item : l->array) { if (item.kind != Json::Kind::array || item.array.size() != 4) continue; diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h new file mode 100644 index 0000000000..d2d8efa921 --- /dev/null +++ b/runtime/src/spirv_bary_fallback.h @@ -0,0 +1,669 @@ +#pragma once + +// Per-pipeline `--bary-fallback` geometry-shader synthesis for D3D12 graphics PSOs (RT-BARY-FALLBACK-PSO). +// +// On GPUs without `VK_KHR_fragment_shader_barycentric`, `tools/rdna2spirv.py --bary-fallback` declares the raw +// barycentric pair a pixel shader reads as an ordinary smooth `vec3` input at the location recorded in +// `index.json` under `"bary_fallback_input": {"location": N}`. At graphics PSO creation, after any +// `--f16-interp-fallback` VS/PS location linking (`spirv_f16_halves.h`), `build_bary_fallback_gs` synthesizes the +// triangle pass-through Geometry SPIR-V module (`tools/bary_fallback_gs.py` equivalent) in memory for the exact +// `(VS, PS)` pair: +// - copies `BuiltIn Position` across the triangle's 3 vertices (`Triangles` -> `OutputTriangleStrip`, 3 vertices); +// - copies every `vec4` `Location` input the PS statically reads (other than `bary_location`) that the VS +// exports, and zero-fills any unexported or unread PS `Location` input without declaring a GS `Input` (preserving +// `VUID-RuntimeSpirv-OpEntryPoint-08743` and avoiding `VUID-RuntimeSpirv-Location-06272` on unused FSSM inputs); +// - forwards a VS `BuiltIn ClipDistance` or `BuiltIn CullDistance` `float[1..8]` array when present (rejecting +// mixed clip+cull and `ShaderLayer` / `ShaderViewportIndex`, which a pass-through helper cannot forward); +// - writes `(1, 0, 0)`, `(0, 1, 0)`, `(0, 0, 1)` at `bary_location` so perspective interpolation yields +// `BaryCoordKHR` (`.y` / `.z` = AMD's `i` / `j`); +// - for a computed I/J pair (SHADER-177, `"per_vertex": {"": }` in the same index +// entry, RT-BARY-FALLBACK-PER-VERTEX), writes the triangle's three values of VS output `` to the +// PS's `Flat vec4[3]` input at `` (element k = vertex k, the same at every emitted vertex, +// so the flat value does not depend on the provoking vertex), as `tools/bary_fallback_gs.py` does; an attribute +// the VS does not export is zero-filled like an ordinary pass-through input. +// +// Pure C++20 stdlib, no Vulkan or Windows headers required. + +#include "spirv_f16_halves.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +struct BaryFallbackGsInfo { + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; + // Per-vertex scalar input components declared by the GS (4 for Position + dist_count + 4 per user Input + // Location, including a VS attribute read only by a computed-I/J block). + std::uint32_t input_components = 0; + // Highest `4 * Location + 4` across GS Input locations (0 when no user locations are forwarded). + // With builtin_components, checked against limits.maxGeometryInputComponents (VUID-RuntimeSpirv-Location-06272). + std::uint32_t max_input_location = 0; + std::uint32_t max_input_location_components = 0; + // Per-vertex scalar output components declared by the GS (4 for Position + dist_count + 4 * pass_locs + 3, + // and 12 for each computed-I/J vec4[3]). + std::uint32_t output_components = 0; + // Highest `4 * Location + components` across GS Output locations (`pass_locs` vec4, `bary_location` vec3 and + // the last Location of each computed-I/J block). + // With builtin_components, checked against limits.maxGeometryOutputComponents (VUID-RuntimeSpirv-Location-06272). + std::uint32_t max_output_location = 0; + std::uint32_t max_output_location_components = 0; + // Built-in components on each side of the GS (4 for Position + dist_count). The Khronos validation layer adds + // them to the Location end above when it checks VUID-RuntimeSpirv-Location-06272, so a stage is within the + // limit when max_*_location_components + builtin_components <= the limit. + std::uint32_t builtin_components = 0; +}; + +// `per_vertex` is the index entry's `bary_fallback_input.per_vertex` (`ShaderEntry::bary_fallback_per_vertex`): +// attribute (VS output location) -> first of the three PS input locations of its `Flat vec4[3]`. +// `raw_vs_locations`: when the VS went through link_f16_halves, the Locations of its raw outputs before linking +// (link_f16_halves' `raw_vs_locations`). A computed-I/J attribute is forwarded only from one of them; a decoded half +// that linking put on an attribute's Location the VS did not export leaves that attribute zero-filled. +inline bool build_bary_fallback_gs(std::span vs_words, + std::span ps_words, + std::uint32_t bary_location, + const std::map& per_vertex, + std::vector& gs_words, + BaryFallbackGsInfo* out_info = nullptr, + std::string* error = nullptr, + const std::set* raw_vs_locations = nullptr) { + const auto fail = [&](const std::string& msg) { + if (error) *error = msg; + return false; + }; + + using namespace spirv_detail; + constexpr std::uint32_t kSpirvVersion15 = 0x00010500u; + constexpr std::uint16_t kOpTypeVoid = 19; + constexpr std::uint16_t kOpTypeArray = 28; + constexpr std::uint16_t kOpTypeStruct = 30; + constexpr std::uint16_t kOpTypeFunction = 33; + constexpr std::uint16_t kOpConstant = 43; + constexpr std::uint16_t kOpConstantComposite = 44; + constexpr std::uint16_t kOpFunctionCall = 57; + constexpr std::uint16_t kOpCopyMemory = 63; + constexpr std::uint16_t kOpCopyMemorySized = 64; + constexpr std::uint16_t kOpPtrAccessChain = 67; + constexpr std::uint16_t kOpInBoundsPtrAccessChain = 70; + constexpr std::uint16_t kOpCopyObject = 83; + constexpr std::uint16_t kOpSelect = 169; + constexpr std::uint16_t kOpEmitVertex = 218; + constexpr std::uint16_t kOpEndPrimitive = 219; + constexpr std::uint16_t kOpPhi = 245; + constexpr std::uint16_t kOpLabel = 248; + + constexpr std::uint32_t kExecModelGeometry = 3; + constexpr std::uint32_t kCapGeometry = 2; + constexpr std::uint32_t kCapClipDistance = 32; + constexpr std::uint32_t kCapCullDistance = 33; + constexpr std::uint32_t kCapShaderLayer = 69; + constexpr std::uint32_t kCapShaderViewportIndex = 70; + + constexpr std::uint32_t kExecModeInvocations = 0; + constexpr std::uint32_t kExecModeTriangles = 22; + constexpr std::uint32_t kExecModeOutputVertices = 26; + constexpr std::uint32_t kExecModeOutputTriangleStrip = 29; + + constexpr std::uint32_t kDecorationBuiltIn = 11; + constexpr std::uint32_t kDecorationFlat = 14; + constexpr std::uint32_t kDecorationComponent = 31; + constexpr std::uint32_t kBuiltInPosition = 0; + constexpr std::uint32_t kBuiltInClipDistance = 3; + constexpr std::uint32_t kBuiltInCullDistance = 4; + constexpr std::uint32_t kBuiltInLayer = 9; + constexpr std::uint32_t kBuiltInViewportIndex = 10; + + Module vs_mod, ps_mod; + if (!vs_mod.parse(vs_words)) return fail("bary_fallback: malformed VS SPIR-V"); + if (!ps_mod.parse(ps_words)) return fail("bary_fallback: malformed PS SPIR-V"); + + // --- Inspect VS --- + bool has_vs_ep = false; + std::set vs_float32_tys; + std::map vs_int32_signed; // int_type_id -> is_signed + std::set vs_v4float_tys; + std::map vs_pos_int_consts; // const_id -> value (> 0) + std::map> vs_arr_tys; // arr_id -> (elem_ty, len_id) + std::map> vs_struct_tys; // struct_id -> member_tys + std::map vs_ptr_out_pointee; // ptr_id -> pointee_ty + std::map vs_out_var_pointee; // var_id -> pointee_ty + std::map vs_var_builtins; // var_id -> BuiltIn + std::map>> vs_member_builtins; + std::vector> vs_loc_decs; // (target_id, loc) + + for (const Inst& inst : vs_mod.insts) { + if (inst.opcode == kOpFunction) break; + if (inst.opcode == kOpCapability && inst.words.size() >= 2) { + if (inst.words[1] == kCapShaderLayer) + return fail("bary_fallback: VS declares ShaderLayer, which the fallback GS cannot forward"); + if (inst.words[1] == kCapShaderViewportIndex) + return fail("bary_fallback: VS declares ShaderViewportIndex, which the fallback GS cannot forward"); + } else if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelVertex) { + has_vs_ep = true; + } else if (inst.opcode == kOpDecorate && inst.words.size() >= 4) { + if (inst.words[2] == kDecorationBuiltIn) vs_var_builtins[inst.words[1]] = inst.words[3]; + if (inst.words[2] == kDecorationLocation) vs_loc_decs.emplace_back(inst.words[1], inst.words[3]); + } else if (inst.opcode == kOpMemberDecorate && inst.words.size() >= 5 && inst.words[3] == kDecorationBuiltIn) { + vs_member_builtins[inst.words[1]].emplace_back(inst.words[2], inst.words[4]); + } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) { + vs_float32_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32) { + vs_int32_signed[inst.words[1]] = (inst.words[3] != 0); + } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4 && inst.words[3] == 4 && + vs_float32_tys.count(inst.words[2])) { + vs_v4float_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpConstant && inst.words.size() == 4) { + const auto it = vs_int32_signed.find(inst.words[1]); + if (it != vs_int32_signed.end()) { + const std::uint32_t raw = inst.words[3]; + const bool positive = it->second ? (static_cast(raw) > 0) : (raw > 0); + if (positive) vs_pos_int_consts[inst.words[2]] = raw; + } + } else if (inst.opcode == kOpTypeArray && inst.words.size() == 4) { + vs_arr_tys[inst.words[1]] = {inst.words[2], inst.words[3]}; + } else if (inst.opcode == kOpTypeStruct && inst.words.size() >= 2) { + vs_struct_tys[inst.words[1]].assign(inst.words.begin() + 2, inst.words.end()); + } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4 && inst.words[2] == kStorageOutput) { + vs_ptr_out_pointee[inst.words[1]] = inst.words[3]; + } else if (inst.opcode == kOpVariable && inst.words.size() >= 4 && inst.words[3] == kStorageOutput) { + const auto pt = vs_ptr_out_pointee.find(inst.words[1]); + if (pt != vs_ptr_out_pointee.end()) vs_out_var_pointee[inst.words[2]] = pt->second; + } + } + if (!has_vs_ep) return fail("bary_fallback: VS has no Vertex entry point"); + + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; + const auto record_vs_builtin = [&](std::uint32_t bi, std::uint32_t ty_id) -> bool { + if (bi == kBuiltInLayer) + return fail("bary_fallback: VS writes BuiltIn Layer, which the fallback GS cannot forward"); + if (bi == kBuiltInViewportIndex) + return fail("bary_fallback: VS writes BuiltIn ViewportIndex, which the fallback GS cannot forward"); + if (bi != kBuiltInClipDistance && bi != kBuiltInCullDistance) return true; + const auto arr_it = vs_arr_tys.find(ty_id); + if (arr_it == vs_arr_tys.end() || !vs_float32_tys.count(arr_it->second.first)) + return fail("bary_fallback: VS ClipDistance/CullDistance output is not float[N]"); + const auto len_it = vs_pos_int_consts.find(arr_it->second.second); + if (len_it == vs_pos_int_consts.end() || len_it->second < 1 || len_it->second > 8) + return fail("bary_fallback: VS ClipDistance/CullDistance length must be in 1..8"); + std::uint32_t& dst = (bi == kBuiltInClipDistance) ? clip_count : cull_count; + if (dst != 0 && dst != len_it->second) + return fail("bary_fallback: conflicting VS ClipDistance/CullDistance output declarations"); + dst = len_it->second; + return true; + }; + + for (const auto& [var_id, pt_ty] : vs_out_var_pointee) { + if (const auto bi_it = vs_var_builtins.find(var_id); bi_it != vs_var_builtins.end()) { + if (!record_vs_builtin(bi_it->second, pt_ty)) return false; + } + if (const auto m_it = vs_member_builtins.find(pt_ty); m_it != vs_member_builtins.end()) { + const auto st_it = vs_struct_tys.find(pt_ty); + if (st_it != vs_struct_tys.end()) { + for (const auto& [member_idx, bi] : m_it->second) { + if (member_idx >= st_it->second.size()) + return fail("bary_fallback: out-of-range MemberDecorate on VS output struct"); + if (!record_vs_builtin(bi, st_it->second[member_idx])) return false; + } + } + } + } + if (clip_count && cull_count) + return fail("bary_fallback: cannot forward mixed ClipDistance and CullDistance"); + + std::map vs_out_loc_pointee; // loc -> pointee_ty + for (const auto& [target, loc] : vs_loc_decs) { + const auto it = vs_out_var_pointee.find(target); + if (it == vs_out_var_pointee.end()) continue; + if (!vs_out_loc_pointee.emplace(loc, it->second).second) + return fail("bary_fallback: duplicate VS Output Location " + std::to_string(loc)); + } + + // --- Inspect PS --- + bool has_ps_ep = false; + std::set ps_float32_tys; + std::set ps_v3float_tys; + std::set ps_v4float_tys; + std::map ps_ptr_in_pointee; + std::map ps_in_var_pointee; + std::vector> ps_loc_decs; + std::set ps_component_targets; + std::set ps_int32_tys; + std::map ps_int_consts; // const_id -> value + std::map> ps_arr_tys; // arr_id -> (elem_ty, len_id) + + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) break; + if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelFragment) { + has_ps_ep = true; + } else if (inst.opcode == kOpDecorate && inst.words.size() >= 4) { + if (inst.words[2] == kDecorationLocation) ps_loc_decs.emplace_back(inst.words[1], inst.words[3]); + if (inst.words[2] == kDecorationComponent) ps_component_targets.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) { + ps_float32_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4 && ps_float32_tys.count(inst.words[2])) { + if (inst.words[3] == 3) ps_v3float_tys.insert(inst.words[1]); + if (inst.words[3] == 4) ps_v4float_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32) { + ps_int32_tys.insert(inst.words[1]); + } else if (inst.opcode == kOpConstant && inst.words.size() == 4 && ps_int32_tys.count(inst.words[1])) { + ps_int_consts[inst.words[2]] = inst.words[3]; + } else if (inst.opcode == kOpTypeArray && inst.words.size() == 4) { + ps_arr_tys[inst.words[1]] = {inst.words[2], inst.words[3]}; + } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4 && inst.words[2] == kStorageInput) { + ps_ptr_in_pointee[inst.words[1]] = inst.words[3]; + } else if (inst.opcode == kOpVariable && inst.words.size() >= 4 && inst.words[3] == kStorageInput) { + const auto pt = ps_ptr_in_pointee.find(inst.words[1]); + if (pt != ps_ptr_in_pointee.end()) ps_in_var_pointee[inst.words[2]] = pt->second; + } + } + if (!has_ps_ep) return fail("bary_fallback: PS has no Fragment entry point"); + + std::map ps_in_loc_pointee; + std::map ps_in_var_by_loc; + for (const auto& [target, loc] : ps_loc_decs) { + const auto it = ps_in_var_pointee.find(target); + if (it == ps_in_var_pointee.end()) continue; + if (ps_component_targets.count(target)) + return fail("bary_fallback: Component-decorated PS Input at Location " + std::to_string(loc)); + if (!ps_in_loc_pointee.emplace(loc, it->second).second) + return fail("bary_fallback: duplicate PS Input Location " + std::to_string(loc)); + ps_in_var_by_loc.emplace(loc, target); + } + + // The translator declares every interpolant in the FSSM table as a PS Input variable, even when the PS never + // reads it. The GS must still write matching outputs for the PS interface, but reading unused locations from the + // VS would bloat the VS->GS interface and exceed maxGeometryInputComponents (64 on RADV). Propagate pointer + // aliases from PS Input variables and forward only inputs statically read (via OpLoad, GLSL.std.450 InterpolateAt* + // OpExtInst, OpFunctionCall, or OpCopyMemory*); unread PS inputs are zero-filled in the GS. + std::map> input_pointer_roots; + for (const auto& [var, _] : ps_in_var_pointee) input_pointer_roots[var].insert(var); + const auto add_roots = [&](std::uint32_t dst_ptr, std::uint32_t src_ptr) -> bool { + const auto it = input_pointer_roots.find(src_ptr); + if (it == input_pointer_roots.end()) return false; + auto& dst = input_pointer_roots[dst_ptr]; + const std::size_t before = dst.size(); + dst.insert(it->second.begin(), it->second.end()); + return dst.size() != before; + }; + bool roots_changed = true; + while (roots_changed) { + roots_changed = false; + bool in_ps_function = false; + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) in_ps_function = true; + if (!in_ps_function) continue; + if ((inst.opcode == kOpAccessChain || inst.opcode == kOpInBoundsAccessChain || + inst.opcode == kOpPtrAccessChain || inst.opcode == kOpInBoundsPtrAccessChain || + inst.opcode == kOpCopyObject) && + inst.words.size() >= 4) { + roots_changed |= add_roots(inst.words[2], inst.words[3]); + } else if (inst.opcode == kOpSelect && inst.words.size() >= 6) { + roots_changed |= add_roots(inst.words[2], inst.words[4]); + roots_changed |= add_roots(inst.words[2], inst.words[5]); + } else if (inst.opcode == kOpPhi && inst.words.size() >= 5) { + for (std::size_t k = 3; k + 1 < inst.words.size(); k += 2) + roots_changed |= add_roots(inst.words[2], inst.words[k]); + } + } + } + std::set statically_read_ps_inputs; + const auto mark_read = [&](std::uint32_t ptr_id) { + if (const auto it = input_pointer_roots.find(ptr_id); it != input_pointer_roots.end()) + statically_read_ps_inputs.insert(it->second.begin(), it->second.end()); + }; + { + bool in_ps_function = false; + for (const Inst& inst : ps_mod.insts) { + if (inst.opcode == kOpFunction) in_ps_function = true; + if (!in_ps_function) continue; + if (inst.opcode == kOpLoad && inst.words.size() >= 4) { + mark_read(inst.words[3]); + } else if (inst.opcode == kOpExtInst && inst.words.size() >= 6) { + for (std::size_t k = 5; k < inst.words.size(); ++k) mark_read(inst.words[k]); + } else if (inst.opcode == kOpFunctionCall && inst.words.size() >= 5) { + for (std::size_t k = 4; k < inst.words.size(); ++k) mark_read(inst.words[k]); + } else if ((inst.opcode == kOpCopyMemory && inst.words.size() >= 3) || + (inst.opcode == kOpCopyMemorySized && inst.words.size() >= 4)) { + mark_read(inst.words[2]); + } + } + } + + if (const auto bary_it = ps_in_loc_pointee.find(bary_location); + bary_it != ps_in_loc_pointee.end() && !ps_v3float_tys.count(bary_it->second)) { + return fail("bary_fallback: bary_location " + std::to_string(bary_location) + + " collides with a non-vec3 PS Input"); + } + + // Computed I/J pairs: the PS's Flat vec4[3] at `base` takes the three vertices' values of VS output `attr`. + struct PerVertex { + std::uint32_t attr = 0; + std::uint32_t base = 0; + bool forwarded = false; // false: the VS does not export `attr`, so the array is zero-filled + }; + std::map pv_base_attr; // first location -> attribute + for (const auto& [attr, base] : per_vertex) { + if (base > UINT32_MAX - 2u) + return fail("bary_fallback: per-vertex locations of attribute " + std::to_string(attr) + " overflow"); + if (!pv_base_attr.emplace(base, attr).second) + return fail("bary_fallback: two per-vertex attributes share first Location " + std::to_string(base)); + } + std::vector pv_list; + for (const auto& [base, attr] : pv_base_attr) { + const auto ps_it = ps_in_loc_pointee.find(base); + if (ps_it == ps_in_loc_pointee.end()) continue; // the PS does not read it: nothing to feed + const auto arr_it = ps_arr_tys.find(ps_it->second); + const auto len_it = arr_it == ps_arr_tys.end() ? ps_int_consts.end() : ps_int_consts.find(arr_it->second.second); + if (arr_it == ps_arr_tys.end() || !ps_v4float_tys.count(arr_it->second.first) || + len_it == ps_int_consts.end() || len_it->second != 3u) { + return fail("bary_fallback: PS per-vertex Input at Location " + std::to_string(base) + + " is not vec4[3]"); + } + for (std::uint32_t k = 0; k < 3; ++k) { + const std::uint32_t loc = base + k; + if (loc == bary_location || (k && ps_in_loc_pointee.count(loc))) { + return fail("bary_fallback: per-vertex locations " + std::to_string(base) + ".." + + std::to_string(base + 2u) + " of attribute " + std::to_string(attr) + + " collide with another PS Input"); + } + } + PerVertex pv{attr, base, false}; + if (const auto vs_it = vs_out_loc_pointee.find(attr); + vs_it != vs_out_loc_pointee.end() && (!raw_vs_locations || raw_vs_locations->count(attr))) { + if (!vs_v4float_tys.count(vs_it->second)) + return fail("bary_fallback: VS Output at Location " + std::to_string(attr) + " is not vec4"); + pv.forwarded = true; + } + pv_list.push_back(pv); + } + const auto in_pv_block = [&](std::uint32_t loc) { + for (const PerVertex& pv : pv_list) + if (loc >= pv.base && loc - pv.base < 3u) return true; + return false; + }; + + std::vector pass_locs; + std::vector forwarded_locs; + std::set zero_loc_set; + for (const auto& [loc, pt_ty] : ps_in_loc_pointee) { + if (loc == bary_location || in_pv_block(loc)) continue; + if (!ps_v4float_tys.count(pt_ty)) + return fail("bary_fallback: PS pass-through Input at Location " + std::to_string(loc) + " is not vec4"); + pass_locs.push_back(loc); + if (!statically_read_ps_inputs.count(ps_in_var_by_loc.at(loc))) { + zero_loc_set.insert(loc); + continue; + } + const auto vs_it = vs_out_loc_pointee.find(loc); + if (vs_it != vs_out_loc_pointee.end()) { + if (!vs_v4float_tys.count(vs_it->second)) + return fail("bary_fallback: VS Output at Location " + std::to_string(loc) + " is not vec4"); + forwarded_locs.push_back(loc); + } else { + zero_loc_set.insert(loc); + } + } + + // --- Synthesize Geometry SPIR-V module --- + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_uint = alloc(); + const std::uint32_t id_int = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v3float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_uint_3 = alloc(); + const std::uint32_t id_arr_v4_3 = alloc(); + const std::uint32_t id_ptr_in_arr = alloc(); + const std::uint32_t id_ptr_in_v4 = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_ptr_out_v3 = alloc(); + const std::uint32_t id_null_v4 = zero_loc_set.empty() ? 0 : alloc(); + bool pv_zero = false; + for (const PerVertex& pv : pv_list) pv_zero = pv_zero || !pv.forwarded; + const std::uint32_t id_ptr_out_arr = pv_list.empty() ? 0 : alloc(); + const std::uint32_t id_null_arr = pv_zero ? alloc() : 0; + + const std::uint32_t dist_count = clip_count ? clip_count : cull_count; + const std::uint32_t dist_cap = cull_count ? kCapCullDistance : kCapClipDistance; + const std::uint32_t dist_builtin = cull_count ? kBuiltInCullDistance : kBuiltInClipDistance; + std::uint32_t id_dist_count = 0; + std::uint32_t id_arr_dist = 0; + std::uint32_t id_tri_dist = 0; + std::uint32_t id_ptr_in_tri_dist = 0; + std::uint32_t id_ptr_in_dist = 0; + std::uint32_t id_ptr_out_dist = 0; + if (dist_count) { + id_dist_count = (dist_count == 3) ? id_uint_3 : alloc(); + id_arr_dist = alloc(); + id_tri_dist = alloc(); + id_ptr_in_tri_dist = alloc(); + id_ptr_in_dist = alloc(); + id_ptr_out_dist = alloc(); + } + + const std::uint32_t id_f0 = alloc(); + const std::uint32_t id_f1 = alloc(); + const std::uint32_t id_bary[3] = {alloc(), alloc(), alloc()}; + const std::uint32_t id_int_v[3] = {alloc(), alloc(), alloc()}; + + const std::uint32_t id_in_pos = alloc(); + const std::uint32_t id_out_pos = alloc(); + std::map id_in_loc; + std::map id_out_loc; + for (std::uint32_t loc : forwarded_locs) id_in_loc[loc] = alloc(); + // A per-vertex attribute reads the VS output at its own number; one GS Input per VS location, shared with an + // ordinary pass-through of the same location. + for (const PerVertex& pv : pv_list) + if (pv.forwarded && !id_in_loc.count(pv.attr)) id_in_loc[pv.attr] = alloc(); + for (std::uint32_t loc : pass_locs) id_out_loc[loc] = alloc(); + std::map id_out_pv; // first location -> Output vec4[3] + for (const PerVertex& pv : pv_list) id_out_pv[pv.base] = alloc(); + const std::uint32_t id_out_bary = alloc(); + const std::uint32_t id_in_dist = dist_count ? alloc() : 0; + const std::uint32_t id_out_dist = dist_count ? alloc() : 0; + + Module gs; + // 1. Capabilities + gs.insts.push_back(make_inst(kOpCapability, {kCapGeometry})); + if (dist_count) gs.insts.push_back(make_inst(kOpCapability, {dist_cap})); + + // 2. MemoryModel + gs.insts.push_back(make_inst(kOpMemoryModel, {0, 1})); // Logical GLSL450 + + // 3. EntryPoint ("main\0") + std::vector ep = {kExecModelGeometry, id_main, 0x6e69616du, 0x00000000u, id_in_pos, id_out_pos}; + for (const auto& [loc, id] : id_in_loc) ep.push_back(id); + for (std::uint32_t loc : pass_locs) ep.push_back(id_out_loc[loc]); + for (const auto& [base, id] : id_out_pv) ep.push_back(id); + ep.push_back(id_out_bary); + if (dist_count) { + ep.push_back(id_in_dist); + ep.push_back(id_out_dist); + } + gs.insts.push_back(make_inst_vec(kOpEntryPoint, ep)); + + // 4. ExecutionModes + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeTriangles})); + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeInvocations, 1})); + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeOutputTriangleStrip})); + gs.insts.push_back(make_inst(kOpExecutionMode, {id_main, kExecModeOutputVertices, 3})); + + // 5. Decorations + gs.insts.push_back(make_inst(kOpDecorate, {id_in_pos, kDecorationBuiltIn, kBuiltInPosition})); + gs.insts.push_back(make_inst(kOpDecorate, {id_out_pos, kDecorationBuiltIn, kBuiltInPosition})); + if (dist_count) { + gs.insts.push_back(make_inst(kOpDecorate, {id_in_dist, kDecorationBuiltIn, dist_builtin})); + gs.insts.push_back(make_inst(kOpDecorate, {id_out_dist, kDecorationBuiltIn, dist_builtin})); + } + for (const auto& [loc, id] : id_in_loc) + gs.insts.push_back(make_inst(kOpDecorate, {id, kDecorationLocation, loc})); + for (std::uint32_t loc : pass_locs) + gs.insts.push_back(make_inst(kOpDecorate, {id_out_loc[loc], kDecorationLocation, loc})); + for (const auto& [base, id] : id_out_pv) { + gs.insts.push_back(make_inst(kOpDecorate, {id, kDecorationLocation, base})); + gs.insts.push_back(make_inst(kOpDecorate, {id, kDecorationFlat})); + } + gs.insts.push_back(make_inst(kOpDecorate, {id_out_bary, kDecorationLocation, bary_location})); + + // 6. Types, Constants, Global Variables + gs.insts.push_back(make_inst(kOpTypeVoid, {id_void})); + gs.insts.push_back(make_inst(kOpTypeFunction, {id_fn, id_void})); + gs.insts.push_back(make_inst(kOpTypeInt, {id_uint, 32, 0})); + gs.insts.push_back(make_inst(kOpTypeInt, {id_int, 32, 1})); + gs.insts.push_back(make_inst(kOpTypeFloat, {id_float, 32})); + gs.insts.push_back(make_inst(kOpTypeVector, {id_v3float, id_float, 3})); + gs.insts.push_back(make_inst(kOpTypeVector, {id_v4float, id_float, 4})); + gs.insts.push_back(make_inst(kOpConstant, {id_uint, id_uint_3, 3})); + gs.insts.push_back(make_inst(kOpTypeArray, {id_arr_v4_3, id_v4float, id_uint_3})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_arr, kStorageInput, id_arr_v4_3})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_v4, kStorageInput, id_v4float})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_v3, kStorageOutput, id_v3float})); + if (id_null_v4) gs.insts.push_back(make_inst(kOpConstantNull, {id_v4float, id_null_v4})); + if (id_ptr_out_arr) gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_arr, kStorageOutput, id_arr_v4_3})); + if (id_null_arr) gs.insts.push_back(make_inst(kOpConstantNull, {id_arr_v4_3, id_null_arr})); + if (dist_count) { + if (id_dist_count != id_uint_3) gs.insts.push_back(make_inst(kOpConstant, {id_uint, id_dist_count, dist_count})); + gs.insts.push_back(make_inst(kOpTypeArray, {id_arr_dist, id_float, id_dist_count})); + gs.insts.push_back(make_inst(kOpTypeArray, {id_tri_dist, id_arr_dist, id_uint_3})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_tri_dist, kStorageInput, id_tri_dist})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_in_dist, kStorageInput, id_arr_dist})); + gs.insts.push_back(make_inst(kOpTypePointer, {id_ptr_out_dist, kStorageOutput, id_arr_dist})); + } + gs.insts.push_back(make_inst(kOpConstant, {id_float, id_f0, 0x00000000u})); + gs.insts.push_back(make_inst(kOpConstant, {id_float, id_f1, 0x3f800000u})); + gs.insts.push_back(make_inst(kOpConstantComposite, {id_v3float, id_bary[0], id_f1, id_f0, id_f0})); + gs.insts.push_back(make_inst(kOpConstantComposite, {id_v3float, id_bary[1], id_f0, id_f1, id_f0})); + gs.insts.push_back(make_inst(kOpConstantComposite, {id_v3float, id_bary[2], id_f0, id_f0, id_f1})); + for (std::uint32_t v = 0; v < 3; ++v) gs.insts.push_back(make_inst(kOpConstant, {id_int, id_int_v[v], v})); + + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_arr, id_in_pos, kStorageInput})); + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v4, id_out_pos, kStorageOutput})); + for (const auto& [loc, id] : id_in_loc) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_arr, id, kStorageInput})); + for (std::uint32_t loc : pass_locs) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v4, id_out_loc[loc], kStorageOutput})); + for (const auto& [base, id] : id_out_pv) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_arr, id, kStorageOutput})); + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v3, id_out_bary, kStorageOutput})); + if (dist_count) { + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_tri_dist, id_in_dist, kStorageInput})); + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_dist, id_out_dist, kStorageOutput})); + } + + // 7. Function main + gs.insts.push_back(make_inst(kOpFunction, {id_void, id_main, 0, id_fn})); + gs.insts.push_back(make_inst(kOpLabel, {id_entry})); + // The triangle's three values of each per-vertex attribute, loaded once: every emitted vertex stores the same. + std::map> pv_vals; // first location -> value ids + for (const PerVertex& pv : pv_list) { + if (!pv.forwarded) continue; + for (std::uint32_t k = 0; k < 3; ++k) { + const std::uint32_t ptr = alloc(); + const std::uint32_t val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_v4, ptr, id_in_loc[pv.attr], id_int_v[k]})); + gs.insts.push_back(make_inst(kOpLoad, {id_v4float, val, ptr})); + pv_vals[pv.base][k] = val; + } + } + for (std::uint32_t v = 0; v < 3; ++v) { + const std::uint32_t pos_ptr = alloc(); + const std::uint32_t pos_val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_v4, pos_ptr, id_in_pos, id_int_v[v]})); + gs.insts.push_back(make_inst(kOpLoad, {id_v4float, pos_val, pos_ptr})); + gs.insts.push_back(make_inst(kOpStore, {id_out_pos, pos_val})); + + for (std::uint32_t loc : pass_locs) { + if (zero_loc_set.count(loc)) { + gs.insts.push_back(make_inst(kOpStore, {id_out_loc[loc], id_null_v4})); + } else { + const std::uint32_t attr_ptr = alloc(); + const std::uint32_t attr_val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_v4, attr_ptr, id_in_loc[loc], id_int_v[v]})); + gs.insts.push_back(make_inst(kOpLoad, {id_v4float, attr_val, attr_ptr})); + gs.insts.push_back(make_inst(kOpStore, {id_out_loc[loc], attr_val})); + } + } + for (const PerVertex& pv : pv_list) { + if (!pv.forwarded) { + gs.insts.push_back(make_inst(kOpStore, {id_out_pv[pv.base], id_null_arr})); + continue; + } + for (std::uint32_t k = 0; k < 3; ++k) { + const std::uint32_t out_ptr = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_out_v4, out_ptr, id_out_pv[pv.base], id_int_v[k]})); + gs.insts.push_back(make_inst(kOpStore, {out_ptr, pv_vals[pv.base][k]})); + } + } + if (dist_count) { + const std::uint32_t d_ptr = alloc(); + const std::uint32_t d_val = alloc(); + gs.insts.push_back(make_inst(kOpAccessChain, {id_ptr_in_dist, d_ptr, id_in_dist, id_int_v[v]})); + gs.insts.push_back(make_inst(kOpLoad, {id_arr_dist, d_val, d_ptr})); + gs.insts.push_back(make_inst(kOpStore, {id_out_dist, d_val})); + } + gs.insts.push_back(make_inst(kOpStore, {id_out_bary, id_bary[v]})); + gs.insts.push_back(make_inst(kOpEmitVertex, {})); + } + gs.insts.push_back(make_inst(kOpEndPrimitive, {})); + gs.insts.push_back(make_inst(kOpReturn, {})); + gs.insts.push_back(make_inst(kOpFunctionEnd, {})); + + gs.header = {kSpirvMagic, kSpirvVersion15, 0u, next_id, 0u}; + gs_words = gs.serialize(); + if (out_info) { + BaryFallbackGsInfo info{}; + info.clip_count = clip_count; + info.cull_count = cull_count; + info.builtin_components = 4u + dist_count; + // Inputs: every GS Input the module declares (id_in_loc), which includes a VS attribute only a computed-I/J + // block reads and counts an input both an ordinary output and a block read once. + info.input_components = 4u + dist_count + 4u * std::uint32_t(id_in_loc.size()); + if (!id_in_loc.empty()) { + info.max_input_location = id_in_loc.rbegin()->first; + info.max_input_location_components = 4u * info.max_input_location + 4u; + } + // Outputs: each computed-I/J vec4[3] takes 12 components at Locations base..base+2, zero-filled or not. + info.output_components = 4u + dist_count + 4u * std::uint32_t(pass_locs.size()) + 3u + + 12u * std::uint32_t(id_out_pv.size()); + info.max_output_location = bary_location; + info.max_output_location_components = 4u * bary_location + 3u; + const auto note_output = [&](std::uint32_t loc) { + if (4u * loc + 4u > info.max_output_location_components) { + info.max_output_location = loc; + info.max_output_location_components = 4u * loc + 4u; + } + }; + if (!pass_locs.empty()) note_output(pass_locs.back()); + for (const auto& [base, id] : id_out_pv) note_output(base + 2u); + *out_info = info; + } + return true; +} + +// A PS with no computed I/J pair (no `per_vertex` in its index entry). +inline bool build_bary_fallback_gs(std::span vs_words, + std::span ps_words, + std::uint32_t bary_location, + std::vector& gs_words, + BaryFallbackGsInfo* out_info = nullptr, + std::string* error = nullptr) { + return build_bary_fallback_gs(vs_words, ps_words, bary_location, std::map{}, + gs_words, out_info, error); +} + +} // namespace leonida diff --git a/runtime/src/spirv_f16_halves.h b/runtime/src/spirv_f16_halves.h index ea8d4f458e..28bf82133e 100644 --- a/runtime/src/spirv_f16_halves.h +++ b/runtime/src/spirv_f16_halves.h @@ -248,14 +248,18 @@ inline constexpr std::uint32_t f16_half_top_location(std::uint32_t max_vertex_ou // // Returns true on success (including the no-op fast path when no patching is needed). On failure returns false and // writes a concise reason to `*error` if non-null; the caller's word vectors are only replaced on success. +// `raw_vs_locations`, when non-null, receives on success the Locations of the VS's raw outputs as they were before +// linking (every located Output but its own static halves): a decoded half may take a Location no raw output +// used, and the --bary-fallback geometry stage must not read it as that attribute (spirv_bary_fallback.h). inline bool link_f16_halves(std::vector& vs_words, const ShaderEntry& vs_entry, std::vector& ps_words, const ShaderEntry& ps_entry, - std::string* error = nullptr, std::uint32_t top_location = 29) { + std::string* error = nullptr, std::uint32_t top_location = 29, + std::set* raw_vs_locations = nullptr) { const auto fail = [&](const std::string& msg) { if (error) *error = msg; return false; }; - if (ps_entry.f16_halves.empty() && vs_entry.f16_halves.empty()) return true; + if (ps_entry.f16_halves.empty() && vs_entry.f16_halves.empty() && !raw_vs_locations) return true; using namespace spirv_detail; Module vs_mod, ps_mod; @@ -289,6 +293,11 @@ inline bool link_f16_halves(std::vector& vs_words, const ShaderEn for (const auto& [loc, var_id] : ps_inputs) { if (!ps_static_half_locs.count(loc)) ps_raw_locs.insert(loc); } + // A computed-I/J input (--bary-fallback `per_vertex`) is a vec4[3] with one Location decoration that takes three + // Locations: a half placed on the second or third would overlap it. + for (const auto& [attr, base] : ps_entry.bary_fallback_per_vertex) { + if (base <= UINT32_MAX - 2u && ps_inputs.count(base)) ps_raw_locs.insert({base, base + 1u, base + 2u}); + } // Fast path: every PS half pair is already exported at the exact same locations by VS, all static halves fit // within 0..top_location, and no unused VS static half collides with a raw PS input. @@ -313,7 +322,10 @@ inline bool link_f16_halves(std::vector& vs_words, const ShaderEn if (!already_linked) break; } } - if (already_linked) return true; + if (already_linked) { + if (raw_vs_locations) *raw_vs_locations = vs_raw_locs; + return true; + } // Choose paired [lo, hi] locations for every param in ps_entry.f16_halves. // Keep PS's existing locations unchanged whenever none collides with VS/PS raw outputs/inputs or exceeds top_location. @@ -654,6 +666,7 @@ inline bool link_f16_halves(std::vector& vs_words, const ShaderEn vs_mod.insts = std::move(out_insts); vs_words = vs_mod.serialize(); if (ps_changed) ps_words = ps_mod.serialize(); + if (raw_vs_locations) *raw_vs_locations = std::move(vs_raw_locs); return true; } diff --git a/runtime/test/d3d12_bary_fallback_test.cpp b/runtime/test/d3d12_bary_fallback_test.cpp new file mode 100644 index 0000000000..261d4d0968 --- /dev/null +++ b/runtime/test/d3d12_bary_fallback_test.cpp @@ -0,0 +1,1222 @@ +// End-to-end Vulkan GPU test for `--bary-fallback` D3D12 graphics PSOs (RT-BARY-FALLBACK-PSO). +// +// Exercises graphics PSOs whose pixel shader carries `bary_fallback_input` in `index.json` through the Xbox-ABI +// device proxy on a real Vulkan 1.3 GPU (including GPUs without `VK_KHR_fragment_shader_barycentric`, such as NVIDIA +// Pascal). SPIR-V 1.5 modules are constructed directly in memory — no glslangValidator, llvm-mc or game files needed: +// 1. Perspective-correct barycentrics + pass-through vec4 attribute: draws a fullscreen-covering triangle with +// non-uniform clip W = (1, 2, 4) and verifies all 16x16 pixels match exact perspective-weighted `(b0, b1, b2)` +// plus pass-through `Location 0` alpha (`0.75`), separating perspective interpolation from affine by >40 LSB. +// 2. VS `ClipDistance[1]` forwarding (when `shaderClipDistance` is enabled): clips `ndc_x < 0` to the clear color +// while keeping `ndc_x > 0` with intact barycentrics. +// 3. Unused PS Input pruning + `--f16-interp-fallback` combinations: +// a) 16-param VS (`0..29`) + PS declaring 26 `Input`s (`0..13`, `16..27`) while only reading `Location 7` + +// `bary_fallback_input` at `Location 14`: unread inputs are zero-filled in the GS so `VS -> GS` stays within +// 64 input components (`maxGeometryInputComponents = 64`, e.g. RADV). +// b) 10-param VS (`0..9`) + PS with `bary_fallback_input` at `Location 12` and colliding `f16_halves` at `[9, 10]` +// relocated into `[13, 14]`: exercises combined `--f16-interp-fallback` + `--bary-fallback` within 64 geometry +// input components. +// c) 16-param VS (`0..15`) + PS with `f16_halves` relocated to `[28, 29]`: draws and verifies all 256 pixels when +// `maxGeometryInputComponents >= 120 && maxGeometryOutputComponents >= 120`, or verifies clean logged refusal + +// skips the draw on devices with tighter geometry stage limits. +// 4. Refusals: non-triangle topology (`E_INVALIDARG`), explicit GS (`E_NOTIMPL`), disabled `geometryShader` feature +// (`E_NOTIMPL`), and `maxGeometryInputComponents` / `VUID-RuntimeSpirv-Location-06272` limit refusals (`E_NOTIMPL`). +// 5. Computed I/J pairs (RT-BARY-FALLBACK-PER-VERTEX): a PS that reads an attribute as a `Flat vec4[3]` named by +// `bary_fallback_input.per_vertex` and weights the three vertices' values with its own I/J. The VS gives each +// vertex a different value, and the weights are chosen so that every other order of the three vertices lands +// at least 15 LSB away. Drawn with the block at the attribute's own first locations and relocated next to an +// ordinary input; without the map the same PS is refused (`E_FAIL`). +// Skips (77) when no usable Vulkan 1.3 device or `geometryShader` feature is present. No game data. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/shader_library.h" +#include "../src/spirv_bary_fallback.h" + +#include +#include +#include +#include +#include +#include +#include + +#define EXPECT(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \ +} while (0) + +using namespace d3d12test; +using namespace leonida::spirv_detail; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: handle in RAX + +namespace { + +void put_inst(std::vector& w, std::uint16_t op, std::initializer_list args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + for (std::uint32_t a : args) w.push_back(a); +} + +void put_inst_vec(std::vector& w, std::uint16_t op, const std::vector& args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + w.insert(w.end(), args.begin(), args.end()); +} + +void write_spv(const std::filesystem::path& path, const std::vector& words) { + std::ofstream f(path, std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); +} + +// Triangle VS from VertexIndex (0, 1, 2): +// - If `non_uniform_w` is true: V0 = (-1, -1, 0, 1), V1 = (6, -2, 0, 2), V2 = (-4, 12, 0, 4) +// (same NDC (-1,-1), (3,-1), (-1,3), with w = 1, 2, 4). +// - Else: V0 = (-1, -1, 0, 1), V1 = (3, -1, 0, 1), V2 = (-1, 3, 0, 1). +// Exports Location `attr_loc` = vec4(0.5, 0.25, 0.75, 1.0), and optionally BuiltIn ClipDistance float[1] = {ndc_x}. +std::vector make_bary_vs(bool non_uniform_w, bool with_clip_x, std::uint32_t attr_loc = 0) { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_int = alloc(); + const std::uint32_t id_uint = alloc(); + const std::uint32_t id_bool = alloc(); + const std::uint32_t id_ptr_in_int = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + + const std::uint32_t id_u1 = with_clip_x ? alloc() : 0; + const std::uint32_t id_clip_arr = with_clip_x ? alloc() : 0; + const std::uint32_t id_ptr_out_clip = with_clip_x ? alloc() : 0; + const std::uint32_t id_ptr_out_f = with_clip_x ? alloc() : 0; + + const std::uint32_t id_f0 = alloc(); // 0.0 + const std::uint32_t id_f1 = alloc(); // 1.0 + const std::uint32_t id_fm1 = alloc(); // -1.0 + const std::uint32_t id_f3 = alloc(); // 3.0 + const std::uint32_t id_f2 = alloc(); // 2.0 + const std::uint32_t id_f4 = alloc(); // 4.0 + const std::uint32_t id_f6 = alloc(); // 6.0 + const std::uint32_t id_fm2 = alloc(); // -2.0 + const std::uint32_t id_fm4 = alloc(); // -4.0 + const std::uint32_t id_f12 = alloc(); // 12.0 + const std::uint32_t id_f025 = alloc(); // 0.25 + const std::uint32_t id_f05 = alloc(); // 0.50 + const std::uint32_t id_f075 = alloc(); // 0.75 + + const std::uint32_t id_p0 = alloc(); + const std::uint32_t id_p1 = alloc(); + const std::uint32_t id_p2 = alloc(); + const std::uint32_t id_attr0_val = alloc(); + const std::uint32_t id_i0 = alloc(); + const std::uint32_t id_i1 = alloc(); + + const std::uint32_t id_vid_var = alloc(); + const std::uint32_t id_pos_var = alloc(); + const std::uint32_t id_out0_var = alloc(); + const std::uint32_t id_clip_var = with_clip_x ? alloc() : 0; + + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_vid = alloc(); + const std::uint32_t id_is0 = alloc(); + const std::uint32_t id_is1 = alloc(); + const std::uint32_t id_p12 = alloc(); + const std::uint32_t id_pos = alloc(); + const std::uint32_t id_cx12 = with_clip_x ? alloc() : 0; + const std::uint32_t id_cx = with_clip_x ? alloc() : 0; + const std::uint32_t id_cptr = with_clip_x ? alloc() : 0; + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + put_inst(w, kOpCapability, {1}); // Shader + if (with_clip_x) put_inst(w, kOpCapability, {32}); // ClipDistance + put_inst(w, kOpMemoryModel, {0, 1}); + + std::vector ep = {kExecModelVertex, id_main, 0x6e69616du, 0x00000000u, + id_vid_var, id_pos_var, id_out0_var}; + if (with_clip_x) ep.push_back(id_clip_var); + put_inst_vec(w, kOpEntryPoint, ep); + + put_inst(w, kOpDecorate, {id_vid_var, 11, 42}); // BuiltIn VertexIndex + put_inst(w, kOpDecorate, {id_pos_var, 11, 0}); // BuiltIn Position + put_inst(w, kOpDecorate, {id_out0_var, kDecorationLocation, attr_loc}); + if (with_clip_x) put_inst(w, kOpDecorate, {id_clip_var, 11, 3}); // BuiltIn ClipDistance + + put_inst(w, 19, {id_void}); + put_inst(w, 33, {id_fn, id_void}); + put_inst(w, kOpTypeFloat, {id_float, 32}); + put_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + put_inst(w, kOpTypeInt, {id_int, 32, 1}); + put_inst(w, kOpTypeInt, {id_uint, 32, 0}); + put_inst(w, 20, {id_bool}); + put_inst(w, kOpTypePointer, {id_ptr_in_int, kStorageInput, id_int}); + put_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + if (with_clip_x) { + put_inst(w, 43, {id_uint, id_u1, 1u}); + put_inst(w, 28, {id_clip_arr, id_float, id_u1}); + put_inst(w, kOpTypePointer, {id_ptr_out_clip, kStorageOutput, id_clip_arr}); + put_inst(w, kOpTypePointer, {id_ptr_out_f, kStorageOutput, id_float}); + } + + put_inst(w, 43, {id_float, id_f0, 0x00000000u}); + put_inst(w, 43, {id_float, id_f1, 0x3f800000u}); + put_inst(w, 43, {id_float, id_fm1, 0xbf800000u}); + put_inst(w, 43, {id_float, id_f3, 0x40400000u}); + put_inst(w, 43, {id_float, id_f2, 0x40000000u}); + put_inst(w, 43, {id_float, id_f4, 0x40800000u}); + put_inst(w, 43, {id_float, id_f6, 0x40c00000u}); + put_inst(w, 43, {id_float, id_fm2, 0xc0000000u}); + put_inst(w, 43, {id_float, id_fm4, 0xc0800000u}); + put_inst(w, 43, {id_float, id_f12, 0x41400000u}); + put_inst(w, 43, {id_float, id_f025, 0x3e800000u}); + put_inst(w, 43, {id_float, id_f05, 0x3f000000u}); + put_inst(w, 43, {id_float, id_f075, 0x3f400000u}); + + put_inst(w, 44, {id_v4float, id_p0, id_fm1, id_fm1, id_f0, id_f1}); + if (non_uniform_w) { + put_inst(w, 44, {id_v4float, id_p1, id_f6, id_fm2, id_f0, id_f2}); + put_inst(w, 44, {id_v4float, id_p2, id_fm4, id_f12, id_f0, id_f4}); + } else { + put_inst(w, 44, {id_v4float, id_p1, id_f3, id_fm1, id_f0, id_f1}); + put_inst(w, 44, {id_v4float, id_p2, id_fm1, id_f3, id_f0, id_f1}); + } + put_inst(w, 44, {id_v4float, id_attr0_val, id_f05, id_f025, id_f075, id_f1}); + put_inst(w, 43, {id_int, id_i0, 0u}); + put_inst(w, 43, {id_int, id_i1, 1u}); + + put_inst(w, kOpVariable, {id_ptr_in_int, id_vid_var, kStorageInput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_pos_var, kStorageOutput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_out0_var, kStorageOutput}); + if (with_clip_x) put_inst(w, kOpVariable, {id_ptr_out_clip, id_clip_var, kStorageOutput}); + + put_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + put_inst(w, 248, {id_entry}); + put_inst(w, kOpLoad, {id_int, id_vid, id_vid_var}); + put_inst(w, 170, {id_bool, id_is0, id_vid, id_i0}); // OpIEqual vid 0 + put_inst(w, 170, {id_bool, id_is1, id_vid, id_i1}); // OpIEqual vid 1 + put_inst(w, 169, {id_v4float, id_p12, id_is1, id_p1, id_p2}); + put_inst(w, 169, {id_v4float, id_pos, id_is0, id_p0, id_p12}); + put_inst(w, kOpStore, {id_pos_var, id_pos}); + put_inst(w, kOpStore, {id_out0_var, id_attr0_val}); + if (with_clip_x) { + // ndc_x = (-1 for V0, +3 for V1, -1 for V2) -> clips left half (ndc_x < 0). + put_inst(w, 169, {id_float, id_cx12, id_is1, id_f3, id_fm1}); + put_inst(w, 169, {id_float, id_cx, id_is0, id_fm1, id_cx12}); + put_inst(w, kOpAccessChain, {id_ptr_out_f, id_cptr, id_clip_var, id_i0}); + put_inst(w, kOpStore, {id_cptr, id_cx}); + } + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// PS reading Location `attr_loc` (vec4 attr0) and Location `bary_loc` (vec3 bary), writing vec4(bary.x, bary.y, bary.z, attr0.z). +std::vector make_bary_ps(std::uint32_t bary_loc, std::uint32_t attr_loc = 0) { + // 1=void, 2=fn, 3=float, 4=v3float, 5=v4float, 6=ptr_in_v3, 7=ptr_in_v4, 8=ptr_out_v4, + // 9=out0, 10=in_attr0, 11=in_bary, 12=main, 13=entry, + // 14=attr0, 15=bary, 16=bx, 17=by, 18=bz, 19=az, 20=rgba + constexpr std::uint32_t kBound = 21; + std::vector w = {kSpirvMagic, 0x00010500u, 0, kBound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + put_inst(w, kOpEntryPoint, {kExecModelFragment, 12, 0x6e69616du, 0x00000000u, 9, 10, 11}); + put_inst(w, kOpExecutionMode, {12, 7}); // OriginUpperLeft + + put_inst(w, kOpDecorate, {9, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {10, kDecorationLocation, attr_loc}); + put_inst(w, kOpDecorate, {11, kDecorationLocation, bary_loc}); + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 3}); + put_inst(w, kOpTypeVector, {5, 3, 4}); + put_inst(w, kOpTypePointer, {6, kStorageInput, 4}); + put_inst(w, kOpTypePointer, {7, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {8, kStorageOutput, 5}); + + put_inst(w, kOpVariable, {8, 9, kStorageOutput}); + put_inst(w, kOpVariable, {7, 10, kStorageInput}); + put_inst(w, kOpVariable, {6, 11, kStorageInput}); + + put_inst(w, kOpFunction, {1, 12, 0, 2}); + put_inst(w, 248, {13}); + put_inst(w, kOpLoad, {5, 14, 10}); + put_inst(w, kOpLoad, {4, 15, 11}); + put_inst(w, kOpCompositeExtract, {3, 16, 15, 0}); + put_inst(w, kOpCompositeExtract, {3, 17, 15, 1}); + put_inst(w, kOpCompositeExtract, {3, 18, 15, 2}); + put_inst(w, kOpCompositeExtract, {3, 19, 14, 2}); + put_inst(w, kOpCompositeConstruct, {5, 20, 16, 17, 18, 19}); + put_inst(w, kOpStore, {9, 20}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// Multi-param VS (param0..param(num_raw-1), optional static f16_halves for 0..6, +// param7.x = packHalf2x16(0.25, 0.75) = 0x3a003400, param7.w = 1.0). +std::vector make_nparam_vs(std::uint32_t num_raw, bool with_static_halves) { + const std::uint32_t num_halves = with_static_halves ? 14u : 0u; + const std::uint32_t last_out_id = 30u + num_raw + num_halves; + const std::uint32_t bound = last_out_id + 1u; + std::vector w = {kSpirvMagic, 0x00010500u, 0, bound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + std::vector ep = {kExecModelVertex, 24, 0x6e69616du, 0x00000000u, 8, 9}; + for (std::uint32_t id = 31; id <= last_out_id; ++id) ep.push_back(id); + put_inst_vec(w, kOpEntryPoint, ep); + + put_inst(w, kOpDecorate, {8, 11, 42}); // BuiltIn VertexIndex + put_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position + for (std::uint32_t p = 0; p < num_raw; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p}); + if (with_static_halves) { + const std::uint32_t half_base = 31u + num_raw; + for (std::uint32_t n = 0; n <= 6; ++n) { + put_inst(w, kOpDecorate, {half_base + 2 * n, kDecorationLocation, 28 - 2 * n}); + put_inst(w, kOpDecorate, {half_base + 2 * n + 1, kDecorationLocation, 29 - 2 * n}); + } + } + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 4}); + put_inst(w, kOpTypeInt, {5, 32, 1}); + put_inst(w, kOpTypePointer, {6, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {7, kStorageOutput, 4}); + put_inst(w, 20, {20}); + + put_inst(w, kOpConstantNull, {4, 10}); + put_inst(w, 43, {3, 11, 0xbf800000u}); // -1.0f + put_inst(w, 43, {3, 12, 0x40400000u}); // 3.0f + put_inst(w, 43, {3, 13, 0x00000000u}); // 0.0f + put_inst(w, 43, {3, 14, 0x3f800000u}); // 1.0f + put_inst(w, 44, {4, 15, 11, 11, 13, 14}); + put_inst(w, 44, {4, 16, 12, 11, 13, 14}); + put_inst(w, 44, {4, 17, 11, 12, 13, 14}); + put_inst(w, 43, {5, 18, 0u}); + put_inst(w, 43, {5, 19, 1u}); + put_inst(w, 43, {3, 21, 0x3a003400u}); // packHalf2x16(0.25, 0.75) + put_inst(w, 43, {3, 22, 0x3c003800u}); + put_inst(w, 44, {4, 23, 21, 22, 13, 14}); + + put_inst(w, kOpVariable, {6, 8, kStorageInput}); + put_inst(w, kOpVariable, {7, 9, kStorageOutput}); + for (std::uint32_t id = 31; id <= last_out_id; ++id) put_inst(w, kOpVariable, {7, id, kStorageOutput}); + + put_inst(w, kOpFunction, {1, 24, 0, 2}); + put_inst(w, 248, {25}); + put_inst(w, kOpLoad, {5, 26, 8}); + put_inst(w, 170, {20, 27, 26, 18}); + put_inst(w, 170, {20, 28, 26, 19}); + put_inst(w, 169, {4, 29, 28, 16, 17}); + put_inst(w, 169, {4, 30, 27, 15, 29}); + put_inst(w, kOpStore, {9, 30}); + for (std::uint32_t p = 0; p < num_raw; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u}); + if (with_static_halves) { + for (std::uint32_t id = 31u + num_raw; id <= last_out_id; ++id) put_inst(w, kOpStore, {id, 10}); + } + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// PS declaring 26 vec4 Inputs (0..13 and 16..27) + vec3 bary at 14, loading ONLY Location 7 + bary 14, +// writing vec4(bary.x, bary.y, bary.z, param7.w) to MRT 0. +std::vector make_bary_pruned_ps() { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v3float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_ptr_in_v3 = alloc(); + const std::uint32_t id_ptr_in_v4 = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_out0 = alloc(); + const std::uint32_t id_in_bary = alloc(); + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + + std::uint32_t id_in7 = 0; + std::vector> in_vars; + for (std::uint32_t loc = 0; loc < 28; ++loc) { + if (loc == 14 || loc == 15) continue; + const std::uint32_t vid = alloc(); + in_vars.push_back({vid, loc}); + if (loc == 7) id_in7 = vid; + } + + const std::uint32_t id_bary_val = alloc(); + const std::uint32_t id_v7 = alloc(); + const std::uint32_t id_bx = alloc(); + const std::uint32_t id_by = alloc(); + const std::uint32_t id_bz = alloc(); + const std::uint32_t id_w7 = alloc(); + const std::uint32_t id_rgba = alloc(); + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + std::vector ep = {kExecModelFragment, id_main, 0x6e69616du, 0x00000000u, id_out0, id_in_bary}; + for (const auto& [vid, loc] : in_vars) ep.push_back(vid); + put_inst_vec(w, kOpEntryPoint, ep); + put_inst(w, kOpExecutionMode, {id_main, 7}); + + put_inst(w, kOpDecorate, {id_out0, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {id_in_bary, kDecorationLocation, 14}); + for (const auto& [vid, loc] : in_vars) put_inst(w, kOpDecorate, {vid, kDecorationLocation, loc}); + + put_inst(w, 19, {id_void}); + put_inst(w, 33, {id_fn, id_void}); + put_inst(w, kOpTypeFloat, {id_float, 32}); + put_inst(w, kOpTypeVector, {id_v3float, id_float, 3}); + put_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + put_inst(w, kOpTypePointer, {id_ptr_in_v3, kStorageInput, id_v3float}); + put_inst(w, kOpTypePointer, {id_ptr_in_v4, kStorageInput, id_v4float}); + put_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + + put_inst(w, kOpVariable, {id_ptr_out_v4, id_out0, kStorageOutput}); + put_inst(w, kOpVariable, {id_ptr_in_v3, id_in_bary, kStorageInput}); + for (const auto& [vid, loc] : in_vars) put_inst(w, kOpVariable, {id_ptr_in_v4, vid, kStorageInput}); + + put_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + put_inst(w, 248, {id_entry}); + put_inst(w, kOpLoad, {id_v3float, id_bary_val, id_in_bary}); + put_inst(w, kOpLoad, {id_v4float, id_v7, id_in7}); + put_inst(w, kOpCompositeExtract, {id_float, id_bx, id_bary_val, 0}); + put_inst(w, kOpCompositeExtract, {id_float, id_by, id_bary_val, 1}); + put_inst(w, kOpCompositeExtract, {id_float, id_bz, id_bary_val, 2}); + put_inst(w, kOpCompositeExtract, {id_float, id_w7, id_v7, 3}); + put_inst(w, kOpCompositeConstruct, {id_v4float, id_rgba, id_bx, id_by, id_bz, id_w7}); + put_inst(w, kOpStore, {id_out0, id_rgba}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// Combined f16 + bary PS: reads raw 0..num_raw-1, bary vec3 at `bary_loc`, and f16 halves at `lo_loc`/`hi_loc`, +// writing vec4(lo.x, hi.x, bary.y, bary.z) to MRT 0. +std::vector make_bary_f16_ps(std::uint32_t num_raw, std::uint32_t bary_loc, + std::uint32_t lo_loc, std::uint32_t hi_loc) { + // 1=void, 2=fn, 3=float, 4=v3float, 5=v4float, 6=ptr_in_v3, 7=ptr_in_v4, 8=ptr_out_v4, + // 9=out0, 10=in_bary, 11=in_lo, 12=in_hi, 13=main, 14=entry, + // 15=bary, 16=vlo, 17=vhi, 18=lox, 19=hix, 20=by, 21=bz, 22=rgba, 23..=raw + const std::uint32_t bound = 23 + num_raw; + std::vector w = {kSpirvMagic, 0x00010500u, 0, bound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + std::vector ep = {kExecModelFragment, 13, 0x6e69616du, 0x00000000u, 9, 10, 11, 12}; + for (std::uint32_t i = 0; i < num_raw; ++i) ep.push_back(23 + i); + put_inst_vec(w, kOpEntryPoint, ep); + put_inst(w, kOpExecutionMode, {13, 7}); + + put_inst(w, kOpDecorate, {9, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {10, kDecorationLocation, bary_loc}); + put_inst(w, kOpDecorate, {11, kDecorationLocation, lo_loc}); + put_inst(w, kOpDecorate, {12, kDecorationLocation, hi_loc}); + for (std::uint32_t i = 0; i < num_raw; ++i) put_inst(w, kOpDecorate, {23 + i, kDecorationLocation, i}); + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 3}); + put_inst(w, kOpTypeVector, {5, 3, 4}); + put_inst(w, kOpTypePointer, {6, kStorageInput, 4}); + put_inst(w, kOpTypePointer, {7, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {8, kStorageOutput, 5}); + + put_inst(w, kOpVariable, {8, 9, kStorageOutput}); + put_inst(w, kOpVariable, {6, 10, kStorageInput}); + put_inst(w, kOpVariable, {7, 11, kStorageInput}); + put_inst(w, kOpVariable, {7, 12, kStorageInput}); + for (std::uint32_t i = 0; i < num_raw; ++i) put_inst(w, kOpVariable, {7, 23 + i, kStorageInput}); + + put_inst(w, kOpFunction, {1, 13, 0, 2}); + put_inst(w, 248, {14}); + put_inst(w, kOpLoad, {4, 15, 10}); + put_inst(w, kOpLoad, {5, 16, 11}); + put_inst(w, kOpLoad, {5, 17, 12}); + put_inst(w, kOpCompositeExtract, {3, 18, 16, 0}); // lo.x = 0.25 + put_inst(w, kOpCompositeExtract, {3, 19, 17, 0}); // hi.x = 0.75 + put_inst(w, kOpCompositeExtract, {3, 20, 15, 1}); // bary.y = i + put_inst(w, kOpCompositeExtract, {3, 21, 15, 2}); // bary.z = j + put_inst(w, kOpCompositeConstruct, {5, 22, 18, 19, 20, 21}); + put_inst(w, kOpStore, {9, 22}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// The VS of the computed-I/J draws, from VertexIndex (0, 1, 2): the positions of make_bary_vs(true, ...) (w = 1, 2, +// 4), Location 0 = vec4(0.5, 0.25, 0.75, 1.0) at every vertex, and Location 1 = a different value per vertex: +// (1, 0, 0.5, 0.25), (0, 1, 0.25, 0.5), (0.5, 0.25, 1, 1). +std::vector make_ij_vs() { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_int = alloc(); + const std::uint32_t id_bool = alloc(); + const std::uint32_t id_ptr_in_int = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + + const std::uint32_t id_f0 = alloc(); // 0.0 + const std::uint32_t id_f1 = alloc(); // 1.0 + const std::uint32_t id_fm1 = alloc(); // -1.0 + const std::uint32_t id_f2 = alloc(); // 2.0 + const std::uint32_t id_f4 = alloc(); // 4.0 + const std::uint32_t id_f6 = alloc(); // 6.0 + const std::uint32_t id_fm2 = alloc(); // -2.0 + const std::uint32_t id_fm4 = alloc(); // -4.0 + const std::uint32_t id_f12 = alloc(); // 12.0 + const std::uint32_t id_f025 = alloc(); // 0.25 + const std::uint32_t id_f05 = alloc(); // 0.50 + const std::uint32_t id_f075 = alloc(); // 0.75 + + const std::uint32_t id_p0 = alloc(); + const std::uint32_t id_p1 = alloc(); + const std::uint32_t id_p2 = alloc(); + const std::uint32_t id_attr0_val = alloc(); + const std::uint32_t id_c0 = alloc(); + const std::uint32_t id_c1 = alloc(); + const std::uint32_t id_c2 = alloc(); + const std::uint32_t id_i0 = alloc(); + const std::uint32_t id_i1 = alloc(); + + const std::uint32_t id_vid_var = alloc(); + const std::uint32_t id_pos_var = alloc(); + const std::uint32_t id_out0_var = alloc(); + const std::uint32_t id_out1_var = alloc(); + + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_vid = alloc(); + const std::uint32_t id_is0 = alloc(); + const std::uint32_t id_is1 = alloc(); + const std::uint32_t id_p12 = alloc(); + const std::uint32_t id_pos = alloc(); + const std::uint32_t id_c12 = alloc(); + const std::uint32_t id_col = alloc(); + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + put_inst(w, kOpCapability, {1}); // Shader + put_inst(w, kOpMemoryModel, {0, 1}); + put_inst(w, kOpEntryPoint, {kExecModelVertex, id_main, 0x6e69616du, 0x00000000u, + id_vid_var, id_pos_var, id_out0_var, id_out1_var}); + + put_inst(w, kOpDecorate, {id_vid_var, 11, 42}); // BuiltIn VertexIndex + put_inst(w, kOpDecorate, {id_pos_var, 11, 0}); // BuiltIn Position + put_inst(w, kOpDecorate, {id_out0_var, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {id_out1_var, kDecorationLocation, 1}); + + put_inst(w, 19, {id_void}); + put_inst(w, 33, {id_fn, id_void}); + put_inst(w, kOpTypeFloat, {id_float, 32}); + put_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + put_inst(w, kOpTypeInt, {id_int, 32, 1}); + put_inst(w, 20, {id_bool}); + put_inst(w, kOpTypePointer, {id_ptr_in_int, kStorageInput, id_int}); + put_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + + put_inst(w, 43, {id_float, id_f0, 0x00000000u}); + put_inst(w, 43, {id_float, id_f1, 0x3f800000u}); + put_inst(w, 43, {id_float, id_fm1, 0xbf800000u}); + put_inst(w, 43, {id_float, id_f2, 0x40000000u}); + put_inst(w, 43, {id_float, id_f4, 0x40800000u}); + put_inst(w, 43, {id_float, id_f6, 0x40c00000u}); + put_inst(w, 43, {id_float, id_fm2, 0xc0000000u}); + put_inst(w, 43, {id_float, id_fm4, 0xc0800000u}); + put_inst(w, 43, {id_float, id_f12, 0x41400000u}); + put_inst(w, 43, {id_float, id_f025, 0x3e800000u}); + put_inst(w, 43, {id_float, id_f05, 0x3f000000u}); + put_inst(w, 43, {id_float, id_f075, 0x3f400000u}); + + put_inst(w, 44, {id_v4float, id_p0, id_fm1, id_fm1, id_f0, id_f1}); + put_inst(w, 44, {id_v4float, id_p1, id_f6, id_fm2, id_f0, id_f2}); + put_inst(w, 44, {id_v4float, id_p2, id_fm4, id_f12, id_f0, id_f4}); + put_inst(w, 44, {id_v4float, id_attr0_val, id_f05, id_f025, id_f075, id_f1}); + put_inst(w, 44, {id_v4float, id_c0, id_f1, id_f0, id_f05, id_f025}); + put_inst(w, 44, {id_v4float, id_c1, id_f0, id_f1, id_f025, id_f05}); + put_inst(w, 44, {id_v4float, id_c2, id_f05, id_f025, id_f1, id_f1}); + put_inst(w, 43, {id_int, id_i0, 0u}); + put_inst(w, 43, {id_int, id_i1, 1u}); + + put_inst(w, kOpVariable, {id_ptr_in_int, id_vid_var, kStorageInput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_pos_var, kStorageOutput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_out0_var, kStorageOutput}); + put_inst(w, kOpVariable, {id_ptr_out_v4, id_out1_var, kStorageOutput}); + + put_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + put_inst(w, 248, {id_entry}); + put_inst(w, kOpLoad, {id_int, id_vid, id_vid_var}); + put_inst(w, 170, {id_bool, id_is0, id_vid, id_i0}); // OpIEqual vid 0 + put_inst(w, 170, {id_bool, id_is1, id_vid, id_i1}); // OpIEqual vid 1 + put_inst(w, 169, {id_v4float, id_p12, id_is1, id_p1, id_p2}); + put_inst(w, 169, {id_v4float, id_pos, id_is0, id_p0, id_p12}); + put_inst(w, 169, {id_v4float, id_c12, id_is1, id_c1, id_c2}); + put_inst(w, 169, {id_v4float, id_col, id_is0, id_c0, id_c12}); + put_inst(w, kOpStore, {id_pos_var, id_pos}); + put_inst(w, kOpStore, {id_out0_var, id_attr0_val}); + put_inst(w, kOpStore, {id_out1_var, id_col}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +// The weights the computed-I/J PS gives the three vertices' values: I = 0.5 and J = 0.125 in +// P0 + I * (P1 - P0) + J * (P2 - P0), so 0.375, 0.5 and 0.125. +constexpr float kIjWeights[3] = {0.375f, 0.5f, 0.125f}; +constexpr float kIjValues[3][4] = {{1.0f, 0.0f, 0.5f, 0.25f}, {0.0f, 1.0f, 0.25f, 0.5f}, {0.5f, 0.25f, 1.0f, 1.0f}}; + +// A PS in the shape rdna2spirv.py --bary-fallback gives a computed I/J pair: the attribute is a Flat vec4[3] at +// `pv_base` (element k = vertex k) and the raw barycentrics a vec3 at `bary_loc`. comb = the kIjWeights sum of the +// three elements. Writes vec4(comb.rgb, bary.y), or with `with_attr0` (an ordinary vec4 Input at Location 0) +// vec4(comb.r, comb.g, bary.y, attr0.z). +std::vector make_ij_ps(std::uint32_t pv_base, std::uint32_t bary_loc, bool with_attr0) { + // 1=void, 2=fn, 3=float, 4=v3float, 5=v4float, 6=uint, 7=uint_3, 8=arr, 9=ptr_in_v3, 10=ptr_in_v4, + // 11=ptr_in_arr, 12=ptr_out_v4, 13=int, 14..16=int 0..2, 17..19=weights, 20=out0, 21=in_pv, 22=in_bary, + // 23=in_attr0, 24=main, 25=entry, 26..31=element pointers and values, 32..34=weighted, 35=sum01, 36=comb, + // 37=bary, 38=comb.r, 39=comb.g, 40=comb.b, 41=bary.y, 42=attr0, 43=attr0.z, 44=rgba + constexpr std::uint32_t kBound = 45; + std::vector w = {kSpirvMagic, 0x00010500u, 0, kBound, 0}; + put_inst(w, kOpCapability, {1}); + put_inst(w, kOpMemoryModel, {0, 1}); + std::vector ep = {kExecModelFragment, 24, 0x6e69616du, 0x00000000u, 20, 21, 22}; + if (with_attr0) ep.push_back(23); + put_inst_vec(w, kOpEntryPoint, ep); + put_inst(w, kOpExecutionMode, {24, 7}); // OriginUpperLeft + + put_inst(w, kOpDecorate, {20, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {21, kDecorationLocation, pv_base}); + put_inst(w, kOpDecorate, {21, 14}); // Flat + put_inst(w, kOpDecorate, {22, kDecorationLocation, bary_loc}); + if (with_attr0) put_inst(w, kOpDecorate, {23, kDecorationLocation, 0}); + + put_inst(w, 19, {1}); + put_inst(w, 33, {2, 1}); + put_inst(w, kOpTypeFloat, {3, 32}); + put_inst(w, kOpTypeVector, {4, 3, 3}); + put_inst(w, kOpTypeVector, {5, 3, 4}); + put_inst(w, kOpTypeInt, {6, 32, 0}); + put_inst(w, 43, {6, 7, 3u}); + put_inst(w, 28, {8, 5, 7}); + put_inst(w, kOpTypePointer, {9, kStorageInput, 4}); + put_inst(w, kOpTypePointer, {10, kStorageInput, 5}); + put_inst(w, kOpTypePointer, {11, kStorageInput, 8}); + put_inst(w, kOpTypePointer, {12, kStorageOutput, 5}); + put_inst(w, kOpTypeInt, {13, 32, 1}); + put_inst(w, 43, {13, 14, 0u}); + put_inst(w, 43, {13, 15, 1u}); + put_inst(w, 43, {13, 16, 2u}); + put_inst(w, 43, {3, 17, 0x3ec00000u}); // 0.375 + put_inst(w, 43, {3, 18, 0x3f000000u}); // 0.5 + put_inst(w, 43, {3, 19, 0x3e000000u}); // 0.125 + + put_inst(w, kOpVariable, {12, 20, kStorageOutput}); + put_inst(w, kOpVariable, {11, 21, kStorageInput}); + put_inst(w, kOpVariable, {9, 22, kStorageInput}); + if (with_attr0) put_inst(w, kOpVariable, {10, 23, kStorageInput}); + + put_inst(w, kOpFunction, {1, 24, 0, 2}); + put_inst(w, 248, {25}); + for (std::uint32_t k = 0; k < 3; ++k) { + put_inst(w, kOpAccessChain, {10, 26 + 2 * k, 21, 14 + k}); + put_inst(w, kOpLoad, {5, 27 + 2 * k, 26 + 2 * k}); + put_inst(w, 142, {5, 32 + k, 27 + 2 * k, 17 + k}); // OpVectorTimesScalar + } + put_inst(w, 129, {5, 35, 32, 33}); // OpFAdd + put_inst(w, 129, {5, 36, 35, 34}); + put_inst(w, kOpLoad, {4, 37, 22}); + put_inst(w, kOpCompositeExtract, {3, 38, 36, 0}); + put_inst(w, kOpCompositeExtract, {3, 39, 36, 1}); + put_inst(w, kOpCompositeExtract, {3, 40, 36, 2}); + put_inst(w, kOpCompositeExtract, {3, 41, 37, 1}); + if (with_attr0) { + put_inst(w, kOpLoad, {5, 42, 23}); + put_inst(w, kOpCompositeExtract, {3, 43, 42, 2}); + put_inst(w, kOpCompositeConstruct, {5, 44, 38, 39, 41, 43}); + } else { + put_inst(w, kOpCompositeConstruct, {5, 44, 38, 39, 40, 41}); + } + put_inst(w, kOpStore, {20, 44}); + put_inst(w, kOpReturn, {}); + put_inst(w, kOpFunctionEnd, {}); + return w; +} + +int to_unorm8(float v) { + if (v <= 0.0f) return 0; + if (v >= 1.0f) return 255; + return int(std::lround(v * 255.0f)); +} + +} // namespace + +int main() { + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + + VkPhysicalDeviceProperties props{}; + d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &props); + const std::uint32_t max_gs_in = props.limits.maxGeometryInputComponents; + const std::uint32_t max_gs_out = props.limits.maxGeometryOutputComponents; + std::printf("GPU limits: maxGeometryInputComponents=%u, maxGeometryOutputComponents=%u\n", max_gs_in, max_gs_out); + + const auto vs_persp_prog = fssm_program({0x5653ba01, 0xbf810000}); + const auto vs_clip_prog = fssm_program({0x5653ba02, 0xbf810000}); + const auto vs_16p_prog = fssm_program({0x5653ba03, 0xbf810000}); + const auto vs_10p_prog = fssm_program({0x5653ba04, 0xbf810000}); + const auto vs_loc16_prog = fssm_program({0x5653ba05, 0xbf810000}); + const auto gs_dummy_prog = fssm_program({0x4753ba01, 0xbf810000}); + const auto ps_bary_prog = fssm_program({0x5053ba01, 0xbf810000}); + const auto ps_f16_prog = fssm_program({0x5053ba02, 0xbf810000}); + const auto ps_f16_low_prog = fssm_program({0x5053ba03, 0xbf810000}); + const auto ps_pruned_prog = fssm_program({0x5053ba04, 0xbf810000}); + const auto ps_loc16_prog = fssm_program({0x5053ba05, 0xbf810000}); + const auto vs_ij_prog = fssm_program({0x5653ba06, 0xbf810000}); + const auto ps_ij_prog = fssm_program({0x5053ba06, 0xbf810000}); + const auto ps_ij_reloc_prog = fssm_program({0x5053ba07, 0xbf810000}); + const auto ps_ij_nomap_prog = fssm_program({0x5053ba08, 0xbf810000}); + + const auto vs_persp_c = shader_container(vs_persp_prog); + const auto vs_clip_c = shader_container(vs_clip_prog); + const auto vs_16p_c = shader_container(vs_16p_prog); + const auto vs_10p_c = shader_container(vs_10p_prog); + const auto vs_loc16_c = shader_container(vs_loc16_prog); + const auto gs_dummy_c = shader_container(gs_dummy_prog); + const auto ps_bary_c = shader_container(ps_bary_prog); + const auto ps_f16_c = shader_container(ps_f16_prog); + const auto ps_f16_low_c = shader_container(ps_f16_low_prog); + const auto ps_pruned_c = shader_container(ps_pruned_prog); + const auto ps_loc16_c = shader_container(ps_loc16_prog); + const auto vs_ij_c = shader_container(vs_ij_prog); + const auto ps_ij_c = shader_container(ps_ij_prog); + const auto ps_ij_reloc_c = shader_container(ps_ij_reloc_prog); + const auto ps_ij_nomap_c = shader_container(ps_ij_nomap_prog); + + const auto vs_persp_spv = make_bary_vs(true, false); + const auto ps_bary_spv = make_bary_ps(1); + std::vector gs_dummy_spv; + EXPECT(leonida::build_bary_fallback_gs(vs_persp_spv, ps_bary_spv, 1, gs_dummy_spv)); + + const auto lib_dir = std::filesystem::temp_directory_path() / "leonida_bary_fallback_gpu_test"; + std::filesystem::create_directories(lib_dir); + write_spv(lib_dir / "vs_persp.spv", vs_persp_spv); + write_spv(lib_dir / "vs_clip.spv", make_bary_vs(false, true)); + write_spv(lib_dir / "vs_16p.spv", make_nparam_vs(16, true)); + write_spv(lib_dir / "vs_10p.spv", make_nparam_vs(10, false)); + write_spv(lib_dir / "vs_loc16.spv", make_bary_vs(false, false, 16)); + write_spv(lib_dir / "gs_dummy.spv", gs_dummy_spv); + write_spv(lib_dir / "ps_bary.spv", ps_bary_spv); + write_spv(lib_dir / "ps_bary_f16.spv", make_bary_f16_ps(14, 14, 15, 16)); + write_spv(lib_dir / "ps_bary_f16_low.spv", make_bary_f16_ps(8, 12, 9, 10)); + write_spv(lib_dir / "ps_bary_pruned.spv", make_bary_pruned_ps()); + write_spv(lib_dir / "ps_loc16.spv", make_bary_ps(1, 16)); + write_spv(lib_dir / "vs_ij.spv", make_ij_vs()); + write_spv(lib_dir / "ps_ij.spv", make_ij_ps(0, 3, false)); + write_spv(lib_dir / "ps_ij_reloc.spv", make_ij_ps(4, 1, true)); + write_spv(lib_dir / "ps_ij_nomap.spv", make_ij_ps(0, 3, false)); + { + std::ofstream idx(lib_dir / "index.json", std::ios::binary | std::ios::trunc); + idx << "{\"vs_persp\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_persp_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"vs_clip\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_clip_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"vs_16p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_16p_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], " + "\"f16_halves\": {\"0\": [28, 29], \"1\": [26, 27], \"2\": [24, 25], \"3\": [22, 23], " + "\"4\": [20, 21], \"5\": [18, 19], \"6\": [16, 17]}},\n" + " \"vs_10p\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_10p_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [], \"f16_halves\": {}},\n" + " \"vs_loc16\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_loc16_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + " \"gs_dummy\": {\"stage\": \"gs\", \"fssm_sha256\": \"" << leonida::sha256_hex(gs_dummy_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144},\n" + " \"ps_bary\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_bary_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], \"inputs\": [0], " + "\"bary_fallback_input\": {\"location\": 1}},\n" + " \"ps_bary_f16\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_f16_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " + "\"bary_fallback_input\": {\"location\": 14}, \"f16_halves\": {\"7\": [15, 16]}},\n" + " \"vs_ij\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_ij_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": []},\n" + // Attribute 1 as a vec4[3] at Locations 0..2, barycentrics at 3 (the layout rdna2spirv gives a PS + // whose only input is the computed pair's attribute). + " \"ps_ij\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_ij_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], \"inputs\": [1], " + "\"bary_fallback_input\": {\"location\": 3, \"per_vertex\": {\"1\": 0}}},\n" + // The block relocated to 4..6 next to an ordinary input at 0, barycentrics at 1 (the VS output + // location the block reads). + " \"ps_ij_reloc\": {\"stage\": \"ps\", \"fssm_sha256\": \"" + << leonida::sha256_hex(ps_ij_reloc_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], \"inputs\": [0, 1], " + "\"bary_fallback_input\": {\"location\": 1, \"per_vertex\": {\"1\": 4}}},\n" + " \"ps_ij_nomap\": {\"stage\": \"ps\", \"fssm_sha256\": \"" + << leonida::sha256_hex(ps_ij_nomap_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], \"inputs\": [1], " + "\"bary_fallback_input\": {\"location\": 3}},\n" + " \"ps_bary_f16_low\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_f16_low_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " + "\"bary_fallback_input\": {\"location\": 12}, \"f16_halves\": {\"7\": [9, 10]}},\n" + " \"ps_bary_pruned\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_pruned_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " + "\"bary_fallback_input\": {\"location\": 14}},\n" + " \"ps_loc16\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_loc16_prog) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0], " + "\"bary_fallback_input\": {\"location\": 1}}}"; + } + + constexpr UINT kSize = 16; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; + info.subgroup = d.subgroup; + info.shader_dir = lib_dir.string(); + + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_COMMAND_QUEUE_DESC qd{}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + Ref alloc; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); + Ref list; + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + D3D12_HEAP_PROPERTIES default_hp{D3D12_HEAP_TYPE_DEFAULT}; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = kSize; + rt_desc.Height = kSize; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + Ref rt_res; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&rt_res.p)))); + + D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv_h{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(rt_res.p, nullptr, rtv_h); + + D3D12_HEAP_PROPERTIES rb_hp{D3D12_HEAP_TYPE_READBACK}; + const auto rb_desc = buffer_desc(kSize * 256); + Ref rb_res; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_hp, D3D12_HEAP_FLAG_NONE, &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&rb_res.p)))); + + const auto make_pso_desc = [&](const std::vector& vs, const std::vector& ps) { + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.p; + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pd.SampleMask = 0xffffffffu; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + pd.SampleDesc.Count = 1; + return pd; + }; + + UINT64 fence_val = 0; + const auto draw_and_readback = [&](ID3D12PipelineState* pso, std::vector& out_bytes) -> bool { + if (FAILED(alloc->Reset()) || FAILED(list->Reset(alloc.p, pso))) return false; + const float clear_col[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + list->ClearRenderTargetView(rtv_h, clear_col, 0, nullptr); + list->OMSetRenderTargets(1, &rtv_h, FALSE, nullptr); + const D3D12_VIEWPORT vp = {0.0f, 0.0f, float(kSize), float(kSize), 0.0f, 1.0f}; + const D3D12_RECT sc = {0, 0, LONG(kSize), LONG(kSize)}; + list->RSSetViewports(1, &vp); + list->RSSetScissorRects(1, &sc); + list->SetGraphicsRootSignature(root.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + + const D3D12_RESOURCE_BARRIER to_copy = + transition(rt_res.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = rb_res.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = rt_res.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + const D3D12_RESOURCE_BARRIER to_rt = + transition(rt_res.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_rt); + if (FAILED(list->Close())) return false; + + ID3D12CommandList* cl = list.p; + queue->ExecuteCommandLists(1, &cl); + if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; + ++fence_val; + if (FAILED(queue->Signal(fence.p, fence_val))) return false; + if (FAILED(fence->SetEventOnCompletion(fence_val, nullptr))) return false; + + void* mapped = nullptr; + const D3D12_RANGE read_range = {0, kSize * 256}; + if (FAILED(rb_res->Map(0, &read_range, &mapped)) || !mapped) return false; + out_bytes.assign(static_cast(mapped), + static_cast(mapped) + kSize * 256); + rb_res->Unmap(0, nullptr); + return true; + }; + + // 1. Perspective-correct barycentrics + pass-through vec4 attribute across all 16x16 pixels. + { + auto pd = make_pso_desc(vs_persp_c, ps_bary_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const float l1 = 0.25f * (ndc_x + 1.0f); + const float l2 = 0.25f * (ndc_y + 1.0f); + const float l0 = 1.0f - l1 - l2; + const float denom = l0 / 1.0f + l1 / 2.0f + l2 / 4.0f; + const int want_r = to_unorm8((l0 / 1.0f) / denom); + const int want_g = to_unorm8((l1 / 2.0f) / denom); + const int want_b = to_unorm8((l2 / 4.0f) / denom); + const auto* px = pixels.data() + row * 256 + col * 4; + if (std::abs(int(px[0]) - want_r) > 2 || std::abs(int(px[1]) - want_g) > 2 || + std::abs(int(px[2]) - want_b) > 2 || std::abs(int(px[3]) - 191) > 1) { + std::fprintf(stderr, "persp (%u,%u): got (%u,%u,%u,%u) want (%d,%d,%d,191)\n", + col, row, px[0], px[1], px[2], px[3], want_r, want_g, want_b); + return 1; + } + } + } + const auto* mid = pixels.data() + (kSize / 2) * 256 + (kSize / 2) * 4; + std::printf("ps_bary (perspective w=1,2,4): center=(%u,%u,%u,%u) OK\n", + mid[0], mid[1], mid[2], mid[3]); + } + + // 2. VS ClipDistance[1] forwarding (clips ndc_x < 0 to clear color). + if (d.enabled.shaderClipDistance) { + auto pd = make_pso_desc(vs_clip_c, ps_bary_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const auto* px = pixels.data() + row * 256 + col * 4; + if (col < kSize / 2 - 1) { + EXPECT(px[0] == 0 && px[1] == 0 && px[2] == 0 && px[3] == 0); + } else if (col > kSize / 2) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const float l1 = 0.25f * (ndc_x + 1.0f); + const float l2 = 0.25f * (ndc_y + 1.0f); + const float l0 = 1.0f - l1 - l2; + EXPECT(std::abs(int(px[0]) - to_unorm8(l0)) <= 2); + EXPECT(std::abs(int(px[1]) - to_unorm8(l1)) <= 2); + EXPECT(std::abs(int(px[2]) - to_unorm8(l2)) <= 2); + EXPECT(std::abs(int(px[3]) - 191) <= 1); + } + } + } + std::printf("ps_bary + ClipDistance[1]: left half clipped, right half interpolated OK\n"); + } + + // 3a. Pruned unused PS Inputs (vs_16p exports 0..29, ps_bary_pruned declares 0..13 & 16..27, loads only 7 + bary 14): + // must succeed and draw accurately even on GPUs with maxGeometryInputComponents = 64 (e.g. RADV). + { + auto pd = make_pso_desc(vs_16p_c, ps_pruned_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const float l1 = 0.25f * (ndc_x + 1.0f); + const float l2 = 0.25f * (ndc_y + 1.0f); + const float l0 = 1.0f - l1 - l2; + const auto* px = pixels.data() + row * 256 + col * 4; + EXPECT(std::abs(int(px[0]) - to_unorm8(l0)) <= 2); + EXPECT(std::abs(int(px[1]) - to_unorm8(l1)) <= 2); + EXPECT(std::abs(int(px[2]) - to_unorm8(l2)) <= 2); + EXPECT(px[3] == 255); // param7.w = 1.0 (unread params in vs_16p are 0.0) + } + } + std::printf("ps_bary_pruned (25 unread PS inputs pruned; live Location 7 + bary 14): all 256 pixels OK\n"); + } + + // 3b. Combined --f16-interp-fallback + --bary-fallback within 64 geometry input components (10-param VS): + // runs on all GPUs including RADV (maxGeometryInputComponents = 64). + { + auto pd = make_pso_desc(vs_10p_c, ps_f16_low_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const int want_i = to_unorm8(0.25f * (ndc_x + 1.0f)); + const int want_j = to_unorm8(0.25f * (ndc_y + 1.0f)); + const auto* px = pixels.data() + row * 256 + col * 4; + EXPECT(std::abs(int(px[0]) - 64) <= 1); + EXPECT(std::abs(int(px[1]) - 191) <= 1); + EXPECT(std::abs(int(px[2]) - want_i) <= 2); + EXPECT(std::abs(int(px[3]) - want_j) <= 2); + } + } + std::printf("ps_bary_f16_low (10-param VS + f16 relocation <=14 + bary GS): all 256 pixels OK\n"); + } + + // 3c. Combined --f16-interp-fallback + --bary-fallback on 16-param VS (relocated f16 halves at [28, 29], + // requiring maxGeometryInputComponents >= 120 and maxGeometryOutputComponents >= 120). + { + auto pd = make_pso_desc(vs_16p_c, ps_f16_c); + Ref pso; + const HRESULT hr = device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p)); + if (max_gs_in < 120 || max_gs_out < 120) { + EXPECT(FAILED(hr) && !pso.p); + std::printf( + "SKIP ps_bary_f16 16-param draw: maxGeometryInputComponents=%u, maxGeometryOutputComponents=%u " + "(< 120); refused cleanly\n", + max_gs_in, max_gs_out); + } else { + EXPECT(SUCCEEDED(hr) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const int want_i = to_unorm8(0.25f * (ndc_x + 1.0f)); + const int want_j = to_unorm8(0.25f * (ndc_y + 1.0f)); + const auto* px = pixels.data() + row * 256 + col * 4; + EXPECT(std::abs(int(px[0]) - 64) <= 1); + EXPECT(std::abs(int(px[1]) - 191) <= 1); + EXPECT(std::abs(int(px[2]) - want_i) <= 2); + EXPECT(std::abs(int(px[3]) - want_j) <= 2); + } + } + std::printf("ps_bary_f16 (16-param f16_halves relocation [28,29] + bary GS): all 256 pixels OK\n"); + } + } + + // 5. Computed I/J pairs: the GS hands the PS the triangle's three values of VS output 1 (element k = vertex + // k), which the PS weights itself. Every pixel gets the same sum whatever its position; the barycentric + // channel still has to be the perspective-correct one of draw 1. + { + int want[4]{}; + for (int c = 0; c < 4; ++c) { + want[c] = to_unorm8(kIjWeights[0] * kIjValues[0][c] + kIjWeights[1] * kIjValues[1][c] + + kIjWeights[2] * kIjValues[2][c]); + } + // The nearest wrong answer: the same weights on any other order of the three vertices. + int nearest = 255; + const int orders[5][3] = {{0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}; + for (const auto& o : orders) { + int worst = 0; + for (int c = 0; c < 2; ++c) { // red and green: the channels both draws write + const int v = to_unorm8(kIjWeights[0] * kIjValues[o[0]][c] + kIjWeights[1] * kIjValues[o[1]][c] + + kIjWeights[2] * kIjValues[o[2]][c]); + worst = (std::max)(worst, std::abs(v - want[c])); + } + nearest = (std::min)(nearest, worst); + } + EXPECT(nearest >= 15); + + const auto want_bary_y = [&](UINT col, UINT row) { + const float ndc_x = -1.0f + 2.0f * (float(col) + 0.5f) / float(kSize); + const float ndc_y = +1.0f - 2.0f * (float(row) + 0.5f) / float(kSize); + const float l1 = 0.25f * (ndc_x + 1.0f); + const float l2 = 0.25f * (ndc_y + 1.0f); + const float l0 = 1.0f - l1 - l2; + return to_unorm8((l1 / 2.0f) / (l0 / 1.0f + l1 / 2.0f + l2 / 4.0f)); + }; + + // 5a. The block at Locations 0..2, barycentrics at 3: vec4(comb.rgb, bary.y). + { + auto pd = make_pso_desc(vs_ij_c, ps_ij_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const auto* px = pixels.data() + row * 256 + col * 4; + const int by = want_bary_y(col, row); + if (std::abs(int(px[0]) - want[0]) > 1 || std::abs(int(px[1]) - want[1]) > 1 || + std::abs(int(px[2]) - want[2]) > 1 || std::abs(int(px[3]) - by) > 2) { + std::fprintf(stderr, "ps_ij (%u,%u): got (%u,%u,%u,%u) want (%d,%d,%d,%d)\n", col, row, + px[0], px[1], px[2], px[3], want[0], want[1], want[2], by); + return 1; + } + } + } + const auto* mid = pixels.data() + (kSize / 2) * 256 + (kSize / 2) * 4; + std::printf("ps_ij (per-vertex block at 0..2): center=(%u,%u,%u,%u), all 256 pixels OK\n", + mid[0], mid[1], mid[2], mid[3]); + } + + // 5b. The block relocated to 4..6, an ordinary input at 0, barycentrics at 1: + // vec4(comb.r, comb.g, bary.y, attr0.z). + { + auto pd = make_pso_desc(vs_ij_c, ps_ij_reloc_c); + Ref pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pso.p))) && pso.p); + std::vector pixels; + EXPECT(draw_and_readback(pso.p, pixels)); + for (UINT row = 0; row < kSize; ++row) { + for (UINT col = 0; col < kSize; ++col) { + const auto* px = pixels.data() + row * 256 + col * 4; + const int by = want_bary_y(col, row); + if (std::abs(int(px[0]) - want[0]) > 1 || std::abs(int(px[1]) - want[1]) > 1 || + std::abs(int(px[2]) - by) > 2 || std::abs(int(px[3]) - 191) > 1) { + std::fprintf(stderr, "ps_ij_reloc (%u,%u): got (%u,%u,%u,%u) want (%d,%d,%d,191)\n", col, + row, px[0], px[1], px[2], px[3], want[0], want[1], by); + return 1; + } + } + } + std::printf("ps_ij_reloc (per-vertex block at 4..6 + ordinary input): all 256 pixels OK\n"); + } + + // 5c. The same PS with no per_vertex in its index entry: the vec4[3] input is refused, not mislinked. + { + auto pd = make_pso_desc(vs_ij_c, ps_ij_nomap_c); + Ref bad; + EXPECT(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&bad.p)) == E_FAIL && !bad.p); + } + } + + // 4a & 4b. Refusals: non-triangle topology -> E_INVALIDARG; explicit GS -> E_NOTIMPL. + { + auto pd_lines = make_pso_desc(vs_persp_c, ps_bary_c); + pd_lines.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; + Ref bad; + EXPECT(device->CreateGraphicsPipelineState(&pd_lines, IID_PPV_ARGS(&bad.p)) == E_INVALIDARG && !bad.p); + + auto pd_gs = make_pso_desc(vs_persp_c, ps_bary_c); + pd_gs.GS = {gs_dummy_c.data(), gs_dummy_c.size()}; + EXPECT(device->CreateGraphicsPipelineState(&pd_gs, IID_PPV_ARGS(&bad.p)) == E_NOTIMPL && !bad.p); + } + + // 4c. Refusal when geometryShader is not enabled on VulkanDeviceInfo -> E_NOTIMPL. + { + rt::d3d12::VulkanDeviceInfo info_no_gs = info; + info_no_gs.features.geometryShader = VK_FALSE; + ID3D12Device* inner_no_gs = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info_no_gs, IID_PPV_ARGS(&inner_no_gs)))); + Ref dev_no_gs; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner_no_gs, __uuidof(ID3D12Device), + reinterpret_cast(&dev_no_gs.p)))); + rt::d3d12::set_device_outer(inner_no_gs, dev_no_gs.p); + Ref root2; + EXPECT(SUCCEEDED(dev_no_gs->CreateRootSignature(0, root_blob.data(), root_blob.size(), + IID_PPV_ARGS(&root2.p)))); + auto pd = make_pso_desc(vs_persp_c, ps_bary_c); + pd.pRootSignature = root2.p; + Ref bad; + EXPECT(dev_no_gs->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&bad.p)) == E_NOTIMPL && !bad.p); + } + + // 4d. Simulated RADV-like max_geometry_input_components = 64 on any GPU: + // - pruned high-location PS inputs (ps_bary_pruned) and 10-param f16 relocation (ps_bary_f16_low) succeed; + // - 16-param f16 relocation (ps_bary_f16) and live Location 16 (VUID-06272: 4*16+4 = 68 > 64) refuse cleanly. + { + rt::d3d12::VulkanDeviceInfo info_gs64 = info; + info_gs64.max_geometry_input_components = 64; + ID3D12Device* inner_gs64 = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info_gs64, IID_PPV_ARGS(&inner_gs64)))); + Ref dev_gs64; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner_gs64, __uuidof(ID3D12Device), + reinterpret_cast(&dev_gs64.p)))); + rt::d3d12::set_device_outer(inner_gs64, dev_gs64.p); + Ref root64; + EXPECT(SUCCEEDED(dev_gs64->CreateRootSignature(0, root_blob.data(), root_blob.size(), + IID_PPV_ARGS(&root64.p)))); + + auto pd_pruned = make_pso_desc(vs_16p_c, ps_pruned_c); + pd_pruned.pRootSignature = root64.p; + Ref pso_pruned; + EXPECT(SUCCEEDED(dev_gs64->CreateGraphicsPipelineState(&pd_pruned, IID_PPV_ARGS(&pso_pruned.p))) && + pso_pruned.p); + + auto pd_low = make_pso_desc(vs_10p_c, ps_f16_low_c); + pd_low.pRootSignature = root64.p; + Ref pso_low; + EXPECT(SUCCEEDED(dev_gs64->CreateGraphicsPipelineState(&pd_low, IID_PPV_ARGS(&pso_low.p))) && pso_low.p); + + auto pd_16p = make_pso_desc(vs_16p_c, ps_f16_c); + pd_16p.pRootSignature = root64.p; + Ref bad; + EXPECT(dev_gs64->CreateGraphicsPipelineState(&pd_16p, IID_PPV_ARGS(&bad.p)) == E_NOTIMPL && !bad.p); + + auto pd_loc16 = make_pso_desc(vs_loc16_c, ps_loc16_c); + pd_loc16.pRootSignature = root64.p; + EXPECT(dev_gs64->CreateGraphicsPipelineState(&pd_loc16, IID_PPV_ARGS(&bad.p)) == E_NOTIMPL && !bad.p); + std::printf("max_geometry_input_components=64 checks (pruned OK, 10p f16 OK, 16p & loc16 refused) OK\n"); + } + } + + std::error_code ec; + std::filesystem::remove_all(lib_dir, ec); + EXPECT(!d.validation || d.validation_errors() == 0); + return 0; +} diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index 840d941b0f..9bc22539ec 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -1323,6 +1323,92 @@ int main() { CHECK(huffman_lut_checks() == 0); + // bary_fallback_input.location: exact non-negative u32 parsed; absent or malformed values stay nullopt. + { + const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_bary_test"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + const std::string h0(64, 'a'), h1(64, 'b'), h2(64, 'c'), h3(64, 'd'), h4(64, 'e'); + { + std::ofstream out(dir / "index.json", std::ios::binary | std::ios::trunc); + out << "{\"ps_ok\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h0 + << "\", \"bary_fallback_input\": {\"location\": 3}},\n" + " \"ps_zero\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h1 + << "\", \"bary_fallback_input\": {\"location\": 0}},\n" + " \"ps_neg\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h2 + << "\", \"bary_fallback_input\": {\"location\": -1}},\n" + " \"ps_frac\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h3 + << "\", \"bary_fallback_input\": {\"location\": 1.5}},\n" + " \"ps_none\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << h4 << "\"}}"; + } + ShaderLibrary lib; + std::string err; + CHECK(lib.load(dir, &err)); + const ShaderEntry* ok = lib.find("ps", h0); + const ShaderEntry* zero = lib.find("ps", h1); + const ShaderEntry* neg = lib.find("ps", h2); + const ShaderEntry* frac = lib.find("ps", h3); + const ShaderEntry* none = lib.find("ps", h4); + CHECK(ok && ok->bary_fallback_location.has_value() && *ok->bary_fallback_location == 3u); + CHECK(zero && zero->bary_fallback_location.has_value() && *zero->bary_fallback_location == 0u); + CHECK(neg && !neg->bary_fallback_location.has_value()); + CHECK(frac && !frac->bary_fallback_location.has_value()); + CHECK(none && !none->bary_fallback_location.has_value()); + std::filesystem::remove_all(dir); + } + + // bary_fallback_input.per_vertex (computed I/J pairs): attribute -> first location, both exact u32. One + // malformed entry drops the whole map (the location is still read), so no partial mapping reaches the GS builder. + { + const auto dir = std::filesystem::temp_directory_path() / "leonida_shader_library_bary_pv_test"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + const std::vector> cases = { + {"pv_ok", "{\"0\": 0, \"5\": 6}"}, + {"pv_empty", "{}"}, + {"pv_key", "{\"0\": 0, \"x\": 3}"}, + {"pv_signed_key", "{\"-1\": 3}"}, + {"pv_big_key", "{\"4294967296\": 3}"}, + {"pv_neg", "{\"0\": -1}"}, + {"pv_frac", "{\"0\": 1.5}"}, + {"pv_string", "{\"0\": \"3\"}"}, + {"pv_overflow", "{\"0\": 4294967294}"}, + {"pv_last", "{\"0\": 4294967293}"}, + {"pv_same_attr", "{\"1\": 0, \"01\": 3}"}, + {"pv_array", "[0, 3]"}, + }; + std::map hashes; + { + std::ofstream out(dir / "index.json", std::ios::binary | std::ios::trunc); + out << "{"; + for (std::size_t i = 0; i < cases.size(); ++i) { + const std::string hash(64, char('a' + i)); + hashes[cases[i].first] = hash; + out << (i ? ",\n " : "") << "\"" << cases[i].first << "\": {\"stage\": \"ps\", \"fssm_sha256\": \"" + << hash << "\", \"bary_fallback_input\": {\"location\": 9, \"per_vertex\": " << cases[i].second + << "}}"; + } + out << "}"; + } + ShaderLibrary lib; + std::string err; + CHECK(lib.load(dir, &err)); + using PerVertex = std::map; + for (const auto& [name, json] : cases) { + const ShaderEntry* e = lib.find("ps", hashes[name]); + CHECK(e && e->bary_fallback_location.has_value() && *e->bary_fallback_location == 9u); + PerVertex want; + if (name == "pv_ok") want = {{0, 0}, {5, 6}}; + if (name == "pv_last") want = {{0, 4294967293u}}; + if (e->bary_fallback_per_vertex != want) { + std::fprintf(stderr, "per_vertex case %s: %zu entries read\n", name.c_str(), + e->bary_fallback_per_vertex.size()); + return 1; + } + } + std::filesystem::remove_all(dir); + } + std::printf("SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK\n"); return 0; } diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py index 3cb5eee591..abb75f9499 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -22,11 +22,12 @@ 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. +A PS with a computed I/J pair (ps_ij_computed) also reads the three vertices' values of the attribute through that +geometry shader. With LEONIDA_F16_INTERP_FALLBACK=1, 16-bit interpolants are translated with --f16-interp-fallback (decoded halves from the producer instead of PerVertexKHR inputs); 0 turns that off. With the variable unset, build.py/check.py turn it on -where tools/vk_subgroup_info.py reports no PerVertexKHR inputs (MoltenVK), as scripts/run_gpu_tests.py does. -Under --bary-fallback, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR inputs (or ---f16-interp-fallback without --bary-fallback), and check.py reports it as SKIP. +where tools/vk_subgroup_info.py reports no PerVertexKHR inputs (MoltenVK), as scripts/run_gpu_tests.py does. Alone, +it lowers a computed I/J pair with DerivativeControl and BaryCoordKHR. 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). @@ -48,8 +49,6 @@ MC = mc_command.mc_command() RSRC2, GROUP = 0x8088, (64, 1, 1) -# Not built under the barycentric fallback, set or picked from the device (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 @@ -253,15 +252,6 @@ 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 is refused under --bary-fallback (whereas --f16-interp-fallback lowers it via - # DerivativeControl): check.py and run_gpu_tests.py report it as SKIP under --bary-fallback. Leave it out instead of - # losing the whole batch. - if 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):", - ", ".join(per_vertex)) - names = [n for n in names if n not in per_vertex] if not names: return 0 out.mkdir(parents=True, exist_ok=True) diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index e589299cf2..a46667474d 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -789,7 +789,8 @@ def salu_ext_test(tools, spirv, env=None): # 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/0, or the device probe when it is unset (as build.py reads it): *_f16 interps were -# translated from decoded-half inputs, with no PerVertexKHR inputs (computed I/J pairs use DerivativeControl instead). +# translated from decoded-half inputs, with no PerVertexKHR inputs (computed I/J pairs use DerivativeControl instead, +# or under --bary-fallback the three vertices' values its geometry shader passes). F16_HALVES = f16_interp_fallback() W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), @@ -2147,10 +2148,6 @@ 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: - # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair (no .spv). - return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " - "unsupported under --bary-fallback)") if not os.path.isfile(path): return f"missing {name}.spv" if name == "ps_cbv_modulate": diff --git a/runtime/test/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp new file mode 100644 index 0000000000..59a0ea4fd3 --- /dev/null +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -0,0 +1,835 @@ +// Pure-CPU tests for runtime/src/spirv_bary_fallback.h (RT-BARY-FALLBACK-PSO): +// 1. Basic VS + PS pair: copies BuiltIn Position and pass-through vec4 Locations, emits one-hot vec3 barycentrics. +// 2. Extra unread VS outputs (including at bary_location itself): left unconsumed on VS->GS while GS->PS writes vec3. +// 3. Unexported PS Input Location: zero-filled via OpConstantNull without declaring a dangling GS Input. +// 4. VS ClipDistance[2] and CullDistance[3] forwarding (capabilities, BuiltIn arrays, no duplicate types). +// 5. Combined link_f16_halves + build_bary_fallback_gs: f16 relocation preserves bary_location and forwards relocated halves. +// 6. Clean refusals: mixed ClipDistance + CullDistance, ShaderLayer / ShaderViewportIndex, non-vec3 collision at bary_location. +// 7. Computed I/J pairs (RT-BARY-FALLBACK-PER-VERTEX): a PS `Flat vec4[3]` Input named by `per_vertex` gets the +// triangle's three values of the VS output it maps, with shared GS Inputs, zero-fill and clean refusals; after +// f16 linking, only from the VS's raw outputs, and with the block's three Locations kept free of halves; the +// blocks count in BaryFallbackGsInfo's component bounds. +// 8. Unused PS Input pruning: declared-but-unread PS Inputs are zero-filled on GS->PS without declaring GS Inputs from VS, +// keeping component counts within RADV's maxGeometryInputComponents (64), while OpLoad / OpAccessChain / InterpolateAt* +// pointer reads are preserved. +// Optional `--dump-dir ` writes each synthesized GS binary for external `spirv-val` inspection. +// No GPU or game files required. +#include "../src/spirv_bary_fallback.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \ +} while (0) + +namespace { + +using namespace leonida::spirv_detail; + +void append_inst(std::vector& w, std::uint16_t op, std::initializer_list args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + for (std::uint32_t a : args) w.push_back(a); +} + +void append_inst_vec(std::vector& w, std::uint16_t op, const std::vector& args) { + w.push_back((std::uint32_t(1 + args.size()) << 16) | op); + w.insert(w.end(), args.begin(), args.end()); +} + +struct VsSpec { + std::vector raw_locs; + std::map> static_halves; + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; + std::vector extra_caps; +}; + +std::vector build_vs(const VsSpec& spec) { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v4float = alloc(); + const std::uint32_t id_uint = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_null_v4 = alloc(); + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_pos = alloc(); + + std::uint32_t id_clip_len = 0, id_clip_arr = 0, id_ptr_clip = 0, id_clip_var = 0, id_null_clip = 0; + if (spec.clip_count) { + id_clip_len = alloc(); + id_clip_arr = alloc(); + id_ptr_clip = alloc(); + id_clip_var = alloc(); + id_null_clip = alloc(); + } + std::uint32_t id_cull_len = 0, id_cull_arr = 0, id_ptr_cull = 0, id_cull_var = 0, id_null_cull = 0; + if (spec.cull_count) { + id_cull_len = alloc(); + id_cull_arr = alloc(); + id_ptr_cull = alloc(); + id_cull_var = alloc(); + id_null_cull = alloc(); + } + + std::vector> out_vars; + for (std::uint32_t loc : spec.raw_locs) out_vars.push_back({alloc(), loc}); + for (const auto& [param, pair] : spec.static_halves) { + out_vars.push_back({alloc(), pair[0]}); + out_vars.push_back({alloc(), pair[1]}); + } + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + append_inst(w, kOpCapability, {1}); // Shader + if (spec.clip_count) append_inst(w, kOpCapability, {32}); + if (spec.cull_count) append_inst(w, kOpCapability, {33}); + for (std::uint32_t cap : spec.extra_caps) append_inst(w, kOpCapability, {cap}); + append_inst(w, kOpMemoryModel, {0, 1}); + + std::vector ep = {kExecModelVertex, id_main, 0x6e69616du, 0x00000000u, id_pos}; + if (id_clip_var) ep.push_back(id_clip_var); + if (id_cull_var) ep.push_back(id_cull_var); + for (const auto& [v, loc] : out_vars) ep.push_back(v); + append_inst_vec(w, kOpEntryPoint, ep); + + append_inst(w, kOpDecorate, {id_pos, 11, 0}); // BuiltIn Position + if (id_clip_var) append_inst(w, kOpDecorate, {id_clip_var, 11, 3}); // BuiltIn ClipDistance + if (id_cull_var) append_inst(w, kOpDecorate, {id_cull_var, 11, 4}); // BuiltIn CullDistance + for (const auto& [v, loc] : out_vars) append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); + + append_inst(w, 19, {id_void}); + append_inst(w, 33, {id_fn, id_void}); + append_inst(w, kOpTypeFloat, {id_float, 32}); + append_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + append_inst(w, kOpTypeInt, {id_uint, 32, 0}); + append_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + append_inst(w, kOpConstantNull, {id_v4float, id_null_v4}); + if (spec.clip_count) { + append_inst(w, 43, {id_uint, id_clip_len, spec.clip_count}); + append_inst(w, 28, {id_clip_arr, id_float, id_clip_len}); + append_inst(w, kOpTypePointer, {id_ptr_clip, kStorageOutput, id_clip_arr}); + append_inst(w, kOpConstantNull, {id_clip_arr, id_null_clip}); + } + if (spec.cull_count) { + append_inst(w, 43, {id_uint, id_cull_len, spec.cull_count}); + append_inst(w, 28, {id_cull_arr, id_float, id_cull_len}); + append_inst(w, kOpTypePointer, {id_ptr_cull, kStorageOutput, id_cull_arr}); + append_inst(w, kOpConstantNull, {id_cull_arr, id_null_cull}); + } + + append_inst(w, kOpVariable, {id_ptr_out_v4, id_pos, kStorageOutput}); + if (id_clip_var) append_inst(w, kOpVariable, {id_ptr_clip, id_clip_var, kStorageOutput}); + if (id_cull_var) append_inst(w, kOpVariable, {id_ptr_cull, id_cull_var, kStorageOutput}); + for (const auto& [v, loc] : out_vars) append_inst(w, kOpVariable, {id_ptr_out_v4, v, kStorageOutput}); + + append_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + append_inst(w, 248, {id_entry}); + append_inst(w, kOpStore, {id_pos, id_null_v4}); + if (id_clip_var) append_inst(w, kOpStore, {id_clip_var, id_null_clip}); + if (id_cull_var) append_inst(w, kOpStore, {id_cull_var, id_null_cull}); + for (const auto& [v, loc] : out_vars) append_inst(w, kOpStore, {v, id_null_v4}); + append_inst(w, kOpReturn, {}); + append_inst(w, kOpFunctionEnd, {}); + return w; +} + +std::vector build_ps(const std::vector& raw_locs, + const std::set& flat_locs, + std::optional bary_v3_loc, + const std::map>& f16_halves = {}, + const std::vector& pv_bases = {}, + const std::set& unread_locs = {}, + const std::set& access_chain_locs = {}, + const std::set& interp_centroid_locs = {}) { + std::uint32_t next_id = 1; + const auto alloc = [&]() { return next_id++; }; + + const std::uint32_t id_glsl = interp_centroid_locs.empty() ? 0 : alloc(); + const std::uint32_t id_void = alloc(); + const std::uint32_t id_fn = alloc(); + const std::uint32_t id_float = alloc(); + const std::uint32_t id_v3float = alloc(); + const std::uint32_t id_v4float = alloc(); + // One uint type for the access-chain index and the computed-I/J array length. + const std::uint32_t id_uint = access_chain_locs.empty() && pv_bases.empty() ? 0 : alloc(); + const std::uint32_t id_u0 = access_chain_locs.empty() ? 0 : alloc(); + const std::uint32_t id_ptr_in_f = access_chain_locs.empty() ? 0 : alloc(); + const std::uint32_t id_ptr_in_v3 = alloc(); + const std::uint32_t id_ptr_in_v4 = alloc(); + const std::uint32_t id_ptr_out_v4 = alloc(); + const std::uint32_t id_null_v4 = alloc(); + const std::uint32_t id_out0 = alloc(); + const std::uint32_t id_main = alloc(); + const std::uint32_t id_entry = alloc(); + const std::uint32_t id_bary = bary_v3_loc ? alloc() : 0; + + std::vector> in_v4_vars; + for (std::uint32_t loc : raw_locs) in_v4_vars.push_back({alloc(), loc}); + for (const auto& [param, pair] : f16_halves) { + in_v4_vars.push_back({alloc(), pair[0]}); + in_v4_vars.push_back({alloc(), pair[1]}); + } + // --bary-fallback computed I/J pairs: a Flat vec4[3] Input at each first location (rdna2spirv's pv_fallback). + std::uint32_t id_uint_3 = 0, id_arr_v4_3 = 0, id_ptr_in_arr = 0; + std::vector> in_pv_vars; + if (!pv_bases.empty()) { + id_uint_3 = alloc(); + id_arr_v4_3 = alloc(); + id_ptr_in_arr = alloc(); + for (std::uint32_t base : pv_bases) in_pv_vars.push_back({alloc(), base}); + } + + std::vector w = {kSpirvMagic, 0x00010500u, 0, 0, 0}; + append_inst(w, kOpCapability, {1}); + if (!interp_centroid_locs.empty()) append_inst(w, kOpCapability, {52}); // InterpolationFunction + if (id_glsl) append_inst(w, kOpExtInstImport, {id_glsl, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u}); + append_inst(w, kOpMemoryModel, {0, 1}); + + std::vector ep = {kExecModelFragment, id_main, 0x6e69616du, 0x00000000u, id_out0}; + if (id_bary) ep.push_back(id_bary); + for (const auto& [v, loc] : in_v4_vars) ep.push_back(v); + for (const auto& [v, loc] : in_pv_vars) ep.push_back(v); + append_inst_vec(w, kOpEntryPoint, ep); + append_inst(w, kOpExecutionMode, {id_main, 7}); // OriginUpperLeft + + append_inst(w, kOpDecorate, {id_out0, kDecorationLocation, 0}); + if (id_bary) append_inst(w, kOpDecorate, {id_bary, kDecorationLocation, *bary_v3_loc}); + for (const auto& [v, loc] : in_v4_vars) { + append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); + if (flat_locs.count(loc)) append_inst(w, kOpDecorate, {v, 14}); // Flat + } + for (const auto& [v, loc] : in_pv_vars) { + append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); + append_inst(w, kOpDecorate, {v, 14}); // Flat + } + + append_inst(w, 19, {id_void}); + append_inst(w, 33, {id_fn, id_void}); + append_inst(w, kOpTypeFloat, {id_float, 32}); + append_inst(w, kOpTypeVector, {id_v3float, id_float, 3}); + append_inst(w, kOpTypeVector, {id_v4float, id_float, 4}); + if (id_uint) append_inst(w, kOpTypeInt, {id_uint, 32, 0}); + if (!access_chain_locs.empty()) { + append_inst(w, 43, {id_uint, id_u0, 0u}); + append_inst(w, kOpTypePointer, {id_ptr_in_f, kStorageInput, id_float}); + } + append_inst(w, kOpTypePointer, {id_ptr_in_v3, kStorageInput, id_v3float}); + append_inst(w, kOpTypePointer, {id_ptr_in_v4, kStorageInput, id_v4float}); + append_inst(w, kOpTypePointer, {id_ptr_out_v4, kStorageOutput, id_v4float}); + append_inst(w, kOpConstantNull, {id_v4float, id_null_v4}); + if (!pv_bases.empty()) { + append_inst(w, 43, {id_uint, id_uint_3, 3}); + append_inst(w, 28, {id_arr_v4_3, id_v4float, id_uint_3}); + append_inst(w, kOpTypePointer, {id_ptr_in_arr, kStorageInput, id_arr_v4_3}); + } + + append_inst(w, kOpVariable, {id_ptr_out_v4, id_out0, kStorageOutput}); + if (id_bary) append_inst(w, kOpVariable, {id_ptr_in_v3, id_bary, kStorageInput}); + for (const auto& [v, loc] : in_v4_vars) append_inst(w, kOpVariable, {id_ptr_in_v4, v, kStorageInput}); + for (const auto& [v, loc] : in_pv_vars) append_inst(w, kOpVariable, {id_ptr_in_arr, v, kStorageInput}); + + append_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + append_inst(w, 248, {id_entry}); + if (id_bary) append_inst(w, kOpLoad, {id_v3float, alloc(), id_bary}); + for (const auto& [v, loc] : in_v4_vars) { + if (unread_locs.count(loc)) continue; + if (access_chain_locs.count(loc)) { + const std::uint32_t ptr_id = alloc(); + append_inst(w, kOpAccessChain, {id_ptr_in_f, ptr_id, v, id_u0}); + append_inst(w, kOpLoad, {id_float, alloc(), ptr_id}); + } else if (interp_centroid_locs.count(loc)) { + append_inst(w, kOpExtInst, {id_v4float, alloc(), id_glsl, 76u, v}); // InterpolateAtCentroid + } else { + append_inst(w, kOpLoad, {id_v4float, alloc(), v}); + } + } + append_inst(w, kOpStore, {id_out0, id_null_v4}); + append_inst(w, kOpReturn, {}); + append_inst(w, kOpFunctionEnd, {}); + w[3] = next_id; + return w; +} + +struct GsInspection { + std::set caps; + std::set in_locs; + std::map out_loc_vec_len; // loc -> 3 or 4 + std::set out_pv_locs; // first location of each Flat Output vec4[3] + int out_pv_stores = 0; // stores through an element of such an Output + int out_pv_null_stores = 0; // whole-array zero-fill stores + int emit_vertices = 0; + int end_primitives = 0; + bool has_in_pos = false; + bool has_out_pos = false; + std::uint32_t builtin_dist_in = 0; + std::uint32_t builtin_dist_out = 0; +}; + +bool verify_gs_module(const std::vector& words, GsInspection& out) { + Module mod; + if (!mod.parse(words)) return false; + if (mod.header[1] != 0x00010500u) return false; + out = {}; + + int section = 0; // 0=cap, 1=mem, 2=ep, 3=execmode, 4=dec, 5=types/consts/vars, 6=fn + std::set defined_ids; + std::set ep_iface; + std::set global_vars; + std::uint32_t float_ty = 0; + std::set exec_modes; + std::map vec_len; + std::map ptr_pointee; + std::map> var_info; // var_id -> (storage, pointee) + std::set arr_v4_3_tys; // vec4[3] + std::map uint_consts; + std::set flat_vars; + std::set null_arr_consts; // OpConstantNull of vec4[3] + std::set out_arr_elem_ptrs; // access chains into an Output vec4[3] + bool saw_fn_end = false; + + const auto record_def = [&](std::uint32_t id) { + return id > 0 && id < mod.header[3] && defined_ids.insert(id).second; + }; + + for (const Inst& inst : mod.insts) { + if (saw_fn_end) return false; + switch (inst.opcode) { + case kOpCapability: + if (section > 0 || inst.words.size() != 2) return false; + out.caps.insert(inst.words[1]); + break; + case kOpMemoryModel: + if (section > 1 || inst.words.size() != 3 || inst.words[1] != 0 || inst.words[2] != 1) return false; + section = 1; + break; + case kOpEntryPoint: { + if (section > 2 || inst.words.size() < 5 || inst.words[1] != 3) return false; + section = 2; + const std::size_t s = entry_point_interface_start(inst); + for (std::size_t i = s; i < inst.words.size(); ++i) ep_iface.insert(inst.words[i]); + break; + } + case kOpExecutionMode: + if (section < 2 || section > 3 || inst.words.size() < 3) return false; + if ((inst.words[2] == 0 || inst.words[2] == 26) ? (inst.words.size() != 4) : (inst.words.size() != 3)) + return false; + exec_modes.insert(inst.words[2]); + section = 3; + break; + case kOpDecorate: + if (section < 3 || section > 4) return false; + if (inst.words.size() == 3 && inst.words[2] == 14) flat_vars.insert(inst.words[1]); + section = 4; + break; + case kOpFunction: + if (section < 5 || inst.words.size() != 5) return false; + if (!record_def(inst.words[2])) return false; + section = 6; + break; + case kOpFunctionEnd: + if (section != 6) return false; + saw_fn_end = true; + break; + default: + if (section < 6) { + if (section < 4) return false; + section = 5; + if (inst.opcode == 19 || inst.opcode == 33 || inst.opcode == kOpTypeInt || inst.opcode == kOpTypeFloat || + inst.opcode == kOpTypeVector || inst.opcode == 28 || inst.opcode == kOpTypePointer) { + if (!record_def(inst.words[1])) return false; + if (inst.opcode == kOpTypeFloat && inst.words[2] == 32) float_ty = inst.words[1]; + if (inst.opcode == kOpTypeVector && inst.words[2] == float_ty) vec_len[inst.words[1]] = inst.words[3]; + if (inst.opcode == kOpTypePointer) ptr_pointee[inst.words[1]] = inst.words[3]; + if (inst.opcode == 28 && vec_len.count(inst.words[2]) && vec_len[inst.words[2]] == 4 && + uint_consts.count(inst.words[3]) && uint_consts[inst.words[3]] == 3) + arr_v4_3_tys.insert(inst.words[1]); + } else if (inst.opcode == 43 || inst.opcode == 44 || inst.opcode == kOpConstantNull) { + if (!record_def(inst.words[2])) return false; + if (inst.opcode == 43 && inst.words.size() == 4) uint_consts[inst.words[2]] = inst.words[3]; + if (inst.opcode == kOpConstantNull && arr_v4_3_tys.count(inst.words[1])) + null_arr_consts.insert(inst.words[2]); + } else if (inst.opcode == kOpVariable) { + if (!record_def(inst.words[2])) return false; + global_vars.insert(inst.words[2]); + var_info[inst.words[2]] = {inst.words[3], ptr_pointee[inst.words[1]]}; + } else { + return false; + } + } else { + if (inst.opcode == 248) { + if (!record_def(inst.words[1])) return false; + } else if (inst.opcode == kOpAccessChain || inst.opcode == kOpLoad) { + if (!record_def(inst.words[2])) return false; + if (inst.opcode == kOpAccessChain) { + const auto base = var_info.find(inst.words[3]); + if (base != var_info.end() && base->second.first == kStorageOutput && + arr_v4_3_tys.count(base->second.second)) + out_arr_elem_ptrs.insert(inst.words[2]); + } + } else if (inst.opcode == kOpStore && out_arr_elem_ptrs.count(inst.words[1])) { + ++out.out_pv_stores; + } else if (inst.opcode == kOpStore && null_arr_consts.count(inst.words[2])) { + ++out.out_pv_null_stores; + } else if (inst.opcode == 218) { + ++out.emit_vertices; + } else if (inst.opcode == 219) { + ++out.end_primitives; + } else if (inst.opcode != kOpStore && inst.opcode != kOpReturn) { + return false; + } + } + break; + } + } + if (!saw_fn_end || !out.caps.count(2) || global_vars != ep_iface || + exec_modes != std::set{0, 22, 26, 29}) + return false; + + for (const Inst& inst : mod.insts) { + if (inst.opcode != kOpDecorate || inst.words.size() < 4) continue; + const auto vit = var_info.find(inst.words[1]); + if (vit == var_info.end()) return false; + const std::uint32_t storage = vit->second.first; + const std::uint32_t pt = vit->second.second; + if (inst.words[2] == 11) { // BuiltIn + if (inst.words[3] == 0) { + if (storage == kStorageInput) out.has_in_pos = true; + if (storage == kStorageOutput) out.has_out_pos = true; + } else if (inst.words[3] == 3 || inst.words[3] == 4) { + if (storage == kStorageInput) out.builtin_dist_in = inst.words[3]; + if (storage == kStorageOutput) out.builtin_dist_out = inst.words[3]; + } + } else if (inst.words[2] == kDecorationLocation) { + const std::uint32_t loc = inst.words[3]; + if (storage == kStorageInput) { + if (!out.in_locs.insert(loc).second) return false; + } else if (storage == kStorageOutput && arr_v4_3_tys.count(pt)) { + // A per-vertex block: Flat, and (checked below) three locations clear of every other output. + if (!flat_vars.count(inst.words[1]) || !out.out_pv_locs.insert(loc).second) return false; + } else if (storage == kStorageOutput) { + const auto vlen = vec_len.find(pt); + if (vlen == vec_len.end()) return false; + if (!out.out_loc_vec_len.emplace(loc, vlen->second).second) return false; + } + } + } + for (std::uint32_t base : out.out_pv_locs) { + for (std::uint32_t k = 0; k < 3; ++k) { + if (out.out_loc_vec_len.count(base + k)) return false; + if (k && out.out_pv_locs.count(base + k)) return false; + } + } + return out.has_in_pos && out.has_out_pos && out.emit_vertices == 3 && out.end_primitives == 1; +} + +void maybe_dump(const std::filesystem::path& dump_dir, const char* name, const std::vector& words) { + if (dump_dir.empty()) return; + std::filesystem::create_directories(dump_dir); + std::ofstream f(dump_dir / (std::string(name) + ".spv"), std::ios::binary | std::ios::trunc); + f.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); +} + +} // namespace + +int main(int argc, char** argv) { + using namespace leonida; + std::filesystem::path dump_dir; + if (argc == 3 && std::strcmp(argv[1], "--dump-dir") == 0) dump_dir = argv[2]; + + // 1. Basic VS + PS pair: bary_location = 1, pass-through Location 0 and 2. + { + const auto vs = build_vs({.raw_locs = {0, 2}}); + const auto ps = build_ps({0, 2}, {}, 1); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, &info, &err)); + CHECK(info.clip_count == 0 && info.cull_count == 0); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0, 2})); + CHECK(ins.out_loc_vec_len.size() == 3); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 3 && ins.out_loc_vec_len[2] == 4); + maybe_dump(dump_dir, "gs_basic", gs); + } + + // 2. Extra unread VS outputs (including Location 1 == bary_location): left unconsumed on VS->GS. + { + const auto vs = build_vs({.raw_locs = {0, 1, 2, 3}}); + const auto ps = build_ps({0}, {}, 1); + std::vector gs; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0})); + CHECK(ins.out_loc_vec_len.size() == 2); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 3); + maybe_dump(dump_dir, "gs_unread_vs", gs); + } + + // 3. Unexported PS Flat Input Location 2: zero-filled in GS without declaring a dangling GS Input. + { + const auto vs = build_vs({.raw_locs = {0}}); + const auto ps = build_ps({0, 2}, {2}, 1); + std::vector gs; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0})); + CHECK(ins.out_loc_vec_len.size() == 3); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 3 && ins.out_loc_vec_len[2] == 4); + maybe_dump(dump_dir, "gs_zero_fill", gs); + } + + // 4a. ClipDistance[2] forwarding. + { + const auto vs = build_vs({.raw_locs = {0}, .clip_count = 2}); + const auto ps = build_ps({0}, {}, 1); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, gs, &info, &err)); + CHECK(info.clip_count == 2 && info.cull_count == 0); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK(ins.caps.count(32) == 1 && !ins.caps.count(33)); + CHECK(ins.builtin_dist_in == 3 && ins.builtin_dist_out == 3); + maybe_dump(dump_dir, "gs_clip2", gs); + } + + // 4b. CullDistance[3] forwarding (dist_count == 3 shares %uint_3 cleanly). + { + const auto vs = build_vs({.raw_locs = {1}, .cull_count = 3}); + const auto ps = build_ps({1}, {}, 0); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 0, gs, &info, &err)); + CHECK(info.clip_count == 0 && info.cull_count == 3); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK(ins.caps.count(33) == 1 && !ins.caps.count(32)); + CHECK(ins.builtin_dist_in == 4 && ins.builtin_dist_out == 4); + CHECK(ins.out_loc_vec_len[0] == 3 && ins.out_loc_vec_len[1] == 4); + maybe_dump(dump_dir, "gs_cull3", gs); + } + + // 5. Combined link_f16_halves + build_bary_fallback_gs: + // 16-param VS (raw 0..15) + PS reading raw 0..13, bary_location = 14, f16_halves[7] = [15, 16] (colliding with VS 15). + { + ShaderEntry vs_e, ps_e; + ps_e.f16_halves = {{7, {15, 16}}}; + ps_e.bary_fallback_location = 14; + std::vector vs_raw, ps_raw; + for (std::uint32_t i = 0; i < 16; ++i) vs_raw.push_back(i); + for (std::uint32_t i = 0; i < 14; ++i) ps_raw.push_back(i); + + auto vs = build_vs({.raw_locs = vs_raw}); + auto ps = build_ps(ps_raw, {}, 14, ps_e.f16_halves); + std::string err; + CHECK(link_f16_halves(vs, vs_e, ps, ps_e, &err, 29)); + + std::vector gs; + CHECK(build_bary_fallback_gs(vs, ps, *ps_e.bary_fallback_location, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + // Forwarded: raw 0..13 + relocated f16 halves 28, 29 (16 vec4 inputs); unconsumed VS 14, 15 omitted; bary 14 is vec3. + CHECK(ins.in_locs.size() == 16); + CHECK(!ins.in_locs.count(14) && !ins.in_locs.count(15)); + CHECK(ins.in_locs.count(28) == 1 && ins.in_locs.count(29) == 1); + CHECK(ins.out_loc_vec_len[14] == 3); + CHECK(ins.out_loc_vec_len[28] == 4 && ins.out_loc_vec_len[29] == 4); + maybe_dump(dump_dir, "gs_f16_linked", gs); + } + + // 6. Refusals leave caller's gs_words untouched. + { + const std::vector sentinel = {0xdeadbeefu}; + std::vector gs = sentinel; + std::string err; + + // Mixed ClipDistance + CullDistance. + const auto vs_mixed = build_vs({.raw_locs = {0}, .clip_count = 1, .cull_count = 1}); + const auto ps_ok = build_ps({0}, {}, 1); + CHECK(!build_bary_fallback_gs(vs_mixed, ps_ok, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + + // ShaderLayer (69) and ShaderViewportIndex (70). + const auto vs_layer = build_vs({.raw_locs = {0}, .extra_caps = {69}}); + const auto vs_vp = build_vs({.raw_locs = {0}, .extra_caps = {70}}); + err.clear(); + CHECK(!build_bary_fallback_gs(vs_layer, ps_ok, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + err.clear(); + CHECK(!build_bary_fallback_gs(vs_vp, ps_ok, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + + // bary_location colliding with a vec4 PS Input. + const auto vs_ok = build_vs({.raw_locs = {0, 1}}); + const auto ps_collide = build_ps({0, 1}, {}, std::nullopt); + err.clear(); + CHECK(!build_bary_fallback_gs(vs_ok, ps_collide, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); + } + + // 7. Computed I/J pairs: bary_fallback_input.per_vertex (attribute -> first of three locations). + using PerVertexMap = std::map; + // 7a. The shape of a translated computed-I/J PS: attribute 0 as a Flat vec4[3] at Locations 0..2, barycentrics + // at 3. + { + const auto vs = build_vs({.raw_locs = {0}}); + const auto ps = build_ps({}, {}, 3, {}, {0}); + std::vector gs; + std::string err; + // Without the map the array is still refused, as before. + CHECK(!build_bary_fallback_gs(vs, ps, 3, gs, nullptr, &err) && !err.empty() && gs.empty()); + err.clear(); + CHECK(build_bary_fallback_gs(vs, ps, 3, PerVertexMap{{0, 0}}, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0})); + CHECK((ins.out_pv_locs == std::set{0})); + CHECK(ins.out_loc_vec_len.size() == 1 && ins.out_loc_vec_len[3] == 3); + CHECK(ins.out_pv_stores == 9 && ins.out_pv_null_stores == 0); // three values at each of three vertices + maybe_dump(dump_dir, "gs_per_vertex", gs); + } + + // 7b. A relocated block next to ordinary inputs: attribute 0 -> Locations 3..5, pass-through 1, barycentrics 2; + // the PS also reads Location 0 as an ordinary input, so one GS Input at Location 0 feeds both. + { + const auto vs = build_vs({.raw_locs = {0, 1, 6}}); + const auto ps = build_ps({0, 1}, {}, 2, {}, {3}); + std::vector gs; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 2, PerVertexMap{{0, 3}}, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0, 1})); // 6 is unread and stays unconsumed + CHECK((ins.out_pv_locs == std::set{3})); + CHECK(ins.out_loc_vec_len.size() == 3); + CHECK(ins.out_loc_vec_len[0] == 4 && ins.out_loc_vec_len[1] == 4 && ins.out_loc_vec_len[2] == 3); + CHECK(ins.out_pv_stores == 9); + maybe_dump(dump_dir, "gs_per_vertex_relocated", gs); + } + + // 7c. Two attributes, one of which the VS does not export: that array is zero-filled, with no dangling GS Input. + { + const auto vs = build_vs({.raw_locs = {2}}); + const auto ps = build_ps({}, {}, 0, {}, {1, 4}); + std::vector gs; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 0, PerVertexMap{{2, 1}, {5, 4}}, gs, nullptr, &err)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{2})); + CHECK((ins.out_pv_locs == std::set{1, 4})); + CHECK(ins.out_pv_stores == 9 && ins.out_pv_null_stores == 3); + maybe_dump(dump_dir, "gs_per_vertex_zero_fill", gs); + } + + // 7f. With --f16-interp-fallback linking first (as create_graphics does): the VS exports attributes 0 and 27, not + // 29. The PS halves at 27/28 collide with VS raw 27, so linking moves them to 29/28, and the VS now has an + // output at Location 29. The computed-I/J array of attribute 29 must stay zero-filled. (Reported by + // @marcelofrayha with a GPU draw that read 0.5 instead of 0.) + { + ShaderEntry vs_e, ps_e; + ps_e.bary_fallback_location = 3; + ps_e.bary_fallback_per_vertex = {{29, 0}}; + ps_e.f16_halves = {{0, {27, 28}}}; + auto vs = build_vs({.raw_locs = {0, 27}}); + auto ps = build_ps({}, {}, 3, ps_e.f16_halves, {0}); + std::set raw; + std::string err; + CHECK(link_f16_halves(vs, vs_e, ps, ps_e, &err, 29, &raw)); + CHECK((raw == std::set{0, 27})); + std::vector with_raw, without_raw; + CHECK(build_bary_fallback_gs(vs, ps, 3, ps_e.bary_fallback_per_vertex, with_raw, nullptr, &err, &raw)); + GsInspection ins; + CHECK(verify_gs_module(with_raw, ins)); + CHECK((ins.out_pv_locs == std::set{0})); + CHECK(ins.out_pv_stores == 0 && ins.out_pv_null_stores == 3); + // Without the raw set the decoded half at 29 is what would be forwarded: the case this guards. + CHECK(build_bary_fallback_gs(vs, ps, 3, ps_e.bary_fallback_per_vertex, without_raw, nullptr, &err)); + GsInspection old; + CHECK(verify_gs_module(without_raw, old) && old.out_pv_stores == 9 && old.out_pv_null_stores == 0); + maybe_dump(dump_dir, "gs_per_vertex_f16_missing_raw", with_raw); + } + + // 7g. The same for a static VS half that linking leaves in place (its fast path): VS halves at 28/29, PS has none. + { + ShaderEntry vs_e, ps_e; + vs_e.f16_halves = {{0, {28, 29}}}; + ps_e.bary_fallback_location = 3; + ps_e.bary_fallback_per_vertex = {{29, 0}}; + auto vs = build_vs({.raw_locs = {0}, .static_halves = vs_e.f16_halves}); + const auto vs_before = vs; + auto ps = build_ps({}, {}, 3, {}, {0}); + std::set raw; + std::string err; + CHECK(link_f16_halves(vs, vs_e, ps, ps_e, &err, 29, &raw)); + CHECK(vs == vs_before && (raw == std::set{0})); + std::vector gs; + CHECK(build_bary_fallback_gs(vs, ps, 3, ps_e.bary_fallback_per_vertex, gs, nullptr, &err, &raw)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK(ins.in_locs.empty() && ins.out_pv_stores == 0 && ins.out_pv_null_stores == 3); + maybe_dump(dump_dir, "gs_per_vertex_f16_static_half", gs); + } + + // 7h. Linking keeps a relocated PS half off all three Locations of a computed-I/J block, not only its first: + // block 25..27, PS halves at 28/29 colliding with VS raw 28, so 27 must not be chosen. + { + ShaderEntry vs_e, ps_e; + ps_e.bary_fallback_location = 3; + ps_e.bary_fallback_per_vertex = {{5, 25}}; + ps_e.f16_halves = {{0, {28, 29}}}; + auto vs = build_vs({.raw_locs = {5, 28}}); + auto ps = build_ps({}, {}, 3, ps_e.f16_halves, {25}); + std::set raw; + std::string err; + CHECK(link_f16_halves(vs, vs_e, ps, ps_e, &err, 29, &raw)); + std::vector gs; + CHECK(build_bary_fallback_gs(vs, ps, 3, ps_e.bary_fallback_per_vertex, gs, nullptr, &err, &raw)); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.out_pv_locs == std::set{25}) && ins.out_pv_stores == 9); + CHECK(!ins.in_locs.count(26) && !ins.in_locs.count(27)); + maybe_dump(dump_dir, "gs_per_vertex_f16_block_reserved", gs); + } + + // 7i. BaryFallbackGsInfo counts computed-I/J blocks (#1497's geometry-limit precheck): the GS Input of an + // attribute only a block reads, and the block's three output Locations (12 components), forwarded or + // zero-filled. Attribute 16 with its block at 14..16 needs 68/68, above a 64-component device. The + // validation layer adds the 4 Position components (and Clip/CullDistance) to the Location end, so attribute + // 15 with its block at 13..15 (end 64) is above it too, and attribute 14 at 12..14 (end 60 + 4) is the edge. + // (Found by @ecox982745 and @zmasi, the built-ins on a Vega 20 by @zmasi.) + { + // ok is false when the builder refused or its module did not parse. + const auto footprint = [&](std::uint32_t attr, std::uint32_t base, bool exported, std::uint32_t clip = 0) { + const auto vs = build_vs({.raw_locs = exported ? std::vector{attr} + : std::vector{}, + .clip_count = clip}); + const auto ps = build_ps({}, {}, 3, {}, {base}); + std::vector gs; + BaryFallbackGsInfo info{}; + GsInspection ins; + std::string err; + const bool ok = build_bary_fallback_gs(vs, ps, 3, PerVertexMap{{attr, base}}, gs, &info, &err) && + verify_gs_module(gs, ins); + return std::tuple{ok, info, ins}; + }; + { + const auto [ok, info, ins] = footprint(16, 14, true); + CHECK(ok); + CHECK((ins.in_locs == std::set{16})); + CHECK(info.input_components == 8 && info.max_input_location == 16 && + info.max_input_location_components == 68); + CHECK(info.output_components == 4 + 3 + 12); + CHECK(info.max_output_location == 16 && info.max_output_location_components == 68); + CHECK(info.builtin_components == 4); + } + { + const auto [ok, info, ins] = footprint(15, 13, true); + CHECK(ok && info.max_input_location_components == 64 && info.max_output_location_components == 64); + CHECK(info.max_input_location_components + info.builtin_components == 68); + } + { + const auto [ok, info, ins] = footprint(14, 12, true); + CHECK(ok && info.max_input_location_components + info.builtin_components == 64); + CHECK(info.max_output_location_components + info.builtin_components == 64); + } + { + // A forwarded ClipDistance[2] adds its components to the built-ins on both sides. + const auto [ok, info, ins] = footprint(14, 12, true, 2); + CHECK(ok && info.clip_count == 2 && info.builtin_components == 6); + CHECK(info.max_input_location_components + info.builtin_components == 66); + } + { + // Zero-filled: no GS Input, but the block's Locations still count on the output side. + const auto [ok, info, ins] = footprint(16, 14, false); + CHECK(ok && ins.in_locs.empty() && info.input_components == 4 && info.max_input_location_components == 0); + CHECK(info.output_components == 4 + 3 + 12 && info.max_output_location_components == 68); + } + } + + // 7d. A mapping the PS does not declare is ignored: the module is the one built without it. + { + const auto vs = build_vs({.raw_locs = {0, 2}}); + const auto ps = build_ps({0, 2}, {}, 1); + std::vector plain, mapped; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 1, plain, nullptr, &err)); + CHECK(build_bary_fallback_gs(vs, ps, 1, PerVertexMap{{0, 7}}, mapped, nullptr, &err)); + CHECK(plain == mapped); + } + + // 7e. Refusals leave caller's gs_words untouched. + { + const std::vector sentinel = {0xdeadbeefu}; + std::vector gs = sentinel; + std::string err; + const auto vs = build_vs({.raw_locs = {0, 1}}); + const auto refused = [&](const std::vector& ps, std::uint32_t bary, const PerVertexMap& pv) { + err.clear(); + return !build_bary_fallback_gs(vs, ps, bary, pv, gs, nullptr, &err) && !err.empty() && gs == sentinel; + }; + // The mapped first location holds a plain vec4, not vec4[3]. + CHECK(refused(build_ps({0}, {}, 3), 3, {{0, 0}})); + // The block 0..2 runs into the barycentric location. + CHECK(refused(build_ps({}, {}, 2, {}, {0}), 2, {{0, 0}})); + // The block 0..2 runs into another PS Input (Location 1). + CHECK(refused(build_ps({1}, {}, 3, {}, {0}), 3, {{0, 0}})); + // Two attributes at one first location. + CHECK(refused(build_ps({}, {}, 3, {}, {0}), 3, {{0, 0}, {1, 0}})); + // A first location whose block would pass the last location. + CHECK(refused(build_ps({}, {}, 3, {}, {0}), 3, {{0, 0}, {1, 0xfffffffeu}})); + // An array the map names by its second location only. + CHECK(refused(build_ps({}, {}, 3, {}, {0}), 3, {{0, 1}})); + } + + // 8. Unused PS Input pruning + BaryFallbackGsInfo component bounds: + // VS exports 0..29; PS declares Inputs 0..13 and 16..29 (bary at 14), reading only Location 0 (OpLoad), + // Location 5 (OpAccessChain + OpLoad), and Location 7 (GLSL.std.450 InterpolateAtCentroid). + // All 25 unread PS Inputs must be zero-filled in the GS without declaring GS Inputs from the VS, keeping + // both input_components (16) and max_input_location_components (32) within RADV's 64-component limit. + { + std::vector vs_locs, ps_locs; + std::set unread; + for (std::uint32_t i = 0; i < 30; ++i) { + vs_locs.push_back(i); + if (i == 14 || i == 15) continue; + ps_locs.push_back(i); + if (i != 0 && i != 5 && i != 7) unread.insert(i); + } + const auto vs = build_vs({.raw_locs = vs_locs}); + const auto ps = build_ps(ps_locs, {}, 14, {}, {}, unread, {5}, {7}); + std::vector gs; + BaryFallbackGsInfo info{}; + std::string err; + CHECK(build_bary_fallback_gs(vs, ps, 14, gs, &info, &err)); + CHECK(info.input_components == 16); + CHECK(info.max_input_location == 7 && info.max_input_location_components == 32); + CHECK(info.output_components == 4 + 28 * 4 + 3); + CHECK(info.max_output_location == 29 && info.max_output_location_components == 120); + GsInspection ins; + CHECK(verify_gs_module(gs, ins)); + CHECK((ins.in_locs == std::set{0, 5, 7})); + CHECK(ins.out_loc_vec_len.size() == 29); + CHECK(ins.out_loc_vec_len[14] == 3); + CHECK(ins.out_loc_vec_len[29] == 4); + maybe_dump(dump_dir, "gs_pruned_unused", gs); + } + + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 8369d594c7..25ff15285f 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -503,6 +503,8 @@ class Device { enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available enable.dualSrcBlend = features.features.dualSrcBlend; // d3d12_translated_draw_test --dual-source enable.depthBounds = features.features.depthBounds; // depth-bounds PSOs (d3d12_mesh_test), where available + enable.shaderClipDistance = features.features.shaderClipDistance; // d3d12_bary_fallback_test, where available + enable.shaderCullDistance = features.features.shaderCullDistance; // d3d12_bary_fallback_test, where available const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index 97fba6ee33..7fe499e41d 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -1023,12 +1023,6 @@ 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(): - # Before the .spv check: under --bary-fallback the translator refuses a computed I/J pair, so there - # is no .spv (--f16-interp-fallback alone lowers it via DerivativeControl + BaryCoordKHR). - results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs or BaryCoordKHR; " - "unsupported under --bary-fallback)")) - continue if not os.path.isfile(spv): results.append((name, False, "missing .spv (translation failed)")) continue diff --git a/tests/semantic/fixtures/sparse_bary_locations.asm b/tests/semantic/fixtures/sparse_bary_locations.asm new file mode 100644 index 0000000000..a127106de5 --- /dev/null +++ b/tests/semantic/fixtures/sparse_bary_locations.asm @@ -0,0 +1,20 @@ +; Six sparse scalar inputs leave the first available three-location block at 9. + v_interp_mov_f32_e32 v3, p0, attr0.x + v_interp_mov_f32_e32 v4, p0, attr1.x + v_add_f32_e32 v3, v3, v4 + v_interp_mov_f32_e32 v4, p0, attr2.x + v_add_f32_e32 v3, v3, v4 + v_interp_mov_f32_e32 v4, p0, attr4.x + v_add_f32_e32 v3, v3, v4 + v_interp_mov_f32_e32 v4, p0, attr6.x + v_add_f32_e32 v3, v3, v4 + v_interp_mov_f32_e32 v4, p0, attr8.x + v_add_f32_e32 v3, v3, v4 + v_mov_b32_e32 v0, 0.25 + v_mov_b32_e32 v1, 0.5 + v_interp_p1_f32_e32 v5, v0, attr20.x + v_interp_p2_f32_e32 v5, v1, attr20.x + v_interp_p1_f32_e32 v6, v0, attr21.x + v_interp_p2_f32_e32 v6, v1, attr21.x + exp mrt0 v3, v5, v6, v4 done vm + s_endpgm 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)) - bary = os.environ.get("LEONIDA_BARY_FALLBACK") == "1" spirv = Path(work) / "spirv" spirv.mkdir(parents=True) index = {} for n in names: - if n == "ps_ij_computed" and bary: - continue # "computed I/J pair under --bary-fallback: no PerVertexKHR inputs" (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07") (spirv / (n + ".spvasm")).write_text("; SPIR-V\n", encoding="utf-8") index[n] = {"stage": n[:2]} @@ -99,24 +95,19 @@ def run_build(self, names, env, probe=DESKTOP): status = e.code return status, stdout.getvalue() - def test_bary_fallback_builds_the_rest_without_ps_ij_computed(self): - self.fresh() - status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_BARY_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("PerVertexKHR", printed) - - def test_f16_interp_fallback_builds_ps_ij_computed(self): - self.fresh() - status, printed = self.run_build(["cs_store", "ps_ij_computed"], - {"LEONIDA_F16_INTERP_FALLBACK": "1", "LEONIDA_BARY_FALLBACK": "0"}) - self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) - self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) - self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) + def test_every_fallback_builds_ps_ij_computed(self): + # PerVertexKHR by default, a Flat vec4[3] the geometry shader fills under --bary-fallback (alone or with the + # f16 fallback), DerivativeControl + BaryCoordKHR under --f16-interp-fallback alone. + for env in ({"LEONIDA_BARY_FALLBACK": "1"}, {"LEONIDA_BARY_FALLBACK": "1", "LEONIDA_F16_INTERP_FALLBACK": "1"}, + {"LEONIDA_F16_INTERP_FALLBACK": "1", "LEONIDA_BARY_FALLBACK": "0"}): + with self.subTest(env=env): + self.fresh() + status, printed = self.run_build(["cs_store", "ps_ij_computed"], env) + self.assertEqual(status, 0, printed) + self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) + self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) + self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) + self.assertNotIn("not built (computed", printed) def test_missing_mullit_fixture_is_not_accepted_as_a_build_target(self): status, printed = self.run_build(["ps_mullit"], {}) @@ -124,10 +115,10 @@ def test_missing_mullit_fixture_is_not_accepted_as_a_build_target(self): self.assertEqual(self.asked, []) def test_the_whole_list_builds_under_a_fallback(self): - # Under LEONIDA_BARY_FALLBACK=1 ps_ij_computed is skipped; under LEONIDA_F16_INTERP_FALLBACK=1 alone it builds. + # ps_ij_computed builds under either fallback. status, printed = self.run_build([], {"LEONIDA_BARY_FALLBACK": "1"}) self.assertEqual(status, 0, printed) - self.assertNotIn("ps_ij_computed", self.asked[0]) + self.assertIn("ps_ij_computed", self.asked[0]) published = {p.stem for p in (self.out / "spirv").glob("*.spv")} self.assertEqual(published, set(self.asked[0])) self.fresh() @@ -160,13 +151,12 @@ def test_a_device_without_per_vertex_inputs_selects_the_f16_fallback(self): self.assertEqual(status, 0, printed) self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) - # A device whose probe selects the barycentric fallback still leaves ps_ij_computed out unless overridden. + # A device whose probe selects the barycentric fallback builds it through the geometry shader. self.fresh() anv = {"barycentric_fallback": True, "per_vertex_inputs": False} status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_BARY_FALLBACK": ""}, probe=anv) self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store"]]) - self.assertIn("PerVertexKHR", printed) + self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) # LEONIDA_F16_INTERP_FALLBACK=0 keeps the device's answer out of it. self.fresh() status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_F16_INTERP_FALLBACK": "0"}, diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 0ac52562f0..4c3879bfaa 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -70,6 +70,7 @@ class FakeDevice: vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT ) fragment_shader_barycentric: bool = True + geometry_shader: bool = True max_push_constants_size: int = 256 driver_id: int = 1 # VK_DRIVER_ID_AMD_PROPRIETARY vendor_id: int = 0 @@ -255,6 +256,10 @@ def _get_physical_device_features2(self, phys_dev, p_features): ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.synchronization2) elif stype == 1000225002: # VkPhysicalDeviceSubgroupSizeControlFeaturesEXT ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.subgroup_size_control) + elif stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: + ctypes.c_uint32.from_address( + node_addr + vk_info.FEATURES2_GEOMETRY_SHADER + ).value = int(dev.geometry_shader) elif stype == vk_info.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR: ctypes.c_uint32.from_address(node_addr + 16).value = int(dev.fragment_shader_barycentric) expected = { @@ -820,6 +825,7 @@ def test_native64_conditions_and_boundaries(self): "native64_compute": want_native64 or label == "missing_mesh_stage_bit", "native64": want_native64, "per_vertex_inputs": True, + "geometry_shader": True, "barycentric_fallback": False, "max_push_constants_size": 256, "vendor_id": 0, @@ -836,6 +842,14 @@ def test_max_push_constants_size(self): res, _vk = self._run_query(FakeDevice(max_push_constants_size=limit)) self.assertEqual(res["max_push_constants_size"], limit) + def test_geometry_shader_bit(self): + """geometryShader is VkPhysicalDeviceFeatures' 5th bool, 16 bytes into VkPhysicalDeviceFeatures2.""" + self.assertEqual(vk_info.FEATURES2_GEOMETRY_SHADER, 32) + for want in (True, False): + with self.subTest(geometry_shader=want): + res, _vk = self._run_query(FakeDevice(geometry_shader=want)) + self.assertIs(res["geometry_shader"], want) + def test_per_vertex_inputs(self): """PerVertexKHR needs fragmentShaderBarycentric with its extension listed, and MoltenVK can't compile it to MSL either way. RADV (Mesa 26.2.6) sets the feature on a gfx90c iGPU that doesn't list the extension.""" diff --git a/tools/bary_fallback_gs.py b/tools/bary_fallback_gs.py index 512b3cb0b0..028ddbd1e1 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 @@ -61,16 +65,26 @@ def _validate_shader_name(name: str, index_path: str) -> None: raise ValueError(f"{index_path}: invalid shader name {name!r}") -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(_parse_location(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 = {_parse_location(n): _parse_location(b) for n, b in (per_vertex or {}).items()} + locations = sorted(set(_parse_location(n) for n in locations) - set(per_vertex)) if type(bary_location) is not int or bary_location < 0: raise ValueError(f"bary location must be a non-negative integer, got {bary_location!r}") 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: @@ -81,7 +95,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 []), @@ -97,6 +111,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", @@ -111,6 +128,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", @@ -127,6 +145,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 []), @@ -138,6 +158,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}"] @@ -200,7 +225,7 @@ def distance_count(kind): if not isinstance(inputs, list): raise ValueError(f"{index_path}: index entry {name!r} inputs must be a list") path = os.path.join(spirv_dir, name + SUFFIX + suffix + ".spvasm") - shader = gs_spvasm(inputs, fb["location"], clip_count, cull_count) + shader = gs_spvasm(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 156fdf52f7..a463f32b0e 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -83,6 +83,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 # --int64-addresses: keep 64-bit integer address arithmetic (Int64) instead of lowering it to 32-bit pairs; see @@ -453,6 +458,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) @@ -15455,6 +15461,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 + # shortcut: --f16-interp-fallback has no PerVertexKHR inputs, so computed (i, j) reconstructs P(i, j) from the # smooth input P_c and 1-pixel OpDPdxFine / OpDPdyFine differences of (%bary.y, %bary.z, P). Binary32 rasterizer # quantization on (%bary, P) (~0.5*ulp(P_c) + |P10|*0.5*ulp(I_c) + |P20|*0.5*ulp(J_c)) is amplified by the pixel @@ -16717,8 +16728,21 @@ 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 = 0 + while not taken.isdisjoint((base, base + 1, base + 2)): + base += 1 + 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. @@ -16894,7 +16918,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") @@ -17262,8 +17288,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: @@ -18319,11 +18345,11 @@ def interp_ij_analysis(insns, g): keeping its bit-identical .spv. Refused here (Unsupported, naming the pattern): a computed pair whose ops are not in one basic block (the captured I would not dominate the p2), whose shared partial register -- the f32 vdst, or the f16 p2's fourth operand naming the p1's vdst -- is written - between the ops, or read between them by anything but a p2's partial operand, any computed pair under - --bary-fallback (no PerVertexKHR inputs), and a computed v_interp_*_f32 on a 16-bit-flagged interpolant - (which half the 32-bit op reads is not established). Under --f16-interp-fallback (without --bary-fallback), - Gen.ij_quad_eval approximates P(i, j) from the smooth input via its %entry 2x2 screen-quad barycentric Jacobian - instead of refusing (shortcut: see Gen.ij_quad_eval). Over the corpus all refused classes are empty under + between the ops, or read between them by anything but a p2's partial operand, and a computed v_interp_*_f32 + on a 16-bit-flagged interpolant (which half the 32-bit op reads is not established). Under --bary-fallback the + attributes are Flat vec4[3] inputs its geometry shader fills (bary_fallback_input.per_vertex). Under + --f16-interp-fallback without --bary-fallback, Gen.ij_quad_eval approximates P(i, j) from the smooth input via + its %entry 2x2 screen-quad barycentric Jacobian instead of refusing (shortcut: see Gen.ij_quad_eval). Over the corpus all refused classes are empty under --f16-interp-fallback: 213 PS hold candidate pairs (207 reaching), every pair sits in one block, and no partial is touched between the ops. @@ -18522,8 +18548,6 @@ 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") return attrs @@ -19536,7 +19560,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"]) @@ -19615,11 +19641,17 @@ def _translate(path): if stage == "ps": 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 when PerVertexKHR is available; under --f16-interp-fallback - # (without --bary-fallback), Gen.ij_quad_eval evaluates them from smooth inputs + %entry fine derivatives. - ij_attrs = interp_ij_analysis(insns, g) - if not F16_HALVES: - g.per_vertex |= ij_attrs + # attributes be read per vertex: PerVertexKHR by default, a Flat vec4[3] its geometry shader fills under + # --bary-fallback. Under --f16-interp-fallback without --bary-fallback (no per-vertex inputs, no geometry + # stage) Gen.ij_quad_eval evaluates them from smooth inputs + %entry fine derivatives instead. + computed = interp_ij_analysis(insns, g) + if BARY_FALLBACK or not F16_HALVES: + 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 @@ -20640,11 +20672,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 diff --git a/tools/vk_subgroup_info.py b/tools/vk_subgroup_info.py index ec32e87a7c..67a9ae093b 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -32,7 +32,11 @@ extension list, and a driver other than MoltenVK, whose SPIR-V to MSL conversion rejects the decoration ("PerVertexKHR decoration is not supported in MSL", MoltenVK 1.4.2). The feature alone is not enough: RADV (Mesa 26.2.6) fills it with a one on a gfx90c iGPU (Vega 8, PCI 1002:15E7) that doesn't list the extension. Where it is -false, the shaders are translated with --f16-interp-fallback. +false, the shaders are translated with --f16-interp-fallback. geometry_shader is +VkPhysicalDeviceFeatures.geometryShader. A GPU with geometry shaders and per_vertex_inputs false (no +fragmentShaderBarycentric; the RX 5700 XT in #1285) is translated with --bary-fallback as well, so a computed +I/J pair can read the three vertices' values from the pass-through geometry shader. MoltenVK reports geometry +shaders off, and keeps the f16 fallback alone. barycentric_fallback is true for Intel's open-source Mesa driver (ANV). SHADER-925 found that Mesa ANV 26.2.5 advertises fragmentShaderBarycentric but returns a zero BaryCoordKHR.i for translated pixel shaders on Intel Arc B580; @@ -107,6 +111,8 @@ PROPS_SIZE = 824 # sizeof(VkPhysicalDeviceProperties) on 64-bit FEATURES2_SIZE = 240 # sizeof(VkPhysicalDeviceFeatures2): 16 + 55 VkBool32, padded to 8 +# VkPhysicalDeviceFeatures.geometryShader is the 5th VkBool32, so 16 + 4 * 4. +FEATURES2_GEOMETRY_SHADER = 32 F12_SIZE = 208 # sizeof(VkPhysicalDeviceVulkan12Features): 16 + 47 VkBool32, padded to 8 F13_SIZE = 80 # sizeof(VkPhysicalDeviceVulkan13Features): 16 + 15 VkBool32, padded to 8 # Byte offsets of the VkBool32 members read below (16-byte header, then 4 bytes per member in header order) @@ -361,6 +367,7 @@ def query(*, stage_caps=False) -> dict: sg.requiredSubgroupSizeStages, sg.maxComputeWorkgroupSubgroups, sgc, bool(u32(bary, 16)) and u32(drv, 16) != VK_DRIVER_ID_MOLTENVK, + bool(u32(f2, FEATURES2_GEOMETRY_SHADER)), int.from_bytes(raw[PROPS_MAX_PUSH_CONSTANTS_SIZE:PROPS_MAX_PUSH_CONSTANTS_SIZE + 4], "little"), int.from_bytes(raw[PROPS_VENDOR_ID:PROPS_VENDOR_ID + 4], "little"), int.from_bytes(raw[PROPS_DEVICE_ID:PROPS_DEVICE_ID + 4], "little"), u32(drv, 16), @@ -373,7 +380,8 @@ def query(*, stage_caps=False) -> dict: ) raise RuntimeError("no Vulkan 1.3 GPU with the features and graphics queue the runtime needs") (name, subgroup_size, supported_stages, lo, hi, required_stages, max_workgroup_subgroups, - sgc, per_vertex, max_push_constants_size, vendor, device, driver, chosen_driver_version) = chosen + sgc, per_vertex, geometry_shader, max_push_constants_size, vendor, device, driver, + chosen_driver_version) = chosen if per_vertex: # The feature counts only with its extension listed (RADV sets it on gfx90c without one). # Reuse the Vulkan 1.2 extension set already fetched above, and query Vulkan 1.3 devices only once chosen. @@ -400,6 +408,7 @@ def query(*, stage_caps=False) -> dict: "native64_compute": compute64, "native64": compute64 and mesh64, "per_vertex_inputs": per_vertex, + "geometry_shader": geometry_shader, "barycentric_fallback": barycentric_fallback(vendor, device, driver, chosen_driver_version), "max_push_constants_size": max_push_constants_size, "vendor_id": vendor,