From a2657986706886c0a27427b5e78d790035201def Mon Sep 17 00:00:00 2001 From: Kikoarl <7354010+Kikoarl@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:48:10 +0100 Subject: [PATCH] shader, gpu: port 32-lane BVH builder lowering, structure views, and GPURT node answer Port the portable pieces of fxceless/victory-fork commits 17533c5, 1170216, 1320dfd, and 9a9091d onto trustno1 main (f3534e6): - victory-shader: enable USER_DISPATCH_THREADS_X guarding for spilled 1D compute programs on 32-lane waves and programs with barriers by adding partial_active/effect_guard instead of early return when threads must stay for s_barrier or two-wave exchanges (after 1320dfd). - victory-shader: check exact operand dwords in lane_uniform (full dwords on scalars, exact VGPR dwords except v_movrel/v_swap), widen ordered/stable uniform ds_read checks beyond ds_read_b32, and mask v_readfirstlane_b32 with partial_active when halves are alike or guarded (after 1170216, 1320dfd). - victory-shader: return [u32::MAX; 4] (-1 per AMD GPURT) for instance and procedural BVH nodes (kinds 6 and 7) in bvh::intersect and emit::intersect, and use effect_guard for BVH intersection loads (after 9a9091d). - victory-gpu: extract Location (words 4-5) for placed as well as shader acceleration-structure views in view_address, returning None when zero (after 9a9091d). Adaptations for main: 17533c5 (VICTORY_WAVE_PAIRS_SPILLED) is inapplicable because main uses halves/exchange/pairs without paired.rs; 9a9091d memory sync/written-page tracking is omitted because main already uses arena Shadow::by_address sync (preserving PR #88 and PR #58) and VICTORY_BVH_BUILDER remains opt-in (=1). --- crates/victory-gpu/src/descriptor/host.rs | 42 ++- crates/victory-shader/src/bvh.rs | 13 +- crates/victory-shader/src/emit/intersect.rs | 13 +- crates/victory-shader/src/emit/lower.rs | 195 +++++++--- .../victory-shader/src/emit/wave64_tests.rs | 345 ++++++++++++++++++ 5 files changed, 542 insertions(+), 66 deletions(-) diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f2aad9792..1e0ea5789 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -4264,16 +4264,22 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { /// The address a shader finds in a descriptor of title memory: where a /// buffer view starts, or the ray-tracing structure of a structure's view -/// (no resource: the view's description holds the address, and the shader -/// walks the structure from there itself). +/// (no resource: the view's description holds the address in words 4-5, and +/// the shader walks the structure from there itself). pub(crate) fn view_address(view: &View) -> Option { const STRUCTURE: u32 = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32; - match view { - View::Shader(_, Some(desc)) if desc[1] == STRUCTURE => { - Some(u64::from(desc[4]) | u64::from(desc[5]) << 32) - } - _ => buffer_range(view).map(|range| range.0), + let words = match view { + View::Shader(_, Some(desc)) => Some(&desc[..]), + View::Placed(false, _, desc) => Some(&desc[..10]), + _ => None, + }; + if let Some(w) = words + && w[1] == STRUCTURE + { + let at = u64::from(w[4]) | u64::from(w[5]) << 32; + return (at != 0).then_some(at); } + buffer_range(view).map(|range| range.0) } /// The title memory the host slot of buffer view `view` is made on @@ -5863,6 +5869,28 @@ mod tests { assert!(!same_placed_texture(&low, &View::Shader(0, None))); } + #[test] + fn structure_views_report_their_location_as_view_address() { + const STRUCTURE: u32 = 11; + let location = 0x0000_0007_8000_1200u64; + let mut srv = [0u32; 10]; + srv[1] = STRUCTURE; + assert_eq!(view_address(&View::Shader(0, Some(srv))), None); + srv[4] = location as u32; + srv[5] = (location >> 32) as u32; + assert_eq!(view_address(&View::Shader(0, Some(srv))), Some(location)); + + let mut placed = [0u32; 16]; + placed[1] = STRUCTURE; + assert_eq!(view_address(&View::Placed(false, [0; 14], placed)), None); + placed[4] = location as u32; + placed[5] = (location >> 32) as u32; + assert_eq!( + view_address(&View::Placed(false, [0; 14], placed)), + Some(location) + ); + } + #[test] fn ranges_that_touch_are_one() { let mut ranges = vec![(40, 50), (30, 40), (35, 40), (10, 20), (45, 60), (60, 61), (1, 1)]; diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs index 3f79f8220..db2012b42 100644 --- a/crates/victory-shader/src/bvh.rs +++ b/crates/victory-shader/src/bvh.rs @@ -66,7 +66,7 @@ //! the console rounds, which of two boxes entered at the same distance it //! returns first, and what it returns for a ray exactly through an edge //! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here: -//! a triangle miss; the title's programs do not read it). +//! all ones, `[u32::MAX; 4]`, as the hardware returns). /// The result dword for a box the ray misses, or a child that is not there. pub const NONE: u32 = 0xffff_ffff; @@ -127,7 +127,10 @@ pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4 4 => boxes(&children(words), &boxes16(words), ray, sort), 5 => boxes(&children(words), &boxes32(words), ray, sort), k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits), - _ => MISS.map(f32::to_bits), + // An instance or a procedural node: the hardware answers -1 in all + // four dwords (AMD GPURT IntersectCommon.hlsl: "User defined node. + // HW returns -1"); the traversal handles the node itself. + _ => [u32::MAX; 4], } } @@ -664,11 +667,13 @@ pub(crate) mod tests { } #[test] - fn instances_and_procedural_nodes_return_a_triangle_miss() { + fn instances_and_procedural_nodes_return_all_ones() { + // As the hardware (AMD GPURT IntersectCommon.hlsl: "User defined + // node. HW returns -1"): the traversal handles such a node itself. let node = triangles(&TRIANGLE, 9); let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0); for k in [6, 7] { - assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits)); + assert_eq!(intersect(&node, k, &ray, true), [u32::MAX; 4]); } } diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index b32afa897..c83703d62 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -19,7 +19,7 @@ //! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4); //! four slab tests; the sorting network //! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test -//! other (6, 7): a triangle miss +//! other (6, 7): all ones (-1, as the hardware returns) //! ``` //! //! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit @@ -116,7 +116,7 @@ impl<'a> Lower<'a> { // dwords; no program of the title asks for it. return Err("a ray-tracing structure that returns triangle ids"); } - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let mut x = Vec::with_capacity(regs.len()); for &r in ®s { let v = inst.read(Reg::V(r)).ok_or("an unread operand")?; @@ -199,9 +199,12 @@ impl<'a> Lower<'a> { let triangle_end = self.cur; self.s.m.terminate(triangle_end, Term::Br(join)); self.cur = join; - // Kinds 6 and 7 (an instance, a procedural primitive): not known - // what the console returns; the title's programs do not read it. - let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits())); + // Kinds 6 and 7 (an instance, a procedural primitive): the hardware + // returns 0xFFFFFFFF in all four dwords (AMD GPURT + // IntersectCommon.hlsl: "User defined node. HW returns -1"); a + // traversal tells such a node by that answer and handles it itself + // (an instance: the ray goes into the object's structure). + let other = [u32::MAX; 4].map(|v| self.s.m.i32(v)); let i32t = self.s.t.i32; let mut results = Vec::with_capacity(4); for k in 0..4 { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3aa6a72c5..f13e78a45 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -95,10 +95,10 @@ pub(crate) fn lower(parts: &Parts) -> Result { /// Whether the title dispatches the program by a count of threads whose last /// group may be partial: the structure builder's programs of one dimension. -/// Their lanes past the count must not run (they count the lanes of a wave -/// and store). Not where a group barrier would wait for lanes that left, nor -/// where two host waves of 32 stand for a console wave (they exchange, which -/// takes all lanes). +/// Where no group barrier, two-wave exchange, or loop back to the entry +/// block keeps threads together, lanes past the count leave at entry; +/// otherwise they stay (`partial_active`) with memory, LDS, ballot, and +/// wave-op effects masked out. fn counted_in_threads(parts: &Parts) -> bool { let crate::native::StageIo::Cs(cs) = &parts.native.io else { return false; @@ -106,13 +106,10 @@ fn counted_in_threads(parts: &Parts) -> bool { cs.threads[0] > 1 && cs.threads[1..] == [1, 1] && crate::spill::is_spilled(parts.native) - && (!parts.native.wave64 || host_max_wave() >= 64) - && !parts.p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_barrier") } -/// [`lower`]; `counted`: the lanes past a dispatch's count of threads leave -/// at once (`shader.rs` `USER_DISPATCH_THREADS_X`; after DexNom/VIctory -/// bc3cd4b0, which does so for two of the programs by their digests). +/// [`lower`]; `counted`: enforce `shader.rs` `USER_DISPATCH_THREADS_X` for lanes +/// past the thread count (early return when safe, else `partial_active`). pub(super) fn lower_counted(parts: &Parts, counted: bool) -> Result { let mut bad = HashMap::new(); loop { @@ -410,6 +407,10 @@ struct Lower<'a> { counters: HashMap)>, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// Whether this lane is within the `USER_DISPATCH_THREADS_X` count when + /// threads past the count stay for barriers or two-wave exchanges instead + /// of returning at entry. + partial_active: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -606,7 +607,7 @@ fn lane_uniform( if st.guards[b][i].is_some() { continue; // lanes outside EXEC keep another value } - let ops: Vec = match &inst.fields { + let alike = match &inst.fields { Fields::Valu(v) if v.dpp.is_none() && v.sdwa.is_none() @@ -614,33 +615,49 @@ fn lane_uniform( && !name.starts_with("v_cmpx") && !name.contains("lane") => { - v.src.clone() + v.src.iter().all(|op| match *op { + Operand::Vector { reg, dwords } => { + // every dword of the operand the instruction reads (not the old value + // of a higher-numbered destination register that IR keeps for guards). + // A relative move reads the register `M0` past this one, and a + // swap or a relative store keeps or moves old values: for those + // every register read from this one on counts, as before. + let whole = name.starts_with("v_movrel") || name.starts_with("v_swap"); + let end = reg.saturating_add(dwords); + let read: Vec = inst + .reads + .iter() + .filter(|r| matches!(r.0, Reg::V(x) if x >= reg && (whole || x < end))) + .map(|r| r.1) + .collect(); + !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + Operand::Scalar { code, dwords } if code != NULL => { + (code..code.saturating_add(dwords)).all(|c| { + inst.read(Reg::S(c)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + }) + } + _ => true, + }) } Fields::Ds { - addr: Some(Operand::Vector { reg, dwords: 1 }), + addr: Some(Operand::Vector { reg, .. }), gds: false, .. - } if ordered_lds && name == "ds_read_b32" && !unstable.contains(&(b, i)) => { - if inst.read(Reg::V(*reg)).is_some_and(|a| same.contains(&a)) { - same.extend(inst.writes.iter().map(|w| w.1)); - } - continue; + } if ordered_lds + && name.starts_with("ds_read") + && !name.contains("_d16") + && !name.contains("addtid") + && !unstable.contains(&(b, i)) => + { + // An unguarded ordered LDS read from a wave-uniform address gives the same + // value in every arriving lane. `_d16` forms preserve the other half of the + // destination register and `addtid` adds the lane index, so both are left out. + inst.read(Reg::V(*reg)).is_some_and(|x| same.contains(&x)) } - _ => continue, + _ => false, }; - let alike = ops.iter().all(|op| match *op { - Operand::Vector { reg, .. } => { - // every dword of the operand the instruction reads from that register on - let read: Vec = - inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); - !read.is_empty() && read.iter().all(|x| same.contains(x)) - } - // a scalar is one value; a lane mask is not, unless a compare of such values made it - Operand::Scalar { code, .. } if code != NULL => { - inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) - } - _ => true, - }); if alike { same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); } @@ -2011,6 +2028,7 @@ impl<'a> Lower<'a> { code_table: None, counters: HashMap::new(), abort: None, + partial_active: None, } } @@ -2102,7 +2120,7 @@ impl<'a> Lower<'a> { .scalar .get(&(b, i)) .ok_or("an untracked global address")?; - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let Some(Operand::Vector { reg, .. }) = *dst else { return Err("a global load result"); }; @@ -2260,7 +2278,12 @@ impl<'a> Lower<'a> { .masks .get(&mask) .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; + let mut on = self.boolean(m, c)?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&mask) + { + on = self.s.m.bin(c, Bin::And, on, active); + } let x = self.i32_of(src)?; let id = self.s.m.i32(ident); return Ok(self.s.m.select(c, on, x, id)); @@ -2290,7 +2313,12 @@ impl<'a> Lower<'a> { .masks .get(&mask) .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; + let mut on = self.boolean(m, c)?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&mask) + { + on = self.s.m.bin(c, Bin::And, on, active); + } let x = self.i32_of(src)?; let id = self.s.m.i32(ident); let x = self.s.m.select(c, on, x, id); @@ -2438,7 +2466,12 @@ impl<'a> Lower<'a> { .masks .get(&mask) .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; + let mut on = self.boolean(m, c)?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&mask) + { + on = self.s.m.bin(c, Bin::And, on, active); + } let lo = self.i32_of(lo)?; let hi = self.i32_of(hi)?; let z = self.s.m.i32(0); @@ -2606,9 +2639,12 @@ impl<'a> Lower<'a> { 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")); } + let order = crate::ir::reverse_postorder(&p.blocks); if counted { // Before anything else, so that wave counts, reads of the first - // lane and stores know only the lanes that run. + // lane and stores know only the lanes that run (or with barriers, + // two-wave exchanges, or an entry loop header, threads past the + // count stay under `partial_active`). let original = self.s.entry; let width = self.s.threads.expect("compute thread count")[0]; let limit = self.host_word(RootType::Other(super::shader::USER_DISPATCH_THREADS_X), 0, width); @@ -2625,13 +2661,25 @@ impl<'a> Lower<'a> { let all = self.s.m.cmp(original, pred::EQ, limit, zero); let inside = self.s.m.cmp(original, pred::IULT, x, limit); let runs = self.s.m.bin(original, Bin::Or, all, inside); - let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); - self.s.m.terminate(original, Term::CondBr(runs, body, done)); - self.s.m.terminate(done, Term::Ret); - self.s.entry = body; + let barrier = p.blocks.iter().enumerate().any(|(b, blk)| { + !self.no_barrier.contains(&b) && blk.insts.iter().any(|i| i.name() == "s_barrier") + }); + let leave = self.exchange.is_none() + && self.halves.is_none() + && self.ticket.is_none() + && !self.split_lds + && !barrier + && p.blocks[order[0]].preds.is_empty(); + if leave { + let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(original, Term::CondBr(runs, body, done)); + self.s.m.terminate(done, Term::Ret); + self.s.entry = body; + } else { + self.partial_active = Some(runs); + } } self.find_coherent(); - let order = crate::ir::reverse_postorder(&p.blocks); for (n, &b) in order.iter().enumerate() { self.rpo[b] = n; } @@ -3552,7 +3600,7 @@ impl<'a> Lower<'a> { }; let (lo, hi) = (word(self, 0)?, word(self, 1)?); let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); let iu = self.s.m.undef(i32t); let align = self.s.m.i32(4); @@ -3806,7 +3854,12 @@ impl<'a> Lower<'a> { } let bit = self.boolean(m, at); self.balloting.remove(&lo); - let bit = bit?; + let mut bit = bit?; + if let Some(active) = self.partial_active + && self.x.st.active.contains(&lo) + { + bit = self.s.m.bin(at, Bin::And, bit, active); + } let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -4737,7 +4790,10 @@ impl<'a> Lower<'a> { Some(b) if b == self.cur_ir => self.cur, Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, }; - let bit = self.boolean(m, at)?; + let mut bit = self.boolean(m, at)?; + if let Some(active) = self.partial_active { + bit = self.s.m.bin(at, Bin::And, bit, active); + } let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); self.s.flags |= flags::WAVE_OPS; @@ -4765,7 +4821,16 @@ impl<'a> Lower<'a> { // elsewhere have no bit set, as on the console, so "some lane" needs no one but // the lanes here, and "every lane's bit is clear" is true of the others anyway. let c = self.cur; - let mine = self.boolean(when, c)?; + let mut mine = self.boolean(when, c)?; + if let Some(active) = self.partial_active { + mine = if any { + self.s.m.bin(c, Bin::And, mine, active) + } else { + let t = self.s.m.bool(true); + let off = self.s.m.bin(c, Bin::Xor, active, t); + self.s.m.bin(c, Bin::Or, mine, off) + }; + } let i1t = self.s.t.i1; self.s.flags |= flags::WAVE_OPS; let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; @@ -4783,12 +4848,15 @@ impl<'a> Lower<'a> { // what the halves exchange is "some lane speaks against" either way (for `any`: // some lane's `when` holds; else: some lane's does not), so a half with no lane says // nothing - let set = if any { + let mut set = if any { mine } else { let t = self.s.m.bool(true); self.s.m.bin(c, Bin::Xor, mine, t) }; + if let Some(active) = self.partial_active { + set = self.s.m.bin(c, Bin::And, set, active); + } let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); self.s.flags |= flags::WAVE_OPS; @@ -4871,6 +4939,18 @@ impl<'a> Lower<'a> { } } + /// Guard for instructions with an observable effect (memory, LDS access, + /// BVH intersection, image or buffer ops): combines [`Self::guard`] with + /// [`Self::partial_active`] so threads past a `DispatchX` count leave no + /// effect while staying alive for barriers and two-wave exchanges. + pub(super) fn effect_guard(&mut self, b: usize, i: usize) -> Result, Why> { + let g = self.guard(b, i)?; + Ok(match (g, self.partial_active) { + (Some(g), Some(a)) => Some(self.s.m.bin(self.cur, Bin::And, g, a)), + (g, a) => g.or(a), + }) + } + // ---- results ---- fn set(&mut self, v: Option, val: Val) { @@ -5406,7 +5486,13 @@ impl<'a> Lower<'a> { return Err("GDS"); } let name = inst.name(); - let guard = self.guard(b, i)?; + // Lanes past a DispatchX count neither read nor write LDS; a swizzle or + // permute moves registers only, under its own guard. + let guard = if name == "ds_swizzle_b32" || name.contains("permute") { + self.guard(b, i)? + } else { + self.effect_guard(b, i)? + }; let c = self.cur; let offset = u32::from(*offset0) | u32::from(*offset1) << 8; let dst_reg = match dst { @@ -9326,7 +9412,6 @@ impl<'a> Lower<'a> { } "v_readfirstlane_b32" => { let a = s(self, 0)?; - let (mine, any) = self.first_lane(a, guard); // two host waves that exchange: the console's first lane may be in the other // one, unless every lane holds the same value let alike = match v.src.first() { @@ -9336,6 +9421,16 @@ impl<'a> Lower<'a> { _ => true, }; let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; + // Alike in every lane the console runs: threads past a DispatchX count + // (`partial_active`) skipped the LDS and memory reads it is made of and hold + // another value, so the first lane is the first within the count. + let first_guard = match (guard, self.partial_active) { + (g, Some(on)) if (halves && alike) || g.is_some() => { + Some(g.map_or(on, |g| self.s.m.bin(self.cur, Bin::And, g, on))) + } + (g, _) => g, + }; + let (mine, any) = self.first_lane(a, first_guard); let r = if halves && !alike { if !self.all_lanes(self.cur_ir) { // shortcut: `VICTORY_FIRSTLANE_OWN=1` takes the host wave's own @@ -11254,7 +11349,7 @@ impl<'a> Lower<'a> { // A load or sample with no channel enabled returns the first. let dmask = if *dmask == 0 { &1 } else { dmask }; let site = (b, i); - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let c = self.cur; let (kind, coords) = match dim { 0 => (1, 1), @@ -12180,7 +12275,7 @@ impl<'a> Lower<'a> { return Err(name); } let site = (b, i); - let guard = self.guard(b, i)?; + let guard = self.effect_guard(b, i)?; let c = self.cur; let store = name.starts_with("buffer_store_"); // DXIL atomic operations: add, and, or, xor, signed and unsigned diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 19009227d..17231a085 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -1010,3 +1010,348 @@ fn the_console_threads_of_a_two_dimensional_group_are_each_given_once() { } eprintln!("ran on the hardware device: 64 of 64 console threads, each once"); } + +/// The structure builder's group prefix sums (wave64, 256 or 512 threads), +/// words 0x14c..0x210 as the console compiler made them: each wave's last lane +/// parks its total in shared memory, a barrier, then every wave but the first +/// adds up the totals of the waves before it in a loop over a lane test +/// (`v_cmpx_eq_u32 exec, s18, v7`) that carries the running sum in `s17` with a +/// `v_readfirstlane_b32` of `s17 + lds[s18 * 4]`. `addr` is the register the +/// loop's `ds_read_b32` takes its address from: v8 (the program's, +/// `v_mov_b32 v8, s16`) or v0 (a per-lane address, to test refusal). +fn prefix_sum_words(addr: u32) -> Vec { + vec![ + 0x7E0C_0300, // v_mov_b32 v6, v0 (the lane's own partial sum) + 0x7E0E_0300, // v_mov_b32 v7, v0 + 0xBE80_0380, // 14c s_mov_b32 s0, 0 + 0xBE81_03C1, // 150 s_mov_b32 s1, -1 + 0x4A0C_0D07, // 154 v_add_nc_u32 v6, v7, v6 + 0xD765_0007, // 158 v_mbcnt_lo_u32_b32 v7, -1, 0 + 0x0001_00C1, + 0xD760_0006, // 160 v_readlane_b32 s6, v6, 31 + 0x0001_3F06, + 0xD766_0009, // 168 v_mbcnt_hi_u32_b32 v9, -1, v7 + 0x0002_0EC1, + 0x2C0E_0086, // 170 v_lshrrev_b32 v7, 6, v0 (the console wave's number in the group) + 0xD501_0008, // 174 v_cndmask_b32 v8, 0, s6, s[0:1] + 0x0000_0C80, + 0xBE80_047E, // 17c s_mov_b64 s[0:1], exec + 0x4A0C_0D08, // 180 v_add_nc_u32 v6, v8, v6 + 0x7DA4_12BF, // 184 v_cmpx_eq_u32 exec, 63, v9 (the wave's last lane) + 0x3410_0E82, // 188 v_lshlrev_b32 v8, 2, v7 + 0xD834_0000, // 18c ds_write_b32 v8, v6 (the wave's total) + 0x0000_0608, + 0xBEFE_0400, // 194 s_mov_b64 exec, s[0:1] + 0xBF8C_C07F, // 198 s_waitcnt lgkmcnt(0) + 0xBF8A_0000, // 19c s_barrier + 0xBF80_0000, // 1a0 (pad) + 0xBF80_0000, + 0x7E10_0280, // 1a8 v_mov_b32 v8, 0 + 0xBE80_047E, // 1ac s_mov_b64 s[0:1], exec + 0x7DAA_0E80, // 1b0 v_cmpx_ne_u32 exec, 0, v7 (every wave but the first) + 0xBF88_0014, // 1b4 s_cbranch_execz 0x208 + 0xBE82_047E, // 1b8 s_mov_b64 s[2:3], exec + 0xBE86_047E, // 1bc s_mov_b64 s[6:7], exec + 0xBE92_0380, // 1c0 s_mov_b32 s18, 0 + 0xBE91_0380, // 1c4 s_mov_b32 s17, 0 + 0xBF82_0003, // 1c8 s_branch 0x1d8 + 0xBF80_0000, // 1cc (pad) + 0x87FE_0610, // 1d0 s_and_b64 exec, s[16:17], s[6:7] + 0x7E22_0508, // 1d4 v_readfirstlane_b32 s17, v8 (the running sum) + 0x8F10_8212, // 1d8 s_lshl_b32 s16, s18, 2 + 0x8112_8112, // 1dc s_add_i32 s18, s18, 1 + 0x7E10_0210, // 1e0 v_mov_b32 v8, s16 + 0xD8D8_0000, // 1e4 ds_read_b32 v8, v{addr} + 0x0800_0000 | addr, + 0xBF8C_C07F, // 1ec s_waitcnt lgkmcnt(0) + 0x4A10_1011, // 1f0 v_add_nc_u32 v8, s17, v8 + 0xBE90_047E, // 1f4 s_mov_b64 s[16:17], exec + 0x7DA4_0E12, // 1f8 v_cmpx_eq_u32 exec, s18, v7 + 0xBF80_0000, // 1fc s_nop 0 + 0x8A86_7E06, // 200 s_andn2_b64 s[6:7], s[6:7], exec + 0xBF85_FFF2, // 204 s_cbranch_scc1 0x1d0 + 0xBEFE_0400, // 208 s_mov_b64 exec, s[0:1] + 0x4A0C_0D08, // 20c v_add_nc_u32 v6, v8, v6 + 0x3402_0082, // v_lshlrev_b32 v1, 2, v0 + 0xD834_0040, // ds_write_b32 v1, v6 offset:64 (keeps the sum live) + 0x0000_0601, + S_ENDPGM, + ] +} + +fn lower_wave64_on_32(words: &[u32], threads: u32) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 15, // 2560 bytes: the totals and one dword a thread + threads: [threads, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, true, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let prev = lower::TEST_HOST_WAVE.replace(Some(32)); + let out = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(prev); + out +} + +#[test] +fn the_builders_prefix_sum_lowers_exactly_on_32_lane_waves() { + for threads in [256, 512] { + if let Err(e) = lower_wave64_on_32(&prefix_sum_words(8), threads) { + panic!("{threads} threads: the builder's prefix sum must lower on 32-lane waves, got: {e}"); + } + } +} + +#[test] +fn a_first_lane_read_of_a_per_lane_shared_memory_read_is_still_refused() { + let err = lower_wave64_on_32(&prefix_sum_words(0), 256) + .err() + .expect("a per-lane shared-memory read must not count as uniform") + .to_string(); + assert!(err.contains("a first-lane read where not every lane runs"), "got: {err}"); +} + +#[test] +fn a_first_lane_read_of_a_uniform_shared_memory_read_lowers_on_wave32() { + let make = |addr: u32| { + vec![ + 0xBE90_0380, // s_mov_b32 s16, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xD760_0004, // v_readlane_b32 s4, v0, 0 (halves exchange) + 0x0001_0100, + 0x7D88_0081, // v_cmp_gt_u32_e32 vcc, 1, v0 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBF88_0005, // s_cbranch_execz -> restore exec + 0x7E02_0210, // v_mov_b32 v1, s16 + 0xD8D8_0000, // ds_read_b32 v2, v{addr} + 0x0200_0000 | addr, + 0x4A10_0411, // v_add_nc_u32 v8, s17, v2 + 0x7E22_0508, // v_readfirstlane_b32 s17, v8 + 0xBEFE_0406, // s_mov_b64 exec, s[6:7] + 0x8011_0411, // s_add_u32 s17, s17, s4 + 0x7E06_0211, // v_mov_b32 v3, s17 + 0xD834_0000, // ds_write_b32 v0, v3 + 0x0000_0300, + S_ENDPGM, + ] + }; + if let Err(e) = lower_wave64_on_32(&make(1), 128) { + panic!("a uniform ds_read_b32 plus a scalar must count as uniform, got: {e}"); + } + let err = lower_wave64_on_32(&make(0), 128) + .err() + .expect("per-lane ds_read_b32 must be refused") + .to_string(); + assert!(err.contains("a first-lane read where not every lane runs"), "got: {err}"); +} + +#[test] +fn the_builders_prefix_sum_lowers_and_validates_as_a_spilled_dispatch_x_program() { + // Spilled user-data table (s[0:1], user data 16), so DispatchX counts + // threads (`USER_DISPATCH_THREADS_X`) and threads past the count stay + // under `partial_active` for the barrier and two-wave exchange. + let words = prefix_sum_words(8); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 256, + layout: vec![RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 16, + slot: 0, + }], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1 | 5 << 15, // s[0:1]: spilled table pointer; 2560 bytes LDS + threads: [256, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + assert!(crate::spill::is_spilled(&native)); + let p = crate::spill::build(&native).expect("spill::build"); + let st = structure::structure(&p).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 _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let prev = lower::TEST_HOST_WAVE.replace(Some(32)); + let out = lower::lower(&lower::Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(prev); + let out = out.unwrap_or_else(|e| panic!("spilled prefix sum must lower on 32-lane waves, got: {e}")); + let counts = RootType::Other(super::USER_DISPATCH_THREADS_X); + assert!( + out.user_data.iter().any(|u| u.root == counts && u.dword == 256), + "the program does not take the DispatchX thread count of x" + ); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = out.dxil.clone(); + v.validate(&mut copy).unwrap_or_else(|e| panic!("DXIL validation failed: {e}")); + } +} + +/// Spilled 64-thread wave64 compute program dispatched with a thread count +/// (`USER_DISPATCH_THREADS_X`): stores `(bit count of EXEC on entry, wave OR of +/// 1 << (lane >> 1))` at `uav[lane * 2..]`. On 64-lane waves threads past the +/// count return at entry; on 32-lane waves they stay under `partial_active` +/// for the two-wave exchange while excluded from the ballot, wave OR, and store. +#[test] +fn threads_past_a_dispatch_x_count_do_nothing() { + let mut words = vec![ + // The spilled table's descriptor-table offset (user data 16) from s[0:1] + 0. + 0x8703_FF01, + 0x0000_00FF, // s_and_b32 s3, s1, 0xff + 0xBE82_0300, // s_mov_b32 s2, s0 + 0x3D << 26 | 4 << 6 | 1, + 125 << 25, // s_load_dword s4, s[2:3], 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, + 125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xBE86_107E, // s_bcnt1_i32_b64 s6, exec + 0x7E0A_0281, // v_mov_b32 v5, 1 + 0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0 + 0x340E_0B06, // v_lshlrev_b32 v7, v6, v5 + ]; + words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + words.extend_from_slice(&[ + 0x3402_0083, // v_lshlrev_b32 v1, 3, v0 (8 bytes a lane) + 0x7E04_0206, // v_mov_b32 v2, s6 + 0x7E06_0207, // v_mov_b32 v3, s7 + 0x38 << 26 | 0x1D << 18 | 1 << 12, + 0x80 << 24 | 2 << 16 | 2 << 8 | 1, // buffer_store_dwordx2 v[2:3], v1, s[8:11], 0 offen + S_ENDPGM, + ]); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 16, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 16, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 16, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, // s[0:1]: the spilled table's pointer + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + assert!(crate::spill::is_spilled(&native)); + let p = crate::spill::build(&native).expect("spill::build"); + let st = structure::structure(&p).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 _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let host = Host::new(false).ok(); + let counts = RootType::Other(super::USER_DISPATCH_THREADS_X); + for host_wave in [64u32, 32] { + let was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); + let lowered = lower::lower(&lower::Parts { + native: &native, + p: &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.unwrap_or_else(|e| panic!("lower (waves of {host_wave}): {e}")); + assert!( + lowered.user_data.iter().any(|u| u.root == counts && u.dword == 64), + "waves of {host_wave}: the program does not take the thread count of x" + ); + 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.clone(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy) + .unwrap_or_else(|e| panic!("DXIL validation failed (waves of {host_wave}): {e}")); + } + let Some(host) = host.as_ref() else { continue }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("the hardware device does not take the waves-of-{host_wave} form; not run"); + continue; + }; + // (count, threads that run, their wave OR: bits 0..ceil(n / 2)) + for (count, active, or) in [(45u32, 45usize, 0x007F_FFFFu32), (1, 1, 1), (0, 64, u32::MAX)] { + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in shader.user_data.iter().filter(|u| u.root == counts && u.dword == 64) { + ud[u.index as usize] = count; + } + 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 (waves of {host_wave}, count {count}): {e}")); + for lane in 0..64 { + let got = (out[0][lane * 2], out[0][lane * 2 + 1]); + let expected = if lane < active { (active as u32, or) } else { (0, 0) }; + assert_eq!(got, expected, "waves of {host_wave}, count {count}, lane {lane}"); + } + } + } +}