SPIRV-OPT-CFG-DSE-FOLDS: type-safe folding, constant branch/bitcast/select folds, liveness DSE, and mark-sweep DCE #544

Closed
github-bot wants to merge 1 commit from github-bot/gh-544 into main AGit
Owner

@⁠xroneyaa on GitHub · 2026-11-24 07:22 UTC · original
fix/spirv-opt-cfg-dse-folds → main · +731 −152 · 2 files · 1 commits · closed without merging

Claimed in the coordination issue as: SPIRV-OPT-CFG-DSE-FOLDS

What and why

tools/spirv_opt.py had a few type-safety gaps in _fold_int_op and missed several common SPIR-V simplification opportunities left behind by translated RDNA2 shaders:

  1. Type-safe folding (_fold_int_op & id_type):
    • _fold_int_op returned raw operand IDs for algebraic identities (+ 0, * 1, & ~0, | 0, ^ 0, shifts by 0, x & x, x | x, OpBitFieldUExtract(..., 0, width)) and constant-folded comparisons without checking operand/result type equality. With mixed %int/%uint operands (e.g., OpIAdd %uint %ix %u0) or vector comparisons (OpIEqual %v4bool %v %v), this could substitute an %int result ID where %uint was expected or a scalar %bool constant into a %v4bool instruction.
    • _fold_int_op now checks id_type equality via same_ty(...), restricts boolean comparison folds to bool_type_id, maps absorbing zero/all-ones identities (* 0, & 0, | ~0, 0 << s, 0 >> s) strictly through int_const_by_val.get((res_ty, ...)), and folds OpBitFieldUExtract(..., width, 0) to zero.
    • optimize() also records types of OpSpecConstant*, OpUndef, and module-scope OpVariable, as well as OpDecorateId operand IDs so DCE never deletes an operand referenced by OpDecorateId.
  2. Additional peepholes & constant/select folds:
    • OpBitcast: eliminates identity casts (id_type[src] == dst_ty) and folds constant OpBitcast across matching-width 32/64-bit int and exact finite IEEE-754 float constants (distinguishing -0.0 from +0.0).
    • OpSelect & comparisons: simplifies chained same-condition selects (select(c, select(c, a, b), d) -> select(c, a, d)), folds select(c, false, true) to !c, and generalizes constant-outcome OpSelect comparisons (OpIEqual/OpINotEqual against any integer constant).
  3. Constant OpBranchConditional folding & unreachable block cleanup:
    • Folds structured selection headers branching on %true/%false (Case A when taken target is merge M, Case B when not-taken target is M and the taken block is single-predecessor, merge-free, ending in OpBranch M), removes dead incoming OpPhi pairs cleanly, and deletes unreachable blocks not referenced by surviving instructions.
  4. Cross-block backward slot-liveness DSE & mark-and-sweep pure DCE:
    • Replaces whole-function slot in loaded_slots DSE with iterative backward slot-liveness analysis across basic blocks on static_trackable slots (falling back if a block has an unrecognized terminator), eliminating cross-block overwritten stores while keeping loop-live stores intact.
    • Replaces single-pass use_count DCE with mark-and-sweep reachability from impure/decorated roots so dead self-referential OpPhi cycles and unused Function OpVariables are removed cleanly.

Tested

  • python -m unittest tests/test_spirv_opt.py -v -> 15/15 Passed (0.071 s), including new regression tests verifying mixed %int/%uint and %v4bool type safety, constant OpBitcast (with -0.0/+0.0), OpSelect comparisons, constant OpBranchConditional folding (spirv_mini_interp parity), cross-block DSE, dead OpPhi cycle DCE, and OpDecorateId operand preservation
  • Cross-check across all 52 tests/semantic/fixtures/disasm/ps_*.s fixtures:
    • spirv_asm.assemble(opt) -> 52/52 succeeded (0 errors)
    • spirv_mini_interp execution parity (raw vs opt) -> 51/51 executable PS fixtures matched bit-for-bit (0 mismatches; 1 fixture requires external descriptors)
    • Total lines across the 52 PS fixtures: 58343 -> 26510 (54.6% reduction)
  • python -I scripts/check_no_game_data.py tools/spirv_opt.py tests/test_spirv_opt.py -> exit 0

GPUs tested: n/a (CPU-only optimizer unit tests, spirv_asm, and spirv_mini_interp)

AI-assisted: yes

