From e6f1beaa9c3c737541b1dac5e19e48124840523f Mon Sep 17 00:00:00 2001 From: pr0vId3nce <148384071+pr0vId3nce@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:02:39 -0500 Subject: [PATCH 1/4] Shader tests: values alike in a console wave under a lane guard, by wave number and from LDS lane_uniform moves from lower.rs into emit/uniform.rs unchanged (lower.rs is 350 bytes under the 512 KiB policy limit), with a test of what the structure builder's prefix-sum passes need on a host of 32-lane waves: a value written under a lane guard over a value that was alike already, the wave number (tid >> 6) and an LDS read count as alike in the wave; over a value that differs by lane they do not. The test is ryotdev's, from fxceless/victory-fork PR #156. Fails: the proof leaves out every guarded write ("old and new values are uniform"). Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/lower.rs | 65 ++---------- crates/victory-shader/src/emit/mod.rs | 1 + crates/victory-shader/src/emit/uniform.rs | 118 ++++++++++++++++++++++ crates/victory-shader/src/lib.rs | 1 + 4 files changed, 128 insertions(+), 57 deletions(-) create mode 100644 crates/victory-shader/src/emit/uniform.rs diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 04cf1fc2fa..9044e383ca 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -366,7 +366,7 @@ pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read /// Per IR block: every lane of the wave that started the program runs it – no per-lane branch /// separates it from the entry (it lies in no lane branch's region: the blocks reachable from /// the branch that do not post-dominate it). None with an indirect exit (not followed). -fn all_lane_blocks(st: &Structured) -> Option> { +pub(super) fn all_lane_blocks(st: &Structured) -> Option> { let n = st.exits.len(); let mut all = vec![true; n]; for (_, region) in lane_regions(st)? { @@ -474,61 +474,6 @@ fn need(block: usize) { }); } -/// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]): -/// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, -/// constants and such values; or loaded from an address made of them. The compiler keeps -/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. -/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes -/// run (no lane branch can have split the arriving lanes); loop-carried values never do. -fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { - let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); - let mut same: HashSet = HashSet::new(); - for b in crate::ir::reverse_postorder(&p.blocks) { - let block = &p.blocks[b]; - let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); - for phi in &block.phis { - if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { - same.insert(phi.value); - } - } - for (i, inst) in block.insts.iter().enumerate() { - let name = inst.name(); - let ops: Vec = match &inst.fields { - Fields::Valu(v) - if v.dpp.is_none() - && v.sdwa.is_none() - && !name.starts_with("v_mbcnt") - && !name.starts_with("v_cmpx") - && !name.contains("lane") => - { - v.src.clone() - } - _ => continue, - }; - if st.guards[b][i].is_some() { - continue; // lanes outside EXEC keep another value - } - let alike = ops.iter().all(|op| match *op { - Operand::Vector { reg, .. } => { - // every dword of the operand the instruction reads from that register on - let read: Vec = - inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); - !read.is_empty() && read.iter().all(|x| same.contains(x)) - } - // a scalar is one value; a lane mask is not, unless a compare of such values made it - Operand::Scalar { code, .. } if code != NULL => { - inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) - } - _ => true, - }); - if alike { - same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); - } - } - } - same -} - /// What a register value holds, for [`wave_local`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Wave { @@ -1559,7 +1504,13 @@ impl<'a> Lower<'a> { local_ok: false, local_any: LOCAL_ANY.get(), uniform: match &exchange { - Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + Some((_, false, all)) if !LOCAL_WAVES.get() => { + let threads = match x.native.io { + StageIo::Cs(cs) => Some(cs.threads), + _ => None, + }; + super::uniform::lane_uniform(p, x.st, all, threads) + } _ => HashSet::new(), }, own_bits: match &exchange { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index ba72c9be7d..b0ab7d408b 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -98,6 +98,7 @@ mod rect; mod sampler; mod shader; mod threading; +mod uniform; #[cfg(windows)] pub mod validator; #[cfg(all(test, windows))] diff --git a/crates/victory-shader/src/emit/uniform.rs b/crates/victory-shader/src/emit/uniform.rs new file mode 100644 index 0000000000..b12e930e48 --- /dev/null +++ b/crates/victory-shader/src/emit/uniform.rs @@ -0,0 +1,118 @@ +//! Which VGPR values are the same in every lane of a console wave, for a console wave64 +//! program on a host of 32-lane waves: such a value read with `v_readfirstlane` needs no +//! exchange between the two host waves. + +use std::collections::HashSet; + +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{Program, Reg, Value}; +use crate::structure::Structured; + +/// VGPR values that are the same in every lane holding them (`all` is `lower.rs`'s `all_lane_blocks`): +/// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, +/// constants and such values; or loaded from an address made of them. The compiler keeps +/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. +/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes +/// run (no lane branch can have split the arriving lanes); loop-carried values never do. +pub(super) fn lane_uniform(p: &Program, st: &Structured, all: &[bool], _threads: Option<[u32; 3]>) -> HashSet { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let mut same: HashSet = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + let ops: Vec = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.clone() + } + _ => continue, + }; + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } + let alike = ops.iter().all(|op| match *op { + Operand::Vector { reg, .. } => { + // every dword of the operand the instruction reads from that register on + let read: Vec = + inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); + !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + } + _ => true, + }); + if alike { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + } + } + } + same +} + +#[cfg(test)] +mod tests { + use crate::ir::Reg; + use crate::{ir, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + + /// A write under a lane guard leaves the other lanes their old value: the result is alike + /// in every lane only if the old value was (ryotdev's correction to the proof). + #[test] + fn a_guarded_uniform_write_can_keep_different_values_in_each_lane() { + let check = |initial: u32, write: &[u32]| { + let mut words = vec![ + initial, // v_mov_b32 v1, v0 (thread ID) or 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x7D88_0400, // v_cmp_gt_u32 vcc, s0, v2 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + ]; + words.extend_from_slice(write); + words.extend_from_slice(&[ + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x7E0E_0501, // v_readfirstlane_b32 s7, v1 + S_ENDPGM, + ]); + let code: Vec<_> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = ir::build(&code, true, 8).unwrap(); + let st = structure::structure(&p).unwrap(); + let all = super::super::lower::all_lane_blocks(&st).unwrap(); + let uniform = super::lane_uniform(&p, &st, &all, Some([64, 1, 1])); + let read = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "v_readfirstlane_b32") + .unwrap(); + uniform.contains(&read.read(Reg::V(1)).unwrap()) + }; + + let writes: &[(&str, &[u32])] = &[ + ("v_mov_b32 v1, 1", &[0x7E02_0281]), + ("v_lshrrev_b32 v1, 6, v0", &[0x2C02_0086]), + ("ds_read_b32 v1, v2", &[0xD8D8_0000, 0x0100_0002]), + ]; + let mut divergent = Vec::new(); + for &(name, write) in writes { + assert!(check(0x7E02_0280, write), "{name}: old and new values are uniform"); + if check(0x7E02_0300, write) { + divergent.push(name); + } + } + assert!(divergent.is_empty(), "when s0 is zero, lanes keep their IDs: {divergent:?}"); + } +} diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index bf13b0fe32..baba9f4e54 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -70,6 +70,7 @@ translation_inputs! { "emit/shader.rs", "emit/threading.rs", "emit/typed_views.rs", + "emit/uniform.rs", "emit/validator.rs", "emit/wave.rs", "gfx10/fields.rs", From 34b50e88a121c122a3d77aeed89ed4b780cab91c Mon Sep 17 00:00:00 2001 From: pr0vId3nce <148384071+pr0vId3nce@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:02:51 -0500 Subject: [PATCH 2/4] Shaders: the structure builder's prefix-sum passes translate for 32-lane waves On a GPU whose waves are 32 lanes (NVIDIA) three programs of the structure builder stopped on "a first-lane read where not every lane runs": the 512-thread prefix-sum passes fetch a running total with v_readfirstlane inside a loop. One stage without a host pipeline keeps the whole builder off (its stages run all or none), so there was no ray tracing on such a card. The lane-uniformity proof now also takes the wave number (tid >> 6), an LDS read at an address alike in the wave, and values joined by a phi where every predecessor is entered by all arriving lanes or none. It is the proof of fxceless/victory-fork PR #156 by sedzz, with ryotdev's correction for writes under a lane guard. As a host of 32-lane waves, XboxBvhBuilder.dll: 52 of 52 programs emitted (was 49). Co-Authored-By: Claude Fable 5.2 --- crates/victory-shader/src/emit/uniform.rs | 200 +++++++++++++++++----- 1 file changed, 161 insertions(+), 39 deletions(-) diff --git a/crates/victory-shader/src/emit/uniform.rs b/crates/victory-shader/src/emit/uniform.rs index b12e930e48..5a142c7bc5 100644 --- a/crates/victory-shader/src/emit/uniform.rs +++ b/crates/victory-shader/src/emit/uniform.rs @@ -1,66 +1,188 @@ //! Which VGPR values are the same in every lane of a console wave, for a console wave64 //! program on a host of 32-lane waves: such a value read with `v_readfirstlane` needs no -//! exchange between the two host waves. +//! exchange between the two host waves. After fxceless/victory-fork PR #156 (sedzz, with +//! ryotdev's correction for guarded writes): without the three further proofs the structure +//! builder's three prefix-sum passes do not translate for 32-lane waves ("a first-lane read +//! where not every lane runs"), and the builder, whose stages run all or none, stays off. use std::collections::HashSet; use crate::gfx10::{Fields, NULL, Operand}; use crate::ir::{Program, Reg, Value}; -use crate::structure::Structured; +use crate::structure::{Atom, Bool, LaneExit, Structured}; /// VGPR values that are the same in every lane holding them (`all` is `lower.rs`'s `all_lane_blocks`): /// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, /// constants and such values; or loaded from an address made of them. The compiler keeps /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. -/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes -/// run (no lane branch can have split the arriving lanes); loop-carried values never do. -pub(super) fn lane_uniform(p: &Program, st: &Structured, all: &[bool], _threads: Option<[u32; 3]>) -> HashSet { +/// +/// Three more facts are proved, each only where no lane of a wave can part from the others: +/// - the wave number (`tid >> 6` of the entry `v0`, in a group whose x size is a multiple of +/// 64) is the same in all lanes of a console wave; +/// - an LDS read (`ds_read_b32`) at such an address is; +/// - a value joined by a phi is, also at a loop header, when its arguments are and every +/// predecessor is entered by all of the arriving lanes or none (the lanes' EXEC there is +/// made of conditions every lane agrees on: SCC values, compares of such values, and the +/// loop-carried masks made of them). That is a greatest fixed point: a loop-carried value +/// is taken to be alike and the assumption is dropped once an argument is not. +/// +/// shortcut: an LDS read is taken to see what a read by another wave of the same instruction +/// would; a write by another wave between the two host waves' reads is not looked for (the +/// scan programs read after a barrier). +pub(super) fn lane_uniform(p: &Program, st: &Structured, all: &[bool], threads: Option<[u32; 3]>) -> HashSet { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); - let mut same: HashSet = HashSet::new(); - for b in crate::ir::reverse_postorder(&p.blocks) { - let block = &p.blocks[b]; - let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + let entry_v0 = p.inputs.iter().find(|(r, _)| *r == Reg::V(0)).map(|x| x.1); + let waves_whole = threads.is_some_and(|t| t[0] != 0 && t[0].is_multiple_of(64)); + // the V-register phis, and the lane-mask phis, assumed alike until shown not to be + let mut assumed_v: HashSet = HashSet::new(); + let mut assumed_m: HashSet = HashSet::new(); + for block in &p.blocks { for phi in &block.phis { - if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { - same.insert(phi.value); + if matches!(phi.reg, Reg::V(_)) { + assumed_v.insert(phi.value); + } + if st.masks.contains_key(&phi.value) { + assumed_m.insert(phi.value); } } - for (i, inst) in block.insts.iter().enumerate() { - let name = inst.name(); - let ops: Vec = match &inst.fields { - Fields::Valu(v) - if v.dpp.is_none() - && v.sdwa.is_none() - && !name.starts_with("v_mbcnt") - && !name.starts_with("v_cmpx") - && !name.contains("lane") => + } + // Whether a condition is the same in every lane of the wave. + let uniform_bool = |b: Bool, same: &HashSet, cmp: &HashSet, masks: &HashSet| { + st.bools.support(b).iter().all(|a| match a { + Atom::Uniform(_) => true, + Atom::Lane(v) => cmp.contains(v) || same.contains(v), + Atom::Phi(v) => masks.contains(v), + _ => false, + }) + }; + loop { + let mut same: HashSet = HashSet::new(); + // values written by compares whose operands are all alike (the lane's bit is the wave's) + let mut cmp: HashSet = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + // every predecessor is entered by all the arriving lanes or none of them + let together = block.preds.iter().all(|&q| { + uniform_bool(st.reach[q], &same, &cmp, &assumed_m) + && st.guards[q] + .iter() + .all(|g| (*g).is_none_or(|g| uniform_bool(g, &same, &cmp, &assumed_m))) + && match &st.exits[q] { + LaneExit::Branch { when, .. } => uniform_bool(*when, &same, &cmp, &assumed_m), + _ => true, + } + }); + for phi in &block.phis { + if !matches!(phi.reg, Reg::V(_)) { + continue; + } + if whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } else if together && assumed_v.contains(&phi.value) { + // its arguments are checked once the pass is done + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + let alike_ops = |ops: &[Operand], same: &HashSet| { + ops.iter().all(|op| match *op { + Operand::Vector { reg, .. } => { + // every dword of the operand the instruction reads from that register on + let read: Vec = inst + .reads + .iter() + .filter(|r| matches!(r.0, Reg::V(x) if x >= reg)) + .map(|r| r.1) + .collect(); + !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + } + _ => true, + }) + }; + // Even a wave-uniform guard can be false. The lanes then keep the old + // destination, which may differ between the two halves of a console wave. + if st.guards[b][i].is_some() + && inst.writes.iter().any(|&(reg, _)| { + matches!(reg, Reg::V(_)) + && inst.read(reg).is_some_and(|old| !same.contains(&old)) + }) + { + continue; + } + // a read of the group's LDS at an address the lanes agree on + if let Fields::Ds { dst: Some(_), addr: Some(addr), gds: false, .. } = &inst.fields + && name == "ds_read_b32" + && alike_ops(&[*addr], &same) + && st.guards[b][i].is_none_or(|g| uniform_bool(g, &same, &cmp, &assumed_m)) + { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + continue; + } + let ops: Vec = match &inst.fields { + Fields::Valu(v) if v.dpp.is_none() && v.sdwa.is_none() => v.src.clone(), + _ => continue, + }; + if name.starts_with("v_cmp") { + if alike_ops(&ops, &same) { + cmp.extend(inst.writes.iter().map(|w| w.1)); + } + if name.starts_with("v_cmpx") { + continue; + } + } else if name.starts_with("v_mbcnt") || name.contains("lane") { + continue; + } + // `tid >> k` (k at least 6) of the entry thread number: the wave's + if waves_whole + && name == "v_lshrrev_b32" + && let [Operand::Const(134..=159), Operand::Vector { reg: 0, .. }] = &ops[..] + && let Some(v0) = entry_v0 + && inst.read(Reg::V(0)) == Some(v0) + && st.guards[b][i].is_none_or(|g| uniform_bool(g, &same, &cmp, &assumed_m)) { - v.src.clone() + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + continue; + } + // lanes outside EXEC keep another value, unless the lanes agree on running it + if st.guards[b][i].is_some_and(|g| !uniform_bool(g, &same, &cmp, &assumed_m)) { + continue; + } + if alike_ops(&ops, &same) { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); } - _ => continue, - }; - if st.guards[b][i].is_some() { - continue; // lanes outside EXEC keep another value } - let alike = ops.iter().all(|op| match *op { - Operand::Vector { reg, .. } => { - // every dword of the operand the instruction reads from that register on - let read: Vec = - inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); - !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // what was assumed of the loop-carried values: dropped where it did not hold + let mut changed = false; + for block in &p.blocks { + for phi in &block.phis { + if assumed_v.contains(&phi.value) + && same.contains(&phi.value) + && !phi.args.iter().all(|a| same.contains(a)) + { + assumed_v.remove(&phi.value); + changed = true; } - // a scalar is one value; a lane mask is not, unless a compare of such values made it - Operand::Scalar { code, .. } if code != NULL => { - inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + if assumed_m.contains(&phi.value) + && !phi.args.iter().all(|a| { + st.masks.get(a).is_some_and(|&m| uniform_bool(m, &same, &cmp, &assumed_m)) + }) + { + assumed_m.remove(&phi.value); + changed = true; } - _ => true, - }); - if alike { - same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); } } + if !changed { + return same; + } } - same } #[cfg(test)] From 68a1a1805b7a574f03a552e33e9d4a9bcf78c9d8 Mon Sep 17 00:00:00 2001 From: pr0vId3nce <148384071+pr0vId3nce@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:02:52 -0500 Subject: [PATCH 3/4] Shader tests: scans in a partly launched group on a host of 32-lane waves A dispatch that counts threads (DispatchX with its thread-count flag) starts its last group with only the first lanes in EXEC. A 64-lane program with a spilled user-data table takes the console compiler's wave total and prefix sum, which turn every lane on and mask by the saved EXEC, and stores both per thread; two groups of 64, counts 70, 100, 33, 1 and none. The lanes past the count must count as zero and store nothing, with the console wave run as two host waves that exchange their halves. Fails: spill::thread_limited, which is to mask EXEC by the count ahead of the program, is a stub ("the count's entry code is there"). Co-Authored-By: Claude Fable 5.2 --- .../victory-shader/src/emit/wave64_tests.rs | 159 ++++++++++++++++++ crates/victory-shader/src/spill.rs | 7 + 2 files changed, 166 insertions(+) diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 6ecf89b652..1bec9be3c9 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -572,3 +572,162 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() } eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); } + +/// A wave64 program of 64 threads with a spilled user-data table (a constant at user-data +/// index 16, a table with a raw UAV at 17, the group's number in s4). Thread t holds +/// (t >> 1) + 1. The console compiler's wave total and exclusive prefix sum, both of which +/// turn every lane on (`s_or_saveexec_b64 -1`) and mask the values by the saved EXEC; each +/// thread stores its prefix sum to dword n and the total to dword 128 + n, n its number +/// over the dispatch. +fn scanning_program() -> NativeProgram { + let mut words = vec![ + 0x8703_FF01, 0x0000_00FF, // s_and_b32 s3, s1, 0xff + 0xBE82_0300, // s_mov_b32 s2, s0 + 0x3D << 26 | 12 << 6 | 1, 125 << 25 | 4, // s_load_dword s12, s[2:3], 4 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0x3D << 26 | 0x02 << 18 | 8 << 6 | 6, 125 << 25, // s_load_dwordx4 s[8:11], s[12:13], 0 + 0x2C14_0081, // v_lshrrev_b32 v10, 1, v0 + 0x4A14_1481, // v_add_nc_u32 v10, 1, v10 + ]; + words.extend_from_slice(&[ + // the total + 0xBE8C_25C1, // s_or_saveexec_b64 s[12:13], -1 + 0xD501_0001, 0x0032_1480, // v_cndmask_b32 v1, 0, v10, s[12:13] + 0x4A02_02E9, 0xDE54_C101, // v_add_nc_u32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + 0x4A02_02E9, 0x9360_1201, // v_add_nc_u32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + 0x4A02_02E9, 0x0009_2401, // v_add_nc_u32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x4A02_02FA, 0xFF09_4001, // v_add_nc_u32 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x4A02_0302, // v_add_nc_u32 v1, v2, v1 + 0xD760_000E, 0x0001_4101, // v_readlane_b32 s14, v1, 32 + 0x4A02_020E, // v_add_nc_u32 v1, s14, v1 + 0xD760_001B, 0x0001_0101, // v_readlane_b32 s27, v1, 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + // the exclusive prefix sum + 0xBE8C_25C1, // s_or_saveexec_b64 s[12:13], -1 + 0xD501_0001, 0x0032_1480, // v_cndmask_b32 v1, 0, v10, s[12:13] + 0x7E04_0301, // v_mov_b32 v2, v1 + 0x4A04_04FA, 0xFF09_1102, // v_add_nc_u32 v2, v2, v2 row_shr:1 bound_ctrl:1 + 0x4A04_04FA, 0xFF01_1202, // v_add_nc_u32 v2, v2, v2 row_shr:2 + 0x4A04_04FA, 0xFF01_1402, // v_add_nc_u32 v2, v2, v2 row_shr:4 + 0x4A04_04FA, 0xFF01_1802, // v_add_nc_u32 v2, v2, v2 row_shr:8 + 0xBEFE_03FF, 0xFFFF_0000, // s_mov_b32 exec_lo, 0xffff0000 + 0xBEFF_03FF, 0xFFFF_0000, // s_mov_b32 exec_hi, 0xffff0000 + 0xD778_4803, 0x0305_8302, // v_permlanex16_b32 v3, v2, -1, -1 fi:1 + 0x4A04_0503, // v_add_nc_u32 v2, v3, v2 + 0xD760_000E, 0x0001_3F02, // v_readlane_b32 s14, v2, 31 + 0xBEFE_0380, // s_mov_b32 exec_lo, 0 + 0xBEFF_03C1, // s_mov_b32 exec_hi, -1 + 0x4A04_040E, // v_add_nc_u32 v2, s14, v2 + 0xBEFE_03C1, // s_mov_b32 exec_lo, -1 + 0xBEFF_03C1, // s_mov_b32 exec_hi, -1 + 0x4C04_0302, // v_sub_nc_u32 v2, v2, v1 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + ]); + words.extend_from_slice(&[ + 0xD746_0006, 4 | 0x86 << 9 | 0x100 << 18, // v_lshl_add_u32 v6, s4, 6, v0 + 0x340C_0C82, // v_lshlrev_b32 v6, 2, v6 + 0xE070_1000, 0x8002_0206, // buffer_store_dword v2, v6, s[8:11], 0 offen + 0x7E06_021B, // v_mov_b32 v3, s27 + 0xE070_1200, 0x8002_0306, // buffer_store_dword v3, v6, s[8:11], 0 offen offset:512 + S_ENDPGM, + ]); + NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 16, + layout: vec![ + RootParam { root: RootType::Constants, table_offset_dwords: 0, sgprs: 1, base_register: 0, user_data: 16, slot: 0 }, + RootParam { root: RootType::Table, table_offset_dwords: 0, sgprs: 1, base_register: 0, user_data: 17, slot: 1 }, + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 17, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 4 << 1 | 1 << 7, // 4 user SGPRs, then the group's number along x in s4 + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// A dispatch of threads whose last group is partly launched, with scans that turn every +/// lane on: the lanes past the limit count as zero in the total and the prefix sums, and +/// store nothing, with the count applied as `spill::thread_limited` does for a host of 32-lane +/// waves (the console wave runs as two host waves that exchange their halves). Two groups of +/// 64; counts 70, 100, 33, 1 and none. +#[test] +fn scans_in_a_partly_launched_group_count_the_launched_lanes_only() { + let native = crate::spill::thread_limited(scanning_program()); + assert_ne!(native.code.len(), scanning_program().code.len(), "the count's entry code is there"); + let p = crate::spill::build(&native).expect("spill::build"); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let host = Host::new(false).ok(); + for host_wave in [32u32] { + let shader = match lowered_for_width(&native, &p, &HashSet::new(), host_wave) { + Ok(s) => s, + Err(e) => panic!("lower (host waves of {host_wave}): {e}"), + }; + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let Some(host) = host.as_ref() else { continue }; + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + eprintln!("the hardware device does not take the program for host waves of {host_wave}; not run"); + continue; + }; + for limit in [70u32, 100, 33, 1, 0] { + let launched = |n: u32| limit == 0 || n < limit; + let mut want = vec![0u32; 256]; + for g in 0..2u32 { + let total: u32 = (0..64).filter(|&t| launched(64 * g + t)).map(|t| (t >> 1) + 1).sum(); + let mut sum = 0; + for t in 0..64u32 { + let n = 64 * g + t; + if launched(n) { + want[n as usize] = sum; + want[128 + n as usize] = total; + } + sum += (t >> 1) + 1; + } + } + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Other(super::USER_DISPATCH_THREADS_X) { + ud[u.index as usize] = limit; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(256)], + samplers: &[], + groups: [2, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + let wrong: Vec = (0..256) + .filter(|&i| out[0][i] != want[i]) + .map(|i| format!("dword {i}: {} want {}", out[0][i], want[i])) + .collect(); + assert!( + wrong.is_empty(), + "host waves of {host_wave}, limit {limit}: {} of 256 dwords wrong: {}", + wrong.len(), + wrong.iter().take(12).cloned().collect::>().join(", ") + ); + } + eprintln!("ran on the hardware device (host waves of {host_wave}): limits 70, 100, 33, 1 and none over two groups"); + } +} diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs index a0feb6aeb3..15f41c2bef 100644 --- a/crates/victory-shader/src/spill.rs +++ b/crates/victory-shader/src/spill.rs @@ -61,6 +61,13 @@ pub fn is_spilled(native: &NativeProgram) -> bool { spilled(native).is_some() } +/// `native` with its EXEC masked on entry by the dispatch's thread count +/// ([`crate::emit::USER_DISPATCH_THREADS_X`]), for a host of 32-lane waves. +/// shortcut: not done yet: the program comes back unchanged. +pub fn thread_limited(native: NativeProgram) -> NativeProgram { + native +} + /// Rewrites the loads of `native`'s spilled user-data table in `p`; returns /// how many loads it replaced. Nothing changes unless the program is a /// compute program whose layout has entries past its user SGPRs, the first From 46fa699aad9ae28397e2439b13ccc93cd93dc608 Mon Sep 17 00:00:00 2001 From: pr0vId3nce <148384071+pr0vId3nce@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:02:52 -0500 Subject: [PATCH 4/4] A dispatch that counts threads on a host of 32-lane waves: the count masks EXEC ahead of the program The structure builder's two passes over shipped structures are dispatched by thread count, and lower_with_thread_limit lets the lanes past the count leave at once. That needs the program as one 64-lane wave: a card whose waves are 32 lanes refuses such a pipeline ("The parameter is incorrect"), so two of the builder's 52 stages had none and the builder stayed off. On a host of 32-lane waves a compute program with a spilled user-data table now gets the count as one more parameter (USER_DISPATCH_THREADS_X, as the host already sets it) and seven instructions in front that AND its EXEC with "thread number < count" (spill::thread_limited), which is what the hardware's launch leaves there. The title's code runs unchanged behind them in the form the translator has for such a host: two host waves that exchange their halves, every thread staying. Hosts of 64-lane waves keep the early exit. XboxBvhBuilder.dll as a host of 32-lane waves on an RTX 4080: 52 emitted, 52 validated, 52 pipelines (was 50 pipelines). Co-Authored-By: Claude Fable 5.2 --- apps/victory/src/translate.rs | 2 + crates/victory-shader/src/emit/lower.rs | 2 + crates/victory-shader/src/emit/mod.rs | 11 +++- crates/victory-shader/src/spill.rs | 85 +++++++++++++++++++++++-- 4 files changed, 95 insertions(+), 5 deletions(-) diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 3881df1f9e..c08e6e0c24 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -468,6 +468,8 @@ fn translate( fn translate_programs(container: &Container, programs: Vec, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) { for p in programs { t.programs += 1; + // as `emit::translate` does for a host of 32-lane waves + let p = if emit::host_max_wave() == 32 { victory_shader::spill::thread_limited(p) } else { p }; match victory_shader::spill::build(&p) { Ok(program) => { t.translated += 1; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 9044e383ca..f02d3d8779 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -2585,6 +2585,8 @@ impl<'a> Lower<'a> { match rp.root { RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)), RootType::Constants | RootType::Table => {} + // The dispatch's thread count, which the host sets (`spill::thread_limited`). + RootType::Other(super::shader::USER_DISPATCH_THREADS_X) => {} _ => return Val::Missing("a root descriptor"), } let index = u32::from(rp.user_data) + dword - self.user_first(); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index b0ab7d408b..91f7feaad9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -336,6 +336,13 @@ pub fn translate(container: &[u8]) -> Result { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; + // A host of 32-lane waves cannot take the early exit of `lower_with_thread_limit` + // (see `spill::thread_limited`): the thread count masks EXEC ahead of the program. + let native = if lower::host_max_wave() == 32 { + crate::spill::thread_limited(native) + } else { + native + }; let p = crate::spill::build(&native)?; // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). @@ -714,7 +721,9 @@ fn emit_program( u128::from_be_bytes(c.digest), 0xba30_5538_e28d_414c_af39_a51a_4bc2_f308 | 0xd635_3bf6_df15_ff8e_c4aa_aec1_0dbf_3974 - ) && matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads == [64, 1, 1]); + ) && matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads == [64, 1, 1]) + // (on a host of 32-lane waves the count already masks EXEC: `translate`) + && lower::host_max_wave() != 32; let l = lower::lower_program(&parts, box_rehydration, tiled_lighting_uint_srvs(c.digest))?; let wave_size = l.wave_size; let shader = HostShader { diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs index 15f41c2bef..1c3b2765c5 100644 --- a/crates/victory-shader/src/spill.rs +++ b/crates/victory-shader/src/spill.rs @@ -61,10 +61,87 @@ pub fn is_spilled(native: &NativeProgram) -> bool { spilled(native).is_some() } -/// `native` with its EXEC masked on entry by the dispatch's thread count -/// ([`crate::emit::USER_DISPATCH_THREADS_X`]), for a host of 32-lane waves. -/// shortcut: not done yet: the program comes back unchanged. -pub fn thread_limited(native: NativeProgram) -> NativeProgram { +/// SGPRs the entry code of [`thread_limited`] uses: no program of the kind reads +/// them before writing them (the hardware leaves them as the last wave did). +const SCRATCH: [u32; 3] = [100, 101, 102]; + +/// `native` with its EXEC masked on entry by the dispatch's thread count, if it is a +/// compute program with a spilled user-data table that gets its group's number along x +/// and whose group is a power of two of threads along x and one along y and z; else +/// unchanged. For a host of 32-lane waves, where the early exit of +/// `lower_with_thread_limit` cannot be used: that one needs the program as one 64-lane +/// wave, which such a card refuses, and a console wave run as two host waves that +/// exchange their halves needs every thread to stay. +/// +/// The console's `DispatchX` can count threads (the structure builder's passes over +/// shipped structures): the last group then starts with only its first lanes in EXEC, and +/// the programs count those lanes (`s_bcnt1_i32_b64 exec`). The program gets the count as +/// one more parameter (index one past its last, kind +/// [`crate::emit::USER_DISPATCH_THREADS_X`]: the threads left from this dispatch's first +/// group on, 0 for a dispatch of whole groups) and these instructions in front, which +/// leave in EXEC what the hardware's launch does: +/// +/// ```text +/// s_and_b32 s101, s1, 0xff ; the table's address, as the program forms it +/// s_mov_b32 s100, s0 +/// s_load_dword s102, s[100:101], count ; rewritten by `user_data` like any parameter +/// s_add_u32 s102, s102, -1 ; 0 (no count) becomes the highest number +/// v_lshl_add_u32 vN, group, log2(threads), v0 +/// v_cmp_ge_u32 vcc, s102, vN +/// s_and_b64 exec, exec, vcc ; s_and_b32 exec_lo for a 32-lane program +/// ``` +/// +/// The title's code runs unchanged behind them, so lane counts, saved EXECs and scans that +/// turn every lane on behave as on the console in every form the translator has. +pub fn thread_limited(mut native: NativeProgram) -> NativeProgram { + let Some(spilled) = spilled(&native) else { + return native; + }; + let StageIo::Cs(cs) = &native.io else { + return native; + }; + let [threads, 1, 1] = cs.threads else { + return native; + }; + let (Some(group), true) = (cs.system_sgprs().0[0], threads.is_power_of_two()) else { + return native; + }; + let Some(index) = spilled.iter().map(|&(first, dwords)| first + dwords).max().filter(|&i| i < 256) else { + return native; + }; + let scratch = u32::from(native.vgprs); + if scratch > 255 { + return native; + } + let [low, high, count] = SCRATCH; + let words = [ + 0x8000_0000 | 14 << 23 | high << 16 | 0xFF << 8 | 1, // s_and_b32 high, s1, literal + 0xFF, + 0xBE80_0300 | low << 16, // s_mov_b32 low, s0 + 0x3D << 26 | count << 6 | (low / 2), // s_load_dword count, s[low:high], offset + (125 << 25) | (4 * (index - FIRST)), + 0x8000_0000 | count << 16 | 0xC1 << 8 | count, // s_add_u32 count, count, -1 + 0xD746_0000 | scratch, // v_lshl_add_u32 scratch, group, log2(threads), v0 + u32::from(group) | (0x80 + threads.trailing_zeros()) << 9 | 0x100 << 18, + 0x7D8C_0000 | scratch << 9 | count, // v_cmp_ge_u32 vcc, count, scratch + if native.wave64 { + 0x8000_0000 | 15 << 23 | 126 << 16 | 106 << 8 | 126 // s_and_b64 exec, exec, vcc + } else { + 0x8000_0000 | 14 << 23 | 126 << 16 | 106 << 8 | 126 // s_and_b32 exec_lo, exec_lo, vcc_lo + }, + ]; + let mut code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + code.extend_from_slice(&native.code); + native.code = code; + native.vgprs += 1; + native.layout.push(crate::native::RootParam { + root: crate::native::RootType::Other(crate::emit::USER_DISPATCH_THREADS_X), + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: index as u8, + slot: 0, + }); native }