diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 150bd88e..3c9b0590 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1001,8 +1001,8 @@ fn view_stride(view: &View) -> u32 { /// The view-stride table's format-kind bits of a buffer view: a typed view /// (no structure stride, not raw) of an integer format gets /// `VIEW_INTEGER`, a signed one also `VIEW_SIGNED`; anything else none. -/// Translated shaders pass 16-bit typed data of such views as bits, not as -/// halves (`victory_shader::emit`, "d16"). +/// Translated shaders select integer typed-buffer overloads for such views, +/// and pass their 16-bit typed data as bits (`victory_shader::emit`, "d16"). fn view_kind(view: &View) -> u32 { use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; let (unordered, words): (bool, &[u32; 10]) = match view { @@ -1801,6 +1801,8 @@ mod tests { // Format, dimension (buffer), first element, count, stride, counter, flags. let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0])); assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT"); + assert_eq!(view_kind(&uav(7, 0, 0)), VIEW_INTEGER, "R32G32B32_UINT"); + assert_eq!(view_kind(&uav(8, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R32G32B32_SINT"); assert_eq!(view_kind(&uav(57, 0, 0)), VIEW_INTEGER, "R16_UINT"); assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT"); assert_eq!(view_kind(&uav(64, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R8_SINT"); diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index 68316a36..dabbd439 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -584,15 +584,28 @@ impl Module { } } + /// Calls of functions named `name` that [`Module::write`] writes, and the + /// blocks holding them. + #[cfg(test)] + pub fn written_call_blocks(&self, name: &str) -> Vec { + let plan = self.plan(); + let mut blocks = Vec::new(); + for &b in &plan.layout { + for &i in &self.blocks[b].body { + if plan.live[i as usize] + && matches!(self.insts[i as usize].op, Op::Call(f, _) if self.funcs[f as usize].name == name) + { + blocks.push(b); + } + } + } + blocks + } + /// Calls of functions named `name` that [`Module::write`] writes. #[cfg(test)] pub fn written_calls(&self, name: &str) -> usize { - let plan = self.plan(); - let calls = plan.layout.iter().flat_map(|&b| &self.blocks[b].body); - calls - .filter(|&&i| plan.live[i as usize]) - .filter(|&&i| matches!(self.insts[i as usize].op, Op::Call(f, _) if self.funcs[f as usize].name == name)) - .count() + self.written_call_blocks(name).len() } /// The globals and functions [`Module::write`] declares, each kept diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index b31d744c..b36165a0 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -72,6 +72,36 @@ pub fn under_wine() -> bool { } impl Host { + /// Whether this device can create a typed buffer UAV and both load and + /// store through it. D3DMetal advertises RGB32 support but aborts when the + /// view is created, so those formats are skipped on the hardware adapter + /// under Wine; WARP is still queried normally. + pub fn typed_buffer_access(&self, format: DXGI_FORMAT, warp: bool) -> bool { + if !warp && under_wine() + && matches!(format, DXGI_FORMAT_R32G32B32_FLOAT | DXGI_FORMAT_R32G32B32_UINT | DXGI_FORMAT_R32G32B32_SINT) + { + return false; + } + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: format, + ..Default::default() + }; + // SAFETY: the query writes the structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of_val(&support) as u32, + ) + .is_ok() + }; + ok && support.Support1.contains(D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + && support.Support2.contains( + D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD | D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE, + ) + } + /// Whether the device runs 64-bit atomics on typed resources in the /// descriptor heap. `victory_gpu` refuses pipelines that need them on /// devices without (D3DMetal 4.0 beta 3 has none). @@ -1361,11 +1391,13 @@ pub enum View<'a> { #[cfg(test)] pub fn view_strides(views: &[View]) -> Vec { let kind = |f: DXGI_FORMAT| match f { - DXGI_FORMAT_R32G32B32A32_UINT | DXGI_FORMAT_R16G16B16A16_UINT | DXGI_FORMAT_R32G32_UINT - | DXGI_FORMAT_R10G10B10A2_UINT | DXGI_FORMAT_R8G8B8A8_UINT | DXGI_FORMAT_R16G16_UINT + DXGI_FORMAT_R32G32B32A32_UINT | DXGI_FORMAT_R32G32B32_UINT | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R32G32_UINT | DXGI_FORMAT_R10G10B10A2_UINT | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R16G16_UINT | DXGI_FORMAT_R32_UINT | DXGI_FORMAT_R8G8_UINT | DXGI_FORMAT_R16_UINT | DXGI_FORMAT_R8_UINT => super::VIEW_INTEGER, - DXGI_FORMAT_R32G32B32A32_SINT | DXGI_FORMAT_R16G16B16A16_SINT | DXGI_FORMAT_R32G32_SINT - | DXGI_FORMAT_R8G8B8A8_SINT | DXGI_FORMAT_R16G16_SINT | DXGI_FORMAT_R32_SINT + DXGI_FORMAT_R32G32B32A32_SINT | DXGI_FORMAT_R32G32B32_SINT | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_SINT | DXGI_FORMAT_R8G8B8A8_SINT | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_SINT | DXGI_FORMAT_R8G8_SINT | DXGI_FORMAT_R16_SINT | DXGI_FORMAT_R8_SINT => super::VIEW_INTEGER | super::VIEW_SIGNED, _ => 0, }; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 7cb1f160..663b8c0b 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -35,6 +35,14 @@ enum Val { Missing(Why), } +#[cfg(test)] +pub(crate) struct TypedBufferCalls { + /// Blocks with `bufferLoad.f32` and `bufferLoad.i32` calls. + pub loads: [Vec; 2], + /// Blocks with `bufferStore.f32` and `bufferStore.i32` calls. + pub stores: [Vec; 2], +} + pub(crate) struct Lowered { pub dxil: Vec, /// Bit n: immediate sampler n is a comparison sampler. @@ -70,6 +78,9 @@ pub(crate) struct Lowered { /// Whether it declares rasterizer-ordered views. #[cfg(test)] pub rovs: bool, + /// Written typed-buffer calls, for structural tests of the dynamic path. + #[cfg(test)] + pub typed_buffer_calls: TypedBufferCalls, /// Barriers added for narrow host waves ([`split_wave_barriers`]). #[cfg(test)] pub split_barriers: usize, @@ -135,6 +146,11 @@ pub(crate) fn lower_pruned( } const TWO_PI: f32 = std::f32::consts::TAU; +/// `dx.types.ResourceProperties`' second dword for a four-component typed +/// handle: component type in byte 0 (`F32` = 9, `I32` = 4), component count in +/// byte 1. UINT and SINT views both use the signless `.i32` DXIL overload. +const TYPED_F32_PROPS: u32 = 9 | 4 << 8; +const TYPED_I32_PROPS: u32 = 4 | 4 << 8; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; @@ -203,6 +219,8 @@ fn half_shift(width: u32) -> u32 { /// parameter and byte offset. type EntryAddress = (usize, u32); +type HandleKey = (usize, Site, u8, bool, (u32, u32)); + struct Lower<'a> { s: Shader, x: &'a Parts<'a>, @@ -242,15 +260,15 @@ struct Lower<'a> { waterfall_compares: Set, waterfall_reads: Set, waterfall_loads: Set, - handles: Map<(usize, Site, u8, bool, u32), V>, + handles: Map, /// Handles made in the entry block for descriptors at addresses the /// root parameters alone give (table and heap loads with no other /// term), by base value, byte offset, dword, offset register, sampler /// heap and properties ([`Lower::entry_address`]). - entry_handles: Map<(EntryAddress, u8, bool, u32), V>, + entry_handles: Map<(EntryAddress, u8, bool, (u32, u32)), V>, /// Handles of descriptors chosen by control flow, made in their join /// block, by the choice (its `Debug` text), sampler heap and properties. - join_handles: Map<(String, bool, u32), V>, + join_handles: Map<(String, bool, (u32, u32)), V>, /// Blocks splitting the edge from one IR block to another. edges: Map<(usize, usize), usize>, /// Per IR block: a `done` export is behind every lane entering it. @@ -1122,7 +1140,8 @@ impl<'a> Lower<'a> { args.push(self.s.m.i32(4)); self.s .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); - self.mark_view_write(h, off, 4 * u32::from(n), None); + let bytes = self.s.m.i32(4 * u32::from(n)); + self.mark_view_write(h, off, bytes, None); self.end_guarded(at, &[]); return Ok(()); } @@ -1165,7 +1184,8 @@ impl<'a> Lower<'a> { ); first.get_or_insert(r); } - self.mark_view_write(h, off, 4, None); + let bytes = self.s.m.i32(4); + self.mark_view_write(h, off, bytes, None); let zero = self.s.m.i32(0); let r = self.end_guarded(at, &[(first.expect("an atomic"), zero)])[0]; if let Some(reg) = returned { @@ -1521,6 +1541,17 @@ impl<'a> Lower<'a> { #[cfg(test)] rovs: self.s.flags & flags::ROVS != 0, #[cfg(test)] + typed_buffer_calls: TypedBufferCalls { + loads: [ + self.s.m.written_call_blocks("dx.op.bufferLoad.f32"), + self.s.m.written_call_blocks("dx.op.bufferLoad.i32"), + ], + stores: [ + self.s.m.written_call_blocks("dx.op.bufferStore.f32"), + self.s.m.written_call_blocks("dx.op.bufferStore.i32"), + ], + }, + #[cfg(test)] split_barriers: self.split_barriers.len(), #[cfg(test)] wave_size: self.s.wave_size, @@ -4644,7 +4675,7 @@ impl<'a> Lower<'a> { /// notes, "Write marks"): the bits of its first and last byte, each set /// only where still clear. Nothing for handles that are no heap view, or /// without [`Parts::view_marks`]. - fn mark_view_write(&mut self, h: V, x: V, bytes: u32, guard: Option) { + fn mark_view_write(&mut self, h: V, x: V, bytes: V, guard: Option) { if !self.x.view_marks { return; } @@ -4666,7 +4697,10 @@ impl<'a> Lower<'a> { None => valid, }; let first = self.s.m.bin(c, Bin::Add, phase, x); - let span = k(self, bytes.max(1) - 1); + let (zero, one) = (k(self, 0), k(self, 1)); + let nonempty = self.s.m.cmp(c, pred::NE, bytes, zero); + let span = self.s.m.bin(c, Bin::Sub, bytes, one); + let span = self.s.m.select(c, nonempty, span, zero); let last = self.s.m.bin(c, Bin::Add, first, span); let (k16, cap) = (k(self, 16), k(self, super::VIEW_WRITE_BITS - 1)); let mut bits = Vec::new(); @@ -4736,6 +4770,68 @@ impl<'a> Lower<'a> { Some((int, signed)) } + /// A 32-bit typed load through independently annotated float and integer + /// handles. The view's format is dynamic, so the overloads must be in + /// mutually exclusive branches: executing `bufferLoad.i32` on a float view + /// (or the reverse) is not a bitcast. Each result channel is an `i32` phi; + /// the float path bitcasts only after the float load has taken place. + fn typed_buffer_load( + &mut self, + float_h: V, + integer_h: V, + index: V, + integer: V, + count: u32, + ) -> Vec { + let head = self.cur; + let (integer_block, float_block, join) = ( + self.s.m.new_block(), + self.s.m.new_block(), + self.s.m.new_block(), + ); + self.s.m.terminate(head, Term::CondBr(integer, integer_block, float_block)); + let iu = self.s.m.undef(self.s.t.i32); + let mut integer_values = Vec::new(); + self.cur = integer_block; + let r = self.s.op( + integer_block, + "bufferLoad.i32", + Attr::ReadOnly, + self.s.t.res_ret_i32, + 68, + &[integer_h, index, iu], + ); + for ch in 0..count { + integer_values.push(self.s.m.extract(integer_block, r, ch)); + } + self.s.m.terminate(integer_block, Term::Br(join)); + let mut float_values = Vec::new(); + self.cur = float_block; + let r = self.s.op( + float_block, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[float_h, index, iu], + ); + for ch in 0..count { + let x = self.s.m.extract(float_block, r, ch); + float_values.push(self.as_int(x)); + } + self.s.m.terminate(float_block, Term::Br(join)); + self.cur = join; + integer_values + .into_iter() + .zip(float_values) + .map(|(integer, float)| { + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, vec![(integer, integer_block), (float, float_block)]); + phi + }) + .collect() + } + /// Title memory at a raw GPU address (decision 0005: the unified-memory /// item). Every access to an address the program computes goes through /// here: scalar and global loads, stores and atomics, the BVH node @@ -5434,7 +5530,7 @@ impl<'a> Lower<'a> { // compiler reloads one before every use rather than keep it // (ActivateRays: 2,399 loads of one), and one handle made in // the entry block serves them all. - let key = (address, *first, sampler, props.0); + let key = (address, *first, sampler, props); if let Some(&h) = self.entry_handles.get(&key) { return Ok(h); } @@ -5447,7 +5543,7 @@ impl<'a> Lower<'a> { Ok(h) } Source::Loaded { load, first } => { - let key = (self.cur, *load, *first, sampler, props.0); + let key = (self.cur, *load, *first, sampler, props); if let Some(&h) = self.handles.get(&key) { return Ok(h); } @@ -5556,7 +5652,7 @@ impl<'a> Lower<'a> { // One handle at the join for every access the choice reaches // (each is in a block the join dominates). let _ = site; - let key = (format!("{src:?}"), sampler, props.0); + let key = (format!("{src:?}"), sampler, props); if let Some(&h) = self.join_handles.get(&key) { return Ok(h); } @@ -9667,7 +9763,8 @@ impl<'a> Lower<'a> { self.s .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) }; - self.mark_view_write(h, byte, 4, None); + let bytes = self.s.m.i32(4); + self.mark_view_write(h, byte, bytes, None); let r = self.end_guarded(at, &[(r, old)])[0]; if returns { self.write(inst, Reg::V(reg), r, None); @@ -9701,7 +9798,8 @@ impl<'a> Lower<'a> { self.s .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); } - self.mark_view_write(h, at, 4, None); + let bytes = self.s.m.i32(4); + self.mark_view_write(h, at, bytes, None); self.end_guarded(begin, &[]); return Ok(()); } @@ -9710,7 +9808,7 @@ impl<'a> Lower<'a> { let mut vals = self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; let typed_h = if typed { - Some(self.handle(site, src, false, (10 | u, 0x409))?) + Some(self.handle(site, src, false, (10 | u, TYPED_F32_PROPS))?) } else { None }; @@ -9746,6 +9844,90 @@ impl<'a> Lower<'a> { } vals = wide; } + if typed && !d16 { + // As for loads, a dynamic integer view gets a separately + // annotated handle and a mutually exclusive integer store. + if count != 4 { + return Err("a typed buffer store of some channels or at an offset"); + } + if *offen || *offset != 0 || matches!(off, V::Inst(_)) { + return Err("a typed buffer store at an offset"); + } + let h = typed_h.ok_or("a typed buffer store")?; + let element = index.unwrap_or(self.s.m.i32(0)); + let (byte, bytes) = if self.x.view_marks { + let at = self + .s + .view_index + .get(&h) + .copied() + .ok_or("a typed buffer store")?; + let stride = self.stride_at(at); + (self.s.m.bin(self.cur, Bin::Mul, element, stride), stride) + } else { + (element, self.s.m.i32(0)) + }; + let integer = self.integer_view(h).map(|(integer, _)| integer); + let integer_h = if integer.is_some() { + Some(self.handle(site, src, false, (10 | u, TYPED_I32_PROPS))?) + } else { + None + }; + let outer = self.begin_guarded(guard); + self.mark_view_write(h, byte, bytes, None); + if let (Some(integer), Some(integer_h)) = (integer, integer_h) { + let head = self.cur; + let (integer_block, float_block, join) = ( + self.s.m.new_block(), + self.s.m.new_block(), + self.s.m.new_block(), + ); + self.s.m.terminate(head, Term::CondBr(integer, integer_block, float_block)); + let iu = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(0xF); + self.cur = integer_block; + let mut args = vec![integer_h, element, iu]; + args.extend_from_slice(&vals); + args.push(mask); + self.s.op( + integer_block, + "bufferStore.i32", + Attr::NoUnwind, + self.s.t.void, + 69, + &args, + ); + self.s.m.terminate(integer_block, Term::Br(join)); + self.cur = float_block; + let mut args = vec![h, element, iu]; + args.extend(vals.iter().map(|&x| self.as_float(x))); + args.push(mask); + self.s.op( + float_block, + "bufferStore.f32", + Attr::NoUnwind, + self.s.t.void, + 69, + &args, + ); + self.s.m.terminate(float_block, Term::Br(join)); + self.cur = join; + } else { + let mut args = vec![h, element, iu]; + args.extend(vals.iter().map(|&x| self.as_float(x))); + args.push(self.s.m.i8(0xF)); + self.s.op( + self.cur, + "bufferStore.f32", + Attr::NoUnwind, + self.s.t.void, + 69, + &args, + ); + } + self.end_guarded(outer, &[]); + return Ok(()); + } let mut args = Vec::new(); // Where the write starts in the view, and how many bytes it may // cover (for its marks). @@ -9753,9 +9935,12 @@ impl<'a> Lower<'a> { let (op, name) = if typed { // shortcut: typed stores are taken to write all four channels // of a float format. - if count != 4 || *offen || *offset != 0 { + if count != 4 { return Err("a typed buffer store of some channels or at an offset"); } + if *offen || *offset != 0 || matches!(off, V::Inst(_)) { + return Err("a typed buffer store at an offset"); + } let h = typed_h.ok_or("a typed buffer store")?; let element = index.unwrap_or(self.s.m.i32(0)); args.push(h); @@ -9763,13 +9948,19 @@ impl<'a> Lower<'a> { for x in vals { args.push(self.as_float(x)); } - // The element's size is the view's stride (16 bytes at most). - (byte, bytes) = match self.s.view_index.get(&h).copied() { - Some(at) if self.x.view_marks => { - let stride = self.stride_at(at); - (self.s.m.bin(self.cur, Bin::Mul, element, stride), 16) - } - _ => (element, 16), + // The element's size is the view's stride, not always 16. It + // is needed at run time only for the write marks. + (byte, bytes) = if self.x.view_marks { + let at = self + .s + .view_index + .get(&h) + .copied() + .ok_or("a typed buffer store")?; + let stride = self.stride_at(at); + (self.s.m.bin(self.cur, Bin::Mul, element, stride), stride) + } else { + (element, self.s.m.i32(0)) }; (69, "bufferStore.f32") } else { @@ -9783,14 +9974,16 @@ impl<'a> Lower<'a> { args.extend([index, off]); let s = self.s.m.i32(stride); let row = self.s.m.bin(self.cur, Bin::Mul, index, s); - (byte, bytes) = (self.s.m.bin(self.cur, Bin::Add, row, off), 4 * count); + let width = self.s.m.i32(4 * count); + (byte, bytes) = (self.s.m.bin(self.cur, Bin::Add, row, off), width); } None => { let n = 4 * count; let (h, off) = self.raw_view(site, src, off, n, (11 | u, 0), true, guard)?; args.extend([h, off, iu]); - (byte, bytes) = (off, n); + let width = self.s.m.i32(n); + (byte, bytes) = (off, width); } } args.extend(&vals); @@ -9861,6 +10054,42 @@ impl<'a> Lower<'a> { self.write(inst, Reg::V(reg), x, guard); return Ok(()); } + if typed && !d16 { + if *offen || matches!(off, V::Inst(_)) || *offset != 0 { + return Err("a typed buffer load at an offset"); + } + if uav { + self.s.flags |= flags::TYPED_UAV_LOADS; + } + let h = self.handle(site, src, false, (10 | u, TYPED_F32_PROPS))?; + let index = index.unwrap_or(self.s.m.i32(0)); + let xs = if let Some((integer, _)) = self.integer_view(h) { + let integer_h = self.handle(site, src, false, (10 | u, TYPED_I32_PROPS))?; + self.typed_buffer_load(h, integer_h, index, integer, count) + } else { + let r = self.s.op( + self.cur, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[h, index, iu], + ); + (0..count) + .map(|ch| { + let x = self.s.m.extract(self.cur, r, ch); + self.as_int(x) + }) + .collect() + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for (k, x) in xs.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } let mut typed_h = None; let r = if typed { if *offen || matches!(off, V::Inst(_)) || *offset != 0 { @@ -9869,7 +10098,7 @@ impl<'a> Lower<'a> { if uav { self.s.flags |= flags::TYPED_UAV_LOADS; } - let h = self.handle(site, src, false, (10 | u, 0x409))?; + let h = self.handle(site, src, false, (10 | u, TYPED_F32_PROPS))?; typed_h = Some(h); let index = index.unwrap_or(self.s.m.i32(0)); self.s.op( @@ -9922,11 +10151,11 @@ impl<'a> Lower<'a> { // Two 16-bit channels per VGPR (an odd last high half 0): f16 for // float and normalized formats; for integer formats (the view's // kind, from the view-stride table) the integer's low 16 bits. - // shortcut: an integer view is read and written through the - // float-typed handle, so its channels' bits travel as the driver - // passes a mismatched component type (unchanged on the RX 6700 - // XT and WARP, `stride_tests`); an integer-typed second handle - // for the slot would not rely on it. + // Unlike the 32-bit accesses above, `_d16` keeps the established + // widened-float path for narrow formats: an integer view is read + // and written through the float-typed handle, so its channels' bits + // travel as the driver passes a mismatched component type + // (unchanged on the RX 6700 XT and WARP, `stride_tests`). let integer = typed_h.and_then(|h| self.integer_view(h)); let c = self.cur; let k16 = self.s.m.i32(16); @@ -11038,1230 +11267,4 @@ pub(crate) fn split_wave_barriers(p: &Program) -> Option> { } #[cfg(test)] -mod tests { - use super::{ - Lowered, Numeric, Parts, barycentric_signature, buffer_format, half_shift, lower, - packed_half, - }; - use crate::native::{ - ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, - }; - use crate::{io, ir, resource, structure}; - - const S_ENDPGM: u32 = 0xBF81_0000; - - #[test] - fn direct_barycentric_modes_match_dxil_semantics() { - use crate::io::Barycentric::*; - - assert_eq!(barycentric_signature(PerspectiveSample), Some((0, 6))); - assert_eq!(barycentric_signature(PerspectiveCenter), Some((0, 2))); - assert_eq!(barycentric_signature(PerspectiveCentroid), Some((0, 3))); - assert_eq!(barycentric_signature(LinearSample), Some((1, 7))); - assert_eq!(barycentric_signature(LinearCenter), Some((1, 4))); - assert_eq!(barycentric_signature(LinearCentroid), Some((1, 5))); - assert_eq!(barycentric_signature(PerspectivePullModel), None); - } - - /// Whether a synthetic compute program translates with these input registers. - fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, false, 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(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - atomic_locks: false, - bias_as_gradients: false, - host_wave32: false, - narrow_waves: false, - view_marks: false, - }) - .map(|_| ()) - } - - /// Lowers a compute program with the root parameters `layout` (in user - /// SGPRs from s0 on) and the used resources `used`. - fn lower_with( - words: &[u32], - layout: Vec, - used: Vec, - ) -> Result { - lower_wave(words, layout, used, false) - } - - /// [`lower_with`] in wave64 if `wave64`. - fn lower_wave( - words: &[u32], - layout: Vec, - used: Vec, - wave64: bool, - ) -> Result { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); - let native = NativeProgram { - stage: HwStage::Cs, - wave64, - vgprs: 256, - layout, - used, - io: StageIo::Cs(ComputeIo { - // The layout's user SGPRs (at least two), 512 bytes of LDS. - rsrc2: 1 << 15 | sgprs.max(2) << 1, - threads: [1, 1, 1], - }), - code, - }; - let p = ir::build(&native.code, wave64, 256).unwrap(); - let st = structure::structure(&p).unwrap(); - let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - let io = io::raise(&p, &native).unwrap(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - atomic_locks: false, - bias_as_gradients: false, - host_wave32: false, - narrow_waves: false, - view_marks: false, - }) - } - - /// Root parameter `slot` in user SGPRs from `user_data` on. - fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { - RootParam { - root, - table_offset_dwords: 0, - sgprs: if root == RootType::Descriptor { 2 } else { 1 }, - base_register: 0, - user_data, - slot, - } - } - - /// Lowers a one-thread compute program that copies four root constants - /// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a - /// descriptor table, so the vector instructions in `body` have an effect. - fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { - let mut words = vec![ - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 - 0xFA00_0000, - ]; - // v_mov_b32 v1..v4, s0..s3 - words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); - words.extend_from_slice(body); - words.extend_from_slice(&[ - 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 - 0x8002_0000, - S_ENDPGM, - ]); - let constants = RootParam { - sgprs: 4, - ..root(RootType::Constants, 0, 0) - }; - let buffer = UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 4, - slot: 1, - }; - lower_with( - &words, - vec![constants, root(RootType::Table, 4, 1)], - vec![buffer], - ) - .map(|_| ()) - } - - #[test] - fn the_24_bit_multiplies_lower_both_halves() { - // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low - // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). - for op in [0x09u32, 0x0A, 0x0B, 0x0C] { - let word = op << 25 | 2 << 9 | 0x101; - lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); - } - } - - #[test] - fn sums_of_absolute_differences_lower() { - // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, - // v_sad_u32 and v_msad_u8. - for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { - let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; - lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); - } - } - - #[test] - fn buffer_cache_invalidations_lower_as_no_ops() { - // MUBUF opcode 0x071/0x072 with no data operand: the title asks the - // host to invalidate its cached view of a buffer. - assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); - assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); - } - - #[test] - fn a_scalar_carry_chain_reaches_the_select() { - // The high dword of a 64-bit add or subtract, then a select on the - // carry (borrow) the high half leaves in SCC, and a branch on it - // (only code with an effect needs its operands). - let add = [ - 0xBE80_03C1, // s_mov_b32 s0, -1 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8000_8100, // s_add_u32 s0, s0, 1 - 0x8201_8001, // s_addc_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - let sub = [ - 0xBE80_0380, // s_mov_b32 s0, 0 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0x8080_8100, // s_sub_u32 s0, s0, 1 - 0x8281_8001, // s_subb_u32 s1, s1, 0 - 0x8502_0001, // s_cselect_b32 s2, s1, s0 - 0xBF07_8002, // s_cmp_lg_u32 s2, 0 - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE83_0380, // s_mov_b32 s3, 0 - S_ENDPGM, - ]; - - for words in [add, sub] { - lowers(&words, 0).unwrap(); - } - } - - #[test] - fn v_cndmask_accepts_uniform_and_constant_masks() { - // Uniform select (`s_cselect_b32`) and inline constant masks in `v_cndmask_b32` - // (resolved in `Structured::other` or directly as constants). - let words = [ - 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 - 0x8500_80C1, // s_cselect_b32 s0, -1, 0 - 0xD501_0001, - 0x0001_0080, // v_cndmask_b32 v1, 0, 1, s0 - 0xD501_0002, - 0x0201_02C1, // v_cndmask_b32 v2, 1, v1, -1 - 0xD834_0000, - 0x0000_0200, // ds_write_b32 v0, v2 - S_ENDPGM, - ]; - lowers(&words, 0x8001).unwrap(); - } - - fn perm_features(selector: u32) -> u64 { - // Synthetic compute shader: - // v0 is the thread ID and can supply a dynamic selector. - // Store the result in LDS to keep the permutation live. - let words = [ - 0x7E02_02FFu32, - 0x817F_34AB, - 0x7E04_02FF, - 0xFE01_56CD, - 0xD744_0003, - 257 | (258 << 9) | (selector << 18), - 0x3408_0082, - 0xD834_0000, - 0x0000_0304, - S_ENDPGM, - ]; - - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 256, - layout: vec![], - used: vec![], - io: StageIo::Cs(ComputeIo { - rsrc2: 1 << 15, - threads: [64, 1, 1], - }), - code, - }; - - let p = ir::build(&native.code, false, 256).unwrap(); - - assert!( - p.blocks - .iter() - .flat_map(|b| &b.insts) - .any(|i| i.name() == "v_perm_b32") - ); - - 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 emitted = lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - atomic_locks: false, - bias_as_gradients: false, - host_wave32: false, - narrow_waves: false, - view_marks: false, - }) - .unwrap(); - - let container = crate::Container::parse(&emitted.dxil).unwrap(); - - let features = container.part(crate::FourCC::SFI0).unwrap(); - - u64::from_le_bytes(features.data.try_into().unwrap()) - } - - #[test] - fn perm_constant_selector_needs_no_int64() { - assert_eq!(perm_features(128) & 0x8000, 0); - } - - #[test] - fn perm_dynamic_selector_needs_no_int64() { - assert_eq!( - perm_features(256) & 0x8000, - 0, - "dynamic v_perm_b32 must not require INT64" - ); - } - - #[test] - fn a_descriptor_selected_by_scc_picks_its_heap_index() { - // Two buffer descriptors loaded from the table at s0, one picked by - // a root constant (s1) with s_cselect_b64 per half, and loaded - // through by index and stored to LDS so the load is needed. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xF408_0302, - 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] - 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] - 0xE030_2000, - 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - // Both are structured buffers of dwords in the table's range. - let used = || { - vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }] - }; - lower_with(&words, layout(), used()).unwrap(); - } - - /// Tables of 2D textures at s0 and samplers at s1. - fn texture_tables() -> (Vec, Vec) { - let range = |kind, user_data, slot| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 0, - dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, - user_data, - slot, - }; - ( - vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], - vec![ - range(ResourceType::Srv, 0, 0), - range(ResourceType::Sampler, 1, 1), - ], - ) - } - - #[test] - fn a_descriptor_loaded_only_for_its_size_takes_the_kind_of_its_reload() { - // The record count of the buffer at s0 (count - 1 as an index), then - // the same descriptor loaded again for the indexed read. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0x810C_C10A, // s_add_i32 s12, s10, -1 - 0xF408_0402, - 0xFA00_0000, // s_load_dwordx4 s[16:19], s[4:5], null - 0x7E04_020C, // v_mov_b32 v2, s12 - 0xE030_2000, - 0x8004_0102, // buffer_load_dword v1, v2, s[16:19], 0 idxen - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_with(&words, layout, used).unwrap(); - } - - #[test] - fn a_waterfall_loop_that_only_sizes_takes_the_kind_of_the_sampled_one() { - // Each lane names table entry (lane & 1) by its byte offset in v7. - // A first waterfall loop only reads the width bits of the entry - // (`v_alignbit_b32`), a second one samples it; the width goes to the - // buffer at dword 16 of the table. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xBE86_0301, // s_mov_b32 s6, s1 - 0xBE87_0380, // s_mov_b32 s7, 0 - 0xF408_0203, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 - 0x7E06_0302, // v_mov_b32 v3, v2 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0x360E_0081, // v_and_b32 v7, 1, v0 - 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xBE97_037E, // s_mov_b32 s23, exec_lo - 0xBE95_037E, // s_mov_b32 s21, exec_lo - 0x7E28_0507, // L1: v_readfirstlane_b32 s20, v7 - 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 - 0xF40C_0302, - 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xD54E_0008, - 0x0278_1A0E, // v_alignbit_b32 v8, s14, s13, 30 - 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 - 0xBF89_FFF7, // s_cbranch_execnz L1 - 0xBEFE_0317, // s_mov_b32 exec_lo, s23 - 0xBE95_037E, // s_mov_b32 s21, exec_lo - 0x7E28_0507, // L2: v_readfirstlane_b32 s20, v7 - 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 - 0xF40C_0302, - 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:2D - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 - 0xBF89_FFF6, // s_cbranch_execnz L2 - 0xBEFE_0317, // s_mov_b32 exec_lo, s23 - 0xE070_1000, - 0x800A_0810, // buffer_store_dword v8, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (layout, used) = texture_and_uav_tables(); - lower_wave(&words, layout, used, false).unwrap(); - } - - #[test] - fn permlanex16_lowers_in_wave32_and_wave64() { - let words = [ - 0xD778_0001, - 0x0004_0100, // v_permlanex16_b32 v1, v0, s0, s1 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = vec![RootParam { - sgprs: 2, - ..root(RootType::Constants, 0, 0) - }]; - for wave64 in [false, true] { - let result = lower_wave(&words, layout.clone(), vec![], wave64).unwrap(); - assert!(result.wave_ops); - } - } - - #[test] - fn compute_spills_beside_a_descriptor_word_read_back() { - // Dword 0 of a buffer descriptor (no host value) and a root constant - // spilled to lanes 0 and 1 of v5 in a compute program; reading lane - // 1 back is the constant (the descriptor's lane is never read). - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0202, - 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null - 0xD761_0005, - 0x0001_0008, // v_writelane_b32 v5, s8, 0 - 0xD761_0005, - 0x0001_0201, // v_writelane_b32 v5, s1, 1 - 0xD760_000C, - 0x0001_0305, // v_readlane_b32 s12, v5, 1 - 0xE030_2000, - 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen - 0x7E06_020C, // v_mov_b32 v3, s12 - 0xD834_0000, - 0x0000_0300, // ds_write_b32 v0, v3 - 0xD834_0000, - 0x0000_0100, // ds_write_b32 v0, v1 - S_ENDPGM, - ]; - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let used = vec![UsedResource { - kind: ResourceType::Srv, - root: RootType::Table, - table_offset_dwords: 0, - lower_bound: 0, - stride: 4, - dwords: 4, - user_data: 0, - slot: 0, - }]; - lower_with(&words, layout, used).unwrap(); - } - - #[test] - fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { - use crate::resource::tests::{ - WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, - }; - for (words, wave64) in [ - (WATERFALL_FETCHED_WAVE32, false), - (WATERFALL_FETCHED_WAVE64, true), - (WATERFALL_PICKED_WAVE32, false), - ] { - let (layout, used) = texture_tables(); - let l = lower_wave(words, layout, used, wave64).unwrap(); - // The loop's reads of the first lane became each lane's own - // dwords: no wave operation is left. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. - pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { - let (layout, mut used) = texture_tables(); - used.push(UsedResource { - kind: ResourceType::Uav, - root: RootType::Table, - table_offset_dwords: 16, - lower_bound: 0, - stride: 0, - dwords: 4, - user_data: 0, - slot: 0, - }); - (layout, used) - } - - #[test] - fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { - use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; - for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { - let (layout, used) = texture_and_uav_tables(); - let l = lower_wave(words, layout, used, false).unwrap(); - // One image handle, from the join's per-lane heap index. - assert_eq!(l.nonuniform_handles, 1); - assert!(!l.wave_ops); - } - } - - #[test] - fn an_address_half_set_where_only_lanes_that_never_run_skip_is_known() { - // As `indirect_light_probes:CS_Alpha_Schedule` after its texture: a - // table address whose high half (s25 = 0) is set inside the region - // that only a skip no lane takes bypasses; the skip edge would bring - // the stale input s25. - let words = [ - 0xBE9A_037E, // s_mov_b32 s26, exec_lo - 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo - 0xBE98_0300, // s_mov_b32 s24, s0 - 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 - 0xBF88_0001, // s_cbranch_execz -> join - 0xBE99_0380, // s_mov_b32 s25, 0 - 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 - 0xF408_0A0C, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[24:25], 0x40 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0x7E06_0280, // v_mov_b32 v3, 0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xE070_1000, - 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (_, mut used) = texture_and_uav_tables(); - used.retain(|u| u.user_data == 0); - let layout = vec![root(RootType::Table, 0, 0)]; - lower_with(&words, layout, used).expect("the high half is 0 wherever a lane runs"); - } - - #[test] - fn a_descriptor_skipped_only_by_lanes_that_never_run_needs_no_source() { - // As `indirect_light_probes:CS_Alpha_Schedule`: the texture is - // loaded under the lanes that ran before `s_wqm`, skipped when there - // are none, and sampled with the helper lanes after the join. With - // every lane running from the start nothing takes the skip, so the - // registers it would bring (no descriptor) are never read. - let words = [ - 0xBE9A_037E, // s_mov_b32 s26, exec_lo - 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 - 0xBF88_0002, // s_cbranch_execz -> join - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 - 0xBE88_03FF, - 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) - 0xBE89_0380, // s_mov_b32 s9, 0 - 0xBE8A_0380, // s_mov_b32 s10, 0 - 0xBE8B_0380, // s_mov_b32 s11, 0 - 0x7E04_02F0, // v_mov_b32 v2, 0.5 - 0x7E06_02F0, // v_mov_b32 v3, 0.5 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D - 0xBF8C_3F70, // s_waitcnt vmcnt(0) - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (_, mut used) = texture_and_uav_tables(); - used.retain(|u| u.user_data == 0); - let layout = vec![root(RootType::Table, 0, 0)]; - let l = lower_with(&words, layout, used).unwrap(); - assert_eq!(l.nonuniform_handles, 0); - #[cfg(windows)] - if let Ok(mut v) = super::super::validator::Validator::load( - super::super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut l.dxil.clone()) - .expect("DXIL validation failed"); - } - } - - #[test] - fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { - // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at - // dword 16) and a root constant at s1: entry 0 if s1 is 0, else - // entry 1 if it is 1, else entry 0 again, the inner if/else joined - // before the outer one. The join's edges are a load and a join. - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0xBE88_03FF, - 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) - 0xBE89_0380, // s_mov_b32 s9, 0 - 0xBE8A_0380, // s_mov_b32 s10, 0 - 0xBE8B_0380, // s_mov_b32 s11, 0 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0xBF84_0003, // s_cbranch_scc0 -> 0x38 - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xBF82_0008, // s_branch -> 0x58 - 0xBF06_8101, // 0x38: s_cmp_eq_u32 s1, 1 - 0xBF84_0003, // s_cbranch_scc0 -> 0x4c - 0xF40C_0302, - 0xFA00_0020, // s_load_dwordx8 s[12:19], s[4:5], 0x20 - 0xBF82_0002, // s_branch -> 0x54 - 0xF40C_0302, - 0xFA00_0000, // 0x4c: s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xBE86_0301, // 0x54: s_mov_b32 s6, s1 - 0x7E04_02F0, // 0x58: v_mov_b32 v2, 0.5 - 0x7E06_02F0, // v_mov_b32 v3, 0.5 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (_, mut used) = texture_and_uav_tables(); - used.retain(|u| u.user_data == 0); - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let l = lower_with(&words, layout, used).unwrap(); - // One image handle from the joins' heap index, the same in all lanes. - assert_eq!(l.nonuniform_handles, 0); - #[cfg(windows)] - if let Ok(mut v) = super::super::validator::Validator::load( - super::super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut l.dxil.clone()) - .expect("DXIL validation failed"); - } - } - - #[test] - fn descriptors_reloaded_from_a_root_table_share_one_handle() { - // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at - // dword 16) and a root constant at s1. Entry 0 is loaded and sampled - // in a branch, then loaded again and sampled after it (the console - // compiler reloads a descriptor before each use rather than keep it). - let words = [ - 0xBE84_0300, // s_mov_b32 s4, s0 - 0xBE85_0380, // s_mov_b32 s5, 0 - 0xF408_0A02, - 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 - 0xBE88_03FF, - 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) - 0xBE89_0380, // s_mov_b32 s9, 0 - 0xBE8A_0380, // s_mov_b32 s10, 0 - 0xBE8B_0380, // s_mov_b32 s11, 0 - 0x7E04_02F0, // v_mov_b32 v2, 0.5 - 0x7E06_02F0, // v_mov_b32 v3, 0.5 - 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 - 0xBF06_8001, // s_cmp_eq_u32 s1, 0 - 0xBF84_0005, // s_cbranch_scc0 -> the reload - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D - 0xF40C_0302, - 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 (again) - 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) - 0xF09C_0F08, - 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] - 0xE070_1000, - 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen - S_ENDPGM, - ]; - let (_, mut used) = texture_and_uav_tables(); - used.retain(|u| u.user_data == 0); - let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; - let l = lower_with(&words, layout, used).unwrap(); - // One image handle made in the entry block for both loads, and the - // UAV's. - assert_eq!(l.heap_handles, 2); - #[cfg(windows)] - if let Ok(mut v) = super::super::validator::Validator::load( - super::super::validator::Validator::default_path().as_deref(), - ) { - v.validate(&mut l.dxil.clone()) - .expect("DXIL validation failed"); - } - } - - #[test] - fn scalar_bit_tests_lower() { - // Each tests one bit of a constant into SCC and branches on it (only - // code with an effect needs its operands). - let tail = [ - 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let bit_tests: [&[u32]; 4] = [ - &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 - &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 - ], - &[ - 0xBE80_0387, // s_mov_b32 s0, 7 - 0xBE81_0380, // s_mov_b32 s1, 0 - 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 - ], - ]; - for head in bit_tests { - let words: Vec = head.iter().chain(&tail).copied().collect(); - lowers(&words, 0).unwrap(); - } - } - - #[test] - fn a_missing_value_stays_missing_through_two_live_joins() { - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // skip the first overwrite - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) - 0xBF85_0001, // skip the second overwrite - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // use the result to branch - 0xBE83_0380, - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - // Compare to a direct read so future timestamp support works in both cases. - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[8..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead - lowers(&words, group_ids_xy).expect("dead timestamp"); - } - - #[test] - fn a_value_no_lane_from_its_edge_reads_needs_no_form() { - // s6 is a timestamp (no DXIL form) where the load is skipped and 5 - // where it runs; a flag in v1, set only with the load, guards the - // read after the join (the console compiler's form, where the - // skipped path leaves a stale lane mask in the register). - let mut words = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0x7E02_0280, // v_mov_b32 v1, 0 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0002, // s_cbranch_scc1 -> join - 0xBE86_0385, // s_mov_b32 s6, 5 - 0x7E02_02C1, // v_mov_b32 v1, -1 - 0x7D84_02C1, // join: v_cmp_eq_u32 vcc_lo, -1, v1 - 0xBF86_0003, // s_cbranch_vccz -> end - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // s_cbranch_scc1 -> end - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let group_ids_xy = 3 << 7; - lowers(&words, group_ids_xy).expect("the timestamp is never read"); - // With the flag set on both paths the timestamp is read: as refused - // (or accepted) as a direct read. - words[2] = 0x7E02_02C1; // v_mov_b32 v1, -1 - let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - let direct = [&words[..2], &words[9..]].concat(); - assert_eq!(refusal(&words), refusal(&direct)); - } - - #[test] - fn a_mask_joined_with_data_needs_a_uniform_join() { - // s6: lanes below 24, then shifted (data) on each back edge; read - // after the loop. Lanes leaving the loop at different iterations - // (per lane) see different numbers than the console's register: - // refused. The uniform loop is `synthetic_tests:: - // a_mask_joined_with_data_at_a_uniform_loop_is_its_number`. - let mut words = [ - 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 - 0x8706_7E6A, // s_and_b32 s6, vcc_lo, exec_lo - 0xBE87_0380, // s_mov_b32 s7, 0 - 0x9006_8406, // header: s_lshr_b32 s6, s6, 4 - 0x8007_8107, // s_add_u32 s7, s7, 1 - 0x7D88_0007, // v_cmp_gt_u32 vcc_lo, s7, v0 - 0x8A7E_6A7E, // s_andn2_b32 exec_lo, exec_lo, vcc_lo - 0xBF89_FFFB, // s_cbranch_execnz header - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, // s_cbranch_scc1 +1 - 0xBE84_0380, // s_mov_b32 s4, 0 - S_ENDPGM, - ]; - let Err(crate::ShaderError::Unsupported { what, .. }) = lowers(&words, 1 << 7) else { - panic!("a per-lane loop's mask join translated"); - }; - assert!(what.contains("lane mask"), "{what}"); - // Leaving on a uniform condition instead: the mask's number. - words[5] = 0xBF0A_8207; // s_cmp_lt_u32 s7, 2 - words[6] = 0xBF80_0000; // s_nop 0 - words[7] = 0xBF85_FFFB; // s_cbranch_scc1 header - lowers(&words, 1 << 7).expect("a uniform loop's mask join"); - } - - #[test] - fn a_scalar_result_needs_no_exec() { - // s6 is 0 where every lane skips and the saved EXEC where some run: - // no lane mask at the per-lane join. EXEC taken from it guards only - // a `v_readlane` (written whatever EXEC holds) before it is restored - // (`CS_IrradianceCache_Shade`). - let words = [ - 0xBE86_0380, // s_mov_b32 s6, 0 - 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 - 0xBE84_3C6A, // s_and_saveexec_b32 s4, vcc_lo - 0xBF88_0001, // s_cbranch_execz +1 - 0xBE86_0304, // s_mov_b32 s6, s4 - 0xBEFE_0306, // s_mov_b32 exec_lo, s6 - 0xD760_0002, // v_readlane_b32 s2, v0, 3 - 0x0001_0700, - 0xBEFE_0304, // s_mov_b32 exec_lo, s4 - S_ENDPGM, - ]; - lowers(&words, 1 << 7).expect("a lane read under an EXEC with no mask"); - } - - #[test] - fn a_missing_value_on_a_path_no_lane_takes_is_dead() { - let refusal = |code: &[u32]| match lowers(code, 1 << 7) { - Ok(()) => None, - Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), - Err(error) => panic!("{error}"), - }; - // The timestamp stays in s6 only where s0 == 0, and those lanes - // overwrite it before the second join: it never reaches the read. - let mut joins = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) - 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp - 0xBE86_0380, // s_mov_b32 s6, 0 - 0xBF84_0001, // s_cbranch_scc0: s0 != 0 keeps that 0 - 0xBE86_0381, // s_mov_b32 s6, 1 - 0xBF07_8006, // s_cmp_lg_u32 s6, 0 - 0xBF85_0001, - 0xBE83_0380, - S_ENDPGM, - ]; - assert_eq!(refusal(&joins), None); - // Tested on the other side, the timestamp reaches the read. - joins[5] = 0xBF85_0001; // s_cbranch_scc1 - assert!(refusal(&joins).is_some()); - // The same through a VGPR whose old value a guarded write keeps - // (lanes outside it get 0 for a value with no DXIL form, as for any - // such write): keeping does not make the join live. - let kept = [ - 0xF490_0180, - 0, // s_memtime s[6:7] - 0x7E02_0206, // v_mov_b32 v1, s6 - 0xBF06_8000, // s_cmp_eq_u32 s0, 0 - 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp - 0x7E02_0280, // v_mov_b32 v1, 0 - 0xBF84_0004, // s_cbranch_scc0: s0 != 0 keeps that 0 - 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 - 0x7E02_0282, // v_mov_b32 v1, 2 (the other lanes keep v1) - 0xBEFE_03C1, // s_mov_b32 exec_lo, -1 - 0x7E02_0283, // v_mov_b32 v1, 3 - 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 - 0xBF87_0001, // s_cbranch_vccnz - 0xBE83_0380, - S_ENDPGM, - ]; - assert_eq!(refusal(&kept), None); - } - - #[test] - fn buffer_formats_by_number() { - // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, - // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. - assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); - assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); - assert_eq!( - buffer_format(50), - Some((&[10, 10, 10, 2][..], Numeric::Unorm)) - ); - assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); - assert_eq!( - buffer_format(77), - Some((&[32, 32, 32, 32][..], Numeric::Float)) - ); - // Invalid, past the table. - assert_eq!(buffer_format(0), None); - assert_eq!(buffer_format(78), None); - } - - #[test] - fn packed_buffer_formats_by_number() { - // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, - // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT - // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. - assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); - assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); - assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); - assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); - assert_eq!( - buffer_format(44), - Some((&[2, 10, 10, 10][..], Numeric::Unorm)) - ); - assert_eq!( - buffer_format(45), - Some((&[2, 10, 10, 10][..], Numeric::Snorm)) - ); - assert_eq!( - buffer_format(46), - Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) - ); - assert_eq!( - buffer_format(47), - Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) - ); - assert_eq!( - buffer_format(48), - Some((&[2, 10, 10, 10][..], Numeric::Uint)) - ); - assert_eq!( - buffer_format(49), - Some((&[2, 10, 10, 10][..], Numeric::Sint)) - ); - } - - /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as - /// `legacyF16ToF32` widens it. - fn half(h: u32) -> f32 { - let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); - let v = match e { - 0 => m as f32 * 2f32.powi(-24), - 31 if m == 0 => f32::INFINITY, - 31 => f32::NAN, - _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), - }; - if s == 1 { -v } else { v } - } - - #[test] - fn small_floats_widen_as_halves() { - // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a - // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. - let f11 = |x: u32| half(x << half_shift(11)); - let f10 = |x: u32| half(x << half_shift(10)); - assert_eq!(f11(0), 0.0); - assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal - assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal - assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal - assert_eq!(f11(0x3C0), 1.0); - assert_eq!(f11(0x3E0), 1.5); - assert_eq!(f11(0x7BF), 65024.0); // largest - assert_eq!(f11(0x7C0), f32::INFINITY); - assert!(f11(0x7C1).is_nan()); - assert_eq!(f10(0x001), 2f32.powi(-19)); - assert_eq!(f10(0x020), 2f32.powi(-14)); - assert_eq!(f10(0x1E0), 1.0); - assert_eq!(f10(0x3DF), 64512.0); - assert_eq!(f10(0x3E0), f32::INFINITY); - assert!(f10(0x3FF).is_nan()); - // A 16-bit float is a half already, sign included. - assert_eq!(half(0xBC00 << half_shift(16)), -1.0); - } - - #[test] - fn packed_halves_fill_parameters_first_fit() { - // 16-bit rows as a title's signature has them: row 0 holds two - // elements (x y and z w), row 3 is 32-bit, row 4 has one channel at w. - let el = |row: u32, col: u8, cols: u8, half: bool| super::SigElement { - name: "TEXCOORD".into(), - index: row, - kind: 0, - comp: 9, - interp: 0, - row: Some(row), - col, - cols, - usage: 0, - half, - }; - let sig = [ - el(0, 0, 2, true), - el(0, 2, 2, true), - el(1, 0, 4, true), - el(2, 0, 3, true), - el(3, 0, 4, false), - el(4, 0, 3, true), - el(4, 3, 1, true), - el(5, 0, 3, true), - ]; - // Each half as row and channel ("-": padding or past the end). - let param = |a| { - (0..8) - .map(|h| match packed_half(&sig, a, h) { - Some((r, c)) => format!("{r}{}", ["x", "y", "z", "w"][usize::from(c)]), - None => "-".into(), - }) - .collect::>() - .join(" ") - }; - // By first channel, then row: row 0's x y, all of row 1, then (last, - // as it starts at z) row 0's z w. - assert_eq!(param(0), "0x 0y 1x 1y 1z 1w 0z 0w"); - // Three channels take two dwords; row 4's w fills the first - // parameter with room, after row 5. - assert_eq!(param(2), "2x 2y 2z - 4x 4y 4z -"); - assert_eq!(param(5), "5x 5y 5z - 4w - - -"); - // No parameter starts in rows 1, 3 or 4. - for a in [1, 3, 4] { - assert_eq!(param(a), "- - - - - - - -"); - } - } - - // ---- one console wave split across host waves ---- - - const V_LSHLREV_V1_2_V0: u32 = 0x3402_0082; // v_lshlrev_b32 v1, 2, v0 - const DS_WRITE_V1_V0: [u32; 2] = [0xD834_0000, 0x0000_0001]; // ds_write_b32 v1, v0 - const DS_READ_V2_V1_4: [u32; 2] = [0xD8D8_0004, 0x0200_0001]; // ds_read_b32 v2, v1 offset:4 - const SAVE_EXEC: u32 = 0xBE80_047E; // s_mov_b64 s[0:1], exec - const CMPX_V0_EQ_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec, 0, v0 - const RESTORE_EXEC: u32 = 0xBEFE_0400; // s_mov_b64 exec, s[0:1] - - /// `s_cbranch_execz` over the next `words` words. - const fn skip(words: u32) -> u32 { - 0xBF88_0000 | words - } - - fn wave64(words: &[u32]) -> ir::Program { - let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); - ir::build(&code, true, 256).unwrap() - } - - /// Lowers a wave64 compute program of `lanes` threads with 512 bytes of - /// LDS: the barriers it got for narrow host waves. - fn split_barriers(words: &[u32], lanes: u32, narrow_waves: bool) -> usize { - lowered(words, lanes, narrow_waves).split_barriers - } - - /// The same program, lowered. - fn lowered(words: &[u32], lanes: u32, narrow_waves: bool) -> super::Lowered { - 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: 1 << 15 | 2 << 1, - threads: [lanes, 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(); - lower(&Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: vec![], - outputs: vec![], - prims: vec![], - mesh_stride: 0, - atomic_locks: false, - bias_as_gradients: false, - narrow_waves, - host_wave32: false, - view_marks: false, - }) - .expect("lower") - } - - #[test] - fn a_read_after_another_lanes_write_syncs_in_a_split_wave() { - let mut w = vec![V_LSHLREV_V1_2_V0]; - w.extend(DS_WRITE_V1_V0); - w.extend(DS_READ_V2_V1_4); - w.push(S_ENDPGM); - let at = super::split_wave_barriers(&wave64(&w)).unwrap(); - assert_eq!(at.into_iter().collect::>(), [(0, 2)]); - assert_eq!(split_barriers(&w, 64, true), 1); - // Option off, or a group one host wave holds: as before. - assert_eq!(split_barriers(&w, 64, false), 0); - assert_eq!(split_barriers(&w, 32, true), 0); - // Synced, it no longer asks for 64-lane waves a 32-lane host lacks - // (D3DMetal runs nothing then); without the option it still does. - assert_eq!(lowered(&w, 64, true).wave_size, None); - assert_eq!(lowered(&w, 64, false).wave_size, Some(64)); - assert_eq!(lowered(&w, 32, true).wave_size, None); - } - - #[test] - fn a_divergent_write_syncs_at_the_join_before_the_read() { - // 34d88edf583f3778's shape: lanes with v0 = 0 write, all read. - let mut w = vec![V_LSHLREV_V1_2_V0, SAVE_EXEC, CMPX_V0_EQ_0, skip(2)]; - w.extend(DS_WRITE_V1_V0); - w.push(RESTORE_EXEC); - w.extend(DS_READ_V2_V1_4); - w.push(S_ENDPGM); - let p = wave64(&w); - let at: Vec<_> = super::split_wave_barriers(&p).unwrap().into_iter().collect(); - assert_eq!(at.len(), 1); - let (b, i) = at[0]; - assert!(p.blocks[b].insts[i].name().starts_with("ds_read")); - assert_eq!(p.blocks[b].preds.len(), 2, "the join"); - assert_eq!(split_barriers(&w, 64, true), 1); - } - - #[test] - fn a_write_before_divergent_reads_syncs_where_all_lanes_run() { - let mut w = vec![V_LSHLREV_V1_2_V0]; - w.extend(DS_WRITE_V1_V0); - w.extend([SAVE_EXEC, CMPX_V0_EQ_0, skip(2)]); - w.extend(DS_READ_V2_V1_4); - w.push(RESTORE_EXEC); - w.push(S_ENDPGM); - let p = wave64(&w); - let at: Vec<_> = super::split_wave_barriers(&p).unwrap().into_iter().collect(); - assert_eq!(at, [(0, p.blocks[0].insts.len())], "the end of the entry"); - assert_eq!(split_barriers(&w, 64, true), 1); - } - - #[test] - fn no_barrier_in_divergent_code() { - // Write and read both under the branch: no barrier can go there. - let mut w = vec![V_LSHLREV_V1_2_V0, SAVE_EXEC, CMPX_V0_EQ_0, skip(4)]; - w.extend(DS_WRITE_V1_V0); - w.extend(DS_READ_V2_V1_4); - w.push(RESTORE_EXEC); - w.push(S_ENDPGM); - assert!(super::split_wave_barriers(&wave64(&w)).is_none()); - assert_eq!(split_barriers(&w, 64, true), 0); - } -} +mod tests; diff --git a/crates/victory-shader/src/emit/lower/tests.rs b/crates/victory-shader/src/emit/lower/tests.rs new file mode 100644 index 00000000..835a0368 --- /dev/null +++ b/crates/victory-shader/src/emit/lower/tests.rs @@ -0,0 +1,1283 @@ +use super::{ + Lowered, Numeric, Parts, barycentric_signature, buffer_format, half_shift, lower, + packed_half, +}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +#[test] +fn direct_barycentric_modes_match_dxil_semantics() { + use crate::io::Barycentric::*; + + assert_eq!(barycentric_signature(PerspectiveSample), Some((0, 6))); + assert_eq!(barycentric_signature(PerspectiveCenter), Some((0, 2))); + assert_eq!(barycentric_signature(PerspectiveCentroid), Some((0, 3))); + assert_eq!(barycentric_signature(LinearSample), Some((1, 7))); + assert_eq!(barycentric_signature(LinearCenter), Some((1, 4))); + assert_eq!(barycentric_signature(LinearCentroid), Some((1, 5))); + assert_eq!(barycentric_signature(PerspectivePullModel), None); +} + +/// Whether a synthetic compute program translates with these input registers. +fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 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(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + atomic_locks: false, + bias_as_gradients: false, + host_wave32: false, + narrow_waves: false, + view_marks: false, + }) + .map(|_| ()) +} + +/// Lowers a compute program with the root parameters `layout` (in user +/// SGPRs from s0 on) and the used resources `used`. +fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, +) -> Result { + lower_wave(words, layout, used, false) +} + +/// [`lower_with`] in wave64 if `wave64`. +fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, +) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + atomic_locks: false, + bias_as_gradients: false, + host_wave32: false, + narrow_waves: false, + view_marks: false, + }) +} + +/// Root parameter `slot` in user SGPRs from `user_data` on. +fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } +} + +/// Lowers a one-thread compute program that copies four root constants +/// (s0..s3) into v1..v4, runs `body`, and stores v0 to a raw buffer from a +/// descriptor table, so the vector instructions in `body` have an effect. +fn lowers_valu(body: &[u32]) -> Result<(), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0xFA00_0000, + ]; + // v_mov_b32 v1..v4, s0..s3 + words.extend((0..4u32).map(|i| 0x7E00_0200 | (i + 1) << 17 | i)); + words.extend_from_slice(body); + words.extend_from_slice(&[ + 0xE070_0000, // buffer_store_dword v0, off, s[8:11], 0 + 0x8002_0000, + S_ENDPGM, + ]); + let constants = RootParam { + sgprs: 4, + ..root(RootType::Constants, 0, 0) + }; + let buffer = UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }; + lower_with( + &words, + vec![constants, root(RootType::Table, 4, 1)], + vec![buffer], + ) + .map(|_| ()) +} + +#[test] +fn the_24_bit_multiplies_lower_both_halves() { + // VOP2 `op v0, v1, v2`: v_mul_i32_i24 and v_mul_u32_u24 (the low + // dword) and v_mul_hi_i32_i24 and v_mul_hi_u32_u24 (the high one). + for op in [0x09u32, 0x0A, 0x0B, 0x0C] { + let word = op << 25 | 2 << 9 | 0x101; + lowers_valu(&[word]).unwrap_or_else(|e| panic!("VOP2 {op:#x}: {e}")); + } +} + +#[test] +fn sums_of_absolute_differences_lower() { + // VOP3 `op v0, v1, v2, v3`: v_sad_u8, v_sad_hi_u8, v_sad_u16, + // v_sad_u32 and v_msad_u8. + for op in [0x15Au32, 0x15B, 0x15C, 0x15D, 0x171] { + let words = [0xD400_0000 | op << 16, 0x101 | 0x102 << 9 | 0x103 << 18]; + lowers_valu(&words).unwrap_or_else(|e| panic!("VOP3 {op:#x}: {e}")); + } +} + +#[test] +fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); + assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); +} + +/// A full typed store to element `s0` through the table at `s1`, with +/// `soffset` in the MUBUF instruction's scalar-source field. +fn typed_store_words(soffset: u8) -> Vec { + let mut words = vec![ + 0xBE84_0301, // s_mov_b32 s4, s1 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0 + 0x7E00_0200, // v_mov_b32 v0, s0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + ]; + words.extend((1..=4).map(|v| 0x7E00_0000 | (v as u32) << 17 | 0x01 << 9 | 0x80)); + words.extend([ + 0xE01C_2000, + 0x8002_0100 | (soffset as u32) << 24, // buffer_store_format_xyzw v[1:4], v0, s[8:11], 0 idxen + S_ENDPGM, + ]); + words +} + +#[test] +fn typed_stores_refuse_register_and_immediate_soffsets() { + let layout = || vec![root(RootType::Constants, 0, 0), root(RootType::Table, 1, 1)]; + // RGBA32 and RGB32 use the same full-store MUBUF form. The mark width + // comes from the host's stride table; the used-resource stride here + // keeps both descriptor layouts in the regression matrix. + for (format, stride) in [("RGBA32", 16), ("RGB32", 12)] { + let used = || { + vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride, + dwords: 4, + user_data: 1, + slot: 1, + }] + }; + // A register and an inline constant both make an instruction-valued + // offset. Neither may be silently dropped until offsets can fold into + // the typed element index. Inline zero is the accepted no-offset form. + for (source, soffset) in [("register", 6), ("immediate", 132)] { + let Err(crate::ShaderError::Unsupported { what, .. }) = + lower_with(&typed_store_words(soffset), layout(), used()) + else { + panic!("translated a {format} typed store with a {source} soffset"); + }; + assert_eq!( + what, "a typed buffer store at an offset", + "{format} {source} soffset" + ); + } + lower_with(&typed_store_words(128), layout(), used()) + .unwrap_or_else(|e| panic!("{format} inline zero soffset: {e}")); + } +} + +#[test] +fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } +} + +#[test] +fn v_cndmask_accepts_uniform_and_constant_masks() { + // Uniform select (`s_cselect_b32`) and inline constant masks in `v_cndmask_b32` + // (resolved in `Structured::other` or directly as constants). + let words = [ + 0xBF06_8000u32, // s_cmp_eq_u32 s0, 0 + 0x8500_80C1, // s_cselect_b32 s0, -1, 0 + 0xD501_0001, + 0x0001_0080, // v_cndmask_b32 v1, 0, 1, s0 + 0xD501_0002, + 0x0201_02C1, // v_cndmask_b32 v2, 1, v1, -1 + 0xD834_0000, + 0x0000_0200, // ds_write_b32 v0, v2 + S_ENDPGM, + ]; + lowers(&words, 0x8001).unwrap(); +} + +fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32") + ); + + 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 emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + atomic_locks: false, + bias_as_gradients: false, + host_wave32: false, + narrow_waves: false, + view_marks: false, + }) + .unwrap(); + + let container = crate::Container::parse(&emitted.dxil).unwrap(); + + let features = container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) +} + +#[test] +fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); +} + +#[test] +fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); +} + +#[test] +fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); +} + +/// Tables of 2D textures at s0 and samplers at s1. +fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) +} + +#[test] +fn a_descriptor_loaded_only_for_its_size_takes_the_kind_of_its_reload() { + // The record count of the buffer at s0 (count - 1 as an index), then + // the same descriptor loaded again for the indexed read. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0x810C_C10A, // s_add_i32 s12, s10, -1 + 0xF408_0402, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[4:5], null + 0x7E04_020C, // v_mov_b32 v2, s12 + 0xE030_2000, + 0x8004_0102, // buffer_load_dword v1, v2, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_with(&words, layout, used).unwrap(); +} + +#[test] +fn a_waterfall_loop_that_only_sizes_takes_the_kind_of_the_sampled_one() { + // Each lane names table entry (lane & 1) by its byte offset in v7. + // A first waterfall loop only reads the width bits of the entry + // (`v_alignbit_b32`), a second one samples it; the width goes to the + // buffer at dword 16 of the table. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // L1: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xD54E_0008, + 0x0278_1A0E, // v_alignbit_b32 v8, s14, s13, 30 + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF7, // s_cbranch_execnz L1 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // L2: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF6, // s_cbranch_execnz L2 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0810, // buffer_store_dword v8, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (layout, used) = texture_and_uav_tables(); + lower_wave(&words, layout, used, false).unwrap(); +} + +#[test] +fn permlanex16_lowers_in_wave32_and_wave64() { + let words = [ + 0xD778_0001, + 0x0004_0100, // v_permlanex16_b32 v1, v0, s0, s1 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = vec![RootParam { + sgprs: 2, + ..root(RootType::Constants, 0, 0) + }]; + for wave64 in [false, true] { + let result = lower_wave(&words, layout.clone(), vec![], wave64).unwrap(); + assert!(result.wave_ops); + } +} + +#[test] +fn compute_spills_beside_a_descriptor_word_read_back() { + // Dword 0 of a buffer descriptor (no host value) and a root constant + // spilled to lanes 0 and 1 of v5 in a compute program; reading lane + // 1 back is the constant (the descriptor's lane is never read). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xD761_0005, + 0x0001_0008, // v_writelane_b32 v5, s8, 0 + 0xD761_0005, + 0x0001_0201, // v_writelane_b32 v5, s1, 1 + 0xD760_000C, + 0x0001_0305, // v_readlane_b32 s12, v5, 1 + 0xE030_2000, + 0x8002_0100, // buffer_load_dword v1, v0, s[8:11], 0 idxen + 0x7E06_020C, // v_mov_b32 v3, s12 + 0xD834_0000, + 0x0000_0300, // ds_write_b32 v0, v3 + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let used = vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }]; + lower_with(&words, layout, used).unwrap(); +} + +#[test] +fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +/// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. +pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) +} + +#[test] +fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } +} + +#[test] +fn an_address_half_set_where_only_lanes_that_never_run_skip_is_known() { + // As `indirect_light_probes:CS_Alpha_Schedule` after its texture: a + // table address whose high half (s25 = 0) is set inside the region + // that only a skip no lane takes bypasses; the skip edge would bring + // the stale input s25. + let words = [ + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo + 0xBE98_0300, // s_mov_b32 s24, s0 + 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 + 0xBF88_0001, // s_cbranch_execz -> join + 0xBE99_0380, // s_mov_b32 s25, 0 + 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 + 0xF408_0A0C, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[24:25], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE070_1000, + 0x800A_0310, // buffer_store_dword v3, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0)]; + lower_with(&words, layout, used).expect("the high half is 0 wherever a lane runs"); +} + +#[test] +fn a_descriptor_skipped_only_by_lanes_that_never_run_needs_no_source() { + // As `indirect_light_probes:CS_Alpha_Schedule`: the texture is + // loaded under the lanes that ran before `s_wqm`, skipped when there + // are none, and sampled with the helper lanes after the join. With + // every lane running from the start nothing takes the skip, so the + // registers it would bring (no descriptor) are never read. + let words = [ + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + 0xBEFE_097E, // s_wqm_b32 exec_lo, exec_lo + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE86_3C1A, // s_and_saveexec_b32 s6, s26 + 0xBF88_0002, // s_cbranch_execz -> join + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBEFE_0306, // join: s_mov_b32 exec_lo, s6 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E04_02F0, // v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0)]; + let l = lower_with(&words, layout, used).unwrap(); + assert_eq!(l.nonuniform_handles, 0); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } +} + +#[test] +fn descriptors_joined_by_nested_control_flow_lower_to_one_uniform_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1: entry 0 if s1 is 0, else + // entry 1 if it is 1, else entry 0 again, the inner if/else joined + // before the outer one. The join's edges are a load and a join. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0003, // s_cbranch_scc0 -> 0x38 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF82_0008, // s_branch -> 0x58 + 0xBF06_8101, // 0x38: s_cmp_eq_u32 s1, 1 + 0xBF84_0003, // s_cbranch_scc0 -> 0x4c + 0xF40C_0302, + 0xFA00_0020, // s_load_dwordx8 s[12:19], s[4:5], 0x20 + 0xBF82_0002, // s_branch -> 0x54 + 0xF40C_0302, + 0xFA00_0000, // 0x4c: s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBE86_0301, // 0x54: s_mov_b32 s6, s1 + 0x7E04_02F0, // 0x58: v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle from the joins' heap index, the same in all lanes. + assert_eq!(l.nonuniform_handles, 0); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } +} + +#[test] +fn descriptors_reloaded_from_a_root_table_share_one_handle() { + // The view table at s0 (2D textures at entries 0 and 1, a raw UAV at + // dword 16) and a root constant at s1. Entry 0 is loaded and sampled + // in a branch, then loaded again and sampled after it (the console + // compiler reloads a descriptor before each use rather than keep it). + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0xBE88_03FF, + 0x0000_0092, // s_mov_b32 s8, 0x92 (an immediate sampler) + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0x7E04_02F0, // v_mov_b32 v2, 0.5 + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF84_0005, // s_cbranch_scc0 -> the reload + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 (again) + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + S_ENDPGM, + ]; + let (_, mut used) = texture_and_uav_tables(); + used.retain(|u| u.user_data == 0); + let layout = vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + let l = lower_with(&words, layout, used).unwrap(); + // One image handle made in the entry block for both loads, and the + // UAV's. + assert_eq!(l.heap_handles, 2); + #[cfg(windows)] + if let Ok(mut v) = super::super::validator::Validator::load( + super::super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut l.dxil.clone()) + .expect("DXIL validation failed"); + } +} + +#[test] +fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } +} + +#[test] +fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); +} + +#[test] +fn a_value_no_lane_from_its_edge_reads_needs_no_form() { + // s6 is a timestamp (no DXIL form) where the load is skipped and 5 + // where it runs; a flag in v1, set only with the load, guards the + // read after the join (the console compiler's form, where the + // skipped path leaves a stale lane mask in the register). + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0002, // s_cbranch_scc1 -> join + 0xBE86_0385, // s_mov_b32 s6, 5 + 0x7E02_02C1, // v_mov_b32 v1, -1 + 0x7D84_02C1, // join: v_cmp_eq_u32 vcc_lo, -1, v1 + 0xBF86_0003, // s_cbranch_vccz -> end + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // s_cbranch_scc1 -> end + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + lowers(&words, group_ids_xy).expect("the timestamp is never read"); + // With the flag set on both paths the timestamp is read: as refused + // (or accepted) as a direct read. + words[2] = 0x7E02_02C1; // v_mov_b32 v1, -1 + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[9..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); +} + +#[test] +fn a_mask_joined_with_data_needs_a_uniform_join() { + // s6: lanes below 24, then shifted (data) on each back edge; read + // after the loop. Lanes leaving the loop at different iterations + // (per lane) see different numbers than the console's register: + // refused. The uniform loop is `synthetic_tests:: + // a_mask_joined_with_data_at_a_uniform_loop_is_its_number`. + let mut words = [ + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x8706_7E6A, // s_and_b32 s6, vcc_lo, exec_lo + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x9006_8406, // header: s_lshr_b32 s6, s6, 4 + 0x8007_8107, // s_add_u32 s7, s7, 1 + 0x7D88_0007, // v_cmp_gt_u32 vcc_lo, s7, v0 + 0x8A7E_6A7E, // s_andn2_b32 exec_lo, exec_lo, vcc_lo + 0xBF89_FFFB, // s_cbranch_execnz header + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // s_cbranch_scc1 +1 + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let Err(crate::ShaderError::Unsupported { what, .. }) = lowers(&words, 1 << 7) else { + panic!("a per-lane loop's mask join translated"); + }; + assert!(what.contains("lane mask"), "{what}"); + // Leaving on a uniform condition instead: the mask's number. + words[5] = 0xBF0A_8207; // s_cmp_lt_u32 s7, 2 + words[6] = 0xBF80_0000; // s_nop 0 + words[7] = 0xBF85_FFFB; // s_cbranch_scc1 header + lowers(&words, 1 << 7).expect("a uniform loop's mask join"); +} + +#[test] +fn a_scalar_result_needs_no_exec() { + // s6 is 0 where every lane skips and the saved EXEC where some run: + // no lane mask at the per-lane join. EXEC taken from it guards only + // a `v_readlane` (written whatever EXEC holds) before it is restored + // (`CS_IrradianceCache_Shade`). + let words = [ + 0xBE86_0380, // s_mov_b32 s6, 0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBE84_3C6A, // s_and_saveexec_b32 s4, vcc_lo + 0xBF88_0001, // s_cbranch_execz +1 + 0xBE86_0304, // s_mov_b32 s6, s4 + 0xBEFE_0306, // s_mov_b32 exec_lo, s6 + 0xD760_0002, // v_readlane_b32 s2, v0, 3 + 0x0001_0700, + 0xBEFE_0304, // s_mov_b32 exec_lo, s4 + S_ENDPGM, + ]; + lowers(&words, 1 << 7).expect("a lane read under an EXEC with no mask"); +} + +#[test] +fn a_missing_value_on_a_path_no_lane_takes_is_dead() { + let refusal = |code: &[u32]| match lowers(code, 1 << 7) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + // The timestamp stays in s6 only where s0 == 0, and those lanes + // overwrite it before the second join: it never reaches the read. + let mut joins = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF84_0001, // s_cbranch_scc0: s0 != 0 keeps that 0 + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, + 0xBE83_0380, + S_ENDPGM, + ]; + assert_eq!(refusal(&joins), None); + // Tested on the other side, the timestamp reaches the read. + joins[5] = 0xBF85_0001; // s_cbranch_scc1 + assert!(refusal(&joins).is_some()); + // The same through a VGPR whose old value a guarded write keeps + // (lanes outside it get 0 for a value with no DXIL form, as for any + // such write): keeping does not make the join live. + let kept = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0x7E02_0206, // v_mov_b32 v1, s6 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0001, // s_cbranch_scc1: s0 == 0 keeps the timestamp + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xBF84_0004, // s_cbranch_scc0: s0 != 0 keeps that 0 + 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02_0282, // v_mov_b32 v1, 2 (the other lanes keep v1) + 0xBEFE_03C1, // s_mov_b32 exec_lo, -1 + 0x7E02_0283, // v_mov_b32 v1, 3 + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBF87_0001, // s_cbranch_vccnz + 0xBE83_0380, + S_ENDPGM, + ]; + assert_eq!(refusal(&kept), None); +} + +#[test] +fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); +} + +#[test] +fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); +} + +/// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as +/// `legacyF16ToF32` widens it. +fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } +} + +#[test] +fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); +} + +#[test] +fn packed_halves_fill_parameters_first_fit() { + // 16-bit rows as a title's signature has them: row 0 holds two + // elements (x y and z w), row 3 is 32-bit, row 4 has one channel at w. + let el = |row: u32, col: u8, cols: u8, half: bool| super::SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 0, + row: Some(row), + col, + cols, + usage: 0, + half, + }; + let sig = [ + el(0, 0, 2, true), + el(0, 2, 2, true), + el(1, 0, 4, true), + el(2, 0, 3, true), + el(3, 0, 4, false), + el(4, 0, 3, true), + el(4, 3, 1, true), + el(5, 0, 3, true), + ]; + // Each half as row and channel ("-": padding or past the end). + let param = |a| { + (0..8) + .map(|h| match packed_half(&sig, a, h) { + Some((r, c)) => format!("{r}{}", ["x", "y", "z", "w"][usize::from(c)]), + None => "-".into(), + }) + .collect::>() + .join(" ") + }; + // By first channel, then row: row 0's x y, all of row 1, then (last, + // as it starts at z) row 0's z w. + assert_eq!(param(0), "0x 0y 1x 1y 1z 1w 0z 0w"); + // Three channels take two dwords; row 4's w fills the first + // parameter with room, after row 5. + assert_eq!(param(2), "2x 2y 2z - 4x 4y 4z -"); + assert_eq!(param(5), "5x 5y 5z - 4w - - -"); + // No parameter starts in rows 1, 3 or 4. + for a in [1, 3, 4] { + assert_eq!(param(a), "- - - - - - - -"); + } +} + +// ---- one console wave split across host waves ---- + +const V_LSHLREV_V1_2_V0: u32 = 0x3402_0082; // v_lshlrev_b32 v1, 2, v0 +const DS_WRITE_V1_V0: [u32; 2] = [0xD834_0000, 0x0000_0001]; // ds_write_b32 v1, v0 +const DS_READ_V2_V1_4: [u32; 2] = [0xD8D8_0004, 0x0200_0001]; // ds_read_b32 v2, v1 offset:4 +const SAVE_EXEC: u32 = 0xBE80_047E; // s_mov_b64 s[0:1], exec +const CMPX_V0_EQ_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec, 0, v0 +const RESTORE_EXEC: u32 = 0xBEFE_0400; // s_mov_b64 exec, s[0:1] + +/// `s_cbranch_execz` over the next `words` words. +const fn skip(words: u32) -> u32 { + 0xBF88_0000 | words +} + +fn wave64(words: &[u32]) -> ir::Program { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ir::build(&code, true, 256).unwrap() +} + +/// Lowers a wave64 compute program of `lanes` threads with 512 bytes of +/// LDS: the barriers it got for narrow host waves. +fn split_barriers(words: &[u32], lanes: u32, narrow_waves: bool) -> usize { + lowered(words, lanes, narrow_waves).split_barriers +} + +/// The same program, lowered. +fn lowered(words: &[u32], lanes: u32, narrow_waves: bool) -> super::Lowered { + 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: 1 << 15 | 2 << 1, + threads: [lanes, 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(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + atomic_locks: false, + bias_as_gradients: false, + narrow_waves, + host_wave32: false, + view_marks: false, + }) + .expect("lower") +} + +#[test] +fn a_read_after_another_lanes_write_syncs_in_a_split_wave() { + let mut w = vec![V_LSHLREV_V1_2_V0]; + w.extend(DS_WRITE_V1_V0); + w.extend(DS_READ_V2_V1_4); + w.push(S_ENDPGM); + let at = super::split_wave_barriers(&wave64(&w)).unwrap(); + assert_eq!(at.into_iter().collect::>(), [(0, 2)]); + assert_eq!(split_barriers(&w, 64, true), 1); + // Option off, or a group one host wave holds: as before. + assert_eq!(split_barriers(&w, 64, false), 0); + assert_eq!(split_barriers(&w, 32, true), 0); + // Synced, it no longer asks for 64-lane waves a 32-lane host lacks + // (D3DMetal runs nothing then); without the option it still does. + assert_eq!(lowered(&w, 64, true).wave_size, None); + assert_eq!(lowered(&w, 64, false).wave_size, Some(64)); + assert_eq!(lowered(&w, 32, true).wave_size, None); +} + +#[test] +fn a_divergent_write_syncs_at_the_join_before_the_read() { + // 34d88edf583f3778's shape: lanes with v0 = 0 write, all read. + let mut w = vec![V_LSHLREV_V1_2_V0, SAVE_EXEC, CMPX_V0_EQ_0, skip(2)]; + w.extend(DS_WRITE_V1_V0); + w.push(RESTORE_EXEC); + w.extend(DS_READ_V2_V1_4); + w.push(S_ENDPGM); + let p = wave64(&w); + let at: Vec<_> = super::split_wave_barriers(&p).unwrap().into_iter().collect(); + assert_eq!(at.len(), 1); + let (b, i) = at[0]; + assert!(p.blocks[b].insts[i].name().starts_with("ds_read")); + assert_eq!(p.blocks[b].preds.len(), 2, "the join"); + assert_eq!(split_barriers(&w, 64, true), 1); +} + +#[test] +fn a_write_before_divergent_reads_syncs_where_all_lanes_run() { + let mut w = vec![V_LSHLREV_V1_2_V0]; + w.extend(DS_WRITE_V1_V0); + w.extend([SAVE_EXEC, CMPX_V0_EQ_0, skip(2)]); + w.extend(DS_READ_V2_V1_4); + w.push(RESTORE_EXEC); + w.push(S_ENDPGM); + let p = wave64(&w); + let at: Vec<_> = super::split_wave_barriers(&p).unwrap().into_iter().collect(); + assert_eq!(at, [(0, p.blocks[0].insts.len())], "the end of the entry"); + assert_eq!(split_barriers(&w, 64, true), 1); +} + +#[test] +fn no_barrier_in_divergent_code() { + // Write and read both under the branch: no barrier can go there. + let mut w = vec![V_LSHLREV_V1_2_V0, SAVE_EXEC, CMPX_V0_EQ_0, skip(4)]; + w.extend(DS_WRITE_V1_V0); + w.extend(DS_READ_V2_V1_4); + w.push(RESTORE_EXEC); + w.push(S_ENDPGM); + assert!(super::split_wave_barriers(&wave64(&w)).is_none()); + assert_eq!(split_barriers(&w, 64, true), 0); +} diff --git a/crates/victory-shader/src/emit/memory_tests.rs b/crates/victory-shader/src/emit/memory_tests.rs index 11a03adc..71a5d50b 100644 --- a/crates/victory-shader/src/emit/memory_tests.rs +++ b/crates/victory-shader/src/emit/memory_tests.rs @@ -10,8 +10,13 @@ //! pointers into memory no copy holds (zeros, marked missed) and stores and //! loads through a root UAV (title memory in such a program). +use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32B32A32_FLOAT, +}; + use super::host::{Dispatch, Host, Root, View}; -use super::{HostShader, lower, validator}; +use super::{HostShader, VIEW_STRIDES, lower, validator}; use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; @@ -59,6 +64,110 @@ const fn buffer_store_dword(vdata: u8, srsrc: u8, byte_off: u16) -> [u32; 2] { ] } +/// A full typed store to element `s0` through the typed UAV at table slot 0, +/// with write marks and `soffset` in the instruction's scalar-source field. +fn typed_store_program(soffset: u8) -> Result { + let mut words = vec![ + s_mov_b32(4, 1), // s[4:5]: the table at s1 + s_mov_b32(5, ZERO as u8), + ]; + words.extend(s_load(2, 8, 4, 0)); + words.push(v_mov_b32(0, 0)); // v0 = s0, the element index + words.push(S_WAITCNT_ALL); + for (v, bits) in [ + (1, 0x3F80_0000), + (2, 0x4000_0000), + (3, 0x4040_0000), + (4, 0x4080_0000), + ] { + words.extend([0x7E00_0000 | (v as u32) << 17 | 0x01 << 9 | 0xFF, bits]); + } + words.extend([ + 0xE01C_2000, + 0x8002_0100 | (soffset as u32) << 24, // buffer_store_format_xyzw v[1:4], v0, s[8:11], 0 idxen + S_ENDPGM, + ]); + let param = |root, user_data, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + param(RootType::Constants, 0, 0), + param(RootType::Table, 1, 1), + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 1, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + 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, + atomic_locks: false, + bias_as_gradients: false, + narrow_waves: false, + host_wave32: false, + view_marks: true, + })?; + assert!(lowered.view_marks, "the typed store marks its view"); + assert_eq!( + lowered.root_srvs, + [VIEW_STRIDES], + "the view's run-time stride" + ); + 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, + memory: lowered.memory, + memory_writes: lowered.memory_writes, + view_addresses: lowered.view_addresses, + heap: lowered.heap, + heap_writes: lowered.heap_writes, + view_marks: lowered.view_marks, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + Ok(shader) +} + fn program() -> HostShader { let mut w = vec![s_mov_b32(5, 0x80)]; // s[4:5]: the table at s4 w.extend(s_load(2, 8, 4, 0)); // s[8:11]: the result UAV @@ -638,6 +747,109 @@ fn writes_through_views_mark_their_pages() { assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); } +/// A typed store's write mark spans the view's real element width. Each store +/// below ends exactly at a 64 KiB page boundary: 4-, 8-, 12- and 16-byte +/// elements must all set only the first page's bit, where a hardcoded 16-byte +/// width would also mark the next page. Inline zero is the no-offset soffset. +#[test] +fn typed_store_marks_use_the_element_stride_at_page_boundaries() { + let shader = typed_store_program(128).expect("lower"); + let cases: [(&str, DXGI_FORMAT, u32); 4] = [ + ("R32F", DXGI_FORMAT_R32_FLOAT, 4), + ("R32G32F", DXGI_FORMAT_R32G32_FLOAT, 8), + ("RGB32F", DXGI_FORMAT_R32G32B32_FLOAT, 12), + ("RGBA32F", DXGI_FORMAT_R32G32B32A32_FLOAT, 16), + ]; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host.compute_pipeline(&shader).expect("pipeline"); + for &(name, format, stride) in &cases { + // WARP on some hosts loses the device on RGB32 typed views, so + // it runs only the formats it says it can load and store. + if warp && !host.typed_buffer_access(format, warp) { + eprintln!("{label} {name}: no typed UAV load and store; skipped"); + continue; + } + let elements = 65_536 / stride; + let index = elements - 1; + // Put the element's last byte at 65,535. 65 KiB is not a + // multiple of 12, so RGB32 needs a four-byte mark phase. + let phase = 65_536 - elements * stride; + let base = 100; + let mut ud = vec![0u32; shader.user_data_dwords() as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match u.root { + RootType::Constants => index, + RootType::Table => 0, + other => panic!("unexpected user data {other:?}"), + }; + } + let views = [View::TypedUav(format, elements, stride)]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: vec![stride], + }, + ), + ( + 2, + Root::View { + srv: true, + data: vec![base, phase], + }, + ), + (3, Root::Uav(8)), + ], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label} {name}: {e}")); + let marked: Vec = (0..out[1].len() * 32) + .filter(|&b| out[1][b / 32] >> (b % 32) & 1 != 0) + .collect(); + assert_eq!(marked, [base as usize], "{label} {name}: pages"); + // D3DMetal substitutes R32G32 for RGB32 typed buffers and drops + // the store. WARP still checks those bytes; both check the mark. + if !warp && super::host::under_wine() && stride == 12 { + eprintln!( + "{label}: D3DMetal's RGB32 typed-buffer substitution; store bytes not compared" + ); + continue; + } + let channels = stride / 4; + let values = [ + 1.0f32.to_bits(), + 2.0f32.to_bits(), + 3.0f32.to_bits(), + 4.0f32.to_bits(), + ]; + let mut want = vec![0; (elements * stride).div_ceil(4) as usize]; + let at = (index * stride / 4) as usize; + want[at..at + channels as usize].copy_from_slice(&values[..channels as usize]); + assert_eq!(out[0], want, "{label} {name}: the typed store"); + } + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + /// Reads of texture views the program takes from the resource heap itself /// mark their heap index (`emit`, "Read marks"): an `image_load` of the view /// at heap byte offset 32 (index 1) sets exactly the bit one past diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6892f320..e88d9d40 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -60,9 +60,11 @@ //! * **Buffer views in the heap** are declared by how the shader reads //! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and //! typed-format loads without an index; structured with the used-resource -//! entry's stride when indexed; typed with four 32-bit float channels for -//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at -//! that index must be of that kind and start at the console descriptor's +//! entry's stride when indexed; typed with four 32-bit channels for +//! `buffer_load_format_*` and `buffer_store_format_*`. A dynamic integer +//! view gets a second, integer-annotated handle and guarded `.i32` loads +//! and stores; float views keep the `.f32` path. The host's view at that +//! index must be of that kind and start at the console descriptor's //! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the //! title's view description says. Typed-format loads from heap //! descriptors (1,024 world compute programs, ray-tracing material @@ -233,6 +235,8 @@ mod shader; mod stride_tests; #[cfg(all(test, windows))] mod synthetic_tests; +#[cfg(test)] +mod typed_buffer_tests; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index f131a03d..0308ee12 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -20,7 +20,8 @@ pub const VIEW_STRIDES: u8 = 255; /// The bits of a view-stride table dword holding the stride. pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; /// In a view-stride table dword: a typed buffer view of an integer format -/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits. +/// (`UINT` or `SINT`), whose 32-bit accesses use the `.i32` overloads and whose +/// 16-bit typed accesses (`_d16`) pass bits. pub const VIEW_INTEGER: u32 = 1 << 31; /// With [`VIEW_INTEGER`]: a signed (`SINT`) format. pub const VIEW_SIGNED: u32 = 1 << 30; diff --git a/crates/victory-shader/src/emit/typed_buffer_tests.rs b/crates/victory-shader/src/emit/typed_buffer_tests.rs new file mode 100644 index 00000000..03cb3669 --- /dev/null +++ b/crates/victory-shader/src/emit/typed_buffer_tests.rs @@ -0,0 +1,369 @@ +//! Synthetic typed-buffer accesses: the view's format is chosen at runtime, +//! so integer views need `bufferLoad.i32`/`bufferStore.i32` without putting +//! mismatched component bits through the float overloads. + +#[cfg(windows)] +use super::{HostShader, VIEW_INTEGER, VIEW_SIGNED, validator}; +use super::{VIEW_STRIDES, lower}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{io, ir, resource, structure}; + +/// User data: s0 a typed UAV, s1 a raw SRV, s2 a raw UAV, s3 a typed SRV. +/// Each lane loads four dwords from element `lane` of the raw SRV, stores them +/// to the typed UAV, loads the typed element back from both the UAV and SRV, +/// and writes the three copies to dwords `12 * lane .. 12 * lane + 11` of the +/// raw UAV. +const ROUND_TRIP_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0303, + 0xFA00_0000, // s_load_dwordx4 s[12:15], s[6:7], 0x0 + 0xBE94_0302, // s_mov_b32 s20, s2 + 0xBE95_0380, // s_mov_b32 s21, 0 + 0xF408_040A, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[20:21], 0x0 + 0xBE96_0303, // s_mov_b32 s22, s3 + 0xBE97_0380, // s_mov_b32 s23, 0 + 0xF408_060B, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[22:23], 0x0 + 0x3406_0084, // v_lshlrev_b32 v3, 4, v0 + 0x1614_00B0, // v_mul_u32_u24 v10, 48, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xE038_1000, + 0x8003_0103, // buffer_load_dwordx4 v[1:4], v3, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE078_1000, + 0x8004_010A, // buffer_store_dwordx4 v[1:4], v10, s[16:19], 0 offen + 0xE01C_2000, + 0x8002_0100, // buffer_store_format_xyzw v[1:4], v0, s[8:11], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE00C_2000, + 0x8002_0500, // buffer_load_format_xyzw v[5:8], v0, s[8:11], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE00C_2000, + 0x8006_0C00, // buffer_load_format_xyzw v[12:15], v0, s[24:27], 0 idxen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xE078_1010, + 0x8004_050A, // buffer_store_dwordx4 v[5:8], v10, s[16:19], 0 offset:16 + 0xE078_1020, + 0x8004_0C0A, // buffer_store_dwordx4 v[12:15], v10, s[16:19], 0 offset:32 + 0xBF81_0000, // s_endpgm +]; + +fn lowered() -> lower::Lowered { + let range = |kind, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: slot, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: (0..4) + .map(|slot| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: slot, + slot, + }) + .collect(), + used: vec![ + range(ResourceType::Uav, 0), + range(ResourceType::Srv, 1), + range(ResourceType::Uav, 2), + range(ResourceType::Srv, 3), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 4 << 1, + threads: [32, 1, 1], + }), + code: ROUND_TRIP_WAVE32 + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(), + }; + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, &native).expect("io::raise"); + 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, + atomic_locks: false, + bias_as_gradients: false, + narrow_waves: false, + host_wave32: false, + view_marks: false, + }) + .expect("lower") +} + +#[cfg(windows)] +fn shader() -> HostShader { + let lowered = lowered(); + HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + static_samplers: lowered + .samplers + .iter() + .map(|&w| super::StaticSampler::from_words(w)) + .collect(), + samplers: lowered.samplers, + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + memory: lowered.memory, + memory_writes: lowered.memory_writes, + view_addresses: lowered.view_addresses, + heap: lowered.heap, + heap_writes: lowered.heap_writes, + view_marks: lowered.view_marks, + } +} + +#[test] +fn typed_accesses_emit_both_component_overloads() { + let lowered = lowered(); + assert_eq!( + lowered.root_srvs, + [VIEW_STRIDES], + "the runtime view-kind table is read" + ); + let calls = lowered.typed_buffer_calls; + let [load_f32, load_i32] = calls.loads; + let [store_f32, store_i32] = calls.stores; + assert_eq!( + (load_f32.len(), load_i32.len()), + (2, 2), + "typed SRV/UAV loads: f32, i32" + ); + assert_eq!( + (store_f32.len(), store_i32.len()), + (1, 1), + "typed UAV stores: f32, i32" + ); + for (float, integer) in [(load_f32, load_i32), (store_f32, store_i32)] { + for (float, integer) in float.into_iter().zip(integer) { + assert_ne!(float, integer, "the component overloads must be guarded"); + } + } +} + +#[cfg(windows)] +#[test] +fn rgb32_and_rgba32_integer_views_have_kind_metadata() { + use super::host::{Stride, View, view_strides}; + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32A32_SINT, + DXGI_FORMAT_R32G32B32A32_UINT, + }; + + let views = [ + View::Buffer { + data: &[0; 3], + stride: Stride::Format(DXGI_FORMAT_R32G32B32_UINT, 12), + }, + View::Buffer { + data: &[0; 3], + stride: Stride::Format(DXGI_FORMAT_R32G32B32_SINT, 12), + }, + View::Buffer { + data: &[0; 4], + stride: Stride::Format(DXGI_FORMAT_R32G32B32A32_UINT, 16), + }, + View::Buffer { + data: &[0; 4], + stride: Stride::Format(DXGI_FORMAT_R32G32B32A32_SINT, 16), + }, + ]; + assert_eq!( + view_strides(&views), + [ + 12 | VIEW_INTEGER, + 12 | VIEW_INTEGER | VIEW_SIGNED, + 16 | VIEW_INTEGER, + 16 | VIEW_INTEGER | VIEW_SIGNED, + ] + ); +} + +#[cfg(windows)] +#[test] +fn synthetic_typed_accesses_validate() { + let mut shader = shader(); + let Ok(mut validator) = validator::Validator::load(None) else { + eprintln!("no dxil.dll; DXIL validation skipped"); + return; + }; + validator + .validate(&mut shader.dxil) + .expect("the guarded typed-buffer module validates"); +} + +#[cfg(windows)] +#[test] +fn integer_typed_bits_survive_srv_and_uav_round_trips() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_SINT, + DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_SINT, + DXGI_FORMAT_R32G32B32A32_UINT, + }; + + use super::host::{Dispatch, Host, Root, Stride, View}; + + let shader = shader(); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let integer = [ + 0xFFFF_FFFF, // UINT_MAX / SINT -1 + 0x8000_0000, // INT_MIN + 0x7FC0_0000, // quiet NaN bits + 0x7F80_0001, // signalling NaN bits + 0xFFC0_0001, // negative signalling NaN bits + 0, + 1, + 0x3F80_0000, + ]; + let float = [ + 0, + 1, + 0x8000_0000, + 0x3F80_0000, + 0xBF80_0000, + 0x7F80_0000, + 0xFF80_0000, + 0x4049_0FDB, + ]; + // (format, bytes per element, integer, signed) + let cases: [(DXGI_FORMAT, u32, bool, bool); 6] = [ + (DXGI_FORMAT_R32G32B32A32_UINT, 16, true, false), + (DXGI_FORMAT_R32G32B32A32_SINT, 16, true, true), + (DXGI_FORMAT_R32G32B32_UINT, 12, true, false), + (DXGI_FORMAT_R32G32B32_SINT, 12, true, true), + (DXGI_FORMAT_R32G32B32A32_FLOAT, 16, false, false), + (DXGI_FORMAT_R32G32B32_FLOAT, 12, false, false), + ]; + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + for &(format, bytes, is_integer, signed) in &cases { + if !host.typed_buffer_access(format, warp) { + eprintln!("{label}: typed buffer access to {format:?} unsupported; skipped"); + continue; + } + let channels = bytes / 4; + let patterns = if is_integer { &integer } else { &float }; + let data: Vec = (0..32u32) + .flat_map(|lane| { + (0..channels) + .map(move |ch| patterns[(lane as usize + ch as usize) % patterns.len()]) + }) + .collect(); + // The raw source is four dwords an element even for RGB32; the + // typed SRV and UAV keep their tightly packed three-channel layout. + let mut raw_data = Vec::with_capacity(128); + for lane in 0..32 { + raw_data.extend_from_slice( + &data[lane * channels as usize..(lane + 1) * channels as usize], + ); + if channels == 3 { + raw_data.push(0); + } + } + let kind = if is_integer { + VIEW_INTEGER | if signed { VIEW_SIGNED } else { 0 } + } else { + 0 + }; + let views = [ + View::TypedUav(format, 32, bytes), + View::Buffer { + data: &raw_data, + stride: Stride::Raw, + }, + View::RawUav(384), + View::Buffer { + data: &data, + stride: Stride::Format(format, bytes), + }, + ]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = 32 * u32::from(u.slot); + } + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: vec![bytes | kind, 4, 4, bytes | kind], + }, + ), + ], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label} {format:?}: dispatch failed: {e}")); + for copy in 0..3 { + for lane in 0..32 { + for ch in 0..channels as usize { + assert_eq!( + words[1][lane * 12 + copy * 4 + ch], + data[lane * channels as usize + ch], + "{label} {format:?}: copy {copy}, lane {lane}, channel {ch}" + ); + } + } + } + for lane in 0..32 { + for ch in 0..channels as usize { + assert_eq!( + words[0][lane * channels as usize + ch], + data[lane * channels as usize + ch], + "{label} {format:?}: UAV lane {lane}, channel {ch}" + ); + } + } + ran += 1; + } + } + assert!(ran > 0, "no adapter supports typed buffer loads and stores"); +}