diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index c817360..f334d20 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -598,6 +598,12 @@ fn check( if let Some(keep) = &checks.keep { lock(keep).push((label(), shader.clone())); } + // With `--list`: a hash of the module and of what the host binds for it, + // to show which shaders a change to the translator touches. + if t.list { + let hash = blake3::hash(format!("{shader:?}").as_bytes()).to_hex(); + t.lines.push(format!("{} emitted {}", label(), &hash[..16])); + } // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. if t.list && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 13551c3..89dc8b7 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -63,6 +63,8 @@ pub const ALL: u32 = MODULE | FIRST; pub(crate) struct Usage { /// A wave or quad operation. pub wave_ops: bool, + /// A rasterizer ordered view. + pub rovs: bool, /// A 64-bit integer, as a result or an operand. pub int64: bool, /// A typed load of several components from a UAV. @@ -388,7 +390,7 @@ impl Module { } /// An integer constant's width and value (the bits of that width). - fn int_k(&self, v: V) -> Option<(u32, u64)> { + pub(crate) fn int_k(&self, v: V) -> Option<(u32, u64)> { let V::Const(i) = v else { return None }; let (ty, Const::Int(x)) = &self.consts[i as usize] else { return None; @@ -1009,6 +1011,8 @@ impl Module { Some((_, 0)) => u.heap_views = true, _ => u.heap_samplers = true, } + } else if name == "annotateHandle" { + u.rovs |= annotation(V::Inst(i)).is_some_and(|(kind, _)| kind & 0x2000 != 0); } else if name.starts_with("atomic") && name.ends_with(".i64") { u.atomic64 = true; } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index c2a9d35..f5a547e 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -107,6 +107,64 @@ pub(crate) fn lower(parts: &Parts) -> Result { const TWO_PI: f32 = std::f32::consts::TAU; /// `s_sendmsg` id of a mesh or NGG stage's output allocation request. const GS_ALLOC_REQ: u16 = 9; +/// `s_sendmsg` id that ends a pixel wave's ordered section. +const ORDERED_PS_DONE: u16 = 7; +/// Hardware register (of `s_setreg_b32`) a pixel wave names its packer in +/// before it waits for the waves it overlaps. +const POPS_PACKER: u16 = 25; +/// The operand `src_pops_exiting_wave_id`. +const POPS_EXITING: u8 = 239; + +/// The instructions inside a pixel program's ordered section +/// (primitive-ordered pixel shading, which the console compiler makes of +/// rasterizer ordered views): from the write of `POPS_PACKER`, along every +/// path, to the message that ends the section or the program's end. The +/// console waits there until the waves holding earlier primitives' samples +/// of the same pixels have left their sections; a host's rasterizer ordered +/// views wait by themselves, at their first access. Empty for a program +/// without such a section. +fn ordered_section(p: &Program) -> HashSet { + let starts = |i: &Inst| { + i.name() == "s_setreg_b32" + && matches!(i.fields, Fields::Sop { imm: Some(imm), .. } if imm & 0x3F == POPS_PACKER) + }; + let ends = |i: &Inst| { + i.name() == "s_sendmsg" + && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == ORDERED_PS_DONE) + }; + let mut section = HashSet::new(); + let mut entered = vec![false; p.blocks.len()]; + let mut work: Vec = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + (0..block.insts.len()) + .filter(|&i| starts(&block.insts[i])) + .map(move |i| (b, i)) + }) + .collect(); + while let Some((b, from)) = work.pop() { + let block = &p.blocks[b]; + let mut done = false; + for i in from..block.insts.len() { + if ends(&block.insts[i]) { + done = true; + break; + } + section.insert((b, i)); + } + if done { + continue; + } + for (t, next) in p.blocks.iter().enumerate() { + if next.preds.contains(&b) && !std::mem::replace(&mut entered[t], true) { + work.push((t, 0)); + } + } + } + section +} /// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, /// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). @@ -194,6 +252,8 @@ struct Lower<'a> { /// Descriptor dwords with no host value (addresses, formats, all of a constant /// buffer's): no program reads them as numbers ([`Self::dead`]). stale: HashSet, + /// See [`ordered_section`] (pixel programs). + ordered: HashSet, mask_phis: HashMap, pending_masks: Vec<(V, usize, usize)>, data_phis: Vec<(V, usize, usize)>, @@ -1486,6 +1546,11 @@ impl<'a> Lower<'a> { data_phis: Vec::new(), read_phis: HashSet::new(), stale: HashSet::new(), + ordered: if x.native.stage == HwStage::Ps { + ordered_section(p) + } else { + HashSet::new() + }, params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), user_data: None, user_reads: BTreeMap::new(), @@ -2064,9 +2129,12 @@ impl<'a> Lower<'a> { /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange /// their halves' sums for the last addition. The high half of the result is lane 0's, /// which no `v_add_f16` writes. - /// That needs every lane of a full wave there to be read: refused where not every lane - /// runs, in a thread group that does not fill its waves, and for each half-wave on its - /// own (half a sum is no sum). + /// On a host wave of 64 lanes where not every lane runs, the lanes that are elsewhere + /// count as the console's do (it masks them to +0): a partner's partial sum is read from + /// the first lane there is of the partner's run of lanes, and is +0 without one. Two host + /// waves of 32 can only exchange where every lane runs: refused elsewhere, in a thread + /// group that does not fill its waves, and for each half-wave on its own (half a sum is + /// no sum). fn half_sum(&mut self, x: V) -> Result { const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; @@ -2087,24 +2155,54 @@ impl<'a> Lower<'a> { } else { all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) }; - if !every { - if halves { - need(self.cur_ir); - } + if !every && halves { + need(self.cur_ir); return Err(WHERE); } let c = self.cur; let i32t = self.s.t.i32; let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + // the lanes that are here, when not all are + let here = (!every).then(|| { + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let yes = self.s.m.bool(true); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[yes]); + (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)) + }); + // `v` of the first lane here of the `n` (a power of two) lanes from `base`: +0 of none + let first_of = |l: &mut Self, v: V, base: V, n: u32| { + let Some((lo, hi)) = here else { + return l.read_lane(v, base); + }; + let (k31, k32) = (l.s.m.i32(31), l.s.m.i32(32)); + let lower = l.s.m.cmp(c, pred::IULT, base, k32); + let word = l.s.m.select(c, lower, lo, hi); + let shift = l.s.m.bin(c, Bin::And, base, k31); + let word = l.s.m.bin(c, Bin::LShr, word, shift); + let run = l.s.m.i32(u32::MAX >> (32 - n)); + let word = l.s.m.bin(c, Bin::And, word, run); + let any = l.s.m.cmp(c, pred::NE, word, zero); + let nth = l.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[word]); + let from = l.s.m.bin(c, Bin::Add, base, nth); + // (no lane there: this one, which is here; the read is not used) + let from = l.s.m.select(c, any, from, lane); + let got = l.read_lane(v, from); + l.s.m.select(c, any, got, zero) + }; let mut sum = x; for step in 0..if halves { 5 } else { 6 } { let bit = self.s.m.i32(1 << step); - let partner = self.s.m.bin(c, Bin::Xor, lane, bit); - let theirs = self.read_lane(sum, partner); + let mut partner = self.s.m.bin(c, Bin::Xor, lane, bit); + if !every { + let run = self.s.m.i32(!((1 << step) - 1)); + partner = self.s.m.bin(c, Bin::And, partner, run); + } + let theirs = first_of(self, sum, partner, 1 << step); sum = self.add_halves(sum, theirs); } - let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); - let first = self.read_lane(x, zero); + let first = first_of(self, x, zero, 1); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); let mine = self.s.m.bin(c, Bin::Or, first, sum); @@ -2258,6 +2356,8 @@ impl<'a> Lower<'a> { // paths only seem to allow it before any save: the lane of a VGPR // nobody wrote, and VGPRs nobody set read as zero. None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), + // No wave overlaps this one (see `ordered_section`). + None if self.pops_collision(v) => Val::I32(self.s.m.i32(0)), None => Val::Missing("a hardware SGPR input"), }, Reg::Scc => Val::Missing("SCC on entry"), @@ -2273,6 +2373,36 @@ impl<'a> Lower<'a> { Ok(()) } + /// Whether the input SGPR `v` is the POPS collision wave id: a program + /// with an ordered section only takes its fields apart (bit 31 says + /// that the wave overlaps another, the others which packer and waves). + fn pops_collision(&self, v: Value) -> bool { + if self.ordered.is_empty() { + return false; + } + let mut packer = false; + for block in &self.x.p.blocks { + if block.phis.iter().any(|p| p.args.contains(&v)) { + return false; + } + for i in &block.insts { + if !i.reads.iter().any(|r| r.1 == v) { + continue; + } + let Fields::Sop { src, .. } = &i.fields else { + return false; + }; + match (i.name(), src.get(1)) { + // bits 28 and 29: the packer + ("s_bfe_u32", Some(Operand::Literal(0x0002_001C))) => packer = true, + ("s_bfe_u32" | "s_lshr_b32", _) => {} + _ => return false, + } + } + } + packer + } + fn input(&mut self, input: Input) -> Val { let (kind, col) = match input { Input::VertexId => (1, 0), @@ -2665,6 +2795,93 @@ impl<'a> Lower<'a> { }) } + /// Whether the image `src` names is one of 32-bit integers (one channel): + /// the program has an integer atomic on the same table entry, which + /// takes no other view. + fn is_counter(&self, src: &Source) -> bool { + let entry = |s: &Source| match s { + Source::Loaded { load, first } => self + .scalar + .get(load) + .filter(|a| a.dynamic.is_none()) + .map(|a| (a.param, a.offset + 4 * u32::from(*first))), + _ => None, + }; + let Some(this) = entry(src) else { + return false; + }; + self.x.res.descriptors.iter().any(|d| { + let i = &self.x.p.blocks[d.site.0].insts[d.site.1]; + d.role == Role::Resource + && matches!(i.fields, Fields::Image { dmask: 1, .. }) + && matches!( + i.name(), + "image_atomic_add" + | "image_atomic_sub" + | "image_atomic_and" + | "image_atomic_or" + | "image_atomic_xor" + | "image_atomic_smin" + | "image_atomic_smax" + | "image_atomic_umin" + | "image_atomic_umax" + ) + && entry(&d.source) == Some(this) + }) + } + + /// The kind of a view no instruction uses (in this program, or through + /// another load of its address), by what the code reads of the + /// descriptor the load `inst` at `site` writes to the SGPRs from `code`: + /// `Some(true)` for a 2D image, read only for its size, `Some(false)` + /// for a structured buffer, read only for its record count. + /// + /// - Eight dwords are an image's. `GetDimensions` of a 2D one reads the + /// width (dwords 1 and 2), the height (dword 2, bits 14-29, with one + /// `s_bfe_u32`) and the base level or the last (dword 3); of an array, + /// a cube or a volume also dword 4. + /// - Four dwords at a table entry the used resources list as an SRV or + /// UAV are a buffer's. A stride above 4 bytes there is an element's + /// (a typed or raw view has at most 4): a test for a null view reads + /// the record count, nothing else. + fn sized_view(&self, inst: &Inst, site: Site, code: u8, count: u32) -> Option { + let dword = |k: u8| inst.write(Reg::S(code + k)); + let read = |v: Value| { + self.x.p.blocks.iter().any(|b| { + b.insts.iter().any(|i| i.reads.iter().any(|r| r.1 == v)) + || b.phis.iter().any(|p| p.args.contains(&v)) + }) + }; + let only = |allowed: &[u8]| { + (0..count as u8).all(|k| allowed.contains(&k) || !dword(k).is_some_and(read)) + }; + match count { + 8 => { + const HEIGHT: u32 = 16 << 16 | 14; + let v = dword(2)?; + let height = self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + i.name() == "s_bfe_u32" + && i.reads.iter().any(|r| r.1 == v) + && matches!(&i.fields, Fields::Sop { src, .. } + if matches!(src.get(1), Some(Operand::Literal(HEIGHT)))) + }); + (height && only(&[1, 2, 3])).then_some(true) + } + 4 => { + let used = self.used_kind(&Source::Loaded { load: site, first: 0 })?; + let a = self.scalar.get(&site)?; + let buffer = used.dwords == 4 + && a.dynamic.is_none() + && used.table_offset_dwords == a.offset / 4 + && matches!(used.kind, ResourceType::Srv | ResourceType::Uav) + && used.stride > 4 + && used.stride.is_multiple_of(4); + (buffer && only(&[2])).then_some(false) + } + _ => None, + } + } + /// The title address (low dword, bits from 32 up) of the buffer view /// whose descriptor the scalar load at `site` reads from the start of /// a table entry, as the host tells it when it binds (`shader.rs` @@ -3052,6 +3269,11 @@ impl<'a> Lower<'a> { if self.exchange.is_some() && !self.local { need(made.unwrap_or(0)); } + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + let by = made.map(|b| &self.x.p.blocks[b]); + let def = by.and_then(|b| b.insts.iter().find(|i| i.writes.iter().any(|w| w.1 == lo))); + eprintln!("MASK-WHY {v:?} made in {made:?} by {:?} at {:x?}; read in block at {:#x}; phi {}", def.map(|i| i.name()), def.map(|i| i.machine.offset), self.x.p.blocks[self.cur_ir].offset, self.phi_at.contains_key(&lo)); + } return Err(MASK_ELSEWHERE); } let (x, y) = match self.ballots.get(&lo) { @@ -3116,6 +3338,8 @@ impl<'a> Lower<'a> { let bit = self.scc_in(inst)?; Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32)) } + // Nothing to wait for (see `ordered_section`). + Operand::Const(POPS_EXITING) if !self.ordered.is_empty() => Ok(self.s.m.i32(0)), Operand::Const(c) => crate::resource::inline(c) .map(|x| self.s.m.i32(x)) .ok_or("a special operand (vccz, execz, scc, lds_direct)"), @@ -5400,12 +5624,30 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; - match self.get(v)? { - Val::Bit(x) => Ok(x), - _ => Err("SCC without a value"), + match self.get(v) { + Ok(Val::Bit(x)) => Ok(x), + Ok(_) => Err("SCC without a value"), + // Of a mask operation whose result lies within EXEC: whether + // some lane is left. + Err(LANE_MASK) if self.within_exec(v) => self.scc_some(v), + Err(why) => Err(why), } } + /// Whether the mask operation that sets the SCC value `scc` gives no + /// lane outside EXEC a bit. + fn within_exec(&self, scc: Value) -> bool { + let Some(&b) = self.def_block.get(&scc) else { + return false; + }; + let by = self.x.p.blocks[b].insts.iter().find(|i| i.write(Reg::Scc) == Some(scc)); + by.is_some_and(|i| { + i.write(Reg::S(EXEC)).is_some() + || matches!(&i.fields, Fields::Sop { dst: Some(Operand::Scalar { code, .. }), .. } + if i.write(Reg::S(*code)).is_some_and(|lo| self.x.st.active.contains(&lo))) + }) + } + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Fields::Smem { data, @@ -5653,7 +5895,12 @@ impl<'a> Lower<'a> { .find_map(|(s, _)| use_of(*s)) }; let use_at = use_of(site).or_else(twin); - let Some((at, first)) = use_at else { + // A view whose kind no use tells, but what is read of it does. + let sized = match use_at { + Some(_) => None, + None => self.sized_view(inst, site, code, count), + }; + let Some((at, first)) = use_at.or(sized.map(|_| (site, 0))) else { // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only // copies its dwords and compares them, lane against first lane, and every load // that reaches those lanes reads one address. Each dword stands in as its place @@ -5721,6 +5968,8 @@ impl<'a> Lower<'a> { || used.is_some_and(|u| u.kind == ResourceType::Uav); let u = if uav { 0x1000 } else { 0 }; let (props, image) = match &ui.fields { + _ if sized.is_some_and(|image| image) => ((2 | u, 0x409), Some(2)), + _ if sized.is_some() => ((11 | u, 0), None), // A ray-tracing structure in a buffer of the host: read raw. Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), Fields::Image { dim, .. } => { @@ -5734,15 +5983,15 @@ impl<'a> Lower<'a> { }; ((kind | u, 0x409), Some(kind)) } - Fields::Buffer { idxen, format, .. } => { - let stride = used.map_or(0, |u| u.stride); + Fields::Buffer { .. } => { let props = if un.starts_with("buffer_load_format") || un.starts_with("buffer_store_format") { (10 | u, 0x409) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { - (12 | u, stride) } else { + // Structured ones too: the host's views of them are raw + // (see `buffer`), which count bytes, and a size asked + // for as a structured view's is that count on AMD. (11 | u, 0) }; if used.is_some_and(|u| u.kind == ResourceType::Cbv) { @@ -9549,7 +9798,13 @@ impl<'a> Lower<'a> { || self .used_kind(src) .is_some_and(|u| u.kind == ResourceType::Uav); - let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + // A UAV inside an ordered section is a rasterizer ordered view. + let ordered = uav && self.ordered.contains(&site); + if ordered { + self.s.flags |= flags::ROVS; + } + let rov = if ordered { 0x2000 } else { 0 }; + let props = (kind | if uav { 0x1000 } else { 0 } | rov, 0x409); if let Some(op) = name.strip_prefix("image_atomic_") { // GLC returns the old value. DXIL implements subtraction by adding // the two's complement of the operand at the same width. @@ -9607,7 +9862,7 @@ impl<'a> Lower<'a> { } else { original }; - let h = self.handle(site, src, false, (kind | 0x1000, component))?; + let h = self.handle(site, src, false, (kind | 0x1000 | rov, component))?; let mut args = vec![h]; let (intrinsic, opcode) = if compare { let comparand = if wide { @@ -9660,7 +9915,9 @@ impl<'a> Lower<'a> { } // shortcut: stores are taken to write all four channels of a // float format (the console converts by the view's format). - if *dmask != 0xF { + // One channel goes into a view the program also counts in. + let counter = *dmask == 1 && self.is_counter(src); + if *dmask != 0xF && !counter { return Err("an image store of some channels"); } let iu = self.s.m.undef(self.s.t.i32); @@ -9671,6 +9928,34 @@ impl<'a> Lower<'a> { let Operand::Vector { reg, .. } = *data else { return Err("image store data"); }; + if counter { + let v = inst.read(Reg::V(reg)).ok_or("image store data")?; + let x = self.i32_of(v)?; + // A 16-bit integer, extended by the view's sign: the same + // number either way only if it is known to be small. + if *d16 && !self.s.m.int_k(x).is_some_and(|(_, k)| k < 0x8000) { + return Err("a 16-bit image store of one channel"); + } + let h = self.handle(site, src, false, (kind | 0x1000 | rov, 0x105))?; + let at = self.begin_guarded(guard); + // All four channels are written (the validator wants them + // all): the view has the first alone. + let mut args = vec![h]; + args.extend(cs); + args.extend([x; 4]); + args.push(self.s.m.i8(0xF)); + let void = self.s.t.void; + self.s.op( + self.cur, + "textureStore.i32", + Attr::NoUnwind, + void, + 67, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } let mut vals = Vec::new(); for k in 0..4u8 { // d16: two f16 channels per VGPR, low half first. diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 9ca8313..d919660 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -99,6 +99,8 @@ mod threading; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] +mod size_tests; +#[cfg(all(test, windows))] mod valu_tests; #[cfg(all(test, windows))] mod waterfall_tests; @@ -859,6 +861,134 @@ mod tests { assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); } + /// A pixel program with an ordered section, as the console compiler + /// makes one of rasterizer ordered views (the title's hair cards keep + /// their nearest layers that way): the wait for overlapped waves is + /// skipped, the views inside the section are the host's ordered ones, + /// the one after it is not. + #[test] + fn an_ordered_section_uses_rasterizer_ordered_views() { + let section = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0201, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00_0000, + 0x9390_FF01, // s_bfe_u32 s16, s1, 0x2001c + 0x0002_001C, + 0x9391_FF01, // s_bfe_u32 s17, s1, 0xa0000 + 0x000A_0000, + 0x8F10_8110, // s_lshl_b32 s16, s16, 1 + 0x9392_FF01, // s_bfe_u32 s18, s1, 0xa0010 + 0x000A_0010, + 0xBE91_0711, // s_not_b32 s17, s17 + 0x9013_9F01, // s_lshr_b32 s19, s1, 31 + 0x8810_8110, // s_or_b32 s16, s16, 1 + 0x8112_1112, // s_add_i32 s18, s18, s17 + 0xBF06_8013, // s_cmp_eq_u32 s19, 0 + 0xB990_1019, // s_setreg_b32 hwreg(HW_REG_POPS_PACKER, 0, 3), s16 + 0x8514_807E, // s_cselect_b32 s20, exec_lo, 0 + 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF08_1215, // s_cmp_gt_u32 s21, s18 + 0x8516_807E, // s_cselect_b32 s22, exec_lo, 0 + 0x8814_1614, // s_or_b32 s20, s20, s22 + 0x876A_147E, // s_and_b32 vcc_lo, exec_lo, s20 + 0xBF87_0004, // s_cbranch_vccnz past the wait + 0xBF8E_FFFF, // s_sleep 0xffff + 0x8115_11EF, // s_add_i32 s21, src_pops_exiting_wave_id, s17 + 0xBF0A_1512, // s_cmp_lt_u32 s18, s21 + 0xBF84_FFFC, // s_cbranch_scc0 back to the sleep + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0xF000_3F88, // image_load v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc dlc + 0x0002_0200, + 0x0604_04F2, // v_add_f32 v2, 1.0, v2 + 0xF020_3F08, // image_store v[2:5], v[0:1], s[8:15] dmask:0xf 2D glc + 0x0002_0200, + 0xBEFC_0380, // s_mov_b32 m0, 0 + 0xBF90_0007, // s_sendmsg sendmsg(MSG_ORDERED_PS_DONE) + ]; + let end = [ + 0xF800_180Fu32, // exp mrt0 v2, v2, v2, v2 done vm + 0x0202_0202, + 0xBF81_0000, // s_endpgm + ]; + // A store after the section, through an ordinary view. + let after = [0xF020_3F08u32, 0x0002_0200]; + let lower = |words: Vec| { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![crate::native::RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![crate::native::UsedResource { + kind: crate::native::ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 8, + user_data: 0, + slot: 0, + }], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }; + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + let out = emit(&c, &native, &p, &st, &io, &res)?; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + Ok::(u64::from_le_bytes(sfi0.try_into().unwrap())) + }; + // D3D_SHADER_REQUIRES_ROVS + let features = lower([§ion[..], &end].concat()).unwrap(); + assert_ne!(features & 0x1000, 0, "SFI0 {features:#x}: no ROVs"); + lower([§ion[..], &after, &end].concat()).unwrap(); + // The same accesses outside a section: ordinary views, no feature. + let plain = [§ion[..4], §ion[28..35], &end].concat(); + let features = lower(plain).unwrap(); + assert_eq!(features & 0x1000, 0, "SFI0 {features:#x}: ROVs"); + // Without the section's start the wait stays unknown. + let mut unmarked = [§ion[..], &end].concat(); + unmarked.remove(16); + assert!(lower(unmarked).is_err()); + } + /// A wave64 compute program that writes only EXEC's high dword /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was /// opaque and keyed by the unchanged low dword, so building its lane bit diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 28a36f1..eb6d589 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -76,6 +76,7 @@ pub(crate) mod flags { pub const DOUBLES: u64 = 1 << 2; pub const STENCIL_REF: u64 = 1 << 11; pub const TYPED_UAV_LOADS: u64 = 1 << 13; + pub const ROVS: u64 = 1 << 18; pub const WAVE_OPS: u64 = 1 << 19; pub const BARYCENTRICS: u64 = 1 << 22; pub const INT64: u64 = 1 << 20; @@ -455,6 +456,7 @@ impl Shader { self.m.optimise(passes); let used = self.m.usage(); for (flag, used) in [ + (flags::ROVS, used.rovs), (flags::WAVE_OPS, used.wave_ops), (flags::INT64, used.int64), (flags::TYPED_UAV_LOADS, used.typed_uav_loads), @@ -787,6 +789,9 @@ impl Shader { if self.flags & flags::TYPED_UAV_LOADS != 0 { features |= 0x800; } + if self.flags & flags::ROVS != 0 { + features |= 0x1000; + } if self.flags & flags::WAVE_OPS != 0 { features |= 0x4000; } diff --git a/crates/victory-shader/src/emit/size_tests.rs b/crates/victory-shader/src/emit/size_tests.rs new file mode 100644 index 0000000..5c6c40e --- /dev/null +++ b/crates/victory-shader/src/emit/size_tests.rs @@ -0,0 +1,268 @@ +//! End-to-end tests of what a program tells about a view by how it uses it: +//! descriptors read for sizes (the dwords of a view no instruction uses) and +//! counters, lowered to DXIL, validated by `dxil.dll` when present, and run +//! on the host GPU and WARP. + +use super::host::{Stride, View}; +use super::waterfall_tests::run; +use super::{HostShader, lower, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{ShaderError, io, ir, resource, structure}; + +/// Lowers a wave32 compute program of one thread with the table of views at +/// s0 and the view heap at s1; `srv`: the dwords and the stride of the used +/// resource at the table's first entry (the third is a raw UAV). +fn build(words: &[u32], srv: (u8, u32)) -> Result { + let param = |root, user_data| RootParam { + root, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: 0, + }; + let range = |kind, table_offset_dwords, dwords, stride| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data: 0, + slot: 0, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 32, + layout: vec![param(RootType::Table, 0), param(RootType::ResourceHeap, 1)], + used: vec![ + range(ResourceType::Srv, 0, srv.0, srv.1), + range(ResourceType::Uav, 16, 4, 0), + ], + 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)?; + let st = structure::structure(&p)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native)?; + 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, + })?; + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: Vec::new(), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + Ok(shader) +} + +/// The table at s[2:3], its raw UAV's descriptor in s[20:23]. +const TABLE: &[u32] = &[ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0501, // s_load_dwordx4 s[20:23], s[2:3], 64 + 0xFA00_0040, +]; + +/// Stores s4 and s5 at bytes 0 and 4 of the UAV. +const STORE: &[u32] = &[ + 0x7E08_0204, // v_mov_b32 v4, s4 + 0x7E0A_0205, // v_mov_b32 v5, s5 + 0xE070_0000, // buffer_store_dword v4, off, s[20:23], 0 + 0x8005_0400, + 0xE070_0004, // buffer_store_dword v5, off, s[20:23], 0 offset:4 + 0x8005_0500, + 0xBF81_0000, // s_endpgm +]; + +/// `GetDimensions` of a texture as the console compiler expands it, from +/// the descriptor in s[8:15]: width in s4, height in s5, base level in s6. +const SIZES: &[u32] = &[ + 0x9004_9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05_820A, // s_lshl_b32 s5, s10, 2 + 0x8804_0504, // s_or_b32 s4, s4, s5 + 0x8704_FF04, // s_and_b32 s4, s4, 0xffff + 0x0000_FFFF, + 0x9385_FF0A, // s_bfe_u32 s5, s10, 0x10000e + 0x0010_000E, + 0x9386_FF0B, // s_bfe_u32 s6, s11, 0x4000c + 0x0004_000C, + 0x8104_8104, // s_add_i32 s4, s4, 1 + 0x8105_8105, // s_add_i32 s5, s5, 1 + 0x9004_0604, // s_lshr_b32 s4, s4, s6 + 0x9005_0605, // s_lshr_b32 s5, s5, s6 +]; + +/// s_load_dwordx8 s[8:15], s[6:7], s12: entry 1 of the view heap. +const FROM_HEAP: &[u32] = &[ + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xBE8C_03A0, // s_mov_b32 s12, 32 + 0xF40C_0203, + 0x1800_0000, +]; + +/// `s_load_dwordx4 s[8:11], s[2:3], 0`, then the record count in s4 and 0 +/// in s5. +const COUNT: &[u32] = &[ + 0xF408_0201, + 0xFA00_0000, + 0xBE84_030A, // s_mov_b32 s4, s10 + 0xBE85_0380, // s_mov_b32 s5, 0 +]; + +/// A puddle pass of the title picks three textures from the view heap, +/// reads the first one's size and samples the other two. +#[test] +fn the_size_of_a_heap_texture_nothing_reads() { + let words = [TABLE, FROM_HEAP, SIZES, STORE].concat(); + let shader = build(&words, (8, 0)).expect("translates"); + let (one, texels) = ([[0.0; 4]; 1], [[0.0; 4]; 15]); + let views = [ + View::Texture(1, 1, &one), + View::Texture(5, 3, &texels), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [5, 3], "{label}"); + } +} + +/// Without the height nothing tells a 2D texture from the others, and a +/// volume's depth or an array's layers are no 2D texture's. +#[test] +fn sizes_of_unknown_dimensions_stay_untranslated() { + let width = [ + 0x9004_9E09, // s_lshr_b32 s4, s9, 30 + 0x8F05_820A, // s_lshl_b32 s5, s10, 2 + 0x8804_0504, // s_or_b32 s4, s4, s5 + ]; + let words = [TABLE, FROM_HEAP, &width, STORE].concat(); + assert!(build(&words, (8, 0)).is_err()); + let depth = [ + 0x8805_0C05, // s_or_b32 s5, s5, s12 + ]; + let words = [TABLE, FROM_HEAP, SIZES, &depth, STORE].concat(); + assert!(build(&words, (8, 0)).is_err()); +} + +/// A water simulation step runs only while a structured buffer is bound: +/// it tests the record count of a view it never reads. +#[test] +fn the_record_count_of_a_structured_buffer_nothing_reads() { + let words = [TABLE, COUNT, STORE].concat(); + let shader = build(&words, (4, 16)).expect("translates"); + let (data, texel) = ([0u32; 12], [[0.0; 4]; 1]); + // The runtime makes structured views raw. + let views = [ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [3, 0], "{label}"); + } + // A stride of 4 or less may be a typed view's component count. + assert!(build(&words, (4, 4)).is_err()); + assert!(build(&words, (4, 0)).is_err()); +} + +/// As [`the_record_count_of_a_structured_buffer_nothing_reads`], of one the +/// program also reads by index. +#[test] +fn the_record_count_of_a_structured_buffer_read_by_index() { + let load = [ + 0x7E06_0280, // v_mov_b32 v3, 0 + 0xE030_2000, // buffer_load_dword v5, v3, s[8:11], 0 idxen + 0x8002_0503, + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5 + ]; + let words = [TABLE, COUNT, &load, STORE].concat(); + let shader = build(&words, (4, 16)).expect("translates"); + let (mut data, texel) = ([0u32; 12], [[0.0; 4]; 1]); + data[0] = 77; + let views = [ + View::Buffer { + data: &data, + stride: Stride::Raw, + }, + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[..2], [3, 77], "{label}"); + } +} + +/// An upscaler counts its groups in a texture with atomics and sets the +/// counter back with a store of one channel, 16 bits wide. +#[test] +fn a_counter_texture_is_set_by_a_store_of_one_channel() { + let program = |store: [u32; 2], value: u32| { + let words = [ + 0xF40C_0201u32, // s_load_dwordx8 s[8:15], s[2:3], 0 + 0xFA00_0000, + 0x7E00_0280, // v_mov_b32 v0, 0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0283, // v_mov_b32 v2, 3 + 0xF044_3108, // image_atomic_add v2, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002_0200, + value, // v_mov_b32 v3, .. + store[0], + store[1], + 0x7E08_0281, // v_mov_b32 v4, 1 + 0xF044_3108, // image_atomic_add v4, v[0:1], s[8:15] dmask:0x1 2D glc + 0x0002_0400, + 0xBE84_0380, // s_mov_b32 s4, 0 + 0xBE85_0380, // s_mov_b32 s5, 0 + ]; + build(&[TABLE, &words, STORE].concat(), (8, 0)) + }; + // image_store v3, v[0:1], s[8:15] dmask:0x1 2D, with and without d16 + for store in [[0xF020_1108, 0x0002_0300], [0xF020_1108, 0x8002_0300]] { + let shader = program(store, 0x7E06_0289).expect("translates"); // v3 = 9 + let texel = [[0.0; 4]; 1]; + let views = [ + View::UintTextureUav(1, 1), + View::Texture(1, 1, &texel), + View::RawUav(2), + ]; + for (label, got) in run(&shader, &views) { + assert_eq!(got[0], 10, "{label}"); + } + } + // Sixteen bits of a number only the card knows may be signed. + assert!(program([0xF020_1108, 0x8002_0300], 0x7E06_0302).is_err()); // v3 = v2 + // A store of two channels says nothing about the view. + assert!(program([0xF020_1308, 0x0002_0300], 0x7E06_0289).is_err()); +} diff --git a/crates/victory-shader/src/emit/waterfall_tests.rs b/crates/victory-shader/src/emit/waterfall_tests.rs index 365883a..31dadd6 100644 --- a/crates/victory-shader/src/emit/waterfall_tests.rs +++ b/crates/victory-shader/src/emit/waterfall_tests.rs @@ -97,7 +97,7 @@ fn build(words: &[u32], buffers: bool) -> HostShader { /// Runs `shader` with `views` at heap indices 0.. (the UAV last) on the /// hardware GPU and on WARP (each skipped without a device) and returns, /// per one that ran, the UAV's 32 dwords. -fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { +pub(super) fn run(shader: &HostShader, views: &[View]) -> Vec<(&'static str, Vec)> { let samplers = [D3D12_SAMPLER_DESC { Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index db82f33..1bdd117 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -199,6 +199,162 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); } +/// "Some lane is left" of a mask operation as a number: an upscaler's programs wait for +/// other groups in a loop that ends when every lane saw its flag, or after enough rounds: +/// both tests become -1 or 0 and SCC of `timeout | ~waiting` ends it. +#[test] +fn some_lane_of_a_mask_is_a_number_the_whole_wave_agrees_on() { + let native = native(&[ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + 0xD766_0001, + 0x0002_02C1, // v_mbcnt_hi_u32_b32 v1, -1, v1 + 0x7D84_0200, // v_cmp_eq_u32 vcc, s0, v1 + 0x8792_7E6A, // s_and_b64 s[18:19], vcc, exec + 0x8592_80C1, // s_cselect_b64 s[18:19], -1, 0 + 0xBF09_8501, // s_cmp_ge_u32 s1, 5 + 0x8594_80C1, // s_cselect_b64 s[20:21], -1, 0 + 0x8B92_1214, // s_orn2_b64 s[18:19], s[20:21], s[18:19] + 0x8506_8081, // s_cselect_b32 s6, 1, 0 + 0x7E04_0206, // v_mov_b32 v2, s6 + 0xE070_0000, + 0x8002_0200, // buffer_store_dword v2, off, s[8:11], 0 + ]); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = on_64_lanes(&native, &p); + // (lane s0 waits, if there is one; s1 rounds) + for (wait, rounds, done) in [(0, 0, 0), (37, 4, 0), (63, 4, 0), (64, 0, 1), (37, 5, 1), (64, 9, 1)] { + let Some(out) = dispatched(&shader, &[wait, rounds]) else { + return; + }; + assert_eq!(out, done, "lane {wait} after {rounds} rounds"); + } +} + +/// `native` for a host of 64-lane waves. +fn on_64_lanes(native: &NativeProgram, p: &ir::Program) -> HostShader { + let st = structure::structure(p).expect("structure"); + let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(p, native).expect("io::raise"); + let was = lower::TEST_HOST_WAVE.replace(Some(64)); + let lowered = lower::lower(&lower::Parts { + native, + p, + st: &st, + io: &io, + res: &res, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh_stride: 0, + }); + lower::TEST_HOST_WAVE.set(was); + let lowered = lowered.expect("lower"); + assert_eq!(lowered.wave_size, Some(64)); + let shader = HostShader { + stage: HwStage::Cs, + dxil: lowered.dxil, + user_data: lowered.user_data, + samplers: lowered.samplers, + static_samplers: Vec::new(), + root_cbvs: lowered.root_cbvs, + root_srvs: lowered.root_srvs, + root_uavs: lowered.root_uavs, + root_indexed_views: res.root_indexed_views, + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + shader +} + +/// Dword 0 of the UAV after `shader` ran with root constants `constants`; none without a +/// device that takes it. +fn dispatched(shader: &HostShader, constants: &[u32]) -> Option { + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program (waves of 64?): {e}; not run"); + return None; + } + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Constants { + ud[u.index as usize] = constants.get(u.dword as usize).copied().unwrap_or(0); + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out[0][0]) +} + +/// The same sum inside `if (t >= s0) { ... }` on a host of 64-lane waves: the lanes below s0 +/// are elsewhere, and count as +0 in the console's tree. +#[test] +fn a_sum_of_halves_where_not_every_lane_runs_on_a_wave_of_64() { + let mut words = vec![ + 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 + 0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7 + 0x4A0E_0EFF, + 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 + 0x7D86_0000, // v_cmp_le_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0000 | 23, // s_cbranch_execz to the restore of EXEC + ]; + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend_from_slice(&[ + 0x7E00_0207, // v_mov_b32 v0, s7 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let shader = on_64_lanes(&native, &p); + let wide = |h: u16| match h { + 0 => 0.0, + h => f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13), + }; + let narrow = |f: f32| { + if f == 0.0 { + return 0; + } + let b = f.to_bits(); + let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); + let rest = b & 0x1FFF; + (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 + }; + for from in [0u32, 1, 5, 31, 32, 37, 63] { + let mut tree: Vec = (0..64u16).map(|t| if u32::from(t) < from { 0 } else { 0x3C00 + 37 * t }).collect(); + while tree.len() > 1 { + tree = tree.chunks(2).map(|c| narrow(wide(c[0]) + wide(c[1]))).collect(); + } + let Some(out) = dispatched(&shader, &[from]) else { + return; + }; + assert_eq!(out, u32::from(tree[0]), "lanes from {from}"); + } +} + /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 /// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The /// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c..5b659e3 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -242,6 +242,9 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result; 256] = [None; 256]; // the last such use let mut used = [false; 128]; let mut parks: Vec> = Vec::with_capacity(list.len()); let mut written: Vec> = Vec::with_capacity(list.len()); @@ -314,7 +317,7 @@ fn unspill( match reg { Reg::S(c) => used[usize::from(c)] = true, Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, - Reg::V(r) => other[usize::from(r)] = true, + Reg::V(r) => other[usize::from(r)] = Some(parks.len()), Reg::Scc => {} } } @@ -323,16 +326,33 @@ fn unspill( written.push(codes); read.push(from); } - for (i, park) in parks.iter_mut().enumerate() { - if park.is_some_and(|p| other[usize::from(p.1)]) { - *park = None; + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + for reg in 0..256 { + let Some(last) = other[reg] else { continue }; + let of = |p: &Option<(bool, u8, u8, u32)>| p.filter(|p| usize::from(p.1) == reg); + let first = parks.iter().position(|p| of(p).is_some_and(|p| p.0)); + let late = first.is_some_and(|first| { + let end = parks.iter().rposition(|p| of(p).is_some()).unwrap_or(first); + let mut saved = Vec::new(); + last < first + && !(first + 1..=end).any(leader) + && parks[first..=end].iter().filter_map(of).all(|(save, _, _, lane)| { + if save { + saved.push(lane); + } + saved.contains(&lane) + }) + }); + let from = if late { first.unwrap_or(0) } else { parks.len() }; + for park in &mut parks[..from] { + if of(park).is_some() { + *park = None; + } } - let _ = i; } if parks.iter().all(Option::is_none) { return Vec::new(); } - let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); // Lane pairs (register, lower lane) that always move together: each // save of the lower lane is followed, in the same block and before its // register changes, by the save of the next register into the next diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index d63d2b3..6ef558c 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2611,6 +2611,42 @@ pub(crate) mod tests { assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]); } + /// A VGPR a wave reduction used is free again after it: from the first + /// save on it holds parked scalars alone (an upscaler program parks a + /// constant buffer's descriptor that way). + #[test] + fn a_vgpr_used_before_holds_spilled_sgprs_from_its_first_save() { + let before = [ + 0x7E00_0281, // v_mov_b32 v0, 1 + 0x7E02_0300, // v_mov_b32 v1, v0 + ]; + let park = [ + 0xD761_0000, + 0x0001_0609, // v_writelane_b32 v0, s9, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + 0xBE83_0380, // s_mov_b32 s3, 0 + ]; + let load = [ + 0xF40C_0001, + 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + ]; + let words = [&before[..], &park, &load].concat(); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + assert_eq!(r.scalar, [((0, 5), at(0, 0x20))]); + // Still lane reads: a lane restored before it is saved, and a + // register with an ordinary use after the first save. + let restored_first = [&before[..], &park[2..4], &park[..2], &load].concat(); + let used_after = [&before[..], &park, &before[1..], &load].concat(); + for words in [restored_first, used_after] { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 8).unwrap(); + let insts = p.blocks.iter().flat_map(|b| &b.insts); + assert_eq!(insts.filter(|i| i.name() == "v_readlane_b32").count(), 1); + } + } + #[test] fn descriptors_joined_by_control_flow_are_traced_per_edge() { let r = track_words(