diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8888caeda..4a893bc56 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -43,6 +43,9 @@ pub(super) struct Em { /// split wave64: pc → SGPRs whose whole value may be read after that instruction /// (`x64_masks`); a mask written to none of them stays in its half (no exchange) pub x64_whole_live: BTreeMap, + /// compute mode: the group is padded to whole console waves (`partial_waves`), the + /// padding lanes inactive at the start + pub cs_pad: bool, /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, @@ -481,6 +484,7 @@ impl Em { uses_scratch: false, x64_words: 1, x64_whole_live: BTreeMap::new(), + cs_pad: false, upper: None, cur_pc: 0, static_ss: BTreeMap::new(), @@ -496,7 +500,9 @@ impl Em { /// Hardware wave count for Compute / Mesh threadgroups (`None` for other stages). fn compute_or_mesh_hw_waves(&self) -> Option { let threads = match &self.opt.mode { - Mode::Compute(cs) => cs.threads.iter().product::(), + // a padded group launches its padding too (in split wave64, a group of 32 threads or + // fewer padded to 64 is two hardware waves) + Mode::Compute(cs) => self.cs_threads(cs), Mode::Mesh(ms) => ms.threads, _ => return None, }; @@ -4160,10 +4166,21 @@ impl Em { // ---------------------------------------------------------------- whole shader - /// Split wave64: threads of the console's thread group. + /// Compute mode: the threads of the PC group – the console's, or whole console waves of + /// them (`cs_pad`). + fn cs_threads(&self, cs: &super::CsInterface) -> u32 { + let threads: u32 = cs.threads.iter().product(); + if self.cs_pad { + threads.next_multiple_of(if self.opt.wave64 { 64 } else { 32 }) + } else { + threads + } + } + + /// Split wave64: threads of the thread group. fn x64_threads(&self) -> u32 { match &self.opt.mode { - Mode::Compute(cs) => cs.threads.iter().product(), + Mode::Compute(cs) => self.cs_threads(cs), Mode::Mesh(ms) => ms.threads, _ => 64, } @@ -4385,7 +4402,10 @@ impl Em { // thread indices (AMD RDNA4 lays them out in 2 x 2 quads: lanes 0, 1, 4, 5, 8 … // of an 8 x 8 group; NVIDIA differs too), the console does – a hardware wave // takes the next `lanes` console threads as it arrives, lane l the l-th of them - let reorder = !self.x64() && y * z > 1; + // a padded group (`cs_pad`) is declared 1-D and takes its threads the same + // way, so the lanes of its last wave that the console launches are its first + let padded = self.cs_pad.then(|| self.cs_threads(cs)); + let reorder = !self.x64() && (y * z > 1 || padded.is_some()); if reorder { // console threads handed to waves so far: the program's top LDS word while // the waves take their threads (the console's LDS starts undefined; D3D12's @@ -4397,9 +4417,10 @@ impl Em { } } self.safe_barrier_prelude(&mut h); + let [nx, ny, nz] = padded.map_or([x, y, z], |t| [t, 1, 1]); let _ = writeln!( h, - "[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" + "[WaveSize({hw_lanes})]\n[numthreads({nx}, {ny}, {nz})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" ); if self.safe_barrier { h.push_str(" xcl_s_barrier_init(gi);\n"); @@ -4409,7 +4430,7 @@ impl Em { self.x64_entry(&mut h); let _ = writeln!(h, " gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); } else if reorder { - let t = x * y * z; + let t = padded.unwrap_or(x * y * z); let _ = writeln!( h, " if (gi == 0u) XCL_WT = 0u;\n GroupMemoryBarrierWithGroupSync();\n lane_id = WaveGetLaneIndex();\n {{\n bool full = WaveActiveCountBits(true) == {lanes}u;\n uint base = {}u;\n if (WaveIsFirstLane() && full) InterlockedAdd(XCL_WT, {lanes}u, base);\n uint xcl_tid = WaveReadLaneFirst(base) + lane_id;\n gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;\n }}\n GroupMemoryBarrierWithGroupSync(); // all waves have their threads before the program writes LDS", @@ -4434,7 +4455,10 @@ impl Em { // waves in the group: a last, partial wave counts (96 threads: 2 of 64) let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes)); } - let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + // a padded group: the lanes past the console's threads start inactive (`gi` is + // the console thread's index here) + let launched = if padded.is_some() { format!("gi < {}u", x * y * z) } else { "true".into() }; + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}({launched}); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); for &v in &self.vgprs { let init = match v { 0 => "gtid.x", diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 82876f01d..28f635261 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -55,6 +55,7 @@ pub mod dxc; pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; +pub mod partial_waves; pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; @@ -510,11 +511,29 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// compute groups that are not whole console waves + pub pad_waves: PadWaves, +} + +/// A compute group that is not a whole number of console waves (40 threads: one wave64 with +/// lanes 0..39 launched) as a PC group of whole waves, its extra lanes inactive at the start +/// as the console's are: for a program that can tell them (`partial_waves`: it turns them on +/// in EXEC, or writes them with `v_writelane`). Every other program keeps its group. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum PadWaves { + /// where the program can tell; `XCL_CS_PAD_ALL=1` / `XCL_NO_CS_PAD=1` make it `Always` / + /// `Never` (for comparison) + #[default] + WhereSeen, + /// every group that is not whole waves + Always, + /// never: the group as the console declares it + Never, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, pad_waves: PadWaves::WhereSeen } } } @@ -1417,13 +1436,32 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } } let mut em = emit::Em::new(opt.clone()); - em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode // continues from the ES into the GS through s_setpc: left as it is) if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { em.x64_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); } + // a compute group that is not whole console waves: padded to whole waves where the + // program can tell the lanes its last wave does not launch + if let Mode::Compute(cs) = &opt.mode { + let lanes = if opt.wave64 { 64 } else { 32 }; + let threads: u32 = cs.threads.iter().product(); + let pad = match opt.pad_waves { + PadWaves::WhereSeen if std::env::var_os("XCL_NO_CS_PAD").is_some() => PadWaves::Never, + PadWaves::WhereSeen if std::env::var_os("XCL_CS_PAD_ALL").is_some() => PadWaves::Always, + p => p, + }; + em.cs_pad = !threads.is_multiple_of(lanes) + && threads.next_multiple_of(lanes) <= 1024 + && match pad { + PadWaves::Always => true, + PadWaves::Never => false, + PadWaves::WhereSeen => partial_waves::sees_lanes_not_launched(&insts, opt.wave64, threads % lanes).is_some(), + }; + } + // after the padding: the group's hardware waves count its padding + em.configure_round_modes(&insts, branches == 0); // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a // program with a read to change gets the form diff --git a/crates/xcl/src/gpu/recomp/partial_waves.rs b/crates/xcl/src/gpu/recomp/partial_waves.rs new file mode 100644 index 000000000..682d29e8a --- /dev/null +++ b/crates/xcl/src/gpu/recomp/partial_waves.rs @@ -0,0 +1,427 @@ +//! Compute groups that are not whole console waves: can the program tell the lanes its last +//! wave does not launch? +//! +//! A group of 40 threads is one wave64 with lanes 0..39 launched. On the console lanes 40..63 +//! exist all the same: inactive, but `v_writelane` (which ignores EXEC) writes them, and code +//! that turns them on in EXEC – whole-wave code (`s_or_saveexec_b64 s, -1`), `s_not_b64 exec`, +//! `s_wqm_b64 exec` – runs in them: its compares see them, its writes reach them, a later +//! `v_readlane` or DPP step reads them back. A PC thread group of 40 threads has no such +//! lanes. A program that can tell gets them (`Em::cs_pad`: the group padded to whole waves, +//! the padding lanes inactive at the start, as on the console); any other program keeps its +//! group, and its translation, as they are. +//! +//! A program can tell when it has a `v_writelane` to a lane the last wave may not launch, or +//! when EXEC may get a bit outside the launched lanes. The second is a forward data-flow pass +//! over the SGPRs as 32-bit words that are known subsets of the last wave's launched lanes, +//! as a low word (lanes 0..31) and as a high word (lanes 32..63): EXEC is one at the start; a +//! VALU mask (`v_cmp*`, carries) is a subset of EXEC; AND with a subset, OR / XOR of two, the +//! saveexec forms, moves and selects keep the property; every other value is taken to have +//! any bit. Conservative: where it cannot follow (an indirect jump, a value from memory) the +//! program is padded, which is exact, only more threads. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::upper_lanes::{is_valu, sgpr_outputs, slot, successors}; +use crate::gpu::rdna2::{self, Decoded}; + +/// What is known of a 32-bit word: `LO` – its bits are launched lanes when it is a low word, +/// `HI` – when it is a high word. +type Sub = u8; +const LO: Sub = 1; +const HI: Sub = 2; + +#[derive(Clone, PartialEq)] +struct State { + s: [Sub; 128], + /// launched lanes of the last wave as (low, high) words + launched: (u32, u32), +} + +impl State { + fn of(&self, v: u32) -> Sub { + (if v & !self.launched.0 == 0 { LO } else { 0 }) | (if v & !self.launched.1 == 0 { HI } else { 0 }) + } + + /// What any value is. + fn any(&self) -> Sub { + self.of(!0) + } + + fn entry(wave64: bool, launched: u32) -> State { + let mask = if launched >= 64 { !0u64 } else { (1u64 << launched) - 1 }; + let mut st = State { s: [0; 128], launched: (mask as u32, (mask >> 32) as u32) }; + st.s = [st.any(); 128]; + st.s[125] = LO | HI; // NULL + st.s[126] |= LO; + if wave64 { + st.s[127] |= HI; + } + st + } + + fn join(&self, o: &State) -> State { + let mut s = self.s; + for (a, b) in s.iter_mut().zip(o.s) { + *a &= b; + } + State { s, launched: self.launched } + } + + fn set(&mut self, r: u64, w: Sub) { + if r < 128 && r != 125 { + self.s[r as usize] = w; + } + } + + /// A 64-bit write: to NULL (125) it writes nothing, not 126 (EXEC_LO) either. + fn set64(&mut self, r: u64, (lo, hi): (Sub, Sub)) { + if r != 125 { + self.set(r, lo); + self.set(r + 1, hi); + } + } + + /// A 32-bit scalar source (operand code). + fn src32(&self, d: &Decoded, code: u64) -> Sub { + match code { + 0..=127 => self.s[code as usize], + 128..=192 => self.of((code - 128) as u32), + 193..=208 => self.of((-((code - 192) as i32)) as u32), + 255 => d.literal.map_or(self.any(), |l| self.of(l)), + _ => self.any(), + } + } + + /// A 64-bit scalar source (operand code) as (low, high) words; a 32-bit literal is the + /// low word of an integer operand, inline integers are sign-extended (as `Em::code64`). + fn src64(&self, d: &Decoded, code: u64) -> (Sub, Sub) { + match code { + 0..=123 | 126 => (self.s[code as usize], self.s[code as usize + 1]), + 125 => (LO | HI, LO | HI), + 128..=192 => (self.of((code - 128) as u32), self.of(0)), + 193..=208 => (self.of((-((code - 192) as i32)) as u32), self.of(!0)), + 255 => (d.literal.map_or(self.any(), |l| self.of(l)), self.of(0)), + _ => (self.any(), self.any()), + } + } + + /// A bitwise SALU operation by its name's second part (`S_ANDN2_SAVEEXEC_B64` → "ANDN2"): + /// a AND b is a subset of either, a OR / XOR b of what both are subsets of, a AND NOT b + /// of a; the forms that invert their result or an OR operand may set any bit. + fn bitop(&self, op: &str, a: Sub, b: Sub) -> Option { + Some(match op { + "AND" => a | b, + "OR" | "XOR" => a & b, + "ANDN2" => a, + "ANDN1" => b, + "ORN2" | "NAND" | "NOR" | "XNOR" | "ORN1" => self.any(), + _ => return None, + }) + } +} + +/// One instruction's effect. +fn step(d: &Decoded, st: &mut State, wave64: bool) { + let name = d.inst.name; + let fv = |f: &str| rdna2::field_value(d.enc, &d.words, f).unwrap_or(0); + let any = st.any(); + if name.starts_with("S_MOVREL") { + // s_movreld / s_movrelsd_2 write s[dst + m0]: any SGPR up to VCC (`x64_masks::uses`) + for r in 0..124 { + st.set(r, any); + } + return; + } + let op = name.split('_').nth(1).unwrap_or(""); + let b64 = name.ends_with("_B64"); + if name.contains("SAVEEXEC") || name.contains("WREXEC") { + // a wave32 program's _B64 forms are its _B32 ones, as `Em` translates them: EXEC_HI + // and the pair's high word are not written + let b64 = b64 && wave64; + let s0 = if b64 { st.src64(d, fv("SSRC0")) } else { (st.src32(d, fv("SSRC0")), any) }; + let (el, eh) = (st.s[126], st.s[127]); + let nl = st.bitop(op, s0.0, el).unwrap_or(any); + let nh = st.bitop(op, s0.1, eh).unwrap_or(any); + let dst = fv("SDST"); + let wr = name.contains("WREXEC"); + st.s[126] = nl; + if b64 { + st.s[127] = nh; + st.set64(dst, if wr { (nl, nh) } else { (el, eh) }); + } else { + st.set(dst, if wr { nl } else { el }); + } + return; + } + if d.enc.name == "ENC_SOP1" || d.enc.name == "ENC_SOP2" { + let dst = fv("SDST"); + let a = |st: &State| if b64 { st.src64(d, fv("SSRC0")) } else { (st.src32(d, fv("SSRC0")), any) }; + let b = |st: &State| if b64 { st.src64(d, fv("SSRC1")) } else { (st.src32(d, fv("SSRC1")), any) }; + let both = |x: (Sub, Sub), y: (Sub, Sub)| (x.0 & y.0, x.1 & y.1); + let r: Option<(Sub, Sub)> = match op { + "MOV" if d.enc.name == "ENC_SOP1" && (name == "S_MOV_B32" || name == "S_MOV_B64") => Some(a(st)), + "CMOV" if d.enc.name == "ENC_SOP1" => Some(both(a(st), (st.s[dst.min(127) as usize], st.s[(dst + 1).min(127) as usize]))), + "CSELECT" => Some(both(a(st), b(st))), + _ if d.enc.name == "ENC_SOP2" && (name.ends_with("_B32") || b64) => { + let (x, y) = (a(st), b(st)); + st.bitop(op, x.0, y.0).zip(st.bitop(op, x.1, y.1)) + } + _ => None, + }; + if let Some((lo, hi)) = r { + if b64 { + st.set64(dst, (lo, hi)); + } else { + st.set(dst, lo); + } + return; + } + } + let valu = is_valu(d); + let (el, eh) = (st.s[126], st.s[127]); + for (r, n) in sgpr_outputs(d) { + if valu && n == 2 { + // a lane mask (v_cmpx: EXEC itself): the bits of inactive lanes are 0. A wave32 + // program's mask is its low word only + if wave64 { + st.set64(r, (el, eh)); + } else { + st.set(r, el); + } + } else { + for k in r..r + n { + st.set(k, any); + } + } + } +} + +/// Why the program can tell the lanes the last wave of its group does not launch (None: it +/// cannot). `insts`: the program in address order, far jumps resolved; `launched`: the lanes +/// that wave does launch (1 .. wave size - 1). +pub fn sees_lanes_not_launched(insts: &[Decoded], wave64: bool, launched: u32) -> Option<&'static str> { + let lanes = if wave64 { 64 } else { 32 }; + if insts.is_empty() || launched == 0 || launched >= lanes { + return None; + } + // `v_writelane` ignores EXEC: a lane that was not launched is written on the console + if insts.iter().any(|d| d.inst.name == "V_WRITELANE_B32" && !slot(d).is_some_and(|(_, l)| l & (lanes - 1) < launched)) { + return Some("v_writelane to a lane the last wave may not launch"); + } + let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let succ = successors(insts, &pcs); + let mut at: Vec> = vec![None; insts.len()]; + at[0] = Some(State::entry(wave64, launched)); + let mut work = BTreeSet::from([0usize]); + while let Some(i) = work.pop_first() { + let mut st = at[i].clone().expect("queued with a state"); + step(&insts[i], &mut st, wave64); + if st.s[126] & LO == 0 || (wave64 && st.s[127] & HI == 0) { + return Some("EXEC may turn on lanes the last wave does not launch"); + } + let Some(s) = &succ[i] else { + return Some("an indirect jump: EXEC is not followed"); + }; + for &j in s { + let new = match &at[j] { + None => st.clone(), + Some(old) => old.join(&st), + }; + if at[j].as_ref() != Some(&new) { + at[j] = Some(new); + work.insert(j); + } + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; + type I = (&'static str, &'static str, &'static [(&'static str, u64)]); + const ENDPGM: I = ("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)]); + const CMP: I = ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]); + + fn program(lines: &[I]) -> Vec { + decoded(lines.iter().flat_map(|(n, e, f)| encode(n, e, f, None).unwrap()).collect()) + } + + fn decoded(bytes: Vec) -> Vec { + let mut out = Vec::new(); + let mut off = 0usize; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + out.push(d); + } + rdna2::resolve_far_jumps(&mut out); + out + } + + fn sees(lines: &[I], launched: u32) -> bool { + sees_lanes_not_launched(&program(lines), true, launched).is_some() + } + + #[test] + fn if_else_and_loop_masks_stay_in_the_launched_lanes() { + // if (vcc) … else … end, as the console compiler writes it + let if_else: &[I] = &[ + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 129)]), + ("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 0)]), + ("S_XOR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 130)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 0)]), + ENDPGM, + ]; + // a loop that lanes leave one by one: s[4:5] collects them, EXEC loses them + let a_loop: &[I] = &[ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 128)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 126)]), + CMP, + ("S_AND_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 126), ("SSRC1", 106)]), + ("S_OR_B64", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 4)]), + ("S_ANDN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 4)]), + ("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", 0xFFFB)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 6)]), + ENDPGM, + ]; + for launched in [1, 10, 20, 32, 40, 63] { + assert!(!sees(if_else, launched), "if / else, {launched} lanes"); + assert!(!sees(a_loop, launched), "loop, {launched} lanes"); + assert!(!sees(&[("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)]), ENDPGM], launched), "v_cmpx, {launched} lanes"); + } + } + + #[test] + fn exec_turning_on_other_lanes_is_seen() { + let widen: [&[I]; 7] = [ + &[("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)])], + &[("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])], + &[("S_NOT_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)])], + &[("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)])], + &[("S_ORN2_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 106)])], + // a mask from the program's arguments, and one from a scalar load + &[("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 8)])], + &[("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 4), ("OFFSET", 0), ("SOFFSET", 125)]), ("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 12)])], + ]; + for w in widen { + let mut l = vec![CMP]; + l.extend_from_slice(w); + l.push(ENDPGM); + for launched in [10, 40] { + assert!(sees(&l, launched), "{} with {launched} lanes", w.last().unwrap().0); + } + } + } + + #[test] + fn a_wave32_saveexec_b64_writes_one_word() { + // in a wave32 program `s_and_saveexec_b64 s[4:5]` writes s4 only (as the translation + // does): s5 keeps the program's argument, and EXEC_LO taken from it may hold any lane + let l: &[I] = &[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 126)]), + CMP, + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 5)]), + ENDPGM, + ]; + assert!(sees_lanes_not_launched(&program(l), false, 20).is_some()); + // the same from s4, the word it does write, stays in the launched lanes + let l: &[I] = &[l[0], l[1], l[2], ("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 4)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(l), false, 20).is_none()); + } + + #[test] + fn a_saveexec_to_null_that_widens_exec_is_seen() { + // EXEC_HI = 0, then `s_or_saveexec_b64 null, 0xFFFFFFFF`: lanes 20..31 turn on. The + // pair's high word must not land in EXEC_LO (s126) and hide that + let widen = [ + encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)], None), + encode("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 125), ("SSRC0", 255)], Some(!0)), + encode("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)], None), + ]; + let widen = decoded(widen.into_iter().flat_map(Result::unwrap).collect()); + assert!(sees_lanes_not_launched(&widen, true, 20).is_some()); + } + + #[test] + fn masks_discarded_into_null_leave_exec_alone() { + // EXEC stays inside the launched lanes + let narrow: [&[I]; 3] = [ + &[CMP, ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 125), ("SSRC0", 106)])], + &[CMP, ("S_AND_B64", "ENC_SOP2", &[("SDST", 125), ("SSRC0", 126), ("SSRC1", 106)])], + &[("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 125), ("SRC0", V), ("SRC1", V + 1)])], + ]; + let mut seen = Vec::new(); + for n in narrow { + let mut l = n.to_vec(); + l.push(ENDPGM); + for launched in [20, 40] { + if sees(&l, launched) { + seen.push(format!("{} with {launched} lanes", n.last().unwrap().0)); + } + } + } + assert!(seen.is_empty(), "{seen:?}"); + } + + #[test] + fn constants_count_by_their_bits() { + // exec = 15 (lanes 0..3): inside 10 or 4 launched lanes, not inside 3 + let low8: &[I] = &[("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 128 + 15)]), ENDPGM]; + assert!(!sees(low8, 10) && !sees(low8, 4) && sees(low8, 3)); + // the high word alone: 1 = lane 32, launched from 33 lanes on + let hi: &[I] = &[("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 129)]), ENDPGM]; + assert!(sees(hi, 32) && !sees(hi, 33)); + // the low word of a wave of 40 lanes is whole: any value is inside it + let lo: &[I] = &[("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 8)]), ENDPGM]; + assert!(!sees(lo, 40) && sees(lo, 31)); + } + + #[test] + fn a_wider_exec_on_one_path_is_seen() { + // s_cbranch_scc0 → skip; s_mov_b64 s[2:3], -1; skip: s_and_b64 exec, exec, s[2:3] is + // fine either way, s_or_b64 is not + let with = |last: I| -> Vec { + vec![ + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 128)]), + ("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 193)]), + last, + ENDPGM, + ] + }; + assert!(!sees(&with(("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)])), 40)); + assert!(sees(&with(("S_OR_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)])), 40)); + } + + #[test] + fn v_writelane_to_a_lane_that_may_be_missing_is_seen() { + let lane5: &[I] = &[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 128 + 5)]), ENDPGM]; + let lane20: &[I] = &[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 128 + 20)]), ENDPGM]; + let lane37: &[I] = &[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 128 + 37)]), ENDPGM]; + assert!(!sees(lane5, 20) && sees(lane20, 20) && sees(lane37, 20)); + // a wave32 program's lane 37 is lane 5 + assert!(sees_lanes_not_launched(&program(lane37), false, 20).is_none()); + // a lane from an SGPR: any lane + assert!(sees(&[("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 6)]), ENDPGM], 20)); + } + + #[test] + fn whole_waves_and_wave32_programs() { + let whole_wave: &[I] = &[("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(whole_wave), true, 0).is_none(), "no partial wave"); + // a wave32 program: EXEC is s126 alone, s127 is data + let w32: &[I] = &[("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 193)]), CMP, ("S_AND_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(w32), false, 20).is_none()); + let w32_wide: &[I] = &[("S_OR_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 193)]), ENDPGM]; + assert!(sees_lanes_not_launched(&program(w32_wide), false, 20).is_some()); + } +} diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index c63f8be85..3a416c130 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -482,7 +482,7 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_CS_PAD_ALL", "XCL_NO_CS_PAD"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -941,7 +941,7 @@ mod shader_cache_tests { #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_CS_PAD_ALL", "XCL_NO_CS_PAD"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name)); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 56d71f0d1..ddd7687bf 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4,7 +4,7 @@ //! as wave32 programs, and only need a GPU and DXC. use super::runner::{self, KernelState}; -use super::{translate, Mode, Options}; +use super::{translate, Mode, Options, PadWaves}; use crate::gpu::rdna2::encode; /// A GPU and DXC for the instruction tests. Wave64 programs run natively where the adapter @@ -7614,3 +7614,321 @@ fn jumps_to_outer_loop_heads_are_structured() { println!("{structured} of 120 programs structured ({entered} jumps into a loop), {ran} run both ways"); assert!(structured >= 100 && entered > 20, "{structured} structured, {entered} jumps into loops"); } + +// ---- compute groups that are not whole waves ---- + +fn cs_of(threads: [u32; 3], tg_size: bool) -> super::CsInterface { + super::CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size, tid_components: 3 } +} + +/// A compute program that can tell the lanes its last, partial wave did not launch +/// (`partial_waves`): on the console they exist, inactive – code that turns them on in EXEC +/// runs in them (a compare of a register with itself is true there whatever it holds, `v_mov` +/// writes them) and `v_writelane` writes them whatever EXEC is. v0 = thread index in the +/// group (s1 = x, s2 = x · y of the group). Each thread stores at s0 + 16 · thread: the bits +/// of `v_cmp_eq_u32 vcc, v0, v0` after `s_not exec, exec` and after `s_or_saveexec s, -1`, +/// the wave's last lane of a VGPR written with EXEC = -1, and a lane `v_writelane` wrote. +fn lanes_not_launched_program(wave64: bool) -> Vec { + let (b, last) = if wave64 { ("B64", 63) } else { ("B32", 31) }; + let s1 = |n: &str, d: u64, s: u64| ins(&format!("{n}_{b}"), "ENC_SOP1", &[("SDST", d), ("SSRC0", s)], None); + let all = || ins("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 0)], None); + let lane = |n: &str, d: u64, s: u64, l: u64| ins(n, "ENC_VOP3", &[("VDST", d), ("SRC0", s), ("SRC1", 128 + l)], None); + let mut parts = vec![ + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 0), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)], None), + s1("S_MOV", 30, 126), + s1("S_NOT", 126, 126), + all(), + s1("S_BCNT1_I32", 20, 106), + s1("S_MOV", 126, 30), + s1("S_OR_SAVEEXEC", 12, 193), + all(), + s1("S_BCNT1_I32", 21, 106), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 9), ("SRC0", 135)], None), + s1("S_MOV", 126, 30), + lane("V_READLANE_B32", 22, V + 9, last), + lane("V_WRITELANE_B32", 10, 128 + 33, last - 1), + lane("V_READLANE_B32", 23, V + 10, last - 1), + ]; + for k in 0..4 { + parts.push(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 24 + k), ("SRC0", 20 + k)], None)); + } + parts.extend([ + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 132), ("VSRC1", 0)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 30), ("SRC0", 0), ("VSRC1", 30)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 30), ("DATA", 24), ("SADDR", 0x7D)], None), + ]); + program_of(&parts) +} + +/// Runs `lanes_not_launched_program` in groups of each of `groups`' dimensions: one line per +/// console wave whose threads did not all store what the console's would (the ISA's +/// definition, not a measurement), and per group in which a thread the console does not +/// have stored anything. +fn lanes_not_launched_mismatches(groups: &[[u32; 3]], wave64: bool, pad_waves: PadWaves) -> Vec { + let (base, lanes) = (0x100usize, if wave64 { 64 } else { 32 }); + let code = lanes_not_launched_program(wave64); + let mut bad = Vec::new(); + for &dims in groups { + let threads = dims.iter().product::(); + let t = translate(&code, &on_gpu(Options { mode: Mode::Compute(cs_of(dims, false)), wave64, pad_waves, ..Default::default() })).unwrap(); + assert!(t.complete(), "{dims:?}: {:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{dims:?}: {e}")); + let mem = vec![0xDEAD_BEEFu32; (base + threads.next_multiple_of(lanes) as usize * 16) / 4]; + let out = runner::dispatch(&dxil, [1, 1, 1], &[base as u32, dims[0], dims[0] * dims[1]], &mem).unwrap_or_else(|e| panic!("{dims:?}: {e}")); + for w in 0..threads.div_ceil(lanes) { + let n = (threads - w * lanes).min(lanes); + let want = [lanes - n, lanes, 7, 33]; + let mut got: Vec<[u32; 4]> = (w * lanes..w * lanes + n).map(|tid| out[base / 4 + tid as usize * 4..][..4].try_into().unwrap()).collect(); + got.dedup(); + if got != [want] { + bad.push(format!("{pad_waves:?} | group {dims:?} wave {w} ({n} lanes) | want {want:?} | got {got:?}")); + } + } + if out[base / 4 + threads as usize * 4..].iter().any(|&x| x != 0xDEAD_BEEF) { + bad.push(format!("{pad_waves:?} | group {dims:?}: a thread past the group's {threads} stored")); + } + } + bad +} + +/// A wave64 compute group that is not whole waves, for a program that can tell: before, a +/// group of 40 threads counted no lane after `s_not_b64 exec, exec` (24 on the console) and +/// 40 after `s_or_saveexec_b64 s, -1` (64), and lost what it wrote to lane 62. In 1-D, 2-D +/// and 3-D groups; without the padding lanes (`PadWaves::Never`: the translation as it was) +/// each of the 11 partial waves differs. +#[test] +fn gpu_wave64_valu_code_in_lanes_not_launched() { + if !gpu_ready() { + return; + } + let groups = [[64, 1, 1], [40, 1, 1], [42, 1, 1], [20, 1, 1], [10, 1, 1], [96, 1, 1], [8, 5, 1], [4, 5, 2], [6, 7, 1], [2, 5, 1], [8, 12, 1], [1, 1, 1]]; + let bad = lanes_not_launched_mismatches(&groups, true, PadWaves::WhereSeen); + assert!(bad.is_empty(), "{bad:#?}"); + let before = lanes_not_launched_mismatches(&groups, true, PadWaves::Never); + assert_eq!(before.len(), 11, "{before:#?}"); +} + +/// The same for wave32 programs: groups of 20, 10, 52 (a full wave and 20 lanes), 5 x 4 and +/// 1 threads; a group of 32 is a whole wave. +#[test] +fn gpu_wave32_valu_code_in_lanes_not_launched() { + if !gpu_ready() { + return; + } + let groups = [[32, 1, 1], [20, 1, 1], [10, 1, 1], [52, 1, 1], [5, 4, 1], [1, 1, 1]]; + let bad = lanes_not_launched_mismatches(&groups, false, PadWaves::WhereSeen); + assert!(bad.is_empty(), "{bad:#?}"); + let before = lanes_not_launched_mismatches(&groups, false, PadWaves::Never); + assert_eq!(before.len(), 5, "{before:#?}"); +} + +/// A 64-bit saveexec to null that turns lanes on (@JGonzalezRodriguez's case): with EXEC_HI 0, +/// `s_or_saveexec_b64 null, 0xFFFFFFFF` in a group of 20 threads turns on lanes 20..31, and a +/// compare of a register with itself counts 32 lanes on the console. When the null write +/// hid this from `partial_waves`, the group was not padded and the count was 20. +#[test] +fn gpu_wave64_saveexec_to_null_turns_on_lanes_not_launched() { + if !gpu_ready() { + return; + } + let code = program_of(&[ + ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 30), ("SSRC0", 126)], None), + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 127), ("SSRC0", 128)], None), + ins("S_OR_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 125), ("SSRC0", 255)], Some(!0)), + ins("V_CMP_EQ_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 0)], None), + ins("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 106)], None), + ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 30)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 20)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 130), ("VSRC1", 0)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 0), ("VSRC1", 2)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7D)], None), + ]); + let base = 0x100usize; + let run = |pad_waves: PadWaves| -> Vec { + let t = translate(&code, &on_gpu(Options { mode: Mode::Compute(cs_of([20, 1, 1], false)), wave64: true, pad_waves, ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let out = runner::dispatch(&dxil, [1, 1, 1], &[base as u32, 20, 20], &vec![0u32; base / 4 + 64]).unwrap(); + out[base / 4..base / 4 + 20].to_vec() + }; + assert_eq!(run(PadWaves::WhereSeen), [32; 20]); + assert_eq!(run(PadWaves::Never), [20; 20], "the unpadded group, for comparison"); +} + +/// Only a program that can tell gets the padded group (`partial_waves`), and only in a group +/// that is not whole waves: every other translation is the one it was. +#[test] +fn compute_groups_are_padded_only_where_the_program_can_tell() { + // the switches (for comparison) replace `WhereSeen` + if std::env::var_os("XCL_CS_PAD_ALL").is_some() || std::env::var_os("XCL_NO_CS_PAD").is_some() { + return; + } + // an if block: EXEC stays inside the launched lanes + let plain = prog(&[ + ("V_CMP_GT_U32", "ENC_VOPC", &[("SRC0", V), ("VSRC1", 1)], None), + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 129)], None), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 6)], None), + ]); + let wide = lanes_not_launched_program(true); + let hlsl = |code: &[u8], dims: [u32; 3], wave64: bool, split: bool, pad: PadWaves| { + let t = translate(code, &Options { mode: Mode::Compute(cs_of(dims, false)), wave64, split_wave64: split, pad_waves: pad, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + t.hlsl + }; + for split in [false, true] { + for dims in [[40, 1, 1], [8, 5, 1], [96, 1, 1], [1, 1, 1]] { + let h = hlsl(&plain, dims, true, split, PadWaves::WhereSeen); + assert!(h.contains(&format!("[numthreads({}, {}, {})]", dims[0], dims[1], dims[2])) && h.contains("(true); exec_lo = e0.x;"), "{dims:?}"); + assert_eq!(h, hlsl(&plain, dims, true, split, PadWaves::Never), "{dims:?}"); + } + // one that can: whole waves, the lanes past its threads inactive at the start + for (dims, padded, threads) in [([40, 1, 1], 64, 40), ([8, 5, 1], 64, 40), ([1, 1, 1], 64, 1), ([4, 4, 6], 128, 96), ([1000, 1, 1], 1024, 1000)] { + let h = hlsl(&wide, dims, true, split, PadWaves::WhereSeen); + assert!(h.contains(&format!("[numthreads({padded}, 1, 1)]")) && h.contains(&format!("(gi < {threads}u); exec_lo = e0.x;")), "{dims:?}"); + // the split form's halves both exist then + assert_eq!(h.contains(&format!("#define XCL_X_THREADS {padded}u")), split, "{dims:?}"); + } + // whole waves are never padded + for dims in [[64, 1, 1], [8, 8, 4]] { + assert_eq!(hlsl(&wide, dims, true, split, PadWaves::Always), hlsl(&wide, dims, true, split, PadWaves::Never), "{dims:?}"); + } + } + // a wave32 program's waves have 32 lanes + let h = hlsl(&lanes_not_launched_program(false), [20, 1, 1], false, false, PadWaves::WhereSeen); + assert!(h.contains("[numthreads(32, 1, 1)]") && h.contains("(gi < 20u); exec_lo = e0.x;")); +} + +/// `s_barrier` in a padded group counts the group's hardware waves with its padding: split +/// wave64 runs a group of 32 threads or fewer, padded to 64, as two hardware waves, and the +/// barrier keeps its group sync (the early-exit-safe form) as for any group of two. +#[test] +fn a_padded_group_barrier_counts_its_padding_waves() { + if std::env::var_os("XCL_SAFE_BARRIER").is_some() { + return; + } + let code = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); + let hlsl = |dims: [u32; 3], split: bool, pad: PadWaves| { + let t = translate(&code, &Options { mode: Mode::Compute(cs_of(dims, false)), wave64: true, split_wave64: split, pad_waves: pad, ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + t.hlsl + }; + // padded to 64 threads: two 32-lane waves split, one 64-lane wave otherwise + for (dims, split, pad, waves) in [ + ([20, 1, 1], true, PadWaves::Always, 2), + ([1, 1, 1], true, PadWaves::Always, 2), + ([40, 1, 1], true, PadWaves::Always, 2), + ([20, 1, 1], true, PadWaves::Never, 1), + ([20, 1, 1], false, PadWaves::Always, 1), + ] { + let h = hlsl(dims, split, pad); + assert_eq!(h.contains("[numthreads(64, 1, 1)]"), pad == PadWaves::Always, "{dims:?} split={split}"); + assert_eq!(h.contains("xcl_s_barrier();"), waves > 1, "{dims:?} split={split} {pad:?}"); + } +} + +/// What a program sees of its group when the group is padded to whole waves is what it sees +/// otherwise: thread ids (1-D, 2-D and 3-D groups), the group id, TG_SIZE, its lane and the +/// launched lanes of its wave, LDS shared across the group around `s_barrier`, and memory – +/// each console thread runs once (an atomic count per group) and no padding lane stores. +/// Wave64 programs (split on 32-lane GPUs: the barrier and the counter-paired forms) and +/// wave32 ones, three groups each. +#[test] +fn gpu_padded_compute_groups_look_the_same_to_the_program() { + if !gpu_ready() { + return; + } + let w64 = [[40u32, 1, 1], [20, 1, 1], [10, 1, 1], [96, 1, 1], [8, 5, 1], [4, 5, 2], [4, 4, 6], [3, 1, 1], [1, 1, 1]]; + let w32 = [[20u32, 1, 1], [10, 1, 1], [52, 1, 1], [5, 4, 1], [1, 1, 1]]; + for (wave64, dims) in w64.map(|d| (true, d)).into_iter().chain(w32.map(|d| (false, d))) { + let lanes: u32 = if wave64 { 64 } else { 32 }; + let (x, xy, n) = (dims[0], dims[0] * dims[1], dims.iter().product::()); + let mut parts = vec![ + // v21 = thread index in the group + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None), + ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 20)], None), + // LDS[4 · thread] = thread + 100; after the barrier, the word of thread n - 1 - thread + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 22), ("SRC0", 130), ("VSRC1", 21)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 23), ("SRC0", 255), ("VSRC1", 21)], Some(100)), + ins("DS_WRITE_B32", "ENC_DS", &[("ADDR", 22), ("DATA0", 23)], None), + ins("S_BARRIER", "ENC_SOPP", &[], None), + ins("V_SUB_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 3), ("VSRC1", 21)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 193), ("VSRC1", 32)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 32), ("SRC0", 130), ("VSRC1", 32)], None), + ins("DS_READ_B32", "ENC_DS", &[("VDST", 29), ("ADDR", 32)], None), + // count[group] += 1 at s0 - 64 + 4 · group + ins("S_SUB_U32", "ENC_SOP2", &[("SDST", 8), ("SSRC0", 0), ("SSRC1", 192)], None), + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 9), ("SSRC0", 128)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 40), ("SRC0", 4)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 40), ("SRC0", 130), ("VSRC1", 40)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 41), ("SRC0", 129)], None), + ins("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 42), ("ADDR", 40), ("DATA", 41), ("SADDR", 8), ("OFFSET", 0), ("GLC", 1)], None), + // the thread id, TG_SIZE (s5), the group id (s4), the lane and the wave's lanes + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 24), ("SRC0", V)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 25), ("SRC0", V + 1)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 26), ("SRC0", V + 2)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 27), ("SRC0", 5)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 28), ("SRC0", 4)], None), + ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 126), ("SRC1", 128)], None), + ]; + if wave64 { + parts.push(ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 30), ("SRC0", 127), ("SRC1", V + 30)], None)); + parts.push(ins("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)], None)); + } else { + parts.push(ins("S_BCNT1_I32_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 126)], None)); + } + parts.extend([ + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 31), ("SRC0", 10)], None), + // out[(group · 256 + thread) · 32]: v24..v27, v28..v31 + ins("S_LSHL_B32", "ENC_SOP2", &[("SDST", 11), ("SSRC0", 4), ("SSRC1", 136)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 11), ("VSRC1", 21)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 133), ("VSRC1", 34)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 0), ("VSRC1", 34)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 35), ("SRC0", 128)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 34), ("DATA", 24), ("SADDR", 0x7D)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 34), ("SRC0", 144), ("VSRC1", 34)], None), + ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 34), ("DATA", 28), ("SADDR", 0x7D)], None), + ]); + let code = program_of(&parts); + let (base, groups) = (0x100usize, 3usize); + let mut tg_size = Vec::new(); + for pad in [PadWaves::Never, PadWaves::Always, PadWaves::WhereSeen] { + let what = format!("{dims:?}, wave{lanes}, {pad:?}"); + let t = translate(&code, &on_gpu(Options { mode: Mode::Compute(cs_of(dims, true)), wave64, pad_waves: pad, ..Default::default() })).unwrap(); + assert!(t.complete(), "{what}: {:?}", t.unsupported_why); + let padded = t.hlsl.contains(&format!("[numthreads({}, 1, 1)]", n.next_multiple_of(lanes))); + // nothing here turns on a lane the wave did not launch: only `Always` pads + // (`XCL_CS_PAD_ALL` makes `WhereSeen` that) + assert_eq!(padded, pad == PadWaves::Always || pad == PadWaves::WhereSeen && std::env::var_os("XCL_CS_PAD_ALL").is_some(), "{what}"); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{what}: {e}")); + let mut mem = vec![0xDEAD_BEEFu32; (base + groups * 256 * 32) / 4]; + mem[..base / 4].fill(0); + let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &[base as u32, x, xy, n], &mem).unwrap_or_else(|e| panic!("{what}: {e}")); + let mut tg = Vec::new(); + for g in 0..groups { + assert_eq!(out[(base - 64) / 4 + g], n, "{what}: threads of group {g} that ran"); + for tid in 0..256u32 { + let at = (base + (g * 256 + tid as usize) * 32) / 4; + let got = &out[at..at + 8]; + if tid >= n { + assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "{what}: group {g}, a thread {tid} stored"); + continue; + } + let (wave, lane) = (tid / lanes, tid % lanes); + assert_eq!(&got[..3], &[tid % x, tid / x % dims[1], tid / xy], "{what}: group {g} thread {tid}: thread id"); + assert_eq!(got[3] >> 6, wave, "{what}: group {g} thread {tid}: wave in TG_SIZE"); + assert_eq!(got[4], g as u32, "{what}: thread {tid}: group id"); + assert_eq!(got[5], n - 1 - tid + 100, "{what}: group {g} thread {tid}: LDS word of thread {}", n - 1 - tid); + assert_eq!(got[6], lane, "{what}: group {g} thread {tid}: lane"); + assert_eq!(got[7], (n - wave * lanes).min(lanes), "{what}: group {g} thread {tid}: lanes of its wave"); + tg.push(got[3]); + } + } + tg_size.push(tg); + } + assert!(tg_size[0] == tg_size[1] && tg_size[0] == tg_size[2], "{dims:?}, wave{lanes}: TG_SIZE with and without padding"); + } +} diff --git a/crates/xcl/src/gpu/recomp/upper_lanes.rs b/crates/xcl/src/gpu/recomp/upper_lanes.rs index d6981b2fb..78af877b0 100644 --- a/crates/xcl/src/gpu/recomp/upper_lanes.rs +++ b/crates/xcl/src/gpu/recomp/upper_lanes.rs @@ -484,7 +484,7 @@ fn evaluate(d: &Decoded, st: &State, vdst: u64) -> Option<[Hi; 32]> { } /// SGPRs an instruction may write (first register, count), from its output operands. -fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { +pub(super) fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { let mut out = Vec::new(); for o in d.ienc.operands.iter().filter(|o| o.output) { let n = (o.size as u64).div_ceil(32).max(1); @@ -494,7 +494,8 @@ fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { (_, "OPR_SDST_M0") => out.push((124, 1)), (Some(f), ty) if !ty.starts_with("OPR_VGPR") && ty != "OPR_SRC_VGPR" => { let v = rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); - if v < 128 { + // 125: NULL, written by nothing + if v < 128 && v != 125 { out.push((v, n)); } } @@ -506,13 +507,17 @@ fn sgpr_outputs(d: &Decoded) -> Vec<(u64, u64)> { if let Some(e) = ext_encoding(d) { let x = |n: &str| rdna2::field_value(e, &d.words, n).unwrap_or(0); out.retain(|&(r, _)| r != 106); - out.push(if x("SD") == 1 { (x("SDST"), 2) } else { (106, 2) }); + match x("SD") { + 1 if x("SDST") == 125 => {} + 1 => out.push((x("SDST"), 2)), + _ => out.push((106, 2)), + } } } out } -fn is_valu(d: &Decoded) -> bool { +pub(super) fn is_valu(d: &Decoded) -> bool { d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP") } @@ -713,7 +718,7 @@ fn classify(d: &Decoded, st: &State) -> Option<(Read, Option<(u64, u32)>)> { } /// Successors of each instruction (index); None: unknown (an indirect jump). -fn successors(insts: &[Decoded], pcs: &BTreeMap) -> Vec>> { +pub(super) fn successors(insts: &[Decoded], pcs: &BTreeMap) -> Vec>> { insts .iter() .enumerate()