From 2778b0ba7a021feb1a179a701491f2c6e633964e Mon Sep 17 00:00:00 2001 From: fixgep <2011slatin@gmail.com> Date: Wed, 25 Nov 2026 00:47:36 +0300 Subject: [PATCH 1/2] Direct DXIL: make Ssa::read iterative to avoid stack overflow (#1805) Part of #1805. Assisted-by: Antigravity (Gemini 4 Hydrogen) --- crates/xcl/src/gpu/dxil/graphics.rs | 183 ++++++++----- crates/xcl/src/gpu/dxil/graphics_tests.rs | 39 +++ crates/xcl/src/gpu/dxil/kernel.rs | 31 +++ crates/xcl/src/gpu/dxil/module/opt.rs | 15 +- crates/xcl/src/gpu/dxil/ssa.rs | 296 ++++++++++++++++++---- 5 files changed, 438 insertions(+), 126 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index 239a923ea9..a191b4bb4f 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -824,79 +824,134 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac in_base: &'a [Option], inputs: &'a [Placed], } - fn block_deps(cx: &Cx, b: usize, st: &mut Sets) -> BTreeSet { - if let Some(d) = Sets::known(&st.blocks, &b, st.pass, &mut st.cut) { - return d; - } - Sets::open(&mut st.blocks, b); - let mut d = BTreeSet::new(); - for &a in &cx.ctrl[b] { - if let Some(c) = cx.cond[a] { - d.extend(value_deps(cx, c, st)); - } - if a != b { - d.extend(block_deps(cx, a, st)); - } - } - Sets::close(&mut st.blocks, b, d, st.pass, &mut st.grew) + #[derive(Clone, Copy)] + enum DepNode { + Block(usize), + Val(Value), } - fn value_deps(cx: &Cx, v: Value, st: &mut Sets) -> BTreeSet { - let Value::Inst(i) = v else { return BTreeSet::new() }; - if let Some(d) = Sets::known(&st.values, &v, st.pass, &mut st.cut) { - return d; - } - Sets::open(&mut st.values, v); - let m = &cx.s.m; - let mut d = BTreeSet::new(); - match m.inst_info(i) { - InstInfo::Call(name, args) if name.starts_with("dx.op.loadInput.") => { - let id = m.const_u64(args[1]).unwrap() as usize; - let col = m.const_u64(args[3]).unwrap() as u32; - if let Some(base) = cx.in_base[id] { - match m.const_u64(args[2]) { - Some(r) => { - d.insert(base + r as u32 * 4 + col); - } - None => { - for r in 0..cx.inputs[id].e.nrows() { - d.insert(base + r * 4 + col); + struct DepFrame { + node: DepNode, + children: Vec, + next: usize, + deps: BTreeSet, + } + fn eval_dep(cx: &Cx, start: DepNode, st: &mut Sets) -> BTreeSet { + let mut stack: Vec = Vec::new(); + let mut cur = start; + loop { + let ready: Option> = match cur { + DepNode::Block(b) => { + if let Some(d) = Sets::known(&st.blocks, &b, st.pass, &mut st.cut) { + Some(d) + } else { + Sets::open(&mut st.blocks, b); + let mut children = Vec::new(); + for &a in &cx.ctrl[b] { + if let Some(c) = cx.cond[a] { + children.push(DepNode::Val(c)); + } + if a != b { + children.push(DepNode::Block(a)); } - d.extend(value_deps(cx, args[2], st)); + } + if children.is_empty() { + Some(Sets::close(&mut st.blocks, b, BTreeSet::new(), st.pass, &mut st.grew)) + } else { + let first = children[0]; + stack.push(DepFrame { node: DepNode::Block(b), children, next: 1, deps: BTreeSet::new() }); + cur = first; + continue; } } } - } - InstInfo::Call(_, args) => { - for &a in args { - d.extend(value_deps(cx, a, st)); - } - } - InstInfo::Phi(list) => { - for &(x, from) in list { - d.extend(value_deps(cx, x, st)); - d.extend(block_deps(cx, from.0 as usize, st)); - if let Some(c) = cx.cond[from.0 as usize] { - d.extend(value_deps(cx, c, st)); - } - } - } - InstInfo::Load(p) => { - d.extend(value_deps(cx, p, st)); - if let Some(vs) = cx.root_stores.get(&root(cx.s, p)) { - for &x in vs { - d.extend(value_deps(cx, x, st)); + DepNode::Val(v) => match v { + Value::Inst(i) => { + if let Some(d) = Sets::known(&st.values, &v, st.pass, &mut st.cut) { + Some(d) + } else { + Sets::open(&mut st.values, v); + let m = &cx.s.m; + let mut d = BTreeSet::new(); + let mut children = Vec::new(); + match m.inst_info(i) { + InstInfo::Call(name, args) if name.starts_with("dx.op.loadInput.") => { + let id = m.const_u64(args[1]).unwrap() as usize; + let col = m.const_u64(args[3]).unwrap() as u32; + if let Some(base) = cx.in_base[id] { + match m.const_u64(args[2]) { + Some(r) => { + d.insert(base + r as u32 * 4 + col); + } + None => { + for r in 0..cx.inputs[id].e.nrows() { + d.insert(base + r * 4 + col); + } + children.push(DepNode::Val(args[2])); + } + } + } + } + InstInfo::Call(_, args) => { + children.extend(args.iter().map(|&a| DepNode::Val(a))); + } + InstInfo::Phi(list) => { + for &(x, from) in list { + children.push(DepNode::Val(x)); + children.push(DepNode::Block(from.0 as usize)); + if let Some(c) = cx.cond[from.0 as usize] { + children.push(DepNode::Val(c)); + } + } + } + InstInfo::Load(p) => { + children.push(DepNode::Val(p)); + if let Some(vs) = cx.root_stores.get(&root(cx.s, p)) { + children.extend(vs.iter().map(|&x| DepNode::Val(x))); + } + } + InstInfo::Other(ops) => { + children.extend(ops.into_iter().map(DepNode::Val)); + } + InstInfo::Store(..) | InstInfo::Term(..) => {} + } + let _ = cx.block_of; + if children.is_empty() { + Some(Sets::close(&mut st.values, v, d, st.pass, &mut st.grew)) + } else { + let first = children[0]; + stack.push(DepFrame { node: DepNode::Val(v), children, next: 1, deps: d }); + cur = first; + continue; + } + } } + _ => Some(BTreeSet::new()), + }, + }; + let mut result = ready.unwrap(); + loop { + let Some(top) = stack.last_mut() else { + return result; + }; + top.deps.extend(result); + if top.next < top.children.len() { + cur = top.children[top.next]; + top.next += 1; + break; } + let frame = stack.pop().unwrap(); + result = match frame.node { + DepNode::Block(b) => Sets::close(&mut st.blocks, b, frame.deps, st.pass, &mut st.grew), + DepNode::Val(v) => Sets::close(&mut st.values, v, frame.deps, st.pass, &mut st.grew), + }; } - InstInfo::Other(ops) => { - for x in ops { - d.extend(value_deps(cx, x, st)); - } - } - InstInfo::Store(..) | InstInfo::Term(..) => {} } - let _ = cx.block_of; - Sets::close(&mut st.values, v, d, st.pass, &mut st.grew) + } + fn block_deps(cx: &Cx, b: usize, st: &mut Sets) -> BTreeSet { + eval_dep(cx, DepNode::Block(b), st) + } + fn value_deps(cx: &Cx, v: Value, st: &mut Sets) -> BTreeSet { + eval_dep(cx, DepNode::Val(v), st) } let cx = Cx { s, block_of: &block_of, ctrl: &ctrl, cond: &cond, root_stores: &root_stores, in_base: &in_base, inputs }; diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs index c8f3802053..3b87906f14 100644 --- a/crates/xcl/src/gpu/dxil/graphics_tests.rs +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -1236,3 +1236,42 @@ fn ps_static_resources_match_dxc() { assert_eq!(part(&c, b"SFI0"), part(DXC_PS_RESOURCES, b"SFI0")); assert_valid(&c); } + +#[test] +fn deep_phi_deps_do_not_overflow_stack() { + let handle = std::thread::Builder::new() + .name("dxil-graphics-deps-test".into()) + .stack_size(2 * 1024 * 1024) + .spawn(|| { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let pos = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let x = io.load_input(&mut s, pos, 0, 0); + let f32 = s.m.f32(); + let one = f(&mut s, 1.0); + let cond = s.m.i1c(true); + let mut cur_val = x; + for _ in 0..4000 { + let prev_b = s.m.current_block(); + let then_b = s.m.new_block(); + let join_b = s.m.new_block(); + s.m.cond_br(cond, then_b, join_b); + s.m.set_block(then_b); + let added = s.m.fbin(BinOp::Add, cur_val, one, 0); + s.m.br(join_b); + s.m.set_block(join_b); + let phi = s.m.phi(f32); + s.m.add_incoming(phi, cur_val, prev_b); + s.m.add_incoming(phi, added, then_b); + cur_val = phi; + } + for c in 0..4u8 { + io.store_output(&mut s, tgt, 0, c, cur_val); + } + let c = s.try_finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }).expect("graphics finish"); + assert_valid(&c); + }) + .expect("spawn bounded-stack thread"); + handle.join().expect("graphics compute_deps overflowed or panicked"); +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..89ba8d4593 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -938,3 +938,34 @@ fn geom_init(lw: &mut Lw, g: &GsInterface, _tid: Value, io: super::shader::RawUa lw.wr(base, none); lw.geom = Some(super::lower_geom::GeomCtx { g: g.clone(), emitted, strip, ntri, base, tri, maxt, rec }); } + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + #[test] + fn deep_branch_chain_compiles_on_bounded_stack() { + let mut code = Vec::new(); + // Define v1 before a 4,000-diamond chain of conditional branches, then read v1 after. + code.extend(encode("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)], None).unwrap()); + code.extend(encode("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None).unwrap()); + let br = encode("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap(); + let body = encode("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 130)], None).unwrap(); + for _ in 0..4000 { + code.extend_from_slice(&br); + code.extend_from_slice(&body); + } + code.extend(encode("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 257), ("VSRC1", 2)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let o = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let handle = std::thread::Builder::new() + .name("dxil-deep-branch-test".into()) + .stack_size(2 * 1024 * 1024) + .spawn(move || translate_on_this_thread(&code, o, Entry::Kernel, Some(false), None, crate::gpu::dxil::compact::TABLE_WORDS_WAVE32)) + .expect("spawn bounded-stack thread"); + let k = handle.join().expect("translator thread panicked").expect("translation failed"); + assert!(!k.dxil.is_empty()); + } +} diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 230a59f9f9..b032d14ad2 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -84,15 +84,14 @@ impl Module { n.starts_with("dx.op.wave") || n.starts_with("dx.op.quad") } - fn is_const_global_ptr(&self, v: Value) -> bool { - match v { - Value::Global(g) => self.globals[g as usize].constant, - Value::Inst(i) => match &self.insts[i as usize].op { - Op::Gep(base, _) => self.is_const_global_ptr(*base), - _ => false, - }, - _ => false, + fn is_const_global_ptr(&self, mut v: Value) -> bool { + while let Value::Inst(i) = v { + match &self.insts[i as usize].op { + Op::Gep(base, _) => v = *base, + _ => return false, + } } + matches!(v, Value::Global(g) if self.globals[g as usize].constant) } fn cse_kind(&self, op: &Op) -> Cse { diff --git a/crates/xcl/src/gpu/dxil/ssa.rs b/crates/xcl/src/gpu/dxil/ssa.rs index 2ebd42fb90..2b743f79c7 100644 --- a/crates/xcl/src/gpu/dxil/ssa.rs +++ b/crates/xcl/src/gpu/dxil/ssa.rs @@ -155,73 +155,123 @@ impl Ssa { /// The definition of `var` reaching the current end of block `b`. pub fn read(&mut self, s: &mut Shader, b: Block, var: u32, init: &mut dyn FnMut(&mut Shader, u32) -> Value) -> Value { - if let Some(&v) = self.at(b).defs.get(&var) { - return v; + struct Frame { + chain: Vec, + b: Block, + preds: Vec, + vals: Vec, } - // chains of sealed single-predecessor blocks (guarded memory accesses make long ones) - // are walked iteratively, not recursively - let mut chain = Vec::new(); - let mut b = b; + let mut stack: Vec = Vec::new(); + let mut cur = b; loop { - let sb = self.at(b); - if !sb.sealed || sb.preds.len() != 1 || sb.region.as_ref().is_some_and(|(_, w)| w.binary_search(&var).is_ok()) { - break; - } - chain.push(b); - b = sb.preds[0]; - if let Some(&v) = self.at(b).defs.get(&var) { + let resolved = if let Some(&v) = self.at(cur).defs.get(&var) { + Some(v) + } else { + // chains of sealed single-predecessor blocks (guarded memory accesses make long ones) + // are walked iteratively, not recursively + let mut chain = Vec::new(); + let mut b = cur; + let hit = loop { + let sb = self.at(b); + if !sb.sealed || sb.preds.len() != 1 || sb.region.as_ref().is_some_and(|(_, w)| w.binary_search(&var).is_ok()) { + break None; + } + chain.push(b); + b = sb.preds[0]; + if let Some(&v) = self.at(b).defs.get(&var) { + break Some(v); + } + }; + if let Some(v) = hit { for c in chain { - self.cache(c, var, v); - } - return v; - } - } - if !chain.is_empty() { - let v = self.read(s, b, var, init); - for c in chain { - self.cache(c, var, v); - } - return v; - } - let v = if !self.at(b).sealed { - let ty = self.ty; - let phi = s.m.phi_at(b, ty); - self.at(b).incomplete.push((var, phi)); - phi - } else { - let preds = self.preds_of(b, var); - match preds.len() { - 0 => init(s, var), - 1 => self.read(s, preds[0], var, init), - _ => { - // the operands first, without a phi: most joins a read walks through - // (guarded accesses make thousands) see one value from every edge - // (Braun et al.'s trivial phi) and need none. A read that comes back - // here around a loop gets a phi, which then stays. - let key = (b.0, var); - if let Some(slot) = self.visiting.get(&key).copied() { - let phi = slot.unwrap_or_else(|| s.m.detached_phi(self.ty)); - self.visiting.insert(key, Some(phi)); - return phi; + self.cache(c, var, v); + } + Some(v) + } else if !self.at(b).sealed { + let ty = self.ty; + let phi = s.m.phi_at(b, ty); + self.at(b).incomplete.push((var, phi)); + self.cache(b, var, phi); + for c in chain { + self.cache(c, var, phi); } - self.visiting.insert(key, None); - let vals: Vec = preds.iter().map(|&p| self.read(s, p, var, init)).collect(); + Some(phi) + } else { + let preds = self.preds_of(b, var); + match preds.len() { + 0 => { + let v = init(s, var); + self.cache(b, var, v); + for c in chain { + self.cache(c, var, v); + } + Some(v) + } + 1 => { + let next = preds[0]; + stack.push(Frame { chain, b, preds, vals: Vec::with_capacity(1) }); + cur = next; + continue; + } + _ => { + // the operands first, without a phi: most joins a read walks through + // (guarded accesses make thousands) see one value from every edge + // (Braun et al.'s trivial phi) and need none. A read that comes back + // here around a loop gets a phi, which then stays. + let key = (b.0, var); + if let Some(slot) = self.visiting.get(&key).copied() { + let phi = slot.unwrap_or_else(|| s.m.detached_phi(self.ty)); + self.visiting.insert(key, Some(phi)); + for c in chain { + self.cache(c, var, phi); + } + Some(phi) + } else { + self.visiting.insert(key, None); + let next = preds[0]; + let cap = preds.len(); + stack.push(Frame { chain, b, preds, vals: Vec::with_capacity(cap) }); + cur = next; + continue; + } + } + } + } + }; + + let mut val = resolved.unwrap(); + loop { + let Some(top) = stack.last_mut() else { + return val; + }; + top.vals.push(val); + if top.vals.len() < top.preds.len() { + cur = top.preds[top.vals.len()]; + break; + } + let frame = stack.pop().unwrap(); + val = if frame.preds.len() == 1 { + frame.vals[0] + } else { + let key = (frame.b.0, var); let marker = self.visiting.remove(&key).flatten(); - if marker.is_none() && vals.iter().all(|&v| v == vals[0]) { - vals[0] + if marker.is_none() && frame.vals.iter().all(|&v| v == frame.vals[0]) { + frame.vals[0] } else { let phi = marker.unwrap_or_else(|| s.m.detached_phi(self.ty)); - for (&v, &p) in vals.iter().zip(&preds) { + for (&v, &p) in frame.vals.iter().zip(&frame.preds) { s.m.add_incoming(phi, v, p); } - s.m.place_phi(b, phi); + s.m.place_phi(frame.b, phi); phi } + }; + self.cache(frame.b, var, val); + for c in frame.chain { + self.cache(c, var, val); } } - }; - self.cache(b, var, v); - v + } } fn add_operands(&mut self, s: &mut Shader, phi: Value, preds: &[Block], var: u32, init: &mut dyn FnMut(&mut Shader, u32) -> Value) { @@ -243,3 +293,141 @@ impl Ssa { self.at(b).sealed = true; } } + +#[cfg(test)] +mod tests { + use super::super::container::Stage; + use super::super::module::BinOp; + use super::*; + + #[test] + fn deep_join_chain_does_not_overflow_stack() { + let handle = std::thread::Builder::new() + .name("ssa-deep-join-test".into()) + .stack_size(2 * 1024 * 1024) + .spawn(|| { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let i32_ty = s.m.i32(); + let mut ssa = Ssa::new(i32_ty); + let mut init = |sh: &mut Shader, _v: u32| sh.m.i32c(0); + + let entry = Block(0); + ssa.expect_preds(&mut s, entry, 0, &mut init); + let initial = s.m.i32c(42); + ssa.write(entry, 0, initial); + let cond = s.m.i1c(true); + let one = s.m.i32c(1); + + // 4,000 sequential if/else diamonds: var 0 is untouched across the chain, + // var 1 is updated on one arm of each diamond so non-trivial phis form. + ssa.write(entry, 1, initial); + let mut cur = entry; + for _ in 0..4000 { + let then_b = s.m.new_block(); + let else_b = s.m.new_block(); + let join_b = s.m.new_block(); + ssa.expect_preds(&mut s, then_b, 1, &mut init); + ssa.expect_preds(&mut s, else_b, 1, &mut init); + ssa.expect_preds(&mut s, join_b, 2, &mut init); + + s.m.set_block(cur); + s.m.cond_br(cond, then_b, else_b); + ssa.add_pred(&mut s, then_b, cur, &mut init); + ssa.add_pred(&mut s, else_b, cur, &mut init); + + s.m.set_block(then_b); + let prev = ssa.read(&mut s, then_b, 1, &mut init); + let next = s.m.bin(BinOp::Add, prev, one); + ssa.write(then_b, 1, next); + s.m.br(join_b); + ssa.add_pred(&mut s, join_b, then_b, &mut init); + + s.m.set_block(else_b); + s.m.br(join_b); + ssa.add_pred(&mut s, join_b, else_b, &mut init); + + cur = join_b; + } + + s.m.set_block(cur); + let got_unmodified = ssa.read(&mut s, cur, 0, &mut init); + assert_eq!(got_unmodified, initial); + let got_modified = ssa.read(&mut s, cur, 1, &mut init); + assert_ne!(got_modified, initial); + s.m.ret(); + let bc = s.try_finish([1, 1, 1], None).expect("valid DXIL"); + assert!(!bc.is_empty()); + }) + .expect("spawn bounded-stack thread"); + handle.join().expect("deep join chain overflowed or panicked"); + } + + #[test] + fn deep_region_join_and_loop_phi_preserve_semantics() { + let handle = std::thread::Builder::new() + .name("ssa-region-loop-test".into()) + .stack_size(2 * 1024 * 1024) + .spawn(|| { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let i32_ty = s.m.i32(); + let mut ssa = Ssa::new(i32_ty); + let mut init = |sh: &mut Shader, _v: u32| sh.m.i32c(0); + + let entry = Block(0); + ssa.expect_preds(&mut s, entry, 0, &mut init); + let v0 = s.m.i32c(7); + let v1 = s.m.i32c(9); + ssa.write(entry, 0, v0); + ssa.write(entry, 1, v1); + let cond = s.m.i1c(true); + let one = s.m.i32c(1); + + // Loop header (unsealed until back-edge) followed by 3,000 region joins. + let hdr = s.m.new_block(); + s.m.set_block(entry); + s.m.br(hdr); + ssa.add_pred(&mut s, hdr, entry, &mut init); + + let mut cur = hdr; + for _ in 0..3000 { + let then_b = s.m.new_block(); + let join_b = s.m.new_block(); + s.m.set_block(cur); + s.m.cond_br(cond, then_b, join_b); + ssa.expect_preds(&mut s, then_b, 1, &mut init); + ssa.add_pred(&mut s, then_b, cur, &mut init); + s.m.set_block(then_b); + ssa.begin_log(); + let x = ssa.read(&mut s, then_b, 1, &mut init); + let x1 = s.m.bin(BinOp::Add, x, one); + ssa.write(then_b, 1, x1); + let written = ssa.end_log(); + s.m.br(join_b); + ssa.seal_region_join(join_b, cur, then_b, written); + cur = join_b; + } + + s.m.set_block(cur); + let back_val = ssa.read(&mut s, cur, 0, &mut init); + let next0 = s.m.bin(BinOp::Add, back_val, one); + ssa.write(cur, 0, next0); + let exit = s.m.new_block(); + ssa.expect_preds(&mut s, exit, 1, &mut init); + s.m.cond_br(cond, hdr, exit); + ssa.add_pred(&mut s, hdr, cur, &mut init); + ssa.seal(&mut s, hdr, &mut init); + ssa.add_pred(&mut s, exit, cur, &mut init); + + s.m.set_block(exit); + let final0 = ssa.read(&mut s, exit, 0, &mut init); + assert_ne!(final0, v0); + let final1 = ssa.read(&mut s, exit, 1, &mut init); + assert_ne!(final1, v1); + s.m.ret(); + let bc = s.try_finish([1, 1, 1], None).expect("valid DXIL"); + assert!(!bc.is_empty()); + }) + .expect("spawn bounded-stack thread"); + handle.join().expect("region join + loop test failed"); + } +} From 2a6feac29252a49af8553ed459f71b00883cde6d Mon Sep 17 00:00:00 2001 From: fixgep <2011slatin@gmail.com> Date: Wed, 25 Nov 2026 02:59:22 +0300 Subject: [PATCH 2/2] Direct DXIL: borrow store lists with cursor in compute_deps Avoid cloning the per-root store list into every live DepFrame in eval_dep by borrowing the shared slice with a usize cursor, preventing quadratic child storage on deep load/store chains. Assisted-by: Antigravity (Gemini 4 Hydrogen) --- crates/xcl/src/gpu/dxil/graphics.rs | 133 ++++++++++++++++------ crates/xcl/src/gpu/dxil/graphics_tests.rs | 62 ++++++++++ 2 files changed, 158 insertions(+), 37 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index a191b4bb4f..dd3a397002 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -643,6 +643,10 @@ struct Deps { /// Input components each value depends on, through data flow, memory and /// control dependence (as DXC's `ComputeViewIdState`). fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Placed]) -> Deps { + compute_deps_with_peak(s, inputs, outputs, prims).0 +} + +fn compute_deps_with_peak(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Placed]) -> (Deps, usize) { let m = &s.m; let nb = m.block_count(); // Successors and the branch condition of each block. @@ -829,14 +833,46 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac Block(usize), Val(Value), } - struct DepFrame { + enum DepChildren<'a> { + List { items: Vec, next: usize }, + Values { items: &'a [Value], next: usize }, + } + impl<'a> DepChildren<'a> { + fn next_child(&mut self) -> Option { + match self { + Self::List { items, next } => { + let c = items.get(*next).copied()?; + *next += 1; + Some(c) + } + Self::Values { items, next } => { + let &v = items.get(*next)?; + *next += 1; + Some(DepNode::Val(v)) + } + } + } + + fn owned_len(&self) -> usize { + match self { + Self::List { items, .. } => items.len(), + Self::Values { .. } => 0, + } + } + } + struct DepFrame<'a> { node: DepNode, - children: Vec, - next: usize, + children: DepChildren<'a>, deps: BTreeSet, } - fn eval_dep(cx: &Cx, start: DepNode, st: &mut Sets) -> BTreeSet { - let mut stack: Vec = Vec::new(); + fn eval_dep<'a>( + cx: &Cx<'a>, + start: DepNode, + st: &mut Sets, + peak_children: &mut usize, + ) -> BTreeSet { + let mut stack: Vec> = Vec::new(); + let mut live_children = 0usize; let mut cur = start; loop { let ready: Option> = match cur { @@ -858,7 +894,10 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac Some(Sets::close(&mut st.blocks, b, BTreeSet::new(), st.pass, &mut st.grew)) } else { let first = children[0]; - stack.push(DepFrame { node: DepNode::Block(b), children, next: 1, deps: BTreeSet::new() }); + let children = DepChildren::List { items: children, next: 1 }; + live_children += children.owned_len(); + *peak_children = (*peak_children).max(live_children); + stack.push(DepFrame { node: DepNode::Block(b), children, deps: BTreeSet::new() }); cur = first; continue; } @@ -872,7 +911,8 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac Sets::open(&mut st.values, v); let m = &cx.s.m; let mut d = BTreeSet::new(); - let mut children = Vec::new(); + let mut list = Vec::new(); + let mut first_and_rest: Option<(DepNode, DepChildren<'a>)> = None; match m.inst_info(i) { InstInfo::Call(name, args) if name.starts_with("dx.op.loadInput.") => { let id = m.const_u64(args[1]).unwrap() as usize; @@ -886,42 +926,50 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac for r in 0..cx.inputs[id].e.nrows() { d.insert(base + r * 4 + col); } - children.push(DepNode::Val(args[2])); + list.push(DepNode::Val(args[2])); } } } } InstInfo::Call(_, args) => { - children.extend(args.iter().map(|&a| DepNode::Val(a))); + if let Some((&first, rest)) = args.split_first() { + first_and_rest = Some((DepNode::Val(first), DepChildren::Values { items: rest, next: 0 })); + } } - InstInfo::Phi(list) => { - for &(x, from) in list { - children.push(DepNode::Val(x)); - children.push(DepNode::Block(from.0 as usize)); + InstInfo::Phi(phi_list) => { + for &(x, from) in phi_list { + list.push(DepNode::Val(x)); + list.push(DepNode::Block(from.0 as usize)); if let Some(c) = cx.cond[from.0 as usize] { - children.push(DepNode::Val(c)); + list.push(DepNode::Val(c)); } } } InstInfo::Load(p) => { - children.push(DepNode::Val(p)); - if let Some(vs) = cx.root_stores.get(&root(cx.s, p)) { - children.extend(vs.iter().map(|&x| DepNode::Val(x))); - } + let stores = cx.root_stores.get(&root(cx.s, p)).map(Vec::as_slice).unwrap_or(&[]); + first_and_rest = Some((DepNode::Val(p), DepChildren::Values { items: stores, next: 0 })); } InstInfo::Other(ops) => { - children.extend(ops.into_iter().map(DepNode::Val)); + list.extend(ops.into_iter().map(DepNode::Val)); } InstInfo::Store(..) | InstInfo::Term(..) => {} } let _ = cx.block_of; - if children.is_empty() { - Some(Sets::close(&mut st.values, v, d, st.pass, &mut st.grew)) - } else { - let first = children[0]; - stack.push(DepFrame { node: DepNode::Val(v), children, next: 1, deps: d }); - cur = first; - continue; + if first_and_rest.is_none() && !list.is_empty() { + let first = list[0]; + first_and_rest = Some((first, DepChildren::List { items: list, next: 1 })); + } + match first_and_rest { + None => { + Some(Sets::close(&mut st.values, v, d, st.pass, &mut st.grew)) + } + Some((first, children)) => { + live_children += children.owned_len(); + *peak_children = (*peak_children).max(live_children); + stack.push(DepFrame { node: DepNode::Val(v), children, deps: d }); + cur = first; + continue; + } } } } @@ -934,12 +982,12 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac return result; }; top.deps.extend(result); - if top.next < top.children.len() { - cur = top.children[top.next]; - top.next += 1; + if let Some(next_node) = top.children.next_child() { + cur = next_node; break; } let frame = stack.pop().unwrap(); + live_children -= frame.children.owned_len(); result = match frame.node { DepNode::Block(b) => Sets::close(&mut st.blocks, b, frame.deps, st.pass, &mut st.grew), DepNode::Val(v) => Sets::close(&mut st.values, v, frame.deps, st.pass, &mut st.grew), @@ -947,15 +995,26 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac } } } - fn block_deps(cx: &Cx, b: usize, st: &mut Sets) -> BTreeSet { - eval_dep(cx, DepNode::Block(b), st) + fn block_deps<'a>( + cx: &Cx<'a>, + b: usize, + st: &mut Sets, + peak_children: &mut usize, + ) -> BTreeSet { + eval_dep(cx, DepNode::Block(b), st, peak_children) } - fn value_deps(cx: &Cx, v: Value, st: &mut Sets) -> BTreeSet { - eval_dep(cx, DepNode::Val(v), st) + fn value_deps<'a>( + cx: &Cx<'a>, + v: Value, + st: &mut Sets, + peak_children: &mut usize, + ) -> BTreeSet { + eval_dep(cx, DepNode::Val(v), st, peak_children) } let cx = Cx { s, block_of: &block_of, ctrl: &ctrl, cond: &cond, root_stores: &root_stores, in_base: &in_base, inputs }; let mut out: HashMap<(u8, u32), BTreeSet> = HashMap::new(); + let mut peak_children = 0usize; let bases = |p: &[Placed]| -> Vec> { p.iter().map(|e| e.at.map(|(r, c)| r * 4 + c as u32)).collect() }; let (ob, pb) = (bases(outputs), bases(prims)); // (code without a loop is done after one pass: nothing was cut) @@ -976,10 +1035,10 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac let Some(base) = base[id] else { continue }; let col = m.const_u64(args[3]).unwrap() as u32; let row = m.const_u64(args[2]).unwrap() as u32; - let mut d = value_deps(&cx, args[4], &mut sets); - d.extend(block_deps(&cx, b, &mut sets)); + let mut d = value_deps(&cx, args[4], &mut sets, &mut peak_children); + d.extend(block_deps(&cx, b, &mut sets, &mut peak_children)); if args.len() > 5 { - d.extend(value_deps(&cx, args[5], &mut sets)); + d.extend(value_deps(&cx, args[5], &mut sets, &mut peak_children)); } out.entry((dir, base + row * 4 + col)).or_default().extend(d); } @@ -988,7 +1047,7 @@ fn compute_deps(s: &Shader, inputs: &[Placed], outputs: &[Placed], prims: &[Plac break; } } - Deps { out } + (Deps { out }, peak_children) } /// The global (or other base) a pointer is derived from. diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs index 3b87906f14..247b119c86 100644 --- a/crates/xcl/src/gpu/dxil/graphics_tests.rs +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -1275,3 +1275,65 @@ fn deep_phi_deps_do_not_overflow_stack() { .expect("spawn bounded-stack thread"); handle.join().expect("graphics compute_deps overflowed or panicked"); } + +fn ps_shared_root_load_store_chain(steps: u32) -> (Shader, GraphicsIo) { + let mut s = Shader::new(Stage::Pixel, (6, 6)); + let mut io = GraphicsIo::new(Stage::Pixel); + let pos = io.input(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let _unused = io.input(SigElement::user("TEXCOORD", 0, CompType::F32, 1)); + let tgt = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::F32, 4)); + let x = io.load_input(&mut s, pos, 0, 0); + let f32 = s.m.f32(); + let arr_ty = s.m.array(u64::from(steps) + 1, f32); + let arr = s.m.alloca(arr_ty, 4); + let zero = s.m.i32c(0); + let one = f(&mut s, 1.0); + let p0 = s.m.gep(arr, &[zero, zero]); + s.m.store(p0, x, 4); + for k in 0..steps { + let idx = s.m.i32c(k); + let pk = s.m.gep(arr, &[zero, idx]); + let ld = s.m.load(pk, 4); + let next = s.m.fbin(BinOp::Add, ld, one, 0); + let next_idx = s.m.i32c(k + 1); + let p_next = s.m.gep(arr, &[zero, next_idx]); + s.m.store(p_next, next, 4); + } + let last_idx = s.m.i32c(steps); + let plast = s.m.gep(arr, &[zero, last_idx]); + let out = s.m.load(plast, 4); + for c in 0..4u8 { + io.store_output(&mut s, tgt, 0, c, out); + } + (s, io) +} + +#[test] +fn deep_shared_root_loads_borrow_store_list_without_quadratic_children() { + let handle = std::thread::Builder::new() + .name("dxil-graphics-load-store-deps-test".into()) + .stack_size(2 * 1024 * 1024) + .spawn(|| { + const STEPS: u32 = 1024; + let (mut s, io) = ps_shared_root_load_store_chain(STEPS); + s.m.ret(); + s.m.optimize(); + let ins = io.place(Dir::In); + let outs = io.place(Dir::Out); + let prims = io.place(Dir::Prim); + let (deps, peak_live_children) = compute_deps_with_peak(&s, &ins, &outs, &prims); + for c in 0..4u32 { + assert_eq!(deps.out.get(&(0, c)).map(|d| d.iter().copied().collect::>()), Some(vec![0])); + } + assert!( + peak_live_children <= (STEPS as usize) * 4, + "expected linear live child storage, got {peak_live_children} for {STEPS} steps" + ); + + let (s, io) = ps_shared_root_load_store_chain(STEPS); + let c = s.try_finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }).expect("graphics finish"); + assert_valid(&c); + }) + .expect("spawn bounded-stack thread"); + handle.join().expect("graphics shared-root load/store test overflowed or panicked"); +}