D3D12-SHADER-OPT-CHAINS-CANONICAL: a chain with its steps the other way round is in order (-8 % translate CPU, -0.34 % DXIL instructions) #2800

Open
bobcatchris wants to merge 3 commits from upstream-pr/2800 into main
bobcatchris commented 2026-11-30 23:15:55 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by bobcatchris on 2026-11-30T23:15:55Z.


What

Module::optimise (leonida-shader/src/emit/bitcode/opt.rs) runs merge, prune, guards and chains for up to four rounds and stops early when none of them changes anything. In a full-archive leonida translate on current main, 10,291 of 25,689 emitted programs (40 %) run all four rounds, and rounds 3 and 4 are 44 % of the time the optimiser takes. I traced those rounds (live instructions, dead instructions, blocks, and which pass said "changed") and they are a loop, not progress: from round 2 on merge and chains both report a change every round while the counts do not move. With the limit raised to 16, 10,236 programs still say "changed" in the last round.

The cause is in chains. It rewrites a conjunction of lane conditions into (((t1 & t2) & t3) & ...), terms in the order they were made, and leaves a chain that is in that form (canonical). canonical only accepted a step written and(lower, term). key() treats an integer and as commutative, so a chain written and(term, lower) was never canonical: chains built and(lower, term) as new instructions, the reuse pass of merge put the instruction that was there back, and the next round did the same. I found it by printing the plans of a small program per round: the same root and the same terms every round, with the prefix and there with its operands the other way round.

canonical now accepts a step with its two operands either way round. That is one match arm.

Claim: D3D12-SHADER-OPT-CHAINS-CANONICAL (coordination issue #2570, https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7294408822). No open pull request edits chains (checked the diffs of the ones that touch opt.rs: #2750, #2698, #2687, #2681, #2569).

The DXIL is not identical to main's, and why

I claimed an identical-DXIL bar in the claim; this is not that, so here is what changes. Full archive, 25,689 programs, hash of the DXIL of each (a scratch patch writing the hashes; not in this pull request):

  • 10,089 programs differ; 15,600 are identical.
  • All of it is in arith: -341,356 instructions (-0.84 % of arith, -0.34 % of all instructions). Every other kind (select, phi, calls, loads, stores, casts, extracts, handles) and the block count are equal, from the census (LEONIDA_SHADER_CENSUS) of both builds.
  • By size: 7,315 programs smaller (up to 7.7 %), 2,767 the same size with a different hash (operands the other way round), 7 larger by 4 bytes each. Total DXIL 979,120,356 -> 977,096,524 bytes (-0.21 %).
  • Why main has those extra instructions: its last round ends on a chains rewrite and no merge follows, so the rewrite's duplicates of existing ands are written out. I checked that: main with one merge added after the last round gives the same arith count (40,370,778) as this branch and the same DXIL in 25,548 programs (total bytes within 8 of this branch's).
  • Both builds are deterministic (two runs of each gave the same hashes).

