From 673ab90c82584abfdd5e65bf61e199c373f5752d Mon Sep 17 00:00:00 2001 From: mokkamokacaffe <329663686+mokkamokacaffe@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:10:14 +0100 Subject: [PATCH 1/2] Direct DXIL: fold CFG branches from known path conditions Fold branch and switch terminators both after ordinary constant simplification and when every incoming control-flow edge proves the selector value. Facts are intersected at joins and bounded to branch selectors, so contradictory paths do not leak through reconvergence. Recompute type-derived shader flags from surviving instructions after CFG folding so removed wide operations cannot leave stale metadata. Assisted-by: OpenAI Codex (GPT-5) Assisted-by: OpenAI Codex (GPT-6.2 Astra Ultra) --- crates/xcl/src/gpu/dxil/module.rs | 17 +- crates/xcl/src/gpu/dxil/module/opt.rs | 427 ++++++++++++++++++++++---- crates/xcl/src/gpu/dxil/shader.rs | 58 ++++ 3 files changed, 435 insertions(+), 67 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..4299ccf8d2 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1416,11 +1416,18 @@ impl Module { /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). pub fn uses_double_extensions(&self) -> bool { let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; - self.insts.iter().any(|d| match &d.op { - Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, - Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, - Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, - _ => false, + self.blocks.iter().flatten().any(|&i| { + let d = &self.insts[i as usize]; + match &d.op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, + Op::Call(f, args) => { + self.funcs[*f as usize].name.starts_with("dx.op.tertiary.") + && args.first().and_then(|&v| self.const_u64(v)) == Some(47) + } + _ => false, + } }) } pub fn insts_use_type(&self, t: Ty) -> bool { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 230a59f9f9..ffa7e6d138 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -424,14 +424,115 @@ impl Module { idom } + /// Replace phis whose incoming values are only themselves and one other value. Repeat + /// because resolving one phi may make another trivial, including across loop backedges. + fn simplify_phis(&self, order: &[u32], repl: &mut [Option]) { + loop { + let mut changed = false; + for &b in order { + for &i in &self.blocks[b as usize] { + let i = i as usize; + if repl[i].is_some() { + continue; + } + let Op::Phi(inc) = &self.insts[i].op else { break }; + let me = Value::Inst(i as u32); + let mut same: Option = None; + let mut trivial = true; + for &(v, _) in inc { + let v = resolve(repl, v); + if v == me || Some(v) == same { + continue; + } + if same.is_some() { + trivial = false; + break; + } + same = Some(v); + } + if let (true, Some(v)) = (trivial, same) { + repl[i] = Some(v); + changed = true; + } + } + } + if !changed { + break; + } + } + } + + /// Constants established by the control-flow edge that reaches each block. Facts are + /// intersected at joins, so a value is kept only when every incoming edge proves the same + /// value. This deliberately tracks branch and switch selectors only; deriving arithmetic + /// facts belongs in the ordinary simplifier. + fn branch_facts(&self, order: &[u32]) -> Vec> { + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in order { + for s in self.successors(b as usize) { + if !preds[s.0 as usize].contains(&(b as usize)) { + preds[s.0 as usize].push(b as usize); + } + } + } + let mut facts: Vec> = vec![HashMap::new(); self.blocks.len()]; + for _ in 0..=order.len() { + let mut changed = false; + for &b in order.iter().skip(1) { + let b = b as usize; + let mut incoming: Option> = None; + for &p in &preds[b] { + let mut edge = facts[p].clone(); + if let Some(&term) = self.blocks[p].last() { + match &self.insts[term as usize].op { + Op::CondBr(v, t, f) if t != f => { + if t.0 as usize == b { + edge.insert(*v, 1); + } else if f.0 as usize == b { + edge.insert(*v, 0); + } + } + Op::Switch(v, default, cases) if default.0 as usize != b => { + let matching: Vec = cases.iter().filter(|(_, t)| t.0 as usize == b).map(|(c, _)| *c).collect(); + if let [case] = matching.as_slice() { + if let Some(value) = self.const_u64(*case) { + edge.insert(*v, value); + } + } + } + _ => {} + } + } + incoming = Some(match incoming { + None => edge, + Some(mut common) => { + common.retain(|v, value| edge.get(v) == Some(value)); + common + } + }); + } + let next = incoming.unwrap_or_default(); + if facts[b] != next { + facts[b] = next; + changed = true; + } + } + if !changed { + return facts; + } + } + // A malformed or irreducible graph that does not reach a fixed point gets no facts. + vec![HashMap::new(); self.blocks.len()] + } + /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); - let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); // malformed IR (a use before its definition or of a void result) is left for the // writer to report, not cleaned away if !self.uses_well_formed(&order) { @@ -459,38 +560,8 @@ impl Module { let mut repl: Vec> = vec![None; self.insts.len()]; // trivial phis (all incoming values the phi itself or one value), to a fixed point - while !skip("phi") { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl[i].is_some() { - continue; - } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl, v); - if v == me || Some(v) == same { - continue; - } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); - } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); - changed = true; - } - } - } - if !changed { - break; - } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); } // CSE along the dominator tree (preorder walk with a scoped table) @@ -563,39 +634,64 @@ impl Module { } // second trivial-phi fixed point if CSE/simplification collapsed incoming values if cse_replaced && !skip("phi") { - loop { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl[i].is_some() { - continue; - } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl, v); - if v == me || Some(v) == same { - continue; - } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); - } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); - changed = true; + self.simplify_phis(&order, &mut repl); + } + // CSE and algebraic simplification can make a terminator constant. Fold it before + // DCE, then rebuild reachability and predecessor edges: a predecessor block can stay + // reachable while one of its edges disappears, and that edge's phi input must go. + let mut cfg_folded = false; + if !skip("cfg") { + let facts = self.branch_facts(&order); + for &b in &order { + let Some(&i) = self.blocks[b as usize].last() else { continue }; + let replacement = match self.insts[i as usize].op.clone() { + Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| facts[b as usize].get(&c).copied()) { + Some(0) => Some(Op::Br(f)), + Some(1) => Some(Op::Br(t)), + _ => None, + }, + Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| facts[b as usize].get(&v).copied()).map(|needle| { + let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); + Op::Br(target) + }), + _ => None, + }; + if let Some(op) = replacement { + self.insts[i as usize].op = op; + cfg_folded = true; + } + } + } + if cfg_folded { + order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut reach = vec![false; self.blocks.len()]; + // CFG blocks normally have very few predecessors, so compact vectors avoid one + // hash-table allocation per block on the giant programs this pass targets. + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + reach[b as usize] = true; + for succ in self.successors(b as usize) { + if let Some(p) = preds.get_mut(succ.0 as usize) { + if !p.contains(&b) { + p.push(b); } } } - if !changed { - break; + } + for (b, r) in reach.iter().enumerate() { + if !r { + self.blocks[b].clear(); } } + for &b in &order { + for &i in &self.blocks[b as usize] { + let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; + inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + } + } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); + } } // phis may name values defined later (back edges): resolve once more for &b in &order { @@ -1401,4 +1497,211 @@ mod tests { let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + + #[test] + fn constant_conditional_removes_edge_and_trivial_phi() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let join = m.new_block(); + let i32 = m.i32(); + let slot = m.alloca(i32, 4); + let one = m.i32c(1); + let cond = m.cmp(Pred::Eq, one, one); + m.cond_br(cond, yes, no); + m.set_block(yes); + let live = m.i32c(7); + m.br(join); + m.set_block(no); + let dead = m.i32c(9); + m.br(join); + m.set_block(join); + let phi = m.phi(i32); + m.add_incoming(phi, live, yes); + m.add_incoming(phi, dead, no); + m.store(slot, phi, 4); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.iter().all(|&b| !m.blocks[b].iter().any(|&i| matches!(m.insts[i as usize].op, Op::CondBr(..))))); + assert!(m.blocks[no.0 as usize].is_empty()); + assert!(!m.blocks[join.0 as usize].iter().any(|&i| matches!(m.insts[i as usize].op, Op::Phi(_)))); + } + + #[test] + fn constant_switch_keeps_only_the_selected_predecessor() { + let mut m = Module::new(); + let default = m.new_block(); + let selected = m.new_block(); + let join = m.new_block(); + let one = m.i32c(1); + let two = m.i32c(2); + let selector = m.bin(BinOp::Add, one, one); + m.switch(selector, default, &[(two, selected)]); + m.set_block(default); + m.br(join); + m.set_block(selected); + m.br(join); + m.set_block(join); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.iter().all(|&b| !m.blocks[b].iter().any(|&i| matches!(m.insts[i as usize].op, Op::Switch(..))))); + assert!(m.blocks[default.0 as usize].is_empty()); + } + + #[test] + fn branch_condition_folds_a_dominated_branch() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let proven = m.new_block(); + let impossible = m.new_block(); + let i1 = m.i1(); + let condition = m.alloca(i1, 1); + let condition = m.load(condition, 1); + m.cond_br(condition, yes, no); + m.set_block(yes); + m.cond_br(condition, proven, impossible); + m.set_block(no); + m.ret(); + m.set_block(proven); + m.ret(); + m.set_block(impossible); + m.ret(); + + m.optimize(); + + assert!(m.blocks[impossible.0 as usize].is_empty()); + assert!(m.blocks[yes.0 as usize] + .iter() + .all(|&i| !matches!(m.insts[i as usize].op, Op::CondBr(..)))); + } + + #[test] + fn branch_condition_is_dropped_when_paths_reconverge() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let join = m.new_block(); + let a = m.new_block(); + let b = m.new_block(); + let i1 = m.i1(); + let condition = m.alloca(i1, 1); + let condition = m.load(condition, 1); + m.cond_br(condition, yes, no); + m.set_block(yes); + m.br(join); + m.set_block(no); + m.br(join); + m.set_block(join); + m.cond_br(condition, a, b); + m.set_block(a); + m.ret(); + m.set_block(b); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.contains(&(a.0 as usize))); + assert!(reachable.contains(&(b.0 as usize))); + assert!(reachable.iter().any(|&block| m.blocks[block] + .iter() + .any(|&i| matches!(m.insts[i as usize].op, Op::CondBr(..))))); + } + + #[test] + fn switch_case_folds_a_dominated_switch() { + let mut m = Module::new(); + let selected = m.new_block(); + let default = m.new_block(); + let proven = m.new_block(); + let impossible = m.new_block(); + let i32 = m.i32(); + let selector = m.alloca(i32, 4); + let selector = m.load(selector, 4); + let seven = m.i32c(7); + m.switch(selector, default, &[(seven, selected)]); + m.set_block(selected); + m.switch(selector, impossible, &[(seven, proven)]); + m.set_block(default); + m.ret(); + m.set_block(proven); + m.ret(); + m.set_block(impossible); + m.ret(); + + m.optimize(); + + assert!(m.blocks[impossible.0 as usize].is_empty()); + assert!(m.blocks[selected.0 as usize] + .iter() + .all(|&i| !matches!(m.insts[i as usize].op, Op::Switch(..)))); + } + + #[test] + fn unreachable_double_conversion_does_not_set_extension_flag() { + let mut m = Module::new(); + let live = m.new_block(); + let dead = m.new_block(); + let one = m.i32c(1); + let always = m.cmp(Pred::Eq, one, one); + m.cond_br(always, live, dead); + m.set_block(dead); + let f64 = m.f64(); + m.cast(CastOp::SIToFP, one, f64); + m.ret(); + m.set_block(live); + m.ret(); + + assert!(m.uses_double_extensions()); + m.optimize(); + + assert!(m.blocks[dead.0 as usize].is_empty()); + assert!(!m.uses_double_extensions()); + } + + #[test] + fn edge_trim_keeps_a_loop_phi_backedge() { + let mut m = Module::new(); + let entry = m.entry_block(); + let dead = m.new_block(); + let lp = m.new_block(); + let exit = m.new_block(); + let i32 = m.i32(); + let i1 = m.i1(); + let result = m.alloca(i32, 4); + let loop_cond = m.alloca(i1, 1); + let zero = m.i32c(0); + let one = m.i32c(1); + let always = m.cmp(Pred::Eq, one, one); + m.cond_br(always, lp, dead); + m.set_block(dead); + let discarded = m.i32c(99); + m.br(lp); + m.set_block(lp); + let phi = m.phi(i32); + m.add_incoming(phi, zero, entry); + m.add_incoming(phi, discarded, dead); + let next = m.bin(BinOp::Add, phi, one); + m.add_incoming(phi, next, lp); + let again = m.load(loop_cond, 1); + m.cond_br(again, lp, exit); + m.set_block(exit); + m.store(result, phi, 4); + m.ret(); + + m.optimize(); + + assert!(m.blocks[dead.0 as usize].is_empty()); + let incoming = m.phi_incoming(phi); + assert_eq!(incoming.len(), 2); + assert!(incoming.iter().any(|p| p.1 == entry)); + assert!(incoming.iter().any(|p| p.1 == lp)); + } } diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..27dddfee41 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -503,6 +503,11 @@ impl Shader { /// from the code and demands in the flags even when the IR was built /// with [`Module`] methods directly rather than the [`Shader`] helpers. pub(super) fn infer_type_features(&mut self) { + // CFG simplification can remove the instruction that originally requested one of + // these features. The validator requires the flags to match the surviving code. + self.features.remove(&Feature::Int64Ops); + self.features.remove(&Feature::Doubles); + self.features.remove(&Feature::DoubleExtensions); let (i64, f64) = self.m.existing_i64_f64(); if i64.is_some_and(|t| self.m.insts_use_type(t)) { self.require(Feature::Int64Ops); @@ -632,6 +637,59 @@ impl Shader { } } +#[cfg(test)] +mod type_feature_tests { + use super::*; + use super::super::module::{BinOp, Pred}; + use super::super::ops::Tertiary; + + #[test] + fn cfg_folding_removes_type_features_used_only_on_the_dead_edge() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let live = s.m.new_block(); + let dead = s.m.new_block(); + let one = s.m.i32c(1); + let always = s.m.cmp(Pred::Eq, one, one); + s.m.cond_br(always, live, dead); + + s.m.set_block(dead); + let i64 = s.m.i64(); + let wide = s.m.const_int(i64, 1); + s.require(Feature::Int64Ops); + s.m.bin(BinOp::Add, wide, wide); + let f64 = s.m.f64(); + let d = s.m.const_float(f64, 1.0f64.to_bits()); + s.tertiary(Tertiary::Fma, d, d, d); + s.m.ret(); + + s.m.set_block(live); + s.m.ret(); + + assert!(s.features.contains(&Feature::Int64Ops)); + assert!(s.features.contains(&Feature::Doubles)); + assert!(s.features.contains(&Feature::DoubleExtensions)); + s.m.optimize(); + s.infer_type_features(); + assert!(!s.features.contains(&Feature::Int64Ops)); + assert!(!s.features.contains(&Feature::Doubles)); + assert!(!s.features.contains(&Feature::DoubleExtensions)); + } + + #[test] + fn surviving_fma_reinfers_double_extension_features() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let f64 = s.m.f64(); + let d = s.m.const_float(f64, 1.0f64.to_bits()); + s.tertiary(Tertiary::Fma, d, d, d); + s.m.ret(); + + s.m.optimize(); + s.infer_type_features(); + assert!(s.features.contains(&Feature::Doubles)); + assert!(s.features.contains(&Feature::DoubleExtensions)); + } +} + /// The function attributes DXC gives each `dx.op` declaration (DXC 1.9 /// `DxilOperations.cpp`, checked against `dxc -Fc` listings). AMD's compiler /// is sensitive to them (e.g. `waveGetLaneIndex` must be `readonly`), so From c32c65e05d561f50713abc6b37bd6aada9ebb0ea Mon Sep 17 00:00:00 2001 From: mokkamokacaffe <329663686+mokkamokacaffe@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:46:15 +0100 Subject: [PATCH 2/2] Keep phi replacements in serialization order after CFG folding --- crates/xcl/src/gpu/dxil/module/opt.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index d30b005237..4d73dc01dc 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -616,7 +616,7 @@ impl Module { /// Replace phis whose incoming values are only themselves and one other value. Repeat /// because resolving one phi may make another trivial, including across loop backedges. - fn simplify_phis(&self, order: &[u32], repl: &mut [Option]) { + fn simplify_phis(&self, order: &[u32], inst_at: &[usize], repl: &mut [Option]) { loop { let mut changed = false; for &b in order { @@ -640,7 +640,12 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + // A backedge definition may follow the phi in serialization order. + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl[i] = Some(v); changed = true; } @@ -759,7 +764,7 @@ impl Module { // trivial phis (all incoming values the phi itself or one value), to a fixed point if !skip("phi") { - self.simplify_phis(&order, &mut repl); + self.simplify_phis(&order, &inst_at, &mut repl); } // CSE along the dominator tree (preorder walk with a scoped table) @@ -832,7 +837,7 @@ impl Module { } // second trivial-phi fixed point if CSE/simplification collapsed incoming values if cse_replaced && !skip("phi") { - self.simplify_phis(&order, &mut repl); + self.simplify_phis(&order, &inst_at, &mut repl); } // CSE and algebraic simplification can make a terminator constant. Fold it before // DCE, then rebuild reachability and predecessor edges: a predecessor block can stay @@ -862,6 +867,10 @@ impl Module { } if cfg_folded { order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + inst_at.fill(usize::MAX); + for (at, &i) in order.iter().flat_map(|&b| &self.blocks[b as usize]).enumerate() { + inst_at[i as usize] = at; + } let mut reach = vec![false; self.blocks.len()]; // CFG blocks normally have very few predecessors, so compact vectors avoid one // hash-table allocation per block on the giant programs this pass targets. @@ -888,7 +897,7 @@ impl Module { } } if !skip("phi") { - self.simplify_phis(&order, &mut repl); + self.simplify_phis(&order, &inst_at, &mut repl); } } // phis may name values defined later (back edges): resolve once more