From 9a257e16cb313a7951348adea4fb2f961863c1ca Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:52:02 -0500 Subject: [PATCH 1/8] Recompiler: split large direct compute pipelines at CFG edges Keep control-flow cycles in one pipeline, pass edge-live values through per-dispatch scratch and compile the pieces on the PSO workers. Direct dispatch records the chain with UAV ordering. Indirect dispatch builds the whole form on demand. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- README.md | 3 + crates/xcl/src/gpu/dxil/kernel.rs | 25 +- crates/xcl/src/gpu/dxil/module.rs | 3 + crates/xcl/src/gpu/dxil/module/opt.rs | 2 +- crates/xcl/src/gpu/dxil/module/split.rs | 646 ++++++++++++++++++ crates/xcl/src/gpu/dxil/shader.rs | 18 + crates/xcl/src/gpu/recomp/pso.rs | 115 +++- crates/xcl/src/gpu/recomp/runner.rs | 35 +- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 4 +- crates/xcl/src/hle/d3d12x/bind.rs | 14 +- crates/xcl/src/hle/d3d12x/console_list.rs | 2 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 71 +- crates/xcl/src/hle/d3d12x/real.rs | 99 ++- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 148 ++++ crates/xcl/src/host.rs | 4 + crates/xcl/src/shaders.rs | 2 +- 16 files changed, 1108 insertions(+), 83 deletions(-) create mode 100644 crates/xcl/src/gpu/dxil/module/split.rs create mode 100644 crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs diff --git a/README.md b/README.md index d9d151320..3a6b2114c 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - **The game folder is never modified** – writes go to the overlay. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. +- Direct compute dispatches can split large programs into pipelines built in parallel. + `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, + zero disables splitting). Loops stay in one piece. Indirect dispatches use the whole pipeline. - Huge pipelines (translated DXIL of `XCL_HUGE_PSO_BYTES` or more, default 262144) built on the background `xcl-pso*` workers take turns in the driver's compiler: `XCL_HUGE_PSO_CONCURRENCY` at once (default 1, maximum 64). Pipelines of 4 MiB or more use a separate one-wide lane so diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 8687e4807..e612bda32 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -65,6 +65,13 @@ pub fn translate(code: &[u8], o: KernelOptions) -> Result, String> { pub struct Kernel { pub dxil: Vec, pub static_samplers: Vec<([u32; 4], bool)>, + pub dispatch_chain: Option>, +} + +pub use super::module::split::DispatchChain; + +pub fn dispatch_piece_limit() -> usize { + std::env::var("XCL_DIRECT_SPLIT_INSTRUCTIONS").ok().and_then(|s| s.parse().ok()).unwrap_or(12_500) } /// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset leaves it to `compact::wanted`. @@ -197,6 +204,7 @@ fn translate_on_this_thread( let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); + let mut split_tid = None; let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -209,6 +217,7 @@ fn translate_on_this_thread( } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); + if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } compute_init(&mut lw, cs, tid, gtid); cs.threads } @@ -422,7 +431,8 @@ fn translate_on_this_thread( lw.s.m.set_block(Block(0)); lw.s.m.br(h0); let hw = if split || !o.wave64 { 32 } else { 64 }; - lw.finish(numthreads, hw) + let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; + lw.finish_dispatch(numthreads, hw, limit, split_tid) } /// True when a pixel shader uses RDNA2 Primitive Ordered Pixel Shading (POPS): @@ -588,15 +598,24 @@ impl Lw { /// The finished container and the static samplers the program bound, once every block /// is closed: `numthreads` and the hardware wave size `hw` for a compute-like entry, the /// stage's I/O for a VS / PS. - pub fn finish(mut self, numthreads: [u32; 3], hw: u32) -> Result { + pub fn finish(self, numthreads: [u32; 3], hw: u32) -> Result { + self.finish_dispatch(numthreads, hw, 0, None) + } + + fn finish_dispatch(mut self, numthreads: [u32; 3], hw: u32, limit: usize, split_tid: Option) -> Result { if let Some(e) = self.exchange_error.take() { return Err(e); } let stage = self.s.stage; + let mut dispatch_chain = None; let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; self.s.try_finish_graphics(g.io, info) + } else if limit > 0 && (numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32 { + self.s.m.optimize(); + dispatch_chain = self.s.split_compute(numthreads, split_tid, limit).map(std::sync::Arc::new); + self.s.finish_optimized(numthreads, Some(hw)) } else { self.s.try_finish(numthreads, Some(hw)) } @@ -607,7 +626,7 @@ impl Lw { return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); } } - Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect() }) + Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect(), dispatch_chain }) } } diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index f2930cd7e..cc85589f5 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; use super::bitstream::{signed, BitWriter}; mod opt; +pub(super) mod split; // ---------------------------------------------------------------- types @@ -59,6 +60,7 @@ enum ConstDef { Aggregate(Ty, Vec), } +#[derive(Clone)] struct FuncDecl { name: String, ty: Ty, @@ -93,6 +95,7 @@ impl FnAttrs { } } +#[derive(Clone)] struct GlobalDef { name: String, /// Value type (the global itself is a pointer to it). diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 7a3454d53..e411877c2 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -41,7 +41,7 @@ impl Op { } /// Rewrites every value operand through `f`. - fn map_operands(&mut self, mut f: impl FnMut(Value) -> Value) { + pub(super) fn map_operands(&mut self, mut f: impl FnMut(Value) -> Value) { match self { Op::Bin(_, a, b, _) | Op::Cmp(_, a, b) | Op::Store(a, b, _) | Op::AtomicRmw(_, a, b) => { *a = f(*a); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs new file mode 100644 index 000000000..8925e5659 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -0,0 +1,646 @@ +//! Partition the optimized compute entry at CFG edges. A dispatch cannot +//! jump back to an earlier dispatch, so a strongly connected component is +//! indivisible. Each crossing edge has its own compact state layout. + +use std::collections::{BTreeSet, HashMap, HashSet}; + +use super::{BinOp, Block, CastOp, Module, Op, TypeDef, Value}; +use crate::gpu::dxil::shader::{Feature, RawUav, Shader}; + +#[derive(Debug)] +pub(crate) struct Edge { + pub from: Block, + pub to: Block, + pub live: Vec, +} + +pub(crate) struct Plan { + pub blocks: Vec>, + pub edges: Vec, +} + +#[derive(Clone)] +pub struct DispatchChain { + pub pieces: Vec>, + pub dwords_per_group: u32, +} + +struct Scratch { + uav: RawUav, + base: Value, +} + +impl Scratch { + fn new(s: &mut Shader, stride: u32, threads: u32, lane: Value) -> Self { + let uav = s.raw_uav(0, 2); + let cb = s.cbv(0, 2, 16); + let zero = s.m.i32c(0); + let ty = s.m.i32(); + let [width, height, _, _] = s.cbuffer_load_legacy(cb, zero, ty); + let [x, y, z] = [0, 1, 2].map(|axis| s.group_id(axis)); + let row = s.m.bin(BinOp::Mul, z, height); + let row = s.m.bin(BinOp::Add, row, y); + let first = s.m.bin(BinOp::Mul, row, width); + let group = s.m.bin(BinOp::Add, first, x); + let n = s.m.i32c(threads); + let first = s.m.bin(BinOp::Mul, group, n); + let index = s.m.bin(BinOp::Add, first, lane); + let bytes = s.m.i32c(stride * 4); + Self { uav, base: s.m.bin(BinOp::Mul, index, bytes) } + } + + fn at(&self, m: &mut Module, slot: u32) -> Value { + let offset = m.i32c(slot * 4); + m.bin(BinOp::Add, self.base, offset) + } +} + +impl Shader { + /// Start with full native wave32 groups. A fresh dispatch can assign a + /// different physical wave to a group; wave-lane index identifies the + /// continuation within a full, single-wave group. + pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { + if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { + return None; + } + if self.m.blocks.iter().map(Vec::len).sum::() <= limit { return None; } + let mut prefix = Vec::new(); + if let Some(tid) = split_tid { + let end = self.m.blocks[0].iter().position(|&i| Value::Inst(i) == tid)?; + prefix.extend_from_slice(&self.m.blocks[0][..=end]); + } + let mut consumed = HashSet::new(); + for &i in self.m.blocks.iter().flatten() { + self.m.insts[i as usize].op.for_each_operand(|v| { consumed.insert(v); }); + } + for (b, block) in self.m.blocks.iter().enumerate() { + // In a single split console wave each inter-half exchange begins + // with TGSM stores, one rendezvous, peer loads and a rendezvous. + // A block ending anywhere inside that sequence cannot be a cut. + let mut exchange = 0; + for &i in block { + if b == 0 && prefix.contains(&i) { continue; } + match &self.m.insts[i as usize].op { + Op::Alloca(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => return None, + Op::Store(..) if split_tid.is_some() && exchange <= 1 => exchange = 1, + Op::Load(p, _) if self.m.global_root(*p).is_some_and(|g| self.m.globals[g].constant) => {} + Op::Load(..) if split_tid.is_some() && matches!(exchange, 2 | 3) => exchange = 3, + Op::Load(..) | Op::Store(..) => return None, + Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.barrier" + && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64) => { + exchange = match exchange { 1 => 2, 3 => 0, _ => return None }; + } + // Sub-dword stores use interlocked AND/OR. They return an + // old word that nobody observes; every write stays in place. + Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.atomicBinOp.i32" + && matches!(self.m.const_u64(args[2]), Some(1 | 2)) + && !consumed.contains(&Value::Inst(i)) => {} + Op::Call(f, _) if ["dx.op.barrier", "dx.op.atomic"].iter().any(|p| self.m.funcs[*f as usize].name.starts_with(p)) => return None, + _ => {} + } + } + if exchange != 0 { return None; } + } + let plan = self.m.dispatch_plan(limit)?; + let mut stride = 1; + for edge in &plan.edges { + let mut words = 1; + for &v in &edge.live { + words += self.m.transport_words(v)?; + } + stride = stride.max(words); + } + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix)).collect::>>()?; + Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) + } + + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, threads: [u32; 3], prefix: &[u32]) -> Option> { + let src = &self.m; + let mut dst = self.dispatch_piece(); + let mut values = HashMap::new(); + for &id in prefix { + let def = &src.insts[id as usize]; + let mut op = def.op.clone(); + op.map_operands(|v| *values.get(&v).unwrap_or(&v)); + values.insert(Value::Inst(id), dst.m.push(op, def.ty)); + } + let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); + let scratch = Scratch::new(&mut dst, stride, threads[0], lane); + let local: HashMap<_, _> = plan.blocks[stage].iter().map(|&b| (b, dst.m.new_block())).collect(); + let mut hops = HashMap::new(); + let mut exits = HashMap::new(); + let mut cases = Vec::new(); + let mut paths = Vec::new(); + let mut incoming = std::collections::BTreeMap::, Block)>>::new(); + let mut statics = BTreeSet::new(); + let merge = dst.m.new_block(); + let done = dst.m.new_block(); + let selector = if stage != 0 { Some(dst.raw_load(scratch.uav, scratch.base, 1)[0]) } else { None }; + for (index, edge) in plan.edges.iter().enumerate() { + let tag = dst.m.i32c(index as u32 + 1); + if local.contains_key(&edge.from) { + exits.insert((edge.from, edge.to), (dst.m.new_block(), tag)); + } + if let Some(&target) = local.get(&edge.to) { + let bridge = dst.m.new_block(); + dst.m.set_block(bridge); + let mut slot = 1; + for &v in &edge.live { + let n = src.transport_words(v)?; + if n == 0 { + statics.insert(v); + continue; + } + let at = scratch.at(&mut dst.m, slot); + let words = dst.raw_load(scratch.uav, at, if n == 2 { 3 } else { 1 }); + incoming.entry(v).or_default().push((words, bridge)); + slot += n; + } + dst.m.br(merge); + let hop = dst.m.new_block(); + dst.m.set_block(hop); + dst.m.br(target); + cases.push((tag, bridge)); + paths.push((bridge, tag, hop)); + hops.insert((edge.from, edge.to), hop); + } + } + dst.m.set_block(Block(0)); + if let Some(sel) = selector { + dst.m.switch(sel, done, &cases); + dst.m.set_block(merge); + let word = dst.m.i32(); + let mut unpack = Vec::new(); + for (original, inc) in incoming { + let mut words = Vec::new(); + for k in 0..inc[0].0.len() { + let phi = dst.m.phi(word); + for &(pred, _, _) in &paths { + let v = inc.iter().find(|p| p.1 == pred).map(|p| p.0[k]).unwrap_or_else(|| dst.m.undef(word)); + dst.m.add_incoming(phi, v, pred); + } + words.push(phi); + } + unpack.push((original, words)); + } + for (original, words) in unpack { + values.insert(original, src.unpack(original, &words, &mut dst.m)); + } + for handle in statics { + src.rebuild_static(handle, &mut dst.m, &mut values)?; + } + let routes: Vec<_> = paths.iter().map(|&(_, tag, hop)| (tag, hop)).collect(); + dst.m.switch(sel, done, &routes); + } else { + dst.m.br(local[&Block(0)]); + } + dst.m.set_block(done); + dst.m.ret(); + + // Assign all instruction identities before fixing operands. A loop's + // phi can use an instruction in a block copied later. + let mut copied = Vec::new(); + for &block in &plan.blocks[stage] { + dst.m.set_block(local[&block]); + for &i in &src.blocks[block.0 as usize] { + if block == Block(0) && prefix.contains(&i) { continue; } + let old = &src.insts[i as usize]; + if matches!(old.op, Op::Ret) && stage + 1 < plan.blocks.len() { + let zero = dst.m.i32c(0); + dst.raw_store(scratch.uav, scratch.base, &[zero]); + } + let v = dst.m.push(old.op.clone(), old.ty); + values.insert(Value::Inst(i), v); + copied.push((block, inst(v)?)); + } + } + for (block, id) in copied { + let op = &mut dst.m.insts[id].op; + let mut complete = true; + op.map_operands(|v| match v { + Value::Inst(_) => values.get(&v).copied().unwrap_or_else(|| { complete = false; v }), + _ => v, + }); + if !complete { return None; } + let target = |b: Block| local.get(&b).copied().or_else(|| exits.get(&(block, b)).map(|p| p.0)); + match op { + Op::Phi(inc) => for (_, p) in inc { + *p = *local.get(p).or_else(|| hops.get(&(*p, block)))?; + }, + Op::Br(b) => *b = target(*b)?, + Op::CondBr(_, t, f) => { *t = target(*t)?; *f = target(*f)?; } + Op::Switch(_, d, cases) => { + *d = target(*d)?; + for (_, t) in cases { *t = target(*t)?; } + } + _ => {} + } + } + for edge in &plan.edges { + let Some(&(b, tag)) = exits.get(&(edge.from, edge.to)) else { continue }; + dst.m.set_block(b); + let mut slot = 1; + for &v in &edge.live { + let n = src.transport_words(v)?; + if n != 0 { + let words = src.pack(v, *values.get(&v)?, &mut dst.m); + let at = scratch.at(&mut dst.m, slot); + dst.raw_store(scratch.uav, at, &words); + slot += n; + } + } + dst.raw_store(scratch.uav, scratch.base, &[tag]); + dst.m.ret(); + } + dst.infer_piece_features(); + // a refused piece leaves the whole program unsplit: say so + let refused = |e: String| crate::xlog_warn!("compute split: piece {} of {} refused, the program stays whole: {}", + stage + 1, plan.blocks.len(), e.lines().next().unwrap_or_default()); + let blob = dst.try_finish(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; + crate::gpu::dxil::validate::validate(&blob).map_err(refused).ok()?; + Some(blob) + } + + fn infer_piece_features(&mut self) { + for f in [Feature::Doubles, Feature::Int64Ops, Feature::DoubleExtensions, + Feature::ResourceHeapIndexing, Feature::SamplerHeapIndexing] { + self.features.remove(&f); + } + // typed UAV loads (`texture_load` without a mip): the whole program's flag stays only on + // the pieces that have one, the validator wants flags to match usage + let uav_load = |args: &[Value], m: &Module| args.get(2).is_some_and(|&mip| matches!(mip, Value::Const(c) if matches!(m.consts[c as usize], super::ConstDef::Undef(_)))); + if !self.m.blocks.iter().flatten().any(|&i| matches!(&self.m.insts[i as usize].op, + Op::Call(f, args) if self.m.funcs[*f as usize].name.starts_with("dx.op.textureLoad") && uav_load(args, &self.m))) { + self.features.remove(&Feature::TypedUavLoadAdditionalFormats); + } + for def in &self.m.insts { + if let Op::Call(f, args) = &def.op { + if self.m.funcs[*f as usize].name == "dx.op.createHandleFromHeap" { + self.features.insert(if self.m.const_u64(args[2]) == Some(0) { + Feature::ResourceHeapIndexing + } else { Feature::SamplerHeapIndexing }); + } + } + } + } +} + +fn inst(v: Value) -> Option { + if let Value::Inst(i) = v { Some(i as usize) } else { None } +} + +impl Module { + fn global_root(&self, v: Value) -> Option { + match v { + Value::Global(g) => Some(g as usize), + Value::Inst(i) => match &self.insts[i as usize].op { + Op::Gep(p, _) => self.global_root(*p), + _ => None, + }, + _ => None, + } + } + + /// Only an index is transported. Resource handles and TGSM pointers are + /// created inside the receiving dispatch, using their original properties. + fn indexed(&self, v: Value) -> Option { + let op = &self.insts[inst(v)?].op; + if let Op::Gep(Value::Global(g), indices) = op { + if self.globals[*g as usize].name == "xcl_xs" && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { + return Some(indices[1]); + } + } + if let Op::Call(f, a) = op { + if self.funcs[*f as usize].name == "dx.op.annotateHandle" && matches!(a[2], Value::Const(_)) { + if let Op::Call(create, args) = &self.insts[inst(a[1])?].op { + if self.funcs[*create as usize].name == "dx.op.createHandleFromHeap" && args[2..].iter().all(|v| matches!(v, Value::Const(_))) { + return Some(args[1]); + } + } + } + } + None + } + + fn transport_words(&self, v: Value) -> Option { + let def = &self.insts[inst(v)?]; + match &self.types[def.ty.0 as usize] { + TypeDef::Int(1..=32) | TypeDef::Float => Some(1), + TypeDef::Int(64) => Some(2), + TypeDef::Struct(..) if self.static_handle(v) => Some(0), + _ if self.indexed(v).is_some() => Some(1), + _ => None, + } + } + + fn static_handle(&self, v: Value) -> bool { + let Value::Inst(i) = v else { return true }; + let Op::Call(f, args) = &self.insts[i as usize].op else { return false }; + match self.funcs[*f as usize].name.as_str() { + "dx.op.createHandleFromBinding" => args.iter().all(|v| matches!(v, Value::Const(_))), + "dx.op.annotateHandle" => args.iter().all(|&v| self.static_handle(v)), + _ => false, + } + } + + fn rebuild_static(&self, v: Value, dst: &mut Module, map: &mut HashMap) -> Option { + let Value::Inst(id) = v else { return Some(v) }; + if let Some(&old) = map.get(&v) { return Some(old); } + let Op::Call(f, args) = &self.insts[id as usize].op else { return None }; + let args: Vec<_> = args.iter().map(|&a| self.rebuild_static(a, dst, map)).collect::>()?; + let new = dst.call(*f, &args); + map.insert(v, new); + Some(new) + } + + fn pack(&self, original: Value, v: Value, dst: &mut Module) -> Vec { + if let Some(index) = dst.indexed(v) { return vec![index]; } + let ty = self.insts[inst(original).unwrap()].ty; + let word = dst.i32(); + match self.types[ty.0 as usize] { + TypeDef::Int(32) => vec![v], + TypeDef::Int(64) => { + let shift = dst.const_int(ty, 32); + let high = dst.bin(BinOp::LShr, v, shift); + vec![dst.cast(CastOp::Trunc, v, word), dst.cast(CastOp::Trunc, high, word)] + } + TypeDef::Float => vec![dst.bitcast(v, word)], + _ => vec![dst.cast(CastOp::ZExt, v, word)], + } + } + + fn unpack(&self, original: Value, words: &[Value], dst: &mut Module) -> Value { + if self.indexed(original).is_some() { + match &self.insts[inst(original).unwrap()].op { + Op::Gep(base, indices) => return dst.gep(*base, &[indices[0], words[0]]), + Op::Call(f, annotate) => { + let Op::Call(create, args) = &self.insts[inst(annotate[1]).unwrap()].op else { unreachable!() }; + let handle = dst.call(*create, &[args[0], words[0], args[2], args[3]]); + return dst.call(*f, &[annotate[0], handle, annotate[2]]); + } + _ => unreachable!(), + } + } + let ty = self.insts[inst(original).unwrap()].ty; + match self.types[ty.0 as usize] { + TypeDef::Int(32) => words[0], + TypeDef::Int(64) => { + let low = dst.cast(CastOp::ZExt, words[0], ty); + let high = dst.cast(CastOp::ZExt, words[1], ty); + let shift = dst.const_int(ty, 32); + let shifted = dst.bin(BinOp::Shl, high, shift); + dst.bin(BinOp::Or, low, shifted) + } + TypeDef::Float => dst.bitcast(words[0], ty), + _ => dst.cast(CastOp::Trunc, words[0], ty), + } + } +} + +impl Module { + /// Preserve symbol and type indices when copying instructions into a + /// piece. The destination has its own blocks, instructions and metadata. + pub(in crate::gpu::dxil) fn declarations(&self) -> Self { + Self { + types: self.types.clone(), + type_ids: self.type_ids.clone(), + consts: self.consts.clone(), + const_ids: self.const_ids.clone(), + funcs: self.funcs.clone(), + func_ids: self.func_ids.clone(), + globals: self.globals.clone(), + ..Self::new() + } + } + + pub(crate) fn dispatch_plan(&self, limit: usize) -> Option { + let (order, _) = self.block_layout(); + let count = |b: usize| self.blocks[b].len(); + if limit == 0 || order.iter().copied().map(count).sum::() <= limit { + return None; + } + let mut predecessors = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + for target in self.successors(b) { + predecessors[target.0 as usize].push(b); + } + } + + // In reverse postorder of the original graph, flooding the transpose + // visits one component at a time in topological order (Kosaraju). + let mut visited = vec![false; self.blocks.len()]; + let mut blocks = vec![Vec::new()]; + let mut stages = vec![usize::MAX; self.blocks.len()]; + let mut used = 0; + for &root in &order { + if visited[root] { + continue; + } + let mut component = Vec::new(); + let mut cost = 0; + let mut stack = vec![root]; + visited[root] = true; + while let Some(b) = stack.pop() { + cost += count(b); + component.push(b); + for &p in &predecessors[b] { + if !visited[p] { + visited[p] = true; + stack.push(p); + } + } + } + if cost > limit { + return None; + } + if used + cost > limit { + blocks.push(Vec::new()); + used = 0; + } + used += cost; + for b in component { + stages[b] = blocks.len() - 1; + } + } + + let mut crossing = BTreeSet::new(); + for &b in &order { + let from = Block(b as u32); + blocks[stages[b]].push(from); + for to in self.successors(b) { + if stages[b] != stages[to.0 as usize] { + debug_assert!(stages[b] < stages[to.0 as usize]); + crossing.insert((from, to)); + } + } + } + let mut live_in = vec![HashSet::new(); self.blocks.len()]; + let mut phi_input = HashMap::<_, BTreeSet<_>>::new(); + let mut work = Vec::new(); + for &b in &order { + for &inst in &self.blocks[b] { + let op = &self.insts[inst as usize].op; + // A phi reads each operand on its incoming edge, including + // when the definition is its predecessor's last instruction. + if let Op::Phi(inputs) = op { + for &(value, pred) in inputs { + if let Value::Inst(i) = value { + let edge = (pred, Block(b as u32)); + if crossing.contains(&edge) { + phi_input.entry(edge).or_default().insert(value); + } + if self.def_block[i as usize] != pred { + work.push((pred.0 as usize, i)); + } + } + } + } else { + op.for_each_operand(|v| { + if let Value::Inst(i) = v { + if self.def_block[i as usize].0 as usize != b { + work.push((b, i)); + } + } + }); + } + } + } + while let Some((b, value)) = work.pop() { + if live_in[b].insert(value) { + for &p in &predecessors[b] { + if self.def_block[value as usize].0 as usize != p { + work.push((p, value)); + } + } + } + } + let edges = crossing.into_iter().map(|(from, to)| { + let mut live = phi_input.remove(&(from, to)).unwrap_or_default(); + live.extend(live_in[to.0 as usize].iter().copied().map(Value::Inst)); + Edge { from, to, live: live.into_iter().collect() } + }).collect(); + Some(Plan { blocks, edges }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::{ + dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::Pred}, + recomp::{runner, CsInterface}, + }; + + fn compare(threads: u32) { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [threads, 1, 1]; + let split = threads == 64; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.s.raw_uav(2, 0); + let group = lw.s.group_id(0); + let count = lw.c(threads); + let base = lw.mul(group, count); + let index = lw.add(base, tid); + let offset = lw.shlc(index, 2); + let original = lw.s.raw_load(mem, offset, 1)[0]; + let trips = lw.andc(tid, 3); + let trips = lw.addc(trips, 1); + let mut value = original; + let i32 = lw.s.m.i32(); + let zero = lw.c(0); + + // Each loop both consumes the previous loop's result and reuses + // the original per-lane input. All lanes eventually reconverge. + for round in 1..=16 { + let pred = lw.cur(); + let body = lw.s.m.new_block(); + let exit = lw.s.m.new_block(); + lw.s.m.br(body); + lw.s.m.set_block(body); + let counter = lw.s.m.phi(i32); + let acc = lw.s.m.phi(i32); + lw.s.m.add_incoming(counter, zero, pred); + lw.s.m.add_incoming(acc, value, pred); + let next = lw.addc(counter, 1); + value = lw.add(acc, original); + value = lw.addc(value, round); + lw.s.m.add_incoming(counter, next, body); + lw.s.m.add_incoming(acc, value, body); + let again = lw.cmp(Pred::ULt, next, trips); + lw.s.m.cond_br(again, body, exit); + lw.s.m.set_block(exit); + if split && round == 8 { + let other_half = lw.exchange(lw.half); + value = lw.add(value, other_half); + } + } + lw.s.raw_store(mem, offset, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 40).expect("split the synthetic program"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + let initial: Vec<_> = (1..=threads * 3).collect(); + let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { + let n = (i as u32 % 4) + 1; + v + n * (16 * v + 136) + u32::from(split && i as u32 % threads < 32) + }).collect(); + let reference = runner::dispatch(&whole, [3, 1, 1], &[], &initial).unwrap(); + assert_eq!(reference, expected); + let result = runner::dispatch_split(&chain, [3, 1, 1], &initial).unwrap(); + assert_eq!(result, reference); + } + + /// A typed UAV load in one piece only: the whole program declares its flag, the other pieces + /// must not (the validator wants flags to match usage, and a refused piece leaves it whole). + #[test] + fn dispatch_chain_declares_typed_uav_loads_only_where_they_are() { + use crate::gpu::dxil::ops::{CompType, TexKind}; + + let geometry = [32, 1, 1]; + let options = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + let first = lw.s.raw_load(mem, offset, 1)[0]; + let entry = lw.cur(); + let middle = lw.s.m.new_block(); + let last = lw.s.m.new_block(); + let width = lw.s.wave_lane_count(); + let taken = lw.cmp(Pred::ULt, tid, width); + lw.s.m.cond_br(taken, middle, last); + lw.s.m.set_block(middle); + let slot = lw.s.m.i32c(9); + let texture = lw.s.heap_texture(slot, TexKind::D2, true, CompType::F32, 4, false); + lw.s.typed_uav_load_additional_formats(); + let texel = lw.s.texture_load(texture, None, &[tid, tid], &[]); + let i32 = lw.s.m.i32(); + let bits = lw.s.m.cast(CastOp::BitCast, texel[1], i32); + let loaded = lw.xor(first, bits); + lw.s.m.br(last); + lw.s.m.set_block(last); + let value = lw.s.m.phi(i32); + lw.s.m.add_incoming(value, loaded, middle); + lw.s.m.add_incoming(value, first, entry); + lw.s.raw_store(mem, offset, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let limit = lw.s.m.blocks.iter().map(Vec::len).max().unwrap(); + let chain = lw.s.split_compute(geometry, None, limit).expect("every piece validates"); + assert!(chain.pieces.len() >= 2); + } + + #[test] + fn dispatch_chain_wave32_live_loops() { compare(32); } + + #[test] + fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64); } +} diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index 5e77eb659..f72756c0f 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -160,6 +160,20 @@ pub struct RawUav { } impl Shader { + pub(super) fn dispatch_piece(&self) -> Self { + Self { + m: self.m.declarations(), + stage: self.stage, + sm: self.sm, + entry: self.entry, + features: self.features.clone(), + bindings: self.bindings.clone(), + handle_ty: self.handle_ty, + props_ty: self.props_ty, + rov: self.rov, + } + } + pub fn new(stage: Stage, sm: (u32, u32)) -> Shader { let mut m = Module::new(); let entry = m.define_entry("main"); @@ -519,6 +533,10 @@ impl Shader { self.m.ret(); } self.m.optimize(); + self.finish_optimized(numthreads, wave_size) + } + + pub(super) fn finish_optimized(mut self, numthreads: [u32; 3], wave_size: Option) -> Result, String> { self.infer_type_features(); let (flags, sfi0) = self.feature_flags(); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 743a31264..46d3c34e7 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -121,6 +121,7 @@ pub type StaticSampler = ([u32; 4], bool); /// A console shader as PC DXIL and the static samplers it needs in its root signature. #[derive(Clone)] pub struct Compiled { + pub dispatch_chain: Option>, pub dxil: Vec, pub samplers: Vec, } @@ -261,6 +262,9 @@ mod translated { Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag), _ => id, }; + let id = if Backend::current() != Backend::Hlsl { + identity_for(&id.to_string(), &format!("dispatch-split-{}", crate::gpu::dxil::kernel::dispatch_piece_limit())) + } else { id }; // `XCL_PER_LANE=1` (direct compute only): its entries under their own identity if Backend::current() != Backend::Hlsl && crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) @@ -311,7 +315,28 @@ mod translated { samplers.push((s, cmp != 0)); } let len = u32_(&mut r)? as usize; - (r.len() == len && super::dxc::valid_dxil_container(r)).then(|| Compiled { dxil: r.to_vec(), samplers }) + if len == 0 { return None; } + let (whole, mut rest) = r.split_at_checked(len)?; + if !super::dxc::valid_dxil_container(whole) { return None; } + let dispatch_chain = if rest.is_empty() { + None + } else { + let dwords_per_group = u32_(&mut rest)?; + let count = u32_(&mut rest)?; + if dwords_per_group == 0 || count < 2 || count as usize > rest.len() / 4 { return None; } + let mut pieces = Vec::new(); + for _ in 0..count { + let len = u32_(&mut rest)? as usize; + if len == 0 { return None; } + let (piece, next) = rest.split_at_checked(len)?; + if !super::dxc::valid_dxil_container(piece) { return None; } + pieces.push(piece.to_vec()); + rest = next; + } + if !rest.is_empty() { return None; } + Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) + }; + Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -326,6 +351,14 @@ mod translated { } b.extend_from_slice(&(c.dxil.len() as u32).to_le_bytes()); b.extend_from_slice(&c.dxil); + if let Some(chain) = &c.dispatch_chain { + b.extend_from_slice(&chain.dwords_per_group.to_le_bytes()); + b.extend_from_slice(&(chain.pieces.len() as u32).to_le_bytes()); + for piece in &chain.pieces { + b.extend_from_slice(&(piece.len() as u32).to_le_bytes()); + b.extend_from_slice(piece); + } + } let Some(dir) = path.parent() else { return }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); // written whole, then renamed: a reader never sees half a file @@ -381,7 +414,7 @@ mod translated { } /// What the direct translator's output depends on besides the HLSL path's identity: its - /// version and sources, a forced compact form, the per-lane form (`direct_compute`). + /// version and sources, a forced compact form, the split target, the per-lane form (`direct_compute`). fn direct_output() -> u64 { static D: OnceLock = OnceLock::new(); *D.get_or_init(|| { @@ -390,6 +423,7 @@ mod translated { Some(on) => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }), None => id, }; + let id = identity_for(&id.to_string(), &format!("dispatch-split-{}", crate::gpu::dxil::kernel::dispatch_piece_limit())); if crate::gpu::recomp::lower_dxil::enabled() { identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID"))) } else { @@ -523,7 +557,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dxil, samplers: t.static_samplers }, false)) + Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -610,6 +644,7 @@ impl ShaderEntry { self.blob.len() + self.key.cache_dir.capacity() + self.shader.dxil.capacity() + + self.shader.dispatch_chain.as_ref().map_or(0, |chain| chain.pieces.iter().map(Vec::capacity).sum()) + self.shader.samplers.capacity() * std::mem::size_of::() } } @@ -826,7 +861,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -836,7 +871,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); - Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -871,7 +906,7 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - _ => return Err("the shader stage does not match its slot in the PSO".into()), }; dump_direct(blob, &k.dxil); - Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) } pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { @@ -946,7 +981,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dxil: cs, samplers: t.static_samplers }, record, ps) + finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) } fn compile_console_mesh( @@ -972,7 +1007,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); } Err(e) => direct_fallback("MS", &e), } @@ -983,7 +1018,7 @@ fn compile_console_mesh( return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) } fn console_mesh_with( @@ -1144,10 +1179,38 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA /// The ABI root signature with the pipeline's static samplers (registers 0.., space 1). pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result { + abi_signature(dev, graphics, samplers, false) +} + +/// Record all piece dispatches after the six common root views have been bound. +pub(crate) unsafe fn record_dispatch_chain<'a>( + list: &ID3D12GraphicsCommandList, grid: [u32; 3], scratch: &ID3D12Resource, + pieces: impl IntoIterator, +) { + let [x, y, z] = grid; + list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); + for (i, piece) in pieces.into_iter().enumerate() { + if i != 0 { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + } + let constants = [x, y, z, i as u32]; + list.SetComputeRoot32BitConstants(7, 4, constants.as_ptr().cast(), 0); + list.SetPipelineState(piece); + list.Dispatch(x, y, z); + } + +} + +pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result { + abi_signature(dev, false, samplers, true) +} + +fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { // u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding) - let params: Vec = (0..6) + let mut params: Vec = (0..6) .map(|i| D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: D3D12_ROOT_PARAMETER1_0 { @@ -1156,6 +1219,22 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }) .collect(); + if split { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, RegisterSpace: 2, Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 4, + } }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } let mut flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; if graphics { flags |= D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; @@ -1218,7 +1297,7 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone())); @@ -1409,7 +1488,7 @@ mod shader_cache_tests { // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). - let valid = Compiled { dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)] }; + let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)] }; translated::store_in(&path, ident, blob, &valid); let mut raw = std::fs::read(&path).unwrap(); let dxil_start = raw.len() - valid.dxil.len(); @@ -1428,7 +1507,7 @@ mod shader_cache_tests { let mut calls = 0usize; let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { calls += 1; - Ok(Compiled { dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) + Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) }) .unwrap(); assert_eq!(calls, 1); @@ -1452,20 +1531,20 @@ mod shader_cache_tests { let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) }) .err() .expect("invalid fresh DXIL must be rejected"); assert!(err.contains("invalid DXIL container"), "{err}"); assert!(!path.exists(), "invalid fresh DXIL must not be written to disk"); - translated::store_in(&path, ident, blob, &Compiled { dxil: b"not DXIL".to_vec(), samplers: Vec::new() }); + translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }); assert!(!path.exists(), "store_in must not write an invalid DXIL container"); // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dxil: real_direct.clone(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new() }) }) .unwrap(); assert_eq!(stored.dxil, real_direct); @@ -1479,6 +1558,7 @@ mod shader_cache_tests { fn compiled(marker: u8) -> Compiled { Compiled { + dispatch_chain: None, dxil: synthetic_dxil(marker), samplers: vec![([marker as u32; 4], false)], } @@ -1554,6 +1634,7 @@ mod shader_cache_tests { cached_shader(&cache, key(1), b"a", || { let dxil = dxc::compile_cached_in(&dir, "probe", "main", "cs_6_6")?.0; Ok(Compiled { + dispatch_chain: None, dxil, samplers: Vec::new(), }) @@ -1587,6 +1668,7 @@ mod shader_cache_tests { key(4), b"d", Arc::new(Compiled { + dispatch_chain: None, dxil: vec![0; limit + 1], samplers: Vec::new(), }), @@ -1761,6 +1843,7 @@ mod shader_cache_tests { let dxil = dxc::compile_cached_in(&dir, "pending probe", "main", "cs_6_6")?.0; Ok(Compiled { + dispatch_chain: None, dxil, samplers: Vec::new(), }) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 4cd1663d5..b5ef5a2ee 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1617,7 +1617,25 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, 1, false, None).map(|(m, _)| m) +} + +#[cfg(test)] +pub(crate) fn dispatch_split( + chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], mem: &[u32], +) -> Result, String> { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; + let rs = super::pso::dispatch_chain_root_signature(&gpu.dev, &[])?; + let pieces: Vec = chain.pieces.iter().map(|dxil| unsafe { + gpu.dev.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, + ..Default::default() + }).map_err(e) + }).collect::>()?; + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, groups, &[], mem, 1, false, + Some((&pieces, chain.dwords_per_group))).map(|(m,_)| m) } /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not @@ -1634,7 +1652,7 @@ pub fn dispatch_timed(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32], }) } .map_err(|x| format!("CreateComputePipelineState: {x}"))?; - dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true).map(|(_, t)| t) + dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pso, &gpu.rs, groups, sgprs, mem, reps.max(1), true, None).map(|(_, t)| t) } /// Dispatch with an existing compute pipeline on `dev` (its own queue), e.g. one the D3D12.X @@ -1644,7 +1662,7 @@ pub fn dispatch_on(dev: &ID3D12Device, pso: &ID3D12PipelineState, rs: &ID3D12Roo unsafe { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; - dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false).map(|(m, _)| m) + dispatch_with(dev, &queue, &fence, &mut 0, pso, rs, groups, sgprs, mem, 1, false, None).map(|(m, _)| m) } } @@ -1661,6 +1679,7 @@ fn dispatch_with( mem: &[u32], reps: usize, timed: bool, + chain: Option<(&[ID3D12PipelineState], u32)>, ) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); io.resize(KERNEL_SGPRS, 0); @@ -1712,6 +1731,10 @@ fn dispatch_with( list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + let scratch = chain.map(|(_, words)| { + let bytes = groups.iter().fold(4 * u64::from(words), |n, &g| n * u64::from(g)); + buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true) + }).transpose()?; // `reps` dispatches, each between two timestamps when `timed` let stamps = 2 * reps as u32; let queries = if timed { @@ -1730,7 +1753,11 @@ fn dispatch_with( if let Some((heap, _)) = &queries { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); } - list.Dispatch(groups[0], groups[1], groups[2]); + if let (Some((pieces, _)), Some(scratch)) = (chain, &scratch) { + super::pso::record_dispatch_chain(&list, groups, scratch, pieces); + } else { + list.Dispatch(groups[0], groups[1], groups[2]); + } if let Some((heap, _)) = &queries { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k + 1); } diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index ba29bb3c4..e821d6074 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -117,7 +117,9 @@ pub fn reset_list(list: usize, alloc: usize, ty: i32, reset: impl FnOnce(usize) } #[cfg(test)] -pub(super) fn recording_backing_for_test(list: usize) -> Option { +pub(super) use recording_backing as recording_backing_for_test; + +pub(super) fn recording_backing(list: usize) -> Option { STATE.lock().unwrap().as_ref()?.of_list.get(&list).copied() } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c888e6325..fad934add 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -314,6 +314,17 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; match bind_abi(this, list, pso, gfx) { Ok(()) => { + if compute { + match super::real::dispatch_chain::whole(pso) { + Ok(Some(whole)) => list.SetPipelineState(&whole), + Ok(None) => {} + Err(e) => { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + count(DISPATCHES_SKIPPED); + return; + } + } + } count(if gfx { DRAWS } else { DISPATCHES }); fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } @@ -970,8 +981,7 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis trace_fullscreen(this, pso, [x, y, z]); } bind_abi(this, list, pso, false)?; - list.Dispatch(x, y, z); - Ok(()) + super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]) } /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3a3480f18..a3348a168 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -854,7 +854,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let raw = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); - list.Dispatch(x, y, z); + super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; out.dispatches += 1; } _ => out.skipped_dispatches += 1, diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 13a9502dc..7384fba01 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -171,10 +171,12 @@ pub fn enabled() -> bool { /// Builds the real pipeline: its raw pointer, 0 = failed. pub type Job = Box usize + Send>; -fn queue() -> &'static Mutex>> { - static Q: OnceLock>>> = OnceLock::new(); +type Work = Box; + +fn queue() -> &'static Mutex> { + static Q: OnceLock>> = OnceLock::new(); Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::>(); + let (tx, rx) = mpsc::channel::(); let rx = Arc::new(Mutex::new(rx)); // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); @@ -182,23 +184,56 @@ fn queue() -> &'static Mutex>> { let rx = rx.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { let next = rx.lock().unwrap().recv(); - let Ok(p) = next else { return }; - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - let _ = p.job.lock().unwrap().take(); - continue; - } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, false); - } + let Ok(work) = next else { return }; + work(); }); } Mutex::new(tx) }) } +fn enqueue(p: Arc) { + let _ = queue().lock().unwrap().send(Box::new(move || { + // (released by the title meanwhile) + if p.orphan.load(Ordering::Acquire) { + let _ = p.job.lock().unwrap().take(); + return; + } + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + build(&p, job, false); + } + })); +} + +/// The caller also drains its batch. Multiple workers can therefore build +/// different chains without ever waiting for a free worker to start a piece. +pub(super) fn build_pieces(jobs: Vec) -> Vec { + let count = jobs.len(); + let jobs = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::>())); + let (send, recv) = mpsc::channel(); + let drain = move || loop { + let job = jobs.lock().unwrap().pop(); + let Some((i, job)) = job else { return }; + let _ = send.send((i, job())); + }; + // the helpers build for this worker's pipeline: the title waiting for it waits for them too + let parent = BUILDING.with(|b| b.borrow().clone()); + for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { + let (drain, parent) = (drain.clone(), parent.clone()); + let _ = queue().lock().unwrap().send(Box::new(move || { + let before = BUILDING.with(|b| b.replace(parent)); + drain(); + BUILDING.with(|b| *b.borrow_mut() = before); + })); + } + drain(); + let mut results = vec![0; count]; + for (i, result) in recv.iter().take(count) { results[i] = result; } + results +} + /// Release a pipeline state XCL owns (raw pointer, 0 = none). pub fn release(p: usize) { if p != 0 { @@ -248,7 +283,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); }); if send { - let _ = queue().lock().unwrap().send(p); + enqueue(p); } else if used::known(key) { if let Some(q) = preload() { q.list.lock().unwrap().push_back(p); @@ -645,7 +680,7 @@ pub fn resolve(pso: usize) -> usize { 0 => { // a lazy one is wanted now: to the workers if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p); + enqueue(p); } pso } @@ -707,7 +742,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> return built(p); } if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); + enqueue(p.clone()); } if p.late.load(Ordering::Acquire) { return pso; @@ -755,7 +790,7 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { if !p.sent.swap(true, Ordering::AcqRel) { - let _ = queue().lock().unwrap().send(p.clone()); + enqueue(p.clone()); } if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 51016f38a..cf429a58e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1816,6 +1816,7 @@ pub(super) fn forget_pso_for_test(pso: usize) { } fn forget_pso(pso: usize) { + dispatch_chain::forget(pso); if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); } @@ -4302,18 +4303,72 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if big && crate::gpu::recomp::dxc::defer() { return Some(Err(())); } + let record = crate::gpu::shader::fnv64(cs); + if let Some(plan) = compiled.dispatch_chain { + if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) { + LAST_COMPUTE_RS.with(|c| c.set(rs)); + note_pso_rs(*ppv, rs as *mut c_void); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(0, ppv); + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + return Some(Ok(0)); + } + } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); + let (hr, in_driver, reused) = compute_container(this, f, d, rs, &dxil, record, riid, ppv, false); + if hr < 0 { + // A huge program's verdict in the log itself: `note_translation_error` goes to the + // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program + // took an AMD driver 15 – 23 s and ~15 GB to refuse with E_OUTOFMEMORY in every run, and + // the log showed only its `driver compile finish` and the dispatches skipped after it. + if dxil.len() >= huge_pso_bytes() { + // (the record hash is the console program's, as in `driver compile start` and + // `xcl shaders --measure-pso`; the driver-cache name is the translated DXIL's) + crate::xlog_warn!( + "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", + dxil.len(), + driver_cache::name(&dxil, d.Flags.0), + in_driver.as_millis() + ); + } + note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); + return Some(Err(())); + } + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_translated_compute(hr, ppv); + crate::xlog_info!( + "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", + dxil.len(), + in_driver.as_millis(), + if reused { ", the driver's blob of an earlier build" } else { "" } + ); + Some(Ok(hr)) +} + +pub(super) mod dispatch_chain; +pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; + +/// `chained`: built with the dispatch chain's root signature (`dispatch_chain`), whose driver blobs +/// are kept apart on disk from the same DXIL's under the title's. +unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, + dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, chained: bool) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); - copy.CS = bytecode(&dxil); + copy.CS = bytecode(dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. - let key = compute_blob_key(&dxil, rs as usize, copy.Flags.0); + let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path(&dxil, copy.Flags.0); + let disk = driver_cache::path(dxil, copy.Flags.0).map(|p| if chained { p.with_extension("chain.pso") } else { p }); let from_disk = cached.is_none(); if from_disk { cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); @@ -4322,7 +4377,6 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } // in the background, a few at a time and within the commit headroom the program asks for - let record = crate::gpu::shader::fnv64(cs); let (mut hr, mut in_driver) = driver_compile_identified( "compute", dxil.len(), @@ -4356,37 +4410,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else if reused && from_disk { driver_cache::note(true, None); } - if hr < 0 { - // A huge program's verdict in the log itself: `note_translation_error` goes to the - // report, or to the notes of a cached-only attempt – a retail title's 13.8 MB program - // took an AMD driver 15 – 23 s and ~15 GB to refuse with E_OUTOFMEMORY in every run, and - // the log showed only its `driver compile finish` and the dispatches skipped after it. - if dxil.len() >= huge_pso_bytes() { - // (the record hash is the console program's, as in `driver compile start` and - // `xcl shaders --measure-pso`; the driver-cache name is the translated DXIL's) - crate::xlog_warn!( - "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", - dxil.len(), - driver_cache::name(&dxil, copy.Flags.0), - in_driver.as_millis() - ); - } - note_translation_error(format!("the driver rejected the compute PSO with the translated CS ({hr:#x})")); - return Some(Err(())); - } - TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); - note_pso_rs(*ppv, rs); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); - } - note_translated_compute(hr, ppv); - crate::xlog_info!( - "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", - dxil.len(), - in_driver.as_millis(), - if reused { ", the driver's blob of an earlier build" } else { "" } - ); - Some(Ok(hr)) + (hr, in_driver, reused) } /// The blobs of `COMPUTE_BLOBS`, kept on disk between runs. @@ -6782,6 +6806,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { + dispatch_chain::allocator_reset(this as usize); super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); } @@ -6792,7 +6817,9 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); - f(raw) + let hr = f(raw); + if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs new file mode 100644 index 000000000..6621821f4 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -0,0 +1,148 @@ +//! PSOs for a split compute entry. The first piece is the real PSO returned +//! to the caller. Other pieces and the lazily built whole form belong to it. +use super::*; +use crate::gpu::{dxil::kernel::DispatchChain, recomp::pso}; +use std::sync::{Arc, LazyLock, OnceLock}; + +static PROGRAMS: AtomicU64 = AtomicU64::new(0); +static PIECES: AtomicU64 = AtomicU64::new(0); +static DISPATCHES: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn log_counts() { + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued", + PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed)); +} + +struct PipelineBuilder { + device: ID3D12Device, + create: PsoFn, + signature: ID3D12RootSignature, + flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, + record: u64, +} + +impl PipelineBuilder { + unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), + dxil, self.record, iid, &mut raw, true); + (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + } +} + +struct Chain { + builder: Arc, + tail: Vec, + words: u32, + whole_code: Vec, + whole: OnceLock, + build_whole: Mutex<()>, +} + +impl Chain { + unsafe fn whole(&self) -> Result { + if let Some(p) = self.whole.get() { return Ok(p.clone()); } + let _guard = self.build_whole.lock().unwrap(); + if let Some(p) = self.whole.get() { return Ok(p.clone()); } + let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; + let _ = self.whole.set(p.clone()); + Ok(p) + } +} + +static CHAINS: LazyLock>>> = LazyLock::new(Default::default); + +pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], + plan: Arc) -> Option { + if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } + let dev = ID3D12Device::from_raw_borrowed(&this)?; + let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; + let rs = signature.as_raw() as usize; + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, + flags: desc.Flags, node: desc.NodeMask, record }); + let jobs = (0..plan.pieces.len()).map(|i| { + let plan = plan.clone(); + let builder = builder.clone(); + let iid = if i == 0 { *iid } else { pc_iid(Kind::PipelineState) }; + Box::new(move || builder.pipeline(&plan.pieces[i], &iid).map_or(0, |p| p.into_raw() as usize)) as super::super::pso_async::Job + }).collect(); + // Take ownership of every success, including when a different piece failed. + let built: Vec<_> = super::super::pso_async::build_pieces(jobs).into_iter() + .map(|p| (p != 0).then(|| ID3D12PipelineState::from_raw(p as *mut c_void))).collect(); + let mut pieces = built.into_iter().collect::>>()?.into_iter(); + let first = pieces.next()?; + let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, + whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()) }); + PROGRAMS.fetch_add(1, Ordering::Relaxed); + PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); + *result = first.into_raw(); + CHAINS.lock().unwrap().insert(*result as usize, chain); + Some(rs) +} + +pub(super) fn forget(pso: usize) { + let gone = CHAINS.lock().unwrap().remove(&pso); + drop(gone); // releasing a tail PSO also goes through forget_pso +} + +pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + chain.map(|c| c.whole()).transpose() +} + +struct Recording { + scratch: ID3D12Resource, + first: ID3D12PipelineState, + chain: Arc, +} + +static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); + +pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { + let recordings = RECORDINGS.lock().unwrap().remove(&allocator); + drop(recordings); +} + +unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }; + let mut resource = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +/// Called with the original six ABI views bound. The extended signature is +/// common to every piece and the whole fallback. Choose before recording any +/// part of the dispatch, including when scratch allocation fails. +pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, grid: [u32; 3]) -> Result<(), String> { + let [x, y, z] = grid; + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { list.Dispatch(x, y, z); return Ok(()) }; + if grid.contains(&0) { return Ok(()); } + // A title Reset can switch to a different PC allocator while this + // recording is still submitted on the old one. Retain by backing. + let allocator = if super::super::alloc_pool::enabled() { + super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) + } else { allocator }; + let size = grid.into_iter().try_fold(u64::from(chain.words) * 4, |s, n| s.checked_mul(n as u64)); + let scratch = size.filter(|&n| n <= u32::MAX as u64 + 1 && allocator != 0 && list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) + .and_then(|n| scratch_buffer(&chain.builder.device, n)); + let Some(scratch) = scratch else { + list.SetPipelineState(&chain.whole()?); + list.Dispatch(x, y, z); + return Ok(()); + }; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + let held = Arc::new(Recording { scratch, first, chain }); + RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); + DISPATCHES.fetch_add(1, Ordering::Relaxed); + pso::record_dispatch_chain(list, grid, &held.scratch, std::iter::once(&held.first).chain(&held.chain.tail)); + Ok(()) +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f3e57ce5f..71a25c7c1 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -35,6 +35,10 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + let _ = std::thread::Builder::new().name("xcl-split-counts".into()).spawn(|| loop { + std::thread::sleep(std::time::Duration::from_secs(10)); + crate::hle::d3d12x::real::log_dispatch_chain_counts(); + }); // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) if std::env::var_os("XCL_ACTIVITY").is_some() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee30332..ff9ac68b2 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1189,7 +1189,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); From 87edf7efbb966b28499516e55683dd4d7fbff83f Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:57:46 -0500 Subject: [PATCH 2/8] Tests: use the compute fixture's existing memory window The synthetic split fixture declared u2 twice with different coherence flags. Bind its existing memory window and validate the whole fixture before checking the cut. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module/split.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 8925e5659..2d09571be 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -525,7 +525,6 @@ impl Module { #[cfg(test)] mod tests { - use super::*; use crate::gpu::{ dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::Pred}, recomp::{runner, CsInterface}, @@ -542,7 +541,7 @@ mod tests { let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); let (tid, _) = lw.setup_lanes_compute(geometry, false); - let mem = lw.s.raw_uav(2, 0); + let mem = lw.mems[0]; let group = lw.s.group_id(0); let count = lw.c(threads); let base = lw.mul(group, count); @@ -583,9 +582,11 @@ mod tests { lw.s.raw_store(mem, offset, &[value]); lw.s.m.ret(); lw.s.m.optimize(); - let chain = lw.s.split_compute(geometry, split.then_some(tid), 40).expect("split the synthetic program"); - assert!(chain.pieces.len() >= 3); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 40); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); + let chain = chain.expect("split the synthetic program"); + assert!(chain.pieces.len() >= 3); let initial: Vec<_> = (1..=threads * 3).collect(); let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { let n = (i as u32 % 4) + 1; From 95f8d260add3e611602d1567d8c9dab5dc68af21 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:05:49 -0500 Subject: [PATCH 3/8] Recompiler: pack consecutive lanes into each dispatch scratch slot Adjacent lanes previously accessed ef008c0f's continuation data 1,612 bytes apart. Store the tag and each live dword in a separate lane-contiguous plane; transport both halves of i64 values through their own planes. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module/split.rs | 42 ++++++++++++++++++------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 2d09571be..1bb4a5e92 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -28,6 +28,7 @@ pub struct DispatchChain { struct Scratch { uav: RawUav, base: Value, + bytes_per_slot: u32, } impl Scratch { @@ -42,15 +43,17 @@ impl Scratch { let row = s.m.bin(BinOp::Add, row, y); let first = s.m.bin(BinOp::Mul, row, width); let group = s.m.bin(BinOp::Add, first, x); - let n = s.m.i32c(threads); - let first = s.m.bin(BinOp::Mul, group, n); + // Give consecutive logical lanes consecutive words for a slot, including + // the continuation tag in slot zero. A workgroup owns all its slots. + let group_words = s.m.i32c(stride * threads); + let first = s.m.bin(BinOp::Mul, group, group_words); let index = s.m.bin(BinOp::Add, first, lane); - let bytes = s.m.i32c(stride * 4); - Self { uav, base: s.m.bin(BinOp::Mul, index, bytes) } + let four = s.m.i32c(4); + Self { uav, base: s.m.bin(BinOp::Mul, index, four), bytes_per_slot: threads * 4 } } fn at(&self, m: &mut Module, slot: u32) -> Value { - let offset = m.i32c(slot * 4); + let offset = m.i32c(slot * self.bytes_per_slot); m.bin(BinOp::Add, self.base, offset) } } @@ -151,8 +154,10 @@ impl Shader { statics.insert(v); continue; } - let at = scratch.at(&mut dst.m, slot); - let words = dst.raw_load(scratch.uav, at, if n == 2 { 3 } else { 1 }); + let words = (slot..slot + n).map(|word| { + let at = scratch.at(&mut dst.m, word); + dst.raw_load(scratch.uav, at, 1)[0] + }).collect(); incoming.entry(v).or_default().push((words, bridge)); slot += n; } @@ -244,8 +249,10 @@ impl Shader { let n = src.transport_words(v)?; if n != 0 { let words = src.pack(v, *values.get(&v)?, &mut dst.m); - let at = scratch.at(&mut dst.m, slot); - dst.raw_store(scratch.uav, at, &words); + for (k, word) in words.into_iter().enumerate() { + let at = scratch.at(&mut dst.m, slot + k as u32); + dst.raw_store(scratch.uav, at, &[word]); + } slot += n; } } @@ -526,7 +533,7 @@ impl Module { #[cfg(test)] mod tests { use crate::gpu::{ - dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::Pred}, + dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::{BinOp, CastOp, Pred}}, recomp::{runner, CsInterface}, }; @@ -548,6 +555,14 @@ mod tests { let index = lw.add(base, tid); let offset = lw.shlc(index, 2); let original = lw.s.raw_load(mem, offset, 1)[0]; + // Two different dynamic dwords cross every cut as one i64. With + // slot-major scratch the high word is a wave width past the low word. + let i64_ty = lw.s.m.i64(); + let lo = lw.s.m.cast(CastOp::ZExt, original, i64_ty); + let hi = lw.s.m.cast(CastOp::ZExt, tid, i64_ty); + let shift = lw.s.m.const_int(i64_ty, 32); + let hi = lw.s.m.bin(BinOp::Shl, hi, shift); + let pair = lw.s.m.bin(BinOp::Or, lo, hi); let trips = lw.andc(tid, 3); let trips = lw.addc(trips, 1); let mut value = original; @@ -579,6 +594,11 @@ mod tests { value = lw.add(value, other_half); } } + let pair_lo = lw.s.m.cast(CastOp::Trunc, pair, i32); + let high = lw.s.m.bin(BinOp::LShr, pair, shift); + let pair_hi = lw.s.m.cast(CastOp::Trunc, high, i32); + let both = lw.xor(pair_lo, pair_hi); + value = lw.add(value, both); lw.s.raw_store(mem, offset, &[value]); lw.s.m.ret(); lw.s.m.optimize(); @@ -590,7 +610,7 @@ mod tests { let initial: Vec<_> = (1..=threads * 3).collect(); let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { let n = (i as u32 % 4) + 1; - v + n * (16 * v + 136) + u32::from(split && i as u32 % threads < 32) + v + n * (16 * v + 136) + u32::from(split && i as u32 % threads < 32) + (v ^ (i as u32 % threads)) }).collect(); let reference = runner::dispatch(&whole, [3, 1, 1], &[], &initial).unwrap(); assert_eq!(reference, expected); From e2db0c0a50ec47fbedf677b8c625036fcf256f29 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:57:20 -0500 Subject: [PATCH 4/8] Tests: exercise divergent forward edges across compute dispatch pieces Adopt WebIdentity1's fixture from #2080. Lanes return early, skip ahead over a piece, or run different numbers of loop iterations. Check the whole and split outputs against the CPU model and guard words on a 2 x 3 x 2 dispatch grid for native wave32 and split wave64. Source: https://github.com/xcl-dev/xcl/pull/2080#issuecomment-7152187595 Assisted-by: OpenAI Codex (GPT-6) Co-authored-by: WebIdentity1 <212448219+WebIdentity1@users.noreply.github.com> --- crates/xcl/src/gpu/dxil/module/split.rs | 118 ++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 1bb4a5e92..46f6eef19 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -664,4 +664,122 @@ mod tests { #[test] fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64); } + /// Early exits and forward skips retain their own continuation tags; group + /// indexing must keep every lane separate across all three dispatch axes. + #[test] + fn dispatch_chain_divergent_forward_edges_3d() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + println!("CHAIN_GPU={}", runner::adapter().unwrap()); + for threads in [32, 64] { + let geometry = [threads, 1, 1]; + let split = threads == 64; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let [x, y, z] = [0, 1, 2].map(|axis| lw.s.group_id(axis)); + let three = lw.c(3); + let row = lw.mul(z, three); + let row = lw.add(row, y); + let row = lw.shlc(row, 1); + let group = lw.add(row, x); + let count = lw.c(threads); + let base = lw.mul(group, count); + let index = lw.add(base, tid); + let offset = lw.shlc(index, 2); + let original = lw.s.raw_load(mem, offset, 1)[0]; + let mode = lw.andc(tid, 3); + let trips = lw.addc(mode, 1); + let zero = lw.c(0); + let one = lw.c(1); + let i32 = lw.s.m.i32(); + let early = lw.s.m.new_block(); + let choose = lw.s.m.new_block(); + let first = lw.s.m.new_block(); + let middle = lw.s.m.new_block(); + let second = lw.s.m.new_block(); + let done = lw.s.m.new_block(); + let exits = lw.cmp(Pred::Eq, mode, zero); + lw.s.m.cond_br(exits, early, choose); + lw.s.m.set_block(early); + let marker = lw.addc(index, 100_000); + lw.s.raw_store(mem, offset, &[marker]); + lw.s.m.ret(); + lw.s.m.set_block(choose); + let skips = lw.cmp(Pred::Eq, mode, one); + lw.s.m.cond_br(skips, middle, first); + lw.s.m.set_block(first); + let mut value = original; + let mut middle_value = None; + for round in 1..=16 { + if round == 9 { + let previous = lw.cur(); + lw.s.m.br(middle); + lw.s.m.set_block(middle); + let joined = lw.s.m.phi(i32); + lw.s.m.add_incoming(joined, original, choose); + lw.s.m.add_incoming(joined, value, previous); + value = joined; + middle_value = Some(joined); + let stops = lw.cmp(Pred::Eq, mode, three); + lw.s.m.cond_br(stops, done, second); + lw.s.m.set_block(second); + } + let pred = lw.cur(); + let body = lw.s.m.new_block(); + let exit = lw.s.m.new_block(); + lw.s.m.br(body); + lw.s.m.set_block(body); + let counter = lw.s.m.phi(i32); + let acc = lw.s.m.phi(i32); + lw.s.m.add_incoming(counter, zero, pred); + lw.s.m.add_incoming(acc, value, pred); + let next = lw.addc(counter, 1); + value = lw.add(acc, original); + value = lw.addc(value, round); + lw.s.m.add_incoming(counter, next, body); + lw.s.m.add_incoming(acc, value, body); + let again = lw.cmp(Pred::ULt, next, trips); + lw.s.m.cond_br(again, body, exit); + lw.s.m.set_block(exit); + } + let last = lw.cur(); + lw.s.m.br(done); + lw.s.m.set_block(done); + let final_value = lw.s.m.phi(i32); + lw.s.m.add_incoming(final_value, middle_value.unwrap(), middle); + lw.s.m.add_incoming(final_value, value, last); + lw.s.raw_store(mem, offset, &[final_value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let plan = lw.s.m.dispatch_plan(64).expect("partition branch fixture"); + let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); + assert!(plan.edges.iter().any(|edge| stage(edge.to) > stage(edge.from) + 1), "exercise a forward skip over an intermediate piece"); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 64).expect("split branch fixture"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); + let words = (threads * 12) as usize; + let initial: Vec<_> = (0..words + 16).map(|i| if i < words { i as u32 + 17 } else { 0xdeadbeef }).collect(); + let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { + if i >= words { return v; } + match i as u32 % 4 { + 0 => 100_000 + i as u32, + 1 => v + 2 * (8 * v + 100), + 2 => v + 3 * (16 * v + 136), + _ => v + 4 * (8 * v + 36), + } + }).collect(); + let reference = runner::dispatch(&whole, [2, 3, 2], &[], &initial).unwrap(); + assert_eq!(reference, expected, "unsplit {threads}"); + let result = runner::dispatch_split(&chain, [2, 3, 2], &initial).unwrap(); + assert_eq!(result, expected, "split {threads}"); + println!("CHAIN_BRANCH threads={threads} pieces={} scratch_words_per_group={} checked_words={words} guards=16", chain.pieces.len(), chain.dwords_per_group); + } + } + } From 6c34370946dd11cdc429fdb106f49b798b63b443 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:22:10 -0500 Subject: [PATCH 5/8] Tests: verify native wave64 compute keeps its whole pipeline Compile and validate a partitionable CFG through the native-wave64 admission gate. On a wave64 adapter, run the whole pipeline and check its lane count and output. Identify the existing compare(64) case as two hardware waves. Assisted-by: OpenAI Codex (GPT-6) --- crates/xcl/src/gpu/dxil/kernel.rs | 44 +++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/module/split.rs | 1 + 2 files changed, 45 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index e612bda32..da772ac2f 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -630,6 +630,50 @@ impl Lw { } } +#[cfg(test)] +#[test] +fn dispatch_chain_native_wave64_builds_whole() { + use crate::gpu::recomp::runner; + + let threads = [64, 1, 1]; + let cs = CsInterface { threads, ..Default::default() }; + let options = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(threads, false); + let offset = lw.shlc(tid, 2); + let width = lw.s.wave_lane_count(); + let mem = lw.mems[0]; + // conditional updates: blocks the optimiser cannot merge into one + for _ in 0..40 { + let update = lw.s.m.new_block(); + let join = lw.s.m.new_block(); + let taken = lw.cmp(Pred::ULt, tid, width); + lw.s.m.cond_br(taken, update, join); + lw.s.m.set_block(update); + let old = lw.s.raw_load(mem, offset, 1)[0]; + let new = lw.add(old, width); + lw.s.raw_store(mem, offset, &[new]); + lw.s.m.br(join); + lw.s.m.set_block(join); + } + lw.s.m.ret(); + lw.s.m.optimize(); + // Exercise the native-wave admission gate with an otherwise partitionable CFG. + assert!(lw.s.m.dispatch_plan(64).is_some()); + let program = lw.finish_dispatch(threads, 64, 64, None).unwrap(); + assert!(program.dispatch_chain.is_none()); + super::validate::validate(&program.dxil).expect("valid native wave64 whole shader"); + + if !runner::wave64_supported().unwrap_or(false) { + runner::skip_test("no wave64"); + return; + } + let initial: Vec = (1..=64).collect(); + let expected: Vec<_> = initial.iter().map(|v| v + 40 * 64).collect(); + let result = runner::dispatch(&program.dxil, [1, 1, 1], &[], &initial).unwrap(); + assert_eq!(result, expected); +} + /// The kernel's epilogue: SGPRs and SCC from lane 0, every touched VGPR per lane. fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { let touched: Vec = lw.init.touched.iter().copied().collect(); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 46f6eef19..a0fb8fc93 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -662,6 +662,7 @@ mod tests { #[test] fn dispatch_chain_wave32_live_loops() { compare(32); } + /// A guest wave64 split across two hardware wave32s. #[test] fn dispatch_chain_wave64_live_loops_and_exchange() { compare(64); } /// Early exits and forward skips retain their own continuation tags; group From bcde3f0dc6e89c75068ecf219dc7aa69c5de9dac Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:39:09 -0500 Subject: [PATCH 6/8] Recompiler: carry wave64 partner exchanges across dispatch pieces Use the workgroup's flat logical thread ID for the continuation of each wave32 half. Keep each counter signal with its peer wait, and transfer the per-half arrival counters and double-buffered exchange slots at a group-wide rendezvous between pieces. Wave allocation starts afresh in each piece. Leave guest LDS and partial guest waves on the whole path. Exercise four wave64s with different exchange epochs across repeated cuts and compare every output word to the whole shader and a CPU oracle. Assisted-by: OpenAI Codex (GPT-6) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/lanes.rs | 2 + crates/xcl/src/gpu/dxil/module.rs | 10 ++ crates/xcl/src/gpu/dxil/module/split.rs | 185 +++++++++++++++++++++--- docs/wave64-on-wave32.md | 7 + 5 files changed, 187 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index da772ac2f..297cfbce4 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -217,7 +217,7 @@ fn translate_on_this_thread( } Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); - if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } + if split && !uses_lds && cs.threads.iter().product::() % 64 == 0 { split_tid = Some(tid); } compute_init(&mut lw, cs, tid, gtid); cs.threads } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 04491ba07..02940dbba 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -300,6 +300,7 @@ impl Lw { let alive = self.cmpc(Pred::Eq, dead, 0); let has = self.cmpc(Pred::Ne, xn, 0); let go = self.land(alive, has); + let region = (self.cur(), self.s.m.block_count()); let _ = self.guarded(go, &mut |lw| { lw.s.barrier(barrier::TGSM_FENCE); let t = lw.s.m.i1c(true); @@ -354,6 +355,7 @@ impl Lw { }); let one = self.c(1); let ho = self.xor(h, one); + self.s.m.finish_spin_region(region.0, region.1); let theirs = at(self, ho); let metv = self.rd(met); let ok = self.nz(metv); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index cc85589f5..84ceed241 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -254,6 +254,7 @@ pub struct Module { insts: Vec, def_block: Vec, blocks: Vec>, + spin_regions: Vec>, cur: Block, insert_before_term: bool, md: Vec, @@ -282,6 +283,7 @@ impl Module { insts: Vec::new(), def_block: Vec::new(), blocks: vec![Vec::new()], + spin_regions: Vec::new(), cur: Block(0), insert_before_term: false, md: Vec::new(), @@ -519,6 +521,14 @@ impl Module { self.blocks.push(Vec::new()); Block(self.blocks.len() as u32 - 1) } + /// Keep both halves' signal and wait in the same dispatch. The join can + /// begin the next piece since the exchange slots are checkpointed. + pub(super) fn finish_spin_region(&mut self, start: Block, first_new: usize) { + let mut region = vec![start]; + region.extend((first_new..self.blocks.len()).map(|i| Block(i as u32)).filter(|&b| b != self.cur)); + self.spin_regions.push(region); + } + pub fn entry_block(&self) -> Block { Block(0) } diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index a0fb8fc93..e6b65d091 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -52,6 +52,45 @@ impl Scratch { Self { uav, base: s.m.bin(BinOp::Mul, index, four), bytes_per_slot: threads * 4 } } + /// Every logical thread participates, including threads whose guest path + /// skipped this piece. Exactly one thread owns each shared word. + fn transfer_shared(&self, s: &mut Shader, lane: Value, lanes: u32, arrays: &[(Value, u32, u32)], restore: bool) { + use crate::gpu::dxil::ops::barrier::GROUP_SYNC; + if !restore { s.barrier(GROUP_SYNC); } + for &(global, count, slot) in arrays { + for page in 0..count.div_ceil(lanes) { + let remaining = count - page * lanes; + let mut join = None; + if remaining < lanes { + let n = s.m.i32c(remaining); + let active = s.m.cmp(super::Pred::ULt, lane, n); + let body = s.m.new_block(); + let next = s.m.new_block(); + s.m.cond_br(active, body, next); + s.m.set_block(body); + join = Some(next); + } + let zero = s.m.i32c(0); + let base = s.m.i32c(page * lanes); + let index = s.m.bin(BinOp::Add, base, lane); + let ptr = s.m.gep(global, &[zero, index]); + let addr = self.at(&mut s.m, slot + page); + if restore { + let v = s.raw_load(self.uav, addr, 1)[0]; + s.m.store(ptr, v, 4); + } else { + let v = s.m.load(ptr, 4); + s.raw_store(self.uav, addr, &[v]); + } + if let Some(next) = join { + s.m.br(next); + s.m.set_block(next); + } + } + } + if restore { s.barrier(GROUP_SYNC); } + } + fn at(&self, m: &mut Module, slot: u32) -> Value { let offset = m.i32c(slot * self.bytes_per_slot); m.bin(BinOp::Add, self.base, offset) @@ -59,11 +98,16 @@ impl Scratch { } impl Shader { - /// Start with full native wave32 groups. A fresh dispatch can assign a - /// different physical wave to a group; wave-lane index identifies the - /// continuation within a full, single-wave group. + /// Native wave32 uses the hardware lane in a single full wave. Split + /// wave64 recreates the flat console thread ID on every dispatch, including + /// when the hardware schedules the waves in a different order. pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { - if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { + let lanes: u32 = threads.into_iter().try_fold(1u32, u32::checked_mul)?; + let multi = split_tid.is_some() && lanes > 64; + if self.m.globals.iter().any(|g| !g.constant + && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs")) + && !(multi && g.name == "xcl_xc")) + { return None; } if self.m.blocks.iter().map(Vec::len).sum::() <= limit { return None; } @@ -76,6 +120,8 @@ impl Shader { for &i in self.m.blocks.iter().flatten() { self.m.insts[i as usize].op.for_each_operand(|v| { consumed.insert(v); }); } + let root_is = |v, name| self.m.global_root(v).is_some_and(|g| self.m.globals[g].name == name); + let spins: HashSet<_> = self.m.spin_regions.iter().flatten().copied().collect(); for (b, block) in self.m.blocks.iter().enumerate() { // In a single split console wave each inter-half exchange begins // with TGSM stores, one rendezvous, peer loads and a rendezvous. @@ -84,10 +130,15 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::AtomicRmw(super::RmwOp::Add, p, _) if multi && root_is(*p, "xcl_xc") => {} + Op::Load(p, _) | Op::Store(p, _, _) if multi && root_is(*p, "xcl_xs") => {} + Op::Call(f, args) if multi && spins.contains(&Block(b as u32)) + && self.m.funcs[*f as usize].name == "dx.op.barrier" + && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::TGSM_FENCE as u64) => {} Op::Alloca(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => return None, - Op::Store(..) if split_tid.is_some() && exchange <= 1 => exchange = 1, + Op::Store(..) if split_tid.is_some() && !multi && exchange <= 1 => exchange = 1, Op::Load(p, _) if self.m.global_root(*p).is_some_and(|g| self.m.globals[g].constant) => {} - Op::Load(..) if split_tid.is_some() && matches!(exchange, 2 | 3) => exchange = 3, + Op::Load(..) if split_tid.is_some() && !multi && matches!(exchange, 2 | 3) => exchange = 3, Op::Load(..) | Op::Store(..) => return None, Op::Call(f, args) if self.m.funcs[*f as usize].name == "dx.op.barrier" && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64) => { @@ -113,11 +164,19 @@ impl Shader { } stride = stride.max(words); } - let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix)).collect::>>()?; - Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) + let mut shared = Vec::new(); + if multi { + for (i, g) in self.m.globals.iter().enumerate().filter(|(_, g)| matches!(g.name.as_str(), "xcl_xc" | "xcl_xs")) { + let TypeDef::Array(n, _) = self.m.types[g.ty.0 as usize] else { return None }; + shared.push((Value::Global(i as u32), u32::try_from(n).ok()?, stride)); + stride = stride.checked_add(u32::try_from(n).ok()?.div_ceil(lanes))?; + } + } + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix, &shared)).collect::>>()?; + Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(lanes)? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, threads: [u32; 3], prefix: &[u32], shared: &[(Value, u32, u32)]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -128,7 +187,12 @@ impl Shader { values.insert(Value::Inst(id), dst.m.push(op, def.ty)); } let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); - let scratch = Scratch::new(&mut dst, stride, threads[0], lane); + let lanes = threads.iter().product(); + let scratch = Scratch::new(&mut dst, stride, lanes, lane); + if stage > 0 && !shared.is_empty() { + scratch.transfer_shared(&mut dst, lane, lanes, shared, true); + } + let dispatch_entry = dst.m.current_block(); let local: HashMap<_, _> = plan.blocks[stage].iter().map(|&b| (b, dst.m.new_block())).collect(); let mut hops = HashMap::new(); let mut exits = HashMap::new(); @@ -170,7 +234,7 @@ impl Shader { hops.insert((edge.from, edge.to), hop); } } - dst.m.set_block(Block(0)); + dst.m.set_block(dispatch_entry); if let Some(sel) = selector { dst.m.switch(sel, done, &cases); dst.m.set_block(merge); @@ -200,6 +264,8 @@ impl Shader { dst.m.br(local[&Block(0)]); } dst.m.set_block(done); + let checkpoint = !shared.is_empty() && stage + 1 < plan.blocks.len(); + if checkpoint { scratch.transfer_shared(&mut dst, lane, lanes, shared, false); } dst.m.ret(); // Assign all instruction identities before fixing operands. A loop's @@ -213,6 +279,7 @@ impl Shader { if matches!(old.op, Op::Ret) && stage + 1 < plan.blocks.len() { let zero = dst.m.i32c(0); dst.raw_store(scratch.uav, scratch.base, &[zero]); + if checkpoint { dst.m.br(done); continue; } } let v = dst.m.push(old.op.clone(), old.ty); values.insert(Value::Inst(i), v); @@ -257,7 +324,7 @@ impl Shader { } } dst.raw_store(scratch.uav, scratch.base, &[tag]); - dst.m.ret(); + if checkpoint { dst.m.br(done); } else { dst.m.ret(); } } dst.infer_piece_features(); // a refused piece leaves the whole program unsplit: say so @@ -313,7 +380,7 @@ impl Module { fn indexed(&self, v: Value) -> Option { let op = &self.insts[inst(v)?].op; if let Op::Gep(Value::Global(g), indices) = op { - if self.globals[*g as usize].name == "xcl_xs" && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { + if matches!(self.globals[*g as usize].name.as_str(), "xcl_xs" | "xcl_xc") && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { return Some(indices[1]); } } @@ -438,7 +505,7 @@ impl Module { let mut visited = vec![false; self.blocks.len()]; let mut blocks = vec![Vec::new()]; let mut stages = vec![usize::MAX; self.blocks.len()]; - let mut used = 0; + let mut components = Vec::new(); for &root in &order { if visited[root] { continue; @@ -457,16 +524,40 @@ impl Module { } } } - if cost > limit { - return None; + for &b in &component { + stages[b] = components.len(); } + components.push((cost, component)); + } + // A wait polling the peer's counter cannot complete if the peer's + // signal was deferred to another dispatch. Pack these SCCs together. + let mut through: Vec = (0..components.len()).collect(); + for region in &self.spin_regions { + let mut span = region.iter().map(|b| stages[b.0 as usize]).filter(|&i| i != usize::MAX); + if let Some(i) = span.next() { + let (lo, hi) = span.fold((i, i), |(lo, hi), i| (lo.min(i), hi.max(i))); + through[lo] = through[lo].max(hi); + } + } + let mut i = 0; + let mut used = 0; + while i < components.len() { + let first = i; + let mut last = i; + let mut cost = 0; + while i <= last { + last = last.max(through[i]); + cost += components[i].0; + i += 1; + } + if cost > limit { return None; } if used + cost > limit { blocks.push(Vec::new()); used = 0; } used += cost; - for b in component { - stages[b] = blocks.len() - 1; + for (_, component) in &components[first..i] { + for &b in component { stages[b] = blocks.len() - 1; } } } @@ -659,6 +750,64 @@ mod tests { assert!(chain.pieces.len() >= 2); } + #[test] + fn dispatch_chain_four_wave64s_preserves_partner_epochs() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [16, 16, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let half = lw.lshrc(tid, 5); + let group = lw.s.group_id(0); + let group_base = lw.shlc(group, 8); + let index = lw.add(group_base, tid); + let addr = lw.shlc(index, 2); + let mem = lw.mems[0]; + let initial = lw.s.raw_load(mem, addr, 1)[0]; + let acc = lw.tmp_var(); + lw.wr(acc, initial); + let odd_wave = lw.andc(tid, 64); + let odd_wave = lw.nz(odd_wave); + // Only odd guest waves perform every exchange. A single common + // exchange count for all guest waves would corrupt their results. + for round in 1..=12 { + let mut exchange = |lw: &mut Lw| { + let payload = lw.addc(half, round); + let peer = lw.exchange(payload); + let old = lw.rd(acc); + let sum = lw.add(old, peer); + lw.wr(acc, sum); + Ok(()) + }; + if round % 2 == 1 { lw.guarded(odd_wave, &mut exchange).unwrap(); } + else { exchange(&mut lw).unwrap(); } + let next = lw.block(Some(1)); + lw.br(next); + lw.s.m.set_block(next); + } + let v = lw.rd(acc); + lw.s.raw_store(mem, addr, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 160).expect("split four guest waves"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + let input: Vec = (1..=512).collect(); + let expected: Vec<_> = input.iter().enumerate().map(|(i, v)| { + let tid = i as u32 % 256; + v + (1..=12).filter(|round| round % 2 == 0 || tid & 64 != 0) + .map(|round| ((tid / 32) ^ 1) + round).sum::() + }).collect(); + let groups = [2, 1, 1]; + let reference = runner::dispatch(&whole, groups, &[], &input).unwrap(); + assert_eq!(reference, expected); + assert_eq!(runner::dispatch_split(&chain, groups, &input).unwrap(), reference); + } + #[test] fn dispatch_chain_wave32_live_loops() { compare(32); } diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index c11d20353..8b84fb48b 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -72,6 +72,13 @@ SGPRs of both halves and the tests fail if they ever differ. are resident on one SM / CU) but not necessarily on WARP. `XCL_WAVE64_SPIN=1` forces this variant everywhere (the test suite passes with it too). +For direct compute dispatches split across pipelines, a group of full console waves can +carry the exchange state through scratch. A signal and its bounded wait stay in one piece. +All threads meet at the piece exit and copy the arrival counters and both banks of slots. +The next piece assigns logical thread IDs again, restores the shared words and synchronises +before following each lane's continuation. Each console wave keeps its own exchange count, +including when other waves skip the piece. Programs using guest LDS stay on the whole pipeline. + A console wave whose upper half does not exist (group of 32 or 96 threads) exchanges with nobody: the missing lanes count as inactive (ballot bits 0), exactly as on the console. The GS phase of ES+GS runs in the lower half only (≤ 21 primitives), likewise without a partner. From 8b2fa0e28c2773dd8b28cd6b5a95eee5517e9732 Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:03:57 -0500 Subject: [PATCH 7/8] Tests: keep exited guest waves in dispatch checkpoints Adopt WebIdentity1's four-wave fixture. Two guest waves return at different points while the other waves keep exchanging. Compare the whole shader and the dispatch chain to the CPU oracle across a 3D grid. Source: https://github.com/xcl-dev/xcl/pull/2097#issuecomment-7152422936 Assisted-by: OpenAI Codex (GPT-6) Co-authored-by: WebIdentity1 <212448219+WebIdentity1@users.noreply.github.com> --- crates/xcl/src/gpu/dxil/module/split.rs | 85 +++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index e6b65d091..9eaa2e1ed 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -808,6 +808,91 @@ mod tests { assert_eq!(runner::dispatch_split(&chain, groups, &input).unwrap(), reference); } + /// Guest waves that returned still participate in the checkpoint rendezvous + /// while other waves keep advancing their partner counters and slot banks. + #[test] + fn dispatch_chain_exited_waves_preserve_other_waves_3d() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + println!("CHAIN_EXIT_GPU={}", runner::adapter().unwrap()); + let geometry = [16, 16, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let half = lw.lshrc(tid, 5); + let wave = lw.lshrc(tid, 6); + let [x, y, z] = [0, 1, 2].map(|axis| lw.s.group_id(axis)); + let z = lw.shlc(z, 1); + let row = lw.add(z, y); + let row = lw.shlc(row, 1); + let group = lw.add(row, x); + let base = lw.shlc(group, 8); + let index = lw.add(base, tid); + let addr = lw.shlc(index, 2); + let mem = lw.mems[0]; + let initial = lw.s.raw_load(mem, addr, 1)[0]; + let acc = lw.tmp_var(); + lw.wr(acc, initial); + let not_second_wave = lw.cmpc(Pred::Ne, wave, 1); + for round in 1..=12 { + if round == 1 || round == 7 { + let exit = lw.block(Some(1)); + let live = lw.block(Some(1)); + let stops = lw.cmpc(Pred::Eq, wave, if round == 1 { 0 } else { 2 }); + lw.cond_br(stops, exit, live); + lw.s.m.set_block(exit); + let old = lw.rd(acc); + let value = if round == 1 { lw.addc(old, 100_000) } else { old }; + lw.s.raw_store(mem, addr, &[value]); + lw.s.m.ret(); + lw.s.m.set_block(live); + } + let mut exchange = |lw: &mut Lw| { + let payload = lw.addc(half, round); + let peer = lw.exchange(payload); + let old = lw.rd(acc); + let value = lw.add(old, peer); + lw.wr(acc, value); + Ok(()) + }; + if round % 2 == 1 { lw.guarded(not_second_wave, &mut exchange).unwrap(); } + else { exchange(&mut lw).unwrap(); } + let next = lw.block(Some(1)); + lw.br(next); + lw.s.m.set_block(next); + } + let value = lw.rd(acc); + lw.s.raw_store(mem, addr, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 160).expect("split with exited guest waves"); + assert!(chain.pieces.len() >= 3); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid whole shader"); + let input: Vec<_> = (0..2064u32).map(|i| if i < 2048 { i + 17 } else { 0xdeadbeef }).collect(); + let expected: Vec<_> = input.iter().enumerate().map(|(i, &v)| { + if i >= 2048 { return v; } + let tid = i as u32 % 256; + let peer = (tid / 32) ^ 1; + match tid / 64 { + 0 => v + 100_000, + 1 => v + 6 * peer + 42, + 2 => v + 6 * peer + 21, + _ => v + 12 * peer + 78, + } + }).collect(); + println!("CHAIN_EXIT_STAGE whole pieces={} scratch_dwords_per_group={}", chain.pieces.len(), chain.dwords_per_group); + let reference = runner::dispatch(&whole, [2, 2, 2], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program CPU oracle"); + println!("CHAIN_EXIT_STAGE split"); + let result = runner::dispatch_split(&chain, [2, 2, 2], &input).unwrap(); + assert_eq!(result, expected, "split program CPU oracle"); + println!("CHAIN_EXIT checked_words=2048 guards=16 pieces={} scratch_dwords_per_group={}", chain.pieces.len(), chain.dwords_per_group); + } + #[test] fn dispatch_chain_wave32_live_loops() { compare(32); } From 4de52614fa58e20fb2b62896bd9a65212dcf9ec0 Mon Sep 17 00:00:00 2001 From: joeypercia <81598667+joeypercia@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:44:29 -0800 Subject: [PATCH 8/8] Recompiler: split direct compute programs that use guest LDS The dispatch-chain splitter kept every program with guest LDS whole: its mutable-global check refused xcl_lds, and its scan refused LDS loads, stores and atomics and guest barriers. Now the LDS (with the split form's exchange words at its top) is copied to the per-group scratch at each piece exit and back at the next piece's start, like the exchange slots of several split waves. Geps into it can cross a cut as their index. In the split form the lane counter lives in the LDS too, so a piece meets once more before restoring over it. One console wave follows the guest's scalar control flow, so any cut keeps its guest barriers paired. A group of several waves can branch and return apart: a piece of such a program starts only at a component every thread enters exactly once (no earlier edge jumps past it, no earlier block returns), and a loop that reads the LDS (a load or an atomic), which could poll for another wave's write past a cut, keeps the program whole. --- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/module/split.rs | 408 +++++++++++++++++++++++- docs/wave64-on-wave32.md | 4 +- 3 files changed, 405 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 297cfbce4..c1cc9d397 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -659,7 +659,7 @@ fn dispatch_chain_native_wave64_builds_whole() { lw.s.m.ret(); lw.s.m.optimize(); // Exercise the native-wave admission gate with an otherwise partitionable CFG. - assert!(lw.s.m.dispatch_plan(64).is_some()); + assert!(lw.s.m.dispatch_plan(64, None).is_some()); let program = lw.finish_dispatch(threads, 64, 64, None).unwrap(); assert!(program.dispatch_chain.is_none()); super::validate::validate(&program.dxil).expect("valid native wave64 whole shader"); diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 9eaa2e1ed..ca2881eb4 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -104,7 +104,11 @@ impl Shader { pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { let lanes: u32 = threads.into_iter().try_fold(1u32, u32::checked_mul)?; let multi = split_tid.is_some() && lanes > 64; - if self.m.globals.iter().any(|g| !g.constant + // The guest LDS (with the split form's exchange words at its top) is + // saved and restored at each cut, and the plan cuts it only where the + // whole group passes. + let lds = self.m.globals.iter().position(|g| g.name == "xcl_lds"); + if self.m.globals.iter().any(|g| !g.constant && g.name != "xcl_lds" && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs")) && !(multi && g.name == "xcl_xc")) { @@ -122,6 +126,7 @@ impl Shader { } let root_is = |v, name| self.m.global_root(v).is_some_and(|g| self.m.globals[g].name == name); let spins: HashSet<_> = self.m.spin_regions.iter().flatten().copied().collect(); + let mut reads = HashSet::new(); for (b, block) in self.m.blocks.iter().enumerate() { // In a single split console wave each inter-half exchange begins // with TGSM stores, one rendezvous, peer loads and a rendezvous. @@ -130,6 +135,12 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::Store(p, _, _) if lds.is_some() && root_is(*p, "xcl_lds") => {} + Op::Load(p, _) | Op::AtomicRmw(_, p, _) | Op::CmpXchg(p, _, _) if lds.is_some() && root_is(*p, "xcl_lds") => { + if !spins.contains(&Block(b as u32)) { reads.insert(Block(b as u32)); } + } + Op::Call(f, args) if lds.is_some() && self.m.funcs[*f as usize].name == "dx.op.barrier" + && self.m.const_u64(args[1]) == Some(crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64) => {} Op::AtomicRmw(super::RmwOp::Add, p, _) if multi && root_is(*p, "xcl_xc") => {} Op::Load(p, _) | Op::Store(p, _, _) if multi && root_is(*p, "xcl_xs") => {} Op::Call(f, args) if multi && spins.contains(&Block(b as u32)) @@ -155,7 +166,14 @@ impl Shader { } if exchange != 0 { return None; } } - let plan = self.m.dispatch_plan(limit)?; + // One console wave follows the guest's scalar control flow: its threads + // diverge only in guarded per-lane accesses, which hold no barrier or + // return, so any cut keeps its guest barriers paired. Several waves + // can branch apart and return apart, so they are cut only where the + // whole group passes. A loop that reads the LDS (a load or an atomic) + // may poll it until another wave writes past a cut, so such a loop + // keeps the program whole. + let plan = self.m.dispatch_plan(limit, lds.filter(|_| multi).map(|_| &reads))?; let mut stride = 1; for edge in &plan.edges { let mut words = 1; @@ -172,6 +190,11 @@ impl Shader { stride = stride.checked_add(u32::try_from(n).ok()?.div_ceil(lanes))?; } } + if let Some(g) = lds { + let TypeDef::Array(n, _) = self.m.types[self.m.globals[g].ty.0 as usize] else { return None }; + shared.push((Value::Global(g as u32), u32::try_from(n).ok()?, stride)); + stride = stride.checked_add(u32::try_from(n).ok()?.div_ceil(lanes))?; + } let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, threads, &prefix, &shared)).collect::>>()?; Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(lanes)? }) } @@ -190,6 +213,11 @@ impl Shader { let lanes = threads.iter().product(); let scratch = Scratch::new(&mut dst, stride, lanes, lane); if stage > 0 && !shared.is_empty() { + // The split form's lane counter is in the LDS: every wave takes + // its lanes before any restore overwrites it. + if !prefix.is_empty() && shared.iter().any(|&(g, ..)| src.global_root(g).is_some_and(|g| src.globals[g].name == "xcl_lds")) { + dst.barrier(crate::gpu::dxil::ops::barrier::GROUP_SYNC); + } scratch.transfer_shared(&mut dst, lane, lanes, shared, true); } let dispatch_entry = dst.m.current_block(); @@ -380,7 +408,7 @@ impl Module { fn indexed(&self, v: Value) -> Option { let op = &self.insts[inst(v)?].op; if let Op::Gep(Value::Global(g), indices) = op { - if matches!(self.globals[*g as usize].name.as_str(), "xcl_xs" | "xcl_xc") && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { + if matches!(self.globals[*g as usize].name.as_str(), "xcl_xs" | "xcl_xc" | "xcl_lds") && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { return Some(indices[1]); } } @@ -487,7 +515,12 @@ impl Module { } } - pub(crate) fn dispatch_plan(&self, limit: usize) -> Option { + /// `uniform`: the program shares state across its thread group (guest + /// LDS and barriers). A piece then starts only at a component that every + /// thread enters exactly once, so the group meets at each cut and a guest + /// barrier in a piece sees the same threads as in the whole program. A + /// loop over a block of `uniform` keeps the whole program. + pub(crate) fn dispatch_plan(&self, limit: usize, uniform: Option<&HashSet>) -> Option { let (order, _) = self.block_layout(); let count = |b: usize| self.blocks[b].len(); if limit == 0 || order.iter().copied().map(count).sum::() <= limit { @@ -539,13 +572,31 @@ impl Module { through[lo] = through[lo].max(hi); } } + // Components are in topological order. A cut before component `i` + // is crossed once by every thread when no earlier edge jumps past `i` + // and no earlier block returns. + let mut starts = vec![true; components.len()]; + if let Some(pinned) = uniform { + let mut reach = 0; + let mut returned = false; + for (i, (_, component)) in components.iter().enumerate() { + starts[i] = reach <= i && !returned; + for &b in component { + let next = self.successors(b); + let looped = component.len() > 1 || next.contains(&Block(b as u32)); + if looped && pinned.contains(&Block(b as u32)) { return None; } + returned |= next.is_empty(); + reach = next.iter().map(|t| stages[t.0 as usize]).fold(reach, usize::max); + } + } + } let mut i = 0; let mut used = 0; while i < components.len() { let first = i; let mut last = i; let mut cost = 0; - while i <= last { + while i <= last || (i < components.len() && !starts[i]) { last = last.max(through[i]); cost += components[i].0; i += 1; @@ -624,7 +675,7 @@ impl Module { #[cfg(test)] mod tests { use crate::gpu::{ - dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::{BinOp, CastOp, Pred}}, + dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::{BinOp, CastOp, Pred, Value}}, recomp::{runner, CsInterface}, }; @@ -991,7 +1042,7 @@ mod tests { lw.s.raw_store(mem, offset, &[final_value]); lw.s.m.ret(); lw.s.m.optimize(); - let plan = lw.s.m.dispatch_plan(64).expect("partition branch fixture"); + let plan = lw.s.m.dispatch_plan(64, None).expect("partition branch fixture"); let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); assert!(plan.edges.iter().any(|edge| stage(edge.to) > stage(edge.from) + 1), "exercise a forward skip over an intermediate piece"); let chain = lw.s.split_compute(geometry, split.then_some(tid), 64).expect("split branch fixture"); @@ -1017,4 +1068,347 @@ mod tests { } } + /// A program with the guest LDS, as the translator declares it when the + /// console code has a DS instruction. + fn lds_lw(threads: u32, split: bool) -> Lw { + let ds = crate::gpu::rdna2::encode("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 0)], None).unwrap(); + let ds = crate::gpu::rdna2::decode(&ds, 0).unwrap(); + let cs = CsInterface { threads: [threads, 1, 1], ..Default::default() }; + let options = KernelOptions { wave64: split, split, mem_windows: 1, sampler_base: 0 }; + let lw = Lw::new(std::slice::from_ref(&ds), &Default::default(), options, &Entry::Compute(cs)); + assert!(lw.lds.is_some()); + lw + } + + /// One loop per round, run `(tid & 3) + 1` times by each lane: `v += trips * (x + round)`. + fn lane_loops(lw: &mut Lw, rounds: std::ops::RangeInclusive, mut v: Value, x: Value, trips: Value) -> Value { + let i32 = lw.s.m.i32(); + let zero = lw.c(0); + for round in rounds { + let pred = lw.cur(); + let body = lw.s.m.new_block(); + let exit = lw.s.m.new_block(); + lw.s.m.br(body); + lw.s.m.set_block(body); + let counter = lw.s.m.phi(i32); + let acc = lw.s.m.phi(i32); + lw.s.m.add_incoming(counter, zero, pred); + lw.s.m.add_incoming(acc, v, pred); + let next = lw.addc(counter, 1); + v = lw.add(acc, x); + v = lw.addc(v, round); + lw.s.m.add_incoming(counter, next, body); + lw.s.m.add_incoming(acc, v, body); + let again = lw.cmp(Pred::ULt, next, trips); + lw.s.m.cond_br(again, body, exit); + lw.s.m.set_block(exit); + } + v + } + + fn lds_read(lw: &mut Lw, index: Value) -> Value { + let g = lw.lds.unwrap(); + let p = lw.s.gs_ptr(g, index); + lw.s.m.load(p, 4) + } + + fn lds_write(lw: &mut Lw, index: Value, v: Value) { + let g = lw.lds.unwrap(); + let p = lw.s.gs_ptr(g, index); + lw.s.m.store(p, v, 4); + } + + fn guest_barrier(lw: &mut Lw) { + lw.s.barrier(crate::gpu::dxil::ops::barrier::GROUP_SYNC); + } + + /// Every thread enters each piece of `plan` once, at one block, and only + /// the last piece returns: the group meets at every cut. + fn uniform_cuts(plan: &super::Plan, m: &crate::gpu::dxil::module::Module) -> bool { + let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); + let last = plan.blocks.len() - 1; + let returns = plan.blocks[..last].iter().flatten().any(|&b| m.successors(b.0 as usize).is_empty()); + let skips = plan.edges.iter().any(|e| stage(e.to) != stage(e.from) + 1); + let entries = (1..=last).any(|k| plan.edges.iter().filter(|e| stage(e.to) == k).map(|e| e.to).collect::>().len() != 1); + !returns && !skips && !entries + } + + /// Negative control: without the group-uniform rule, some plan of `m` has + /// a cut that not every thread crosses. With it, none does. + fn cuts_only_where_the_group_meets(m: &crate::gpu::dxil::module::Module) { + let limits = 40..=160; + assert!(limits.clone().filter_map(|limit| m.dispatch_plan(limit, None)).any(|plan| !uniform_cuts(&plan, m)), + "the fixture has cuts the group does not pass together"); + let plans: Vec<_> = limits.filter_map(|limit| m.dispatch_plan(limit, Some(&Default::default()))).collect(); + assert!(plans.iter().any(|plan| plan.blocks.len() >= 3)); + assert!(plans.iter().all(|plan| uniform_cuts(plan, m)), "a cut the group does not pass together"); + } + + /// The guest LDS crosses cuts: written and counted with an LDS atomic before + /// a guest barrier, read by other threads (other halves and waves) after + /// several cuts, written and read again across a second barrier. Lanes take + /// different loop counts; with several waves, odd and even waves take + /// different branches, where the group may not be cut. + fn lds_chain(threads: u32, split: bool) { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [threads, 1, 1]; + let multi = threads > 64; + let mut lw = lds_lw(threads, split); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let group = lw.s.group_id(0); + let count = lw.c(threads); + let base = lw.mul(group, count); + let index = lw.add(base, tid); + let offset = lw.shlc(index, 2); + let x = lw.s.raw_load(mem, offset, 1)[0]; + // the halves' exchange keeps its state in the translator's SSA, which + // knows only the entry block here + let peer_half = split.then(|| { + let half = lw.half; + lw.exchange(half) + }); + let mode = lw.andc(tid, 3); + let trips = lw.addc(mode, 1); + let three = lw.c(3); + let a = lw.mul(x, three); + let a = lw.addc(a, 1); + lds_write(&mut lw, tid, a); + let counter = lw.c(4000); + let zero = lw.c(0); + lds_write(&mut lw, counter, zero); + guest_barrier(&mut lw); + let g = lw.lds.unwrap(); + let p = lw.s.gs_ptr(g, counter); + lw.s.m.atomic_rmw(crate::gpu::dxil::module::RmwOp::Add, p, x); + guest_barrier(&mut lw); + let mut v = lane_loops(&mut lw, 1..=8, x, x, trips); + let other = lw.addc(tid, 33); + let n = lw.c(threads); + let other = lw.bin(BinOp::URem, other, n); + let peer = lds_read(&mut lw, other); + let sum = lds_read(&mut lw, counter); + v = lw.add(v, peer); + v = lw.add(v, sum); + if multi { + let odd = lw.andc(tid, 64); + let odd = lw.nz(odd); + let (xb, yb, join) = (lw.s.m.new_block(), lw.s.m.new_block(), lw.s.m.new_block()); + lw.s.m.cond_br(odd, xb, yb); + lw.s.m.set_block(xb); + let vx = lane_loops(&mut lw, 20..=21, v, x, trips); + let xe = lw.cur(); + lw.s.m.br(join); + lw.s.m.set_block(yb); + let vy = lane_loops(&mut lw, 30..=31, v, x, trips); + let ye = lw.cur(); + lw.s.m.br(join); + lw.s.m.set_block(join); + let i32 = lw.s.m.i32(); + v = lw.s.m.phi(i32); + lw.s.m.add_incoming(v, vx, xe); + lw.s.m.add_incoming(v, vy, ye); + } + if let Some(peer_half) = peer_half { + v = lw.add(v, peer_half); + } + guest_barrier(&mut lw); + lds_write(&mut lw, tid, v); + guest_barrier(&mut lw); + v = lane_loops(&mut lw, 9..=16, v, x, trips); + let last = lw.c(threads - 1); + let mirror = lw.sub(last, tid); + let mirrored = lds_read(&mut lw, mirror); + v = lw.add(v, mirrored); + lw.s.raw_store(mem, offset, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + + let limit = if multi { 80 } else { 56 }; + let chain = lw.s.split_compute(geometry, split.then_some(tid), limit).expect("split the LDS program"); + assert!(chain.pieces.len() >= 3, "{} pieces", chain.pieces.len()); + if multi { + cuts_only_where_the_group_meets(&lw.s.m); + } + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); + let groups = 3; + let words = (threads * groups) as usize; + let input: Vec = (0..words + 16).map(|i| if i < words { (i as u32).wrapping_mul(2654435761) >> 8 } else { 0xdeadbeef }).collect(); + let mut expected = input.clone(); + for g in 0..groups as usize { + let n = threads as usize; + let x = &input[g * n..(g + 1) * n]; + let loops = |t: usize, rounds: std::ops::RangeInclusive| rounds.map(|r| ((t as u32 & 3) + 1).wrapping_mul(x[t].wrapping_add(r))).fold(0u32, u32::wrapping_add); + let sum = x.iter().fold(0u32, |a, &b| a.wrapping_add(b)); + let stored: Vec = (0..n).map(|t| { + let mut v = x[t].wrapping_add(loops(t, 1..=8)); + v = v.wrapping_add(x[(t + 33) % n].wrapping_mul(3).wrapping_add(1)).wrapping_add(sum); + if multi { v = v.wrapping_add(loops(t, if t & 64 != 0 { 20..=21 } else { 30..=31 })); } + if split { v = v.wrapping_add((t as u32 >> 5 & 1) ^ 1); } + v + }).collect(); + for t in 0..n { + expected[g * n + t] = stored[t].wrapping_add(loops(t, 9..=16)).wrapping_add(stored[n - 1 - t]); + } + } + let reference = runner::dispatch(&whole, [groups, 1, 1], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program, {threads} threads"); + let result = runner::dispatch_split(&chain, [groups, 1, 1], &input).unwrap(); + assert_eq!(result, expected, "split program, {threads} threads"); + println!("CHAIN_LDS threads={threads} split={split} pieces={} scratch_dwords_per_group={} checked_words={words} guards=16", chain.pieces.len(), chain.dwords_per_group); + } + + #[test] + fn dispatch_chain_lds_wave32() { lds_chain(32, false); } + + #[test] + fn dispatch_chain_lds_wave64_split() { lds_chain(64, true); } + + #[test] + fn dispatch_chain_lds_two_wave64s() { lds_chain(128, true); } + + #[test] + fn dispatch_chain_lds_three_wave64s() { lds_chain(192, true); } + + #[test] + fn dispatch_chain_lds_four_wave64s() { lds_chain(256, true); } + + /// Guest wave 0 returns early and the other waves meet at guest barriers + /// afterwards. A cut after the return would leave wave 0 waiting at the + /// piece exit while the others wait at a guest barrier: the plan keeps + /// everything from the return on in the last piece. + #[test] + fn dispatch_chain_lds_cuts_before_a_guest_wave_returns() { + let threads = 256; + let geometry = [threads, 1, 1]; + let mut lw = lds_lw(threads, true); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let group = lw.s.group_id(0); + let count = lw.c(threads); + let base = lw.mul(group, count); + let index = lw.add(base, tid); + let offset = lw.shlc(index, 2); + let x = lw.s.raw_load(mem, offset, 1)[0]; + let mode = lw.andc(tid, 3); + let trips = lw.addc(mode, 1); + lds_write(&mut lw, tid, x); + guest_barrier(&mut lw); + let mut v = lane_loops(&mut lw, 1..=14, x, x, trips); + let wave = lw.lshrc(tid, 6); + let first = lw.cmpc(Pred::Eq, wave, 0); + let (exit, live) = (lw.s.m.new_block(), lw.s.m.new_block()); + lw.s.m.cond_br(first, exit, live); + lw.s.m.set_block(exit); + lw.s.raw_store(mem, offset, &[v]); + lw.s.m.ret(); + lw.s.m.set_block(live); + v = lane_loops(&mut lw, 15..=16, v, x, trips); + guest_barrier(&mut lw); + lds_write(&mut lw, tid, v); + guest_barrier(&mut lw); + v = lane_loops(&mut lw, 17..=18, v, x, trips); + let other = lw.c(255); + let other = lw.sub(other, tid); + let peer = lds_read(&mut lw, other); + v = lw.add(v, peer); + lw.s.raw_store(mem, offset, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + + let limit = 64; + let m = &lw.s.m; + let ret = |b: &super::Block| m.successors(b.0 as usize).is_empty(); + let barrier = |b: &super::Block| m.blocks[b.0 as usize].iter().any(|&i| matches!(&m.insts[i as usize].op, + super::Op::Call(f, _) if m.funcs[*f as usize].name == "dx.op.barrier")); + // the guest barriers that wave 0 skips by returning + let fork = (0..m.blocks.len()).find(|&b| { let s = m.successors(b); s.len() == 2 && s.iter().any(ret) }).unwrap(); + let mut after = std::collections::BTreeSet::new(); + let mut work = m.successors(fork); + while let Some(b) = work.pop() { + if after.insert(b) { work.extend(m.successors(b.0 as usize)); } + } + // one of them in a piece that wave 0 still has to pass + let late_barrier = |plan: &super::Plan| plan.blocks[..plan.blocks.len() - 1].iter().flatten() + .any(|b| after.contains(b) && barrier(b)); + assert!((40..=160).filter_map(|limit| m.dispatch_plan(limit, None)).any(|plan| late_barrier(&plan)), + "the negative control cuts after the return"); + assert!((40..=160).filter_map(|limit| m.dispatch_plan(limit, Some(&Default::default()))).all(|plan| !late_barrier(&plan))); + cuts_only_where_the_group_meets(m); + let plan = m.dispatch_plan(limit, Some(&Default::default())).unwrap(); + assert!(plan.blocks.len() >= 3, "{} pieces", plan.blocks.len()); + + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let chain = lw.s.split_compute(geometry, Some(tid), limit).expect("split before the return"); + assert_eq!(chain.pieces.len(), plan.blocks.len()); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + let input: Vec = (0..512 + 16).map(|i| if i < 512 { i * 7 + 3 } else { 0xdeadbeef }).collect(); + let mut expected = input.clone(); + for g in 0..2 { + let x = &input[g * 256..(g + 1) * 256]; + let loops = |t: usize, rounds: std::ops::RangeInclusive| rounds.map(|r| ((t as u32 & 3) + 1) * (x[t] + r)).sum::(); + let stored: Vec = (0..256).map(|t| x[t] + loops(t, 1..=14) + loops(t, 15..=16)).collect(); + for t in 0..256 { + expected[g * 256 + t] = if t < 64 { x[t] + loops(t, 1..=14) } + else { stored[t] + loops(t, 17..=18) + if 255 - t < 64 { x[255 - t] } else { stored[255 - t] } }; + } + } + let reference = runner::dispatch(&whole, [2, 1, 1], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program"); + assert_eq!(runner::dispatch_split(&chain, [2, 1, 1], &input).unwrap(), expected, "split program"); + } + + /// Another guest wave may poll the LDS in a loop (with an atomic or a + /// plain load) until a write that a cut would defer: such a group of + /// several waves stays whole. One wave cannot wait for another. + #[test] + fn dispatch_chain_lds_poll_loop_keeps_several_waves_whole() { + for (threads, looped, atomic) in [(128, true, true), (128, true, false), (128, false, true), (64, true, true), (64, true, false)] { + let geometry = [threads, 1, 1]; + let mut lw = lds_lw(threads, true); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + let x = lw.s.raw_load(mem, offset, 1)[0]; + let mode = lw.andc(tid, 3); + let trips = lw.addc(mode, 1); + let mut v = lane_loops(&mut lw, 1..=6, x, x, trips); + let g = lw.lds.unwrap(); + let zero = lw.c(0); + let p = lw.s.gs_ptr(g, zero); + if looped { + let pred = lw.cur(); + let body = lw.s.m.new_block(); + let exit = lw.s.m.new_block(); + lw.s.m.br(body); + lw.s.m.set_block(body); + let i32 = lw.s.m.i32(); + let old = lw.s.m.phi(i32); + lw.s.m.add_incoming(old, zero, pred); + let got = if atomic { lw.s.m.atomic_rmw(crate::gpu::dxil::module::RmwOp::Add, p, zero) } else { lw.s.m.load(p, 4) }; + lw.s.m.add_incoming(old, got, body); + let wait = lw.cmp(Pred::ULt, got, x); + lw.s.m.cond_br(wait, body, exit); + lw.s.m.set_block(exit); + v = lw.add(v, old); + } else { + let got = lw.s.m.atomic_rmw(crate::gpu::dxil::module::RmwOp::Add, p, x); + v = lw.add(v, got); + } + v = lane_loops(&mut lw, 7..=12, v, x, trips); + lw.s.raw_store(mem, offset, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, Some(tid), 48); + // one guest wave cannot wait for another + assert_eq!(chain.is_some(), !(looped && threads > 64), "{threads} threads, LDS polled in a loop: {looped}, atomic: {atomic}"); + } + } } diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 8b84fb48b..3dac90eef 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -77,7 +77,9 @@ carry the exchange state through scratch. A signal and its bounded wait stay in All threads meet at the piece exit and copy the arrival counters and both banks of slots. The next piece assigns logical thread IDs again, restores the shared words and synchronises before following each lane's continuation. Each console wave keeps its own exchange count, -including when other waves skip the piece. Programs using guest LDS stay on the whole pipeline. +including when other waves skip the piece. The guest LDS, with the exchange words at its top, +is copied the same way. A group of several console waves is then cut only before a block that +every thread reaches once without returning, so guest barriers pair as in the whole program. A console wave whose upper half does not exist (group of 32 or 96 threads) exchanges with nobody: the missing lanes count as inactive (ballot bits 0), exactly as on the console. The