Not rewriting a chain is always sound (it leaves the lowering's own form), so the new output is main's with duplicate ands absent and some operands in the other order; I did not run a GPU test on it.

leonida translate --validate (Windows SDK 10.0.26100 dxil.dll) on both builds: the same counts (14,220 of 14,247 vertex and pixel programs, 2,677 of 2,677 compute, 8,673 of 8,765 mesh) and the same table of reasons for the rest (compared line by line, counts included), so nothing new is refused.

Measured

Full-archive leonida translate, release build with mimalloc, 16 threads, Ryzen 7 7800X3D, main at 2878a3911 as the baseline (the same tree with the one arm taken out), four alternating runs of each:

wall user CPU
main 37.1 / 36.3 / 36.5 / 36.7 s 477.1 / 476.5 / 477.3 / 478.0 s
this branch 35.6 / 33.0 / 33.3 / 33.2 s 436.4 / 436.1 / 439.2 / 435.7 s

Means: wall 36.65 -> 33.78 s (-7.8 %), user CPU 477.2 -> 436.9 s (-8.5 %).

Tests

  • New a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is: the term first at the root, below it, and both; chains() finds nothing to rewrite, still nothing after optimise(CHAINS | REUSE | DEAD) has merged them, and a second run leaves the instructions as they were. Negative control: taking the new arm out makes it fail on the first assertion.
  • New a_chain_with_its_terms_out_of_order_is_still_rewritten: the control for the other direction (it passes with and without the arm).
  • cargo test -p leonida-shader (debug): 402 passed, 0 failed, 5 ignored.
  • rustfmt --edition 2024 --check opt.rs: no diff in the lines this changes (the file's other diffs were there before). cargo clippy -p leonida-shader --no-deps --all-targets -- -D warnings reports errors in other files of the crate and two in opt.rs (lines 1318 and 1778, from the commit that added chains), none in the lines this changes.
  • check_no_game_data.py on the changed file: clean.

AI-assisted: Gemini 4 Neon (including an independent read-only review pass on follow-up commit b6ebcedd4)

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5575530388 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800). Originally posted by [bobcatchris](https://github.com/bobcatchris) on 2026-11-30T23:15:55Z. --- ## What `Module::optimise` (`leonida-shader/src/emit/bitcode/opt.rs`) runs `merge`, `prune`, `guards` and `chains` for up to four rounds and stops early when none of them changes anything. In a full-archive `leonida translate` on current `main`, 10,291 of 25,689 emitted programs (40 %) run all four rounds, and rounds 3 and 4 are 44 % of the time the optimiser takes. I traced those rounds (live instructions, dead instructions, blocks, and which pass said "changed") and they are a loop, not progress: from round 2 on `merge` and `chains` both report a change every round while the counts do not move. With the limit raised to 16, 10,236 programs still say "changed" in the last round. The cause is in `chains`. It rewrites a conjunction of lane conditions into `(((t1 & t2) & t3) & ...)`, terms in the order they were made, and leaves a chain that is in that form (`canonical`). `canonical` only accepted a step written `and(lower, term)`. `key()` treats an integer `and` as commutative, so a chain written `and(term, lower)` was never canonical: `chains` built `and(lower, term)` as new instructions, the reuse pass of `merge` put the instruction that was there back, and the next round did the same. I found it by printing the plans of a small program per round: the same root and the same terms every round, with the prefix `and` there with its operands the other way round. `canonical` now accepts a step with its two operands either way round. That is one match arm. Claim: D3D12-SHADER-OPT-CHAINS-CANONICAL (coordination issue #2570, https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7294408822). No open pull request edits `chains` (checked the diffs of the ones that touch `opt.rs`: #2750, #2698, #2687, #2681, #2569). ## The DXIL is not identical to `main`'s, and why I claimed an identical-DXIL bar in the claim; this is not that, so here is what changes. Full archive, 25,689 programs, hash of the DXIL of each (a scratch patch writing the hashes; not in this pull request): - 10,089 programs differ; 15,600 are identical. - All of it is in `arith`: -341,356 instructions (-0.84 % of arith, -0.34 % of all instructions). Every other kind (select, phi, calls, loads, stores, casts, extracts, handles) and the block count are equal, from the census (`LEONIDA_SHADER_CENSUS`) of both builds. - By size: 7,315 programs smaller (up to 7.7 %), 2,767 the same size with a different hash (operands the other way round), 7 larger by 4 bytes each. Total DXIL 979,120,356 -> 977,096,524 bytes (-0.21 %). - Why `main` has those extra instructions: its last round ends on a `chains` rewrite and no `merge` follows, so the rewrite's duplicates of existing `and`s are written out. I checked that: `main` with one `merge` added after the last round gives the same arith count (40,370,778) as this branch and the same DXIL in 25,548 programs (total bytes within 8 of this branch's). - Both builds are deterministic (two runs of each gave the same hashes). Not rewriting a chain is always sound (it leaves the lowering's own form), so the new output is `main`'s with duplicate `and`s absent and some operands in the other order; I did not run a GPU test on it. `leonida translate --validate` (Windows SDK 10.0.26100 `dxil.dll`) on both builds: the same counts (14,220 of 14,247 vertex and pixel programs, 2,677 of 2,677 compute, 8,673 of 8,765 mesh) and the same table of reasons for the rest (compared line by line, counts included), so nothing new is refused. ## Measured Full-archive `leonida translate`, release build with `mimalloc`, 16 threads, Ryzen 7 7800X3D, `main` at 2878a3911 as the baseline (the same tree with the one arm taken out), four alternating runs of each: | | wall | user CPU | |---|---|---| | main | 37.1 / 36.3 / 36.5 / 36.7 s | 477.1 / 476.5 / 477.3 / 478.0 s | | this branch | 35.6 / 33.0 / 33.3 / 33.2 s | 436.4 / 436.1 / 439.2 / 435.7 s | Means: wall 36.65 -> 33.78 s (-7.8 %), user CPU 477.2 -> 436.9 s (-8.5 %). ## Tests - New `a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is`: the term first at the root, below it, and both; `chains()` finds nothing to rewrite, still nothing after `optimise(CHAINS | REUSE | DEAD)` has merged them, and a second run leaves the instructions as they were. Negative control: taking the new arm out makes it fail on the first assertion. - New `a_chain_with_its_terms_out_of_order_is_still_rewritten`: the control for the other direction (it passes with and without the arm). - `cargo test -p leonida-shader` (debug): 402 passed, 0 failed, 5 ignored. - `rustfmt --edition 2024 --check opt.rs`: no diff in the lines this changes (the file's other diffs were there before). `cargo clippy -p leonida-shader --no-deps --all-targets -- -D warnings` reports errors in other files of the crate and two in `opt.rs` (lines 1318 and 1778, from the commit that added `chains`), none in the lines this changes. - `check_no_game_data.py` on the changed file: clean. AI-assisted: Gemini 4 Neon (including an independent read-only review pass on follow-up commit `b6ebcedd4`)
OreoFR commented 2026-11-30 23:19:22 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-30T23:19:22Z.


Verified by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), head 9e39fbb58, main d4fabd3fe. CPU only, no game files.

MEASURED

  • cargo test --release -p leonida-shader: main 242 passed, 0 failed, 2 ignored; main + this PR (merge-tree) 244 passed, 0 failed, 2 ignored. The two extra tests are the new ones.
  • Red, on main + this PR with only the added arm removed (Op::Bin(Bin::And, x, y) if x == want => cur = y,), tests matching a_chain_with: 1 failed, 1 passed.
    • a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is fails, at opt.rs:1853 (assert!(!m.chains(), "no chain here is out of order")).
    • a_chain_with_its_terms_out_of_order_is_still_rewritten passes, as a control should.
  • So the new test pins the fix, and the control shows that out-of-order chains are still rewritten.

READ IN CODE

  • The fix is the one arm in canonical. It walks the chain from the root using whichever operand of and is not the expected term. That matches key() treating an integer and as commutative, so chains and the reuse pass now agree on what "in order" means.
  • The new test covers the three shapes (swapped at the root and below, at the root only, below only). It also checks that a second optimise(CHAINS | REUSE | DEAD) leaves the same instructions, which is the fixed point that was missing.

ASSUMED

  • The archive figures (DXIL changes in 10,089 of 25,689 programs, all in arith, -0.34 % instructions, -8 % translation CPU) are from your run and are not reproduced here: they need the game's archive. The DXIL is not byte-identical to main, so an in-game check on the translated output is what would cover the behavior change.

AI-assisted: Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7294979791 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7294979791). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-11-30T23:19:22Z. --- Verified by OreoFR on macOS 27.2.1, Apple M5, Rust (rustup), head `9e39fbb58`, main `d4fabd3fe`. CPU only, no game files. **MEASURED** - `cargo test --release -p leonida-shader`: main 242 passed, 0 failed, 2 ignored; main + this PR (merge-tree) 244 passed, 0 failed, 2 ignored. The two extra tests are the new ones. - Red, on main + this PR with only the added arm removed (`Op::Bin(Bin::And, x, y) if x == want => cur = y,`), tests matching `a_chain_with`: 1 failed, 1 passed. - `a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is` fails, at `opt.rs:1853` (`assert!(!m.chains(), "no chain here is out of order")`). - `a_chain_with_its_terms_out_of_order_is_still_rewritten` passes, as a control should. - So the new test pins the fix, and the control shows that out-of-order chains are still rewritten. **READ IN CODE** - The fix is the one arm in `canonical`. It walks the chain from the root using whichever operand of `and` is not the expected term. That matches `key()` treating an integer `and` as commutative, so `chains` and the reuse pass now agree on what "in order" means. - The new test covers the three shapes (swapped at the root and below, at the root only, below only). It also checks that a second `optimise(CHAINS | REUSE | DEAD)` leaves the same instructions, which is the fixed point that was missing. **ASSUMED** - The archive figures (DXIL changes in 10,089 of 25,689 programs, all in `arith`, -0.34 % instructions, -8 % translation CPU) are from your run and are not reproduced here: they need the game's archive. The DXIL is not byte-identical to main, so an in-game check on the translated output is what would cover the behavior change. AI-assisted: Claude Code
KelboLive commented 2026-12-01 05:19:52 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by KelboLive on 2026-12-01T05:19:52Z.

Review: COMMENTED


Verified the Rust arm (this is d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs, not the Python translator — so the semantic suite cannot discriminate it): cargo test --locked -p leonida-shader --lib is 402 passed / 0 failed / 5 ignored, and removing the new match arm makes a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is fail at opt.rs:1853, while the out-of-order control test still passes. So the new arm is pinned in both directions.

The change is semantically safe as far as I can tell: only i1 and nodes (plus pure xor) are replaced, leaves — including effectful loads/calls — keep their instructions and positions, and a store/atomic/barrier is not an i1 and step, so nothing with side effects is reordered. The term order is irrelevant to AND, and the terms are sorted by definition site and deduped, with a term-with-its-complement refused (:1242-1261); the only hash-ordered collection is the pre-existing by_block map, which does not decide which chains collapse.