Checklist

  • Based on current main and merges cleanly (a conflicting pull request is labeled needs rebase).
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed (n/a — optimizer pass only, no new ISA translation rule).
**@⁠xroneyaa** on GitHub · 2026-11-24 07:22 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/544) `fix/spirv-opt-cfg-dse-folds` → `main` · +731 −152 · 2 files · 1 commits · closed without merging Claimed in the coordination issue as: SPIRV-OPT-CFG-DSE-FOLDS ### What and why `tools/spirv_opt.py` had a few type-safety gaps in `_fold_int_op` and missed several common SPIR-V simplification opportunities left behind by translated RDNA2 shaders: 1. **Type-safe folding (`_fold_int_op` & `id_type`)**: - `_fold_int_op` returned raw operand IDs for algebraic identities (`+ 0`, `* 1`, `& ~0`, `| 0`, `^ 0`, shifts by `0`, `x & x`, `x | x`, `OpBitFieldUExtract(..., 0, width)`) and constant-folded comparisons without checking operand/result type equality. With mixed `%int`/`%uint` operands (e.g., `OpIAdd %uint %ix %u0`) or vector comparisons (`OpIEqual %v4bool %v %v`), this could substitute an `%int` result ID where `%uint` was expected or a scalar `%bool` constant into a `%v4bool` instruction. - `_fold_int_op` now checks `id_type` equality via `same_ty(...)`, restricts boolean comparison folds to `bool_type_id`, maps absorbing zero/all-ones identities (`* 0`, `& 0`, `| ~0`, `0 << s`, `0 >> s`) strictly through `int_const_by_val.get((res_ty, ...))`, and folds `OpBitFieldUExtract(..., width, 0)` to zero. - `optimize()` also records types of `OpSpecConstant*`, `OpUndef`, and module-scope `OpVariable`, as well as `OpDecorateId` operand IDs so DCE never deletes an operand referenced by `OpDecorateId`. 2. **Additional peepholes & constant/select folds**: - `OpBitcast`: eliminates identity casts (`id_type[src] == dst_ty`) and folds constant `OpBitcast` across matching-width 32/64-bit int and exact finite IEEE-754 float constants (distinguishing `-0.0` from `+0.0`). - `OpSelect` & comparisons: simplifies chained same-condition selects (`select(c, select(c, a, b), d) -> select(c, a, d)`), folds `select(c, false, true)` to `!c`, and generalizes constant-outcome `OpSelect` comparisons (`OpIEqual`/`OpINotEqual` against any integer constant). 3. **Constant `OpBranchConditional` folding & unreachable block cleanup**: - Folds structured selection headers branching on `%true`/`%false` (`Case A` when taken target is merge `M`, `Case B` when not-taken target is `M` and the taken block is single-predecessor, merge-free, ending in `OpBranch M`), removes dead incoming `OpPhi` pairs cleanly, and deletes unreachable blocks not referenced by surviving instructions. 4. **Cross-block backward slot-liveness DSE & mark-and-sweep pure DCE**: - Replaces whole-function `slot in loaded_slots` DSE with iterative backward slot-liveness analysis across basic blocks on `static_trackable` slots (falling back if a block has an unrecognized terminator), eliminating cross-block overwritten stores while keeping loop-live stores intact. - Replaces single-pass `use_count` DCE with mark-and-sweep reachability from impure/decorated roots so dead self-referential `OpPhi` cycles and unused `Function` `OpVariable`s are removed cleanly. ### Tested - `python -m unittest tests/test_spirv_opt.py -v` -> 15/15 Passed (`0.071 s`), including new regression tests verifying mixed `%int`/`%uint` and `%v4bool` type safety, constant `OpBitcast` (with `-0.0`/`+0.0`), `OpSelect` comparisons, constant `OpBranchConditional` folding (`spirv_mini_interp` parity), cross-block DSE, dead `OpPhi` cycle DCE, and `OpDecorateId` operand preservation - Cross-check across all 52 `tests/semantic/fixtures/disasm/ps_*.s` fixtures: - `spirv_asm.assemble(opt)` -> 52/52 succeeded (0 errors) - `spirv_mini_interp` execution parity (`raw` vs `opt`) -> 51/51 executable PS fixtures matched bit-for-bit (0 mismatches; 1 fixture requires external descriptors) - Total lines across the 52 PS fixtures: `58343 -> 26510` (`54.6%` reduction) - `python -I scripts/check_no_game_data.py tools/spirv_opt.py tests/test_spirv_opt.py` -> exit 0 GPUs tested: n/a (CPU-only optimizer unit tests, `spirv_asm`, and `spirv_mini_interp`) AI-assisted: yes ### Checklist - [x] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed (n/a — optimizer pass only, no new ISA translation rule).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 09:07:33 +00:00
Author
Owner

