From e7987db42050179a38945e3682e400252112ad96 Mon Sep 17 00:00:00 2001 From: dash Date: Tue, 24 Nov 2026 18:58:41 -0500 Subject: [PATCH 1/8] Translate computed I/J pairs when a GPU has no per-vertex inputs. Those pixel shaders were refused under both fallbacks, so the shaders stage stopped on a geometry-capable GPU without fragmentShaderBarycentric. The barycentric fallback now supplies the three vertex values, and make_game selects it there. Co-authored-by: Cursor --- docs/design.md | 4 +- docs/testing.md | 5 +- make_game.py | 26 +++- runtime/test/shaders/build.py | 16 ++- runtime/test/shaders/check.py | 9 +- scripts/run_gpu_tests.py | 11 +- tests/semantic/support.py | 6 +- tests/semantic/test_interp_computed_ij.py | 167 ++++++++++++++++++++-- tests/test_make_game_translator_flags.py | 25 +++- tests/test_run_gpu_tests.py | 39 ++--- tests/test_shader_build_fallbacks.py | 36 +++-- tests/test_vk_subgroup_info.py | 14 ++ tools/bary_fallback_gs.py | 35 ++++- tools/rdna2spirv.py | 60 ++++++-- tools/vk_subgroup_info.py | 12 +- 15 files changed, 370 insertions(+), 95 deletions(-) diff --git a/docs/design.md b/docs/design.md index 2e0d0582a6..add664e3ba 100644 --- a/docs/design.md +++ b/docs/design.md @@ -372,7 +372,7 @@ How the generated SPIR-V expects the runtime to work: | `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. | | PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | | Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | +| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--f16-interp-fallback` without `--bary-fallback` (no per-vertex inputs; the decoded-half read would otherwise drop the computed weights; with `--bary-fallback`, alone or with it, the geometry shader supplies the three vertices' values: "Barycentric fallback" below), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | | Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). | | Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does 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). | @@ -405,7 +405,7 @@ How the generated SPIR-V expects the runtime to work: | Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | | Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | | Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | -| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | +| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `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`. With both fallbacks, 10,011 translate (9,804 before). Every other module is byte-identical to before in all three modes (no fallback, `--bary-fallback`, both). GPU-checked on the GTX 1060 (driver 560.94): `ps_ij_computed` passes through its geometry shader with `LEONIDA_BARY_FALLBACK=1`, with the f16 fallback on (the default there) and off. Checked in `tests/semantic/test_interp_computed_ij.py` (`ComputedIJBaryFallback`: the same values as the `PerVertexKHR` path for every computed form, the f16 pair under both fallbacks, the locations, the geometry shader). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/docs/testing.md b/docs/testing.md index 71aacf533d..2399e883b3 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -602,7 +602,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 @@ -746,6 +748,7 @@ game's device ignores it`, so leaving them set cannot slow a game down (`run_tin | `check.py`'s `cs_fma_fused` fails on a Mac with MoltenVK 1.4.2: word 7 reads `15360` (`0x3c00`), want `29521` (`0x7351`) | The f16 multiply-add (round to odd). The MSL of 1.4.2 and of MoltenVK `main` differ only in SPIRV-Cross's precise-arithmetic helpers (`[[clang::optnone]]` and `fma(l, r, 0)` against `math_mode(safe)` and `fma(l, r, -0.0)`, the SHADER-182 / SHADER-234 change) | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` | | `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | | With `LEONIDA_W64_EMULATE=1` on llvmpipe, the `ms_*` tests fail. Measured with Mesa 26.3.1: on x86_64 at 256-bit vectors (the default there) all six abort with "LLVM ERROR: Cannot emit physreg copy instruction"; on arm64 (128-bit) `ms_tri` draws nothing (the frame stays at the clear color); on x86_64 at 128 bits (`LP_NATIVE_VECTOR_WIDTH=128`) `ms_tri` happened to draw correctly, but with Mesa 26.0.3 `ms_wave_info_s3` and `ms_v5_workgroup` draw nothing there (4 of 6 pass, [measured by @TreXito](https://github.com/ItsNotRexed/Leonida/pull/3838#issuecomment-7086696759)) ([measured runs](https://github.com/ItsNotRexed/Leonida/issues/3127#issuecomment-7086469679)) | An llvmpipe bug: a mesh shader's runtime `CullPrimitiveEXT` is stored through an invalid `bitcast to ` (TEST-782, #3127; see "Without a GPU: Mesa llvmpipe") | Run the mesh tests on llvmpipe without `LEONIDA_W64_EMULATE`, or add `LEONIDA_MESH_COMPUTE=1` (the compute fallback): with it all 6 `ms_*` pass emulated on llvmpipe (x86_64, 256-bit) | +| `ps_ij_computed` is skipped on a Mac, with or without `LEONIDA_BARY_FALLBACK=1` ("computed I/J pairs need per-vertex inputs", or `unsupported: no geometryShader`) | A computed I/J pair needs the three vertices' values of the attribute: `PerVertexKHR` inputs, or under `--bary-fallback` the geometry shader that passes them (`docs/design.md`, "Barycentric fallback"). MoltenVK has neither, and `--f16-interp-fallback` alone has no per-vertex inputs | Expected; nothing to do. Devices with geometry shaders (NVIDIA Pascal, for one) run it with `LEONIDA_BARY_FALLBACK=1` | | On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | | A pixel shader exporting non-canonical f32 NaNs reads back `0x7fc00000` from an RGBA32F color attachment | KosmicKrisp (Mesa 26.3.1), reproduced on Apple M3 Max, M2 Ultra and M1 Pro ([#3125](https://github.com/ItsNotRexed/Leonida/issues/3125)): `nir_to_msl` emits `(NAN)` for `float`-typed NaN constants (`MESA_KK_DEBUG=msl`); MoltenVK 1.4.2 preserved both tested payloads on the same hardware | `ps_nan_payload` allows the measured canonical word only for the NaN channels and only when `vk_harness` reports `driver: KosmicKrisp`. Finite channels and other drivers still require exact words. Integer or storage-buffer readback still canonicalizes constants that NIR infers as `float` (see the `cs_bvh` row below). | | `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words | diff --git a/make_game.py b/make_game.py index 0f5c499cbc..ff87479423 100644 --- a/make_game.py +++ b/make_game.py @@ -1805,6 +1805,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() @@ -2981,6 +2990,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: @@ -3003,11 +3013,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/test/shaders/build.py b/runtime/test/shaders/build.py index 03a7ecd229..1ee3d57b59 100644 --- a/runtime/test/shaders/build.py +++ b/runtime/test/shaders/build.py @@ -22,8 +22,9 @@ With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and each gets a pass-through geometry shader, .bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). With the variable unset, build.py/check.py follow the Mesa ANV probe automatically. -Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR -inputs, and check.py reports it as SKIP. +A PS with a computed I/J pair (ps_ij_computed) also reads the three vertices' values of the attribute through that +geometry shader. Under LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs the +per-vertex values, which that fallback doesn't have, and check.py reports it as SKIP. With LEONIDA_PC_TAIL_UBO=1, every shader is translated with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the heap base and code base in a uniform block at set 1), for devices whose maxPushConstantsSize is 128; set it for check.py too, whose test programs then bind that block (runtime/test/vk_pc_tail.h). @@ -45,7 +46,7 @@ MC = mc_command.mc_command() RSRC2, GROUP = 0x8088, (64, 1, 1) -# Not built under LEONIDA_BARY_FALLBACK=1 or LEONIDA_F16_INTERP_FALLBACK=1 (see main). +# Not built under LEONIDA_F16_INTERP_FALLBACK=1 (see main). NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",) sys.path.insert(0, HERE) # this script is also run with python -I from compute_fixture import compute_header, shift_user_data, user_data_shift # noqa: E402 @@ -221,12 +222,13 @@ def main(): if skipped: print("not built (need a DXBC container with signatures):", ", ".join(skipped)) names = [n for n in names if n not in skipped] - # A computed I/J pair needs PerVertexKHR inputs, which both fallbacks take away: the translator refuses it there, - # and check.py and run_gpu_tests.py report it as SKIP. Leave it out instead of losing the whole batch. - if barycentric_fallback() or os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1": + # A computed I/J pair needs the three vertices' values, which --f16-interp-fallback doesn't have (--bary-fallback + # gets them from its geometry shader): the translator refuses it there, and check.py and run_gpu_tests.py report + # it as SKIP. Leave it out instead of losing the whole batch. + if os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" and not barycentric_fallback(): per_vertex = [n for n in names if n in NEEDS_PER_VERTEX_INPUTS] if per_vertex: - print("not built (computed I/J pairs need PerVertexKHR inputs, off under the fallback):", + print("not built (computed I/J pairs need per-vertex inputs, off under --f16-interp-fallback):", ", ".join(per_vertex)) names = [n for n in names if n not in per_vertex] if not names: diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py index 3b73d736fb..889e0de714 100644 --- a/runtime/test/shaders/check.py +++ b/runtime/test/shaders/check.py @@ -721,7 +721,8 @@ def frexp_ldexp_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 (as build.py reads it): *_f16 interps were translated from decoded-half inputs, with no -# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there. +# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there. (--bary-fallback +# translates it: its geometry shader passes the three vertices' values.) F16_HALVES = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), @@ -2055,9 +2056,9 @@ def nan_payload_problem(px, out): def pixel_test(tools, spirv, name): path = os.path.join(spirv, name + ".spv") - if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair (no .spv). - return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)") + if name == "ps_ij_computed" and F16_HALVES and not BARY_FALLBACK: + # Before the .spv check: without per-vertex inputs the translator refuses a computed I/J pair (no .spv). + return Skip("SKIP (computed I/J pairs need per-vertex inputs: --f16-interp-fallback without --bary-fallback)") if not os.path.isfile(path): return f"missing {name}.spv" if name == "ps_cbv_modulate": diff --git a/scripts/run_gpu_tests.py b/scripts/run_gpu_tests.py index fef03e9c94..5c6ac53697 100644 --- a/scripts/run_gpu_tests.py +++ b/scripts/run_gpu_tests.py @@ -985,11 +985,12 @@ def run_suite(a, work: str) -> int: for fname in asm_files: name = os.path.splitext(fname)[0] spv = os.path.join(spirv_dir, f"{name}.spv") - if name == "ps_ij_computed" and (bary_fallback() or f16_interp_fallback()): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair, so there - # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). - results.append((name, None, "SKIP (computed I/J pairs need PerVertexKHR inputs: " - "no --bary-fallback / --f16-interp-fallback)")) + if name == "ps_ij_computed" and f16_interp_fallback() and not bary_fallback(): + # Before the .spv check: without per-vertex inputs the translator refuses a computed I/J pair, so there + # is no .spv (the f16 fallback is on by default where PerVertexKHR doesn't compile: MoltenVK). Under + # --bary-fallback the geometry shader passes the three vertices' values, so it runs. + results.append((name, None, "SKIP (computed I/J pairs need per-vertex inputs: " + "--f16-interp-fallback without --bary-fallback)")) continue if not os.path.isfile(spv): results.append((name, False, "missing .spv (translation failed)")) diff --git a/tests/semantic/support.py b/tests/semantic/support.py index 950890271e..dd8032fbbd 100644 --- a/tests/semantic/support.py +++ b/tests/semantic/support.py @@ -72,12 +72,14 @@ def mrt0_words(spvasm, **run_options): def varyings(spvasm, attrs, bary): """Input values for a translated PS, given {attribute n: three per-vertex vec4s of the producer's raw 32-bit words} and the barycentric weights `bary` of vertices 0..2, as Vulkan hands them over: a PerVertexKHR input gets - the three vertices, a Flat one vertex 0, any other the words read as f32 and interpolated; %bary gets `bary`.""" + the three vertices, a Flat one vertex 0, any other the words read as f32 and interpolated; %bary gets `bary`. + A Flat vec4[3] (--bary-fallback's per-vertex attribute) gets the three vertices, as its geometry shader writes + them.""" f = lambda w: struct.unpack("/spirv: a module and an index entry per shader it validated.""" self.asked.append(list(names)) - fallback = any(os.environ.get(v) == "1" for v in FALLBACKS) + fallback = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" and os.environ.get("LEONIDA_BARY_FALLBACK") != "1" spirv = Path(work) / "spirv" spirv.mkdir(parents=True) index = {} @@ -79,17 +80,24 @@ def run_build(self, names, env): status = e.code return status, stdout.getvalue() - def test_each_fallback_builds_the_rest_without_ps_ij_computed(self): - for var in FALLBACKS: - with self.subTest(fallback=var): + def test_the_f16_fallback_builds_the_rest_without_ps_ij_computed(self): + status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_F16_INTERP_FALLBACK": "1"}) + self.assertEqual(status, 0, printed) + self.assertEqual(self.asked, [["cs_store"]]) + self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) + self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) + self.assertIn("ps_ij_computed", printed) + self.assertIn("per-vertex inputs", printed) + + def test_the_bary_fallback_builds_ps_ij_computed(self): + for env in ({"LEONIDA_BARY_FALLBACK": "1"}, {"LEONIDA_BARY_FALLBACK": "1", "LEONIDA_F16_INTERP_FALLBACK": "1"}): + with self.subTest(env=env): self.fresh() - status, printed = self.run_build(["cs_store", "ps_ij_computed"], {var: "1"}) + status, printed = self.run_build(["cs_store", "ps_ij_computed"], env) self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store"]]) - self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) - self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) - self.assertIn("ps_ij_computed", printed) - self.assertIn("PerVertexKHR", printed) + self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) + self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) + self.assertNotIn("not built (computed", printed) def test_missing_mullit_fixture_is_not_accepted_as_a_build_target(self): status, printed = self.run_build(["ps_mullit"], {}) diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 9f8ff15b69..3b4935552d 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py @@ -69,6 +69,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 @@ -250,6 +251,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 = { @@ -814,6 +819,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, @@ -830,6 +836,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, and MoltenVK can't compile it to MSL either way.""" for label, bary, driver, want in (("amd", True, 1, True), ("no_barycentrics", False, 1, False), diff --git a/tools/bary_fallback_gs.py b/tools/bary_fallback_gs.py index 7533fdd57c..5ece83d1fb 100644 --- a/tools/bary_fallback_gs.py +++ b/tools/bary_fallback_gs.py @@ -8,6 +8,10 @@ vertices. Default (perspective) interpolation of those gives the perspective-correct barycentrics, the value BaryCoordKHR has, so the pixel shader's .y/.z are AMD's i/j. +An attribute a computed I/J pair reads (SHADER-177) is listed in "bary_fallback_input" under "per_vertex", with the +first of three locations: the geometry shader writes the three vertices' values of the attribute there, as a Flat +vec4[3] (element k = vertex k) at every vertex it emits, which the pixel shader weights with its own I/J. + python -I tools/bary_fallback_gs.py # .bary_gs.spv per such PS in index.json python -I tools/bary_fallback_gs.py --pair VS PS @@ -28,16 +32,26 @@ SUFFIX = ".bary_gs" # .bary_gs.spvasm / .spv next to the pixel shader -def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0): +def gs_spvasm(locations, bary_location, clip_count: int = 0, cull_count: int = 0, per_vertex=None): """SPIR-V assembly for a triangle pass-through GS: Position and the vec4 inputs at `locations`, copied per vertex, - plus the one-hot barycentric vec3 at `bary_location`.""" - locations = sorted(set(int(n) for n in locations)) + plus the one-hot barycentric vec3 at `bary_location`. `per_vertex` maps an attribute (an input location) to the + first of three output locations that get its three vertices' values as a Flat vec4[3] instead of a copy.""" + per_vertex = {int(n): int(b) for n, b in (per_vertex or {}).items()} + locations = sorted(set(int(n) for n in locations) - set(per_vertex)) if 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: @@ -48,7 +62,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 []), @@ -64,6 +78,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", @@ -78,6 +95,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", @@ -94,6 +112,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 []), @@ -105,6 +125,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}"] @@ -156,7 +181,7 @@ def distance_count(kind): if not fb: continue path = os.path.join(spirv_dir, name + SUFFIX + suffix + ".spvasm") - shader = gs_spvasm(meta.get("inputs", []), fb["location"], clip_count, cull_count) + shader = gs_spvasm(meta.get("inputs", []), fb["location"], clip_count, cull_count, fb.get("per_vertex")) yield path, shader diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 7dc94f29c0..17f0ea2427 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -65,6 +65,11 @@ # VK_KHR_fragment_shader_barycentric. Whatever feeds the stage before the PS (a pass-through geometry shader) writes # (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices; interpolating those gives the perspective-correct # barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. +# An attribute a computed I/J pair reads (SHADER-177), which needs the three vertices' values, is a Flat vec4[3] +# input instead of PerVertexKHR, at three consecutive locations no other input uses ("per_vertex" in +# bary_fallback_input: attribute -> first location). The geometry shader writes vertex k's value of the attribute +# into element k at every vertex it emits, so the flat value is the triangle's three values whatever the provoking +# vertex; Gen.attribute then weights them as on the PerVertexKHR path. BARY_FALLBACK = False SHADER_CLOCK = False FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma @@ -274,6 +279,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) @@ -14448,6 +14454,11 @@ def pair_value(self, r): self.emit(f"{t} = OpBitcast %float {u}") return t + def pv_input(self, name): + """Whether input variable `name` is an attribute read per vertex (a vec4[3]: PerVertexKHR, or Flat under + --bary-fallback). By attribute number, since --bary-fallback moves such an input off its own location.""" + return name.startswith("%in_attr") and int(name[len("%in_attr"):]) in self.per_vertex + def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). @@ -15520,8 +15531,19 @@ def assemble(gen): if k.startswith("%in_f16h"): a_str, h_str = k[len("%in_f16h"):].split("_") gen.inputs[k] = gen.f16_half_locs[int(a_str)][int(h_str)] - used = set(gen.inputs.values()) - if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute + gen.pv_fallback = {} + if BARY_FALLBACK and gen.per_vertex: + # The per-vertex attributes become Flat vec4[3] inputs, each at the lowest three consecutive locations no + # other input uses (their own location is free: every read of such an attribute goes through the array). + taken = {v for k, v in gen.inputs.items() if not (k.startswith("%in_attr") and int(k[8:]) in gen.per_vertex)} + taken |= {loc for pair in gen.f16_half_locs.values() for loc in pair} + for n in sorted(gen.per_vertex): + base = next(b for b in range(len(taken) + 3) if not {b, b + 1, b + 2} & taken) + gen.pv_fallback[n] = base + gen.inputs[f"%in_attr{n}"] = base + taken |= {base, base + 1, base + 2} + used = set(gen.inputs.values()) | {b + k for b in gen.pv_fallback.values() for k in (1, 2)} + if len(set(gen.inputs.values())) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a # raw attribute at the location of a half this shader doesn't read is overwritten all the same. @@ -15689,7 +15711,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") @@ -16039,8 +16063,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: @@ -17016,10 +17040,9 @@ def partner(k, s): if s["src"] in (0, 1): g.frag_inputs[s["src"]] = ("bary_i", "bary_j")[s["src"]] attrs.add(s["attr"]) - if attrs and BARY_FALLBACK: - raise Unsupported("computed I/J pair under --bary-fallback: no PerVertexKHR inputs") - if attrs and F16_HALVES: - # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either + if attrs and F16_HALVES and not BARY_FALLBACK: + # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either. With + # --bary-fallback as well (NVIDIA Pascal), the geometry shader passes the three vertices' raw words instead. raise Unsupported("computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs") return attrs @@ -17772,7 +17795,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"]) @@ -17840,7 +17865,13 @@ def translate(path): g.v_interp_copy = interp_copy_sources(insns) # before v_interp runs: I/J guards (SHADER-177) # SHADER-177: annotate v_interp sites whose I/J operand is a computed pair, and let those # attributes be read per-vertex (attribute() weights them with the operand values). - g.per_vertex |= interp_ij_analysis(insns, g) + computed = interp_ij_analysis(insns, g) + g.per_vertex |= computed + # --bary-fallback with --f16-interp-fallback: a computed attribute's f16 reads decode the per-vertex raw + # words (Gen.attribute) rather than the producer's decoded halves. + g.f16_halves -= computed + if BARY_FALLBACK and mixed_f32 - computed: + raise Unsupported("flat and interpolated reads of one f32 attribute need per-vertex inputs") if any("ij" in i for i in insns): # Computed v_interp sites load their I/J VGPRs at runtime; no_bary above stripped all # v_interp sources, so an untouched (or conditionally/EXEC-masked written) v0/v1 still @@ -18788,11 +18819,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 d380fd279b..dea8a691a0 100644 --- a/tools/vk_subgroup_info.py +++ b/tools/vk_subgroup_info.py @@ -30,7 +30,11 @@ per_vertex_inputs says whether the device can run a pixel shader with PerVertexKHR inputs (16-bit interpolation, docs/design.md): the fragmentShaderBarycentric feature, 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). 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; @@ -95,6 +99,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) @@ -332,6 +338,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)) @@ -343,7 +350,7 @@ 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 + sgc, per_vertex, geometry_shader, max_push_constants_size, vendor, device, driver) = chosen compute_required = bool(required_stages & VK_SHADER_STAGE_COMPUTE_BIT) mesh_required = bool(required_stages & VK_SHADER_STAGE_MESH_BIT_EXT) compute_supported = bool(supported_stages & VK_SHADER_STAGE_COMPUTE_BIT) @@ -365,6 +372,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), "max_push_constants_size": max_push_constants_size, "vendor_id": vendor, From 53df7d1aee7c5fc53ee97a9ff320faa2aa7d13b2 Mon Sep 17 00:00:00 2001 From: robot00f Date: Tue, 24 Nov 2026 23:10:53 -0300 Subject: [PATCH 2/8] runtime/d3d12: synthesize --bary-fallback geometry shader in graphics PSOs When a translated pixel shader carries `"bary_fallback_input": {"location": N}` in `spirv/index.json` (`rdna2spirv.py --bary-fallback` for GPUs without `VK_KHR_fragment_shader_barycentric`), `PipelineState::create_graphics` now synthesizes the triangle pass-through Geometry SPIR-V 1.5 module in memory (`leonida::build_bary_fallback_gs` in `runtime/src/spirv_bary_fallback.h`) after `--f16-interp-fallback` VS/PS location linking: - Parses `bary_fallback_input.location` in `ShaderLibrary::load_index` into `ShaderEntry::bary_fallback_location`. - Copies `BuiltIn Position` and every `vec4` `Location` input read by the PS (other than `bary_location`) that the VS exports, while zero-filling any unexported PS `Location` input without declaring a dangling GS `Input` and leaving unread VS outputs unconsumed (`VUID-RuntimeSpirv-OpEntryPoint-08743`). - Forwards a VS `BuiltIn ClipDistance` or `BuiltIn CullDistance` `float[1..8]` array (checking `shaderClipDistance` / `shaderCullDistance`), and emits `(1, 0, 0)`, `(0, 1, 0)`, `(0, 0, 1)` at `bary_location` across the 3 strip vertices so perspective interpolation matches `BaryCoordKHR`. - Supports both eager and lazy graphics pipeline builds (`StageSource::bary_fallback` in `stage_words`), clamps `--f16-interp-fallback` `top_location` against `maxGeometryInputComponents` / `maxGeometryOutputComponents`, and refuses mesh PSOs, explicit GS or rectangle-list stages, missing `geometryShader`, or non-triangle topologies with clear HRESULTs (`E_NOTIMPL` / `E_INVALIDARG`). - Adds `spirv_bary_fallback` (portable CPU test) and `d3d12_bary_fallback` (end-to-end Vulkan GPU D3D12 PSO test). Claim: RT-BARY-FALLBACK-PSO AI-assisted: yes (Antigravity) --- runtime/CMakeLists.txt | 10 + runtime/shims/d3d12_vulkan_device.cpp | 100 +++- runtime/src/shader_library.h | 10 + runtime/src/spirv_bary_fallback.h | 428 ++++++++++++++ runtime/test/d3d12_bary_fallback_test.cpp | 678 ++++++++++++++++++++++ runtime/test/shader_library_test.cpp | 34 ++ runtime/test/spirv_bary_fallback_test.cpp | 495 ++++++++++++++++ runtime/test/vk_test_device.h | 2 + 8 files changed, 1747 insertions(+), 10 deletions(-) create mode 100644 runtime/src/spirv_bary_fallback.h create mode 100644 runtime/test/d3d12_bary_fallback_test.cpp create mode 100644 runtime/test/spirv_bary_fallback_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..205b374262 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1457,6 +1457,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) @@ -3303,6 +3305,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_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1fb36401e3..a05dc3e29a 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -63,6 +63,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_vsharp_slots.h" @@ -2336,6 +2337,7 @@ 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; 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; @@ -10981,6 +10983,32 @@ 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); } @@ -10988,12 +11016,13 @@ class PipelineState final (!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)) { 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_ = lazy_graphics_pipelines(); @@ -11048,8 +11077,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(); } @@ -11082,6 +11111,40 @@ 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, words, &bary_info, + &bary_error)) { + 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)); + } + 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; @@ -12102,9 +12165,10 @@ 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) 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); } public: @@ -12137,7 +12201,8 @@ class PipelineState final } 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_)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { @@ -12150,6 +12215,12 @@ 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, words[i], nullptr, + &why)) + return false; } else if (sources_[i].kind == StageSource::depth_only) { words[i] = leonida::depth24_depth_only_fragment(depth24_bias_); } else { @@ -12181,7 +12252,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 @@ -12194,8 +12265,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 @@ -13507,6 +13579,14 @@ class Device final ? 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 && + props.limits.maxGeometryInputComponents && props.limits.maxGeometryOutputComponents) { + state_.bary_f16_half_top_location = std::min( + state_.f16_half_top_location, + leonida::f16_half_top_location(props.limits.maxGeometryInputComponents, + props.limits.maxGeometryOutputComponents)); + } } 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 7699dfbb0d..b6a88e93cf 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -873,6 +874,8 @@ 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; // 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; @@ -1301,6 +1304,13 @@ 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); + } + } 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..01194b8b67 --- /dev/null +++ b/runtime/src/spirv_bary_fallback.h @@ -0,0 +1,428 @@ +#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 reads (other than `bary_location`) that the VS exports, and +// zero-fills any declared PS `Location` input the VS omits without declaring a dangling GS `Input` (preserving +// `VUID-RuntimeSpirv-OpEntryPoint-08743` on both `VS -> GS` and `GS -> PS` interfaces); +// - 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`). +// +// Pure C++20 stdlib, no Vulkan or Windows headers required. + +#include "spirv_f16_halves.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +struct BaryFallbackGsInfo { + std::uint32_t clip_count = 0; + std::uint32_t cull_count = 0; +}; + +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) { + 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 kOpEmitVertex = 218; + constexpr std::uint16_t kOpEndPrimitive = 219; + 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 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; + + 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 == 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; + 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)); + } + + 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"); + } + + 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) 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); + 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(); + + 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(); + for (std::uint32_t loc : pass_locs) id_out_loc[loc] = 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 (std::uint32_t loc : forwarded_locs) ep.push_back(id_in_loc[loc]); + for (std::uint32_t loc : pass_locs) ep.push_back(id_out_loc[loc]); + 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 (std::uint32_t loc : forwarded_locs) + gs.insts.push_back(make_inst(kOpDecorate, {id_in_loc[loc], kDecorationLocation, loc})); + for (std::uint32_t loc : pass_locs) + gs.insts.push_back(make_inst(kOpDecorate, {id_out_loc[loc], kDecorationLocation, loc})); + 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 (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 (std::uint32_t loc : forwarded_locs) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_arr, id_in_loc[loc], kStorageInput})); + for (std::uint32_t loc : pass_locs) + gs.insts.push_back(make_inst(kOpVariable, {id_ptr_out_v4, id_out_loc[loc], 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})); + 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})); + } + } + 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) *out_info = {clip_count, cull_count}; + return true; +} + +} // namespace leonida diff --git a/runtime/test/d3d12_bary_fallback_test.cpp b/runtime/test/d3d12_bary_fallback_test.cpp new file mode 100644 index 0000000000..6f94d4dc05 --- /dev/null +++ b/runtime/test/d3d12_bary_fallback_test.cpp @@ -0,0 +1,678 @@ +// 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. Combined `--f16-interp-fallback` + `--bary-fallback`: a 16-param VS (with packed f16 pairs in `param7` and +// colliding static halves) paired with a PS reading raw `0..13`, `bary_fallback_input` at `Location 14`, and +// `f16_halves` for `param7` at `[15, 16]` (relocated to `[28, 29]` before GS synthesis). +// 4. Refusals: non-triangle topology (`E_INVALIDARG`), explicit GS (`E_NOTIMPL`), and disabled `geometryShader` +// feature (`E_NOTIMPL`). +// 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 + +#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 0 = 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 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, 0}); + 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 0 (vec4 attr0) and Location 1 (vec3 bary), writing vec4(bary.x, bary.y, bary.z, attr0.z). +std::vector make_bary_ps(std::uint32_t bary_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_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, 0}); + 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; +} + +// 16-param VS (param0..param15, static f16_halves for 0..6, param7.x = packHalf2x16(0.25, 0.75) = 0x3a003400). +std::vector make_16param_vs() { + constexpr std::uint32_t kBound = 61; + std::vector w = {kSpirvMagic, 0x00010500u, 0, kBound, 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 <= 60; ++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 < 16; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p}); + for (std::uint32_t n = 0; n <= 6; ++n) { + put_inst(w, kOpDecorate, {47 + 2 * n, kDecorationLocation, 28 - 2 * n}); + put_inst(w, kOpDecorate, {48 + 2 * n, 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 <= 60; ++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 < 16; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u}); + for (std::uint32_t id = 47; id <= 60; ++id) put_inst(w, kOpStore, {id, 10}); + 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; +} + +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; + } + + 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 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 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 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 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_16param_vs()); + 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)); + { + 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" + " \"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]}}}"; + } + + 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"); + } + + // 3. Combined --f16-interp-fallback + --bary-fallback (relocated f16 halves + synthesized GS). + { + auto pd = make_pso_desc(vs_16p_c, ps_f16_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 (combined f16_halves relocation + bary GS): all 256 pixels OK\n"); + } + + // 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); + } + } + + 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 ee49c48ebb..f6a9f60943 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -1289,6 +1289,40 @@ 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); + } + 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/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp new file mode 100644 index 0000000000..5e06c555bb --- /dev/null +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -0,0 +1,495 @@ +// 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. +// 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 + +#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 = {}) { + 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_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]}); + } + + std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + append_inst(w, kOpCapability, {1}); + 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); + 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 + } + + 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}); + 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}); + + 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}); + + append_inst(w, kOpFunction, {id_void, id_main, 0, id_fn}); + append_inst(w, 248, {id_entry}); + append_inst(w, kOpStore, {id_out0, id_null_v4}); + append_inst(w, kOpReturn, {}); + append_inst(w, kOpFunctionEnd, {}); + return w; +} + +struct GsInspection { + std::set caps; + std::set in_locs; + std::map out_loc_vec_len; // loc -> 3 or 4 + 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) + 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; + 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]; + } else if (inst.opcode == 43 || inst.opcode == 44 || inst.opcode == kOpConstantNull) { + if (!record_def(inst.words[2])) return false; + } 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; + } 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) { + 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; + } + } + } + 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); + } + + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index eb1be0a2c9..d02fe268d7 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -497,6 +497,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. From 682de28946f27bcc6ddb404ce583df7797c9812e Mon Sep 17 00:00:00 2001 From: mrgenty <51083221+mrgenty@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:00:41 +0100 Subject: [PATCH 3/8] runtime/d3d12: the --bary-fallback geometry stage feeds computed I/J pairs (RT-BARY-FALLBACK-PER-VERTEX) A pixel shader with a computed I/J pair, translated with --bary-fallback, reads the pair's attribute as a Flat vec4[3] at the first of three locations its index entry gives under bary_fallback_input.per_vertex. The runtime's geometry-stage builder read only bary_fallback_input.location and refused that input ("PS pass-through Input at Location 0 is not vec4"), so such a PSO was never created. - shader_library.h: parse per_vertex (attribute -> first location) into ShaderEntry::bary_fallback_per_vertex; one malformed entry drops the whole map. - spirv_bary_fallback.h: build_bary_fallback_gs takes the map and writes the triangle's three values of each mapped VS output to the PS's Flat vec4[3] (element k = vertex k, the same at every emitted vertex), as tools/bary_fallback_gs.py does. An attribute the VS does not export is zero-filled. A vec4[3] the map does not name, a block that runs into another input or the barycentric location, and two attributes at one first location are refused. The old signature stays as a wrapper with an empty map. - d3d12_vulkan_device.cpp: both call sites (eager and lazy) pass the entry's map. - Tests: spirv_bary_fallback (five per-vertex cases), shader_library (twelve per_vertex parsing cases), d3d12_bary_fallback (two draws of a synthetic computed-I/J PS and one refusal). - docs/design.md: the runtime builder in the "Barycentric fallback" row, with what was and was not checked. Co-Authored-By: Claude Mythos 5.2 --- docs/design.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 6 +- runtime/src/shader_library.h | 24 ++ runtime/src/spirv_bary_fallback.h | 132 ++++++++- runtime/test/d3d12_bary_fallback_test.cpp | 324 +++++++++++++++++++++- runtime/test/shader_library_test.cpp | 52 ++++ runtime/test/spirv_bary_fallback_test.cpp | 151 +++++++++- 7 files changed, 679 insertions(+), 12 deletions(-) diff --git a/docs/design.md b/docs/design.md index c67063e18f..e45b205fb6 100644 --- a/docs/design.md +++ b/docs/design.md @@ -435,7 +435,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. `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`. 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). | +| 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; 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). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0d25b5a93e..e6db3ab3fb 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -11122,7 +11122,8 @@ class PipelineState final 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, words, &bary_info, + *ps_stage.entry->bary_fallback_location, + ps_stage.entry->bary_fallback_per_vertex, words, &bary_info, &bary_error)) { std::fprintf(stderr, "[rt] d3d12: %s\n", bary_error.c_str()); return E_FAIL; @@ -12224,7 +12225,8 @@ class PipelineState final } 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, words[i], nullptr, + *sources_[ps].entry->bary_fallback_location, + sources_[ps].entry->bary_fallback_per_vertex, words[i], nullptr, &why)) return false; } else if (sources_[i].kind == StageSource::depth_only) { diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index b6a88e93cf..efab48e561 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -876,6 +876,10 @@ struct ShaderEntry { 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; @@ -1310,6 +1314,26 @@ class ShaderLibrary { 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) { diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index 01194b8b67..6cefed76f4 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -15,12 +15,18 @@ // - 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`). +// `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 @@ -36,9 +42,12 @@ struct BaryFallbackGsInfo { std::uint32_t cull_count = 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]`. 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) { @@ -72,6 +81,7 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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; @@ -194,6 +204,9 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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; @@ -207,6 +220,12 @@ inline bool build_bary_fallback_gs(std::span vs_words, } 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) { @@ -232,11 +251,57 @@ inline bool build_bary_fallback_gs(std::span vs_words, " 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()) { + 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) continue; + 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); @@ -270,6 +335,10 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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; @@ -299,7 +368,13 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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; @@ -314,8 +389,9 @@ inline bool build_bary_fallback_gs(std::span vs_words, // 3. EntryPoint ("main\0") std::vector ep = {kExecModelGeometry, id_main, 0x6e69616du, 0x00000000u, id_in_pos, id_out_pos}; - for (std::uint32_t loc : forwarded_locs) ep.push_back(id_in_loc[loc]); + 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); @@ -336,10 +412,14 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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 (std::uint32_t loc : forwarded_locs) - gs.insts.push_back(make_inst(kOpDecorate, {id_in_loc[loc], kDecorationLocation, loc})); + 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 @@ -357,6 +437,8 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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})); @@ -374,10 +456,12 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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 (std::uint32_t loc : forwarded_locs) - gs.insts.push_back(make_inst(kOpVariable, {id_ptr_in_arr, id_in_loc[loc], kStorageInput})); + 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})); @@ -387,6 +471,18 @@ inline bool build_bary_fallback_gs(std::span vs_words, // 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(); @@ -405,6 +501,17 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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(); @@ -425,4 +532,15 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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/test/d3d12_bary_fallback_test.cpp b/runtime/test/d3d12_bary_fallback_test.cpp index 6f94d4dc05..0b4990ac94 100644 --- a/runtime/test/d3d12_bary_fallback_test.cpp +++ b/runtime/test/d3d12_bary_fallback_test.cpp @@ -13,6 +13,11 @@ // `f16_halves` for `param7` at `[15, 16]` (relocated to `[28, 29]` before GS synthesis). // 4. Refusals: non-triangle topology (`E_INVALIDARG`), explicit GS (`E_NOTIMPL`), and disabled `geometryShader` // feature (`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" @@ -21,6 +26,7 @@ #include "../src/shader_library.h" #include "../src/spirv_bary_fallback.h" +#include #include #include #include @@ -354,6 +360,206 @@ std::vector make_bary_f16_ps(std::uint32_t num_raw, std::uint32_t 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; @@ -381,6 +587,10 @@ int main() { 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 vs_ij_prog = fssm_program({0x5653ba04, 0xbf810000}); + const auto ps_ij_prog = fssm_program({0x5053ba03, 0xbf810000}); + const auto ps_ij_reloc_prog = fssm_program({0x5053ba04, 0xbf810000}); + const auto ps_ij_nomap_prog = fssm_program({0x5053ba05, 0xbf810000}); const auto vs_persp_c = shader_container(vs_persp_prog); const auto vs_clip_c = shader_container(vs_clip_prog); @@ -388,6 +598,10 @@ int main() { 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 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); @@ -402,6 +616,10 @@ int main() { 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 / "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) @@ -419,7 +637,24 @@ int main() { "\"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]}}}"; + "\"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}}}"; } constexpr UINT kSize = 16; @@ -639,6 +874,93 @@ int main() { std::printf("ps_bary_f16 (combined f16_halves relocation + 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); diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index f6a9f60943..721d6b07a9 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -1323,6 +1323,58 @@ int main() { 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/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp index 5e06c555bb..5f9ca9a522 100644 --- a/runtime/test/spirv_bary_fallback_test.cpp +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -5,6 +5,8 @@ // 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. // 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" @@ -141,7 +143,8 @@ std::vector build_vs(const VsSpec& spec) { 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::map>& f16_halves = {}, + const std::vector& pv_bases = {}) { std::uint32_t next_id = 1; const auto alloc = [&]() { return next_id++; }; @@ -165,6 +168,16 @@ std::vector build_ps(const std::vector& raw_locs, 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 = 0, 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 = alloc(); + 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, next_id, 0}; append_inst(w, kOpCapability, {1}); @@ -173,6 +186,7 @@ std::vector build_ps(const std::vector& raw_locs, 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 @@ -182,6 +196,10 @@ std::vector build_ps(const std::vector& raw_locs, 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}); @@ -192,10 +210,17 @@ std::vector build_ps(const std::vector& raw_locs, 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, kOpTypeInt, {id_uint, 32, 0}); + 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}); @@ -209,6 +234,9 @@ 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; @@ -232,6 +260,11 @@ bool verify_gs_module(const std::vector& words, GsInspection& out 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) { @@ -265,6 +298,7 @@ bool verify_gs_module(const std::vector& words, GsInspection& out 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: @@ -286,8 +320,14 @@ bool verify_gs_module(const std::vector& words, GsInspection& out 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]); @@ -300,6 +340,16 @@ bool verify_gs_module(const std::vector& words, GsInspection& out 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) { @@ -333,6 +383,9 @@ bool verify_gs_module(const std::vector& words, GsInspection& out 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; @@ -340,6 +393,12 @@ bool verify_gs_module(const std::vector& words, GsInspection& out } } } + 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; } @@ -491,5 +550,95 @@ int main(int argc, char** argv) { 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); + } + + // 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}})); + } + return 0; } From 0b7532951f91ee86512cbc7fc5a939ab7eac9b63 Mon Sep 17 00:00:00 2001 From: mrgenty <51083221+mrgenty@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:01:39 +0100 Subject: [PATCH 4/8] runtime/d3d12: computed I/J reads only the VS's raw outputs after f16 linking (RT-BARY-FALLBACK-PER-VERTEX) With both --bary-fallback and --f16-interp-fallback, create_graphics (and the lazy stage_words) links the f16 halves into the VS before the geometry stage is built. Linking may place a decoded half on a Location no raw VS output used; when that Location is a computed-I/J attribute the VS does not export, build_bary_fallback_gs read the half as that attribute and forwarded it instead of zero-filling the array. - link_f16_halves can return the Locations of the VS's raw outputs as they were before linking, and build_bary_fallback_gs forwards a computed-I/J attribute only from one of them. Both call sites pass the set when the halves were linked. - link_f16_halves also keeps halves off the second and third Locations of a per_vertex vec4[3] block, which has a Location decoration on its first only. spirv_bary_fallback_test 7f-7h: a relocated half and a static half on a missing attribute's Location (zero-filled; without the set the half is forwarded), and a block whose third Location linking would otherwise choose (the builder refused it). Reported, with a GPU reproduction, by @marcelofrayha in mrgenty/leonida#2; the fix follows his commit 7f63a4876, and the block reservation his bdff821c1, adapted to this branch without the geometry-input packing. Co-authored-by: Marcelo Frayha Co-Authored-By: Claude Opus 5.5 --- docs/design.md | 2 +- runtime/shims/d3d12_vulkan_device.cpp | 15 +++-- runtime/src/spirv_bary_fallback.h | 9 ++- runtime/src/spirv_f16_halves.h | 19 +++++- runtime/test/spirv_bary_fallback_test.cpp | 73 ++++++++++++++++++++++- 5 files changed, 105 insertions(+), 13 deletions(-) diff --git a/docs/design.md b/docs/design.md index e45b205fb6..b60567ed51 100644 --- a/docs/design.md +++ b/docs/design.md @@ -435,7 +435,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. `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; 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). | +| 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). | | Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e6db3ab3fb..ac8a28c281 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -11018,11 +11018,12 @@ class PipelineState final 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, bary_fallback)) { + &link_error, bary_fallback, &raw_vs_locations)) { std::fprintf(stderr, "[rt] d3d12: %s\n", link_error.c_str()); return E_FAIL; } @@ -11124,7 +11125,7 @@ class PipelineState final 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)) { + &bary_error, f16_linked_ ? &raw_vs_locations : nullptr)) { std::fprintf(stderr, "[rt] d3d12: %s\n", bary_error.c_str()); return E_FAIL; } @@ -12172,10 +12173,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, bool bary_fallback = false) const { + 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); + return leonida::link_f16_halves(vs_words, vs_entry, ps_words, ps_entry, error, top_loc, raw_vs_locations); } public: @@ -12206,10 +12208,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, - bary_fallback_)) + bary_fallback_, &raw_vs_locations)) return false; } for (std::size_t i = 0; i < sources_.size(); ++i) { @@ -12227,7 +12230,7 @@ class PipelineState final !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)) + &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_); diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index 6cefed76f4..d516b4e448 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -44,13 +44,17 @@ struct BaryFallbackGsInfo { // `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) { + std::string* error = nullptr, + const std::set* raw_vs_locations = nullptr) { const auto fail = [&](const std::string& msg) { if (error) *error = msg; return false; @@ -284,7 +288,8 @@ inline bool build_bary_fallback_gs(std::span vs_words, } } PerVertex pv{attr, base, false}; - if (const auto vs_it = vs_out_loc_pointee.find(attr); vs_it != vs_out_loc_pointee.end()) { + 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; 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/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp index 5f9ca9a522..d5b5777029 100644 --- a/runtime/test/spirv_bary_fallback_test.cpp +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -6,7 +6,8 @@ // 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. +// 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. // 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" @@ -605,6 +606,76 @@ int main(int argc, char** argv) { 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); + } + // 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}}); From 961d719d544065e08053e758d256de53bd2eea34 Mon Sep 17 00:00:00 2001 From: robot00f Date: Thu, 26 Nov 2026 21:42:28 -0300 Subject: [PATCH 5/8] runtime/d3d12: prune unread bary-fallback PS inputs and enforce GS component limits - Prune declared-but-unread PS Input variables on the VS -> GS interface in build_bary_fallback_gs (tracking pointer aliases through OpAccessChain, OpCopyObject, OpSelect, and OpPhi into OpLoad, GLSL.std.450 InterpolateAt*, OpFunctionCall, and OpCopyMemory*), zero-filling unread FSSM table inputs in the synthesized GS instead of reading them from the VS. - Record per-vertex input/output scalar component totals and highest 4 * Location + components bounds (VUID-RuntimeSpirv-Location-06272) in BaryFallbackGsInfo, and check them against maxGeometryInputComponents, maxGeometryOutputComponents, and maxGeometryTotalOutputComponents in create_graphics with explicit [rt] d3d12: refusal diagnostics. - Extend spirv_bary_fallback_test and d3d12_bary_fallback_test to cover unused-input pruning, 10-param f16 relocation within 64 geometry input components, simulated maxGeometryInputComponents=64 acceptance/refusal on any GPU, and clean refusal + draw skip on <120-component devices (such as RADV gfx1036) for the 16-param relocated f16 case. Co-authored-by: ZroFreaks <42916282+ZroIsHere@users.noreply.github.com> --- runtime/shims/d3d12_com.h | 3 + runtime/shims/d3d12_vulkan_device.cpp | 70 +++++- runtime/src/spirv_bary_fallback.h | 114 ++++++++- runtime/test/d3d12_bary_fallback_test.cpp | 278 +++++++++++++++++++--- runtime/test/spirv_bary_fallback_test.cpp | 68 +++++- 5 files changed, 496 insertions(+), 37 deletions(-) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 3bad0b7671..4d20c571bb 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 644e322790..5fc5857697 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -2818,6 +2818,9 @@ struct DeviceState { 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; @@ -11833,6 +11836,16 @@ class PipelineState final std::string link_error; if (!link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, &link_error, bary_fallback)) { + 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; } @@ -11947,6 +11960,50 @@ class PipelineState final "--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() : ""; + const std::uint32_t max_gs_in = device_.max_geometry_input_components; + if (max_gs_in && (bary_info.max_input_location_components > max_gs_in || + bary_info.input_components > max_gs_in)) { + if (bary_info.max_input_location_components > max_gs_in) { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s reads Location %u " + "(component end %u > maxGeometryInputComponents %u); refusing pipeline\n", + vs_name, ps_name, bary_info.max_input_location, + bary_info.max_input_location_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 && (bary_info.max_output_location_components > max_gs_out || + bary_info.output_components > max_gs_out)) { + if (bary_info.max_output_location_components > max_gs_out) { + std::fprintf(stderr, + "[rt] d3d12: --bary-fallback geometry stage for %s + %s writes Location %u " + "(component end %u > maxGeometryOutputComponents %u); refusing pipeline\n", + vs_name, ps_name, bary_info.max_output_location, + bary_info.max_output_location_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_) { @@ -14451,17 +14508,24 @@ 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 && - props.limits.maxGeometryInputComponents && props.limits.maxGeometryOutputComponents) { + 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(props.limits.maxGeometryInputComponents, - props.limits.maxGeometryOutputComponents)); + leonida::f16_half_top_location(state_.max_geometry_input_components, + state_.max_geometry_output_components)); } } if (const auto get_props2 = reinterpret_cast( diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index 01194b8b67..519d04c146 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -9,9 +9,9 @@ // 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 reads (other than `bary_location`) that the VS exports, and -// zero-fills any declared PS `Location` input the VS omits without declaring a dangling GS `Input` (preserving -// `VUID-RuntimeSpirv-OpEntryPoint-08743` on both `VS -> GS` and `GS -> PS` interfaces); +// - 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 @@ -34,6 +34,18 @@ 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 * forwarded_locs). + std::uint32_t input_components = 0; + // Highest `4 * Location + 4` across GS Input locations (0 when no user locations are forwarded); + // Vulkan VUID-RuntimeSpirv-Location-06272 requires this <= limits.maxGeometryInputComponents. + 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). + std::uint32_t output_components = 0; + // Highest `4 * Location + components` across GS Output locations (`pass_locs` vec4 and `bary_location` vec3); + // Vulkan VUID-RuntimeSpirv-Location-06272 requires this <= limits.maxGeometryOutputComponents. + std::uint32_t max_output_location = 0; + std::uint32_t max_output_location_components = 0; }; inline bool build_bary_fallback_gs(std::span vs_words, @@ -55,8 +67,16 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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; @@ -217,6 +237,7 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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; @@ -224,6 +245,66 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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); @@ -240,6 +321,10 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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)) @@ -421,7 +506,28 @@ inline bool build_bary_fallback_gs(std::span vs_words, gs.header = {kSpirvMagic, kSpirvVersion15, 0u, next_id, 0u}; gs_words = gs.serialize(); - if (out_info) *out_info = {clip_count, cull_count}; + if (out_info) { + BaryFallbackGsInfo info{}; + info.clip_count = clip_count; + info.cull_count = cull_count; + info.input_components = 4u + dist_count + 4u * std::uint32_t(forwarded_locs.size()); + if (!forwarded_locs.empty()) { + info.max_input_location = forwarded_locs.back(); + info.max_input_location_components = 4u * info.max_input_location + 4u; + } + info.output_components = 4u + dist_count + 4u * std::uint32_t(pass_locs.size()) + 3u; + info.max_output_location = bary_location; + info.max_output_location_components = 4u * bary_location + 3u; + if (!pass_locs.empty()) { + const std::uint32_t hi_pass = pass_locs.back(); + const std::uint32_t hi_comp = 4u * hi_pass + 4u; + if (hi_comp > info.max_output_location_components) { + info.max_output_location = hi_pass; + info.max_output_location_components = hi_comp; + } + } + *out_info = info; + } return true; } diff --git a/runtime/test/d3d12_bary_fallback_test.cpp b/runtime/test/d3d12_bary_fallback_test.cpp index 6f94d4dc05..3a1e43b238 100644 --- a/runtime/test/d3d12_bary_fallback_test.cpp +++ b/runtime/test/d3d12_bary_fallback_test.cpp @@ -8,11 +8,18 @@ // 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. Combined `--f16-interp-fallback` + `--bary-fallback`: a 16-param VS (with packed f16 pairs in `param7` and -// colliding static halves) paired with a PS reading raw `0..13`, `bary_fallback_input` at `Location 14`, and -// `f16_halves` for `param7` at `[15, 16]` (relocated to `[28, 29]` before GS synthesis). -// 4. Refusals: non-triangle topology (`E_INVALIDARG`), explicit GS (`E_NOTIMPL`), and disabled `geometryShader` -// feature (`E_NOTIMPL`). +// 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`). // 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" @@ -57,8 +64,8 @@ void write_spv(const std::filesystem::path& path, const std::vector make_bary_vs(bool non_uniform_w, bool with_clip_x) { +// 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++; }; @@ -126,7 +133,7 @@ std::vector make_bary_vs(bool non_uniform_w, bool with_clip_x) { 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_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}); @@ -197,8 +204,8 @@ std::vector make_bary_vs(bool non_uniform_w, bool with_clip_x) { return w; } -// PS reading Location 0 (vec4 attr0) and Location 1 (vec3 bary), writing vec4(bary.x, bary.y, bary.z, attr0.z). -std::vector make_bary_ps(std::uint32_t bary_loc) { +// 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 @@ -210,7 +217,7 @@ std::vector make_bary_ps(std::uint32_t bary_loc) { put_inst(w, kOpExecutionMode, {12, 7}); // OriginUpperLeft put_inst(w, kOpDecorate, {9, kDecorationLocation, 0}); - put_inst(w, kOpDecorate, {10, kDecorationLocation, 0}); + put_inst(w, kOpDecorate, {10, kDecorationLocation, attr_loc}); put_inst(w, kOpDecorate, {11, kDecorationLocation, bary_loc}); put_inst(w, 19, {1}); @@ -241,22 +248,28 @@ std::vector make_bary_ps(std::uint32_t bary_loc) { return w; } -// 16-param VS (param0..param15, static f16_halves for 0..6, param7.x = packHalf2x16(0.25, 0.75) = 0x3a003400). -std::vector make_16param_vs() { - constexpr std::uint32_t kBound = 61; - std::vector w = {kSpirvMagic, 0x00010500u, 0, kBound, 0}; +// 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 <= 60; ++id) ep.push_back(id); + 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 < 16; ++p) put_inst(w, kOpDecorate, {31 + p, kDecorationLocation, p}); - for (std::uint32_t n = 0; n <= 6; ++n) { - put_inst(w, kOpDecorate, {47 + 2 * n, kDecorationLocation, 28 - 2 * n}); - put_inst(w, kOpDecorate, {48 + 2 * n, kDecorationLocation, 29 - 2 * n}); + 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}); @@ -284,7 +297,7 @@ std::vector make_16param_vs() { put_inst(w, kOpVariable, {6, 8, kStorageInput}); put_inst(w, kOpVariable, {7, 9, kStorageOutput}); - for (std::uint32_t id = 31; id <= 60; ++id) put_inst(w, kOpVariable, {7, id, 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}); @@ -294,8 +307,86 @@ std::vector make_16param_vs() { 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 < 16; ++p) put_inst(w, kOpStore, {31 + p, p == 7 ? 23u : 10u}); - for (std::uint32_t id = 47; id <= 60; ++id) put_inst(w, kOpStore, {id, 10}); + 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; @@ -375,19 +466,35 @@ int main() { 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_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_persp_spv = make_bary_vs(true, false); const auto ps_bary_spv = make_bary_ps(1); @@ -398,10 +505,15 @@ int main() { 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_16param_vs()); + 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)); { 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) @@ -412,6 +524,10 @@ int main() { << "\", \"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) @@ -419,7 +535,16 @@ int main() { "\"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]}}}"; + "\"bary_fallback_input\": {\"location\": 14}, \"f16_halves\": {\"7\": [15, 16]}},\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; @@ -616,9 +741,35 @@ int main() { std::printf("ps_bary + ClipDistance[1]: left half clipped, right half interpolated OK\n"); } - // 3. Combined --f16-interp-fallback + --bary-fallback (relocated f16 halves + synthesized GS). + // 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_f16_c); + 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; @@ -636,7 +787,40 @@ int main() { EXPECT(std::abs(int(px[3]) - want_j) <= 2); } } - std::printf("ps_bary_f16 (combined f16_halves relocation + bary GS): all 256 pixels OK\n"); + 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"); + } } // 4a & 4b. Refusals: non-triangle topology -> E_INVALIDARG; explicit GS -> E_NOTIMPL. @@ -669,6 +853,44 @@ int main() { 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; diff --git a/runtime/test/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp index 5e06c555bb..cab68c8942 100644 --- a/runtime/test/spirv_bary_fallback_test.cpp +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -5,6 +5,9 @@ // 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. 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" @@ -141,15 +144,22 @@ std::vector build_vs(const VsSpec& spec) { 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::map>& f16_halves = {}, + 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(); + const std::uint32_t id_uint = access_chain_locs.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(); @@ -166,8 +176,10 @@ std::vector build_ps(const std::vector& raw_locs, in_v4_vars.push_back({alloc(), pair[1]}); } - std::vector w = {kSpirvMagic, 0x00010500u, 0, next_id, 0}; + 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}; @@ -188,6 +200,11 @@ std::vector build_ps(const std::vector& raw_locs, 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}); + 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}); @@ -199,9 +216,23 @@ std::vector build_ps(const std::vector& raw_locs, 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; } @@ -491,5 +522,38 @@ int main(int argc, char** argv) { CHECK(!build_bary_fallback_gs(vs_ok, ps_collide, 1, gs, nullptr, &err) && !err.empty() && gs == sentinel); } + // 7. 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; } From c6aa38942eeffbcea0690cc105d53072076dee78 Mon Sep 17 00:00:00 2001 From: mrgenty <51083221+mrgenty@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:43:07 +0100 Subject: [PATCH 6/8] runtime/d3d12: count computed-I/J blocks in the geometry-limit check (RT-BARY-FALLBACK-PER-VERTEX) #1497's precheck compares BaryFallbackGsInfo with maxGeometryInput/OutputComponents, but the info left out the per_vertex blocks: an attribute read only by a block had a GS Input that was not counted, and each vec4[3] output (Locations base..base+2, 12 components, zero-filled or not) was missing from the output bounds. Attribute 16 with its block at 14..16 reported 0/15 while the module needs 68/68, so a 64-component device would get it. Inputs are now counted from the GS's final Input map (a location shared by an ordinary output and a block once), and each block adds 12 output components and its last Location to the output bound. spirv_bary_fallback_test 7i checks 68/68, the 64/64 edge and a zero-filled block; it fails with the old count. Also fixes two leftovers of the #1497 merge in the tests: build_ps declared its uint type twice when a PS had both a block and an access chain, and an extra brace closed the D3D12 test's index.json early. Found by @ecox982745 and confirmed on a Vega 20 by @zmasi in #1930. --- runtime/src/spirv_bary_fallback.h | 35 +++++++++------ runtime/test/d3d12_bary_fallback_test.cpp | 2 +- runtime/test/spirv_bary_fallback_test.cpp | 54 ++++++++++++++++++++--- 3 files changed, 69 insertions(+), 22 deletions(-) diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index 6bf9da14bb..fa43a6ee4f 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -40,15 +40,18 @@ 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 * forwarded_locs). + // 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); // Vulkan VUID-RuntimeSpirv-Location-06272 requires this <= limits.maxGeometryInputComponents. 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). + // 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 and `bary_location` vec3); + // Highest `4 * Location + components` across GS Output locations (`pass_locs` vec4, `bary_location` vec3 and + // the last Location of each computed-I/J block); // Vulkan VUID-RuntimeSpirv-Location-06272 requires this <= limits.maxGeometryOutputComponents. std::uint32_t max_output_location = 0; std::uint32_t max_output_location_components = 0; @@ -622,22 +625,26 @@ inline bool build_bary_fallback_gs(std::span vs_words, BaryFallbackGsInfo info{}; info.clip_count = clip_count; info.cull_count = cull_count; - info.input_components = 4u + dist_count + 4u * std::uint32_t(forwarded_locs.size()); - if (!forwarded_locs.empty()) { - info.max_input_location = forwarded_locs.back(); + // 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; } - info.output_components = 4u + dist_count + 4u * std::uint32_t(pass_locs.size()) + 3u; + // 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; - if (!pass_locs.empty()) { - const std::uint32_t hi_pass = pass_locs.back(); - const std::uint32_t hi_comp = 4u * hi_pass + 4u; - if (hi_comp > info.max_output_location_components) { - info.max_output_location = hi_pass; - info.max_output_location_components = hi_comp; + 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; diff --git a/runtime/test/d3d12_bary_fallback_test.cpp b/runtime/test/d3d12_bary_fallback_test.cpp index 3b1f8bf67f..261d4d0968 100644 --- a/runtime/test/d3d12_bary_fallback_test.cpp +++ b/runtime/test/d3d12_bary_fallback_test.cpp @@ -770,7 +770,7 @@ int main() { " \"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" + "\"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" diff --git a/runtime/test/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp index b6ec5b1f48..4e2c49e67e 100644 --- a/runtime/test/spirv_bary_fallback_test.cpp +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -7,7 +7,8 @@ // 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. +// 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. @@ -23,6 +24,7 @@ #include #include #include +#include #include #define CHECK(cond) do { \ @@ -161,7 +163,8 @@ std::vector build_ps(const std::vector& raw_locs, 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 = access_chain_locs.empty() ? 0 : 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(); @@ -180,10 +183,9 @@ std::vector build_ps(const std::vector& raw_locs, 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 = 0, id_uint_3 = 0, id_arr_v4_3 = 0, id_ptr_in_arr = 0; + 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 = alloc(); id_uint_3 = alloc(); id_arr_v4_3 = alloc(); id_ptr_in_arr = alloc(); @@ -219,8 +221,8 @@ std::vector build_ps(const std::vector& raw_locs, 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 (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}); } @@ -229,7 +231,6 @@ std::vector build_ps(const std::vector& raw_locs, 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, kOpTypeInt, {id_uint, 32, 0}); 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}); @@ -707,6 +708,45 @@ int main(int argc, char** argv) { 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; attribute 15 + // with its block at 13..15 is the 64/64 edge. (Found by @ecox982745, confirmed 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) { + const auto vs = build_vs({.raw_locs = exported ? std::vector{attr} + : std::vector{}}); + 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); + } + { + const auto [ok, info, ins] = footprint(15, 13, true); + CHECK(ok && info.max_input_location_components == 64 && info.max_output_location_components == 64); + } + { + // 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}}); From 9a51aff6dcc9041b02cd775837a320d10e19b582 Mon Sep 17 00:00:00 2001 From: OpenAI Codex Date: Sat, 28 Nov 2026 15:01:46 +1000 Subject: [PATCH 7/8] rdna2spirv: find contiguous per-vertex locations across sparse inputs Search for the lowest available block of three until one is found. The number of occupied locations does not bound the start of the first free block. Exercise two computed attributes after sparse reads at locations 0, 1, 2, 4, 6 and 8. Reported in ProjectLeonida/mandy#1608 (issuecomment-7234323048). AI-assisted-by: OpenAI Codex (GPT-6) (cherry picked from commit d1361e9c4fb47ca611b1aa5935e8545784f54d14) --- .../fixtures/sparse_bary_locations.asm | 20 +++++++++++++++++++ tests/semantic/test_interp_computed_ij.py | 10 ++++++++++ tools/rdna2spirv.py | 4 +++- 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/semantic/fixtures/sparse_bary_locations.asm 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/test_interp_computed_ij.py b/tests/semantic/test_interp_computed_ij.py index 778eed55e2..0319f8d288 100644 --- a/tests/semantic/test_interp_computed_ij.py +++ b/tests/semantic/test_interp_computed_ij.py @@ -394,6 +394,16 @@ def test_the_array_avoids_other_inputs(self): self.assertIn("OpDecorate %in_attr1 Location 1", spv) self.assertEqual(meta["inputs"], [0, 1]) + def test_sparse_inputs_leave_room_for_two_per_vertex_arrays(self): + path = os.path.join(support.HERE, "fixtures", "sparse_bary_locations.asm") + with open(path, encoding="utf-8") as fixture: + spv, meta = self.translate(fixture.read().splitlines()) + self.assertEqual(meta["bary_fallback_input"]["per_vertex"], {"20": 9, "21": 12}) + self.assertEqual(meta["bary_fallback_input"]["location"], 3) + self.assertEqual(meta["inputs"], [0, 1, 2, 4, 6, 8, 20, 21]) + self.assertIn("OpDecorate %in_attr20 Location 9", spv) + self.assertIn("OpDecorate %in_attr21 Location 12", spv) + def test_f16_pair_with_the_f16_fallback_too(self): """NVIDIA Pascal takes both fallbacks: a computed f16 pair decodes the three vertices' raw words rather than the producer's decoded halves, and gives the PerVertexKHR path's halves.""" diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py index 1221422df6..6078c14b20 100644 --- a/tools/rdna2spirv.py +++ b/tools/rdna2spirv.py @@ -16368,7 +16368,9 @@ def assemble(gen): taken = {v for k, v in gen.inputs.items() if not (k.startswith("%in_attr") and int(k[8:]) in gen.per_vertex)} taken |= {loc for pair in gen.f16_half_locs.values() for loc in pair} for n in sorted(gen.per_vertex): - base = next(b for b in range(len(taken) + 3) if not {b, b + 1, b + 2} & taken) + 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} From 32b2d6e66334aaf779459e57159a7fb166584939 Mon Sep 17 00:00:00 2001 From: mrgenty <51083221+mrgenty@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:08:14 +0100 Subject: [PATCH 8/8] runtime/d3d12: count the GS built-ins in the geometry-limit check (RT-BARY-FALLBACK-PER-VERTEX) The Khronos validation layer checks VUID-RuntimeSpirv-Location-06272 for a geometry shader as the last interface slot plus the components of its built-in variables (sl_spirv.cpp, SDK 1.4.341), so the fallback GS's Position (4) and any forwarded ClipDistance/CullDistance count on top of the Location end. The precheck compared the Location end alone: a block at 13..15 (end 64) passed on a 64-component device and drew correctly, but the layer reported 06272 (68 components). BaryFallbackGsInfo gains builtin_components (4 + dist_count), and the precheck refuses a stage whose Location end plus built-ins is above maxGeometryInput/OutputComponents. spirv_bary_fallback_test 7i checks the 68 of the 13..15 block, the 64 edge at 12..14 and a ClipDistance[2] adding 2. Reported by @zmasi on a Vega 20 (RADV) in #1930. --- runtime/shims/d3d12_vulkan_device.cpp | 23 ++++++++++++---------- runtime/src/spirv_bary_fallback.h | 13 ++++++++---- runtime/test/spirv_bary_fallback_test.cpp | 24 +++++++++++++++++++---- 3 files changed, 42 insertions(+), 18 deletions(-) diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index e052d7a04e..50bb86530b 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -12738,15 +12738,18 @@ class PipelineState final } 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 && (bary_info.max_input_location_components > max_gs_in || - bary_info.input_components > max_gs_in)) { - if (bary_info.max_input_location_components > max_gs_in) { + 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 > maxGeometryInputComponents %u); refusing pipeline\n", + "(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, max_gs_in); + 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 " @@ -12756,14 +12759,14 @@ class PipelineState final 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 && (bary_info.max_output_location_components > max_gs_out || - bary_info.output_components > max_gs_out)) { - if (bary_info.max_output_location_components > max_gs_out) { + 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 > maxGeometryOutputComponents %u); refusing pipeline\n", + "(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, max_gs_out); + 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 " diff --git a/runtime/src/spirv_bary_fallback.h b/runtime/src/spirv_bary_fallback.h index fa43a6ee4f..d2d8efa921 100644 --- a/runtime/src/spirv_bary_fallback.h +++ b/runtime/src/spirv_bary_fallback.h @@ -43,18 +43,22 @@ struct BaryFallbackGsInfo { // 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); - // Vulkan VUID-RuntimeSpirv-Location-06272 requires this <= limits.maxGeometryInputComponents. + // 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); - // Vulkan VUID-RuntimeSpirv-Location-06272 requires this <= limits.maxGeometryOutputComponents. + // 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`): @@ -625,6 +629,7 @@ inline bool build_bary_fallback_gs(std::span vs_words, 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()); diff --git a/runtime/test/spirv_bary_fallback_test.cpp b/runtime/test/spirv_bary_fallback_test.cpp index 4e2c49e67e..59a0ea4fd3 100644 --- a/runtime/test/spirv_bary_fallback_test.cpp +++ b/runtime/test/spirv_bary_fallback_test.cpp @@ -710,13 +710,16 @@ int main(int argc, char** argv) { // 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; attribute 15 - // with its block at 13..15 is the 64/64 edge. (Found by @ecox982745, confirmed on a Vega 20 by @zmasi.) + // 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) { + 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{}}); + : std::vector{}, + .clip_count = clip}); const auto ps = build_ps({}, {}, 3, {}, {base}); std::vector gs; BaryFallbackGsInfo info{}; @@ -734,10 +737,23 @@ int main(int argc, char** argv) { 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.