One residual, performance only but worth closing: born[p] = (rank, 0) for every phi in a block (:1202) and a stable sort_by_key (:1249) mean same-block phis tie, so their order follows the DFS — which reverses when the chain is rebuilt. With three i1 phis from one block in a chain, canonical rejects the rebuilt chain and chains() rewrites again next call (temporary test: first call true, second call true; with three distinct comparisons the second is false). A total tie-break — (born, base) or a per-phi birth index — finishes the loop fix this PR is after.

(The Python semantic suite is irrelevant here: 553 files / 6,720 tests pass, but it never loads leonida-shader. The archive hash change is not reproducible here either — no work folder with disassembly on this machine — and the PR does not claim identical output anyway.)

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6125578029 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#pullrequestreview-6125578029). Originally posted by [KelboLive](https://github.com/KelboLive) on 2026-12-01T05:19:52Z. **Review:** COMMENTED --- Verified the Rust arm (this is `d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs`, not the Python translator — so the semantic suite cannot discriminate it): `cargo test --locked -p leonida-shader --lib` is **402 passed / 0 failed / 5 ignored**, and removing the new match arm makes `a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is` fail at `opt.rs:1853`, while the out-of-order control test still passes. So the new arm is pinned in both directions. The change is semantically safe as far as I can tell: only i1 `and` nodes (plus pure `xor`) are replaced, leaves — including effectful loads/calls — keep their instructions and positions, and a store/atomic/barrier is not an i1 `and` step, so nothing with side effects is reordered. The term order is irrelevant to AND, and the terms are sorted by definition site and deduped, with a term-with-its-complement refused (`:1242-1261`); the only hash-ordered collection is the pre-existing `by_block` map, which does not decide which chains collapse. One residual, performance only but worth closing: `born[p] = (rank, 0)` for every phi in a block (`:1202`) and a stable `sort_by_key` (`:1249`) mean same-block phis tie, so their order follows the DFS — which reverses when the chain is rebuilt. With three i1 phis from one block in a chain, `canonical` rejects the rebuilt chain and `chains()` rewrites again next call (temporary test: first call true, second call true; with three distinct comparisons the second is false). A total tie-break — `(born, base)` or a per-phi birth index — finishes the loop fix this PR is after. (The Python semantic suite is irrelevant here: 553 files / 6,720 tests pass, but it never loads `leonida-shader`. The archive hash change is not reproducible here either — no work folder with disassembly on this machine — and the PR does not claim identical output anyway.)
imShangLi commented 2026-12-01 15:43:36 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by imShangLi on 2026-12-01T15:43:36Z.


VERIFY-2800 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files

Verdict: PASS. The fix is one line and the pull request brings its own control: the out-of-order chain is still rewritten.

Head 9e39fbb5, base the current main 88a9f133, merge base 2878a391, 1 commit, 1 file, +86/−1: d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs.

1. The change

chains() asks whether the chain it is looking at is already in canonical order, and the answer walked the chain's steps like this:

match m.insts[i as usize].op {
    Op::Bin(Bin::And, x, y) if y == want => cur = x,
    _ => return false,
}

That only accepts a step written as x & want — the term second. An integer and is the same value whichever way round its operands are, so want & x is the same chain; the old answer said "not canonical" for it. The pull request adds the other way:

    Op::Bin(Bin::And, x, y) if y == want => cur = x,
    Op::Bin(Bin::And, x, y) if x == want => cur = y,

The comment in the pull request describes the consequence: the reuse pass would put the instruction that is there back in place of the rewrite, and the next round would plan the same rewrite again, "up to the round limit".

2. Red and green, and the discrimination

cargo test -p leonida-shader (Linux, pinned toolchain) on the pull request's branch:

test result: ok. 241 passed; 0 failed; 2 ignored

