Shaders: one instruction for one value (13.5 % fewer emitted instructions, no program lost) #2150

Open
github-bot wants to merge 3 commits from github-bot/gh-2150 into main AGit
Owner

@⁠r4tedx on GitHub · 2026-11-25 06:16 UTC · original
r4tedx:shader/value-reuse → main · +570 −0 · 4 files · 3 commits · open

Summary: a pass over the finished DXIL module keeps one instruction for one value. On the title's shaders it takes out 10.5 % of the emitted instructions (on main 13f91ca) and loses no program. It makes a synthetic store-heavy program 19–27 % faster on WARP and changes nothing measurable on an AMD GPU, whose compiler already does this. So the gain shown is smaller modules, not GPU time.

What it does

The lowering writes code as the console instructions name it: a register read as a float is cast again at each read, a descriptor's handle is made and its index clamped again in each block, an address is shifted and masked again for each access. bitcode::reuse (new file emit/bitcode/reuse.rs, called from Shader::finish before the module is written) walks the dominator tree. An instruction that computes what an earlier one computed, where every path to it has run that earlier one, is left out, and its readers take the earlier result.

It takes part only where the result is a function of the operands:

  • integer arithmetic and compares, integer selects, width casts and bit casts, extractvalue, getelementptr
  • createHandleFromBinding, createHandleFromHeap, annotateHandle, and the integer dx.ops declared readnone
  • getDimensions: a resource's dimensions do not change while a shader runs
  • raw loads from the host's own tables (page table, view addresses, view marks, view strides). No shader writes them. The host does rewrite entries while the GPU runs, and the pass needs no promise about that: inside one invocation, the reads of one entry it merges give one value, the first read's.

It leaves these exactly as the lowering wrote them:

  • float arithmetic, float compares, conversions and float dx.ops: a driver may contract or reorder them by how they are used
  • every other load, samples, atomics, barriers, wave operations

Why it cannot break the flags

#1716 and #1646 each lose programs that validate on main ("Flags must match usage", "Internal declaration 'code' is unused"): removing the last use of an operation leaves the declared flags or a declaration stale. This pass removes only a copy of an instruction that stays, with the same operands. So no operation and no declaration loses its last use, no value loses its last reader, and nothing has to be recomputed. It does not do dead-code elimination or folding; those are #697, #1716 and #1646, and it composes with them.

Measured

Offline, the title's shaders.rpf (local title data, CPU only, translate --validate --list --count from #2115 b0f0b2e, dxil.dll 10.0.26100.0; counts only). Counted on main 13f91ca, which already has 850b66f (one handle per descriptor in the entry block) and 286a00e (dead code left out, constant branches folded):

main 13f91ca with this PR
instructions in emitted programs 164,909,025 147,551,134 −10.53 %
programs validated 24,846 24,846 none lost, none gained
programs smaller / same / larger 25,076 / 589 / 0

Every program has the same outcome as on main, compared program by program. What goes: bitcast −10,910,357, and −1,926,671, icmp −948,319, add −775,608, select −705,144, lshr −437,927, shl −406,785, or −390,609, annotateHandle −205,819, createHandleFromHeap −108,011, createHandleFromBinding −98,758, rawBufferLoad −84,623 (the table loads), getDimensions −925. Blocks are unchanged. (On 940d32f, before 850b66f and 286a00e, it was 190,954,569 -> 165,215,092, −13.48 %.)

GPU timestamps on a synthetic program (measured at 91d75b8 on 940d32f) (a compute program of 32 lanes that stores to an unordered buffer view 8 or 32 times, with write marks; least of 7 runs; the benchmark is not in this PR):

adapter stores main with this PR
WARP, 4,096 groups 8 6.13 ms 4.47 ms
WARP, 4,096 groups 32 23.08 ms 18.78 ms
AMD Radeon integrated (driver 32.0.21036.18), 65,536 groups 8 1.367 ms 1.367 ms
AMD Radeon integrated, 65,536 groups 32 5.198 ms 5.190 ms

