perf(shader): promote bitcast-wrapped i32 PHIs to f32 in bitcode opt (#276) #311

Merged
RUIZ-Enrique-25002136 merged 1 commit from upstream-pr/311 into main 2026-12-03 11:31:58 +00:00
RUIZ-Enrique-25002136 commented 2026-12-02 08:55:28 +00:00 (Migrated from github.com)

Imported from Androtim/MiniVI. Originally posted by RUIZ-Enrique-25002136 on 2026-12-02T08:55:28Z.


Summary

Implements Module::promote_float_phis in crates/victory-shader/src/emit/bitcode/opt.rs (tracked in #276's victory-shader GPU Shader Time backlog): promotes bitcast-wrapped 32-bit i32 Op::Phi webs directly to f32 Op::Phis during Module::optimise, allowing merge() and drop_dead() to eliminate redundant f32 <-> i32 bitcast round-trips across branches and loops.

Refs #276

AI-Ready Context & Change Map

For downstream coding/review agents, here is the exact scope, algorithm, and invariant set of this PR:

  1. crates/victory-shader/src/emit/bitcode/opt.rs — Module::promote_float_phis & Pass Integration

    • Pass ordering (Module::optimise, opt.rs:236-247):
      • Runs self.promote_float_phis() inside the for _ in 0..4 loop whenever passes & FOLD != 0, before self.merge(passes).
      • Running before merge(passes) ensures that every promoted i32 -> f32 PHI immediately turns its downstream Op::Cast(Cast::Bitcast, V::Inst(phi)) users into f32 -> f32 identity bitcasts (opt.rs:650: if from == ty { return Some(x); }), which merge() deletes from blk.body and rewires in the same iteration, while drop_dead() drops all now-unused f32 -> i32 producer bitcasts.
    • Reachability scoping (opt.rs:705-746):
      • Only inspects blocks where self.reached()[b] is true, matching merge()'s dominator-tree traversal and Module::write()'s reachable postorder traversal so no unreachable bitcast(f32 -> f32) can ever be orphaned.
    • Greatest-fixpoint web elimination (opt.rs:753-795):
      • Initializes cand[i] = true for every non-empty 32-bit integer Op::Phi in a reachable block.
      • Repeatedly eliminates any candidate i if:
        • term_used[i] is true (used directly by Term::CondBr), OR
        • any user u in users[i] is neither an i32 -> f32 Cast::Bitcast nor another surviving cand PHI, OR
        • any incoming edge (v, _) of i is not float_bitcast_src(f32_ty, v) (Op::Cast(Cast::Bitcast, x) with type_of(x) == f32_ty), a surviving cand PHI, or a 32-bit Const::Int / Const::Undef.
    • Witness check (opt.rs:799-838):
      • Prevents promoting pure-integer constant/unused PHI cycles by requiring every surviving cand web to be connected (transitively along cand PHI-to-PHI edges) to at least one actual f32 -> i32 incoming bitcast or i32 -> f32 user bitcast.
    • Bit-exact rewrite (opt.rs:840-866):
      • Updates self.insts[i].ty = f32_ty and rewrites each incoming (v, b) to:
        • (x, b) when v is bitcast(x: f32 -> i32),
        • (v, b) when v is another promoted cand PHI,
        • (self.f32(bits as u32), b) for Const::Int(bits),
        • (self.undef(f32_ty), b) for Const::Undef.
      • Because Const::Int(bits) maps bit-for-bit to Const::Float(bits as u32) and bitcasts preserve exact 32-bit payloads (including -0.0 and NaN encodings), semantics are bit-exact.
  2. crates/victory-shader/src/emit/bitcode/opt.rs — Unit Tests

    • float_phis_promote_across_diamond_and_loop (opt.rs:2418-2504):
      • Verifies promotion of both a diamond join PHI and a loop-carried PHI (Const::Int(0) init + bitcast(fadd(bitcast(phi))) back-edge), asserting both PHIs become f32, 0 Cast::Bitcast instructions remain after optimise(ALL), Module::write() succeeds, and the interpreter run() trace matches before/after across branching inputs.
    • mixed_int_and_float_phi_stays_i32 (opt.rs:2506-2548):
      • Verifies an i32 PHI mixing bitcast(f32 -> i32) and an integer Bin::Add stays i32 and preserves exact run() behavior.

Rig Specs Tested On

  • CPU: Linux workstation (offline unit tests, differential fuzzer 400 seeds × 8 pass configs, and clippy)
  • GPU & VRAM: N/A (not executed on live Windows D3D12 hardware)
  • System RAM: N/A
  • OS & GPU Driver: Linux (x86_64) — Windows x86_64-pc-windows-msvc full workspace clippy and live GPU frame-time benchmarks deferred to GitHub Actions (windows-latest) / maintainer run

Run Settings & Profile

  • Build & Commit SHA: victory-shader bitcode optimizer changes on top of origin/main (c7d3102)
  • Console Profile & Internal Resolution / Scale: N/A (unit tests & differential fuzzer)
  • Ray Tracing: N/A
  • Upscaling: N/A
  • Frame Generation: N/A
  • Launcher Command / Preset & Extra VICTORY_* Overrides: N/A
  • Scene / Area & Session Length: N/A

Measurements & Verification

  • Base FPS (without Frame Gen): N/A (offline compiler unit tests)
  • Frame-Gen FPS (if enabled): N/A
  • VRAM / RAM Usage: N/A
  • Crashes / DRED Resets: N/A
  • Automated Checks:
    • cargo clippy --workspace --all-targets --locked -- -D warnings (requires x86_64-pc-windows-msvc; verified on GitHub Actions windows-latest CI)
    • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings (requires x86_64-pc-windows-msvc; verified on GitHub Actions windows-latest CI)
    • cargo clippy --locked -p victory-shader --lib -- -D warnings -> 0 warnings, exit 0
    • cargo test --locked -p victory-shader emit::bitcode::opt::tests -> 13 passed, 0 failed (including every_pass_leaves_what_random_programs_store, float_phis_promote_across_diamond_and_loop, mixed_int_and_float_phi_stays_i32)
    • cargo test --locked -p victory-shader -- --test-threads=1 -> 254 passed, 0 failed, 2 ignored
    • cargo test --locked -p xtask -> 8 passed, 0 failed
    • cargo xtask policy -> asset policy: 321 files ok
<!-- greyfinch-sync:Androtim/MiniVI:issue:5603102303 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/pull/311). Originally posted by [RUIZ-Enrique-25002136](https://github.com/RUIZ-Enrique-25002136) on 2026-12-02T08:55:28Z. --- ## Summary Implements `Module::promote_float_phis` in `crates/victory-shader/src/emit/bitcode/opt.rs` (tracked in #276's `victory-shader` GPU Shader Time backlog): promotes bitcast-wrapped 32-bit `i32` `Op::Phi` webs directly to `f32` `Op::Phi`s during `Module::optimise`, allowing `merge()` and `drop_dead()` to eliminate redundant `f32 <-> i32` `bitcast` round-trips across branches and loops. Refs #276 ### AI-Ready Context & Change Map For downstream coding/review agents, here is the exact scope, algorithm, and invariant set of this PR: 1. **`crates/victory-shader/src/emit/bitcode/opt.rs` — `Module::promote_float_phis` & Pass Integration** - **Pass ordering (`Module::optimise`, `opt.rs:236-247`):** - Runs `self.promote_float_phis()` inside the `for _ in 0..4` loop whenever `passes & FOLD != 0`, **before** `self.merge(passes)`. - Running before `merge(passes)` ensures that every promoted `i32 -> f32` PHI immediately turns its downstream `Op::Cast(Cast::Bitcast, V::Inst(phi))` users into `f32 -> f32` identity bitcasts (`opt.rs:650`: `if from == ty { return Some(x); }`), which `merge()` deletes from `blk.body` and rewires in the same iteration, while `drop_dead()` drops all now-unused `f32 -> i32` producer bitcasts. - **Reachability scoping (`opt.rs:705-746`):** - Only inspects blocks where `self.reached()[b]` is true, matching `merge()`'s dominator-tree traversal and `Module::write()`'s reachable postorder traversal so no unreachable `bitcast(f32 -> f32)` can ever be orphaned. - **Greatest-fixpoint web elimination (`opt.rs:753-795`):** - Initializes `cand[i] = true` for every non-empty 32-bit integer `Op::Phi` in a reachable block. - Repeatedly eliminates any candidate `i` if: - `term_used[i]` is true (used directly by `Term::CondBr`), OR - any user `u` in `users[i]` is neither an `i32 -> f32` `Cast::Bitcast` nor another surviving `cand` PHI, OR - any incoming edge `(v, _)` of `i` is not `float_bitcast_src(f32_ty, v)` (`Op::Cast(Cast::Bitcast, x)` with `type_of(x) == f32_ty`), a surviving `cand` PHI, or a 32-bit `Const::Int` / `Const::Undef`. - **Witness check (`opt.rs:799-838`):** - Prevents promoting pure-integer constant/unused PHI cycles by requiring every surviving `cand` web to be connected (transitively along `cand` PHI-to-PHI edges) to at least one actual `f32 -> i32` incoming bitcast or `i32 -> f32` user bitcast. - **Bit-exact rewrite (`opt.rs:840-866`):** - Updates `self.insts[i].ty = f32_ty` and rewrites each incoming `(v, b)` to: - `(x, b)` when `v` is `bitcast(x: f32 -> i32)`, - `(v, b)` when `v` is another promoted `cand` PHI, - `(self.f32(bits as u32), b)` for `Const::Int(bits)`, - `(self.undef(f32_ty), b)` for `Const::Undef`. - Because `Const::Int(bits)` maps bit-for-bit to `Const::Float(bits as u32)` and bitcasts preserve exact 32-bit payloads (including `-0.0` and NaN encodings), semantics are bit-exact. 2. **`crates/victory-shader/src/emit/bitcode/opt.rs` — Unit Tests** - **`float_phis_promote_across_diamond_and_loop` (`opt.rs:2418-2504`):** - Verifies promotion of both a diamond join PHI and a loop-carried PHI (`Const::Int(0)` init + `bitcast(fadd(bitcast(phi)))` back-edge), asserting both PHIs become `f32`, `0` `Cast::Bitcast` instructions remain after `optimise(ALL)`, `Module::write()` succeeds, and the interpreter `run()` trace matches before/after across branching inputs. - **`mixed_int_and_float_phi_stays_i32` (`opt.rs:2506-2548`):** - Verifies an `i32` PHI mixing `bitcast(f32 -> i32)` and an integer `Bin::Add` stays `i32` and preserves exact `run()` behavior. ## Rig Specs Tested On - **CPU:** Linux workstation (offline unit tests, differential fuzzer `400` seeds × `8` pass configs, and clippy) - **GPU & VRAM:** N/A (not executed on live Windows D3D12 hardware) - **System RAM:** N/A - **OS & GPU Driver:** Linux (x86_64) — Windows `x86_64-pc-windows-msvc` full workspace clippy and live GPU frame-time benchmarks deferred to GitHub Actions (`windows-latest`) / maintainer run ## Run Settings & Profile - **Build & Commit SHA:** `victory-shader` bitcode optimizer changes on top of `origin/main` (`c7d3102`) - **Console Profile & Internal Resolution / Scale:** N/A (unit tests & differential fuzzer) - **Ray Tracing:** N/A - **Upscaling:** N/A - **Frame Generation:** N/A - **Launcher Command / Preset & Extra `VICTORY_*` Overrides:** N/A - **Scene / Area & Session Length:** N/A ## Measurements & Verification - **Base FPS (without Frame Gen):** N/A (offline compiler unit tests) - **Frame-Gen FPS (if enabled):** N/A - **VRAM / RAM Usage:** N/A - **Crashes / DRED Resets:** N/A - **Automated Checks:** - [ ] `cargo clippy --workspace --all-targets --locked -- -D warnings` (requires `x86_64-pc-windows-msvc`; verified on GitHub Actions `windows-latest` CI) - [ ] `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings` (requires `x86_64-pc-windows-msvc`; verified on GitHub Actions `windows-latest` CI) - [x] `cargo clippy --locked -p victory-shader --lib -- -D warnings` -> 0 warnings, exit 0 - [x] `cargo test --locked -p victory-shader emit::bitcode::opt::tests` -> 13 passed, 0 failed (including `every_pass_leaves_what_random_programs_store`, `float_phis_promote_across_diamond_and_loop`, `mixed_int_and_float_phi_stays_i32`) - [x] `cargo test --locked -p victory-shader -- --test-threads=1` -> 254 passed, 0 failed, 2 ignored - [x] `cargo test --locked -p xtask` -> 8 passed, 0 failed - [x] `cargo xtask policy` -> `asset policy: 321 files ok`
Androtim commented 2026-12-02 09:03:43 +00:00 (Migrated from github.com)

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-02T09:03:43Z.


Automated triage for the maintainers (not an approval).

Verdict: needs-gpu-test · CI (check): passing

Review Summary

Logic, type-safety invariants, and test coverage look solid, and CI is passing. Because this changes emitted DXIL shader bitcode (victory-shader), a quick local Windows/D3D12 real-GPU smoke test (cold shader compile + PSO creation + visual check) is warranted before merging.

What was verified

  • Pass ordering (crates/victory-shader/src/emit/bitcode/opt.rs, Module::optimise): Running self.promote_float_phis() inside the for _ in 0..4 loop right before self.merge(passes) when passes & FOLD != 0 ensures newly created f32 -> f32 identity bitcasts are immediately folded by Module::fold (Cast::Bitcast from == ty branch) in the same iteration, with dead producer bitcasts cleaned up by drop_dead().
  • Greatest-fixpoint web analysis (Module::promote_float_phis, Module::float_bitcast_src):
    • Correctly scopes candidates and users to self.reached() blocks.
    • Rejects any candidate i32 PHI with non-bitcast/non-candidate users, terminator uses (Term::CondBr), or non-float-bitcast/non-candidate/non-Const::Int|Const::Undef incoming edges.
    • Bidirectional witnessed propagation over cand PHI-to-PHI edges ensures connected PHI webs are promoted atomically (no mixed i32/f32 PHI edges) and only when anchored to at least one actual float bitcast.
    • Const::Int(bits) => self.f32(bits as u32) and Const::Undef => self.undef(f32_ty) preserve exact 32-bit bit patterns (including -0.0 and NaN payloads).
  • Tests: float_phis_promote_across_diamond_and_loop and mixed_int_and_float_phi_stays_i32 cover both positive (diamond + loop-carried PHI with zero remaining bitcasts and Module::write()) and negative (mixed int/float PHI stays i32) cases alongside the existing randomized differential pass tests.

Minor note (non-blocking)

  • The two fixpoint loops in promote_float_phis iterate 0..self.insts.len(); collecting candidate PHI indices into a small Vec<usize> would avoid scanning non-PHI instructions on repeated fixpoint passes, though the current cost is negligible for typical shader sizes.

Next step

Run a local Windows D3D12 smoke test with a cold shader cache to confirm DXIL validation, driver PSO compilation, and rendering output on real GPU hardware.


Generated with Antigravity CLI (agy).

<!-- greyfinch-sync:Androtim/MiniVI:comment:7340316272 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/pull/311#issuecomment-7340316272). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-02T09:03:43Z. --- <!-- minivi-triage v1 head=26c1e47c5eeaf1f75871d92a3e519e91c7295621 verdict=needs-gpu-test ci=passing at=2026-12-02T09:04:14Z --> Automated triage for the maintainers (not an approval). **Verdict:** `needs-gpu-test` · **CI (`check`):** `passing` ### Review Summary Logic, type-safety invariants, and test coverage look solid, and CI is passing. Because this changes emitted DXIL shader bitcode (`victory-shader`), a quick local Windows/D3D12 real-GPU smoke test (cold shader compile + PSO creation + visual check) is warranted before merging. ### What was verified - **Pass ordering (`crates/victory-shader/src/emit/bitcode/opt.rs`, `Module::optimise`)**: Running `self.promote_float_phis()` inside the `for _ in 0..4` loop right before `self.merge(passes)` when `passes & FOLD != 0` ensures newly created `f32 -> f32` identity bitcasts are immediately folded by `Module::fold` (`Cast::Bitcast` `from == ty` branch) in the same iteration, with dead producer bitcasts cleaned up by `drop_dead()`. - **Greatest-fixpoint web analysis (`Module::promote_float_phis`, `Module::float_bitcast_src`)**: - Correctly scopes candidates and users to `self.reached()` blocks. - Rejects any candidate `i32` PHI with non-bitcast/non-candidate users, terminator uses (`Term::CondBr`), or non-float-bitcast/non-candidate/non-`Const::Int|Const::Undef` incoming edges. - Bidirectional `witnessed` propagation over `cand` PHI-to-PHI edges ensures connected PHI webs are promoted atomically (no mixed `i32`/`f32` PHI edges) and only when anchored to at least one actual float bitcast. - `Const::Int(bits) => self.f32(bits as u32)` and `Const::Undef => self.undef(f32_ty)` preserve exact 32-bit bit patterns (including `-0.0` and NaN payloads). - **Tests**: `float_phis_promote_across_diamond_and_loop` and `mixed_int_and_float_phi_stays_i32` cover both positive (diamond + loop-carried PHI with zero remaining bitcasts and `Module::write()`) and negative (mixed int/float PHI stays `i32`) cases alongside the existing randomized differential pass tests. ### Minor note (non-blocking) - The two fixpoint loops in `promote_float_phis` iterate `0..self.insts.len()`; collecting candidate PHI indices into a small `Vec<usize>` would avoid scanning non-PHI instructions on repeated fixpoint passes, though the current cost is negligible for typical shader sizes. ### Next step Run a local Windows D3D12 smoke test with a cold shader cache to confirm DXIL validation, driver PSO compilation, and rendering output on real GPU hardware. --- _Generated with Antigravity CLI (`agy`)._
Androtim commented 2026-12-03 11:12:46 +00:00 (Migrated from github.com)

Imported from Androtim/MiniVI. Originally posted by Androtim on 2026-12-03T11:12:46Z.


Gate 3 Live Windows D3D12 Cold-Cache GPU Verification — PASS

Tested combined PR #311 + PR #314 on Windows 11 + NVIDIA RTX 4060 Ti 8 GB (1440p DLSS Quality, fresh cold shader cache):

  • Unit tests: 14/14 victory-shader::emit::bitcode::opt::tests passing (including float_phis_promote_across_diamond_and_loop, mixed_int_and_float_phi_stays_i32, idempotent_saturate_and_minmax_calls_fold, and randomized differential tests).
  • Cold shader cache: Translated 1,049 shaders and built 199 host PSOs cleanly with 0 DXIL validation errors, 0 PSO compilation failures, 0 DRED, and 0 device-removed (only the known baseline unsupported wave64 compute shaders).
  • Visual & VRAM verification: Full in-world scene parity verified (DRAWS 9904, DROPPED 172, 0 being made, peak dedicated VRAM 5476 / 6613 MiB, crisp lighting/textures/meshes).

Ready to merge!

<!-- greyfinch-sync:Androtim/MiniVI:comment:7376371767 --> Imported from [Androtim/MiniVI](https://github.com/Androtim/MiniVI/pull/311#issuecomment-7376371767). Originally posted by [Androtim](https://github.com/Androtim) on 2026-12-03T11:12:46Z. --- ### Gate 3 Live Windows D3D12 Cold-Cache GPU Verification — PASS Tested combined PR #311 + PR #314 on Windows 11 + **NVIDIA RTX 4060 Ti 8 GB** (`1440p` DLSS Quality, fresh cold shader cache): - **Unit tests:** `14/14` `victory-shader::emit::bitcode::opt::tests` passing (including `float_phis_promote_across_diamond_and_loop`, `mixed_int_and_float_phi_stays_i32`, `idempotent_saturate_and_minmax_calls_fold`, and randomized differential tests). - **Cold shader cache:** Translated **1,049 shaders** and built **199 host PSOs** cleanly with **0 DXIL validation errors**, **0 PSO compilation failures**, **0 DRED**, and **0 device-removed** (only the known baseline unsupported wave64 compute shaders). - **Visual & VRAM verification:** Full in-world scene parity verified (`DRAWS 9904`, `DROPPED 172`, `0 being made`, peak dedicated VRAM `5476 / 6613 MiB`, crisp lighting/textures/meshes). Ready to merge!
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Androtim/MiniVI!311
No description provided.