@⁠sodove on GitHub · 2026-11-24 07:38 UTC · original

Independent GPU verification of 60668dfbdf against main d42773d. I ran seven hand-written synthetic fragment cases with Khronos SPIRV-Tools v2026.4 (ef96ed76, Vulkan 1.2) and VK_LAYER_KHRONOS_validation 1.4.369.

Variant Modules accepted by SPIRV-Tools Pixels matching expected values Vulkan validation errors
Unoptimized 7/7 56/56 0
main optimizer 6/7 48/48 across valid modules 0
#544 optimizer 7/7 56/56 0

The rejected main output substitutes a signed operand into OpUDiv when folding the preceding mixed-signedness arithmetic identity. The PR preserves the unsigned result type. All seven PR readbacks match the unoptimized readbacks byte for byte on two runs.

Both constant-branch fold shapes, a nested selection, the switch with predecessor stores, the loop with a continue edge and a loop-carried store, and the negative-zero bitcast retained their outputs. In the switch case the PR dropped the overwritten initial store and retained all four predecessor stores. The loop retained both stores.

GPU: NVIDIA RTX 5070 Ti, driver 610.74, Windows 11 26100.7623. Synthetic fixtures only. AI-assisted.

**@⁠sodove** on GitHub · 2026-11-24 07:38 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/544#issuecomment-7125207876) Independent GPU verification of 60668dfbdfffdad4193a3e851a1935e2917f5d2d against main d42773d. I ran seven hand-written synthetic fragment cases with Khronos SPIRV-Tools v2026.4 (ef96ed76, Vulkan 1.2) and VK_LAYER_KHRONOS_validation 1.4.369. | Variant | Modules accepted by SPIRV-Tools | Pixels matching expected values | Vulkan validation errors | | --- | ---: | ---: | ---: | | Unoptimized | 7/7 | 56/56 | 0 | | main optimizer | 6/7 | 48/48 across valid modules | 0 | | #544 optimizer | 7/7 | 56/56 | 0 | The rejected main output substitutes a signed operand into OpUDiv when folding the preceding mixed-signedness arithmetic identity. The PR preserves the unsigned result type. All seven PR readbacks match the unoptimized readbacks byte for byte on two runs. Both constant-branch fold shapes, a nested selection, the switch with predecessor stores, the loop with a continue edge and a loop-carried store, and the negative-zero bitcast retained their outputs. In the switch case the PR dropped the overwritten initial store and retained all four predecessor stores. The loop retained both stores. GPU: NVIDIA RTX 5070 Ti, driver 610.74, Windows 11 26100.7623. Synthetic fixtures only. AI-assisted.
Author
Owner

@⁠aslan2142 on GitHub · 2026-11-25 19:43 UTC · original

test_mixed_signedness_identities_and_vector_iequal_stay_type_safe fails wherever spirv-as/spirv-val are installed (SPIRV-Tools v2026.4). spirv-val rejects the input module before the optimizer runs: %b = OpBitFieldUExtract %uint %ix ... has an int base (Expected Base Type to be equal to Result Type). Please make the input valid, so the test checks the optimizer rather than the fixture.

AI-assisted (Claude Code, Claude Opus 5.5).

**@⁠aslan2142** on GitHub · 2026-11-25 19:43 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/544#issuecomment-7172691087) `test_mixed_signedness_identities_and_vector_iequal_stay_type_safe` fails wherever `spirv-as`/`spirv-val` are installed (SPIRV-Tools v2026.4). `spirv-val` rejects the input module before the optimizer runs: `%b = OpBitFieldUExtract %uint %ix ...` has an `int` base (`Expected Base Type to be equal to Result Type`). Please make the input valid, so the test checks the optimizer rather than the fixture. AI-assisted (Claude Code, Claude Opus 5.5).
github-bot closed this pull request 2026-11-27 07:40:11 +00:00

Pull request closed

This discussion has been locked. Commenting is limited to contributors.
No description provided.