From 9e39fbb584c11cf9f060b77150d139ba890f26a7 Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:13:00 -0600 Subject: [PATCH 1/2] D3D12-SHADER-OPT-CHAINS-CANONICAL: a chain with its steps the other way round is in order `chains` rewrites a conjunction of lane conditions into `(((t1 & t2) & t3) & ...)` with the terms in the order they were made, and leaves a chain alone when it is that already (`canonical`). `canonical` only accepted a step written `and(lower, term)`. `key` has an integer `and` the same whichever way round its operands are, 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, until the limit of four rounds. Both passes said "changed" every round, so `optimise` never stopped early on those modules, and its last round ended on a `chains` rewrite that no `merge` followed, which left the rewrite's duplicates in the DXIL. `canonical` now accepts a step with its two operands either way round. Full-archive `leonida translate` (25,689 emitted programs): 10,291 programs ran all four rounds before (rounds 3 and 4 were 44 % of the optimiser's time); the DXIL of 10,089 programs changes, all of it in `arith` (-341,356 instructions, -0.84 % of arith, -0.34 % of all; every other kind of instruction and the block count are equal), 7,315 smaller, 2,767 of the same size, 7 larger by 4 bytes. The old code with one `merge` added after its last round gives the same arith count. The validator (`--validate`) reports the same table of reasons and the same counts before and after. Wall -7.8 %, user CPU -8.5 % over four alternating runs each. Tests: a chain with the term first at the root, below it, and both is left as it is (fails without the change), and a chain with its terms out of order is still rewritten. AI-assisted: Claude Sonnet 5.5 Co-authored-by: Cursor --- .../leonida-shader/src/emit/bitcode/opt.rs | 87 ++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs index 17ba664162..9a2779b040 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs @@ -1260,13 +1260,17 @@ impl Module { } (out.len() >= 3).then_some(out) }; - // Whether the root is the chain of these terms already. + // Whether the root is the chain of these terms already. A step with its two operands the + // other way round counts: `key` has an integer `and` the same whichever way round, so 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. let canonical = |m: &Module, root: u32, terms: &[Cond]| -> bool { let mut cur = V::Inst(root); for t in terms.iter().skip(1).rev() { let (V::Inst(i), Some(want)) = (cur, t.existing) else { return false }; match m.insts[i as usize].op { Op::Bin(Bin::And, x, y) if y == want => cur = x, + Op::Bin(Bin::And, x, y) if x == want => cur = y, _ => return false, } } @@ -1815,6 +1819,87 @@ mod tests { m.write(); } + /// `key` has an integer `and` the same whichever way round its operands are, so a chain whose + /// steps have the term first is the chain in order as far as the reuse pass can tell. `chains` + /// used to rebuild it each round for the reuse pass to put back, and say that it had changed + /// something every time, up to the limit of rounds. + #[test] + fn a_chain_with_the_operands_of_its_steps_the_other_way_round_is_left_as_it_is() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2)); + let cond = |m: &mut Module, k: V| { + let v = m.call(b, reads, vec![k, k]); + m.cmp(b, pred::NE, v, zero) + }; + // made in this order, so the chain in order is `(a & c1) & c2` + let (a, c1, c2) = (cond(&mut m, zero), cond(&mut m, one), cond(&mut m, two)); + let swapped_low = m.bin(b, Bin::And, c1, a); + let in_order_low = m.bin(b, Bin::And, a, c1); + // the term first at the root and at the step below it, at the root only, below only + let both = m.bin(b, Bin::And, c2, swapped_low); + let root_only = m.bin(b, Bin::And, c2, in_order_low); + let below_only = m.bin(b, Bin::And, swapped_low, c2); + for (k, chain) in [both, root_only, below_only].into_iter().enumerate() { + let value = m.select(b, chain, one, zero); + let slot = m.i32(k as u32); + m.call(b, writes, vec![value, slot]); + } + m.terminate(b, Term::Ret); + assert!(!m.chains(), "no chain here is out of order"); + let ops = |m: &Module| -> String { + let ops: Vec<&Op> = m.blocks[b] + .body + .iter() + .map(|&i| &m.insts[i as usize].op) + .collect(); + format!("{ops:?}") + }; + let before = ops(&m); + m.optimise(CHAINS | REUSE | DEAD); + assert!(!m.chains(), "nor after the reuse pass has merged them"); + let merged = ops(&m); + m.optimise(CHAINS | REUSE | DEAD); + assert_eq!( + ops(&m), + merged, + "and a second run leaves the same instructions" + ); + assert_ne!(before, merged, "the reuse pass did merge the three"); + m.write(); + } + + /// The control of the one above: the terms in the wrong order are still rewritten. + #[test] + fn a_chain_with_its_terms_out_of_order_is_still_rewritten() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let (zero, one, two) = (m.i32(0), m.i32(1), m.i32(2)); + let cond = |m: &mut Module, k: V| { + let v = m.call(b, reads, vec![k, k]); + m.cmp(b, pred::NE, v, zero) + }; + let (a, c1, c2) = (cond(&mut m, zero), cond(&mut m, one), cond(&mut m, two)); + let low = m.bin(b, Bin::And, c2, a); + let chain = m.bin(b, Bin::And, low, c1); + let value = m.select(b, chain, one, zero); + m.call(b, writes, vec![value, two]); + m.terminate(b, Term::Ret); + assert!(m.chains(), "`c2 & a` then `& c1` is not `(a & c1) & c2`"); + assert!(!m.chains(), "and the rewrite is in order"); + m.write(); + } + #[test] fn branch_conditions_and_phi_cycles() { let Kit { From b6ebcedd4057659ff189acdb712129765aa8df6d Mon Sep 17 00:00:00 2001 From: bobcatchris <83428450+bobcatchris@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:24:36 -0600 Subject: [PATCH 2/2] leonida-shader: give same-block phis a total birth order in chains() --- .../leonida-shader/src/emit/bitcode/opt.rs | 53 +++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs index 79c85c8b84..32b6f74c91 100644 --- a/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs +++ b/d3d12/crates/leonida-shader/src/emit/bitcode/opt.rs @@ -1319,11 +1319,12 @@ impl Module { let n = self.insts.len(); let mut born: Vec<(usize, usize)> = vec![(usize::MAX, 0); n]; for (rank, &b) in tree.order.iter().enumerate() { - for &p in &self.blocks[b].phis { - born[p as usize] = (rank, 0); + let phis = self.blocks[b].phis.len(); + for (k, &p) in self.blocks[b].phis.iter().enumerate() { + born[p as usize] = (rank, k); } for (k, &i) in self.blocks[b].body.iter().enumerate() { - born[i as usize] = (rank, k + 1); + born[i as usize] = (rank, phis + k); } } // What one root is, as terms in order; None: leave it. @@ -2021,6 +2022,52 @@ mod tests { m.write(); } + /// Three `i1` phis defined in the same block must have a total birth order so + /// a chain over them settles in a single pass instead of reversing and + /// rewriting again on the next round. + #[test] + fn a_chain_of_three_phis_in_the_same_block_settles_in_one_pass() { + let Kit { + mut m, + b: entry, + reads, + writes, + .. + } = kit(); + let (zero, one) = (m.i32(0), m.i32(1)); + let i1 = m.int(1); + let left = m.new_block(); + let right = m.new_block(); + let join = m.new_block(); + let v = m.call(entry, reads, vec![zero, zero]); + let br = m.cmp(entry, pred::NE, v, zero); + m.terminate(entry, Term::CondBr(br, left, right)); + let cond = |m: &mut Module, blk, k: u32| { + let arg = m.i32(k); + let x = m.call(blk, reads, vec![arg, zero]); + m.cmp(blk, pred::NE, x, zero) + }; + let (l0, l1, l2) = (cond(&mut m, left, 1), cond(&mut m, left, 2), cond(&mut m, left, 3)); + m.terminate(left, Term::Br(join)); + let (r0, r1, r2) = (cond(&mut m, right, 4), cond(&mut m, right, 5), cond(&mut m, right, 6)); + m.terminate(right, Term::Br(join)); + let p0 = m.phi(join, i1); + let p1 = m.phi(join, i1); + let p2 = m.phi(join, i1); + m.set_phi(p0, vec![(l0, left), (r0, right)]); + m.set_phi(p1, vec![(l1, left), (r1, right)]); + m.set_phi(p2, vec![(l2, left), (r2, right)]); + // Out of phi order: `(p2 & p0) & p1`. + let low = m.bin(join, Bin::And, p2, p0); + let chain = m.bin(join, Bin::And, low, p1); + let value = m.select(join, chain, one, zero); + m.call(join, writes, vec![value, zero]); + m.terminate(join, Term::Ret); + assert!(m.chains(), "out-of-order phi chain is rewritten once"); + assert!(!m.chains(), "rebuilt same-block phi chain is canonical and settles"); + m.write(); + } + #[test] fn branch_conditions_and_phi_cycles() { let Kit {