diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b2c27c5342..83019b8994 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -670,7 +670,7 @@ impl HostHeap { )); let strides = (!sampler) .then(|| { - let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4; + let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_DWORDS) * 4; let (buffer, data) = host.upload_buffer(bytes)?; // SAFETY: the buffer's whole mapping; a live buffer. let gpu = unsafe { @@ -1125,6 +1125,17 @@ impl HostHeap { // SAFETY: inside the mapping; shaders read it while we write (a // dword, either value is one the slot had). unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; + // The title address of the buffer view, after the strides + // (`victory_shader::emit::SLOT_ADDRESSES`): low dword, then high. + let address = view + .and_then(buffer_range) + .map_or(0, |range| range.0); + // SAFETY: as above, two dwords inside the mapping. + unsafe { + let at = (*data as *mut u32).add((victory_shader::emit::SLOT_ADDRESSES + 2 * index) as usize); + at.write_volatile(address as u32); + at.add(1).write_volatile((address >> 32) as u32); + } } let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); let was = if stride.is_some() { diff --git a/crates/victory-shader/src/bvh.rs b/crates/victory-shader/src/bvh.rs index 9f5400114c..5360cf07a3 100644 --- a/crates/victory-shader/src/bvh.rs +++ b/crates/victory-shader/src/bvh.rs @@ -32,9 +32,10 @@ //! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four //! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16 //! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes -//! 112-127 are not read). The result is the pointers of the children whose -//! box the ray enters before its extent, nearest entry first when the -//! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest. +//! 112-127 are not read). The result is the pointers of the children that +//! are there and whose box the ray enters before its extent, nearest entry +//! first when the descriptor enables box sorting (bit 63), and +//! `0xffff_ffff` for the rest. //! //! # Triangle nodes //! @@ -64,9 +65,10 @@ //! JCGT 2013), and agree with what the title's own structure //! builder writes and its trace programs read. Not known from either: how //! 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). +//! returns first, what it returns for a ray exactly through an edge (here: +//! a hit in both triangles of the edge), for a child that is not there +//! whose box the ray enters (here: a miss) or for kinds 6 and 7 (here: a +//! triangle miss; the title's programs do not read it). /// The result dword for a box the ray misses, or a child that is not there. pub const NONE: u32 = 0xffff_ffff; @@ -196,8 +198,10 @@ pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) } let enter = near[0].max(near[1]).max(near[2]); let leave = far[0].min(far[1]).min(far[2]); - // A box whose minimum x is NaN is switched off. - if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent { + // A child that is not there is a miss, whatever bytes its box + // holds; a box whose minimum x is NaN is switched off. + let there = children[n] != NONE && !b[0].is_nan(); + if there && leave >= enter.max(0.0) && enter < ray.extent { ids[n] = children[n]; distances[n] = enter; } @@ -473,10 +477,45 @@ pub(crate) mod tests { [UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF], ); let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0); - // Child 1 is hit but is not there: its pointer is what "none" is. + // Child 1's box is entered, but child 1 is not there: a miss. assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]); } + /// A node whose children that are not there have boxes the ray + /// enters: the first before the one child's, the other two at the + /// ray's origin. (The card tests run it too.) + pub(crate) const MISSING_FIRST: ([u32; 4], [[f32; 6]; 4]) = ( + [NONE, 8, NONE, NONE], + [ + [-1.0, -1.0, 1.0, 1.0, 1.0, 2.0], + [-1.0, -1.0, 3.0, 1.0, 1.0, 4.0], + [0.0; 6], + [0.0; 6], + ], + ); + + /// The ray of [`MISSING_FIRST`]: from the origin along +z. + pub(crate) fn missing_first() -> Ray { + Ray::new([0.0; 3], [0.0, 0.0, 1.0], 10.0) + } + + #[test] + fn a_child_that_is_not_there_is_a_miss_whatever_its_box() { + let (children, boxes) = MISSING_FIRST; + let ray = missing_first(); + for (node, kind) in [(box32(children, boxes), 5), (box16(children, boxes), 4)] { + // Sorted: the child that is there (entered at 3), then the + // three that are not, their boxes entered at 0 and 1. + assert_eq!( + intersect(&node, kind, &ray, true), + [8, NONE, NONE, NONE], + "kind {kind}" + ); + // Not sorted: child order. + assert_eq!(intersect(&node, kind, &ray, false), children, "kind {kind}"); + } + } + #[test] fn equal_distances_keep_child_order() { let node = box32([8, 16, 24, 32], [UNIT; 4]); diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index 78a1d99ed4..0a928b71f9 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -403,6 +403,10 @@ impl<'a> Lower<'a> { let on = self.s.m.bin(c, Bin::Xor, off, on); let hit = self.s.m.bin(c, Bin::And, through, before); let hit = self.s.m.bin(c, Bin::And, hit, on); + // A child that is not there is a miss, whatever bytes its box + // holds: it must not sort before a child that is. + let there = self.s.m.cmp(c, pred::IULT, children[n], none); + let hit = self.s.m.bin(c, Bin::And, hit, there); ids[n] = self.s.m.select(c, hit, children[n], none); distances[n] = self.s.m.select(c, hit, enter, infinity); } diff --git a/crates/victory-shader/src/emit/intersect_tests.rs b/crates/victory-shader/src/emit/intersect_tests.rs index 0266579ac1..9bc6fb6d62 100644 --- a/crates/victory-shader/src/emit/intersect_tests.rs +++ b/crates/victory-shader/src/emit/intersect_tests.rs @@ -295,6 +295,13 @@ fn scene() -> (Scene, Vec>) { let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc]; box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5)); box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4)); + // A child that is not there whose box the ray enters first: the + // reference's own test of it, in both widths, with its ray alone. + let (missing, missing_boxes) = nodes::MISSING_FIRST; + let missing_nodes = [ + (s.add(nodes::box32(missing, missing_boxes), 32), 5), + (s.add(nodes::box16(missing, missing_boxes), 16), 4), + ]; // Random boxes. for n in 0..6 { let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| { @@ -357,6 +364,10 @@ fn scene() -> (Scene, Vec>) { cases.push(Some((n, kind, Ray::new(origin, direction, extent)))); } } + // The reference's test of a child that is not there, at its ray. + for &(n, kind) in &missing_nodes { + cases.push(Some((n, kind, nodes::missing_first()))); + } // Random rays at every box node, half of them aimed at a box. for &(n, kind) in &box_nodes { let words = s.node(n); diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index bef2e3c439..d103168f6f 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -450,55 +450,164 @@ fn need(block: usize) { /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, /// constants and such values; or loaded from an address made of them. The compiler keeps /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. -/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes -/// run (no lane branch can have split the arriving lanes); loop-carried values never do. -fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { +/// +/// Three more facts are proved, each only where no lane of a wave can part from the others: +/// - the wave number (`tid >> 6` of the entry `v0`, in a group whose x size is a multiple of +/// 64) is the same in all lanes of a console wave; +/// - an LDS read (`ds_read_b32`) at such an address is; +/// - a value joined by a phi is, also at a loop header, when its arguments are and every +/// predecessor is entered by all of the arriving lanes or none (the lanes' EXEC there is +/// made of conditions every lane agrees on: SCC values, compares of such values, and the +/// loop-carried masks made of them). That is a greatest fixed point: a loop-carried value +/// is taken to be alike and the assumption is dropped once an argument is not. +/// +/// shortcut: an LDS read is taken to see what a read by another wave of the same instruction +/// would; a write by another wave between the two host waves' reads is not looked for (the +/// scan programs read after a barrier). +fn lane_uniform(p: &Program, st: &Structured, all: &[bool], threads: Option<[u32; 3]>) -> HashSet { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); - let mut same: HashSet = HashSet::new(); - for b in crate::ir::reverse_postorder(&p.blocks) { - let block = &p.blocks[b]; - let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + let entry_v0 = p.inputs.iter().find(|(r, _)| *r == Reg::V(0)).map(|x| x.1); + let waves_whole = threads.is_some_and(|t| t[0] != 0 && t[0].is_multiple_of(64)); + // the V-register phis, and the lane-mask phis, assumed alike until shown not to be + let mut assumed_v: HashSet = HashSet::new(); + let mut assumed_m: HashSet = HashSet::new(); + for block in &p.blocks { for phi in &block.phis { - if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { - same.insert(phi.value); + if matches!(phi.reg, Reg::V(_)) { + assumed_v.insert(phi.value); + } + if st.masks.contains_key(&phi.value) { + assumed_m.insert(phi.value); } } - for (i, inst) in block.insts.iter().enumerate() { - let name = inst.name(); - let ops: Vec = match &inst.fields { - Fields::Valu(v) - if v.dpp.is_none() - && v.sdwa.is_none() - && !name.starts_with("v_mbcnt") - && !name.starts_with("v_cmpx") - && !name.contains("lane") => + } + // Whether a condition is the same in every lane of the wave. + let uniform_bool = |b: Bool, same: &HashSet, cmp: &HashSet, masks: &HashSet| { + st.bools.support(b).iter().all(|a| match a { + Atom::Uniform(_) => true, + Atom::Lane(v) => cmp.contains(v) || same.contains(v), + Atom::Phi(v) => masks.contains(v), + _ => false, + }) + }; + loop { + let mut same: HashSet = HashSet::new(); + // values written by compares whose operands are all alike (the lane's bit is the wave's) + let mut cmp: HashSet = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + // every predecessor is entered by all the arriving lanes or none of them + let together = block.preds.iter().all(|&q| { + uniform_bool(st.reach[q], &same, &cmp, &assumed_m) + && st.guards[q] + .iter() + .all(|g| (*g).is_none_or(|g| uniform_bool(g, &same, &cmp, &assumed_m))) + && match &st.exits[q] { + LaneExit::Branch { when, .. } => uniform_bool(*when, &same, &cmp, &assumed_m), + _ => true, + } + }); + for phi in &block.phis { + if !matches!(phi.reg, Reg::V(_)) { + continue; + } + if whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } else if together && assumed_v.contains(&phi.value) { + // its arguments are checked once the pass is done + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + let alike_ops = |ops: &[Operand], same: &HashSet| { + 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, + }) + }; + // a read of the group's LDS at an address the lanes agree on + if let Fields::Ds { dst: Some(_), addr: Some(addr), gds: false, .. } = &inst.fields + && name == "ds_read_b32" + && alike_ops(&[*addr], &same) + && st.guards[b][i].is_none_or(|g| uniform_bool(g, &same, &cmp, &assumed_m)) { - v.src.clone() + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + continue; + } + let ops: Vec = match &inst.fields { + Fields::Valu(v) if v.dpp.is_none() && v.sdwa.is_none() => v.src.clone(), + _ => continue, + }; + if name.starts_with("v_cmp") { + if alike_ops(&ops, &same) { + cmp.extend(inst.writes.iter().map(|w| w.1)); + } + if name.starts_with("v_cmpx") { + continue; + } + } else if name.starts_with("v_mbcnt") || name.contains("lane") { + continue; + } + // `tid >> k` (k at least 6) of the entry thread number: the wave's + if waves_whole + && name == "v_lshrrev_b32" + && let [Operand::Const(134..=159), Operand::Vector { reg: 0, .. }] = &ops[..] + && let Some(v0) = entry_v0 + && inst.read(Reg::V(0)) == Some(v0) + && st.guards[b][i].is_none_or(|g| uniform_bool(g, &same, &cmp, &assumed_m)) + { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + continue; + } + // lanes outside EXEC keep another value, unless the lanes agree on running it + if st.guards[b][i].is_some_and(|g| !uniform_bool(g, &same, &cmp, &assumed_m)) { + continue; + } + if alike_ops(&ops, &same) { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); } - _ => continue, - }; - if st.guards[b][i].is_some() { - continue; // lanes outside EXEC keep another value } - 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)) + } + // what was assumed of the loop-carried values: dropped where it did not hold + let mut changed = false; + for block in &p.blocks { + for phi in &block.phis { + if assumed_v.contains(&phi.value) + && same.contains(&phi.value) + && !phi.args.iter().all(|a| same.contains(a)) + { + assumed_v.remove(&phi.value); + changed = true; } - // 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)) + if assumed_m.contains(&phi.value) + && !phi.args.iter().all(|a| { + st.masks.get(a).is_some_and(|&m| uniform_bool(m, &same, &cmp, &assumed_m)) + }) + { + assumed_m.remove(&phi.value); + changed = true; } - _ => true, - }); - if alike { - same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); } } + if !changed { + return same; + } } - same } /// What a register value holds, for [`wave_local`]. @@ -1523,7 +1632,13 @@ impl<'a> Lower<'a> { local_ok: false, local_any: LOCAL_ANY.get(), uniform: match &exchange { - Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + Some((_, false, all)) if !LOCAL_WAVES.get() => { + let threads = match x.native.io { + StageIo::Cs(cs) => Some(cs.threads), + _ => None, + }; + lane_uniform(p, x.st, all, threads) + } _ => HashSet::new(), }, own_bits: match &exchange { @@ -2083,8 +2198,9 @@ impl<'a> Lower<'a> { if !every { if halves { need(self.cur_ir); + return Err(WHERE); } - return Err(WHERE); + return Ok(self.half_sum_present(x)); } let c = self.cur; let i32t = self.s.t.i32; @@ -2112,6 +2228,61 @@ impl<'a> Lower<'a> { Ok(self.s.m.bin(c, Bin::Or, first, total)) } + /// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past + /// the end of the data returns early): the console runs the sum in every lane, a lane + /// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds + /// that run's partial sum, the lanes that left included. A lane reads its partner run's + /// sum from the first lane of that run that is here, and +0 where none is (every lane of + /// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left. + fn half_sum_present(&mut self, x: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let here = self.s.m.bool(true); + let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); + // The lanes of the run of `size` lanes at `base` that are here, from bit 0. + let present = |l: &mut Self, base: V, size: u32| -> V { + let upper = l.s.m.cmp(c, pred::IUGE, base, k32); + let word = l.s.m.select(c, upper, bhi, blo); + let at = l.s.m.bin(c, Bin::And, base, k31); + let bits = l.s.m.bin(c, Bin::LShr, word, at); + if size >= 32 { + bits + } else { + let m = l.s.m.i32((1u32 << size) - 1); + l.s.m.bin(c, Bin::And, bits, m) + } + }; + let mut sum = x; + for step in 0..6u32 { + let size = 1u32 << step; + let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1))); + let other = self.s.m.bin(c, Bin::Xor, lane, bit); + let base = self.s.m.bin(c, Bin::And, other, run); + let bits = present(self, base, size); + // FirstbitLo (dx.op 32): the run's first lane that is here + let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let any = self.s.m.cmp(c, pred::NE, bits, zero); + let first = self.s.m.select(c, any, first, zero); + let from = self.s.m.bin(c, Bin::Add, base, first); + let theirs = self.read_lane(sum, from); + let theirs = self.s.m.select(c, any, theirs, zero); + sum = self.add_halves(sum, theirs); + } + let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1)); + let lane0 = self.s.m.bin(c, Bin::And, blo, one); + let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero); + let first = self.read_lane(x, zero); + let first = self.s.m.select(c, lane0, first, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + self.s.m.bin(c, Bin::Or, first, sum) + } + fn run(mut self) -> Result { let p = self.x.p; let order = crate::ir::reverse_postorder(&p.blocks); @@ -5617,6 +5788,18 @@ impl<'a> Lower<'a> { .find_map(|(s, _)| use_of(*s)) }; let use_at = use_of(site).or_else(twin); + // A descriptor nothing uses as one, whose size the code reads all the same (a + // texture picked from the heap by an index in a constant buffer, its width and + // height turned into a texel size; a buffer tested for being empty by its record + // count): the kind from its dwords and its used-resource entry. + let unused = if use_at.is_none() { + self.unused_descriptor_kind(inst, site, code, count) + } else { + None + }; + let (first, props, image, uav, used) = if let Some(kind) = unused { + kind + } else { let Some((at, first)) = use_at else { // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only // copies its dwords and compares them, lane against first lane, and every load @@ -5647,9 +5830,16 @@ impl<'a> Lower<'a> { // A buffer view the code only takes the address of, to walk // the memory behind it (a ray-tracing structure): the address // from the host, the other dwords have no value. - if count <= 4 - && let Some((lo, hi)) = self.view_address(site) - { + // The same for a view picked from the heap at an index the + // program computes: the host's table by heap slot has it. + let address = if count > 4 { + None + } else if let Some(a) = self.view_address(site) { + Some(a) + } else { + self.slot_address(site)? + }; + if let Some((lo, hi)) = address { for k in 0..count { let reg = Reg::S(code + k as u8); match k { @@ -5726,6 +5916,9 @@ impl<'a> Lower<'a> { } _ => return Err("a scalar memory read as data"), }; + (first, props, image, uav, used) + }; + let src = Source::Loaded { load: site, first }; let h = self.handle(site, &src, false, props)?; let c = self.cur; let i32t = self.s.t.i32; @@ -5793,8 +5986,10 @@ impl<'a> Lower<'a> { inst.write(Reg::S(code + first + k)) .is_some_and(|v| self.computed_with(v, 6)) }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) if first == 0 - && computed + && (computed || unused.is_some()) && let Some((lo, hi)) = self.view_address(site) { words.extend([(0, lo), (1, hi)]); @@ -5817,6 +6012,67 @@ impl<'a> Lower<'a> { Ok(()) } + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose dwords the code reads: the first dword, the handle properties, + /// the image kind (none for a buffer), whether it is an unordered view, and its + /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four + /// as a raw view's where the code reads its record count (dword 2); none for anything + /// else (a constant buffer, a sampler, a buffer whose address alone is read). + // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's + // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of + // another kind would answer its own sizes. + #[allow(clippy::type_complexity)] + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(u8, (u32, u32), Option, bool, Option<&'a UsedResource>)> { + // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases + // `descriptor_data` handles on their own. + if self.x.res.lane_copied.contains(&site) + || self.x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }) + { + return None; + } + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + // width (dwords 1-2), height (2), levels (3), depth (4) + 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => { + Some((0, (2 | u, 0x409), Some(2), uav, used)) + } + // the record count + 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => { + Some((0, (11 | u, 0), None, uav, used)) + } + _ => None, + } + } + /// `s_load_dword*` from the program's constant table. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { @@ -6295,6 +6551,48 @@ impl<'a> Lower<'a> { Ok(Some(v)) } + /// The title address (low, high dword) of the buffer view the scalar load + /// at `load` picks from the view heap at an index the program computes, + /// from the host's table by heap slot ([`super::shader::SLOT_ADDRESSES`]); + /// None if the load is not of that kind. + fn slot_address(&mut self, load: Site) -> Result, Why> { + let heap = self + .scalar + .get(&load) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap); + if !heap { + return Ok(None); + } + let c = self.cur; + let slot = self.heap_index(load, 0, false)?; + // Inside the table whatever the index. + let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); + let i32t = self.s.t.i32; + let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + let three = self.s.m.i32(3); + let byte = self.s.m.bin(c, Bin::Shl, slot, three); + let first = self.s.m.i32(super::shader::SLOT_ADDRESSES * 4); + let byte = self.s.m.bin(c, Bin::Add, byte, first); + let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); + let iu = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(3); + let align = self.s.m.i32(4); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ); + let lo = self.s.m.extract(c, r, 0); + let lo = self.as_int(lo); + let hi = self.s.m.extract(c, r, 1); + let hi = self.as_int(hi); + Ok(Some((lo, hi))) + } + /// The heap index of a descriptor that may differ between lanes, /// computed in the current block (or, chosen by control flow, at the /// join). @@ -8902,6 +9200,25 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { + // The first half of a pair: its second half interpolates the + // attribute itself, so nothing needs this half's partial sum. + // But an f16 second half that writes the high half of the + // register this one wrote keeps the low half as it was (the + // console compiler reuses the register; the low half is not + // read), so the register needs a value: 0. + let name = inst.name(); + if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" { + let dst = match &inst.fields { + Fields::Vintrp { dst, .. } => Some(*dst), + Fields::Valu(v) => v.dst, + _ => None, + }; + if let Some(Operand::Vector { reg, .. }) = dst { + let zero = self.s.m.i32(0); + self.write(inst, Reg::V(reg), zero, None); + return Ok(()); + } + } return Err("the first half of an interpolation"); }; let name = inst.name(); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 5f2b298d50..d2d3133d1d 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -113,8 +113,8 @@ pub use sampler::StaticSampler; pub use lower::set_host_max_wave; pub use rect::rect_list_gs; pub use shader::{ - MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_ADDRESSES, SLOT_FAULTS, SLOT_MEMORY, + SLOT_STRIDES, SLOT_STRIDES_COUNT, SLOT_STRIDES_DWORDS, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit, }; diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 28a36f1bed..b1355bfee8 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -26,6 +26,16 @@ pub const ROOT_CBV_SPACE: u32 = 1; pub const SLOT_STRIDES: u8 = 255; /// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it. pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; +/// Where the [`SLOT_STRIDES`] buffer goes on, in dwords: two per heap slot, +/// the low and then the high dword of the title address of the buffer view +/// at that slot (0: none). For a program that takes a buffer view out of the +/// heap at an index it computes and reads the address out of the descriptor +/// to walk the memory behind it (the shadow-ray trace programs take their +/// ray-tracing structure this way). +pub const SLOT_ADDRESSES: u32 = SLOT_STRIDES_COUNT; +/// Dwords of the whole [`SLOT_STRIDES`] buffer: the strides, then the +/// addresses ([`SLOT_ADDRESSES`]). +pub const SLOT_STRIDES_DWORDS: u32 = 3 * SLOT_STRIDES_COUNT; /// Title memory by address (`resource::MEMORY`): console code reads and /// writes through raw 40-bit addresses it takes from root constants, diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index db82f33bc5..55cc55de13 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -95,10 +95,20 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { /// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet) -> Result { + lowered_on(native, p, wide, 32) +} + +/// [`lowered`] for a host whose waves have at most `host_wave` lanes. +fn lowered_on( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet, + host_wave: u32, +) -> Result { 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 was = lower::TEST_HOST_WAVE.replace(Some(host_wave)); let lowered = lower::lower(&lower::Parts { native, p, @@ -199,6 +209,76 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } +/// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a +/// thread past the end of the data): on the console they add +0, and after each step of the +/// tree they hold their run's partial sum all the same. On a host of 64-lane waves (AMD) the +/// lanes that are here read each partner run's sum from a lane of it that is here. +#[test] +fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { + let mut words = vec![ + 0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay + 0, // s_cbranch_execz to the end (filled in below) + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + // past every word after it, to the program's end + words[1] = 0xBF88_0000 | (words.len() as u32 - 2); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = lowered_on(&native, &p, &HashSet::new(), 64).expect("lower"); + 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"); + } + let wide = |h: u16| { + if h == 0 { + 0.0 + } else { + f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13) + } + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = false; + for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] { + let terms: Vec = (0..64u32) + .map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 }) + .collect(); + let mut tree = terms.clone(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); + } + let Some(got) = on_the_card(&shader, [stay, 0]) else { + return; + }; + ran = true; + // (the high half is lane 0's term's: zero) + assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]); + } + if ran { + eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case"); + } +} + /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 /// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The /// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md index dee02815c7..2d1f2de3d7 100644 --- a/docs/fork-ray-tracing.md +++ b/docs/fork-ray-tracing.md @@ -49,7 +49,7 @@ shaders and emulates the one instruction. for box nodes; a watertight ray/triangle test for triangle nodes; both forms of the instruction. A plain Rust reference lives in `crates/victory-shader/src/bvh.rs`; tests run the emitted DXIL on the GPU - over 311 ray/node cases and compare with the reference bit for bit. + over 313 ray/node cases and compare with the reference bit for bit. 4. **The trace and shading programs translate** (59 of 64 trace programs, and the irradiance-cache shading program). This needed lane masks treated as plain numbers on some paths, and exact forms for programs written for @@ -70,8 +70,9 @@ shaders and emulates the one instruction. - An access to a title page that has no host copy is lost (a read gives zero, a store is dropped). - Not publicly documented, and assumed: the instruction's rounding, the order - of two boxes entered at the same distance, and the result for a ray exactly - through an edge. + of two boxes entered at the same distance, the result for a ray exactly + through an edge, and what a child that is not there returns when the ray + enters its box (here: a miss). - Cost on the GPU is unmeasured. ## Where to look