With only that one line put back (the pull request's tests kept):

test emit::bitcode::opt::tests::a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is ... FAILED
  panicked at crates/leonida-shader/src/emit/bitcode/opt.rs:1853:9
test result: FAILED. 240 passed; 1 failed; 2 ignored

So the new test looks at the code it is about.

3. The control is in the pull request

a_chain_with_its_terms_out_of_order_is_still_rewritten is the negative control, and it is the part I like most about this pull request:

let low = m.bin(b, Bin::And, c2, a);      // c2 & a  — the terms are in the wrong order
let chain = m.bin(b, Bin::And, low, c1);
assert!(m.chains(), "`c2 & a` then `& c1` is not `(a & c1) & c2`");
assert!(!m.chains(), "and the rewrite is in order");

The first assertion is that the pass finds work, the second that a second call finds none — so the fix cannot be "the pass stopped rewriting anything". With the fix reverted, the other test fails and this one still passes, which is what a control should do.

4. The claim about the reuse pass

The pull request says the chain "would be rebuilt each round for the reuse pass to put back, and say that it had changed something every time, up to the limit of rounds". The new test checks the end of that: m.optimise(CHAINS | REUSE | DEAD) merges the three chains, and a second optimise leaves the instructions identical (assert_eq!(ops(&m), merged)).

I did not measure the round count or the CPU saving on a real shader corpus — the pull request's title quotes "-8 % translate CPU, -0.34 % DXIL instructions", and that needs the game's shaders, which are not in the repository and which I do not have.

5. It does not collide with #2872

Both pull requests change chains() in opt.rs (#2872 makes the block grouping deterministic, this one makes the canonical test accept a commutative step). I merged both onto today's main and ran the crate:

test result: ok. 249 passed; 0 failed; 2 ignored

No conflict, and neither pull request's test breaks the other's.

6. What I did not check

  • The translation of a real shader. Everything above is the crate's unit tests over hand-built modules. I did not translate a game shader, so I did not measure the CPU or the instruction count the pull request's title quotes.
  • The other crates in the workspace — leonida-gpu, leonida-hle and leonida-loader do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows #2577"), so I ran leonida-shader on its own.
  • Whether Bin::And is always commutative in this IR. The fix assumes an integer and; the pass works on i1/i32 values, and and on those is commutative. I did not look for a use of Bin::And on a non-integer type, where the reasoning would not hold.
  • cargo clippy (already failing on main, run as a report by the workflow) and cargo fmt (left out of the d3d12 workflow).

AI-assisted: MiniMax M3.1 Flash.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7316402906 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7316402906). Originally posted by [imShangLi](https://github.com/imShangLi) on 2026-12-01T15:43:36Z. --- ## VERIFY-2800 — Linux, Rust 1.98.1 (the pinned toolchain), no GPU device, no game files **Verdict: PASS.** The fix is one line and the pull request brings its own control: the out-of-order chain is still rewritten. Head `9e39fbb5`, base the current `main` `88a9f133`, merge base `2878a391`, 1 commit, 1 file, +86/−1: `d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs`. ### 1. The change `chains()` asks whether the chain it is looking at is already in canonical order, and the answer walked the chain's steps like this: ```rust match m.insts[i as usize].op { Op::Bin(Bin::And, x, y) if y == want => cur = x, _ => return false, } ``` That only accepts a step written as `x & want` — the term second. An integer `and` is the same value whichever way round its operands are, so `want & x` is the same chain; the old answer said "not canonical" for it. The pull request adds the other way: ```rust Op::Bin(Bin::And, x, y) if y == want => cur = x, Op::Bin(Bin::And, x, y) if x == want => cur = y, ``` The comment in the pull request describes the consequence: the reuse pass would put the instruction that is there back in place of the rewrite, and the next round would plan the same rewrite again, "up to the round limit". ### 2. Red and green, and the discrimination `cargo test -p leonida-shader` (Linux, pinned toolchain) on the pull request's branch: ``` test result: ok. 241 passed; 0 failed; 2 ignored ``` With **only that one line** put back (the pull request's tests kept): ``` test emit::bitcode::opt::tests::a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is ... FAILED panicked at crates/leonida-shader/src/emit/bitcode/opt.rs:1853:9 test result: FAILED. 240 passed; 1 failed; 2 ignored ``` So the new test looks at the code it is about. ### 3. The control is in the pull request `a_chain_with_its_terms_out_of_order_is_still_rewritten` is the negative control, and it is the part I like most about this pull request: ```rust let low = m.bin(b, Bin::And, c2, a); // c2 & a — the terms are in the wrong order let chain = m.bin(b, Bin::And, low, c1); assert!(m.chains(), "`c2 & a` then `& c1` is not `(a & c1) & c2`"); assert!(!m.chains(), "and the rewrite is in order"); ``` The first assertion is that the pass finds work, the second that a second call finds none — so the fix cannot be "the pass stopped rewriting anything". With the fix reverted, the other test fails and this one still passes, which is what a control should do. ### 4. The claim about the reuse pass The pull request says the chain "would be rebuilt each round for the reuse pass to put back, and say that it had changed something every time, up to the limit of rounds". The new test checks the end of that: `m.optimise(CHAINS | REUSE | DEAD)` merges the three chains, and a **second** `optimise` leaves the instructions identical (`assert_eq!(ops(&m), merged)`). I did not measure the round count or the CPU saving on a real shader corpus — the pull request's title quotes "-8 % translate CPU, -0.34 % DXIL instructions", and that needs the game's shaders, which are not in the repository and which I do not have. ### 5. It does not collide with #2872 Both pull requests change `chains()` in `opt.rs` (#2872 makes the block grouping deterministic, this one makes the canonical test accept a commutative step). I merged both onto today's `main` and ran the crate: ``` test result: ok. 249 passed; 0 failed; 2 ignored ``` No conflict, and neither pull request's test breaks the other's. ### 6. What I did not check - **The translation of a real shader.** Everything above is the crate's unit tests over hand-built modules. I did not translate a game shader, so I did not measure the CPU or the instruction count the pull request's title quotes. - **The other crates in the workspace** — `leonida-gpu`, `leonida-hle` and `leonida-loader` do not build on Linux for reasons that predate this pull request (upstream: "The crates are Windows-only today … Linux follows #2577"), so I ran `leonida-shader` on its own. - **Whether `Bin::And` is always commutative in this IR.** The fix assumes an integer `and`; the pass works on `i1`/`i32` values, and `and` on those is commutative. I did not look for a use of `Bin::And` on a non-integer type, where the reasoning would not hold. - `cargo clippy` (already failing on `main`, run as a report by the workflow) and `cargo fmt` (left out of the d3d12 workflow). AI-assisted: MiniMax M3.1 Flash.
bobcatchris commented 2026-12-01 18:25:59 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by bobcatchris on 2026-12-01T18:25:59Z.


@KelboLive Addressed the same-block phi tie-break residual in b6ebcedd4 (after merging main, no rebase/force-push):

  • Assigned distinct birth positions (rank, k) for each phi (0..phis.len()) and (rank, phis.len() + k) for body instructions in chains(), giving every instruction in reachable blocks a strict total birth order.
  • Added a_chain_of_three_phis_in_the_same_block_settles_in_one_pass pinning that a 3-phi chain in one block rewrites once and settles (chains() returns false on the second call).
  • Verified locally on Windows (Rust 1.98.1): cargo test --locked -p leonida-shader --lib bitcode::opt (21 passed, 0 failed) and python -I scripts/check_no_game_data.py (clean).

AI-assisted: Gemini 4 Neon (including an independent read-only reviewer pass).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7320936963 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7320936963). Originally posted by [bobcatchris](https://github.com/bobcatchris) on 2026-12-01T18:25:59Z. --- @KelboLive Addressed the same-block phi tie-break residual in `b6ebcedd4` (after merging `main`, no rebase/force-push): - Assigned distinct birth positions `(rank, k)` for each phi (`0..phis.len()`) and `(rank, phis.len() + k)` for body instructions in `chains()`, giving every instruction in reachable blocks a strict total birth order. - Added `a_chain_of_three_phis_in_the_same_block_settles_in_one_pass` pinning that a 3-phi chain in one block rewrites once and settles (`chains()` returns `false` on the second call). - Verified locally on Windows (Rust 1.98.1): `cargo test --locked -p leonida-shader --lib bitcode::opt` (21 passed, 0 failed) and `python -I scripts/check_no_game_data.py` (clean). AI-assisted: Gemini 4 Neon (including an independent read-only reviewer pass).
MoonEyes commented 2026-12-02 12:25:31 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T12:25:31Z.


This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists).

Could you, or anyone with a working setup, post a run report on the current head merged onto current main:

  • the head SHA and the main SHA it was merged onto;
  • GPU, driver and OS;
  • at least 300 s in the world after loading;
  • device lost / crashes (count), and rendered fps (median) if you have them;
  • the same run on main alone for comparison, if you can.

Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7345318097 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7345318097). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T12:25:31Z. --- This pull request touches the render path, so it needs an in-game run before it can be merged: unit tests and CI do not catch rendering regressions (a device loss after an earlier merge is why this gate exists). Could you, or anyone with a working setup, post a run report on the **current head** merged onto current `main`: - the head SHA and the `main` SHA it was merged onto; - GPU, driver and OS; - at least 300 s in the world after loading; - device lost / crashes (count), and rendered fps (median) if you have them; - the same run on `main` alone for comparison, if you can. Please do not attach logs or screenshots that show game content. If a run on this exact head is already posted, a link to it in a reply is enough. AI-assisted (Claude Code).
Kal0s-design commented 2026-12-02 17:54:01 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by Kal0s-design on 2026-12-02T17:54:01Z.


Ran natively on Windows 11, head b6ebced merged into current main (45dc41f, clean merge). Rust 1.98.1, --locked. Some runs were done on main 5b1fff8, where leonida-shader is byte-identical to 45dc41f.

The other checks in this thread were on 9e39fbb. This one is on the current head, which adds the phi tie-break. It also covers the overlap with #3156.

Overlap with #3156 (measured)

