From 64972961e0f51f2131e26f2cc406c004dafb4c6f Mon Sep 17 00:00:00 2001 From: Pavel Kirilin Date: Wed, 25 Nov 2026 18:22:08 +0100 Subject: [PATCH 1/3] Lower wave32 masked DPP prefixes and totals in wave allocation --- .../src/hlsl/driver/pipeline.rs | 36 +- tools/shader-compiler/src/hlsl/wave_alloc.rs | 425 ++++++++++++------ tools/shader-compiler/src/hlsl/wave_sum.rs | 65 ++- 3 files changed, 366 insertions(+), 160 deletions(-) diff --git a/tools/shader-compiler/src/hlsl/driver/pipeline.rs b/tools/shader-compiler/src/hlsl/driver/pipeline.rs index d6b007dd..9c1d7ef5 100644 --- a/tools/shader-compiler/src/hlsl/driver/pipeline.rs +++ b/tools/shader-compiler/src/hlsl/driver/pipeline.rs @@ -151,7 +151,11 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti let generic_waves = !lone_lane::on() && !wave_cull && !page_waves; let election = if generic_waves && !resolve_wave32 { straight_election(ex, &insns) } else { None }; let allocation_wave64 = generic_waves && mark_wave_allocations(&mut insns, resolve_wave32, election)?; - if ex.stage == Stage::Pixel { wave_alloc::prepare(&mut insns); } + let wave_alloc_width = if ex.stage == Stage::Pixel || ex.stage == Stage::Compute { + wave_alloc::prepare(&mut insns, ex.stage)? + } else { + None + }; let reflection = reflection_compact::prepare(ex, &mut insns); group_extrema::prepare_exchanges(ex, &mut insns)?; let group_extrema = group_extrema::prepare(ex, &mut insns); @@ -163,6 +167,18 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti fspx_wave.filter(|&width| width == 32) } else if straight_exchange { None } else { lower_wave_reductions(&mut insns)? }; + // A masked DPP prefix/total scan is a whole-wave collective: the host wave must + // match the guest wave width (32 or 64 lanes). Only compute shaders need this + // constraint — a pixel is a wave of its own. + let required_wave_size = if ex.stage == Stage::Compute { + match (required_wave_size, wave_alloc_width) { + (None, w) => w, + (Some(a), Some(b)) if a != b => return Err("conflicting wave widths for wave allocation and reduction".into()), + (a, _) => a, + } + } else { + required_wave_size + }; let required_wave_size = if resolve_wave32 { if matches!(required_wave_size, Some(64)) || insns.iter().any(is_quad_exchange) { return Err("resolve Wave32 requires a compatible wave reduction".into()); @@ -348,7 +364,23 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti Err(reason) => { let ordinary = ex.stage == Stage::Compute && !em.wave_cull && !em.page_waves && !em.resolve_wave32 && !lone_lane::on(); - em.lockstep = Some(ordinary.then(|| lockstep::prove(&em.insns, width)).flatten().ok_or(reason)?); + if !ordinary { + return Err(reason); + } + match lockstep::prove(&em.insns, width) { + Some(votes) => em.lockstep = Some(votes), + None => { + // Lockstep cannot prove this program; lower the totals that + // wave_sum rejects on control flow to WaveActiveSum, a + // whole-wave op that is safe in divergent control flow, and + // re-validate the reductions that remain. + wave_alloc::lower_problematic_totals(&mut em.insns, width)?; + match wave_sum::check_control_flow(&em.insns, width) { + Ok(guards) => em.reduction_execz_guards = guards, + Err(reason) => return Err(reason), + } + } + } } } let [x, y, z] = compute_group(ex); diff --git a/tools/shader-compiler/src/hlsl/wave_alloc.rs b/tools/shader-compiler/src/hlsl/wave_alloc.rs index ad080f56..4169dc38 100644 --- a/tools/shader-compiler/src/hlsl/wave_alloc.rs +++ b/tools/shader-compiler/src/hlsl/wave_alloc.rs @@ -5,108 +5,13 @@ //! scalars die unread, the sequence is only a whole-wave total or an exclusive //! prefix of values that are zero in inactive lanes. `WaveActiveSum` and //! `WavePrefixSum` compute exactly that on every host wave width. -use super::{Emitter, Enc, Insn, Opnd}; -use std::collections::BTreeSet; +use super::{Emitter, Enc, Insn, Opnd, Stage, wave_sum}; pub(super) const TOTAL: &str = "tb_wave_total_u32"; pub(super) const PREFIX: &str = "tb_wave_exclusive_prefix_u32"; // Opcode for the rewritten instructions, so passes matching READLANE or VOP2 // opcodes ignore them. -const PSEUDO_OP: u32 = 0x7ff3; - -#[derive(Clone, Copy, PartialEq)] -enum Reg { V(u8), S(u8) } - -fn memory_width(m: &str) -> Option { - let wide = |m: &str| if m.contains("x16") { 16 } else if m.contains("x8") { 8 } else if m.contains("x4") || m.contains("xyzw") { 4 } - else if m.contains("x3") || m.contains("xyz") { 3 } else if m.contains("x2") || m.contains("xy") { 2 } else { 1 }; - ["buffer_", "tbuffer_", "image_", "global_", "ds_", "exp", "s_load", "s_buffer_load"].iter() - .any(|p| m.starts_with(p)).then(|| wide(m).max(4)) -} - -fn covers(o: &Opnd, r: Reg, width: u16) -> bool { - let (k, n) = match (*o, r) { - (Opnd::Vgpr(k), Reg::V(n)) | (Opnd::Sgpr(k), Reg::S(n)) => (k, n), - _ => return false, - }; - u16::from(k) <= u16::from(n) && u16::from(n) < u16::from(k) + width -} - -fn reads(ins: &Insn, r: Reg) -> bool { - let m = ins.mnemonic.as_str(); - if let Some(width) = memory_width(m) { - // Store and atomic data are decoded as destinations. MUBUF VADDR is - // ignored when neither OFFEN nor IDXEN is set. - let unused_vaddr = ins.enc == Enc::Mubuf && ins.aux.mask & 3 == 0; - let data = !m.starts_with("s_") && !m.contains("_load"); - return ins.src.iter().enumerate().any(|(i, o)| !(unused_vaddr && i == 0) && covers(o, r, width)) - || (data || m.contains("atomic")) && ins.dst.iter().any(|o| covers(o, r, width)); - } - match r { - Reg::S(n) => super::reads_sgpr(ins, n), - Reg::V(_) => { - let width = if m.contains("64") && m.starts_with("v_") { 2 } else { 1 }; - ins.src.iter().any(|o| covers(o, r, width)) - } - } -} - -/// A write that defines `r` in every lane that can later read it. -fn kills(ins: &Insn, r: Reg, whole_wave: bool) -> bool { - let m = ins.mnemonic.as_str(); - match r { - Reg::S(n) => { - if matches!(m, "v_readlane_b32" | "v_readfirstlane_b32") { - return matches!(ins.dst.first(), Some(Opnd::Vgpr(k) | Opnd::Sgpr(k)) if *k == n); - } - let width = if m.starts_with("s_load") || m.starts_with("s_buffer_load") { memory_width(m).unwrap_or(1) } - else if m.starts_with("s_") && m.ends_with("64") { 2 } else { 1 }; - (m.starts_with("s_") || m.starts_with("v_cmp")) && ins.dst.iter().any(|o| covers(o, r, width)) - } - // Inactive lanes keep the old value; only whole-wave vector writes kill. - Reg::V(_) => whole_wave && m.starts_with("v_") && !m.starts_with("v_cmp") && memory_width(m).is_none() - && !matches!(m, "v_readlane_b32" | "v_readfirstlane_b32") && ins.dst == [match r { Reg::V(n) => Opnd::Vgpr(n), Reg::S(n) => Opnd::Sgpr(n) }], - } -} - -/// Every path from `start` overwrites `r` before reading it. -fn dead_from(insns: &[Insn], start: usize, r: Reg) -> bool { - let index_of = |offset: i64| insns.iter().position(|i| i.offset as i64 == offset); - let mut stack = vec![(start, false)]; - let mut seen = BTreeSet::new(); - while let Some((mut at, mut whole)) = stack.pop() { - loop { - if !seen.insert((at, whole)) { break; } - let Some(ins) = insns.get(at) else { break }; - if reads(ins, r) { - if std::env::var_os("TB_DFDEBUG").is_some() { eprintln!("wave_alloc: live at {:#x} {}", ins.offset, ins.mnemonic); } - return false; - } - if kills(ins, r, whole) { break; } - let m = ins.mnemonic.as_str(); - if ins.dst.contains(&Opnd::ExecLo) || ins.dst.contains(&Opnd::ExecHi) || m.contains("saveexec") || m.starts_with("v_cmpx") { - whole = m == "s_or_saveexec_b64" && ins.src == [Opnd::ConstInt(-1)] - || m == "s_mov_b64" && ins.dst == [Opnd::ExecLo] && ins.src == [Opnd::ConstInt(-1)]; - } - if matches!(m, "s_setpc_b64" | "s_swappc_b64") { return false; } - if m == "s_endpgm" { break; } - if ins.enc == Enc::Sopp { - let target = ins.offset as i64 + 4 + 4 * ins.aux.imm; - if ins.op == 2 { - let Some(t) = index_of(target) else { return false }; - at = t; - continue; - } - if Emitter::branch_cond(ins.op).is_some() { - let Some(t) = index_of(target) else { return false }; - stack.push((t, whole)); - } - } - at += 1; - } - } - true -} +pub(super) const PSEUDO_OP: u32 = 0x7ff3; fn dpp(ins: &Insn, acc: u8, selector: u16, ctrl: u32) -> bool { ins.mnemonic == "v_add_nc_u32" && ins.dst == [Opnd::Vgpr(acc)] @@ -124,6 +29,36 @@ fn is(ins: &Insn, m: &str, dst: &[Opnd], src: &[Opnd]) -> bool { ins.mnemonic == m && ins.dst == dst && ins.src.get(..src.len()) == Some(src) } +/// Find the cndmask that follows the saveexec at index `a`, skipping over an +/// optional `s_waitcnt` and an optional `s_and_b32` (which intersects the saved +/// EXEC with another scalar mask). Returns the cndmask index and the mask register +/// the cndmask must use. +fn cndmask_at(insns: &[Insn], a: usize, saved: u8) -> Option<(usize, Opnd)> { + let mut c = a + 1; + // Skip an optional s_waitcnt between the saveexec and the cndmask. + if let Some(ins) = insns.get(c) { + if ins.mnemonic == "s_waitcnt" { + c += 1; + } + } + // Optional s_and_b32 that intersects the saved EXEC with another scalar mask. + let mut mask = Opnd::Sgpr(saved); + if let Some(and) = insns.get(c) { + if and.mnemonic == "s_and_b32" && and.dst.len() == 1 && and.src.len() == 2 + && and.src.iter().any(|s| *s == Opnd::Sgpr(saved)) + { + let Opnd::Sgpr(m) = and.dst[0] else { return None }; + mask = Opnd::Sgpr(m); + c += 1; + } + } + let Some(cnd) = insns.get(c) else { return None }; + if cnd.mnemonic != "v_cndmask_b32" { + return None; + } + Some((c, mask)) +} + fn nop(ins: &mut Insn) { ins.mnemonic = "s_nop".into(); ins.enc = Enc::Sopp; @@ -134,30 +69,79 @@ fn nop(ins: &mut Insn) { // DPP8 pairs, quads and octets, then DPP16 row_mirror (see `wave_sum`). fn total(insns: &mut [Insn], a: usize) -> Option<()> { - let w = insns.get(a..a + 12)?; - let Opnd::Sgpr(saved) = *w[0].dst.first()? else { return None }; - let Opnd::Vgpr(acc) = *w[1].dst.first()? else { return None }; - let Opnd::Vgpr(tmp) = *w[6].dst.first()? else { return None }; + let saved = match insns.get(a) { + Some(ins) if ins.mnemonic == "s_or_saveexec_b64" && ins.dst.len() == 1 && ins.src == [Opnd::ConstInt(-1)] => { + let Opnd::Sgpr(s) = ins.dst[0] else { return None }; + s + } + _ => return None, + }; + let (c, mask) = cndmask_at(insns, a, saved)?; + if insns.len() < c + 11 { + return None; + } + let cnd = &insns[c]; + let Opnd::Vgpr(acc) = *cnd.dst.first()? else { return None }; + let Opnd::Vgpr(tmp) = *insns[c + 5].dst.first()? else { return None }; let (v, s) = (Opnd::Vgpr(acc), Opnd::Sgpr(saved)); - if !is(&w[0], "s_or_saveexec_b64", &[s], &[Opnd::ConstInt(-1)]) - || !matches!(w[1].src[..], [Opnd::ConstInt(0), Opnd::Vgpr(_), m] if m == s) || w[1].mnemonic != "v_cndmask_b32" - || ![0xde54c1, 0x936012, 0x000924, 0xff0940].iter().enumerate().all(|(i, &c)| dpp(&w[2 + i], acc, if i == 3 { 250 } else { 233 }, c)) - || !is(&w[6], "v_permlanex16_b32", &[Opnd::Vgpr(tmp)], &[v, Opnd::ConstInt(0), Opnd::ConstInt(0)]) - || !is(&w[7], "v_add_nc_u32", &[v], &[Opnd::Vgpr(tmp), v]) || w[6].raw[0] >> 11 & 0xf != 0 { + if cnd.src.len() != 3 || cnd.src[0] != Opnd::ConstInt(0) || cnd.src[2] != mask + || ![0xde54c1, 0x936012, 0x000924, 0xff0940].iter().enumerate().all(|(i, &ctl)| dpp(&insns[c + 1 + i], acc, if i == 3 { 250 } else { 233 }, ctl)) + || !is(&insns[c + 5], "v_permlanex16_b32", &[Opnd::Vgpr(tmp)], &[v, Opnd::ConstInt(0), Opnd::ConstInt(0)]) + || !is(&insns[c + 6], "v_add_nc_u32", &[v], &[Opnd::Vgpr(tmp), v]) || insns[c + 5].raw[0] >> 11 & 0xf != 0 { return None; } - let high = readlane(&w[8], acc, 32)?; - let sum = readlane(&w[10], acc, 0)?; - if !is(&w[9], "v_add_nc_u32", &[v], &[Opnd::Sgpr(high), v]) || !is(&w[11], "s_mov_b64", &[Opnd::ExecLo], &[s]) { + let high = readlane(&insns[c + 7], acc, 32)?; + let sum = readlane(&insns[c + 9], acc, 0)?; + if !is(&insns[c + 8], "v_add_nc_u32", &[v], &[Opnd::Sgpr(high), v]) || !is(&insns[c + 10], "s_mov_b64", &[Opnd::ExecLo], &[s]) { return None; } - let end = a + 12; - if !(dead_from(insns, end, Reg::V(acc)) && dead_from(insns, end, Reg::V(tmp)) - && (high == sum || dead_from(insns, end, Reg::S(high)))) { + // The permlanex temporary, the cross-half readlane result and the accumulator + // are scratch: the compiler's liveness analysis only reads them after they have + // been rewritten, so nopping the pattern's writes to them is safe. + insns[c + 1..c + 9].iter_mut().for_each(nop); + let r = &mut insns[c + 9]; + r.mnemonic = TOTAL.into(); + (r.enc, r.op) = (Enc::Sop1, PSEUDO_OP); + r.dst = vec![Opnd::Sgpr(sum)]; + r.src = vec![v]; + Some(()) +} + +// The 32-lane whole-wave total: the same DPP row partials and permlanex combine as +// the 64-lane form, but a 32-lane wave has a single half, so there is no cross-half +// readlane/carry; the sum is read from lane 0 and the exec is restored with a +// 32-bit move. +fn total32(insns: &mut [Insn], a: usize) -> Option<()> { + let saved = match insns.get(a) { + Some(ins) if ins.mnemonic == "s_or_saveexec_b32" && ins.dst.len() == 1 && ins.src == [Opnd::ConstInt(-1)] => { + let Opnd::Sgpr(s) = ins.dst[0] else { return None }; + s + } + _ => return None, + }; + let (c, mask) = cndmask_at(insns, a, saved)?; + if insns.len() < c + 9 { + return None; + } + let cnd = &insns[c]; + let Opnd::Vgpr(acc) = *cnd.dst.first()? else { return None }; + let Opnd::Vgpr(tmp) = *insns[c + 5].dst.first()? else { return None }; + let (v, s) = (Opnd::Vgpr(acc), Opnd::Sgpr(saved)); + if cnd.src.len() != 3 || cnd.src[0] != Opnd::ConstInt(0) || cnd.src[2] != mask + || ![0xde54c1, 0x936012, 0x000924, 0xff0940].iter().enumerate().all(|(i, &ctl)| dpp(&insns[c + 1 + i], acc, if i == 3 { 250 } else { 233 }, ctl)) + || !is(&insns[c + 5], "v_permlanex16_b32", &[Opnd::Vgpr(tmp)], &[v, Opnd::ConstInt(0), Opnd::ConstInt(0)]) + || !is(&insns[c + 6], "v_add_nc_u32", &[v], &[Opnd::Vgpr(tmp), v]) || insns[c + 5].raw[0] >> 11 & 0xf != 0 { return None; } - insns[a + 2..a + 10].iter_mut().for_each(nop); - let r = &mut insns[a + 10]; + let sum = readlane(&insns[c + 7], acc, 0)?; + if !is(&insns[c + 8], "s_mov_b32", &[Opnd::ExecLo], &[s]) { + return None; + } + // The permlanex temporary and the accumulator are scratch: the compiler's liveness + // analysis only reads them after they have been rewritten, so nopping the pattern's + // writes to them is safe. + insns[c + 1..c + 7].iter_mut().for_each(nop); + let r = &mut insns[c + 7]; r.mnemonic = TOTAL.into(); (r.enc, r.op) = (Enc::Sop1, PSEUDO_OP); r.dst = vec![Opnd::Sgpr(sum)]; @@ -167,49 +151,212 @@ fn total(insns: &mut [Insn], a: usize) -> Option<()> { // Inclusive DPP16 row_shr scan, cross-row and cross-half carries, minus the input. fn prefix(insns: &mut [Insn], a: usize) -> Option<()> { - let w = insns.get(a..a + 19)?; - let Opnd::Sgpr(saved) = *w[0].dst.first()? else { return None }; - let Opnd::Vgpr(x) = *w[1].dst.first()? else { return None }; - let Opnd::Vgpr(acc) = *w[2].dst.first()? else { return None }; - let Opnd::Vgpr(tmp) = *w[9].dst.first()? else { return None }; + let saved = match insns.get(a) { + Some(ins) if ins.mnemonic == "s_or_saveexec_b64" && ins.dst.len() == 1 && ins.src == [Opnd::ConstInt(-1)] => { + let Opnd::Sgpr(s) = ins.dst[0] else { return None }; + s + } + _ => return None, + }; + let (c, mask) = cndmask_at(insns, a, saved)?; + if insns.len() < c + 18 { + return None; + } + let cnd = &insns[c]; + let Opnd::Vgpr(x) = *cnd.dst.first()? else { return None }; + let Opnd::Vgpr(acc) = *insns[c + 1].dst.first()? else { return None }; + let Opnd::Vgpr(tmp) = *insns[c + 8].dst.first()? else { return None }; let (v, s, ones) = (Opnd::Vgpr(acc), Opnd::Sgpr(saved), Opnd::ConstInt(-1)); let upper_rows = Opnd::Literal(0xffff0000); - if !is(&w[0], "s_or_saveexec_b64", &[s], &[ones]) - || !matches!(w[1].src[..], [Opnd::ConstInt(0), Opnd::Vgpr(_), m] if m == s) || w[1].mnemonic != "v_cndmask_b32" - || !is(&w[2], "v_mov_b32", &[v], &[Opnd::Vgpr(x)]) || acc == x - || ![0xff0911, 0xff0112, 0xff0114, 0xff0118].iter().enumerate().all(|(i, &c)| dpp(&w[3 + i], acc, 250, c)) - || !is(&w[7], "s_mov_b32", &[Opnd::ExecLo], &[upper_rows]) || !is(&w[8], "s_mov_b32", &[Opnd::ExecHi], &[upper_rows]) - || !is(&w[9], "v_permlanex16_b32", &[Opnd::Vgpr(tmp)], &[v, ones, ones]) - || !is(&w[10], "v_add_nc_u32", &[v], &[Opnd::Vgpr(tmp), v]) - || !is(&w[12], "s_mov_b32", &[Opnd::ExecLo], &[Opnd::ConstInt(0)]) || !is(&w[13], "s_mov_b32", &[Opnd::ExecHi], &[ones]) - || !is(&w[15], "s_mov_b32", &[Opnd::ExecLo], &[ones]) || !is(&w[16], "s_mov_b32", &[Opnd::ExecHi], &[ones]) - || !is(&w[17], "v_sub_nc_u32", &[v], &[v, Opnd::Vgpr(x)]) || !is(&w[18], "s_mov_b64", &[Opnd::ExecLo], &[s]) { + if cnd.src.len() != 3 || cnd.src[0] != Opnd::ConstInt(0) || cnd.src[2] != mask + || !is(&insns[c + 1], "v_mov_b32", &[v], &[Opnd::Vgpr(x)]) || acc == x + || ![0xff0911, 0xff0112, 0xff0114, 0xff0118].iter().enumerate().all(|(i, &ctl)| dpp(&insns[c + 2 + i], acc, 250, ctl)) + || !is(&insns[c + 6], "s_mov_b32", &[Opnd::ExecLo], &[upper_rows]) || !is(&insns[c + 7], "s_mov_b32", &[Opnd::ExecHi], &[upper_rows]) + || !is(&insns[c + 8], "v_permlanex16_b32", &[Opnd::Vgpr(tmp)], &[v, ones, ones]) + || !is(&insns[c + 9], "v_add_nc_u32", &[v], &[Opnd::Vgpr(tmp), v]) + || !is(&insns[c + 11], "s_mov_b32", &[Opnd::ExecLo], &[Opnd::ConstInt(0)]) || !is(&insns[c + 12], "s_mov_b32", &[Opnd::ExecHi], &[ones]) + || !is(&insns[c + 14], "s_mov_b32", &[Opnd::ExecLo], &[ones]) || !is(&insns[c + 15], "s_mov_b32", &[Opnd::ExecHi], &[ones]) + || !is(&insns[c + 16], "v_sub_nc_u32", &[v], &[v, Opnd::Vgpr(x)]) || !is(&insns[c + 17], "s_mov_b64", &[Opnd::ExecLo], &[s]) { + return None; + } + let half = readlane(&insns[c + 10], acc, 31)?; + if !is(&insns[c + 13], "v_add_nc_u32", &[v], &[Opnd::Sgpr(half), v]) { + return None; + } + // The permlanex temporary, the cross-half readlane result and the accumulator + // are scratch: the compiler's liveness analysis only reads them after they have + // been rewritten, so nopping the pattern's writes to them is safe. + insns[c + 1..c + 16].iter_mut().for_each(nop); + let r = &mut insns[c + 16]; + r.mnemonic = PREFIX.into(); + (r.enc, r.op) = (Enc::Sop1, PSEUDO_OP); + r.src = vec![Opnd::Vgpr(x)]; + Some(()) +} + +// The 32-lane exclusive prefix: an inclusive DPP16 row_shr scan and cross-row +// carry, minus the input. Unlike the 64-lane form, a 32-lane wave has a single +// half, so there is no cross-half readlane/carry and the result is per-lane: +// the whole accumulator holds the exclusive prefix, so no lane read is needed. +// The compiler may intersect the saved EXEC with another scalar mask +// (s_and_b32) before the cndmask; that adds one instruction. +fn prefix32(insns: &mut [Insn], a: usize) -> Option<()> { + let saved = match insns.get(a) { + Some(ins) if ins.mnemonic == "s_or_saveexec_b32" && ins.dst.len() == 1 && ins.src == [Opnd::ConstInt(-1)] => { + let Opnd::Sgpr(s) = ins.dst[0] else { return None }; + s + } + _ => return None, + }; + // The cndmask follows the saveexec, possibly after an s_waitcnt and/or an + // s_and_b32 that intersects the saved EXEC with another scalar mask. + let (c, mask) = cndmask_at(insns, a, saved)?; + if insns.len() < c + 13 { return None; } - let half = readlane(&w[11], acc, 31)?; - if !is(&w[14], "v_add_nc_u32", &[v], &[Opnd::Sgpr(half), v]) { + let cnd = &insns[c]; + let Opnd::Vgpr(x) = *cnd.dst.first()? else { return None }; + if cnd.src.len() != 3 || cnd.src[0] != Opnd::ConstInt(0) || cnd.src[2] != mask + || !matches!(cnd.src[1], Opnd::Vgpr(_)) { return None; } - // Lanes 16-31 and 48-63 read lane 15 of the other row: FI and BC are set, - // and both selectors are -1, so the source lane is always active. - if !(dead_from(insns, a + 19, Reg::V(tmp)) && dead_from(insns, a + 19, Reg::S(half))) { + let Opnd::Vgpr(acc) = *insns[c + 1].dst.first()? else { return None }; + let Opnd::Vgpr(tmp) = *insns[c + 7].dst.first()? else { return None }; + let (v, ones) = (Opnd::Vgpr(acc), Opnd::ConstInt(-1)); + // The result is stored by a plain move of the accumulator; the destination may be + // the original data register or a separate register the caller uses later. + if !is(&insns[c + 1], "v_mov_b32", &[v], &[Opnd::Vgpr(x)]) || acc == x + || ![0xff0911, 0xff0112, 0xff0114, 0xff0118].iter().enumerate().all(|(i, &ctl)| dpp(&insns[c + 2 + i], acc, 250, ctl)) + || !is(&insns[c + 6], "s_mov_b32", &[Opnd::ExecLo], &[Opnd::Literal(0xffff0000)]) + || !is(&insns[c + 7], "v_permlanex16_b32", &[Opnd::Vgpr(tmp)], &[v, ones, ones]) + || !is(&insns[c + 8], "v_add_nc_u32", &[v], &[Opnd::Vgpr(tmp), v]) + || !is(&insns[c + 9], "s_mov_b32", &[Opnd::ExecLo], &[Opnd::ConstInt(-1)]) + || !is(&insns[c + 10], "v_sub_nc_u32", &[v], &[v, Opnd::Vgpr(x)]) + || !is(&insns[c + 11], "s_mov_b32", &[Opnd::ExecLo], &[Opnd::Sgpr(saved)]) + || !(insns[c + 12].mnemonic == "v_mov_b32" + && matches!(insns[c + 12].dst.first(), Some(Opnd::Vgpr(_))) + && insns[c + 12].src == [v]) { return None; } - insns[a + 2..a + 17].iter_mut().for_each(nop); - let r = &mut insns[a + 17]; + // The accumulator holds the exclusive prefix; the final move copies it to the + // original data register. Replace the sub with the pseudo-op and nop the body. + // The permlanex temporary is scratch: the compiler's liveness analysis only reads + // it after it has been rewritten, so nopping the pattern's write to it is safe. + insns[c + 1..c + 10].iter_mut().for_each(nop); + let r = &mut insns[c + 10]; r.mnemonic = PREFIX.into(); (r.enc, r.op) = (Enc::Sop1, PSEUDO_OP); r.src = vec![Opnd::Vgpr(x)]; Some(()) } +/// Lower a whole-wave total that `wave_sum` lowered to `DPP_REDUCE` into a +/// `WaveActiveSum`. The reduction region spans `start` (save-EXEC) through +/// `end` (EXEC restore); the lane-0 read is at `end - 1`. Only integer totals +/// (`v_add_nc_u32`) are lowered; extrema keep their per-lane lowering. +fn total_to_wave_active_sum(insns: &mut [Insn], start: usize, end: usize, width: u32) -> Option<()> { + let saved = match insns.get(start) { + Some(ins) if ins.mnemonic == (if width == 32 { "s_or_saveexec_b32" } else { "s_or_saveexec_b64" }) + && ins.dst.len() == 1 && ins.src == [Opnd::ConstInt(-1)] => + { + let Opnd::Sgpr(s) = ins.dst[0] else { return None }; + s + } + _ => return None, + }; + let (c, _mask) = cndmask_at(insns, start, saved)?; + let first = c + 1; + let dpp = insns.get(first)?; + if dpp.op != wave_sum::DPP_REDUCE || dpp.aux.imm != 0 || dpp.mnemonic != "v_add_nc_u32" { + return None; + } + let cnd = &insns[c]; + let Opnd::Vgpr(acc) = *cnd.dst.first()? else { return None }; + let read = insns.get(end - 1)?; + if read.op != wave_sum::READ_LANE { + return None; + } + let Opnd::Sgpr(sum) = read.dst[0] else { return None }; + // Nop the body (c+1 .. end-1) so the accumulator keeps the per-lane values + // selected by the cndmask, and replace the lane-0 read with the total. + insns[c + 1..end - 1].iter_mut().for_each(nop); + let r = &mut insns[end - 1]; + r.mnemonic = TOTAL.into(); + (r.enc, r.op) = (Enc::Sop1, PSEUDO_OP); + r.dst = vec![Opnd::Sgpr(sum)]; + r.src = vec![Opnd::Vgpr(acc)]; + Some(()) +} + +/// Lower every whole-wave total that `wave_sum` would reject on control flow +/// (an early exit before it, or a divergent branch crossing it) to +/// `WaveActiveSum`, which is safe in divergent control flow. Clean totals are +/// left for `wave_sum`, which lowers them per-lane. Returns an error when a +/// non-total reduction is rejected, since there is no whole-wave form for extrema. +pub(super) fn lower_problematic_totals(insns: &mut [Insn], width: u32) -> Result<(), String> { + let mut verified_reads = Vec::new(); + let regions: Vec<(usize, std::ops::RangeInclusive)> = + wave_sum::reduction_regions(insns, width).collect(); + for (first, region) in regions { + let start = insns[*region.start()].offset as i64; + let end = insns[*region.end()].offset as i64; + let last_read = *region.end() - 1; + if wave_sum::check_region(insns, first, start, end, &verified_reads).is_err() { + if insns[first].mnemonic != "v_add_nc_u32" { + return Err("wave reduction in divergent control flow".into()); + } + total_to_wave_active_sum(insns, *region.start(), *region.end(), width); + continue; + } + verified_reads.push(last_read); + } + Ok(()) +} + /// Rewrite every recognized sequence. Unrecognized ones stay for `wave_sum`. -pub(super) fn prepare(insns: &mut [Insn]) { +/// Returns the guest wave width (32 or 64 lanes) of the recognized sequences, or +/// `None` when there are none; the host wave must match so that `WavePrefixSum` +/// and `WaveActiveSum` are correct. +/// +/// The exclusive prefix — which `wave_sum` does not recognize — is always lowered +/// here. The integer total is lowered by `wave_sum`, which lowers it per-lane and +/// verifies its control flow; only the totals it rejects are lowered here to +/// `WaveActiveSum` (see [`lower_problematic_totals`]), and only when the lockstep +/// fallback cannot prove the program. For pixel shaders every total is lowered +/// unconditionally, because a pixel is a wave of its own and has no lockstep +/// fallback. +pub(super) fn prepare(insns: &mut [Insn], stage: Stage) -> Result, String> { + let mut width = None; for a in 0..insns.len() { - if insns[a].mnemonic == "s_or_saveexec_b64" && total(insns, a).is_none() { - let _ = prefix(insns, a); + if insns[a].mnemonic == "s_or_saveexec_b64" { + let matched = if stage == Stage::Pixel { + total(insns, a).is_some() || prefix(insns, a).is_some() + } else { + prefix(insns, a).is_some() + }; + if matched { + match width { + None => width = Some(64), + Some(ow) if ow != 64 => return Err("conflicting wave allocation widths".into()), + Some(_) => (), + } + } + } else if insns[a].mnemonic == "s_or_saveexec_b32" { + let matched = if stage == Stage::Pixel { + total32(insns, a).is_some() || prefix32(insns, a).is_some() + } else { + prefix32(insns, a).is_some() + }; + if matched { + match width { + None => width = Some(32), + Some(ow) if ow != 32 => return Err("conflicting wave allocation widths".into()), + Some(_) => (), + } + } } } + Ok(width) } pub(super) fn emit(em: &mut Emitter, ins: &Insn) -> Result { diff --git a/tools/shader-compiler/src/hlsl/wave_sum.rs b/tools/shader-compiler/src/hlsl/wave_sum.rs index 101ae0a5..e94f7566 100644 --- a/tools/shader-compiler/src/hlsl/wave_sum.rs +++ b/tools/shader-compiler/src/hlsl/wave_sum.rs @@ -758,40 +758,67 @@ fn guard_region( false } +/// Validate the control flow of a single reduction region: the one whose first +/// DPP instruction is at `first`, spanning the byte offsets `start..=end`. +/// Returns an error when the region may execute on a partial lane set (an early +/// exit before it, or a divergent branch crossing it). `verified_reads` are the +/// result reads of the regions before this one, matching the order +/// [`check_control_flow`] processes them. +pub(super) fn check_region( + insns: &[Insn], + first: usize, + start: i64, + end: i64, + verified_reads: &[usize], +) -> Result<(), String> { + let ins = &insns[first]; + for (branch_index, branch) in insns.iter().enumerate().filter(|(_, i)| i.enc == Enc::Sopp) { + let pc = branch.offset as i64; + if branch.op == 1 && pc < start { + return Err(format!("wave reduction at {start:#x} after an early exit")); + } + if Emitter::branch_cond(branch.op).is_some() { + let target = pc + 4 + 4 * branch.aux.imm; + if (pc < start && target >= start) || (pc > end && target <= end) + || (pc >= start && pc <= end) + { + if !guard_region(insns, branch_index, start as usize, end as usize, first, &ins.mnemonic, verified_reads) { + if std::env::var("TUXBOX_WAVE_DEBUG").is_ok() { + let prev = insns.get(branch_index.checked_sub(1).unwrap_or(0)); + eprintln!("WAVEDEBUG region=[{start:#x}..{end:#x}] op={} branch_idx={} op={} pc={:#x} target={:#x} prev={:?}", + ins.mnemonic, branch_index, branch.op, pc, target, + prev.map(|p| (p.mnemonic.as_str(), p.src.iter().map(|o| format!("{o:?}")).collect::>()))); + } + return Err(format!( + "wave reduction at {start:#x} may execute in divergent control flow" + )); + } + } + } + } + Ok(()) +} + /// Validate fixed-width reductions and return EXECZ instruction indices whose /// masked region and whole-wave arrival permit a wave-wide empty-EXEC vote. pub(super) fn check_control_flow(insns: &[Insn], width: u32) -> Result, String> { let mut execz_guards = BTreeSet::new(); let mut verified_reads = Vec::new(); for (first, region) in reduction_regions(insns, width) { - let ins = &insns[first]; let start = insns[*region.start()].offset as i64; let end = insns[*region.end()].offset as i64; let last_read = *region.end() - 1; + check_region(insns, first, start, end, &verified_reads)?; + // Every branch that affects the region passed `check_region`, so the + // EXECZ ones among them are safe to vote on. for (branch_index, branch) in insns.iter().enumerate().filter(|(_, i)| i.enc == Enc::Sopp) { let pc = branch.offset as i64; - if branch.op == 1 && pc < start { - return Err(format!("wave reduction at {start:#x} after an early exit")); - } - if Emitter::branch_cond(branch.op).is_some() { + if branch.op == 8 && Emitter::branch_cond(branch.op).is_some() { let target = pc + 4 + 4 * branch.aux.imm; if (pc < start && target >= start) || (pc > end && target <= end) || (pc >= start && pc <= end) { - if !guard_region(insns, branch_index, start as usize, end as usize, first, &ins.mnemonic, &verified_reads) { - if std::env::var("TUXBOX_WAVE_DEBUG").is_ok() { - let prev = insns.get(branch_index.checked_sub(1).unwrap_or(0)); - eprintln!("WAVEDEBUG region=[{start:#x}..{end:#x}] op={} branch_idx={} op={} pc={:#x} target={:#x} prev={:?}", - ins.mnemonic, branch_index, branch.op, pc, target, - prev.map(|p| (p.mnemonic.as_str(), p.src.iter().map(|o| format!("{o:?}")).collect::>()))); - } - return Err(format!( - "wave reduction at {start:#x} may execute in divergent control flow" - )); - } - if branch.op == 8 { - execz_guards.insert(branch_index); - } + execz_guards.insert(branch_index); } } } From 65533685364edadab5b6192ea11f0d124e1d4835 Mon Sep 17 00:00:00 2001 From: Pavel Kirilin Date: Wed, 25 Nov 2026 18:49:10 +0100 Subject: [PATCH 2/3] Added selftest. Signed-off-by: Pavel Kirilin --- build.py | 1 + examples/lanes/selftest.cpp | 35 +++++++++++++- examples/lanes/wave_alloc_fixture.py | 68 ++++++++++++++++++++++++++++ project_tuxbox/verify.py | 59 +++++++++++++++++++++++- 4 files changed, 159 insertions(+), 4 deletions(-) create mode 100644 examples/lanes/wave_alloc_fixture.py diff --git a/build.py b/build.py index be0a512b..d1444ae9 100644 --- a/build.py +++ b/build.py @@ -334,6 +334,7 @@ def build_target(tools, target, dxc, d3d12_reference=None): game = tools.compile(src / "game.cpp", objects) subprocess.run([sys.executable, str(src / "shader_fixture.py"), "xbox_shader.h"], cwd=objects, check=True) subprocess.run([sys.executable, str(src / "raster_fixture.py"), "raster_shader.h"], cwd=objects, check=True) + subprocess.run([sys.executable, str(src / "wave_alloc_fixture.py"), "wave_alloc_shader.h"], cwd=objects, check=True) selftest = tools.compile(src / "selftest.cpp", objects, f"/I{objects}") xmem, d3d, gameinput = OUTPUT / "xmem-smoke", OUTPUT / "d3d12-smoke", OUTPUT / "gameinput" tools.link(objects / "lanes.exe", course, screen, controls, game, selftest, xmem / "xmem.lib", diff --git a/examples/lanes/selftest.cpp b/examples/lanes/selftest.cpp index 1abd0827..3934288f 100644 --- a/examples/lanes/selftest.cpp +++ b/examples/lanes/selftest.cpp @@ -15,6 +15,7 @@ #include "xbox_shader.h" #include "raster_shader.h" #include "reclaim_shader.h" +#include "wave_alloc_shader.h" #include #include @@ -630,6 +631,36 @@ void raster_tables(ID3D12Device* device) { } } + +// A console shader whose wave32 masked DPP exclusive prefix the translator must +// lower to `WavePrefixSum`. The old translator rejects it with "unrecognized +// masked DPP prologue", so this scenario fails without the wave-alloc lowering. +void wave_alloc_scenario(ID3D12Device* device) { + ComPtr root; + D3D12_ROOT_SIGNATURE_DESC signature{}; + ComPtr serialized; + check(D3D12SerializeRootSignature(&signature, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr), + "serialize empty root signature"); + check(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), + IID_PPV_ARGS(&root)), "create empty root signature"); + D3D12_COMPUTE_PIPELINE_STATE_DESC shader{}; + shader.pRootSignature = root.Get(); + shader.CS = {wave_alloc_shader, sizeof(wave_alloc_shader)}; + ComPtr pipeline; + check(method(device, device_create_compute)(device, &shader, 0, nullptr, + IID_PPV_ARGS(&pipeline)), + "create pipeline from the wave-alloc console shader"); + Memory memory(65536); + Queue compute(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); + method(compute.list.Get(), slot_compute_root)(compute.list.Get(), root.Get()); + compute.list->SetPipelineState(pipeline.Get()); + compute.list->Dispatch(1, 1, 1); + compute.write64(memory.address(0), 3); + compute.submit(); + compute.finish("dispatch of the wave-alloc console shader"); + expect_value(memory, 0, 3, "write after the dispatch"); +} + ComPtr compute_pipeline(ID3D12Device* device, ComPtr& root, D3D12_SHADER_BYTECODE bytecode) { D3D12_ROOT_PARAMETER params[2]{}; @@ -1660,6 +1691,7 @@ constexpr Scenario scenarios[] = { {L"xbox-shader", xbox_shader_scenario}, {L"wave64-shader", wave64_shader_scenario}, {L"raster-tables", raster_tables}, + {L"wave-alloc", wave_alloc_scenario}, }; // A fresh Scarlett device on the requested adapter. The factory is reached @@ -1711,8 +1743,7 @@ const wchar_t* const selftest_scenarios[] = {L"labels", L"cross-queue L"indirect-dispatch", L"gpu-indirect-dispatch", L"dispatch-wait", L"texture-readback", L"ray-tracing-builder", L"thread-dimensions", L"descriptor-reclaim", - L"xbox-shader", L"wave64-shader", - L"raster-tables"}; + L"xbox-shader", L"wave64-shader", L"raster-tables", L"wave-alloc"}; const unsigned selftest_scenario_count = static_cast(std::size(selftest_scenarios)); static_assert(std::size(selftest_scenarios) == std::size(scenarios)); diff --git a/examples/lanes/wave_alloc_fixture.py b/examples/lanes/wave_alloc_fixture.py new file mode 100644 index 00000000..f81bfffb --- /dev/null +++ b/examples/lanes/wave_alloc_fixture.py @@ -0,0 +1,68 @@ +"""The synthetic Xbox compute shader the Lanes self-test loads for the +wave-alloc self-test. + +It is a small hand-written console program: a constant input, a wave32 masked +DPP exclusive-prefix (the pattern the translator lowers to `WavePrefixSum`), +and an `s_endpgm`. Not taken from any game. +""" +import hashlib +from pathlib import Path +import struct +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from tools.reference.scarlett_worker_fixture import container, pack # noqa: E402 + +CODE = ( + 0x7e000281, # v_mov_b32 v0, 1 + 0xbe803dc1, # s_or_saveexec_b32 s0, -1 + 0xd5010001, # v_cndmask_b32 v1, 0, v0, s0 + 0x00020080, + 0x7e040301, # v_mov_b32 v2, v1 + 0x4a0404fa, # v_add_nc_u32 v2, 250, v2 (DPP row_shr) + 0xff091102, + 0x4a0404fa, + 0xff011202, + 0x4a0404fa, + 0xff011402, + 0x4a0404fa, + 0xff011802, + 0xbefe03ff, # s_mov_b32 ExecLo, 0xffff0000 + 0xffff0000, + 0xd7780003, # v_permlanex16_b32 v3, v2, -1, -1 + 0x03058302, + 0x4a040503, # v_add_nc_u32 v2, v3, v2 + 0xbefe03c1, # s_mov_b32 ExecLo, -1 + 0x4c040302, # v_sub_nc_u32 v2, v2, v1 + 0xbefe0300, # s_mov_b32 ExecLo, s0 + 0x7e080302, # v_mov_b32 v4, v2 + 0xbf810000, # s_endpgm +) +# Root signature 1.0 with no parameters, samplers or flags. +EMPTY_ROOT = pack([1, 0, 24, 0, 24, 0]) + + +def shader(): + base = container(list(CODE), width=32) + count = struct.unpack_from(" Date: Wed, 25 Nov 2026 23:55:11 +0100 Subject: [PATCH 3/3] Fixed PR comments. Signed-off-by: Pavel Kirilin --- examples/lanes/selftest.cpp | 48 ++++- examples/lanes/wave_alloc_fixture.py | 31 ++-- tools/shader-compiler/src/hlsl/wave_alloc.rs | 164 ++++++++++++++++-- .../src/tests/hlsl/wave_sum.rs | 110 ++++++++++++ 4 files changed, 320 insertions(+), 33 deletions(-) diff --git a/examples/lanes/selftest.cpp b/examples/lanes/selftest.cpp index 3934288f..00b115ae 100644 --- a/examples/lanes/selftest.cpp +++ b/examples/lanes/selftest.cpp @@ -34,6 +34,10 @@ constexpr std::array scarlett_profile{ // scenario that needs that release must already count as failed. constexpr DWORD deadline_ms = 2000; +// Sentinel written to the wave-alloc UAV so a shader that never stores is +// distinguishable from one that stored the expected value (0). +constexpr UINT kWaveAllocSentinel = 0xdeadbeefu; + // Xbox command-list and queue slots (GDK gen9/d3d12_xs.h). constexpr size_t slot_copy_memory = 62, slot_write32 = 71, slot_write64 = 72, slot_wait64 = 74, slot_dispatch_flagged = 80, slot_copy_texture = 83, slot_build = 119, @@ -635,14 +639,22 @@ void raster_tables(ID3D12Device* device) { // A console shader whose wave32 masked DPP exclusive prefix the translator must // lower to `WavePrefixSum`. The old translator rejects it with "unrecognized // masked DPP prologue", so this scenario fails without the wave-alloc lowering. +// The shader stores the exclusive-prefix result (0 for the single active lane) +// to a UAV; the scenario reads it back and requires it to be the expected +// value, so a numerical miscompile of the lowering is caught here. void wave_alloc_scenario(ID3D12Device* device) { - ComPtr root; + D3D12_ROOT_PARAMETER params[1]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[0].Descriptor = {0, 0}; D3D12_ROOT_SIGNATURE_DESC signature{}; + signature.NumParameters = 1; + signature.pParameters = params; ComPtr serialized; check(D3D12SerializeRootSignature(&signature, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr), - "serialize empty root signature"); + "serialize wave-alloc root signature"); + ComPtr root; check(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(), - IID_PPV_ARGS(&root)), "create empty root signature"); + IID_PPV_ARGS(&root)), "create wave-alloc root signature"); D3D12_COMPUTE_PIPELINE_STATE_DESC shader{}; shader.pRootSignature = root.Get(); shader.CS = {wave_alloc_shader, sizeof(wave_alloc_shader)}; @@ -650,15 +662,33 @@ void wave_alloc_scenario(ID3D12Device* device) { check(method(device, device_create_compute)(device, &shader, 0, nullptr, IID_PPV_ARGS(&pipeline)), "create pipeline from the wave-alloc console shader"); - Memory memory(65536); + auto output = buffer(device, D3D12_HEAP_TYPE_DEFAULT, sizeof(UINT), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + // Seed the UAV with a sentinel so a missing store is distinguishable from the + // expected value (0) in the readback. + auto sentinel = buffer(device, D3D12_HEAP_TYPE_UPLOAD, sizeof(UINT), D3D12_RESOURCE_STATE_GENERIC_READ); + compute_fixture::upload(sentinel.Get(), &kWaveAllocSentinel, sizeof(kWaveAllocSentinel)); + auto proof = buffer(device, D3D12_HEAP_TYPE_READBACK, sizeof(UINT), D3D12_RESOURCE_STATE_COPY_DEST); Queue compute(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); - method(compute.list.Get(), slot_compute_root)(compute.list.Get(), root.Get()); - compute.list->SetPipelineState(pipeline.Get()); - compute.list->Dispatch(1, 1, 1); - compute.write64(memory.address(0), 3); + auto* list = compute.list.Get(); + list->CopyBufferRegion(output.Get(), 0, sentinel.Get(), 0, sizeof(UINT)); + method(list, slot_compute_root)(list, root.Get()); + list->SetPipelineState(pipeline.Get()); + method(list, slot_root_uav)(list, 0, output->GetGPUVirtualAddress()); + compute_fixture::transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->Dispatch(1, 1, 1); + compute_fixture::transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(proof.Get(), 0, output.Get(), 0, sizeof(UINT)); compute.submit(); compute.finish("dispatch of the wave-alloc console shader"); - expect_value(memory, 0, 3, "write after the dispatch"); + D3D12_RANGE range{0, sizeof(UINT)}, empty{}; + void* mapped{}; + check(proof->Map(0, &range, &mapped), "map wave-alloc proof"); + const UINT row = *static_cast(mapped); + proof->Unmap(0, &empty); + if (row != 0u) throw std::runtime_error("wave-alloc shader stored the wrong prefix result (or stored nothing)"); } ComPtr compute_pipeline(ID3D12Device* device, ComPtr& root, diff --git a/examples/lanes/wave_alloc_fixture.py b/examples/lanes/wave_alloc_fixture.py index f81bfffb..6c5bdbcb 100644 --- a/examples/lanes/wave_alloc_fixture.py +++ b/examples/lanes/wave_alloc_fixture.py @@ -3,7 +3,9 @@ It is a small hand-written console program: a constant input, a wave32 masked DPP exclusive-prefix (the pattern the translator lowers to `WavePrefixSum`), -and an `s_endpgm`. Not taken from any game. +and an `s_endpgm`. The prefix result is stored to a UAV so the self-test can +read it back and check the shader's arithmetic, not just that it dispatched. +Not taken from any game. """ import hashlib from pathlib import Path @@ -36,24 +38,25 @@ 0x4c040302, # v_sub_nc_u32 v2, v2, v1 0xbefe0300, # s_mov_b32 ExecLo, s0 0x7e080302, # v_mov_b32 v4, v2 + 0x7e100280, # v_mov_b32 v8, 0 (address of the result in the UAV) + 0xf4080402, # s_load_dwordx4 s[16:19], s[4:5], 0 + 0xfa000000, + 0xbf8cc07f, # s_waitcnt lgkmcnt(0) + 0xe0701000, # buffer_store_dword v4, v8, s[16:19], 0 (offset 0) + 0x80040408, 0xbf810000, # s_endpgm ) -# Root signature 1.0 with no parameters, samplers or flags. -EMPTY_ROOT = pack([1, 0, 24, 0, 24, 0]) +# Root signature 1.0 with a single UAV table for the result buffer. +UAV_ROOT = pack([1, 1, 24, 0, 0, 0, 0, 0, 36, 1, 44, 1, 1, 0, 0, 0]) def shader(): - base = container(list(CODE), width=32) - count = struct.unpack_from(" Option { + let wide = |m: &str| if m.contains("x16") { 16 } else if m.contains("x8") { 8 } else if m.contains("x4") || m.contains("xyzw") { 4 } + else if m.contains("x3") || m.contains("xyz") { 3 } else if m.contains("x2") || m.contains("xy") { 2 } else { 1 }; + ["buffer_", "tbuffer_", "image_", "global_", "ds_", "exp", "s_load", "s_buffer_load"].iter() + .any(|p| m.starts_with(p)).then(|| wide(m).max(4)) +} + +fn covers(o: &Opnd, r: Reg, width: u16) -> bool { + let (k, n) = match (*o, r) { + (Opnd::Vgpr(k), Reg::V(n)) | (Opnd::Sgpr(k), Reg::S(n)) => (k, n), + _ => return false, + }; + u16::from(k) <= u16::from(n) && u16::from(n) < u16::from(k) + width +} + +fn reads(ins: &Insn, r: Reg) -> bool { + let m = ins.mnemonic.as_str(); + if let Some(width) = memory_width(m) { + // Store and atomic data are decoded as destinations. MUBUF VADDR is + // ignored when neither OFFEN nor IDXEN is set. + let unused_vaddr = ins.enc == Enc::Mubuf && ins.aux.mask & 3 == 0; + let data = !m.starts_with("s_") && !m.contains("_load"); + return ins.src.iter().enumerate().any(|(i, o)| !(unused_vaddr && i == 0) && covers(o, r, width)) + || (data || m.contains("atomic")) && ins.dst.iter().any(|o| covers(o, r, width)); + } + match r { + Reg::S(n) => super::reads_sgpr(ins, n), + Reg::V(_) => { + let width = if m.contains("64") && m.starts_with("v_") { 2 } else { 1 }; + ins.src.iter().any(|o| covers(o, r, width)) + } + } +} + +/// A write that defines `r` in every lane that can later read it. +fn kills(ins: &Insn, r: Reg, whole_wave: bool) -> bool { + let m = ins.mnemonic.as_str(); + match r { + Reg::S(n) => { + if matches!(m, "v_readlane_b32" | "v_readfirstlane_b32") { + return matches!(ins.dst.first(), Some(Opnd::Vgpr(k) | Opnd::Sgpr(k)) if *k == n); + } + let width = if m.starts_with("s_load") || m.starts_with("s_buffer_load") { memory_width(m).unwrap_or(1) } + else if m.starts_with("s_") && m.ends_with("64") { 2 } else { 1 }; + (m.starts_with("s_") || m.starts_with("v_cmp")) && ins.dst.iter().any(|o| covers(o, r, width)) + } + // Inactive lanes keep the old value; only whole-wave vector writes kill. + Reg::V(_) => whole_wave && m.starts_with("v_") && !m.starts_with("v_cmp") && memory_width(m).is_none() + && !matches!(m, "v_readlane_b32" | "v_readfirstlane_b32") && ins.dst == [match r { Reg::V(n) => Opnd::Vgpr(n), Reg::S(n) => Opnd::Sgpr(n) }], + } +} + +/// Every path from `start` overwrites `r` before reading it. +fn dead_from(insns: &[Insn], start: usize, r: Reg) -> bool { + let index_of = |offset: i64| insns.iter().position(|i| i.offset as i64 == offset); + let mut stack = vec![(start, false)]; + let mut seen = BTreeSet::new(); + while let Some((mut at, mut whole)) = stack.pop() { + loop { + if !seen.insert((at, whole)) { break; } + let Some(ins) = insns.get(at) else { break }; + if reads(ins, r) { + if std::env::var_os("TB_DFDEBUG").is_some() { eprintln!("wave_alloc: live at {:#x} {}", ins.offset, ins.mnemonic); } + return false; + } + if kills(ins, r, whole) { break; } + let m = ins.mnemonic.as_str(); + if ins.dst.contains(&Opnd::ExecLo) || ins.dst.contains(&Opnd::ExecHi) || m.contains("saveexec") || m.starts_with("v_cmpx") { + whole = m == "s_or_saveexec_b64" && ins.src == [Opnd::ConstInt(-1)] + || m == "s_mov_b64" && ins.dst == [Opnd::ExecLo] && ins.src == [Opnd::ConstInt(-1)]; + } + if matches!(m, "s_setpc_b64" | "s_swappc_b64") { return false; } + if m == "s_endpgm" { break; } + if ins.enc == Enc::Sopp { + let target = ins.offset as i64 + 4 + 4 * ins.aux.imm; + if ins.op == 2 { + let Some(t) = index_of(target) else { return false }; + at = t; + continue; + } + if Emitter::branch_cond(ins.op).is_some() { + let Some(t) = index_of(target) else { return false }; + stack.push((t, whole)); + } + } + at += 1; + } + } + true +} + fn dpp(ins: &Insn, acc: u8, selector: u16, ctrl: u32) -> bool { ins.mnemonic == "v_add_nc_u32" && ins.dst == [Opnd::Vgpr(acc)] && ins.src == [Opnd::Raw(selector), Opnd::Vgpr(acc)] && ins.raw.get(1) == Some(&(ctrl << 8 | u32::from(acc))) @@ -96,8 +191,14 @@ fn total(insns: &mut [Insn], a: usize) -> Option<()> { return None; } // The permlanex temporary, the cross-half readlane result and the accumulator - // are scratch: the compiler's liveness analysis only reads them after they have - // been rewritten, so nopping the pattern's writes to them is safe. + // are scratch: nopping the pattern's writes to them is only safe when every + // later instruction overwrites them before reading them, so prove they are + // dead before the rewrite. + let end = c + 11; + if !(dead_from(insns, end, Reg::V(acc)) && dead_from(insns, end, Reg::V(tmp)) + && (high == sum || dead_from(insns, end, Reg::S(high)))) { + return None; + } insns[c + 1..c + 9].iter_mut().for_each(nop); let r = &mut insns[c + 9]; r.mnemonic = TOTAL.into(); @@ -137,9 +238,14 @@ fn total32(insns: &mut [Insn], a: usize) -> Option<()> { if !is(&insns[c + 8], "s_mov_b32", &[Opnd::ExecLo], &[s]) { return None; } - // The permlanex temporary and the accumulator are scratch: the compiler's liveness - // analysis only reads them after they have been rewritten, so nopping the pattern's - // writes to them is safe. + // The permlanex temporary and the accumulator are scratch: nopping the + // pattern's writes to them is only safe when every later instruction + // overwrites them before reading them, so prove they are dead before the + // rewrite. + let end = c + 9; + if !(dead_from(insns, end, Reg::V(acc)) && dead_from(insns, end, Reg::V(tmp))) { + return None; + } insns[c + 1..c + 7].iter_mut().for_each(nop); let r = &mut insns[c + 7]; r.mnemonic = TOTAL.into(); @@ -183,9 +289,15 @@ fn prefix(insns: &mut [Insn], a: usize) -> Option<()> { if !is(&insns[c + 13], "v_add_nc_u32", &[v], &[Opnd::Sgpr(half), v]) { return None; } - // The permlanex temporary, the cross-half readlane result and the accumulator - // are scratch: the compiler's liveness analysis only reads them after they have - // been rewritten, so nopping the pattern's writes to them is safe. + // The permlanex temporary and the cross-half readlane result are scratch: + // nopping the pattern's writes to them is only safe when every later + // instruction overwrites them before reading them, so prove they are dead + // before the rewrite. The accumulator holds the prefix in both the original + // and the lowered form, so it needs no liveness check. + let end = c + 18; + if !(dead_from(insns, end, Reg::V(tmp)) && dead_from(insns, end, Reg::S(half))) { + return None; + } insns[c + 1..c + 16].iter_mut().for_each(nop); let r = &mut insns[c + 16]; r.mnemonic = PREFIX.into(); @@ -240,8 +352,13 @@ fn prefix32(insns: &mut [Insn], a: usize) -> Option<()> { } // The accumulator holds the exclusive prefix; the final move copies it to the // original data register. Replace the sub with the pseudo-op and nop the body. - // The permlanex temporary is scratch: the compiler's liveness analysis only reads - // it after it has been rewritten, so nopping the pattern's write to it is safe. + // The permlanex temporary is scratch: nopping the pattern's write to it is only + // safe when every later instruction overwrites it before reading it, so prove it + // is dead before the rewrite. + let end = c + 13; + if !dead_from(insns, end, Reg::V(tmp)) { + return None; + } insns[c + 1..c + 10].iter_mut().for_each(nop); let r = &mut insns[c + 10]; r.mnemonic = PREFIX.into(); @@ -277,6 +394,33 @@ fn total_to_wave_active_sum(insns: &mut [Insn], start: usize, end: usize, width: return None; } let Opnd::Sgpr(sum) = read.dst[0] else { return None }; + // The permlanex temporary and, for the 64-lane form, the cross-half readlane + // result are scratch: nopping the body is only safe when every later + // instruction overwrites them before reading them, so prove they are dead + // before the rewrite. The accumulator keeps the per-lane values selected by + // the cndmask, which is exactly what WaveActiveSum consumes. + let tmp = match insns.get(c + 5) { + Some(ins) if ins.mnemonic == "v_permlanex16_b32" => { + let Opnd::Vgpr(t) = ins.dst[0] else { return None }; + t + } + _ => return None, + }; + let high = if width == 64 { + let ins = insns.get(c + 7)?; + if ins.op != wave_sum::READ_LANE || ins.mnemonic != "v_readlane_b32" { + return None; + } + let Opnd::Sgpr(h) = ins.dst[0] else { return None }; + Some(h) + } else { + None + }; + let after = end + 1; + if !dead_from(insns, after, Reg::V(acc)) || !dead_from(insns, after, Reg::V(tmp)) + || (high.is_some() && high.unwrap() != sum && !dead_from(insns, after, Reg::S(high.unwrap()))) { + return None; + } // Nop the body (c+1 .. end-1) so the accumulator keeps the per-lane values // selected by the cndmask, and replace the lane-0 read with the total. insns[c + 1..end - 1].iter_mut().for_each(nop); diff --git a/tools/shader-compiler/src/tests/hlsl/wave_sum.rs b/tools/shader-compiler/src/tests/hlsl/wave_sum.rs index 99dd80ff..e3a128ce 100644 --- a/tools/shader-compiler/src/tests/hlsl/wave_sum.rs +++ b/tools/shader-compiler/src/tests/hlsl/wave_sum.rs @@ -797,3 +797,113 @@ fn execz_skip_allows_uniform_merge_branch_in_window() { assert!(check_control_flow(&ops, width).is_ok()); } } + +/// A single DPP8/DPP16 shuffle as the pattern matchers expect: `v_add_nc_u32` +/// with the selector as a raw operand and the control word in the second word. +fn dpp_ins(acc: u8, selector: u16, ctrl: u32) -> Insn { + Insn { + offset: 0, + dwords: 1, + enc: Enc::Vop2, + op: 0, + raw: vec![0, ctrl << 8 | u32::from(acc)], + mnemonic: "v_add_nc_u32".into(), + dst: vec![Opnd::Vgpr(acc)], + src: vec![Opnd::Raw(selector), Opnd::Vgpr(acc)], + aux: Default::default(), + } +} + +/// A wave32 masked DPP exclusive prefix: save-EXEC, cndmask, the inclusive +/// row_shr scan, the cross-row carry, the input subtraction and the final move. +/// The permlanex temporary is v3 and the accumulator is v2. +fn wave32_prefix() -> Vec { + let mut ops = vec![ + insn("v_mov_b32", Enc::Vop2, 0, vec![Opnd::Vgpr(0)], vec![Opnd::ConstInt(1)]), + insn("s_or_saveexec_b32", Enc::Sop1, 0, vec![Opnd::Sgpr(0)], vec![Opnd::ConstInt(-1)]), + insn("v_cndmask_b32", Enc::Vop2, 0, vec![Opnd::Vgpr(1)], + vec![Opnd::ConstInt(0), Opnd::Vgpr(0), Opnd::Sgpr(0)]), + insn("v_mov_b32", Enc::Vop2, 0, vec![Opnd::Vgpr(2)], vec![Opnd::Vgpr(1)]), + dpp_ins(2, 250, 0xff0911), + dpp_ins(2, 250, 0xff0112), + dpp_ins(2, 250, 0xff0114), + dpp_ins(2, 250, 0xff0118), + insn("s_mov_b32", Enc::Sop1, 0, vec![Opnd::ExecLo], vec![Opnd::Literal(0xffff0000)]), + insn("v_permlanex16_b32", Enc::Vop1, 0, vec![Opnd::Vgpr(3)], + vec![Opnd::Vgpr(2), Opnd::ConstInt(-1), Opnd::ConstInt(-1)]), + insn("v_add_nc_u32", Enc::Vop2, 0, vec![Opnd::Vgpr(2)], vec![Opnd::Vgpr(3), Opnd::Vgpr(2)]), + insn("s_mov_b32", Enc::Sop1, 0, vec![Opnd::ExecLo], vec![Opnd::ConstInt(-1)]), + insn("v_sub_nc_u32", Enc::Vop2, 0, vec![Opnd::Vgpr(2)], vec![Opnd::Vgpr(2), Opnd::Vgpr(1)]), + insn("s_mov_b32", Enc::Sop1, 0, vec![Opnd::ExecLo], vec![Opnd::Sgpr(0)]), + insn("v_mov_b32", Enc::Vop2, 0, vec![Opnd::Vgpr(4)], vec![Opnd::Vgpr(2)]), + ]; + offsets(&mut ops); + ops +} + +#[test] +fn wave32_prefix_is_rejected_when_the_scratch_temp_is_read_later() { + // The clean prefix is lowered to the exclusive-prefix pseudo-op. + let mut clean = wave32_prefix(); + let width = super::super::wave_alloc::prepare(&mut clean, Stage::Compute).unwrap(); + assert_eq!(width, Some(32)); + assert!(clean.iter().any(|i| i.mnemonic == "tb_wave_exclusive_prefix_u32"), + "the clean prefix must be lowered"); + + // A later read of the nopped permlanex temporary (v3) would receive stale + // data, so the liveness proof must reject the lowering. + let mut live = wave32_prefix(); + live.push(insn("v_mov_b32", Enc::Vop2, 0, vec![Opnd::Vgpr(5)], vec![Opnd::Vgpr(3)])); + offsets(&mut live); + let width = super::super::wave_alloc::prepare(&mut live, Stage::Compute).unwrap(); + assert_eq!(width, None, "a live scratch temporary must prevent the lowering"); + assert!(!live.iter().any(|i| i.mnemonic == "tb_wave_exclusive_prefix_u32")); +} + +/// Disassemble the 64-lane whole-wave total from the wave-guard fixture. +fn wave64_total() -> Vec { + let raw = [ + 0xbe80_25c1u32, + 0xd501_0002, 0x0002_0080, + 0x4a04_04e9, 0xde54_c102, + 0x4a04_04e9, 0x9360_1202, + 0x4a04_04e9, 0x0009_2402, + 0x4a04_04fa, 0xff09_4002, + 0xd778_0003, 0x0201_0102, + 0x4a04_0503, + 0xd760_0006, 0x0001_4102, + 0x4a04_0406, + 0xd760_0007, 0x0001_0102, + 0xbefe_0400, + ]; + let block: Vec = raw.iter().flat_map(|w| w.to_le_bytes()).collect(); + crate::rdna2::disassemble(&block) +} + +/// Append a plain vector move that reads `reg`, mirroring a later use of a +/// scratch register. +fn read_later(ops: &mut Vec, reg: Opnd, new_reg: u8) { + let last = ops.last().unwrap().offset + ops.last().unwrap().dwords * 4; + ops.push(insn("v_mov_b32", Enc::Vop2, 0, vec![Opnd::Vgpr(new_reg)], vec![reg])); + ops.last_mut().unwrap().offset = last; +} + +#[test] +fn wave64_total_is_rejected_when_a_scratch_temp_is_read_later() { + // The clean 64-lane total (pixel) is lowered to the WaveActiveSum pseudo-op. + let mut clean = wave64_total(); + let width = super::super::wave_alloc::prepare(&mut clean, Stage::Pixel).unwrap(); + assert_eq!(width, Some(64), "the clean total must be lowered"); + assert!(clean.iter().any(|i| i.mnemonic == "tb_wave_total_u32")); + + // A later read of the accumulator (v2), the permlanex temp (v3) or the + // cross-half readlane result (v6, consumed as an SGPR) would receive stale + // data, so the liveness proof must reject the lowering. + for (reg, new_reg) in [(Opnd::Vgpr(2), 40u8), (Opnd::Vgpr(3), 41u8), (Opnd::Sgpr(6), 42u8)] { + let mut live = wave64_total(); + read_later(&mut live, reg, new_reg); + let width = super::super::wave_alloc::prepare(&mut live, Stage::Pixel).unwrap(); + assert_eq!(width, None, "a live scratch register must prevent the lowering"); + assert!(!live.iter().any(|i| i.mnemonic == "tb_wave_total_u32")); + } +}