From 4f4970974ff6ac910735c407a93310f6c3b92f5e Mon Sep 17 00:00:00 2001 From: readmet3xt-lab <238408149+readmet3xt-lab@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:38:46 +0530 Subject: [PATCH] Wave64 groups of several console waves on 32-lane hosts: host waves meet per console wave CS_DefragHeap_ComputeRelocations (vfx_triangleClip, 128 threads: two console waves, which walk the decal triangle heap each its own way, with LDS shared inside one wave and no barrier) did not translate on NVIDIA: "an LDS read and write in one lane-branch region", and the wave-wide branches (`widen`) were refused for groups of more than one console wave, because a group barrier inside a branch one console wave takes and the other skips would wait for threads that never come. Its dispatch was dropped every frame. - `lower::with_pair_meetings`: the two host waves of each console wave meet on their own (`Lower::meet`): an LDS counter per console wave that its 64 lanes count up and wait on, polling at most 4096 times (a partner that never comes costs wrong values, not a hung card). Used for the LDS meetings, the exchanges of masks, lane reads and wave-wide decisions. A meeting starts a new block: exchanges happen where the code is being lowered, the masks and SCC an instruction reads as numbers are exchanged before its own code (`exchange_first`), and an IR block's last DXIL block is taken after its exit's code (phi predecessors were wrong otherwise). - With it, a branch closing a loop is in its own lane region (a lane that left the loop does not run it again), and the title's barriers count wave-wide branches as per-lane ones (`fence_only`). - `widen` takes groups of whole console waves when allowed (the digest list or VICTORY_WAVE_WIDE=1); the LANE_MASK and driver-loop paths stay as they were. A program whose LDS with the meetings' dwords passes the host's 32 KiB is refused. - Digest list: CS_DefragHeap_ComputeRelocations (128) and CS_TransmissionVolumetricsSubmerged (water_shading, 64 threads, the underwater volumetric light: widened like its tiled siblings). CS_CollectTriangles_Meshlets (1024 threads) still does not translate: its own LDS is the host group's whole 32 KiB, no room for exchange dwords or meeting counters. Checked: both translate and validate (dxil.dll); 1,800 other compute programs translate to the same DXIL as before (VICTORY_HOST_MAX_WAVE=32). New test: two console waves of one group in loops of 4 and 8 rounds with LDS shared across their halves, bit-exact on an RTX 4070 SUPER. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/lower.rs | 257 +++++++++++++++--- crates/victory-shader/src/emit/mod.rs | 37 ++- .../victory-shader/src/emit/wave64_tests.rs | 162 +++++++++++ 3 files changed, 417 insertions(+), 39 deletions(-) diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 72af2be..733199a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -360,6 +360,11 @@ struct Lower<'a> { /// handed to host waves (`wave_base`), and the base made in the entry block. halves: Option, wave_base: Option, + /// The host waves of a console wave meet on their own ([`with_pair_meetings`]): the first + /// of the LDS dwords that count each console wave's arrivals, and the dword of this + /// thread's console wave (made in the entry block). + pairs: Option, + meeting: Option, /// Vertex and mesh outputs holding 16-bit values: row, whether two per /// dword, and the row packed after it. half_outputs: HashMap)>, @@ -434,9 +439,16 @@ pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from /// the branch that do not post-dominate it). None with an indirect exit (not followed). fn all_lane_blocks(st: &Structured) -> Option> { + all_lane_blocks_of(st, false) +} + +/// [`all_lane_blocks`]; with `group`, of every console wave of the thread group: the branches +/// a console wave takes together ([`Structured::wide`]) count as per-lane branches too, as +/// two console waves of one group may take them different ways. +fn all_lane_blocks_of(st: &Structured, group: bool) -> Option> { let n = st.exits.len(); let mut all = vec![true; n]; - for (_, region) in lane_regions(st)? { + for (_, region) in lane_regions_of(st, group)? { for b in (0..n).filter(|&b| region[b]) { all[b] = false; } @@ -448,6 +460,15 @@ fn all_lane_blocks(st: &Structured) -> Option> { /// not post-dominate it, which only some lanes run. Not the branches the wave takes together /// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit. fn lane_regions(st: &Structured) -> Option)>> { + lane_regions_of(st, false) +} + +/// [`lane_regions`]; with `group`, the wave-wide branches too ([`all_lane_blocks_of`]). +/// With console waves meeting on their own ([`with_pair_meetings`]), a branch that closes a +/// loop (the code leads back to it) is in its own region: a lane that left the loop does not +/// run it again. (Not yet for the other programs: their translations stay as they were.) +fn lane_regions_of(st: &Structured, group: bool) -> Option)>> { + let loops = PAIR_MEETINGS.get(); let n = st.exits.len(); let mut succ: Vec> = vec![Vec::new(); n]; for (b, e) in st.exits.iter().enumerate() { @@ -488,14 +509,14 @@ fn lane_regions(st: &Structured) -> Option)>> { let mut regions = Vec::new(); for (d, e) in st.exits.iter().enumerate() { let LaneExit::Branch { when, .. } = *e else { continue }; - if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { + if st.wide.contains(&d) && !group || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { continue; // a wave-wide or uniform branch: all lanes go the same way } // blocks reachable from the lane branch that do not post-dominate it let mut seen = vec![false; n]; let mut stack: Vec = succ[d].clone(); while let Some(b) = stack.pop() { - if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 { + if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 && !(loops && b == d) { continue; } seen[b] = true; @@ -1054,8 +1075,35 @@ thread_local! { static LOCAL_WAVES: std::cell::Cell = const { std::cell::Cell::new(false) }; /// See [`with_local_waves_any`]. static LOCAL_ANY: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// See [`with_pair_meetings`]. + static PAIR_MEETINGS: std::cell::Cell = const { std::cell::Cell::new(false) }; } +/// LDS dwords a host thread group has (D3D12: 32 KiB). +const HOST_LDS_DWORDS: u32 = 8192; + +/// Runs `f` with the two host waves of each console wave meeting on their own +/// ([`Lower::meet`]) in console wave64 programs on 32-lane hosts whose thread group holds +/// several console waves, instead of with the whole group. Every console wave of such a group +/// takes its wave-wide branches ([`crate::structure::structure_wide`]) its own way, as the +/// console does: a group barrier inside one would wait for threads that took the other way. +/// The meeting is an LDS counter per console wave that its 64 lanes count up and wait on +/// (spinning, bounded): the host has no barrier for part of a group. Groups of whole console +/// waves only. +pub(super) fn with_pair_meetings(f: impl FnOnce() -> R) -> R { + let was = PAIR_MEETINGS.replace(true); + let r = f(); + PAIR_MEETINGS.set(was); + r +} + +/// Polls of a meeting's counter before a host wave goes on without its partner +/// ([`Lower::meet`]): a partner that never comes (lanes cut out of a loop at +/// [`LOOP_LIMIT`]) costs wrong values, not a hung card. A poll is a few hundred +/// nanoseconds; the partner, in the same group on the same unit, is at most a memory +/// fetch behind. +const MEETING_POLLS: u32 = 1 << 12; + /// As [`with_local_waves`], with every other use of a lane mask as a number /// and every lane read and write taken per host wave too: the program runs /// as it would on a console of 32-lane waves, lanes numbered 0..31 or @@ -1414,6 +1462,8 @@ impl<'a> Lower<'a> { let mut exchange: Option<(u32, bool, Vec)> = None; // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter let mut halves: Option = None; + // its host waves meet per console wave (`with_pair_meetings`): the first counter's dword + let mut pairs: Option = None; if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; @@ -1541,6 +1591,10 @@ impl<'a> Lower<'a> { // console threads go to host waves in the order the waves take them (`wave_base`) halves = Some(s.lds_dwords); s.lds_dwords += 1; + if PAIR_MEETINGS.get() && group > 64 && group % 64 == 0 && (split_lds || exchange.is_some()) { + pairs = Some(s.lds_dwords); + s.lds_dwords += group / 64; + } } if console_lanes || one_wave && s.lds_dwords > 0 { s.wave_size = Some(wave); @@ -1567,7 +1621,9 @@ impl<'a> Lower<'a> { .iter() .enumerate() .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); - let all = all_lane_blocks(x.st); + // (with console waves meeting on their own, a branch one takes wave-wide may be + // taken another way by the others) + let all = all_lane_blocks_of(x.st, pairs.is_some()); (0..p.blocks.len()) .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) .filter(|&b| { @@ -1712,6 +1768,8 @@ impl<'a> Lower<'a> { pair: None, halves, wave_base: None, + pairs, + meeting: None, flat: None, no_barrier, fence_only, @@ -2108,7 +2166,8 @@ impl<'a> Lower<'a> { let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]); let tb = bits(self, total); let c = self.cur; - let (lo, _) = self.exchange_halves(c, tb); + let (lo, _) = self.exchange_halves(c, tb)?; + let c = self.cur; let lo = back(self, lo); let cl = self.console_lane(); let k32 = self.s.m.i32(32); @@ -2120,7 +2179,8 @@ impl<'a> Lower<'a> { None => { let rb = bits(self, r); let c = self.cur; - let (lo, hi) = self.exchange_halves(c, rb); + let (lo, hi) = self.exchange_halves(c, rb)?; + let c = self.cur; let (lo, hi) = (back(self, lo), back(self, hi)); match op { Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), @@ -2197,8 +2257,8 @@ impl<'a> Lower<'a> { need(self.cur_ir); return Err("a wave reduction where not every lane runs"); } - let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); - let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); + let (lo0, lo1) = self.exchange_halves(self.cur, r_lo)?; + let (hi0, hi1) = self.exchange_halves(self.cur, r_hi)?; let c = self.cur; let d0 = self .s @@ -2320,7 +2380,7 @@ impl<'a> Lower<'a> { if !halves { return Ok(mine); } - let (lo, hi) = self.exchange_halves(c, mine); + let (lo, hi) = self.exchange_halves(c, mine)?; let c = self.cur; let total = self.add_halves(lo, hi); let total = self.s.m.bin(c, Bin::And, total, low); @@ -2330,6 +2390,11 @@ impl<'a> Lower<'a> { fn run(mut self, counted: bool) -> Result { let p = self.x.p; + // A host group has 32 KiB of LDS (D3D12): the program's LDS with the meetings' and + // exchanges' dwords past it must fit (`CS_CollectTriangles_Meshlets` uses all 32 KiB). + if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS { + return Err(unsupported(0, "LDS for the console waves' meetings past the host's 32 KiB")); + } if counted { // Before anything else, so that wave counts, reads of the first // lane and stores know only the lanes that run. @@ -3548,7 +3613,7 @@ impl<'a> Lower<'a> { need(b.unwrap_or(0)); return Err(DIVERGENT_MASK_EXCHANGE); } - xy = self.exchange_halves(at, xy.0); + xy = self.exchange_halves(at, xy.0)?; } self.ballots.insert(lo, xy); xy @@ -4101,6 +4166,20 @@ impl<'a> Lower<'a> { let ptr = self.s.m.element(e, lds, k); let zero = self.s.m.i32(0); self.s.m.store(e, ptr, zero); + if let (Some(first), StageIo::Cs(cs)) = (self.pairs, &self.x.native.io) { + // the console waves' meeting counters too: thread n zeroes counter n (the last one + // past them) + let waves = cs.threads.iter().product::() / 64; + let i32t = self.s.t.i32; + let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); + let last = self.s.m.i32(waves - 1); + let past = self.s.m.cmp(e, pred::IUGT, flat, last); + let n = self.s.m.select(e, past, last, flat); + let first = self.s.m.i32(first); + let at = self.s.m.bin(e, Bin::Add, first, n); + let ptr = self.s.m.element(e, lds, at); + self.s.m.store(e, ptr, zero); + } self.group_sync(e); let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let first = self.s.m.cmp(e, pred::EQ, lane, zero); @@ -4149,6 +4228,99 @@ impl<'a> Lower<'a> { cl } + /// With console waves meeting on their own: the ballots of the lane masks `inst` reads as + /// numbers, and "some lane" of the SCC it reads, exchanged before its own code is lowered. + /// Their meetings start new blocks ([`Self::meet`]), and an instruction's code goes on in + /// the block it began in; made here, its code finds them made. What fails here fails + /// again, and is told, where the instruction reads it. + fn exchange_first(&mut self, inst: &Inst) { + let needs = NEEDS.with_borrow(|n| n.clone()); + let st = self.x.st; + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let ops: Vec = match &inst.fields { + Fields::Sop { src, .. } => src.clone(), + Fields::Valu(v) => v.src.clone(), + _ => Vec::new(), + }; + for op in ops { + let Operand::Scalar { code, .. } = op else { continue }; + if code == NULL { + continue; + } + for c in [code, code + 1] { + if let Some(v) = inst.read(Reg::S(c)).filter(|&v| is_mask(v)) { + let lo = st.highs.get(&v).copied().unwrap_or(v); + if !self.ballots.contains_key(&lo) { + let _ = self.mask_dword(v); + } + } + } + } + if let Some(v) = inst.read(Reg::Scc) + && st.scc_some.contains_key(&v) + && matches!(self.vals.get(&v), None | Some(Val::Missing(_))) + && let Ok(x) = self.scc_some(v) + { + self.vals.insert(v, Val::Bit(x)); + } + NEEDS.with_borrow_mut(|n| *n = needs); + } + + /// The two host waves of this thread's console wave meet: what either wrote to LDS + /// before is seen by both after. A group barrier with an LDS fence; with + /// [`with_pair_meetings`], the console wave's own meeting: each of its 64 lanes counts + /// itself in on the console wave's LDS counter and waits (polling, at most + /// [`MEETING_POLLS`] times) until the count reaches the next multiple of 64. The code + /// after it is in a new block ([`Self::cur`]). + fn meet(&mut self) { + let Some(first) = self.pairs else { + let c = self.cur; + self.group_sync(c); + return; + }; + let (i32t, void) = (self.s.t.i32, self.s.t.void); + let fence = self.s.m.i32(8); + let head = self.cur; + self.s.op(head, "barrier", Attr::NoDuplicate, void, 80, &[fence]); + if super::group_sync() == 0 { + return; + } + let index = match self.meeting { + Some(v) => v, + None => { + let e = self.s.entry; + let thread = self.console_thread(); + let six = self.s.m.i32(6); + let wave = self.s.m.bin(e, Bin::LShr, thread, six); + let base = self.s.m.i32(first); + let v = self.s.m.bin(e, Bin::Add, base, wave); + self.meeting = Some(v); + v + } + }; + let lds = self.s.lds(); + let ptr = self.s.m.element(head, lds, index); + let (zero, one) = (self.s.m.i32(0), self.s.m.i32(1)); + let old = self.s.m.atomic(head, Rmw::Add, ptr, one); + let (low, k64) = (self.s.m.i32(!63u32), self.s.m.i32(64)); + let base = self.s.m.bin(head, Bin::And, old, low); + let target = self.s.m.bin(head, Bin::Add, base, k64); + let (wait, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(head, Term::Br(wait)); + let n = self.s.m.phi(wait, i32t); + let now = self.s.m.atomic(wait, Rmw::Add, ptr, zero); + let short = self.s.m.bin(wait, Bin::Sub, now, target); + let early = self.s.m.cmp(wait, pred::SLT, short, zero); + let n1 = self.s.m.bin(wait, Bin::Add, n, one); + let limit = self.s.m.i32(MEETING_POLLS); + let more = self.s.m.cmp(wait, pred::IULT, n1, limit); + let again = self.s.m.bin(wait, Bin::And, early, more); + self.s.m.terminate(wait, Term::CondBr(again, wait, done)); + self.s.m.set_phi(n, vec![(zero, head), (n1, wait)]); + self.cur = done; + self.s.op(done, "barrier", Attr::NoDuplicate, void, 80, &[fence]); + } + /// A group barrier with an LDS fence in `block`. fn group_sync(&mut self, block: usize) { let mode = self.s.m.i32(meeting_mode()); @@ -4157,15 +4329,18 @@ impl<'a> Lower<'a> { } /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get - /// (lower half's, upper half's). A group with no upper half gets 0 for it. - fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) { + /// (lower half's, upper half's). A group with no upper half gets 0 for it. The halves + /// meet ([`Self::meet`]): the results are in [`Self::cur`], which may be a new block; + /// with console waves meeting on their own, only where the code is being lowered + /// (`at` is [`Self::cur`]). + fn exchange_halves(&mut self, at: usize, mine: V) -> Result<(V, V), Why> { let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else { let z = self.s.m.i32(0); - return (mine, z); + return Ok((mine, z)); }; if small { let z = self.s.m.i32(0); - return (mine, z); + return Ok((mine, z)); } if self.local { // each host wave on its own: its half holds `mine`, the other nothing @@ -4174,7 +4349,11 @@ impl<'a> Lower<'a> { let upper = self.s.m.cmp(at, pred::IUGE, cl, k32); let lo = self.s.m.select(at, upper, z, mine); let hi = self.s.m.select(at, upper, mine, z); - return (lo, hi); + return Ok((lo, hi)); + } + if self.pairs.is_some() && at != self.cur { + // (the meeting would split a block lowered already) + return Err("a lane mask exchanged after its block, in a group of several console waves"); } // the pair of dwords of this thread's console wave: its half's, then both let pair = self.exchange_pair(slot); @@ -4185,7 +4364,13 @@ impl<'a> Lower<'a> { let lds = self.s.lds(); let ptr = self.s.m.element(at, lds, index); self.s.m.store(at, ptr, mine); - self.group_sync(at); + let at = if self.pairs.is_some() { + self.meet(); + self.cur + } else { + self.group_sync(at); + at + }; let one = self.s.m.i32(1); let k1 = self.s.m.bin(at, Bin::Add, pair, one); let p0 = self.s.m.element(at, lds, pair); @@ -4193,8 +4378,12 @@ impl<'a> Lower<'a> { let lo = self.s.m.load(at, p0); let hi = self.s.m.load(at, p1); // the slots are written again only after every thread read them - self.group_sync(at); - (lo, hi) + if self.pairs.is_some() { + self.meet(); + } else { + self.group_sync(at); + } + Ok((lo, hi)) } /// The first of the two exchange dwords of this thread's console wave (made in the entry @@ -4250,7 +4439,9 @@ impl<'a> Lower<'a> { return Err(DIVERGENT_MASK_EXCHANGE); } let some = self.s.m.cast(at, Cast::ZExt, some, i32t); - let (lo, hi) = self.exchange_halves(at, some); + let (lo, hi) = self.exchange_halves(at, some)?; + // (the halves met: on in a new block) + let at = if self.pairs.is_some() { self.cur } else { at }; let both = self.s.m.bin(at, Bin::Or, lo, hi); let z = self.s.m.i32(0); Ok(self.s.m.cmp(at, pred::NE, both, z)) @@ -4292,7 +4483,7 @@ impl<'a> Lower<'a> { let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); self.s.flags |= flags::WAVE_OPS; let some = self.s.m.cast(c, Cast::ZExt, some, i32t); - let (lo, hi) = self.exchange_halves(c, some); + let (lo, hi) = self.exchange_halves(c, some)?; let c = self.cur; let both = self.s.m.bin(c, Bin::Or, lo, hi); let z = self.s.m.i32(0); @@ -5313,6 +5504,9 @@ impl<'a> Lower<'a> { // each host wave answers for itself. MaskData::None => self.uniform_test(inst), }; + if self.pairs.is_some() && self.mask_ok && reads_mask_as_data(self.x.st, inst) { + self.exchange_first(inst); + } let effect = matches!(inst.fields, Fields::Exp { .. }) || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") || name.contains("store") @@ -5329,9 +5523,7 @@ impl<'a> Lower<'a> { { // the two host waves of a console wave meet before each LDS access: what the other // half wrote is visible, and what it still reads is not overwritten - let mode = self.s.m.i32(meeting_mode()); - let void = self.s.t.void; - self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.meet(); } // The structure builder's threads take turns through atomics (a tree // built from its leaves up): what one wrote before its atomic is @@ -5413,9 +5605,7 @@ impl<'a> Lower<'a> { /// The two host waves of a console wave meet (a group barrier with a shared-memory /// fence): LDS writes before are seen by reads after. fn lds_meeting(&mut self) { - let mode = self.s.m.i32(meeting_mode()); - let void = self.s.t.void; - self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + self.meet(); } /// Whether `v` is a register no program reads as a number: a descriptor dword without @@ -8771,11 +8961,11 @@ impl<'a> Lower<'a> { let ptr = self.s.m.element(self.cur, lds, k); self.s.m.store(self.cur, ptr, a); self.end_guarded(at, &[]); + self.meet(); let c2 = self.cur; - self.group_sync(c2); let ptr = self.s.m.element(c2, lds, k); let r = self.s.m.load(c2, ptr); - self.group_sync(c2); + self.meet(); return int(self, r); } let r = self.read_lane(a, lane); @@ -8851,13 +9041,15 @@ impl<'a> Lower<'a> { // has. No half needs to ask the other whether it has // a lane (an exchange of the constant 1: two group // barriers), and the lower half's value is the answer. - let (lo, _) = self.exchange_halves(c, mine); + let (lo, _) = self.exchange_halves(c, mine)?; lo } else { let i32t = self.s.t.i32; let has = self.s.m.cast(c, Cast::ZExt, any, i32t); - let (lo_has, hi_has) = self.exchange_halves(c, has); - let (lo, hi) = self.exchange_halves(c, mine); + let (lo_has, hi_has) = self.exchange_halves(c, has)?; + let c = self.cur; + let (lo, hi) = self.exchange_halves(c, mine)?; + let c = self.cur; let z = self.s.m.i32(0); let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); @@ -12502,6 +12694,9 @@ impl<'a> Lower<'a> { LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), }; let _ = Exit::End; + // (the exit's own code may have moved on to a new block: the halves of a console wave + // meeting for a wave-wide branch, [`Self::meet`]; the edges out leave from there) + self.tail[b] = Some(self.cur); self.s.m.terminate(self.cur, term); Ok(()) } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5c191a7..b3871be 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -547,6 +547,12 @@ pub fn emit( // an LDS read and write in one lane-branch region, so no other form translates // them on 32-lane hosts and their dispatches were dropped (no volumetric light // or fog on NVIDIA). Widened, they translate (4 and 7 branches taken wave-wide). + // The underwater one (`CS_TransmissionVolumetricsSubmerged`) likewise (29 branches). + // The triangle clip's heap defragmentation (`vfx_triangleClip:CS_DefragHeap_ + // ComputeRelocations`, groups of 128) holds two console waves, which walk the heap + // each its own way: their host waves meet per console wave ([`widen`]). (Its + // `CS_CollectTriangles_Meshlets`, groups of 1024, does not fit that way: its own LDS + // is the host group's whole 32 KiB.) let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64) && matches!( c.digest, @@ -554,7 +560,10 @@ pub fn emit( | [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c] | [0x24, 0x12, 0x6c, 0x14, 0xdc, 0x76, 0x19, 0xb0, 0x82, 0xef, 0x57, 0x12, 0x96, 0x03, 0x88, 0x90] | [0x70, 0x99, 0xa5, 0x7f, 0xde, 0xd1, 0x42, 0x61, 0x3b, 0x44, 0xf4, 0x10, 0x46, 0x3d, 0x6b, 0xe6] - ); + | [0xf1, 0xf1, 0x61, 0xe4, 0x7e, 0xef, 0xa3, 0x64, 0x69, 0x18, 0x39, 0xfd, 0x72, 0x06, 0xcc, 0xf6] + ) + || matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 128) + && c.digest == [0x50, 0xcf, 0x28, 0x32, 0x8b, 0x58, 0x05, 0x3d, 0xa8, 0x9a, 0x8d, 0xa0, 0x1a, 0xa1, 0x23, 0xc6]; let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1"); // A single guest wave can iterate an active-lane loop until both host // halves have finished. The precise latch and convergence conditions @@ -593,7 +602,7 @@ pub fn emit( Some(p), ]; if let Some(base) = bases.into_iter().flatten().next() { - let again = widen(c, native, base, why, driver_loop); + let again = widen(c, native, base, why, driver_loop, wide_on); report("wave-wide branches", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -655,7 +664,7 @@ pub fn emit( && what == lower::LANE_MASK && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => { - let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false); + let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false, false); match again { Ok(_) => again, Err(_) => emit_program(c, native, p, st, io, res), @@ -694,15 +703,17 @@ pub fn emit( /// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the /// lowering names the blocks where the two host waves must meet and could not /// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until -/// it translates or a branch cannot be widened. Only where a thread group is one console -/// wave: with several, the waves of a group would decide differently and a barrier inside -/// such a branch would wait for threads that never come. +/// it translates or a branch cannot be widened. Where a thread group is several console +/// waves, those decide differently and a group barrier inside such a branch would wait for +/// threads that never come: the host waves of each console wave meet on their own there +/// ([`lower::with_pair_meetings`]; whole console waves only), when `groups` allows it. fn widen( c: &Container, native: &NativeProgram, p: &ir::Program, why: bool, active_loop_only: bool, + groups: bool, ) -> Result<(HostShader, Option), ShaderError> { const NOT: ShaderError = ShaderError::Unsupported { offset: 0, @@ -712,6 +723,7 @@ fn widen( // (a program whose waves are the host's meets no one: no barrier, any group) crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {} crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64 => {} + crate::native::StageIo::Cs(cs) if groups && cs.threads.iter().product::() % 64 == 0 => {} crate::native::StageIo::Cs(cs) => { if why { eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads); @@ -720,13 +732,21 @@ fn widen( } _ => return Err(NOT), } + // (several console waves to a group, each two host waves) + let pairs = native.wave64 + && lower::host_max_wave() == 32 + && matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() > 64); let mut wide = std::collections::HashSet::new(); loop { let st = structure::structure_wide(p, &wide)?; let io = io::raise(p, native)?; let res = resource::track(p, &native.layout, native.stage, Some(&st))?; lower::take_needs(); - let r = emit_program(c, native, p, &st, &io, &res); + let r = if pairs { + lower::with_pair_meetings(|| emit_program(c, native, p, &st, &io, &res)) + } else { + emit_program(c, native, p, &st, &io, &res) + }; let needs = lower::take_needs(); // (or translated for 64-lane waves still: shared memory read and written where not // every lane runs, whose blocks the lowering names too) @@ -754,7 +774,8 @@ fn widen( } return r; } - let more: Vec = lower::branches_around(&st, &needs) + let around = || lower::branches_around(&st, &needs); + let more: Vec = if pairs { lower::with_pair_meetings(around) } else { around() } .unwrap_or_default() .into_iter() .filter(|b| !wide.contains(b)) diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 5d1557b..be47af6 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -736,3 +736,165 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { } } } + +/// The wave size a lowering of `native` at a host of 32-lane waves asks for, and the shader. +fn lowered_with_wave( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet, +) -> (Option, HostShader) { + let st = structure::structure_wide(p, wide).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered.expect("lower"); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }; + (lowered.wave_size, shader) +} + +/// Two console waves in a group of 128 threads, each run as two host waves of 32. Lane t goes +/// round a per-lane loop (t >> 4) + 1 times: it writes its sum to LDS and adds that of lane +/// t ^ 63 (in the other host wave of its console wave) with no barrier between, as one console +/// wave may; after the loop every lane adds lane 63's sum (`v_readlane_b32`). The loop's back +/// edge is taken as the console takes it, by each console wave as a whole, and the two console +/// waves go round 4 and 8 times: their host waves meet per console wave +/// ([`lower::with_pair_meetings`]). A group barrier in the loop would wait for the threads of +/// the console wave that left it (`CS_DefragHeap_ComputeRelocations`, groups of 128, whose +/// console waves walk a heap each its own way). +#[test] +fn console_waves_of_one_group_meet_on_their_own_in_loops_of_their_own() { + let words = [ + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0: this lane's LDS dword + 0x3A06_00BF, // v_xor_b32 v3, 63, v0 + 0x3406_0682, // v_lshlrev_b32 v3, 2, v3: the partner lane's (other half, same wave) + 0x4A04_0000, // v_add_nc_u32 v2, s0, v0: the sum starts at s0 + t + 0x2C0E_0084, // v_lshrrev_b32 v7, 4, v0 + 0x4A0E_0E81, // v_add_nc_u32 v7, 1, v7: rounds (t >> 4) + 1 + 0x7E0A_0280, // v_mov_b32 v5, 0 + 0xBE8E_047E, // s_mov_b64 s[14:15], exec + 0xD834_0000, + 0x0000_0201, // loop: ds_write_b32 v1, v2 + 0xD8D8_0000, + 0x0400_0003, // ds_read_b32 v4, v3 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x4A04_0902, // v_add_nc_u32 v2, v2, v4 + 0x4A0A_0A81, // v_add_nc_u32 v5, 1, v5 + 0x7DA8_0B07, // v_cmpx_gt_u32 exec, v7, v5: the lanes with rounds left + 0xBF89_FFF7, // s_cbranch_execnz loop + 0xBEFE_040E, // s_mov_b64 exec, s[14:15] + 0xD760_0007, + 0x0001_7F02, // v_readlane_b32 s7, v2, 63 + 0x4A04_0407, // v_add_nc_u32 v2, s7, v2 + 0xE070_1000, + 0x8002_0201, // buffer_store_dword v2, v1, s[8:11], 0 offen + ]; + let mut native = native_of(&words, true, 128); + if let StageIo::Cs(cs) = &mut native.io { + cs.rsrc2 |= 1 << 15; // 512 bytes of LDS + } + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let back = (0..p.blocks.len()) + .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execnz")) + .expect("the back edge"); + // per lane, the loop's LDS write and read stand where not every lane runs: still 64 lanes, + // and the lowering names the loop + lower::take_needs(); + let (wave, _) = lower::with_pair_meetings(|| lowered_with_wave(&native, &p, &HashSet::new())); + assert_eq!(wave, Some(64)); + let needs = lower::take_needs(); + let st = structure::structure(&p).expect("structure"); + assert_eq!(lower::with_pair_meetings(|| lower::branches_around(&st, &needs)), Some(vec![back])); + // the back edge taken per console wave: waves of 32, meeting per console wave + let wide = HashSet::from([back]); + let (wave, shader) = lower::with_pair_meetings(|| lowered_with_wave(&native, &p, &wide)); + assert_eq!(wave, Some(32)); + assert!(lower::take_needs().is_empty()); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // the console: each wave's lanes in step, writes before reads + let console = |s0: u32| { + let mut out = [0u32; 128]; + let mut lds = [0u32; 128]; + for w in 0..2u32 { + let lanes = 64 * w..64 * w + 64; + let mut sum: Vec = lanes.clone().map(|t| s0.wrapping_add(t)).collect(); + for round in 0..8 { + let on: Vec = lanes.clone().filter(|t| round < (t >> 4) + 1).collect(); + if on.is_empty() { + break; + } + for &t in &on { + lds[t as usize] = sum[(t - 64 * w) as usize]; + } + for &t in &on { + let k = (t - 64 * w) as usize; + sum[k] = sum[k].wrapping_add(lds[(t ^ 63) as usize]); + } + } + let last = sum[63]; + for t in lanes { + out[t as usize] = sum[(t - 64 * w) as usize].wrapping_add(last); + } + } + out + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + let (root, pso) = match host.compute_pipeline(&shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program: {e}; not run"); + return; + } + }; + for s0 in [0u32, 1000, 0xFFFF_FF00] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = s0; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(128)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + let want = console(s0); + assert_eq!(&out[0][..128], &want[..], "s0 = {s0:#x}"); + } + eprintln!("ran on the hardware device: both console waves' loops, as the console runs them"); +}