#3156 adds the same canonical() arm as this PR, if x == want => cur = y, character for character. Beyond that the two PRs share nothing:

  • This PR gives same-block phis distinct birth positions (b6ebced).
  • #3156 runs one merge() after the round loop when chains() fired in the last round.

main + #2800 + #3156 merges cleanly in either order. Both orders give the same tree.

There are five new tests in total (three from this PR, two from #3156). I ran them against the optimiser code of each variant, from the merged file with the other PR's code hunks reverted:

test main #2800 code #3156 code both
a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is FAIL ok ok ok
a_chain_with_its_terms_out_of_order_is_still_rewritten (control) ok ok ok ok
a_chain_of_three_phis_in_the_same_block_settles_in_one_pass FAIL (second chains() returns true) ok FAIL ok
chains_accepts_commuted_and_operands (#3156) FAIL ok ok ok
optimise_merges_chains_emitted_on_final_round (#3156) FAIL FAIL (b4: 3 and, want 1) ok ok
  • The phi test goes red on main and green with b6ebced. It also fails on #3156's code, so #3156 does not cover it.
  • This PR does not cover #3156's final-round case. The PR body measured "main with one merge added after the last round"; that one merge is exactly #3156's second half.

The tie-break, narrower case (measured)

Two same-block phis are enough to loop on main when a dominating term comes first. br is a compare in the entry block; p0/p1 are i1 phis of the join; chains() was called 4 times:

main #3156 code #2800 code
(br & p0) & p1 true ×4 true ×4 false ×4
(p0 & p1) & t (t made in the join) true ×4 false ×4 false ×4

The commuted arm on its own absorbs the tie only when the two phis are the lowest pair. b6ebced fixes both shapes.

Differential fuzz of chains() (throwaway test, not proposed for the PR)

Programs come from two generators:

  • 20,000 synthetic programs:
    • 3–7 compare leaves from input/buffer loads.
    • Nested and (operands in either order), or, xor, xor true, select(c, t, false), select(c, false, f), i1 add/mul, and zext → add/mul → compare.
    • Repeated terms, true/false constants, and commuted copies of existing ands.
    • 0–2 diamonds with 1–4 i1 phis.
  • The crate's random_program, seeds 1–10,000.

Each program ran in the crate's interpreter (run) on 12 input vectors, before and after optimise() with 6 pass sets: CHAINS, +REUSE, +DEAD, +FOLD, GUARDS|CHAINS|REUSE|DEAD, ALL. Each was also optimised a second time.

To check that the harness can catch a miscompile, I ran it on a build where chains() drops the last term of a 4+ term chain. That build gave 70,100 mismatches.

Synthetic generator, 20,000 programs:

main #2800 #3156 both
store/return traces differ from the unoptimised program 0 0 0 0
chains() + merge(REUSE) not settled after 12 alternations 10,726 0 748 0
chains() still fires right after optimise(CHAINS) 1,018 0 751 0
optimise(CHAINS|REUSE) twice ≠ once 10,711 0 748 0
optimise(ALL) twice ≠ once 5,455 1 591 1
live instructions after ALL (ands) 1,695,006 (343,670) 1,680,781 (329,317) 1,680,803 (329,344) 1,680,781 (329,317)
optimise(ALL) time, 3 passes over the set 10.8 s 6.7 s 6.0 s 6.7 s

random_program, 10,000 seeds:

main #2800 #3156 both
traces differ 0 0 0 0
not settled after 12 alternations 363 0 0 0
optimise(ALL) twice ≠ once 9 2 2 2
live instructions after ALL 800,498 800,491 800,491 800,491
  • This PR alone gives zero unsettled programs on both generators. Adding #3156 on top changed no instruction count in any of the 30,000 programs. Only #3156's hand-built three-round fixture needs its trailing merge.
  • The 1–2 programs where optimise(ALL) twice ≠ once behave the same with CHAINS off (ALL & !CHAINS, GUARDS|REUSE|DEAD) and on main. They do not come from this PR.
  • Timing is a rough figure: release build, run alongside a GPU test run.
  • On the synthetic generator, ALL output is larger with CHAINS than without it in every variant: 1,652,367 live and 266,546 ands without it. It is less so with this PR than on main. Shared sub-ands get rebuilt per root. This is a property of the pass on these shapes; the archive figures in the PR body point the other way for real shaders.

Suites (measured)

tree cargo test -p leonida-shader, NVIDIA card WARP
main + #2800 partial run, stopped: 239 passed, 0 failed when stopped not run
main + #2800 + #3156 433 passed, 0 failed, 6 ignored 425 passed, 8 failed
main — 420 passed, 8 failed (the same 8)

The 8 WARP failures are the same on main. They are pipeline creation failing with "The parameter is incorrect", in pack_tests, valu_tests and wave64_tests. They are not related to this PR.

cargo clippy -p leonida-shader --all-targets: the same 6 warnings as main, none new.

Not checked: game shaders or archive output, the in-game run requested above, debug-layer runs, rustfmt, other crates. WARP was not run for this PR on its own. The full suite on main + this PR alone was stopped part way. The opt tests above were run on this PR's code, and the full suite passed on the tree with both PRs merged.

Suggestion: the two PRs are complementary. Merging both, or taking #3156's trailing merge into this one, passes all five tests and gives zero unsettled programs in the fuzz.

GPUs tested: one NVIDIA desktop card + WARP

AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7353753490 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7353753490). Originally posted by [Kal0s-design](https://github.com/Kal0s-design) on 2026-12-02T17:54:01Z. --- Ran natively on Windows 11, head `b6ebced` merged into current `main` (`45dc41f`, clean merge). Rust 1.98.1, `--locked`. Some runs were done on `main` `5b1fff8`, where `leonida-shader` is byte-identical to `45dc41f`. The other checks in this thread were on `9e39fbb`. This one is on the current head, which adds the phi tie-break. It also covers the overlap with #3156. **Overlap with #3156 (measured)** #3156 adds the same `canonical()` arm as this PR, `if x == want => cur = y`, character for character. Beyond that the two PRs share nothing: - This PR gives same-block phis distinct birth positions (`b6ebced`). - #3156 runs one `merge()` after the round loop when `chains()` fired in the last round. `main` + #2800 + #3156 merges cleanly in either order. Both orders give the same tree. There are five new tests in total (three from this PR, two from #3156). I ran them against the optimiser code of each variant, from the merged file with the other PR's code hunks reverted: | test | main | #2800 code | #3156 code | both | |---|---|---|---|---| | `a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is` | FAIL | ok | ok | ok | | `a_chain_with_its_terms_out_of_order_is_still_rewritten` (control) | ok | ok | ok | ok | | `a_chain_of_three_phis_in_the_same_block_settles_in_one_pass` | FAIL (second `chains()` returns true) | ok | **FAIL** | ok | | `chains_accepts_commuted_and_operands` (#3156) | FAIL | ok | ok | ok | | `optimise_merges_chains_emitted_on_final_round` (#3156) | FAIL | **FAIL** (b4: 3 `and`, want 1) | ok | ok | - The phi test goes red on `main` and green with `b6ebced`. It also fails on #3156's code, so #3156 does not cover it. - This PR does not cover #3156's final-round case. The PR body measured "`main` with one `merge` added after the last round"; that one merge is exactly #3156's second half. **The tie-break, narrower case (measured)** Two same-block phis are enough to loop on `main` when a dominating term comes first. `br` is a compare in the entry block; `p0`/`p1` are `i1` phis of the join; `chains()` was called 4 times: | | main | #3156 code | #2800 code | |---|---|---|---| | `(br & p0) & p1` | true ×4 | true ×4 | false ×4 | | `(p0 & p1) & t` (`t` made in the join) | true ×4 | false ×4 | false ×4 | The commuted arm on its own absorbs the tie only when the two phis are the lowest pair. `b6ebced` fixes both shapes. **Differential fuzz of `chains()` (throwaway test, not proposed for the PR)** Programs come from two generators: - 20,000 synthetic programs: - 3–7 compare leaves from input/buffer loads. - Nested `and` (operands in either order), `or`, `xor`, `xor true`, `select(c, t, false)`, `select(c, false, f)`, `i1` `add`/`mul`, and `zext` → `add`/`mul` → compare. - Repeated terms, `true`/`false` constants, and commuted copies of existing `and`s. - 0–2 diamonds with 1–4 `i1` phis. - The crate's `random_program`, seeds 1–10,000. Each program ran in the crate's interpreter (`run`) on 12 input vectors, before and after `optimise()` with 6 pass sets: `CHAINS`, `+REUSE`, `+DEAD`, `+FOLD`, `GUARDS|CHAINS|REUSE|DEAD`, `ALL`. Each was also optimised a second time. To check that the harness can catch a miscompile, I ran it on a build where `chains()` drops the last term of a 4+ term chain. That build gave 70,100 mismatches. Synthetic generator, 20,000 programs: | | main | #2800 | #3156 | both | |---|---|---|---|---| | store/return traces differ from the unoptimised program | 0 | 0 | 0 | 0 | | `chains()` + `merge(REUSE)` not settled after 12 alternations | 10,726 | 0 | 748 | 0 | | `chains()` still fires right after `optimise(CHAINS)` | 1,018 | 0 | 751 | 0 | | `optimise(CHAINS\|REUSE)` twice ≠ once | 10,711 | 0 | 748 | 0 | | `optimise(ALL)` twice ≠ once | 5,455 | 1 | 591 | 1 | | live instructions after `ALL` (`and`s) | 1,695,006 (343,670) | 1,680,781 (329,317) | 1,680,803 (329,344) | 1,680,781 (329,317) | | `optimise(ALL)` time, 3 passes over the set | 10.8 s | 6.7 s | 6.0 s | 6.7 s | `random_program`, 10,000 seeds: | | main | #2800 | #3156 | both | |---|---|---|---|---| | traces differ | 0 | 0 | 0 | 0 | | not settled after 12 alternations | 363 | 0 | 0 | 0 | | `optimise(ALL)` twice ≠ once | 9 | 2 | 2 | 2 | | live instructions after `ALL` | 800,498 | 800,491 | 800,491 | 800,491 | - This PR alone gives zero unsettled programs on both generators. Adding #3156 on top changed no instruction count in any of the 30,000 programs. Only #3156's hand-built three-round fixture needs its trailing merge. - The 1–2 programs where `optimise(ALL)` twice ≠ once behave the same with `CHAINS` off (`ALL & !CHAINS`, `GUARDS|REUSE|DEAD`) and on `main`. They do not come from this PR. - Timing is a rough figure: release build, run alongside a GPU test run. - On the synthetic generator, `ALL` output is larger with `CHAINS` than without it in every variant: 1,652,367 live and 266,546 `and`s without it. It is less so with this PR than on `main`. Shared sub-`and`s get rebuilt per root. This is a property of the pass on these shapes; the archive figures in the PR body point the other way for real shaders. **Suites (measured)** | tree | `cargo test -p leonida-shader`, NVIDIA card | WARP | |---|---|---| | main + #2800 | partial run, stopped: 239 passed, 0 failed when stopped | not run | | main + #2800 + #3156 | 433 passed, 0 failed, 6 ignored | 425 passed, 8 failed | | main | — | 420 passed, 8 failed (the same 8) | The 8 WARP failures are the same on `main`. They are pipeline creation failing with "The parameter is incorrect", in `pack_tests`, `valu_tests` and `wave64_tests`. They are not related to this PR. `cargo clippy -p leonida-shader --all-targets`: the same 6 warnings as `main`, none new. Not checked: game shaders or archive output, the in-game run requested above, debug-layer runs, `rustfmt`, other crates. WARP was not run for this PR on its own. The full suite on `main` + this PR alone was stopped part way. The `opt` tests above were run on this PR's code, and the full suite passed on the tree with both PRs merged. Suggestion: the two PRs are complementary. Merging both, or taking #3156's trailing merge into this one, passes all five tests and gives zero unsettled programs in the fuzz. GPUs tested: one NVIDIA desktop card + WARP AI-assisted: yes (Claude Code).
MoonEyes commented 2026-12-02 18:21:39 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T18:21:39Z.


RUN (in game, batch of seventeen render-path pull requests), each head merged with git merge --no-ff onto main 3c106eb2f, in one build: #3111 15b579756, #2948 5284c6eae, #2698 1f188c4f7, #2946 44bf554fe, #3001 d924cbb65, #2832 0c861595a, #2915 58e8535cf, #2822 d359a2f85, #2896 c9c6b103d, #2983 8278ef1b9, #3115 ba5121192, #2945 d2c08c14f, #2975 74512d658, #2951 26da88e8e, #2800 b6ebcedd4, #2893 7c7e99b48, #3113 fa1460b6b (and #3097 0d7a451ab, merged since). RTX 4060 8 GB, driver 610.88, Windows 11. Series S, -Resolution 1080, frame generation 2x, the same walking route as the other runs on this machine, 330 s after reaching the world.

What Result
Device lost / device removed 0
Exceptions, panics, hang watchdog, GPU stall, title suspended 0
Process alive at the end yes, stopped by the time limit
Rendered fps, last 240 s (43 samples) median 14.6, mean 12.7
Rendered fps, last 120 s median 13.7
Time under 5 fps in the world 13 % (short drops, lowest sample 0.3 fps)

The drops under 5 fps line up with shaders being translated while walking (about 500 translations in the last 330 s): this batch changes the shader translation, so the shader cache built by earlier runs did not apply and the pipeline precompile alone took about 45 minutes. The batch-5 run on the same machine and route had no sample under 5 fps (median 16.4). I read this as cold-cache stutter, not as a regression of a single pull request, but this run cannot tell them apart.

Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this batch, on the heads listed above. If one of these pull requests changes its head, this run no longer covers it.

Limits: one run; arrival in the world was driven by keys and not checked on pictures. A first attempt of this batch is not counted: the run script gave up waiting for the game window after 40 minutes of precompile.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7354443429 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7354443429). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:21:39Z. --- RUN (in game, batch of seventeen render-path pull requests), each head merged with `git merge --no-ff` onto main `3c106eb2f`, in one build: #3111 `15b579756`, #2948 `5284c6eae`, #2698 `1f188c4f7`, #2946 `44bf554fe`, #3001 `d924cbb65`, #2832 `0c861595a`, #2915 `58e8535cf`, #2822 `d359a2f85`, #2896 `c9c6b103d`, #2983 `8278ef1b9`, #3115 `ba5121192`, #2945 `d2c08c14f`, #2975 `74512d658`, #2951 `26da88e8e`, #2800 `b6ebcedd4`, #2893 `7c7e99b48`, #3113 `fa1460b6b` (and #3097 `0d7a451ab`, merged since). RTX 4060 8 GB, driver 610.88, Windows 11. Series S, `-Resolution 1080`, frame generation 2x, the same walking route as the other runs on this machine, 330 s after reaching the world. | What | Result | |---|---| | Device lost / device removed | 0 | | Exceptions, panics, hang watchdog, GPU stall, title suspended | 0 | | Process alive at the end | yes, stopped by the time limit | | Rendered fps, last 240 s (43 samples) | median 14.6, mean 12.7 | | Rendered fps, last 120 s | median 13.7 | | Time under 5 fps in the world | 13 % (short drops, lowest sample 0.3 fps) | The drops under 5 fps line up with shaders being translated while walking (about 500 translations in the last 330 s): this batch changes the shader translation, so the shader cache built by earlier runs did not apply and the pipeline precompile alone took about 45 minutes. The batch-5 run on the same machine and route had no sample under 5 fps (median 16.4). I read this as cold-cache stutter, not as a regression of a single pull request, but this run cannot tell them apart. Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this batch, on the heads listed above. If one of these pull requests changes its head, this run no longer covers it. Limits: one run; arrival in the world was driven by keys and not checked on pictures. A first attempt of this batch is not counted: the run script gave up waiting for the game window after 40 minutes of precompile. AI-assisted (Claude Code).
MoonEyes commented 2026-12-02 18:28:56 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-02T18:28:56Z.


Verification of #2800 (D3D12-SHADER-OPT-CHAINS-CANONICAL): third-party run on Linux x86_64 with Rust 1.98.1 (the pinned toolchain), no GPU and no game files.

  • Head: b6ebcedd4, merge base 27613ab6b, merged locally (detached, clean merge) into main 45dc41f95.

Commands and results

  • cargo test -p leonida-shader --locked: 256 passed, 0 failed, 2 ignored.
  • Red/green: I reverted only the two source hunks in d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs: the per-phi birth index at L1362-1367 and the if x == want => cur = y arm at L1435. The new tests stayed in. Then I reran cargo test -p leonida-shader --locked --lib: 254 passed and 2 failed (a_chain_of_three_phis_in_the_same_block_settles_in_one_pass and a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is). The control test a_chain_with_its_terms_out_of_order_is_still_rewritten passes both ways, as intended. After restoring the file, all tests pass again.
  • python -I scripts/check_no_game_data.py on the changed file: clean.
  • Not run here: clippy and rustfmt, because those components are not installed on this machine. CI check and d3d12 (windows-latest) pass on this head.

Review

  • The commuted arm is sound. key() treats integer and as commutative, so counting and(want, lower) as canonical only stops a rewrite that the reuse pass would undo.
  • The phi birth order is now (rank, k) for phis and (rank, phis + k) for the body. That gives a total order within a block, so no two same-block phis tie.
  • No code defects found.

Process notes

  • The PR body says AI-assisted: Claude Sonnet 5.5. CONTRIBUTING.md lists Sonnet for documentation and simple fixes only. New code should use one of the models listed under "new code and reviews", and the body does not name the reviewer agent's model.
  • The maintainer asked for an in-game run on the current head because this touches the render path. That run is not posted yet. The Windows run on b6ebced in this thread covers unit tests and fuzzing only.

Verdict: ready on the code (red/green reproduced on Linux). Still needs the in-game run and a disclosure fix.

AI-assisted verification: Claude Opus (Claude Code), separate agent per batch.


Generated by Claude Code

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7354659621 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7354659621). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-02T18:28:56Z. --- **Verification of #2800 (D3D12-SHADER-OPT-CHAINS-CANONICAL)**: third-party run on Linux x86_64 with Rust 1.98.1 (the pinned toolchain), no GPU and no game files. - Head: `b6ebcedd4`, merge base `27613ab6b`, merged locally (detached, clean merge) into `main` `45dc41f95`. **Commands and results** - `cargo test -p leonida-shader --locked`: 256 passed, 0 failed, 2 ignored. - Red/green: I reverted only the two source hunks in `d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs`: the per-phi birth index at L1362-1367 and the `if x == want => cur = y` arm at L1435. The new tests stayed in. Then I reran `cargo test -p leonida-shader --locked --lib`: 254 passed and **2 failed** (`a_chain_of_three_phis_in_the_same_block_settles_in_one_pass` and `a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is`). The control test `a_chain_with_its_terms_out_of_order_is_still_rewritten` passes both ways, as intended. After restoring the file, all tests pass again. - `python -I scripts/check_no_game_data.py` on the changed file: clean. - Not run here: clippy and rustfmt, because those components are not installed on this machine. CI `check` and `d3d12 (windows-latest)` pass on this head. **Review** - The commuted arm is sound. `key()` treats integer `and` as commutative, so counting `and(want, lower)` as canonical only stops a rewrite that the reuse pass would undo. - The phi birth order is now `(rank, k)` for phis and `(rank, phis + k)` for the body. That gives a total order within a block, so no two same-block phis tie. - No code defects found. **Process notes** - The PR body says `AI-assisted: Claude Sonnet 5.5`. CONTRIBUTING.md lists Sonnet for documentation and simple fixes only. New code should use one of the models listed under "new code and reviews", and the body does not name the reviewer agent's model. - The maintainer asked for an in-game run on the current head because this touches the render path. That run is not posted yet. The Windows run on `b6ebced` in this thread covers unit tests and fuzzing only. **Verdict:** ready on the code (red/green reproduced on Linux). Still needs the in-game run and a disclosure fix. AI-assisted verification: Claude Opus (Claude Code), separate agent per batch. --- _Generated by [Claude Code](https://claude.ai/code)_
bobcatchris commented 2026-12-02 21:02:03 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by bobcatchris on 2026-12-02T21:02:03Z.


@MoonEyes Thank you for the review and @Kal0s-design for verifying compatibility with #3156.

  • Updated the PR description's AI-assisted disclosure per CONTRIBUTING.md (naming Gemini 4 Neon and the independent read-only review pass on b6ebcedd4).
  • Leaving head b6ebcedd4 untouched: @MoonEyes's 2026-12-02T18:21:39Z in-game batch PASS (330 s, RTX 4060, main 3c106eb2f) already covers #2800 at exact head b6ebcedd4.

AI-assisted: Gemini 4 Neon

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7358692082 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7358692082). Originally posted by [bobcatchris](https://github.com/bobcatchris) on 2026-12-02T21:02:03Z. --- @MoonEyes Thank you for the review and `@Kal0s-design` for verifying compatibility with `#3156`. - Updated the PR description's `AI-assisted` disclosure per `CONTRIBUTING.md` (naming `Gemini 4 Neon` and the independent read-only review pass on `b6ebcedd4`). - Leaving head `b6ebcedd4` untouched: `@MoonEyes`'s `2026-12-02T18:21:39Z` in-game batch PASS (330 s, RTX 4060, main `3c106eb2f`) already covers `#2800` at exact head `b6ebcedd4`. AI-assisted: Gemini 4 Neon
fiestorra commented 2026-12-03 05:08:27 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T05:08:27Z.


VERIFY-2800 — 21 tests de opt pasan, y el cambio es de canonicalización

d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs   1 file changed, 136 insertions(+), 4 deletions(-)
cargo test -p leonida-shader --lib opt                21 passed   (2.4 s)

El título: «a chain with its steps the othe…» — una cadena de optimización cuyos pasos están en otro orden. Y el cambio está en opt.rs, que es el fichero que decide el orden.

Por qué ese orden importa, dicho sin jerga: dos programas que hacen lo mismo tienen que compilar al mismo DXIL, o el caché de shaders (que va por hash) los trata como distintos y compila dos veces. Una cadena cuyos pasos no están canónicamente ordenados es un programa que se ve distinto según cómo se escribió — y el juego, que compila miles, paga la duplicación.

Y es la tercera vez esta noche que aparece el mismo tema: #3284 (formatos enlazados), #2892 (joins de descriptores) y #2957 (gemelos enmascarados) son claves de caché que no incluyen algo; este es programas que son iguales y se ven distintos. Cuatro PRs, cuatro autores, el mismo invariante: la identidad de lo compilado tiene que depender de lo que hace, no de cómo está escrito.

Lo que verifiqué: 21 tests de opt en verde, y el fichero es el que toca el orden.
Lo que no: que el DXIL final sea idéntico para las dos escrituras — el test compara la decisión de optimización, no el binario emitido. Para eso haría falta un test de extremo a extremo con dos programas equivalentes, y ese es el que cerraría el círculo con el caché.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7368417232 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7368417232). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T05:08:27Z. --- ## VERIFY-2800 — 21 tests de `opt` pasan, y el cambio es de canonicalización ``` d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs 1 file changed, 136 insertions(+), 4 deletions(-) cargo test -p leonida-shader --lib opt 21 passed (2.4 s) ``` **El título**: **«a chain with its steps the othe…»** — **una cadena de optimización cuyos pasos están en otro orden.** **Y el cambio está en `opt.rs`, que es el fichero que decide el orden.** **Por qué ese orden importa, dicho sin jerga**: **dos programas que hacen lo mismo tienen que compilar al mismo DXIL, o el caché de shaders (que va por hash) los trata como distintos y compila dos veces.** **Una cadena cuyos pasos no están canónicamente ordenados es un programa que se ve distinto según cómo se escribió** — **y el juego, que compila miles, paga la duplicación.** **Y es la tercera vez esta noche que aparece el mismo tema**: **`#3284` (formatos enlazados), `#2892` (joins de descriptores) y `#2957` (gemelos enmascarados) son *claves de caché* que no incluyen algo; este es *programas que son iguales y se ven distintos*.** **Cuatro PRs, cuatro autores, el mismo invariante: la identidad de lo compilado tiene que depender de lo que hace, no de cómo está escrito.** **Lo que verifiqué**: **21 tests de `opt` en verde, y el fichero es el que toca el orden.** **Lo que no**: **que el DXIL final sea idéntico para las dos escrituras** — **el test compara la decisión de optimización, no el binario emitido.** **Para eso haría falta un test de extremo a extremo con dos programas equivalentes, y ese es el que cerraría el círculo con el caché.**
MoonEyes commented 2026-12-03 18:03:51 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-03T18:03:51Z.


