diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 65c1a51b00..f847bf1285 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -554,6 +554,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { key.push(sampler.is_some() as u64); key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); key.push(match lw.mask_batch_end.get(&d.pc) { None => 0, Some(false) => 1, Some(true) => 2 }); + key.push(lw.uniform_reads.contains(&d.pc) as u64); // what `Lw::write_mask` asks of this address, for any register a mask can go to if let Some(&l) = lw.whole_live.get(&d.pc) { let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); diff --git a/crates/xcl/src/gpu/dxil/idioms.rs b/crates/xcl/src/gpu/dxil/idioms.rs new file mode 100644 index 0000000000..ef4e27457d --- /dev/null +++ b/crates/xcl/src/gpu/dxil/idioms.rs @@ -0,0 +1,693 @@ +//! Idioms of a split wave64 compute or mesh program (`docs/wave64-on-wave32.md`, "Idioms"): +//! instruction sequences around a whole-wave value that are exact without its exchange. +//! +//! A local vote: a forward `s_cbranch_execz` over lane work only. A half none of whose lanes +//! is in EXEC loses nothing by skipping that work, whatever the other half's lanes do, so the +//! branch reads each half's own word of EXEC and the compare behind it stays in its half. +//! Where the skipped side ends at `s_or_b64 exec, exec, s` of the EXEC saved before the vote, +//! EXEC there is within `s`, so the result is `s` and does not ask for EXEC whole. +//! +//! A uniform first lane: `v_readfirstlane` of a value every lane of EXEC holds (the compiler's +//! scalar arithmetic through a VGPR). A half with a lane in EXEC reads its own; the halves +//! exchange only when one of them has none. +use std::collections::{BTreeMap, BTreeSet}; + +use super::cfg::{Cfg, Term}; +use super::lower::Lw; +use super::mask_exchange::{self, Uses, EXEC, SCC}; +use super::module::{BinOp, Pred, Value}; +use crate::gpu::{rdna2::{self, Decoded, Variant}, recomp::x64_masks}; + +/// `XCL_WAVE64_IDIOMS=0` exchanges every such value. +pub fn enabled() -> bool { + #[cfg(test)] + if let Some(v) = IDIOMS_IN_TEST.with(|c| c.get()) { + return v; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WAVE64_IDIOMS").map_or(true, |v| v.trim() != "0")) +} + +#[cfg(test)] +thread_local! { + pub(super) static IDIOMS_IN_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// SOPK instructions that read and write what their operands say, no more. +pub(super) fn plain_sopk(name: &str) -> bool { + enabled() && (matches!(name, "S_MOVK_I32" | "S_CMOVK_I32" | "S_ADDK_I32" | "S_MULK_I32" | "S_VERSION") || name.starts_with("S_CMPK_") || name.starts_with("S_WAITCNT_")) +} + +struct Vote { + branch: usize, + join: u64, + /// compares of the skipped side: each must stay in its half + masks: Vec<(usize, u128)>, + writes_exec: bool, + /// the join is `s_or_b64 exec, exec, s` of the EXEC saved before the vote: `s` again + restore: Option, +} + +fn field(d: &Decoded, f: &str) -> Option { + rdna2::field_value(d.enc, &d.words, f) +} + +fn valu(d: &Decoded) -> bool { + d.enc.name.starts_with("ENC_VOP") || d.enc.name.starts_with("VOP") +} + +/// Every SGPR `d` may write, SCC included. +fn written(d: &Decoded) -> u128 { + if d.inst.name.contains("MOVREL") { + return !0; + } + let scc = d.ienc.operands.iter().any(|o| o.ty == "OPR_SSRC_SPECIAL_SCC" && o.output); + rdna2::sgpr_uses(d).1.into_iter().fold(x64_masks::uses(d).1 | if scc { SCC } else { 0 }, |w, r| w | 1 << r) +} + +/// The SGPRs an instruction of a skipped side may write, None for one a half cannot skip alone. +fn lane_work(d: &Decoded) -> Option { + let n = d.inst.name; + let ok = match d.enc.name { + "ENC_SOPP" => matches!(n, "S_NOP" | "S_WAITCNT" | "S_WAITCNT_DEPCTR" | "S_BRANCH") || n.starts_with("S_CBRANCH_"), + "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => { + !["MOVREL", "SETPC", "SWAPPC", "RFE", "CALL", "GETREG", "SETREG", "WREXEC", "GPR_IDX", "SETKILL", "SETHALT"].iter().any(|k| n.contains(k)) + } + "ENC_SMEM" => (n.starts_with("S_LOAD_") || n.starts_with("S_BUFFER_LOAD_")) && field(d, "GLC") != Some(1) && field(d, "DLC") != Some(1), + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_EXP" => true, + _ => valu(d) && !matches!(n, "V_READLANE_B32" | "V_READFIRSTLANE_B32" | "V_WRITELANE_B32") && !n.contains("MOVREL"), + }; + ok.then(|| written(d)) +} + +/// Reads of any kind, a lane's own bit of a mask included, and the registers replaced. +fn any_use(d: &Decoded, u: Uses) -> Uses { + let (whole, written) = x64_masks::uses(d); + if u.read == !0 { + return Uses { read: whole | SCC | EXEC, written: written & !SCC, ..Default::default() }; + } + let mut read = u.read | u.inputs | whole; + if u.save != 0 { + read |= EXEC; + } + if matches!(d.inst.name, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") { + read |= 3 << 106; + if let Some(r) = field(d, "SRC2").filter(|&r| r <= 126) { + read |= 3 << r; + } + } + Uses { read, written: u.written, ..Default::default() } +} + +/// Bit n of `empty`: the pair s[n], s[n + 1] has no lane of a half that has none in EXEC at +/// the vote. The pairs still known empty after `d`, which may write `written`. +fn empty_after(d: &Decoded, u: Uses, written: u128, empty: u128) -> u128 { + let is = |f: &str| field(d, f).is_some_and(|r| r == 128 || (r <= 126 && empty >> r & 1 == 1)); + let dst = match d.inst.name { + "S_AND_SAVEEXEC_B64" => field(d, "SDST").filter(|_| empty >> 126 & 1 == 1), + "S_AND_B64" => field(d, "SDST").filter(|_| is("SSRC0") || is("SSRC1")), + "S_ANDN2_B64" | "S_MOV_B64" => field(d, "SDST").filter(|_| is("SSRC0")), + "S_OR_B64" | "S_XOR_B64" => field(d, "SDST").filter(|_| is("SSRC0") && is("SSRC1")), + _ => mask_exchange::cmp_dst(d, u).filter(|_| empty >> 126 & 1 == 1).map(|m| m.trailing_zeros() as u64), + }; + let keeps_exec = d.inst.name == "S_AND_SAVEEXEC_B64" && empty >> 126 & 1 == 1; + let mut empty = empty & !(written | written >> 1); + if let Some(r) = dst.filter(|&r| r <= 126) { + empty |= 1 << r; + } + if keeps_exec { + empty |= 1 << 126; + } + empty +} + +/// The vote at `branch` (an `s_cbranch_execz` to the instruction `end`), if the instructions it +/// jumps over are lane work that leaves EXEC without a lane of a half that entered with none +/// and no scalar a later instruction reads (`live`: any read, at the join). +fn vote(cfg: &Cfg, info: &[Uses], x64: &BTreeMap, branch: usize, end: usize, live: u128) -> Option { + let index_of = |pc: u64| cfg.insts.binary_search_by_key(&pc, |d| d.pc).ok(); + let inside = branch + 1..end; + let mut alone = true; + for d in cfg.insts[..branch].iter().chain(&cfg.insts[end..]) { + match rdna2::branch_target(d).and_then(index_of) { + Some(t) if inside.contains(&t) => return None, + Some(t) if t == branch || t == end => alone = false, + _ => {} + } + } + let mut v = Vote { branch, join: cfg.insts[end].pc, masks: Vec::new(), writes_exec: false, restore: None }; + let mut written_all = 0; + let mut joins: BTreeMap = BTreeMap::new(); + let mut empty = Some(1u128 << 126); + for i in inside { + let d = &cfg.insts[i]; + let written = lane_work(d)?; + written_all |= written; + if let Some(e) = joins.remove(&i) { + empty = Some(empty.map_or(e, |x| x & e)); + } + if valu(d) && written != 0 { + match mask_exchange::cmp_dst(d, info[i]) { + Some(m) => v.masks.push((i, m)), + None if x64.get(&d.pc).is_some_and(|live| live & written == 0) => {} + None => return None, + } + } + let Some(e) = empty else { continue }; + let e = empty_after(d, info[i], written, e); + if e >> 126 & 1 == 0 { + return None; + } + empty = Some(e); + if let Some(t) = rdna2::branch_target(d) { + let t = index_of(t).filter(|&t| t > i && t <= end)?; + joins.entry(t).and_modify(|x| *x &= e).or_insert(e); + if d.inst.name == "S_BRANCH" { + empty = None; + } + } else if d.enc.name == "ENC_SOPP" && d.inst.name.starts_with("S_CBRANCH_") { + return None; + } + } + v.writes_exec = written_all & EXEC != 0; + let saved = branch.checked_sub(1).map(|i| &cfg.insts[i]).filter(|d| alone && d.inst.name == "S_AND_SAVEEXEC_B64") + .and_then(|d| field(d, "SDST")).filter(|&s| s <= 122 && s % 2 == 0 && written_all & (3 << s) == 0); + let j = &cfg.insts[end]; + if let Some(s) = saved.filter(|_| j.inst.name == "S_OR_B64" && field(j, "SDST") == Some(126)) { + let srcs = (field(j, "SSRC0"), field(j, "SSRC1")); + if srcs == (Some(126), Some(s)) || srcs == (Some(s), Some(126)) { + v.restore = Some(end); + } + } + (written_all & !EXEC & live == 0).then_some(v) +} + +/// VALU instructions whose result in a lane is a function of their operands in that lane. +fn lane_arithmetic(d: &Decoded) -> bool { + let n = d.inst.name; + valu(d) && d.variant == Variant::Plain + && !["READLANE", "READFIRSTLANE", "WRITELANE", "MBCNT", "PERMLANE", "REL", "SWAP", "INTERP"].iter().any(|k| n.contains(k)) +} + +/// The `v_readfirstlane`s (by pc) of a value every lane of EXEC holds: lane arithmetic on +/// scalars, on masks with one bit for all of EXEC's lanes and on such values again, with no +/// write of EXEC since the first of it in the block. +pub(super) fn uniform_reads(cfg: &Cfg) -> BTreeSet { + let mut reads = BTreeSet::new(); + for b in cfg.blocks.iter().filter(|_| enabled()) { + let mut vgprs = BTreeSet::new(); + let mut masks = 1u128 << 126; + for d in b.insts.iter().map(|&i| &cfg.insts[i]) { + let name = d.inst.name; + let (mut read, to) = rdna2::vgpr_uses(d); + if name.contains("MAC") || matches!(name, "V_DOT2C_F32_F16" | "V_DOT4C_I32_I8") || d.ienc.operands.iter().any(|o| o.field == Some("VDST") && o.size < 32) { + read.extend(&to); + } + let mask = |f: &str| field(d, f).is_some_and(|r| matches!(r, 128 | 193) || (r <= 126 && masks >> r & 1 == 1)); + let select = d.ienc.operands.iter().filter(|o| o.input && matches!(o.ty, "OPR_VCC" | "OPR_SREG")).all(|o| o.field.map_or(masks >> 106 & 1 == 1, |f| mask(f))); + let w = written(d); + let uniform = lane_arithmetic(d) && select && read.iter().all(|r| vgprs.contains(r)); + if name == "V_READFIRSTLANE_B32" && d.variant == Variant::Plain && read.iter().all(|r| vgprs.contains(r)) { + reads.insert(d.pc); + } + if name.contains("REL") { + vgprs.clear(); + } + for r in to { + if uniform && w == 0 { + vgprs.insert(r); + } else { + vgprs.remove(&r); + } + } + let dst = match name { + "S_CSELECT_B64" | "S_AND_B64" | "S_OR_B64" | "S_XOR_B64" | "S_ANDN2_B64" | "S_ORN2_B64" | "S_NAND_B64" | "S_NOR_B64" | "S_XNOR_B64" => { + field(d, "SDST").filter(|_| mask("SSRC0") && mask("SSRC1")) + } + "S_MOV_B64" | "S_NOT_B64" => field(d, "SDST").filter(|_| mask("SSRC0")), + _ => mask_exchange::cmp_dst(d, mask_exchange::uses(d)).filter(|_| uniform).map(|m| m.trailing_zeros() as u64), + }; + masks &= !(w | w >> 1); + if w & EXEC != 0 { + vgprs.clear(); + masks = 0; + } else if let Some(r) = dst.filter(|&r| r <= 122) { + masks |= 1 << r; + } + masks |= 1 << 126; + } + } + reads +} + +impl Lw { + /// A half's lanes as a mask: `n` of them, from lane 0. + fn lanes_mask(&mut self, n: Value) -> Value { + let k = self.c(32); + let s = self.sub(k, n); + let s = self.andc(s, 31); + let ones = self.c(!0); + let m = self.bin(BinOp::LShr, ones, s); + let none = self.cmpc(Pred::Eq, n, 0); + self.selc(none, 0, m) + } + + /// Split form, `v_readfirstlane` of `v`, which every lane of EXEC (lo, hi) holds: this + /// half's first running lane of EXEC when both halves have one, the exchange otherwise. + pub(super) fn read_first_lane_uniform(&mut self, v: Value, lo: Value, hi: Value) -> super::lower::LResult { + let u = self.upper; + let (mine, theirs) = match self.live_exec { + Some((l, h)) => (self.sel(u, h, l), self.sel(u, l, h)), + None => { + let t = self.s.m.i1c(true); + let n = self.s.wave_all_bit_count(t); + (self.lanes_mask(n), self.lanes_mask(self.xn)) + } + }; + let (own, other) = (self.sel(u, hi, lo), self.sel(u, lo, hi)); + let (own, other) = (self.and(own, mine), self.and(other, theirs)); + let l = self.firstbitlow(own); + let l = self.andc(l, 31); + let r = self.s.wave_read_lane_at(v, l); + let out = self.tmp_var(); + self.wr(out, r); + let (a, b) = (self.cmpc(Pred::Eq, own, 0), self.cmpc(Pred::Eq, other, 0)); + let lone = self.lor(a, b); + let sites = self.exchange_sites; + self.guarded(lone, &mut |lw| { + let l = lw.first_lane(lo, hi); + let r = lw.read_lane_uniform(v, l); + lw.wr(out, r); + Ok(()) + })?; + self.exchange_sites = sites; + Ok(self.rd(out)) + } +} + +fn entry_at(cfg: &Cfg, entry: &[u128], pc: u64) -> u128 { + cfg.blocks.iter().zip(entry).filter(|(b, _)| b.pc == pc).fold(0, |a, (_, &e)| a | e) +} + +fn candidates(cfg: &Cfg, info: &[Uses]) -> Vec { + let votes: Vec<(usize, usize)> = cfg.blocks.iter().filter_map(|b| { + let Term::Cond(i, ..) = b.term else { return None }; + let d = &cfg.insts[i]; + let t = rdna2::branch_target(d).filter(|_| d.inst.name == "S_CBRANCH_EXECZ" && d.far_target.is_none())?; + let end = cfg.insts.binary_search_by_key(&t, |d| d.pc).ok().filter(|&e| e > i)?; + Some((i, end)) + }).collect(); + // an indirect jump could enter a skipped side + if votes.is_empty() || cfg.insts.iter().any(|d| d.inst.flags & rdna2::F_INDIRECT != 0 && d.far_target.is_none()) { + return Vec::new(); + } + let any: Vec = cfg.insts.iter().zip(info).map(|(d, &u)| any_use(d, u)).collect(); + let (live, _) = mask_exchange::demand(cfg, &any); + let x64 = x64_masks::by_pc(&cfg.insts, false); + let mut seen = std::collections::BTreeSet::new(); + votes.into_iter().filter(|&(i, _)| seen.insert(i)) + .filter_map(|(i, end)| vote(cfg, info, &x64, i, end, entry_at(cfg, &live, cfg.insts[end].pc))) + .collect() +} + +/// Takes the EXEC read off every branch that is a local vote and gives the whole demand after +/// each instruction (`mask_exchange::demand`). A vote is local while no compare of its skipped +/// side is exchanged (the halves would meet out of step) and, if that side writes EXEC, EXEC is +/// not read whole at the join. +pub(super) fn local_votes(cfg: &Cfg, info: &mut [Uses]) -> Vec { + let mut votes = if enabled() { candidates(cfg, info) } else { Vec::new() }; + for i in votes.iter().filter_map(|v| v.restore) { + info[i].inputs &= !EXEC; + } + loop { + for v in &votes { + info[v.branch].read &= !EXEC; + } + let (entry, after) = mask_exchange::demand(cfg, info); + let n = votes.len(); + votes.retain(|v| { + let local = v.masks.iter().all(|&(i, m)| after[i] & m == 0) && !(v.writes_exec && entry_at(cfg, &entry, v.join) & EXEC != 0); + if !local { + info[v.branch].read |= EXEC; + } + local + }); + if votes.len() == n { + return after; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::kernel::{self, KernelOptions}; + use crate::gpu::recomp::{runner, CsInterface, KERNEL_SGPRS}; + + fn ins(n: &str, enc: &str, operands: &[(&str, u64)]) -> Vec { + rdna2::encode(n, enc, operands, None).unwrap() + } + fn cmp(name: &str, k: u64) -> Vec { + ins(name, "ENC_VOP3", &[("VDST", 106), ("SRC0", 128 + k), ("SRC1", 256)]) + } + fn vmov(dst: u64, src: u64) -> Vec { + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", dst), ("SRC0", src)]) + } + fn sop2(name: &str, dst: u64, a: u64, b: u64) -> Vec { + ins(name, "ENC_SOP2", &[("SDST", dst), ("SSRC0", a), ("SSRC1", b)]) + } + fn restore() -> Vec { + sop2("S_OR_B64", 126, 126, 4) + } + /// `if (compare) { body }`: EXEC saved in s4, the join left to the caller + fn vote_over(compare: Vec, body: &[Vec]) -> Vec> { + let body = body.concat(); + let mut v = vec![ + compare, + ins("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + ins("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", body.len() as u64 / 4)]), + ]; + v.push(body); + v + } + fn code(parts: &[Vec]) -> Vec { + let mut code = parts.concat(); + code.extend(ins("S_ENDPGM", "ENC_SOPP", &[])); + code + } + fn with_idioms(on: bool, f: impl FnOnce() -> T) -> T { + IDIOMS_IN_TEST.with(|c| c.set(Some(on))); + let r = f(); + IDIOMS_IN_TEST.with(|c| c.set(None)); + r + } + /// whether the compare at the start of `parts` is exchanged + fn exchanged(on: bool, parts: &[Vec]) -> bool { + let cfg = Cfg::build(&code(parts)).unwrap(); + with_idioms(on, || mask_exchange::plan(&cfg).demand[&0] != 0) + } + fn first_lane(dst: u64) -> Vec { + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", dst), ("SRC0", 256)]) + } + + #[test] + fn a_vote_over_lane_work_stays_in_each_half() { + let mut p = vote_over(cmp("V_CMP_GT_U32", 8), &[vmov(4, 170)]); + assert!(!exchanged(true, &p), "no join instruction: the program ends with the narrowed EXEC"); + assert!(exchanged(false, &p)); + p.push(restore()); + p.push(first_lane(10)); + assert!(!exchanged(true, &p), "the restored EXEC is the saved one"); + assert!(exchanged(false, &p)); + let nested = [vmov(4, 170), vote_over(cmp("V_CMP_GT_U32", 4), &[vmov(4, 171)]).concat(), sop2("S_OR_B64", 126, 126, 4)].concat(); + let mut outer = vote_over(cmp("V_CMP_GT_U32", 8), &[nested]); + outer[1] = ins("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 106)]); + outer.push(sop2("S_OR_B64", 126, 126, 6)); + outer.push(first_lane(10)); + assert!(!exchanged(true, &outer), "a vote inside a vote"); + } + + #[test] + fn a_vote_over_more_than_lane_work_is_exchanged() { + let refused = |body: &[Vec], after: &[Vec]| { + let mut p = vote_over(cmp("V_CMP_GT_U32", 8), body); + p.push(restore()); + p.extend(after.iter().cloned()); + exchanged(true, &p) + }; + assert!(!refused(&[vmov(4, 170)], &[])); + assert!(refused(&[first_lane(10)], &[]), "another lane's value: the halves meet"); + assert!(refused(&[ins("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 129), ("SRC1", 128)])], &[]), "a write whatever EXEC is"); + assert!(refused(&[ins("S_BARRIER", "ENC_SOPP", &[])], &[])); + assert!(refused(&[ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 129)])], &[vmov(5, 8)]), "a scalar read after the join"); + assert!(!refused(&[ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 129)]), vmov(5, 8)], &[]), "a scalar of the side alone"); + assert!(refused(&[sop2("S_OR_B64", 126, 126, 4), vmov(4, 170)], &[]), "EXEC widened to lanes the vote left out"); + assert!(refused(&[ins("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 193)])], &[]), "every lane back on"); + assert!(refused(&[cmp("V_CMP_GT_U32", 4), sop2("S_ADD_U32", 8, 106, 107), vmov(5, 8)], &[]), "a mask of the side read as a number"); + // the join is something other than the saved EXEC's return: EXEC read whole after it + let mut p = vote_over(cmp("V_CMP_GT_U32", 8), &[vmov(4, 170)]); + p.push(first_lane(10)); + assert!(exchanged(true, &p)); + // the vote's mask counted + let mut p = vote_over(cmp("V_CMP_GT_U32", 8), &[vmov(4, 170)]); + p.insert(1, ins("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 106)])); + p.push(vmov(5, 8)); + assert!(exchanged(true, &p)); + // a backward branch into the side + let mut p = vote_over(cmp("V_CMP_GT_U32", 8), &[vmov(4, 170), vmov(5, 170)]); + p.push(restore()); + p.push(ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)])); + assert!(exchanged(true, &p)); + } + + /// v4 = 5; if (tid < 8) v4 = 42; if (tid > 40) v4 = 17; if (tid == 70) v4 = 43; + /// then every thread stores v4 with its wave's first lane's v4 << 8 + fn three_votes() -> Vec { + let parts = [ + vec![vmov(4, 133)], + vote_over(cmp("V_CMP_GT_U32", 8), &[vmov(4, 170)]), vec![restore()], + vote_over(cmp("V_CMP_LT_U32", 40), &[vmov(4, 145)]), vec![restore()], + vote_over(rdna2::encode("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 106), ("SRC0", 255), ("SRC1", 256)], Some(70)).unwrap(), &[vmov(4, 171)]), vec![restore()], + vec![ + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 256 + 4)]), + vmov(9, 10), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 9), ("SRC0", 136), ("VSRC1", 9)]), + ins("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 256 + 4), ("VSRC1", 9)]), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 130), ("VSRC1", 0)]), + vmov(7, 128), + ins("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 125)]), + ], + ].concat(); + code(&parts) + } + const SPLIT: KernelOptions = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; + + #[test] + fn local_votes_leave_one_exchange_of_four() { + for threads in [64, 128] { + let cs = CsInterface { threads: [threads, 1, 1], tid_components: 1, ..Default::default() }; + let sites = |on| with_idioms(on, || kernel::translate_compute(&three_votes(), SPLIT, &cs)).unwrap().exchange_sites; + assert_eq!((sites(true), sites(false)), (1, 4), "{threads} threads: the first lane's value alone is exchanged"); + } + } + + #[test] + fn gpu_split_wave64_local_votes_leave_what_the_exchange_leaves() { + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + let code = three_votes(); + for threads in [32u32, 48, 64, 128] { + let cs = CsInterface { threads: [threads, 1, 1], tid_components: 1, ..Default::default() }; + let run = |on: bool| { + let k = with_idioms(on, || kernel::translate_compute(&code, SPLIT, &cs)).unwrap(); + runner::dispatch(&k.dxil, [1; 3], &[0; KERNEL_SGPRS], &vec![0; threads as usize]).unwrap() + }; + let (mem, mem_off) = (run(true), run(false)); + let v4 = |tid: u32| if tid == 70 { 43 } else if tid > 40 { 17 } else if tid < 8 { 42 } else { 5 }; + for tid in 0..threads { + assert_eq!(mem[tid as usize], v4(tid) | v4(tid & !63) << 8, "thread {tid} of {threads}"); + } + assert_eq!(mem[..threads as usize], mem_off[..threads as usize], "{threads} threads"); + } + } + + #[test] + fn a_scalar_constant_asks_for_no_mask_whole() { + let sopk = |n: &str, dst: u64| ins(n, "ENC_SOPK", &[("SDST", dst), ("SIMM16", 7)]); + let select = ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128), ("SRC1", 129), ("SRC2", 106)]); + let around = |k: Vec| [cmp("V_CMP_GT_U32", 8), k, select.clone()]; + for (n, dst) in [("S_MOVK_I32", 8), ("S_ADDK_I32", 8), ("S_MULK_I32", 8), ("S_CMOVK_I32", 8), ("S_CMPK_EQ_I32", 8)] { + assert!(!exchanged(true, &around(sopk(n, dst))), "{n}"); + assert!(exchanged(false, &around(sopk(n, dst))), "{n}"); + } + assert!(exchanged(true, &around(sopk("S_ADDK_I32", 106))), "the mask as a number"); + assert!(exchanged(true, &around(sopk("S_CMPK_EQ_I32", 107)))); + assert!(exchanged(true, &around(sopk("S_MOVK_I32", 107))), "half of the pair replaced"); + assert!(exchanged(true, &around(ins("S_GETREG_B32", "ENC_SOPK", &[("SDST", 8), ("SIMM16", 1)])))); + } + + #[test] + fn a_vote_over_a_wait_stays_in_each_half() { + let wait = ins("S_WAITCNT_VSCNT", "ENC_SOPK", &[("SDST", 125), ("SIMM16", 0)]); + let mut p = vote_over(cmp("V_CMP_GT_U32", 8), &[vmov(4, 170), wait]); + p.push(restore()); + p.push(first_lane(10)); + assert!(!exchanged(true, &p)); + assert!(exchanged(false, &p)); + } + + #[test] + fn a_first_lane_of_scalar_arithmetic_is_uniform() { + let read = ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 256 + 1)]); + let double = ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]); + let uniform = |before: &[Vec]| { + let mut p = before.to_vec(); + p.push(read.clone()); + let cfg = Cfg::build(&code(&p)).unwrap(); + let at = cfg.insts.iter().find(|d| d.inst.name == "V_READFIRSTLANE_B32").unwrap().pc; + assert!(with_idioms(false, || uniform_reads(&cfg)).is_empty()); + with_idioms(true, || uniform_reads(&cfg)).contains(&at) + }; + assert!(uniform(&[vmov(1, 3), double.clone()])); + assert!(!uniform(&[]), "a register from before the block"); + assert!(!uniform(&[vmov(1, 256)]), "the thread's own id"); + assert!(!uniform(&[vmov(1, 3), ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256 + 1), ("VSRC1", 0)])])); + assert!(!uniform(&[vmov(1, 3), sop2("S_OR_B64", 126, 126, 4)]), "lanes that were off when it was written"); + assert!(!uniform(&[vmov(1, 3), ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 193), ("SRC1", 256 + 1)])]), "a lane's rank"); + assert!(!uniform(&[vmov(1, 3), ins("V_WRITELANE_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 129), ("SRC1", 128)])])); + assert!(!uniform(&[vmov(6, 128), vmov(7, 128), ins("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("VDST", 1), ("SADDR", 125)])]), "memory another wave may write"); + let select = |mask: Vec| [mask, ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 128), ("SRC1", 129), ("SRC2", 8)])]; + assert!(uniform(&select(sop2("S_CSELECT_B64", 8, 126, 128))), "all of EXEC's lanes or none"); + assert!(!uniform(&select(ins("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 130), ("SRC1", 256)]))), "a mask of some lanes"); + assert!(uniform(&select(ins("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 8), ("SRC0", 130), ("SRC1", 3)]))), "a compare of scalars"); + assert!(!uniform(&[sop2("S_CSELECT_B64", 8, 126, 128), ins("S_BITSET1_B64", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 129)]), select(vec![])[1].clone()]), "a mask changed in one lane"); + let fmas = ins("V_DIV_FMAS_F32", "ENC_VOP3", &[("VDST", 1), ("SRC0", 129), ("SRC1", 130), ("SRC2", 131)]); + assert!(uniform(&[sop2("S_CSELECT_B64", 106, 126, 128), fmas.clone()])); + assert!(!uniform(&[cmp("V_CMP_GT_U32", 8), fmas]), "a mask of some lanes in VCC"); + assert!(!uniform(&[cmp("V_CMP_GT_U32", 8), ins("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 1), ("SDST", 125), ("SRC0", 129), ("SRC1", 130), ("SRC2", 106)])]), "a carry in of some lanes"); + assert!(!uniform(&[vmov(1, 256), ins("V_CVT_F16_F32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 3)])]), "the half a 16-bit result keeps"); + assert!(!uniform(&[vmov(1, 256), vmov(2, 3), ins("V_DOT2C_F32_F16", "ENC_VOP2", &[("VDST", 1), ("SRC0", 3), ("VSRC1", 2)])]), "an accumulator"); + } + + /// v1 = tid + 100; then for each of six masks: under it v1 = 2 * (33 + j), s[10 + j] = + /// the first lane's v1; every thread stores the six, a byte each + fn six_first_lanes() -> Vec { + let lit = |n: &str, enc: &str, f: &[(&str, u64)], l: u32| rdna2::encode(n, enc, f, Some(l)).unwrap(); + let masks = [ + cmp("V_CMP_LT_U32", 40), cmp("V_CMP_GT_U32", 8), + lit("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 106), ("SRC0", 255), ("SRC1", 256)], 200), + cmp("V_CMP_GT_U32", 60), + lit("V_CMP_LT_U32", "ENC_VOP3", &[("VDST", 106), ("SRC0", 255), ("SRC1", 256)], 100), + lit("V_CMP_GT_U32", "ENC_VOP3", &[("VDST", 106), ("SRC0", 255), ("SRC1", 256)], 80), + ]; + let mut p = Vec::new(); + for (j, mask) in masks.into_iter().enumerate() { + let j = j as u64; + p.extend([ + lit("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 255), ("VSRC1", 0)], 100), + mask, + ins("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 106)]), + vmov(1, 128 + 33 + j), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 129), ("VSRC1", 1)]), + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 10 + j), ("SRC0", 256 + 1)]), + restore(), + ]); + } + for (j, into, shift) in [(11, 10, 8), (12, 10, 16), (13, 10, 24), (15, 14, 8)] { + p.push(sop2("S_LSHL_B32", j, j, 128 + shift)); + p.push(sop2("S_OR_B32", into, into, j)); + } + p.extend([ + vmov(4, 10), vmov(5, 14), vmov(7, 128), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 131), ("VSRC1", 0)]), + ins("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 4), ("SADDR", 125)]), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 132), ("VSRC1", 6)]), + ins("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 5), ("SADDR", 125)]), + ]); + code(&p) + } + + #[test] + fn uniform_first_lanes_leave_the_masks_to_exchange() { + let cs = CsInterface { threads: [128, 1, 1], tid_components: 1, ..Default::default() }; + let sites = |on| with_idioms(on, || kernel::translate_compute(&six_first_lanes(), SPLIT, &cs)).unwrap().exchange_sites; + assert_eq!((sites(true), sites(false)), (6, 12)); + } + + #[test] + fn gpu_split_wave64_uniform_first_lanes_read_what_the_exchange_reads() { + match runner::wave32_supported() { + Ok(true) => {} + Ok(false) => return runner::skip_test("no wave32"), + Err(e) => return runner::skip_test(&e), + } + let code = six_first_lanes(); + let on: [fn(u32) -> bool; 6] = [|t| t > 40, |t| t < 8, |t| t == 200, |t| t < 60, |t| t > 100, |t| t < 80]; + for threads in [32u32, 48, 64, 96, 128] { + let cs = CsInterface { threads: [threads, 1, 1], tid_components: 1, ..Default::default() }; + let run = |idioms: bool| { + let k = with_idioms(idioms, || kernel::translate_compute(&code, SPLIT, &cs)).unwrap(); + runner::dispatch(&k.dxil, [1; 3], &[0; KERNEL_SGPRS], &vec![0; 2 * threads as usize]).unwrap() + }; + let (mem, mem_off) = (run(true), run(false)); + for tid in 0..threads { + let wave = tid & !63; + let first = |j: usize| if (wave..threads.min(wave + 64)).any(on[j]) { 2 * (33 + j as u32) } else { 100 + wave }; + let want = [first(0) | first(1) << 8 | first(2) << 16 | first(3) << 24, first(4) | first(5) << 8]; + assert_eq!(mem[2 * tid as usize..][..2], want, "thread {tid} of {threads}"); + } + assert_eq!(mem[..2 * threads as usize], mem_off[..2 * threads as usize], "{threads} threads"); + } + } + + /// What the halves of a pack's wave64 compute and mesh programs exchange, with the idioms + /// and without, and how often the instructions other idioms would start from occur + /// (`XCL_SAMPLE_RPF`). + #[test] + #[ignore] + fn retail_wave64_compute_exchange_census() { + use crate::gpu::recomp::{self, Mode}; + let Ok(path) = std::env::var("XCL_SAMPLE_RPF") else { return }; + let data = std::fs::read(path).unwrap(); + let mut seen = std::collections::BTreeSet::new(); + let mut n: BTreeMap<&str, usize> = BTreeMap::new(); + for r in crate::gpu::pack::scan(&data, 0x40) { + let Some(blob) = crate::gpu::pack::inflate(&data, &r) else { continue }; + let Some(sh) = crate::gpu::xbox::parse(&blob) else { continue }; + for f in &sh.fssm { + let Some(p) = f.programs.first() else { continue }; + let code = &f.data[p.offset..p.offset + p.len]; + if !matches!(recomp::interface(&blob, &sh, f), Some(Mode::Compute(_) | Mode::Mesh(_))) || !recomp::fssm_wave64(f, code) || !seen.insert(code.to_vec()) { + continue; + } + let Ok(mut cfg) = Cfg::build(code) else { continue }; + *n.entry("programs").or_default() += 1; + if cfg.insts.iter().any(kernel::real_lds_access) { + *n.entry("programs with LDS (every mask exchanged)").or_default() += 1; + continue; + } + super::super::waterfall::collapse(&mut cfg); + let lowered: Vec = cfg.rpo.iter().flat_map(|&b| cfg.blocks[b].insts.iter().copied()).collect::>().into_iter().collect(); + let masks = |on| with_idioms(on, || mask_exchange::plan(&cfg)).demand.values().filter(|&&d| d != 0).count(); + let (on, off) = (masks(true), masks(false)); + *n.entry("compares exchanged, idioms off").or_default() += off; + *n.entry("compares exchanged, idioms on").or_default() += on; + let mut others = 0; + for &i in &lowered { + let d = &cfg.insts[i]; + let glc = d.enc.name == "ENC_SMEM" && (field(d, "GLC") == Some(1) || field(d, "DLC") == Some(1)); + let kind = match d.inst.name { + "V_READFIRSTLANE_B32" => "v_readfirstlane", + "V_READLANE_B32" => "v_readlane", + "DS_BPERMUTE_B32" => "ds_bpermute", + "S_BCNT1_I32_B64" => "(s_bcnt1_i32_b64)", + "V_MBCNT_LO_U32_B32" | "V_MBCNT_HI_U32_B32" => "(v_mbcnt)", + "S_FF1_I32_B64" => "(s_ff1_i32_b64)", + "S_CBRANCH_VCCZ" | "S_CBRANCH_VCCNZ" => "(s_cbranch_vcc*)", + "S_CBRANCH_EXECNZ" => "(s_cbranch_execnz)", + _ if glc => "coherent scalar load", + _ => continue, + }; + others += usize::from(!kind.starts_with('(')); + *n.entry(kind).or_default() += 1; + } + *n.entry("v_readfirstlane of a value every lane of EXEC holds").or_default() += with_idioms(true, || uniform_reads(&cfg)).len(); + let votes = cfg.blocks.iter().filter(|b| matches!(b.term, Term::Cond(i, ..) if cfg.insts[i].inst.name == "S_CBRANCH_EXECZ")).count(); + *n.entry("(s_cbranch_execz)").or_default() += votes; + *n.entry("(s_cbranch_execz over lane work)").or_default() += with_idioms(true, || candidates(&cfg, &cfg.insts.iter().map(mask_exchange::uses).collect::>())).len(); + if off + others > 0 { + *n.entry("programs that exchange, idioms off").or_default() += 1; + } + if on + others > 0 { + *n.entry("programs that exchange, idioms on").or_default() += 1; + } + } + } + for (k, v) in n { + println!("{v:>8} {k}"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d8d9939b27..26b373f1ec 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -86,6 +86,8 @@ pub struct Kernel { pub dxil: Vec, pub static_samplers: Vec<([u32; 4], bool)>, pub dispatch_chain: Option>, + /// places where the halves of a split wave64 program meet + pub exchange_sites: u32, } pub use super::module::split::DispatchChain; @@ -103,9 +105,14 @@ pub fn compact_mode() -> Option { } } -/// Non-default `XCL_DIRECT_COMPACT_NEST` cache tag for the translated cache identity. +/// Non-default `XCL_DIRECT_COMPACT_NEST` and `XCL_WAVE64_IDIOMS=0` cache tag for the translated cache identity. pub fn compact_nest_tag() -> Option { - super::compact::nest_mode().cache_tag() + let tags = [ + super::compact::nest_mode().cache_tag(), + (!super::idioms::enabled()).then(|| "xcl-wave64-idioms-0".to_string()), + ]; + let tags: Vec = tags.into_iter().flatten().collect(); + (!tags.is_empty()).then(|| tags.join("-")) } /// `translate_full` in the compact form (`compact = true`) or the plain one. @@ -252,12 +259,16 @@ fn translate_entry_with( let code = code.to_vec(); #[cfg(test)] let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(test)] + let idioms = super::idioms::IDIOMS_IN_TEST.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) .spawn(move || { #[cfg(test)] super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + #[cfg(test)] + super::idioms::IDIOMS_IN_TEST.with(|c| c.set(idioms)); translate_on_this_thread(&code, o, entry, compact, nest, rodata, ps_rt32_mask) }) .map_err(|e| format!("translator thread: {e}"))? @@ -336,6 +347,7 @@ fn translate_on_this_thread( let mut lw = Lw::new_with_slot(&cfg.insts, &leaders, o, &entry, masks.words); lw.whole_live.extend(masks.demand); lw.mask_batch_end = masks.batch_end; + lw.uniform_reads = masks.uniform_reads; lw.waterfall_ssamp = waterfall_ssamp; // In non-kernel entries, constant data after the program is only reachable via `s_getpc_b64` // (which supplies `CODE_ADDRESS_HI`). Without `s_getpc_b64`, probing every loaded dword against @@ -736,6 +748,7 @@ impl Lw { xs: None, xw: None, xc: None, + exchange_sites: 0, barrier_waves: None, safe_bar: None, waves: 1, @@ -754,6 +767,7 @@ impl Lw { whole_live: Default::default(), ps_masks: Default::default(), mask_batch_end: Default::default(), + uniform_reads: Default::default(), waterfall_ssamp: Default::default(), pending_masks: Vec::new(), guard_override: None, @@ -879,7 +893,7 @@ impl Lw { return Err(format!("direct DXIL failed validation: {e}\n--- disassembly ---\n{dis}")); } } - Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect(), dispatch_chain }) + Ok(Kernel { dxil: c, static_samplers: self.static_used.iter().map(|&(w, c, _)| (w, c)).collect(), dispatch_chain, exchange_sites: self.exchange_sites }) } } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 5746adaa95..8bbbdca9af 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -409,6 +409,7 @@ impl Lw { Partner::Spin => return self.exchange_spin(vals), Partner::Missing => return vals.iter().map(|_| self.c(0)).collect(), } + self.exchange_sites += 1; let (xs, base) = self.xs_storage(); let slot = self.xslot; assert!(vals.len() as u32 <= slot, "exchange of {} words, slot {slot}", vals.len()); @@ -452,6 +453,7 @@ impl Lw { /// pairs (per lane allowed), then reads the partner's slot at `loads`. fn spin_exchange(&mut self, stores: &[(Value, Value)], loads: &[Value]) -> Vec { use super::lower::{VAR_XDEAD, VAR_XK}; + self.exchange_sites += 1; let (xs, base) = self.xs.expect("spin slots"); let (xc, cbase) = self.xc.expect("spin counters"); let slot = self.xslot; @@ -770,6 +772,7 @@ impl Lw { let z = self.c(0); return self.sel(same, own, z); } + self.exchange_sites += 1; let (xs, base) = self.xs_storage(); let h = self.half; let mine = self.shlc(h, 5); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 07220732d1..4380f98115 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -309,6 +309,7 @@ pub struct Lw { pub xw: Option<(super::ops::GroupShared, u32)>, /// arrival counters of the spin exchange (two per console wave) pub xc: Option<(super::ops::GroupShared, u32)>, + pub exchange_sites: u32, /// hardware waves of a compute or mesh thread group (None: another kind of entry), as the /// HLSL emitter's `compute_or_mesh_hw_waves` pub barrier_waves: Option, @@ -343,6 +344,8 @@ pub struct Lw { /// split form: SGPRs whole-live after each instruction (`recomp::x64_masks::by_pc`) pub whole_live: std::collections::BTreeMap, pub(super) mask_batch_end: std::collections::BTreeMap, + /// split form: `v_readfirstlane`s of a value every lane of EXEC holds (`idioms`) + pub(super) uniform_reads: std::collections::BTreeSet, pub(super) waterfall_ssamp: std::collections::BTreeMap, pub(super) pending_masks: Vec<(Dst, Value)>, /// pixel shaders: compares whose mask needs less than the per-quad form (`recomp::ps_masks`) diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index d98e6a369c..3cbda785fb 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1054,8 +1054,12 @@ impl Lw { } "v_readfirstlane_b32" => { let (el, eh) = self.exec_mask(); - let l = self.first_lane(el, eh); - let t = self.read_lane_uniform(a, l); + let t = if self.uniform_reads.contains(&d.pc) { + self.read_first_lane_uniform(a, el, eh)? + } else { + let l = self.first_lane(el, eh); + self.read_lane_uniform(a, l) + }; self.write32(&dst, t); return Ok(()); } diff --git a/crates/xcl/src/gpu/dxil/mask_exchange.rs b/crates/xcl/src/gpu/dxil/mask_exchange.rs index def16d37b3..ee6b8fec66 100644 --- a/crates/xcl/src/gpu/dxil/mask_exchange.rs +++ b/crates/xcl/src/gpu/dxil/mask_exchange.rs @@ -7,8 +7,8 @@ use std::collections::BTreeMap; use super::cfg::{Cfg, Term}; use crate::gpu::{rdna2::{self, Decoded, Variant}, recomp::x64_masks}; -const EXEC: u128 = 3 << 126; -const SCC: u128 = 1 << 125; // NULL in the ISA operands, SCC in the lowering +pub(super) const EXEC: u128 = 3 << 126; +pub(super) const SCC: u128 = 1 << 125; // NULL in the ISA operands, SCC in the lowering const VCC: u128 = 3 << 106; #[derive(Default)] @@ -16,21 +16,22 @@ pub(super) struct Plan { pub demand: BTreeMap, // A member queues its ballot word. The last member exchanges and writes all destinations. pub batch_end: BTreeMap, + pub uniform_reads: std::collections::BTreeSet, pub words: u32, } -#[derive(Clone, Copy)] -struct Uses { - read: u128, - written: u128, +#[derive(Clone, Copy, Default)] +pub(super) struct Uses { + pub read: u128, + pub written: u128, // Transfer inputs whose whole value is required only when these outputs are observed. - if_live: u128, - inputs: u128, - save: u128, + pub if_live: u128, + pub inputs: u128, + pub save: u128, } impl Uses { - fn before(self, live: u128) -> u128 { + pub(super) fn before(self, live: u128) -> u128 { let mut before = self.read | (live & !self.written); if live & self.if_live != 0 { before |= self.inputs; } if live & self.save != 0 { before |= EXEC; } @@ -38,7 +39,7 @@ impl Uses { } } -fn uses(d: &Decoded) -> Uses { +pub(super) fn uses(d: &Decoded) -> Uses { let (mut read, regs) = x64_masks::uses(d); // A multiword SGPR destination can span NULL (125). write64 skips that // dword. Only a real SCC definition may kill demand for SCC here. @@ -49,7 +50,7 @@ fn uses(d: &Decoded) -> Uses { let opaque = || Uses { read: !0, written: 0, if_live: 0, inputs: 0, save: 0 }; if name.contains("MOVREL") || name.contains("SETREG") || name.contains("WREXEC") || (name.contains("SAVEEXEC") && name != "S_AND_SAVEEXEC_B64") - || name.starts_with("DS_") || d.enc.name == "ENC_SOPK" { + || name.starts_with("DS_") || (d.enc.name == "ENC_SOPK" && !super::idioms::plain_sopk(name)) { return opaque(); } let field = |f| rdna2::field_value(d.enc, &d.words, f); @@ -61,7 +62,7 @@ fn uses(d: &Decoded) -> Uses { if o.ty == "OPR_SSRC_SPECIAL_SCC" { if o.input { read |= SCC; } // Only kill SCC for operations whose lowering unconditionally sets it. - if o.output && (name.starts_with("S_CMP_") || matches!(name, "S_AND_SAVEEXEC_B64" + if o.output && (name.starts_with("S_CMP_") || name.starts_with("S_CMPK_") || matches!(name, "S_ADDK_I32" | "S_AND_SAVEEXEC_B64" | "S_AND_B64" | "S_OR_B64" | "S_XOR_B64" | "S_ANDN2_B64" | "S_ORN2_B64" | "S_NAND_B64" | "S_NOR_B64" | "S_XNOR_B64" | "S_NOT_B64" | "S_AND_B32" | "S_XOR_B32" | "S_ADD_I32" | "S_SUB_I32" | "S_ADD_U32" | "S_ADDC_U32" @@ -101,15 +102,15 @@ fn uses(d: &Decoded) -> Uses { u } -fn cmp_dst(d: &Decoded, u: Uses) -> Option { +pub(super) fn cmp_dst(d: &Decoded, u: Uses) -> Option { if d.inst.name.starts_with("V_CMPX_") && d.variant == Variant::Plain && u.written == EXEC { return Some(EXEC); } let r = u.written.trailing_zeros(); (d.inst.name.starts_with("V_CMP_") && d.variant == Variant::Plain && r <= 122 && r % 2 == 0 && u.written == 3u128 << r).then_some(u.written) } -pub(super) fn plan(cfg: &Cfg) -> Plan { - let info: Vec<_> = cfg.insts.iter().map(uses).collect(); +/// Whole demand at each block's entry and after each instruction. +pub(super) fn demand(cfg: &Cfg, info: &[Uses]) -> (Vec, Vec) { let mut entry = vec![0; cfg.blocks.len()]; let mut after = vec![0; cfg.insts.len()]; loop { @@ -132,7 +133,13 @@ pub(super) fn plan(cfg: &Cfg) -> Plan { } if !changed { break; } } - let mut p = Plan::default(); + (entry, after) +} + +pub(super) fn plan(cfg: &Cfg) -> Plan { + let mut info: Vec<_> = cfg.insts.iter().map(uses).collect(); + let after = super::idioms::local_votes(cfg, &mut info); + let mut p = Plan { uniform_reads: super::idioms::uniform_reads(cfg), ..Default::default() }; for &b in &cfg.rpo { let mut group = Vec::with_capacity(3); let (mut read, mut written) = (0, 0); @@ -208,6 +215,19 @@ mod tests { assert_ne!(plan(&program(&across_null)).demand[&0], 0); } + #[test] + fn split_wave64_scalar_constant_compares_replace_scc() { + for k in ["S_CMPK_EQ_I32", "S_ADDK_I32"] { + let body = [ + cmp(106, 130), saveexec(4, 106), + ins(k, "ENC_SOPK", &[("SDST", 8), ("SIMM16", 7)]), + ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)]), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 170)]), + ]; + assert_eq!(plan(&program(&body)).demand[&0], 0, "{k}"); + } + } + #[test] fn split_wave64_compare_batch_requires_independent_operands_and_one_block() { let mut body = vec![cmp(2, 128), cmp(4, 132), cmp(6, 160), scalar(10, 2), scalar(10, 4), scalar(10, 7)]; diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index 9ce7088a19..6ca3ed7b5a 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -19,6 +19,7 @@ pub mod coverage; pub mod graphics; pub mod kernel; mod lanes; +mod idioms; mod mask_exchange; pub mod lower; mod lower_geom; diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 9945b2849d..bfc8319f0f 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -37,7 +37,7 @@ fn semantic_pipeline_setting(name: &str) -> bool { "XCL_HEAP_WINDOWS" | "XCL_LDS_TOP" | "XCL_LINK_MEM" | "XCL_MEM_ACCESSORS" | "XCL_MW" | "XCL_PAGE_ALIAS" | "XCL_PER_LANE" | "XCL_PIXEL" | "XCL_RECOMP_DXIL" | "XCL_RECOMP_NO_STRUCTURED" | "XCL_SAFE_BARRIER" | - "XCL_SPLIT_WAVE64" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" | + "XCL_SPLIT_WAVE64" | "XCL_WAVE64_IDIOMS" | "XCL_WAVE64_SPIN" | "XCL_WT" | "XCL_X64_ALL_MASKS" | "XCL_XC" | "XCL_XS" | "XCL_XW" | "XCL_X_FAIL" | "XCL_X_LDS_ORDER" | "XCL_X_LDS_TOP" | "XCL_X_SLOT" | "XCL_X_SPIN" | "XCL_X_THREADS" | "XCL_X_WAVES") } @@ -140,6 +140,14 @@ fn warm_settings_ignore_waits_watchdogs_and_traces_but_keep_pipeline_switches() assert_eq!(plain, key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_TRACEX", "1")]), "unknown diagnostics stay cache-neutral until reviewed"); } +#[cfg(test)] +#[test] +fn warm_settings_keep_the_wave64_idioms_switch_on_both_backends() { + let key = |entries: &[(&str, &str)]| warm_settings(entries.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + assert_ne!(key(&[]), key(&[("XCL_WAVE64_IDIOMS", "0")])); + assert_ne!(key(&[("XCL_DIRECT_DXIL", "1")]), key(&[("XCL_DIRECT_DXIL", "1"), ("XCL_WAVE64_IDIOMS", "0")])); +} + #[cfg(test)] #[test] fn warm_settings_are_canonical_and_only_hash_semantic_switches() { diff --git a/docs/wave64-on-wave32.md b/docs/wave64-on-wave32.md index 9a01a70742..839904decc 100644 --- a/docs/wave64-on-wave32.md +++ b/docs/wave64-on-wave32.md @@ -152,6 +152,61 @@ has no liveness pass: its masks are exchanged as before, except those two kinds destination, 0 in every lane), which are the same in both halves either way. `XCL_X64_ALL_MASKS=1` exchanges every mask (for comparison). +### Idioms + +Sequences around a whole-wave value that are exact without its exchange (`gpu/dxil/idioms.rs`, +the direct translator's compute and mesh programs without LDS; `XCL_WAVE64_IDIOMS=0` turns them +off, and is part of the translated cache's identity and the warm pipeline library's settings). + +**A local vote.** `s_cbranch_execz` forward over lane work: the `if` of a shader +(`v_cmp`, `s_and_saveexec_b64`, `s_cbranch_execz`, the body, `s_or_b64 exec, exec, saved`). A +half with no lane in EXEC loses nothing by skipping the body whatever the other half does, so +the branch reads each half's own word and the compare stays in its half; the halves may take +different sides. It holds when, between the branch and its target, +- every instruction is per-lane work under EXEC, scalar arithmetic or a plain scalar load: no + `v_readlane` / `v_readfirstlane` / `v_writelane`, no `ds_*`, no coherent scalar load, no + `s_barrier`, nothing indirect or relative, and no mask that is itself exchanged (the halves + would meet out of step); +- branches go forward and stay inside, and none comes in from outside; +- EXEC stays within the EXEC at the branch on every path (`s_and_saveexec_b64`, `s_and_b64`, + `s_andn2_b64`, `s_or_b64` / `s_xor_b64` / `s_mov_b64` of pairs known to be within it, compares); +- no SGPR written there, SCC included, is read after the target, and EXEC is not read whole + at the target if it was written. + +**The saved EXEC's return.** At the target of such a vote, `s_or_b64 exec, exec, s` with `s` +the EXEC that `s_and_saveexec_b64` saved right before the branch gives `s`: EXEC there is +within it. A whole read of EXEC after the `if` then asks for `s` and not for the compare. + +**A uniform first lane.** `v_readfirstlane` of a value every lane of EXEC holds: the compiler's +scalar arithmetic that has no scalar instruction (float conversion, reciprocal, a 0 / 1 from a +scalar condition), done in a VGPR and read back. When both halves have a running lane in EXEC +each reads its own first one, the same value; when one has none the halves exchange as before +(EXEC is still read whole, so both know). A value is known to be in every lane of EXEC when, +in its block and after the last write of EXEC, it came from plain VALU instructions whose +operands (an accumulator's or a 16-bit result's destination included) are scalars or such +values again, and whose lane masks (`v_cndmask_b32`'s, a carry in, `v_div_fmas_f32`'s VCC) +have one bit for all of EXEC's lanes (`s_cselect_b64` of EXEC and constants, bitwise 64-bit +operations and compares of such operands). Not a lane's rank or index (`v_mbcnt`), a +cross-lane read, a carry out, an SDWA / DPP form, nor a memory load: another wave may write +that memory between the halves' loads. + +**A scalar constant.** `s_movk_i32`, `s_cmovk_i32`, `s_addk_i32`, `s_mulk_i32` and `s_cmpk_*` +read and write the registers they name, and `s_waitcnt_*cnt` and `s_version` none; the mask +demand took every SOPK instruction for one that may read any register, so a compare before any +of them was exchanged. + +On a retail pack's 9 442 distinct wave64 compute and mesh programs without LDS +(`retail_wave64_compute_exchange_census`, ignored, `XCL_SAMPLE_RPF`): 157 393 exchanged compares +without the idioms, 114 214 with the votes, 90 743 with the constants too; 38 702 of 57 884 +`v_readfirstlane` are uniform. Of the compares still exchanged, 66 037 are read by an +`s_cbranch_execz` whose side is more than lane work (an export count, another lane's value, a +scalar read later) or holds such a vote. + +The decision is made with the mask demand (`mask_exchange.rs`): the votes are assumed local, +and one whose side turns out to exchange a compare, or to be followed by a whole read of the +EXEC it wrote, is taken back until nothing changes. `Kernel::exchange_sites` counts the places +where the halves meet in a translation. + ## Cost A wave64 program pays one exchange per mask write that is read whole (`v_cmp*` feeding