diff --git a/README.md b/README.md index 91c019d824..a1fa9198df 100644 --- a/README.md +++ b/README.md @@ -374,6 +374,8 @@ Fill the reusable DXIL cache ahead of a run with the read-only package wrapper. Pipelines used by an earlier run are dequeued for preload before never-used speculative pipelines resume building ahead; demanded pipelines still overtake either kind. - Direct compute dispatches can split large programs into pipelines built in parallel. + With guest LDS, single-wave groups can use any thread-group dimensions for native wave32 + and wave64 emulated on wave32. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the target gets its own piece, up to four times the target. Larger components and indirect diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f57cf8d7c0..e8de338b94 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -316,6 +316,7 @@ fn translate_on_this_thread( } } let compute = matches!(entry, Entry::Compute(_)); + let mesh = matches!(entry, Entry::Mesh(_)); let split = o.wave64 && o.split && !gfx; // split wave64 LDS keeps the console wave's order through the halves' meets (`Lw::writes_lds`, // `lanes::lds_in_order`); `XCL_X_LDS_ORDER=0` leaves that out, and the HLSL path takes it @@ -362,13 +363,22 @@ fn translate_on_this_thread( Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); lw.safe_barrier_init(); - if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } + let total = cs.threads.iter().try_fold(1u32, |a, &b| a.checked_mul(b)).unwrap_or(0); + if split && total != 0 && total % 64 == 0 && (!uses_lds || total == 64) { + split_tid = Some(tid); + } else if !o.wave64 && !uses_lds && cs.threads[1] * cs.threads[2] > 1 && total > 32 && total % 32 == 0 { + split_tid = Some(tid); + } group_runs = Some(compute_init(&mut lw, cs, tid, gtid)); cs.threads } Entry::Mesh(ms) => { let (tid, _) = lw.setup_lanes_compute([ms.threads, 1, 1], uses_lds); lw.safe_barrier_init(); + // a two-pass mesh program's producer is a compute dispatch: it can run as a chain + if split && ms.threads != 0 && ms.threads % 64 == 0 && (!uses_lds || ms.threads == 64) { + split_tid = Some(tid); + } mesh_init(&mut lw, ms, tid, io); [ms.threads, 1, 1] } @@ -621,7 +631,7 @@ fn translate_on_this_thread( lw.s.m.set_block(prologue); lw.s.m.br(first); let hw = if split || !o.wave64 { 32 } else { 64 }; - let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; + let limit = if (compute && (!split || split_tid.is_some())) || (mesh && split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; lw.finish_dispatch(numthreads, hw, limit, split_tid) } @@ -846,28 +856,16 @@ impl Lw { } let stage = self.s.stage; let mut dispatch_chain = None; + let total = numthreads.iter().try_fold(1u32, |a, &b| a.checked_mul(b)).unwrap_or(0); + let native_w32 = !self.wave64 && !self.split && total >= 32 && total % 32 == 0 + && (self.lds.is_none() || total == 32); 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 { + } else if limit > 0 && (native_w32 || split_tid.is_some()) && hw == 32 { self.s.m.optimize(); - // A single split wave64 meets its other half through group-shared counters its entry - // zeroes (`Partner::Spin`), and the exchange's running number counts from the - // program's start: a later piece of a chain, a new dispatch, would wait for counts - // its own counters never reach. Such a program stays whole. - if split_tid.is_some() && self.partner == Partner::Spin { - let size: usize = (0..self.s.m.block_count()).map(|b| self.s.m.block_insts(Block(b as u32)).len()).sum(); - if size > limit { - static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); - let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - if n < 4 || n.is_power_of_two() { - crate::xlog_info!("compute split: a split wave64 compute program of {size} instructions stays whole: its halves exchange through group-shared counters a later dispatch would start again at zero ({} so far)", n + 1); - } - } - } else { - dispatch_chain = self.s.split_compute(numthreads, split_tid, limit).map(std::sync::Arc::new); - } + 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)) @@ -921,7 +919,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"); @@ -969,9 +967,13 @@ fn a_split_wave64_compute_program_stays_whole() { lw.s.raw_store(mem, offset, &[late]); lw.s.m.ret(); lw.s.m.optimize(); - assert!(lw.s.m.dispatch_plan(64).is_some(), "the program could be cut"); + assert!(lw.s.m.dispatch_plan(64, None).is_some(), "the program could be cut"); let program = lw.finish_dispatch(threads, 32, 64, Some(tid)).unwrap(); - assert!(program.dispatch_chain.is_none()); + let chain = program.dispatch_chain.as_ref().expect("split wave64 chain"); + assert!(chain.pieces.len() > 1); + for piece in &chain.pieces { + super::validate::validate(piece).expect("valid split wave64 chain piece"); + } super::validate::validate(&program.dxil).expect("valid split wave64 whole shader"); } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 5746adaa95..daccc4a8a3 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -130,7 +130,7 @@ impl Lw { let t = self.s.m.i1c(true); let rank = self.s.wave_prefix_bit_count(t); self.add(base, rank) - } else if y * z > 1 { + } else if y * z > 1 && total > lanes { let i32 = self.s.m.i32(); let (g, at) = match (self.lds, lds_top_word) { (Some(l), true) => (l, 8191), @@ -152,8 +152,13 @@ impl Lw { let base = self.sel(take, got, dflt); let base = self.s.wave_read_lane_first(base); let tid = self.add(base, hw); - self.s.barrier(barrier::GROUP_SYNC); + if lds_top_word && self.lds.is_some() { + self.s.barrier(barrier::GROUP_SYNC); + } tid + } else if y * z > 1 { + // single native wave (`total <= lanes`): base is always 0, so no `xcl_wt` counter or barriers + self.s.wave_lane_index() } else { self.s.flattened_thread_id_in_group() }; @@ -172,6 +177,8 @@ impl Lw { } let lane = if self.split { self.andc(tid, 63) + } else if y * z > 1 && total <= lanes { + tid } else { self.s.wave_lane_index() }; @@ -484,6 +491,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); @@ -583,6 +591,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 01b328a1c2..2eebcd5b0b 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -271,6 +271,7 @@ pub struct Module { def_block: Vec, blocks: Vec>, preserve_block_boundary: Vec, + spin_regions: Vec>, cur: Block, insert_before_term: bool, md: Vec, @@ -302,6 +303,7 @@ impl Module { blocks: vec![Vec::new()], preserve_block_boundary: vec![false], flat_reads: Vec::new(), + spin_regions: Vec::new(), cur: Block(0), insert_before_term: false, md: Vec::new(), @@ -559,6 +561,13 @@ impl Module { pub fn preserve_block_boundary(&mut self, b: Block) { self.preserve_block_boundary[b.0 as usize] = true; } + /// 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 fe11901212..d00fd65cfd 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -80,6 +80,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) @@ -87,11 +126,33 @@ 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. + /// Partition a full-wave compute entry into a dispatch chain. Single-wave + /// native wave32 groups identify continuations by `WaveGetLaneIndex()`, + /// 1-D multi-wave native wave32 groups by `FlattenedThreadIdInGroup()`, and + /// 2-D/3-D multi-wave or split-wave64 groups by replaying their `tid` prefix. 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 total = threads[0].checked_mul(threads[1])?.checked_mul(threads[2])?; + if total == 0 { + return None; + } + // 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 lds.is_some() && split_tid.is_none() && total != 32 { return None; } + let has_xs = split_tid.is_some() && self.m.globals.iter().any(|g| g.name == "xcl_xs"); + let has_xc = split_tid.is_some() && self.m.globals.iter().any(|g| g.name == "xcl_xc"); + let uses_spin = split_tid.is_some() && (has_xc || !self.m.spin_regions.is_empty()); + let multi = split_tid.is_some() && total > 64 && (has_xs || lds.is_some()); + // The early-exit-safe barrier of several hardware waves (`Lw::safe_barrier_sync`) polls + // groupshared words: its live-wave count and arrival state are saved and restored at + // each cut like the LDS. Its group syncs are in `Block(0)`. Pieces run in the order of + // the program's flow and keep a loop whole, so a wave polling in a piece waits only + // for waves that arrive at that barrier in that piece or have already arrived. + let bar = self.m.globals.iter().position(|g| g.name == "xcl_bar"); + if self.m.globals.iter().any(|g| !g.constant && g.name != "xcl_lds" && g.name != "xcl_bar" + && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs" | "xcl_wt" | "xcl_xc"))) + { return None; } if self.m.blocks.iter().map(Vec::len).sum::() <= limit { return None; } @@ -104,6 +165,9 @@ 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(); + 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. @@ -112,12 +176,30 @@ impl Shader { for &i in block { if b == 0 && prefix.contains(&i) { continue; } match &self.m.insts[i as usize].op { + Op::Load(p, _) | Op::Store(p, _, _) | Op::AtomicRmw(_, p, _) | Op::CmpXchg(p, _, _) + if bar.is_some() && root_is(*p, "xcl_bar") => {} + 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) => {} + // the safe barrier's fences, and the group syncs of its set-up + Op::Call(f, args) if bar.is_some() && (uses_spin || !has_xs) + && self.m.funcs[*f as usize].name == "dx.op.barrier" + && matches!(self.m.const_u64(args[1]), Some(m) if m == crate::gpu::dxil::ops::barrier::TGSM_FENCE as u64 + || (b == 0 && m == crate::gpu::dxil::ops::barrier::GROUP_SYNC as u64)) => {} + Op::AtomicRmw(super::RmwOp::Add, p, _) | Op::CmpXchg(p, _, _) if uses_spin && root_is(*p, "xcl_xc") => {} + Op::Load(p, _) | Op::Store(p, _, _) if uses_spin && root_is(*p, "xcl_xs") => {} + Op::Call(f, args) if uses_spin && 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 has_xs && !uses_spin && 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 has_xs && !uses_spin && 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" + Op::Call(f, args) if has_xs && !uses_spin && 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 }; } @@ -136,7 +218,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))?; // Slot zero is the tag. Transported SSA values reuse slots across // non-overlapping piece lifetimes (`end < start`), so an outgoing store // can never overwrite a value restored by the same piece. @@ -150,12 +239,25 @@ impl Shader { } } (stride, slots) = self.m.reuse_piece_slots(&plan, &slots)?; - stride.checked_mul(threads[0])?.checked_mul(4)?; - let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix)).collect::>>()?; - Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) + let mut shared = Vec::new(); + if uses_spin { + 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(total))?; + } + } + for g in [lds, bar].into_iter().flatten() { + 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(total))?; + } + stride.checked_mul(total)?.checked_mul(4)?; + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, total, &prefix, &shared)).collect::>>()?; + Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(total)? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], total: u32, prefix: &[u32], shared: &[(Value, u32, u32)]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -167,8 +269,20 @@ impl Shader { let v = dst.m.push(op, def.ty); values.insert(Value::Inst(id), slab.group_id(src, &def.op, &mut dst.m, v)); } - let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); - let scratch = Scratch::new(&mut dst, &slab, stride, threads[0], lane); + let lane = prefix + .last() + .map(|&i| values[&Value::Inst(i)]) + .unwrap_or_else(|| if total == 32 { dst.wave_lane_index() } else { dst.flattened_thread_id_in_group() }); + let scratch = Scratch::new(&mut dst, &slab, stride, total, 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, total, 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(); @@ -191,7 +305,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 { for v in incoming { if values.contains_key(&v) { continue; } @@ -208,6 +322,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, total, shared, false); } dst.m.ret(); // Assign all instruction identities before fixing operands. A loop's @@ -221,6 +337,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), slab.group_id(src, &old.op, &mut dst.m, v)); @@ -265,7 +382,7 @@ impl Shader { } } dst.raw_store(scratch.uav, scratch.base, &[tag]); - dst.m.ret(); + if checkpoint { dst.m.br(done); } else { dst.m.ret(); } } src.place_restores(&mut dst, &scratch, slots, &deferred)?; dst.m.sink_cheap_piece_ops(); @@ -285,7 +402,7 @@ impl Shader { fn infer_piece_features(&mut self) { for f in [Feature::Doubles, Feature::Int64Ops, Feature::DoubleExtensions, - Feature::ResourceHeapIndexing, Feature::SamplerHeapIndexing] { + Feature::ResourceHeapIndexing, Feature::SamplerHeapIndexing, Feature::WaveOps] { self.features.remove(&f); } // typed UAV loads (`texture_load` without a mip): the whole program's flag stays only on @@ -295,12 +412,15 @@ impl Shader { 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" { + for &i in self.m.blocks.iter().flatten() { + if let Op::Call(f, args) = &self.m.insts[i as usize].op { + let name = &self.m.funcs[*f as usize].name; + if name == "dx.op.createHandleFromHeap" { self.features.insert(if self.m.const_u64(args[2]) == Some(0) { Feature::ResourceHeapIndexing } else { Feature::SamplerHeapIndexing }); + } else if name.starts_with("dx.op.wave") || name.starts_with("dx.op.quad") { + self.features.insert(Feature::WaveOps); } } } @@ -493,7 +613,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" | "xcl_lds" | "xcl_bar") && indices.len() == 2 && self.const_u64(indices[0]) == Some(0) { return Some(indices[1]); } } @@ -600,7 +720,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 { @@ -620,7 +745,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; @@ -639,11 +764,8 @@ impl Module { } } } - // The target is soft for an indivisible component. A component - // above it occupies a piece by itself; bound that exception so a - // very large loop still selects the whole pipeline. - if cost > limit.saturating_mul(4) { - return None; + for &b in &component { + stages[b] = components.len(); } // A polling group could wait for another group's ADD in a later dispatch. // Keep the whole pipeline if a loop can read writable global memory. @@ -657,13 +779,58 @@ impl Module { { return None; } + 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); + } + } + // 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 || (i < components.len() && !starts[i]) { + last = last.max(through[i]); + cost += components[i].0; + i += 1; + } + // An indivisible component, spin region, or non-uniform span may + // exceed the soft target and occupy its own piece up to 4x limit. + let cap = limit.saturating_mul(4); + if cost > cap { return None; } if used != 0 && 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; } } } @@ -736,7 +903,7 @@ mod tests { container::Stage, kernel::{Entry, KernelOptions}, lower::Lw, - module::{BinOp, CastOp, Pred}, + module::{BinOp, CastOp, Pred, Value}, shader::{ResClass, Shader}, }, recomp::{runner, CsInterface}, @@ -786,9 +953,9 @@ mod tests { m.ret(); // Header (3) + body (13) is exactly four times a target of 4. - let plan = m.dispatch_plan(4).expect("keep the loop in its own piece"); + let plan = m.dispatch_plan(4, None).expect("keep the loop in its own piece"); assert_eq!(plan.blocks, [vec![entry], vec![header, body], vec![exit]]); - assert!(m.dispatch_plan(3).is_none()); + assert!(m.dispatch_plan(3, None).is_none()); // An oversized first block must not create an empty leading piece. // If the program fits wholly in this one component, splitting has no benefit. @@ -799,12 +966,12 @@ mod tests { m.br(end); m.set_block(end); m.ret(); - assert_eq!(m.dispatch_plan(4).unwrap().blocks, [vec![Block(0)], vec![end]]); + assert_eq!(m.dispatch_plan(4, None).unwrap().blocks, [vec![Block(0)], vec![end]]); let mut m = Module::new(); let one = m.i32c(1); for _ in 0..4 { m.bin(BinOp::Add, one, one); } m.ret(); - assert!(m.dispatch_plan(4).is_none()); + assert!(m.dispatch_plan(4, None).is_none()); } #[test] @@ -843,7 +1010,7 @@ mod tests { lw.s.raw_store(mem, dest, &[value]); lw.s.m.ret(); lw.s.m.optimize(); - let plan = lw.s.m.dispatch_plan(32).unwrap(); + let plan = lw.s.m.dispatch_plan(32, None).unwrap(); assert!(plan.edges.iter().any(|edge| edge.live.contains(&old))); let chain = lw.s.split_compute(geometry, None, 32).expect("admit a UAV ADD"); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); @@ -880,11 +1047,11 @@ mod tests { s.m.set_block(next); } s.m.ret(); - assert!(s.m.dispatch_plan(16).is_some()); + assert!(s.m.dispatch_plan(16, None).is_some()); // A different group could be waiting on this very increment. s.m.set_insert_before_term(true); s.raw_atomic(mem, AtomicOp::Add, zero, one); - assert!(s.m.dispatch_plan(16).is_none()); + assert!(s.m.dispatch_plan(16, None).is_none()); } /// 64 threads: a single split wave64, whose halves exchange through group-shared counters @@ -961,16 +1128,13 @@ mod tests { if let Some(oversized) = large_loop { let n = lw.s.m.block_insts(oversized).len(); assert!(n > 40 && n <= 160); - let plan = lw.s.m.dispatch_plan(40).expect("partition around oversized loop"); + let plan = lw.s.m.dispatch_plan(40, None).expect("partition around oversized loop"); assert!(plan.blocks.iter().any(|piece| piece == &[oversized])); } 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 = if split { - assert!(chain.is_none(), "a split wave64 that exchanges through counters stays whole"); - None - } else { + let chain = Some({ let chain = chain.expect("split the synthetic program"); assert!(chain.pieces.len() >= 3); let has_memory_binding: Vec<_> = chain.pieces.iter().map(|piece| { @@ -978,10 +1142,12 @@ mod tests { .contains("ResBind { i32 2, i32 2, i32 0, i8 1 }") }).collect(); assert!(has_memory_binding.iter().any(|&present| present)); - assert!(has_memory_binding.iter().any(|&present| !present), - "pieces that only transport scratch must omit the title-memory binding"); - Some(chain) - }; + if !split { + assert!(has_memory_binding.iter().any(|&present| !present), + "pieces that only transport scratch must omit the title-memory binding"); + } + chain + }); if !runner::wave32_supported().unwrap_or(false) { runner::skip_test("no wave32 GPU"); return; @@ -1051,7 +1217,7 @@ mod tests { lw.s.m.optimize(); let limit = lw.s.m.blocks.iter().map(Vec::len).max().unwrap(); - let plan = lw.s.m.dispatch_plan(limit).unwrap(); + let plan = lw.s.m.dispatch_plan(limit, None).unwrap(); assert_eq!(plan.blocks.len(), 3); let incoming = plan.edges.iter().find(|edge| edge.to == middle).unwrap(); let outgoing = plan.edges.iter().find(|edge| edge.from == middle && edge.to == last).unwrap(); @@ -1125,6 +1291,149 @@ mod tests { #[test] fn dispatch_chain_payload_survives_reused_edge_slot() { check_persistent_payload(true); } + #[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); + } + + /// 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, 0); } @@ -1231,18 +1540,13 @@ 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); - let chain = if split { - assert!(chain.is_none(), "a split wave64 that exchanges through counters stays whole"); - None - } else { - let chain = chain.expect("split branch fixture"); - assert!(chain.pieces.len() >= 3); - Some(chain) - }; + let chain = lw.s.split_compute(geometry, split.then_some(tid), 64) + .expect("split branch fixture"); + assert!(chain.pieces.len() >= 3); + let chain = Some(chain); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); if !gpu { @@ -1312,4 +1616,691 @@ mod tests { } } + /// Single-wave 2D/3D native groups (`total <= lanes`, e.g. `[8, 4, 1]`, `[4, 4, 2]` wave32 + /// and `[8, 8, 1]` native wave64) need no `xcl_wt` groupshared counter or barriers. + /// Multi-wave 2D/3D native wave32 groups (`[8, 8, 1]`) still emit `xcl_wt` with one barrier + /// when not sharing `xcl_lds`, and reject splitting if a guest barrier appears outside the prefix. + #[test] + fn single_wave_2d_3d_omits_xcl_wt_and_guest_barrier_declines_split() { + for (geometry, wave64) in [([8, 4, 1], false), ([4, 4, 2], false), ([8, 8, 1], true)] { + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, gtid) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + let sum = lw.add(gtid[0], gtid[1]); + let sum = lw.add(sum, gtid[2]); + lw.s.raw_store(mem, offset, &[sum]); + lw.s.m.ret(); + lw.s.m.optimize(); + assert!( + lw.s.m.globals.iter().all(|g| g.name != "xcl_wt"), + "{geometry:?} wave64={wave64} should not emit xcl_wt" + ); + let has_barrier = lw.s.m.blocks.iter().flatten().any(|&i| { + matches!(&lw.s.m.insts[i as usize].op, super::Op::Call(f, _) if lw.s.m.funcs[*f as usize].name == "dx.op.barrier") + }); + assert!(!has_barrier, "{geometry:?} wave64={wave64} should not emit a barrier"); + let dxil = lw.s.finish_optimized(geometry, Some(if wave64 { 64 } else { 32 })).unwrap(); + crate::gpu::dxil::validate::validate(&dxil).expect("valid single-wave 2D/3D shader"); + } + + // Negative control: a multi-wave `[8, 8, 1]` native wave32 shader with a guest barrier + // outside the `xcl_wt` prefix must stay whole. + let geometry = [8, 8, 1]; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: false, 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(geometry, false); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + let mut v = lw.s.raw_load(mem, offset, 1)[0]; + for round in 1..=20u32 { + let b = lw.s.m.new_block(); + lw.s.m.br(b); + lw.s.m.set_block(b); + v = lw.addc(v, round); + if round == 10 { + lw.s.barrier(crate::gpu::dxil::ops::barrier::GROUP_SYNC); + } + } + lw.s.raw_store(mem, offset, &[v]); + lw.s.m.ret(); + lw.s.m.optimize(); + assert!(lw.s.m.globals.iter().any(|g| g.name == "xcl_wt")); + assert!(lw.s.split_compute(geometry, Some(tid), 16).is_none()); + } + + /// Native wave32 dispatch splitting across single-wave 2D/3D (`[8, 4, 1]`, `[4, 4, 2]`), + /// multi-wave 2D (`[8, 8, 1]` with `xcl_wt` prefix), and multi-wave 1D (`[128, 1, 1]`): + /// every piece validates and GPU readback matches the whole shader and CPU reference + /// across a 3D dispatch grid with loops, divergent branches, `(gx, gy, gz)`, and wave ops. + #[test] + fn dispatch_chain_native_wave32_group_shapes_match_whole() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + for (geometry, grid) in [ + ([8, 4, 1], [2, 2, 1]), + ([4, 4, 2], [2, 1, 2]), + ([8, 8, 1], [2, 2, 1]), + ([128, 1, 1], [2, 1, 1]), + ] { + let total: u32 = geometry.iter().product(); + let groups: u32 = grid.iter().product(); + let cs = CsInterface { threads: geometry, ..Default::default() }; + let options = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, [gx, gy, gz]) = lw.setup_lanes_compute(geometry, false); + let split_tid = (geometry[1] * geometry[2] > 1 && total > 32).then_some(tid); + let mem = lw.mems[0]; + let [wx, wy, wz] = [0, 1, 2].map(|axis| lw.s.group_id(axis)); + let gy_dim = lw.c(grid[1]); + let gx_dim = lw.c(grid[0]); + let row = lw.mul(wz, gy_dim); + let row = lw.add(row, wy); + let group = lw.mul(row, gx_dim); + let group = lw.add(group, wx); + let count = lw.c(total); + 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]; + // Encode `(gx, gy, gz)` so any thread-coordinate mismatch fails immediately. + let gy8 = lw.shlc(gy, 4); + let gz16 = lw.shlc(gz, 8); + let coord_tag = lw.or(gx, gy8); + let coord_tag = lw.or(coord_tag, gz16); + let mut value = lw.xor(original, coord_tag); + let zero = lw.c(0); + let i32 = lw.s.m.i32(); + let mode = lw.andc(tid, 3); + let trips = lw.addc(mode, 1); + for round in 1..=12u32 { + 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 round == 6 { + // Wave-local op in a middle piece: verifies wave membership survives the cut. + let w0 = lw.s.wave_read_lane_first(tid); + let wave_base = lw.andc(w0, !31); + value = lw.add(value, wave_base); + } + } + lw.s.raw_store(mem, offset, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + + let chain = lw.s.split_compute(geometry, split_tid, 40).expect("split wave32 group"); + assert!(chain.pieces.len() >= 3, "{geometry:?} expected >= 3 pieces, got {}", chain.pieces.len()); + let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); + crate::gpu::dxil::validate::validate(&whole).expect("valid whole fixture"); + + let words = (total * groups) as usize; + let initial: Vec = (0..words).map(|i| (i as u32).wrapping_mul(17).wrapping_add(3)).collect(); + let expected: Vec = initial + .iter() + .enumerate() + .map(|(idx, &orig)| { + let t = idx as u32 % total; + let tx = t % geometry[0]; + let ty = (t / geometry[0]) % geometry[1]; + let tz = t / (geometry[0] * geometry[1]); + let tag = tx | (ty << 4) | (tz << 8); + let n = (t & 3) + 1; + let mut v = orig ^ tag; + for round in 1..=12u32 { + v = v.wrapping_add(n.wrapping_mul(orig.wrapping_add(round))); + if round == 6 { + v = v.wrapping_add(t & !31); + } + } + v + }) + .collect(); + let reference = runner::dispatch(&whole, grid, &[], &initial).unwrap(); + assert_eq!(reference, expected, "whole {geometry:?}"); + let result = runner::dispatch_split(&chain, grid, &initial).unwrap(); + assert_eq!(result, expected, "split {geometry:?}"); + for most in [1, 3, 7] { + let slabbed = runner::dispatch_split_by(&chain, grid, &initial, most).unwrap(); + assert_eq!(slabbed, expected, "split {geometry:?}, {most} groups at once"); + } + println!( + "CHAIN_W32 geometry={geometry:?} grid={grid:?} pieces={} scratch_words_per_group={}", + chain.pieces.len(), + chain.dwords_per_group + ); + } + } + + + /// A program with the guest LDS, as the translator declares it when the + /// console code has a DS instruction. + fn lds_lw(geometry: [u32; 3], 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: geometry, ..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(geometry: [u32; 3], split: bool) { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let threads = geometry.iter().product::(); + let shaped = geometry[1] * geometry[2] > 1; + let multi = threads > 64; + let mut lw = lds_lw(geometry, split); + let (tid, gtid) = lw.setup_lanes_compute(geometry, true); + if !split { + assert!(!lw.s.m.funcs.iter().any(|f| f.name == "dx.op.barrier"), "single-wave lane setup has a group barrier"); + } + 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); + if shaped { + let five = lw.c(5); + let y = lw.mul(gtid[1], three); + let z = lw.mul(gtid[2], five); + let coord = lw.add(gtid[0], y); + let coord = lw.add(coord, z); + v = lw.add(v, coord); + } + 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]); + if shaped { + let [width, height, _] = geometry; + let lane = t as u32; + let coord = lane % width + 3 * (lane / width % height) + 5 * (lane / (width * height)); + expected[g * n + t] = expected[g * n + t].wrapping_add(coord); + } + } + } + let reference = runner::dispatch(&whole, [groups, 1, 1], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program, {geometry:?}"); + let result = runner::dispatch_split(&chain, [groups, 1, 1], &input).unwrap(); + assert_eq!(result, expected, "split program, {geometry:?}"); + println!("CHAIN_LDS group={geometry:?} 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, 1, 1], false); } + + #[test] + fn dispatch_chain_split_lds_wave32_8x4x1() { lds_chain([8, 4, 1], false); } + + #[test] + fn dispatch_chain_split_lds_wave32_4x8x1() { lds_chain([4, 8, 1], false); } + + #[test] + fn dispatch_chain_split_lds_wave32_2x4x4() { lds_chain([2, 4, 4], false); } + + #[test] + fn dispatch_chain_lds_wave64_split() { lds_chain([64, 1, 1], true); } + + #[test] + fn dispatch_chain_split_lds_wave64_8x4x2() { lds_chain([8, 4, 2], true); } + + /// Four hardware waves (two split console wave64s, no LDS) meet at early-exit-safe barriers + /// (`Lw::safe_barrier_sync`) between loops whose trips differ by wave and branches taken by + /// one console wave, so the plan cuts where the waves do not pass together. The barrier's + /// words cross the cuts: between the last two barriers they count the four waves, after the + /// last they hold its generation, and every result is the whole program's. + #[test] + fn dispatch_chain_safe_barrier_crosses_cuts() { + if !runner::wave32_supported().unwrap_or(false) { + runner::skip_test("no wave32 GPU"); + return; + } + let geometry = [128, 1, 1]; + let barrier = crate::gpu::rdna2::encode("S_BARRIER", "ENC_SOPP", &[], None).unwrap(); + let barrier = crate::gpu::rdna2::decode(&barrier, 0).unwrap(); + 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(std::slice::from_ref(&barrier), &Default::default(), options, &Entry::Compute(cs)); + assert!(lw.lds.is_none() && lw.s.m.globals.iter().any(|g| g.name == "xcl_bar")); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + lw.safe_barrier_init(); + let (bar, at) = lw.safe_bar.unwrap(); + let mem = lw.mems[0]; + let group = lw.s.group_id(0); + let count = lw.c(128); + 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 wave = lw.lshrc(tid, 5); + let trips = lw.andc(wave, 3); + let trips = lw.addc(trips, 1); + let mut v = x; + // (the barrier reads a translator variable: its blocks are the translator's, `Lw::block`) + fn wave_loops(lw: &mut Lw, rounds: std::ops::RangeInclusive, mut v: Value, x: Value, trips: Value) -> Value { + let i32 = lw.s.m.i32(); + for round in rounds { + let zero = lw.c(0); + let pred = lw.cur(); + let (body, exit) = (lw.block(Some(2)), lw.block(Some(1))); + lw.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.cond_br(again, body, exit); + lw.s.m.set_block(exit); + } + v + } + for (k, rounds) in [1..=6, 7..=12, 13..=18].into_iter().enumerate() { + v = wave_loops(&mut lw, rounds, v, x, trips); + let second = lw.andc(tid, 64); + let second = lw.nz(second); + let (yes, no, join) = (lw.block(Some(1)), lw.block(Some(1)), lw.block(Some(2))); + lw.cond_br(second, yes, no); + lw.s.m.set_block(yes); + let vy = wave_loops(&mut lw, 40..=43, v, x, trips); + let ye = lw.cur(); + lw.br(join); + lw.s.m.set_block(no); + let vn = wave_loops(&mut lw, 50..=51, v, x, trips); + let ne = lw.cur(); + lw.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, vy, ye); + lw.s.m.add_incoming(v, vn, ne); + if k == 2 { + let alive = lw.c(at); + let alive = lw.s.gs_ptr(bar, alive); + let alive = lw.s.m.load(alive, 4); + let seven = lw.c(7); + let alive = lw.mul(alive, seven); + v = lw.add(v, alive); + } + lw.safe_barrier_sync(); + } + let state = lw.c(at + 1); + let state = lw.s.gs_ptr(bar, state); + let state = lw.s.m.load(state, 4); + v = lw.add(v, state); + lw.s.raw_store(mem, offset, &[v]); + lw.safe_barrier_exit(); + lw.s.m.ret(); + lw.s.m.optimize(); + + let limit = (40..=240).step_by(8).find(|&limit| { + lw.s.m.dispatch_plan(limit, None).is_some_and(|plan| plan.blocks.len() >= 3 && !uniform_cuts(&plan, &lw.s.m)) + }).expect("cuts the waves do not pass together"); + let chain = lw.s.split_compute(geometry, Some(tid), limit).expect("split the safe-barrier program"); + assert!(chain.pieces.len() >= 3, "{} pieces", chain.pieces.len()); + 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 = (128 * 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 (i, e) in expected.iter_mut().enumerate().take(words) { + let t = (i % 128) as u32; + let (x, trips) = (input[i], (t >> 5 & 3) + 1); + let loops = |rounds: std::ops::RangeInclusive| rounds.map(|r| trips.wrapping_mul(x.wrapping_add(r))).fold(0u32, u32::wrapping_add); + let branch = || if t & 64 != 0 { loops(40..=43) } else { loops(50..=51) }; + let mut v = x; + for rounds in [1..=6, 7..=12, 13..=18] { + v = v.wrapping_add(loops(rounds)).wrapping_add(branch()); + } + // four waves alive, and three barriers passed with none waiting + *e = v.wrapping_add(4 * 7).wrapping_add(3 << 12); + } + let reference = runner::dispatch(&whole, [groups, 1, 1], &[], &input).unwrap(); + assert_eq!(reference, expected, "whole program"); + let result = runner::dispatch_split(&chain, [groups, 1, 1], &input).unwrap(); + assert_eq!(result, expected, "split program"); + println!("CHAIN_SAFE_BARRIER limit={limit} pieces={} scratch_dwords_per_group={} checked_words={words} guards=16", chain.pieces.len(), chain.dwords_per_group); + } + + #[test] + fn dispatch_chain_split_refuses_two_wave32s() { + let geometry = [8, 8, 1]; + let mut lw = lds_lw(geometry, false); + let (tid, _) = lw.setup_lanes_compute(geometry, true); + let value = lane_loops(&mut lw, 1..=16, tid, tid, tid); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + lw.s.raw_store(mem, offset, &[value]); + lw.s.m.ret(); + lw.s.m.optimize(); + assert!(lw.s.m.dispatch_plan(56, None).is_some(), "fixture has cuts"); + assert!(lw.s.split_compute(geometry, None, 56).is_none()); + } + + #[test] + fn dispatch_chain_lds_two_wave64s() { lds_chain([128, 1, 1], true); } + + #[test] + fn dispatch_chain_lds_three_wave64s() { lds_chain([192, 1, 1], true); } + + #[test] + fn dispatch_chain_lds_four_wave64s() { lds_chain([256, 1, 1], 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(geometry, 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(geometry, 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/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index f4a3b95d8c..9f934463b7 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1428,13 +1428,15 @@ pub struct TwoPass { pub mesh_groups_per_record: u32, /// static samplers of the compute pass pub samplers: Vec, + /// the compute pass cut into a dispatch chain (`dxil::kernel`), as a compute program's + pub cs_chain: Option>, } fn finish_two_pass_compiled(cs: Compiled, record: super::MsInterface, ps: Option<&[u8]>) -> Result { let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); let ms = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); - Ok(TwoPass { cs: cs.dxil, ms, record, mesh_groups_per_record, samplers: cs.samplers }) + Ok(TwoPass { cs: cs.dxil, ms, record, mesh_groups_per_record, samplers: cs.samplers, cs_chain: cs.dispatch_chain }) } fn compile_console_mesh( @@ -1461,7 +1463,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); + return Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => direct_fallback("MS", &e), } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 0c064f8f93..991373cfc9 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -2535,6 +2535,10 @@ unsafe fn defer_dispatch_mesh(this: *mut c_void, tp: &Arc, pso: usize, raw_pso: usize, sig: usize, msig: DispatchMeshSig, max: u32, src: usize, count: Option) -> bool { + if super::real::dispatch_chain::is_chain(tp.compute) { + return false; + } let record_bytes = tp.record.record_dwords() as u64 * 4; let fb_dev = super::real::list_device(this); let (fb_va, fb_slot, hint) = match fb_dev.as_ref().and_then(|d| prepare_indirect_feedback(d, pso)) { @@ -3463,7 +3470,9 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } else { bind_two_pass_stage(this, list, pso, &tp, va, compute)?; } - if compute { + if compute && super::real::dispatch_chain::is_chain(tp.compute) { + super::real::dispatch_chain::dispatch(list, pso, tp.compute, with(this, |s| s.allocator), [count, 1, 1])?; + } else if compute { list.Dispatch(count, 1, 1); } else { pc_dm(this, count * tp.mesh_groups_per_record, 1, 1); @@ -3671,6 +3680,12 @@ unsafe fn execute_indirect_snapshot( if max == 0 || args == 0 { return Ok(()); } + // (a compute pass cut into a chain runs its whole form: the group counts are the GPU's) + let whole = match super::real::dispatch_chain::whole_ready(tp.compute)? { + super::real::dispatch_chain::Whole::Plain => None, + super::real::dispatch_chain::Whole::Ready(w) => Some(w), + super::real::dispatch_chain::Whole::Late => return Err("the whole form of its compute pass is still being built".into()), + }; let commands = max as usize * msig.byte_stride as usize; let src = match commands_at { Some((p, n)) if commands <= n => p, @@ -3706,6 +3721,9 @@ unsafe fn execute_indirect_snapshot( let plan = two_pass_plan(max, records, with(this, |s| s.record_open)); let passes = run_two_pass_plan(this, list, &plan, &res_buf, res_va, region, |k, compute, va| { bind_two_pass_stage(this, list, pso, &tp, va, compute)?; + if let Some(w) = whole.as_ref().filter(|_| compute) { + super::real::bind_pipeline_exact(this, pso, w.as_raw() as usize); + } let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); Ok(()) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e70e3d9e85..fbe2fc8eec 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9545,14 +9545,27 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: ccached = cloaded.as_ref().map(driver_cache::LoadedBlob::shared); } let rejected_cgeneration = ccached.clone(); + // A compute pass cut into a dispatch chain is built in pieces, as a compute program is + // (`dispatch_chain::build`), unless its whole form is ready from a cache: the driver + // compiles the pieces at once. A retail title's 253 KB foliage producer took an NVIDIA + // driver 5.1 s whole and 1.3 s as four pieces of 71 - 113 KB. + let chained = tp.cs_chain.is_some() && ccached.is_none() && !compute_from_library + && !crate::shaders::pipeline_library::building(); if let Some(b) = &ccached { cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; - } else if !compute_from_library { + } else if !compute_from_library && !chained { take_cold_slot(); } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = library_compute.map_or(std::ptr::null_mut(), |pso| pso.into_raw()); - let (mut hc, mut cin_driver) = if compute_from_library { + let chain_rs = match tp.cs_chain.clone().filter(|_| chained) { + Some(plan) => dispatch_chain::build(this, fc, &cdesc, &iid, &mut compute, crate::gpu::shader::fnv64(&tp.cs), &tp.cs, &tp.samplers, plan), + None => None, + }; + if chained && chain_rs.is_none() { + take_cold_slot(); + } + let (mut hc, mut cin_driver) = if compute_from_library || chain_rs.is_some() { (S_OK, std::time::Duration::ZERO) } else { driver_compile_identified("compute pass", tp.cs.len(), false, None, ccached.is_some(), || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) @@ -9581,7 +9594,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: crate::shaders::warm_replay::accepted(cdisk.as_deref(), blob); } } - if hc >= 0 && !creused && !compute.is_null() { + if hc >= 0 && !creused && !compute.is_null() && chain_rs.is_none() { let kept = keep_driver_blob_at(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, ckey, tp.cs.len(), cdisk.as_deref(), cpersist_took, driver_cache::compute_keep_threshold(), || read_pso_cached_blob(compute)).or_else(|| compute_blob(ckey)); if let (Some(p), Some(b)) = (cdisk.as_deref(), kept) { @@ -9607,6 +9620,10 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: }, &mesh_pso, ).and_then(|_| { + // (no pipeline library is built with chains: `chained`) + if chain_rs.is_some() { + return Ok(()); + } let compute_pso = ID3D12PipelineState::from_raw_borrowed(&compute) .ok_or_else(|| "The two-pass compute pipeline has no native object".to_string())?; crate::shaders::pipeline_library::store( @@ -9622,10 +9639,11 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let mesh_pso = mesh_pso.into_raw(); *ppv = mesh_pso; note_pso_rs(mesh_pso, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: chain_rs.unwrap_or(rs as usize), mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 1000 == 0 || pso_trace() { - crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL; blobs reused: compute {creused}, mesh {greused})", tp.cs.len(), tp.ms.len()); + let pieces = tp.cs_chain.as_ref().filter(|_| chain_rs.is_some()).map_or(String::new(), |c| format!(" in {} pieces", c.pieces.len())); + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B{pieces} + mesh {} B DXIL; blobs reused: compute {creused}, mesh {greused})", tp.cs.len(), tp.ms.len()); } hr } @@ -14216,6 +14234,7 @@ mod mesh_stream_tests { record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1 }, mesh_groups_per_record: 1, samplers: vec![sampler], + cs_chain: None, }; let stream = StreamOut::default(); let iid = pc_iid(Kind::PipelineState); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6f6172165d..85db2a1ed3 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -311,6 +311,11 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT Some(rs) } +/// Whether `pso` is the first piece of a chain (`build`), dispatched by `dispatch`. +pub(in crate::hle::d3d12x) fn is_chain(pso: usize) -> bool { + CHAINS.lock().unwrap().contains_key(&pso) +} + pub(super) fn forget(pso: usize) { let gone = CHAINS.lock().unwrap().remove(&pso); drop(gone); // releasing a tail PSO also goes through forget_pso diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 9a01a70742..321c1258b9 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -77,6 +77,15 @@ SGPRs of both halves and the tests fail if they ever differ. for groups of one console wave in the HLSL path only (the direct translator always spins for compute and mesh). +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. 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 GS phase of ES+GS runs in the lower half only (≤ 21 primitives), likewise without a partner.