In-game gate run on an RTX 4060 8 GB (driver 610.88, Windows 11), in a batch of #2822, #2800, #2664 and #2661 merged into main 09273248c; this PR tested at its current head b6ebcedd4. Series S 1080, DLSS FG 2x, play-nvidia.ps1 -SeriesS -Resolution 1080 -FrameGen 2 -PrecompileUsed, scripted walk, 330 s, screen kept on.

  • Result: PASS. No device lost, no crash, no unhandled exception; the run ended on its time limit.
  • Median over the last 240 s: 16.8 fps (main alone today: 15.8-17.5); 19.1 frames per 1000 over 100 ms; 6 pauses over 1 s (usual: 1-4).
  • Precompilation took 896 s, against ~160 s for the batches before it on the same cache. Something in this batch changes the translated shaders' cache keys (likely #2822 or #2800, which change the shader optimizer), so every player would rebuild the whole cache once. Not yet isolated per PR.
  • Covered: a normal launch and walk with this PR's code in the build. It does not isolate this PR's own change from the three others in the batch.

AI-assisted (Claude Opus 5.5), run and read by MoonEyes' agent.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7387539304 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2800#issuecomment-7387539304). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T18:03:51Z. --- In-game gate run on an RTX 4060 8 GB (driver 610.88, Windows 11), in a batch of #2822, #2800, #2664 and #2661 merged into main `09273248c`; this PR tested at its current head `b6ebcedd4`. Series S 1080, DLSS FG 2x, `play-nvidia.ps1 -SeriesS -Resolution 1080 -FrameGen 2 -PrecompileUsed`, scripted walk, 330 s, screen kept on. - Result: **PASS**. No device lost, no crash, no unhandled exception; the run ended on its time limit. - Median over the last 240 s: 16.8 fps (main alone today: 15.8-17.5); 19.1 frames per 1000 over 100 ms; 6 pauses over 1 s (usual: 1-4). - Precompilation took **896 s, against ~160 s** for the batches before it on the same cache. Something in this batch changes the translated shaders' cache keys (likely #2822 or #2800, which change the shader optimizer), so every player would rebuild the whole cache once. Not yet isolated per PR. - Covered: a normal launch and walk with this PR's code in the build. It does not isolate this PR's own change from the three others in the batch. AI-assisted (Claude Opus 5.5), run and read by MoonEyes' agent.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/2800:upstream-pr/2800'
git switch 'upstream-pr/2800'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/2800'
git switch 'upstream-pr/2800'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/2800'
git switch 'upstream-pr/2800'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/2800'
git switch 'main'
git merge --squash 'upstream-pr/2800'
git switch 'main'
git merge --ff-only 'upstream-pr/2800'
git switch 'main'
git merge 'upstream-pr/2800'
git push origin 'main'
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
ProjectLeonida/mandy!2800
No description provided.