WARP times do not predict a graphics card, and the Radeon rows show it: its compiler removes the copies itself. I did not measure pipeline compile time, and nothing was measured on NVIDIA or in the title.

Checks

  • cargo test -p victory-shader --lib at dcdb50e with VICTORY_WARP=1, one thread: 272 passed, 0 failed, 3 ignored, 3 skipped. Skipped: synthetic_tests::gathers_at_a_level_match_the_hardware, synthetic_tests::permutes_read_the_lane_named_and_zero_from_lanes_left_out, synthetic_tests::a_mask_joined_with_data_at_a_uniform_loop_is_its_number. They come from main, and their first leg asks for the hardware adapter, which VICTORY_WARP=1 turns into WARP (wave of 32 refused, WARP's gather rounding), so they fail there by design.
  • clippy -p victory-shader --all-targets -D warnings at dcdb50e: clean.
  • Five new unit tests, no device: a block keeps one of each value; a value serves only what it dominates (not a sibling branch, not the join from one side); floats, loads and atomics are left alone; a table entry is read once and the same load through another handle stays; a loop's phi and branch read the value kept.
  • cargo clippy -p victory-shader -p victory --all-targets: clean. rustfmt --check on the new file: clean. cargo xtask policy: ok.
  • Not run: the suite on a hardware GPU. A run on AMD and NVIDIA hardware by someone who has them would be welcome.

Credit

The fork fxceless/victory-fork has a clean-up pass with a "reuse" step; the idea of doing this on the finished module comes from reading it. No code is taken from it. This pass differs in what it admits (an explicit list and the declared readnone attribute, not name prefixes, and no floats).

AI-assisted.

🤖 Generated with Claude Code

**@⁠r4tedx** on GitHub · 2026-11-25 06:16 UTC · [original](https://github.com/Marvisak/VIctory/pull/2150) `r4tedx:shader/value-reuse` → `main` · +570 −0 · 4 files · 3 commits · open **Summary:** a pass over the finished DXIL module keeps one instruction for one value. On the title's shaders it takes out 10.5 % of the emitted instructions (on main 13f91ca) and loses no program. It makes a synthetic store-heavy program 19–27 % faster on WARP and changes nothing measurable on an AMD GPU, whose compiler already does this. So the gain shown is smaller modules, not GPU time. ## What it does The lowering writes code as the console instructions name it: a register read as a float is cast again at each read, a descriptor's handle is made and its index clamped again in each block, an address is shifted and masked again for each access. `bitcode::reuse` (new file `emit/bitcode/reuse.rs`, called from `Shader::finish` before the module is written) walks the dominator tree. An instruction that computes what an earlier one computed, where every path to it has run that earlier one, is left out, and its readers take the earlier result. It takes part only where the result is a function of the operands: - integer arithmetic and compares, integer selects, width casts and bit casts, `extractvalue`, `getelementptr` - `createHandleFromBinding`, `createHandleFromHeap`, `annotateHandle`, and the integer `dx.op`s declared `readnone` - `getDimensions`: a resource's dimensions do not change while a shader runs - raw loads from the host's own tables (page table, view addresses, view marks, view strides). No shader writes them. The host does rewrite entries while the GPU runs, and the pass needs no promise about that: inside one invocation, the reads of one entry it merges give one value, the first read's. It leaves these exactly as the lowering wrote them: - float arithmetic, float compares, conversions and float `dx.op`s: a driver may contract or reorder them by how they are used - every other load, samples, atomics, barriers, wave operations ## Why it cannot break the flags #1716 and #1646 each lose programs that validate on `main` ("Flags must match usage", "Internal declaration 'code' is unused"): removing the last use of an operation leaves the declared flags or a declaration stale. This pass removes only a copy of an instruction that stays, with the same operands. So no operation and no declaration loses its last use, no value loses its last reader, and nothing has to be recomputed. It does not do dead-code elimination or folding; those are #697, #1716 and #1646, and it composes with them. ## Measured **Offline, the title's `shaders.rpf`** (local title data, CPU only, `translate --validate --list --count` from #2115 `b0f0b2e`, dxil.dll 10.0.26100.0; counts only). Counted on `main` `13f91ca`, which already has 850b66f (one handle per descriptor in the entry block) and 286a00e (dead code left out, constant branches folded): | | `main` `13f91ca` | with this PR | | | --- | ---: | ---: | ---: | | instructions in emitted programs | 164,909,025 | 147,551,134 | −10.53 % | | programs validated | 24,846 | 24,846 | none lost, none gained | | programs smaller / same / larger | | 25,076 / 589 / 0 | | Every program has the same outcome as on `main`, compared program by program. What goes: `bitcast` −10,910,357, `and` −1,926,671, `icmp` −948,319, `add` −775,608, `select` −705,144, `lshr` −437,927, `shl` −406,785, `or` −390,609, `annotateHandle` −205,819, `createHandleFromHeap` −108,011, `createHandleFromBinding` −98,758, `rawBufferLoad` −84,623 (the table loads), `getDimensions` −925. Blocks are unchanged. (On `940d32f`, before 850b66f and 286a00e, it was 190,954,569 -> 165,215,092, −13.48 %.) **GPU timestamps on a synthetic program** (measured at `91d75b8` on `940d32f`) (a compute program of 32 lanes that stores to an unordered buffer view 8 or 32 times, with write marks; least of 7 runs; the benchmark is not in this PR): | adapter | stores | `main` | with this PR | | --- | ---: | ---: | ---: | | WARP, 4,096 groups | 8 | 6.13 ms | 4.47 ms | | WARP, 4,096 groups | 32 | 23.08 ms | 18.78 ms | | AMD Radeon integrated (driver 32.0.21036.18), 65,536 groups | 8 | 1.367 ms | 1.367 ms | | AMD Radeon integrated, 65,536 groups | 32 | 5.198 ms | 5.190 ms | WARP times do not predict a graphics card, and the Radeon rows show it: its compiler removes the copies itself. I did not measure pipeline compile time, and nothing was measured on NVIDIA or in the title. ## Checks - `cargo test -p victory-shader --lib` at `dcdb50e` with `VICTORY_WARP=1`, one thread: 272 passed, 0 failed, 3 ignored, 3 skipped. Skipped: `synthetic_tests::gathers_at_a_level_match_the_hardware`, `synthetic_tests::permutes_read_the_lane_named_and_zero_from_lanes_left_out`, `synthetic_tests::a_mask_joined_with_data_at_a_uniform_loop_is_its_number`. They come from main, and their first leg asks for the hardware adapter, which `VICTORY_WARP=1` turns into WARP (wave of 32 refused, WARP's gather rounding), so they fail there by design. - clippy `-p victory-shader --all-targets -D warnings` at `dcdb50e`: clean. - Five new unit tests, no device: a block keeps one of each value; a value serves only what it dominates (not a sibling branch, not the join from one side); floats, loads and atomics are left alone; a table entry is read once and the same load through another handle stays; a loop's phi and branch read the value kept. - `cargo clippy -p victory-shader -p victory --all-targets`: clean. `rustfmt --check` on the new file: clean. `cargo xtask policy`: ok. - Not run: the suite on a hardware GPU. A run on AMD and NVIDIA hardware by someone who has them would be welcome. ## Credit The fork `fxceless/victory-fork` has a clean-up pass with a "reuse" step; the idea of doing this on the finished module comes from reading it. No code is taken from it. This pass differs in what it admits (an explicit list and the declared `readnone` attribute, not name prefixes, and no floats). AI-assisted. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
The lowering writes code as the console instructions name it: a register
read as a float is cast again at each read, a descriptor's handle is made
and its index clamped again in each block, an address is shifted and
masked again for each access. `bitcode::reuse` runs on the finished
module: an instruction that computes what an earlier one computed, where
every path to it has run that earlier one, is left out and its readers
take the earlier result.

It takes integer arithmetic and compares, integer selects, width and bit
casts, extractvalue, getelementptr, handle creation and annotation, the
integer `readnone` operations, `getDimensions`, and raw loads from the
host's own tables (page table, view addresses, view marks, view
strides). Float arithmetic, float compares, conversions, every other
load, samples, atomics and wave operations stay as written.

What goes is always a copy of an instruction that stays, so no operation
and no declaration loses its last use: shader flags and declarations
stay valid without being recomputed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The host rewrites table entries while the GPU runs (the heap's
write_stride, set_mark and note_address), so the notes no longer say it
does not. The pass needs no such promise: inside one invocation the
reads of one entry it merges give the first read's value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:56:14 +00:00
Author
Owner

@⁠Dathinel on GitHub · 2026-11-25 06:34 UTC · original

Native NVIDIA run as requested: Windows, RTX 3050 Laptop, driver 32.0.16.1062, pinned Rust MSVC, adapter overrides unset. I ran cargo test --frozen -p victory-shader --no-fail-fast -- --nocapture --test-threads=1 on both unmodified revisions.

Revision Passed Failed Ignored
Parent 940d32f 244 3 3
PR 91d75b8 249 3 3

All five new reuse tests passed. The three failures had identical diagnostics on both runs: by-element stride read, missing buffer view, and gather (the three in #1835). All 467 printed arithmetic-model comparison lines also matched between runs. Six compiler-dependent checks skipped internally; the wave-32 permute test skipped its WARP path.

I also checked that the pass actually rewrote a shader exercised by the suite. In a separate run, logging the return value of self.m.reuse(&tables) in intersections_on_nodes_in_title_memory_equal_the_reference reported 58 instructions removed on each of its two emissions; the reference comparison passed. No game or performance measurement. AI-assisted.

**@⁠Dathinel** on GitHub · 2026-11-25 06:34 UTC · [original](https://github.com/Marvisak/VIctory/pull/2150#issuecomment-7154936546) Native NVIDIA run as requested: Windows, RTX 3050 Laptop, driver 32.0.16.1062, pinned Rust MSVC, adapter overrides unset. I ran `cargo test --frozen -p victory-shader --no-fail-fast -- --nocapture --test-threads=1` on both unmodified revisions. | Revision | Passed | Failed | Ignored | |---|---:|---:|---:| | Parent `940d32f` | 244 | 3 | 3 | | PR `91d75b8` | 249 | 3 | 3 | All five new reuse tests passed. The three failures had identical diagnostics on both runs: by-element stride read, missing buffer view, and gather (the three in #1835). All 467 printed arithmetic-model comparison lines also matched between runs. Six compiler-dependent checks skipped internally; the wave-32 permute test skipped its WARP path. I also checked that the pass actually rewrote a shader exercised by the suite. In a separate run, logging the return value of `self.m.reuse(&tables)` in `intersections_on_nodes_in_title_memory_equal_the_reference` reported 58 instructions removed on each of its two emissions; the reference comparison passed. No game or performance measurement. AI-assisted.
Author
Owner

@⁠sinan-cmyk on GitHub · 2026-11-25 08:18 UTC · original

Offline measurement on a retail dump

Result: no count change against main.

I merged head 91d75b82 onto main 940d32f (clean merge) and ran victory translate --validate --list on shaders.rpf (1.0.2.1), with dxil.dll 1.8.2502.11. I compared the result with main program by program (25,889 programs). Validated: 23,918 on main, 23,918 with this PR.

No program changes its failure reason. The count shows that the change rejects nothing on this data. It does not show whether the output is right.

No shader names or data are included, per the asset policy. AI-assisted (Claude Code).

**@⁠sinan-cmyk** on GitHub · 2026-11-25 08:18 UTC · [original](https://github.com/Marvisak/VIctory/pull/2150#issuecomment-7156858717) ### Offline measurement on a retail dump **Result: no count change against `main`.** I merged head 91d75b82 onto `main` 940d32f (clean merge) and ran `victory translate --validate --list` on `shaders.rpf` (1.0.2.1), with dxil.dll 1.8.2502.11. I compared the result with `main` program by program (25,889 programs). Validated: 23,918 on `main`, 23,918 with this PR. No program changes its failure reason. The count shows that the change rejects nothing on this data. It does not show whether the output is right. No shader names or data are included, per the asset policy. AI-assisted (Claude Code).
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 11:25 UTC · original · edited 2026-11-25 22:26 UTC

Automated triage for the maintainers.

Merge candidate. Re-reviewed at dcdb50e, which now merges cleanly into main. Module::reuse (new crates/victory-shader/src/emit/bitcode/reuse.rs, called from Shader::finish) walks the dominator tree. It drops an instruction whose key (opcode and operands) matches one in a dominating block, and points readers at the earlier result, including phis and branch conditions.

I checked what it admits:

  • integer binaries, compares and selects, width and bit casts, extractvalue and getelementptr;
  • createHandleFromBinding/FromHeap, annotateHandle and getDimensions;
  • .i32 dx.ops declared ReadNone;
  • rawBufferLoad only through the host's own tables (page table, view addresses, view marks, view strides).

The lowering declares wave and lane ops NoUnwind or ReadOnly, not ReadNone, so a ballot or lane read in a narrower branch is not merged with one above it. Floats, other loads, samples, atomics and barriers are left alone. The pass removes only copies of an instruction that stays, so no declared operation loses its last use and the feature flags cannot go stale.

Evidence: on the title's archive, 10.5% fewer instructions on 13f91ca, and every program has the same outcome as on main. The suite passed on WARP, and on an RTX 3050 earlier.

On your reply: the corrected note in bitcode/reuse.rs and emit/mod.rs (reads of one entry inside an invocation take the first read's value, with no promise about the host) matches the code, and so does the updated figure. CI: check passing on this head.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 11:25 UTC · [original](https://github.com/Marvisak/VIctory/pull/2150#issuecomment-7161039528) · edited 2026-11-25 22:26 UTC <!-- victory-triage v1 head=dcdb50e25ac433086bd7d56c8cac95b56b8da7d6 verdict=merge-candidate at=2026-11-25T22:33:00Z --> Automated triage for the maintainers. **Merge candidate.** Re-reviewed at `dcdb50e`, which now merges cleanly into `main`. `Module::reuse` (new `crates/victory-shader/src/emit/bitcode/reuse.rs`, called from `Shader::finish`) walks the dominator tree. It drops an instruction whose key (opcode and operands) matches one in a dominating block, and points readers at the earlier result, including phis and branch conditions. I checked what it admits: - integer binaries, compares and selects, width and bit casts, `extractvalue` and `getelementptr`; - `createHandleFromBinding`/`FromHeap`, `annotateHandle` and `getDimensions`; - `.i32` `dx.op`s declared `ReadNone`; - `rawBufferLoad` only through the host's own tables (page table, view addresses, view marks, view strides). The lowering declares wave and lane ops `NoUnwind` or `ReadOnly`, not `ReadNone`, so a ballot or lane read in a narrower branch is not merged with one above it. Floats, other loads, samples, atomics and barriers are left alone. The pass removes only copies of an instruction that stays, so no declared operation loses its last use and the feature flags cannot go stale. Evidence: on the title's archive, 10.5% fewer instructions on `13f91ca`, and every program has the same outcome as on `main`. The suite passed on WARP, and on an RTX 3050 earlier. On your reply: the corrected note in `bitcode/reuse.rs` and `emit/mod.rs` (reads of one entry inside an invocation take the first read's value, with no promise about the host) matches the code, and so does the updated figure. CI: `check` passing on this head. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠r4tedx on GitHub · 2026-11-25 21:15 UTC · original

Thanks for checking the pass. Both points are done at dcdb50e.

The note. You are right that the host rewrites the tables while the GPU runs (write_stride, set_mark and note_address write the mapped tables in place; descriptor/host.rs:531). The notes in bitcode/reuse.rs and emit/mod.rs no longer say otherwise. They now say that inside one invocation, the reads of one entry that the pass merges give one value, the first read's. So the pass needs no promise about the host.

One correction to the example: buffer_guard and view_stride do not share a read. buffer_guard reads VIEW_STRIDES at the clamped index (select(index > HEAP_VIEWS - 1, HEAP_VIEWS - 1, index), lower.rs:5313-5320). view_stride reads it at the unclamped index * 4 (lower.rs:5030-5033). The addresses differ, so the pass keeps both loads. What it does merge is a repeated read of the same entry at the same address, for example buffer_guard for one descriptor in several blocks. So I left that example out of the note.

The figure. Recounted on current main (13f91ca, whose code is that of 67e8ae1, so it includes 850b66f and 286a00e). The run was offline on the title's shaders.rpf (local title data, CPU only), with translate --validate --list --count from #2115 (b0f0b2e) and dxil.dll 10.0.26100.0:

  • instructions in emitted programs: 164,909,025 on main, 147,551,134 with this PR (−17,357,891, −10.53 %)
  • programs validated: 24,846 on both. Compared program by program, none was lost or gained, 25,076 are smaller, 589 are the same and none is larger. Blocks are unchanged.
  • handles: createHandleFromHeap −108,011 and annotateHandle −205,819, with createHandleFromBinding −98,758. That is −0.41 M together, against −2.4 M before 850b66f. Most of the reduction is still bitcast (−10.9 M), then and (−1.9 M), icmp, add and select.

So −13.5 % was stale; it is now −10.5 %. The PR text is updated.

AI-assisted.

**@⁠r4tedx** on GitHub · 2026-11-25 21:15 UTC · [original](https://github.com/Marvisak/VIctory/pull/2150#issuecomment-7174837639) Thanks for checking the pass. Both points are done at `dcdb50e`. **The note.** You are right that the host rewrites the tables while the GPU runs (`write_stride`, `set_mark` and `note_address` write the mapped tables in place; descriptor/host.rs:531). The notes in `bitcode/reuse.rs` and `emit/mod.rs` no longer say otherwise. They now say that inside one invocation, the reads of one entry that the pass merges give one value, the first read's. So the pass needs no promise about the host. One correction to the example: `buffer_guard` and `view_stride` do not share a read. `buffer_guard` reads `VIEW_STRIDES` at the clamped index (`select(index > HEAP_VIEWS - 1, HEAP_VIEWS - 1, index)`, lower.rs:5313-5320). `view_stride` reads it at the unclamped `index * 4` (lower.rs:5030-5033). The addresses differ, so the pass keeps both loads. What it does merge is a repeated read of the same entry at the same address, for example `buffer_guard` for one descriptor in several blocks. So I left that example out of the note. **The figure.** Recounted on current `main` (`13f91ca`, whose code is that of `67e8ae1`, so it includes 850b66f and 286a00e). The run was offline on the title's `shaders.rpf` (local title data, CPU only), with `translate --validate --list --count` from #2115 (`b0f0b2e`) and dxil.dll 10.0.26100.0: - instructions in emitted programs: 164,909,025 on `main`, 147,551,134 with this PR (−17,357,891, −10.53 %) - programs validated: 24,846 on both. Compared program by program, none was lost or gained, 25,076 are smaller, 589 are the same and none is larger. Blocks are unchanged. - handles: `createHandleFromHeap` −108,011 and `annotateHandle` −205,819, with `createHandleFromBinding` −98,758. That is −0.41 M together, against −2.4 M before 850b66f. Most of the reduction is still `bitcast` (−10.9 M), then `and` (−1.9 M), `icmp`, `add` and `select`. So −13.5 % was stale; it is now −10.5 %. The PR text is updated. AI-assisted.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2150/head:github-bot/gh-2150'
git switch 'github-bot/gh-2150'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2150'
git switch 'github-bot/gh-2150'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2150'
git switch 'github-bot/gh-2150'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2150'
git switch 'main'
git merge --squash 'github-bot/gh-2150'
git switch 'main'
git merge --ff-only 'github-bot/gh-2150'
git switch 'main'
git merge 'github-bot/gh-2150'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
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.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory!2150
No description provided.