Shadow and trace programs translate, lint clean, ray-tracing write-up

- 59 of the 64 trace programs and the irradiance-cache shading program
  translate; 51 programs leave the approximate wave64 forms.
- The workspace passes the lint with warnings as errors in both feature sets;
  a few style lints are let through in Cargo.toml for this fork.
- README status updated (relay and in-place memory results);
  docs/fork-ray-tracing.md describes what the title does and what is built.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
fxcelessandClaude Fable 5.2 committed 2026-11-24 13:48:06 -05:00
1 parent 578d459c34
commit 6a2d9f99c9
21 files changed
+2350 -62

No files matched your search

+2 -2
View File
@@ -146,12 +146,12 @@ pub(crate) fn frame_drew(frame: u64, drawn: u64) {
pub(crate) fn wanted(n: u64) -> bool {
// Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too
// (small pictures of menus, loading screens and title cards).
let before_world = world_on() && n % 16 == 0 && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX;
let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX;
// In the world: every 8th frame's picture, a timeline of the opening
// cutscene (its shots do not fall on the same frame numbers from run to
// run, so single frames cannot be compared between runs).
let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
let in_world = world_on() && first != u64::MAX && n > first && (n - first) % 8 == 0;
let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(8);
folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world)
}
+2 -2
View File
@@ -1534,13 +1534,13 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw:
let f = format.0 as u32;
let element = if raw {
// raw: R32 typeless, counted in dwords, starting on 16 bytes
if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || first % 4 != 0 {
if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) {
return false;
}
4
} else if stride > 0 {
// structured: no format, a stride the host takes
if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || stride % 4 != 0 {
if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) {
return false;
}
u64::from(stride)
+1 -1
View File
@@ -377,7 +377,7 @@ extern "system" fn unknown_pipeline<const SLOT: usize>(
let mut bytes = [0u8; 128];
(at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| {
bytes
.chunks_exact(8)
.as_chunks::<8>().0.iter()
.map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b)))
.collect()
})
+1 -1
View File
@@ -929,7 +929,7 @@ extern "system" fn copy_texture_region(
static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
let made = read_back(list, dst, x, y, z, src, source_box);
if n <= 16 || n % 4096 == 0 || made.is_err() {
if n <= 16 || n.is_multiple_of(4096) || made.is_err() {
static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 {
return;
+1
View File
@@ -83,6 +83,7 @@ static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::Ato
/// the library's file (kept whole while the library lives) and what its
/// last save wrote.
#[cfg(windows)]
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(crate) fn kept() -> [u64; 7] {
use std::sync::atomic::Ordering::Relaxed;
[
+1
View File
@@ -306,6 +306,7 @@ pub(crate) struct HostPipeline {
pub(crate) name: String,
/// Its depth, stencil, cull and blend state in short, for the frame
/// listing (empty for compute).
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(crate) state: String,
}
+2 -2
View File
@@ -853,7 +853,7 @@ const NOT_WATCHED: u8 = 2;
fn first_difference(a: &[u8], b: &[u8]) -> Option<usize> {
let whole = a.len().min(b.len()) / 8 * 8;
let from = a[..whole]
.chunks_exact(8)
.as_chunks::<8>().0.iter()
.zip(b[..whole].chunks_exact(8))
.position(|(x, y)| x != y)
.map_or(whole, |word| word * 8);
@@ -867,7 +867,7 @@ fn last_difference(a: &[u8], b: &[u8]) -> Option<usize> {
return Some(whole + i);
}
let word = a[..whole]
.chunks_exact(8)
.as_chunks::<8>().0.iter()
.zip(b[..whole].chunks_exact(8))
.rposition(|(x, y)| x != y)?
* 8;
+1 -1
View File
@@ -653,7 +653,7 @@ impl Staging {
const HASH_EVERY: u64 = 8;
let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked);
last.asked = now;
let turn = crate::frame::current().wrapping_add((start >> 16) as u64) % HASH_EVERY == 0;
let turn = crate::frame::current().wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY);
if unwritten && !turn {
return 0;
}
+1 -1
View File
@@ -890,7 +890,7 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin
// title asking.
static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let asked = ASKED.fetch_add(1, Ordering::Relaxed);
if asked % 1024 == 0 {
if asked.is_multiple_of(1024) {
tracing::info!(
asked = asked + 1,
which = _which,
@@ -159,10 +159,6 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> {
}
}
/// `code` as hex, for a log line.
pub fn hex(code: &[u8]) -> String {
code.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
+416 -16
View File
@@ -255,6 +255,9 @@ struct Lower<'a> {
/// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane
/// read of one needs nothing from the other host wave.
uniform: HashSet<Value>,
/// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which
/// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]).
own_bits: super::own_bits::OwnBits,
/// The console lane (0..63) of this thread, made in the entry block.
clane: Option<V>,
/// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]).
@@ -325,7 +328,10 @@ enum MaskData {
}
/// What a value holding a lane mask read as a number stops with.
const LANE_MASK: Why = "a lane mask read as data";
pub(super) const LANE_MASK: Why = "a lane mask read as data";
/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that
/// run that block are not all of the wave.
pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data";
/// Instructions that read a lane mask (not EXEC implicitly, not a lane's
/// bit) as a number.
@@ -333,6 +339,20 @@ const LANE_MASK: Why = "a lane mask read as data";
/// 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<Vec<bool>> {
let n = st.exits.len();
let mut all = vec![true; n];
for (_, region) in lane_regions(st)? {
for b in (0..n).filter(|&b| region[b]) {
all[b] = false;
}
}
Some(all)
}
/// Every per-lane branch (by its block) with its region: the blocks reachable from it that do
/// not post-dominate it, which only some lanes run. Not the branches the wave takes together
/// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit.
fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
let n = st.exits.len();
let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
for (b, e) in st.exits.iter().enumerate() {
@@ -370,11 +390,11 @@ fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
}
}
}
let mut all = vec![true; n];
let mut regions = Vec::new();
for (d, e) in st.exits.iter().enumerate() {
let LaneExit::Branch { when, .. } = *e else { continue };
if st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
continue; // a uniform branch: all lanes go the same way
if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
continue; // a wave-wide or uniform branch: all lanes go the same way
}
// blocks reachable from the lane branch that do not post-dominate it
let mut seen = vec![false; n];
@@ -384,11 +404,46 @@ fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
continue;
}
seen[b] = true;
all[b] = false;
stack.extend(succ[b].iter().copied());
}
regions.push((d, seen));
}
Some(all)
Some(regions)
}
/// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two
/// host waves must meet, [`take_needs`]): the ones to take wave-wide
/// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one
/// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]).
pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option<Vec<usize>> {
let mut out = Vec::new();
for (d, region) in lane_regions(st)? {
if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) {
st.wave_any.get(d).copied().flatten()?;
out.push(d);
}
}
Some(out)
}
/// Whether a refusal is of code that needs every lane of the wave where it stands (two host
/// waves meeting there), which the other forms of the program may give it.
pub(super) fn needs_every_lane(what: &str) -> bool {
what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE
}
/// The blocks where the last lowering on this thread wanted every lane and did not have it
/// (its "... where not every lane runs" refusals), which it forgets.
pub(super) fn take_needs() -> Vec<usize> {
NEEDS.take()
}
fn need(block: usize) {
NEEDS.with_borrow_mut(|n| {
if !n.contains(&block) {
n.push(block);
}
});
}
/// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]):
@@ -535,7 +590,7 @@ pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'s
// Everything else it reads (addresses, descriptors, SCC, the high dwords of wide
// operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it
// writes, which only the lanes outside EXEC keep.
let named: Vec<Value> = ops.iter().filter_map(|o| val(o)).collect();
let named: Vec<Value> = ops.iter().filter_map(&val).collect();
for &(r, v) in &inst.reads {
let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r);
if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) {
@@ -888,6 +943,8 @@ pub fn set_host_max_wave(lanes: u32) {
}
thread_local! {
/// See [`take_needs`].
static NEEDS: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
/// See [`with_local_waves`].
static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// See [`with_local_waves_any`].
@@ -931,11 +988,49 @@ pub(super) fn with_local_waves<R>(f: impl FnOnce() -> R) -> R {
r
}
/// `VICTORY_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`,
/// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them
/// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA:
/// the last place of a result that is not exact is then one lower than the console's).
/// Off by default: it is exact but untried in a game run, and adds instructions to every
/// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact.
fn f16_nearest_on() -> bool {
#[cfg(test)]
if let Some(on) = TEST_F16_NEAREST.get() {
return on;
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_F16_NEAREST").is_some_and(|v| v == "1"))
}
#[cfg(test)]
thread_local! {
/// A test's choice for [`f16_nearest_on`], for its thread only.
pub(super) static TEST_F16_NEAREST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
/// `VICTORY_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before
/// ([`super::own_bits`]).
fn own_bits_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
}
pub(super) fn host_max_wave() -> u32 {
#[cfg(test)]
if let Some(lanes) = TEST_HOST_WAVE.get() {
return lanes;
}
HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed)
}
fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
#[cfg(test)]
thread_local! {
/// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's).
pub(super) static TEST_HOST_WAVE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}
pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool {
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
let ops: Vec<&Operand> = match &i.fields {
// A mask operation (its result a mask) is no data use.
@@ -1171,7 +1266,9 @@ impl<'a> Lower<'a> {
|| matches!(n, "v_readlane_b32" | "v_writelane_b32")
|| matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some())
|| reads_mask_as_data(x.st, i)
}) || lane_constant_masks(x.st);
}) || lane_constant_masks(x.st)
// (a branch the wave takes together asks the wave)
|| !x.st.wide.is_empty();
let mut wave = if x.native.wave64 { 64 } else { 32 };
let group = cs.threads.iter().product::<u32>();
let one_wave = group <= wave;
@@ -1191,7 +1288,8 @@ impl<'a> Lower<'a> {
|| n.starts_with("ds_permute")
|| n.starts_with("ds_bpermute")
|| reads_mask_as_data(x.st, i)
}) || lane_constant_masks(x.st);
}) || lane_constant_masks(x.st)
|| !x.st.wide.is_empty();
if !crosses && (s.lds_dwords == 0 || group <= 32) {
wave = 32;
} else {
@@ -1216,6 +1314,15 @@ impl<'a> Lower<'a> {
lds_meet = Some((all.clone(), meet));
lds_ok = true;
}
if !lds_ok {
// (the blocks whose LDS accesses not every lane runs: with the
// branches around them taken wave-wide they get their barriers)
for (b, blk) in p.blocks.iter().enumerate() {
if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) {
need(b);
}
}
}
if lds_ok {
wave = 32;
split_lds = s.lds_dwords > 0 && group > 32;
@@ -1403,6 +1510,12 @@ impl<'a> Lower<'a> {
Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all),
_ => HashSet::new(),
},
own_bits: match &exchange {
Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => {
super::own_bits::find(p, x.st, std::env::var_os("VICTORY_WAVE_WHY").is_some())
}
_ => Default::default(),
},
exchange,
clane: None,
pair: None,
@@ -1642,7 +1755,8 @@ impl<'a> Lower<'a> {
for &(_, w) in &inst.writes {
let val = if self.section_out.contains(&w) {
let shape = self.sections[&b][&start].shapes.get(&w).copied();
match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) {
let own = self.own_bits.totals.contains(&w);
match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) {
Ok(x) => Val::I32(x),
Err(why) => Val::Missing(why),
}
@@ -1657,7 +1771,11 @@ impl<'a> Lower<'a> {
/// host's active lanes: the console's result with console lanes; on
/// another wave size, what the HLSL wave operation the console compiler
/// expanded gives on that wave.
fn shape(&mut self, shape: super::wave::Shape) -> Result<V, Why> {
///
/// `own`: a wave OR that only steers a loop over each lane's own bits
/// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is
/// this host wave's.
fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result<V, Why> {
use super::wave::{Op, Shape};
let (op, src, mask, ident, prefix) = match shape {
Shape::K(k) => return Ok(self.s.m.i32(k)),
@@ -1706,6 +1824,12 @@ impl<'a> Lower<'a> {
let id = self.s.m.i32(ident);
let x = self.s.m.select(c, on, x, id);
self.s.flags |= flags::WAVE_OPS;
if op == Op::AddH {
return match prefix {
Some(_) => Err("a wave prefix of an operation other than a sum"),
None => self.half_sum(x),
};
}
let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF);
let (i32t, f32t) = (self.s.t.i32, self.s.t.f32);
let arg = if float { self.as_float(x) } else { x };
@@ -1764,8 +1888,13 @@ impl<'a> Lower<'a> {
// 32 threads or fewer, which one host wave holds whole (combining with the 0 a
// missing half "gives" broke AND, MIN and signed MAX)
r
} else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) {
// each thread walks the bits of this value and works only at its own, which the
// host wave's OR holds: the same run as with the console wave's OR
r
} else if self.exchange.is_some() {
if !self.all_lanes(self.cur_ir) {
need(self.cur_ir);
return Err("a wave reduction where not every lane runs");
}
let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v };
@@ -1817,6 +1946,85 @@ impl<'a> Lower<'a> {
Ok(if float { self.as_int(r) } else { r })
}
/// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's
/// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest
/// ([`Self::f16_nearest`]).
fn add_halves(&mut self, a: V, b: V) -> V {
let c = self.cur;
let f32t = self.s.t.f32;
let low = self.s.m.i32(0xFFFF);
let wide = |l: &mut Self, x: V| {
let h = l.s.m.bin(c, Bin::And, x, low);
l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h])
};
let (fa, fb) = (wide(self, a), wide(self, b));
let f = self.s.m.bin(c, Bin::Add, fa, fb);
self.f16_nearest(f)
}
/// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the
/// lanes outside the mask), bit for bit as the console adds it: every addition rounds to
/// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes
/// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves;
/// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the
/// lane whose number differs in one bit, step by step; two host waves of 32 then exchange
/// their halves' sums for the last addition. The high half of the result is lane 0's,
/// which no `v_add_f16` writes.
/// That needs every lane of a full wave there to be read: refused where not every lane
/// runs, in a thread group that does not fill its waves, and for each half-wave on its
/// own (half a sum is no sum).
fn half_sum(&mut self, x: V) -> Result<V, Why> {
const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs";
let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?;
if threads.iter().product::<u32>() % 64 != 0 {
return Err("a wave sum of 16-bit floats in a wave that is not full");
}
if self.local {
return Err("a wave sum of 16-bit floats in a half-wave");
}
// two host waves of 32 that exchange, or one host wave of 64 lanes
let halves = match (&self.exchange, self.s.wave_size) {
(Some((_, false, _)), _) => true,
(None, Some(64)) if self.x.p.wave64 => false,
_ => return Err("a wave sum of 16-bit floats on these waves"),
};
let every = if halves {
self.all_lanes(self.cur_ir)
} else {
all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false))
};
if !every {
if halves {
need(self.cur_ir);
}
return Err(WHERE);
}
let c = self.cur;
let i32t = self.s.t.i32;
let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let mut sum = x;
for step in 0..if halves { 5 } else { 6 } {
let bit = self.s.m.i32(1 << step);
let partner = self.s.m.bin(c, Bin::Xor, lane, bit);
let theirs = self.read_lane(sum, partner);
sum = self.add_halves(sum, theirs);
}
let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0));
let first = self.read_lane(x, zero);
let first = self.s.m.bin(c, Bin::And, first, high);
let sum = self.s.m.bin(c, Bin::And, sum, low);
let mine = self.s.m.bin(c, Bin::Or, first, sum);
if !halves {
return Ok(mine);
}
let (lo, hi) = self.exchange_halves(c, mine);
let c = self.cur;
let total = self.add_halves(lo, hi);
let total = self.s.m.bin(c, Bin::And, total, low);
let first = self.s.m.bin(c, Bin::And, lo, high);
Ok(self.s.m.bin(c, Bin::Or, first, total))
}
fn run(mut self) -> Result<Lowered, Stop> {
let p = self.x.p;
let order = crate::ir::reverse_postorder(&p.blocks);
@@ -2740,8 +2948,16 @@ impl<'a> Lower<'a> {
None => (v, false),
};
let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?;
if !self.x.st.active.contains(&lo) {
return Err("a lane mask holding lanes elsewhere read as data");
// A mask that holds lanes outside EXEC where it is written (the complement of one,
// say) is the ballot of the lanes that are there: all of them, where two exchanging
// host waves know every lane runs that block.
let made = self.def_block.get(&lo).copied();
let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b));
if !self.x.st.active.contains(&lo) && !whole {
if self.exchange.is_some() && !self.local {
need(made.unwrap_or(0));
}
return Err(MASK_ELSEWHERE);
}
let (x, y) = match self.ballots.get(&lo) {
Some(&xy) => xy,
@@ -2774,6 +2990,7 @@ impl<'a> Lower<'a> {
}
} else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) {
// (a group of 32 or fewer has no other half to exchange with)
need(b.unwrap_or(0));
return Err("a lane mask exchanged where not every lane runs");
}
xy = self.exchange_halves(at, xy.0);
@@ -2994,6 +3211,44 @@ impl<'a> Lower<'a> {
self.s.m.select(c, away, stepped, h)
}
/// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's
/// 16-bit float operations round, whatever the host's own conversion does: D3D lets
/// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070:
/// `wave64_tests`). The conversion toward zero, or the next half away from zero where
/// that one is nearer, or as near and the first one odd. Past the largest half the next
/// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity.
/// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the
/// rounding of the exact result, 24 bits being more than twice 11 and two.)
fn f16_nearest(&mut self, f: V) -> V {
let c = self.cur;
let f32t = self.s.t.f32;
let lo = self.f16_toward_zero(f);
let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0));
let hi = self.s.m.bin(c, Bin::Add, lo, one);
let size = |l: &mut Self, h: V| {
let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]);
l.unary(6, w)
};
let (below, above) = (size(self, lo), size(self, hi));
let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00));
let m = self.s.m.bin(c, Bin::And, hi, magnitude);
let top = self.s.m.cmp(c, pred::EQ, m, infinity);
let bound = self.s.m.f32(65536.0f32.to_bits());
let above = self.s.m.select(c, top, bound, above);
let fa = self.unary(6, f);
// (both differences are exact: the three values lie within one half's step)
let under = self.s.m.bin(c, Bin::Sub, fa, below);
let over = self.s.m.bin(c, Bin::Sub, above, fa);
// Ordered: never for NaN, which stays what the conversion made of it.
let nearer = self.s.m.cmp(c, pred::OLT, over, under);
let tie = self.s.m.cmp(c, pred::OEQ, over, under);
let odd = self.s.m.bin(c, Bin::And, lo, one);
let odd = self.s.m.cmp(c, pred::NE, odd, zero);
let tie = self.s.m.bin(c, Bin::And, tie, odd);
let up = self.s.m.bin(c, Bin::Or, nearer, tie);
self.s.m.select(c, up, hi, lo)
}
/// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's
/// top bit when `signed`; widths from 32 on take every bit. A signed
/// field that runs past bit 31 extends from bit 31, as the hardware
@@ -3350,6 +3605,90 @@ impl<'a> Lower<'a> {
v
}
/// The console's decision of the branch closing IR block `b`, which the wave takes
/// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken
/// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or
/// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`].
/// Each host wave asks its lanes and the halves exchange the answers, so both go the
/// same way and can meet again inside the branch.
/// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the
/// console wave has its bit of the result, asked where the operation stands. The lanes
/// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with
/// the console's waves the host wave's answer is the console's; two host waves of 32
/// exchange theirs, which needs every lane there.
fn scc_some(&mut self, scc: Value) -> Result<V, Why> {
let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?;
// (not for a console wave cut into host waves that do not exchange)
if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() {
return Err(LANE_MASK);
}
let made = self.def_block.get(&scc).copied();
let at = match made {
None => self.s.entry,
Some(b) if b == self.cur_ir => self.cur,
Some(b) => self.tail[b].ok_or("a lane mask written after its use")?,
};
let bit = self.boolean(m, at)?;
let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]);
self.s.flags |= flags::WAVE_OPS;
if !self.exchange.as_ref().is_some_and(|e| !e.1) {
return Ok(some);
}
if !made.is_none_or(|b| self.all_lanes(b)) {
need(made.unwrap_or(0));
return Err("a lane mask exchanged where not every lane runs");
}
let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
let (lo, hi) = self.exchange_halves(at, some);
let both = self.s.m.bin(at, Bin::Or, lo, hi);
let z = self.s.m.i32(0);
Ok(self.s.m.cmp(at, pred::NE, both, z))
}
fn wave_wide(&mut self, b: usize, when: Bool) -> Result<V, Why> {
const WHY: Why = "a wave-wide branch where not every lane runs";
let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?;
if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console {
// The host's waves are the console's: the wave's own answer. The lanes that are
// elsewhere have no bit set, as on the console, so "some lane" needs no one but
// the lanes here, and "every lane's bit is clear" is true of the others anyway.
let c = self.cur;
let mine = self.boolean(when, c)?;
let i1t = self.s.t.i1;
self.s.flags |= flags::WAVE_OPS;
let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) };
return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine]));
}
if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) {
return Err(WHY);
}
if !self.all_lanes(b) {
need(b);
return Err(WHY);
}
let c = self.cur;
let mine = self.boolean(when, c)?;
// what the halves exchange is "some lane speaks against" either way (for `any`:
// some lane's `when` holds; else: some lane's does not), so a half with no lane says
// nothing
let set = if any {
mine
} else {
let t = self.s.m.bool(true);
self.s.m.bin(c, Bin::Xor, mine, t)
};
let (i1t, i32t) = (self.s.t.i1, self.s.t.i32);
let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]);
self.s.flags |= flags::WAVE_OPS;
let some = self.s.m.cast(c, Cast::ZExt, some, i32t);
let (lo, hi) = self.exchange_halves(c, some);
let c = self.cur;
let both = self.s.m.bin(c, Bin::Or, lo, hi);
let z = self.s.m.i32(0);
Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z))
}
/// Whether every lane runs IR block `b` (always true without `exchange`).
fn all_lanes(&self, b: usize) -> bool {
self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false))
@@ -6872,6 +7211,7 @@ impl<'a> Lower<'a> {
}
// the lane that holds it may be in the other host wave: it gives it through LDS
if !self.all_lanes(self.cur_ir) {
need(self.cur_ir);
return Err("a lane read where not every lane runs");
}
let cl = self.console_lane();
@@ -6921,6 +7261,15 @@ impl<'a> Lower<'a> {
let a = s(self, 0)?;
int(self, a)
}
"v_readfirstlane_b32"
if matches!(v.src.first(), Some(&Operand::Vector { reg, .. })
if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) =>
{
// The bits a loop over a wave OR has still to visit (`own_bits`): every lane of
// the host wave holds the same, so the first lane's is the lane's own.
let a = s(self, 0)?;
int(self, a)
}
"v_readfirstlane_b32" => {
let a = s(self, 0)?;
let (mine, any) = self.first_lane(a, guard);
@@ -6935,6 +7284,7 @@ impl<'a> Lower<'a> {
let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local;
let r = if halves && !alike {
if !self.all_lanes(self.cur_ir) {
need(self.cur_ir);
return Err("a first-lane read where not every lane runs");
}
let c = self.cur;
@@ -7205,8 +7555,15 @@ impl<'a> Lower<'a> {
if v.clamp {
f = l.unary(7, f);
}
let h =
l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
// The console rounds to nearest; the host's conversion may round toward zero
// (NVIDIA's does), one step of the last place lower where the two differ.
// shortcut: the host's conversion unless `VICTORY_F16_NEAREST=1`
// ([`f16_nearest_on`]), which costs a dozen instructions per result.
let h = if f16_nearest_on() {
l.f16_nearest(f)
} else {
l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f])
};
l.write_half(inst, h, guard)
};
if name == "v_cvt_f16_f32" {
@@ -10074,6 +10431,10 @@ impl<'a> Lower<'a> {
} => {
// A negated condition branches the other way round.
let (cond, taken, not_taken) = match self.x.st.bools.node(when) {
_ if self.x.st.wide.contains(&b) => {
let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?;
(c, taken, not_taken)
}
Some((atom, Bool::TRUE, Bool::FALSE)) => {
let a = self
.atom(atom, self.cur)
@@ -10295,6 +10656,45 @@ impl<'a> Lower<'a> {
{
self.s.m.i32(0)
}
// A lane mask joined with numbers (a traversal that keeps its lanes' masks on
// a stack with its node numbers): the mask comes as the number it is, the
// ballot of its lanes where it is written.
(Some(Val::Missing(_)) | None, false)
if self.read_phis.contains(&phi.value)
&& self.mask_data == MaskData::Console
&& (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) =>
{
match self.mask_dword(arg) {
Ok(x) => x,
Err(why) => return Err(Stop::Retry(phi.value, why)),
}
}
// SCC of a mask operation ("some lane is left") joined with a scalar test:
// the compiler branches around code that sets SCC and tests SCC after it,
// the skip bringing "no lane" along. As data it is "some lane of the wave
// has the bit" - right only if the wave took that skip together, as the
// console does: a lane that skipped alone would bring "some lane" where the
// console has the skipped code's SCC. So the branch must be one the wave
// takes together; else its region is named for `emit`'s retry to widen it.
(Some(Val::Missing(_)) | None, true)
if self.read_phis.contains(&phi.value)
&& self.mask_data == MaskData::Console
&& st.scc_some.contains_key(&arg) =>
{
let per_lane = !st.wide.contains(&q)
&& matches!(st.exits[q], LaneExit::Branch { when, .. }
if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))));
if per_lane {
for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) {
need(other);
}
return Err(Stop::Retry(phi.value, LANE_MASK));
}
match self.scc_some(arg) {
Ok(x) => x,
Err(why) => return Err(Stop::Retry(phi.value, why)),
}
}
(Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => {
return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values"));
}
+144 -17
View File
@@ -89,6 +89,7 @@ mod intersect_tests;
#[cfg(all(windows, any(test, feature = "host")))]
pub mod host;
mod lower;
mod own_bits;
mod rect;
mod sampler;
mod shader;
@@ -99,6 +100,8 @@ pub mod validator;
mod valu_tests;
#[cfg(all(test, windows))]
mod waterfall_tests;
#[cfg(all(test, windows))]
mod wave64_tests;
mod wave;
use crate::dxbc::{Container, FourCC};
@@ -270,6 +273,8 @@ pub fn emit(
io: &io::Io,
res: &resource::Resources,
) -> Result<HostShader, ShaderError> {
// (what an earlier program's lowering on this thread left behind)
lower::take_needs();
let original = emit_program(c, native, p, st, io, res);
// A console wave64 compute program on a host of 32-lane waves that
// still needs 64 lanes, or whose cross-lane code sits where not every
@@ -278,9 +283,12 @@ pub fn emit(
// body from being a block every lane runs.
let stuck = match &original {
Ok((_, wave)) => *wave == Some(64),
Err(ShaderError::Unsupported { what, .. }) => what.ends_with("where not every lane runs"),
Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what),
Err(_) => false,
};
// (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave
// on its own)
let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE);
if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 {
let why = std::env::var_os("VICTORY_WAVE_WHY").is_some();
let report = |what: &str, r: &Result<(HostShader, Option<u32>), ShaderError>| {
@@ -322,7 +330,7 @@ pub fn emit(
};
let forms = [
("without early-outs", form(ir::without_early_outs(p))),
("without skips", form(ir::without_skips(p))),
("without skips", form(ir::without_skips(p, false))),
];
for (name, f) in &forms {
if let Some((p, st, io, res)) = f {
@@ -333,31 +341,70 @@ pub fn emit(
}
}
}
if local_on {
// exact first (every form), then approximate
for exact in [true, false] {
if !exact && strict {
break;
let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0");
// exact first: each host wave on its own where that is exact (the idiom, every
// form; no barriers), then the other exact forms; then approximate
for exact in [true, false] {
if !exact {
// Before anything approximate, the exact forms that cost group barriers.
// Every skip left out that the code after it cannot see
// ([`ir::without_skips`], `deep`): most of the body is then code every
// lane runs, where the two host waves can exchange.
// (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.)
let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0");
let deep = if deep_on { form(ir::without_skips(p, true)) } else { None };
if let Some((p, st, io, res)) = &deep {
let again = emit_program(c, native, p, st, io, res);
report("without skips, scalars followed", &again);
if done(&again) {
return again.map(|(shader, _)| shader);
}
}
for (name, f) in &forms {
if let Some((p, st, io, res)) = f
&& idiom(p, st) == exact
{
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
if done(&local) {
return local.map(|(shader, _)| shader);
// Still stopped where not every lane runs: the per-lane branches around
// those places taken as the console takes them, by the whole wave at once
// ([`widen`]), at two group barriers per such branch.
if wide_on {
let bases = [
deep.as_ref().map(|f| &f.0),
forms[1].1.as_ref().map(|f| &f.0),
forms[0].1.as_ref().map(|f| &f.0),
Some(p),
];
if let Some(base) = bases.into_iter().flatten().next() {
let again = widen(c, native, base, why);
report("wave-wide branches", &again);
if done(&again) {
return again.map(|(shader, _)| shader);
}
}
}
if idiom(p, st) == exact {
if strict {
break;
}
}
if !local_on || exact_only {
continue;
}
for (name, f) in &forms {
if let Some((p, st, io, res)) = f
&& idiom(p, st) == exact
{
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local);
if done(&local) {
return local.map(|(shader, _)| shader);
}
}
}
if idiom(p, st) == exact {
let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res));
report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local);
if done(&local) {
return local.map(|(shader, _)| shader);
}
}
}
if local_on && !exact_only {
// Last: every mask and lane read per host wave.
if !strict {
for (name, f) in &forms {
@@ -377,6 +424,23 @@ pub fn emit(
}
}
}
// SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane
// trace programs): right once the wave takes that skip together ([`widen`]; the
// lowering has named the skipped blocks).
let original = match original {
Err(ShaderError::Unsupported { what, .. })
if native.stage == HwStage::Cs
&& what == lower::LANE_MASK
&& std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") =>
{
let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some());
match again {
Ok(_) => again,
Err(_) => emit_program(c, native, p, st, io, res),
}
}
other => other,
};
let original = original.map(|(shader, _)| shader);
// Retry unsupported programs only. Threading can separate an unknown
// register value from its apparent use on a mutually exclusive path.
@@ -394,6 +458,69 @@ pub fn emit(
emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader)
}
/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane
/// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the
/// lowering names the blocks where the two host waves must meet and could not
/// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until
/// it translates or a branch cannot be widened. Only where a thread group is one console
/// wave: with several, the waves of a group would decide differently and a barrier inside
/// such a branch would wait for threads that never come.
fn widen(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
why: bool,
) -> Result<(HostShader, Option<u32>), ShaderError> {
const NOT: ShaderError = ShaderError::Unsupported {
offset: 0,
what: "wave-wide branches in a thread group of several console waves",
};
match native.io {
// (a program whose waves are the host's meets no one: no barrier, any group)
crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {}
crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64 => {}
crate::native::StageIo::Cs(cs) => {
if why {
eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads);
}
return Err(NOT);
}
_ => return Err(NOT),
}
let mut wide = std::collections::HashSet::new();
loop {
let st = structure::structure_wide(p, &wide)?;
let io = io::raise(p, native)?;
let res = resource::track(p, &native.layout, native.stage, Some(&st))?;
lower::take_needs();
let r = emit_program(c, native, p, &st, &io, &res);
let needs = lower::take_needs();
// (or translated for 64-lane waves still: shared memory read and written where not
// every lane runs, whose blocks the lowering names too)
let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. })
if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty())
|| matches!(&r, Ok((_, Some(64)))) && !needs.is_empty();
if !stuck {
if why {
eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len());
}
return r;
}
let more: Vec<usize> = lower::branches_around(&st, &needs)
.unwrap_or_default()
.into_iter()
.filter(|b| !wide.contains(b))
.collect();
if more.is_empty() {
if why {
eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len());
}
return r;
}
wide.extend(more);
}
}
/// The translated program, and the wave size it requires of the host.
fn emit_program(
c: &Container,
+914
View File
@@ -0,0 +1,914 @@
//! Wave ORs that only steer a loop over each lane's own bits.
//!
//! The title's light loops are "scalarised": the lanes' light masks are ORed over the wave and
//! the wave walks the set bits of the result together, each lane working only where its own
//! mask has the bit:
//!
//! ```text
//! merged = WaveActiveBitOr(mask); // over the lanes that run
//! while (merged != 0) {
//! bit = firstbitlow(merged);
//! if (mask & (1 << bit)) { ... } // the body
//! merged ^= 1 << bit;
//! }
//! ```
//!
//! A console wave64 program in two host waves of 32 cannot exchange the halves' ORs where not
//! every lane runs (a group barrier must be reached by every thread). It does not have to: as
//! one thread runs it, the loop visits the bits of `merged` in rising order and does something
//! only at the bits of the thread's own mask, so any `merged` that holds the thread's own bits
//! gives that thread the same run. The host wave's own OR is such a value.
//!
//! That holds only if the OR is used for nothing else, and if a round of the loop at a bit the
//! thread does not have leaves nothing behind. [`find`] proves both for each wave OR, with no
//! instruction sequence taken on trust:
//!
//! - the OR and what derives from it as "the bits still to visit" (copies, the loop's join, the
//! first-lane read of it, the set less the visited bit) are read only by the loop's own
//! steps: the test for an empty set, the lowest set bit, the removal of that bit, the test
//! that ends the loop;
//! - the lane's test is its own bit of the very value that was ORed, and "the body" is what a
//! lane only reaches with that test true in the same round;
//! - outside the body the loop has no side effect and no cross-lane step, writes nothing that
//! is read after the loop or carried into a later round, and is left only by the test for
//! "no bits left";
//! - no lane mask that depends on the test is used outside the round that made it.
//!
//! Anything else is refused there as before ("a wave reduction where not every lane runs") and
//! left to the forms of the program in which every lane runs that code (`emit`'s retries: the
//! skips left out, the branches around it taken wave-wide), where the halves do exchange.
//! `VICTORY_WAVE_OWN_BITS=0` turns this off.
use std::collections::{HashMap, HashSet};
use super::wave::{self, Op, Shape};
use crate::gfx10::{Fields, NULL, Operand};
use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value};
use crate::structure::{Atom, Bool, LaneExit, Structured};
type Why = &'static str;
const USED: Why = "a wave OR used as data";
const NO_LOOP: Why = "a wave OR that steers no loop over its bits";
const SHAPE: Why = "a loop over a wave OR's bits of another shape";
const TEST: Why = "a loop over a wave OR's bits whose lanes do not test their own bit";
const LEAVES: Why = "a value of a round over a wave OR's bits that outlives the round";
const EFFECT: Why = "an effect in a loop over a wave OR's bits outside the lanes' own bits";
const CROSS: Why = "a cross-lane step in a loop over a wave OR's bits outside the lanes' own bits";
const EXIT: Why = "a loop over a wave OR's bits left another way";
const STALE: Why = "a lane's own-bit test used outside its round";
const MASK: Why = "a wave OR over a mask a running lane may be outside";
/// What [`find`] proved.
#[derive(Debug, Default)]
pub(super) struct OwnBits {
/// Wave ORs (the values their sections leave) a host wave may take over its own lanes.
pub totals: HashSet<Value>,
/// VGPR values of those loops that every lane of a host wave holds alike (the bits still
/// to visit): a first-lane read of one is the lane's own value.
pub alike: HashSet<Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum User {
Inst(usize, usize),
Phi(usize, usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Arg {
Val(Value),
K(u32),
Other,
}
struct Ctx<'a> {
p: &'a Program,
st: &'a Structured,
users: HashMap<Value, Vec<User>>,
/// The instruction writing each value.
def: HashMap<Value, (usize, usize)>,
/// Values an instruction reads, directly or through joins.
live: HashSet<Value>,
idom: Vec<usize>,
sections: Vec<HashMap<usize, wave::Section>>,
}
/// The values instruction `i` of block `b` uses: what its operands read, without EXEC (lane
/// masks are followed as booleans) and without the old value of a VGPR it writes, which only
/// lanes outside a guard keep.
fn used(p: &Program, st: &Structured, b: usize, i: usize) -> Vec<Value> {
let inst = &p.blocks[b].insts[i];
let ops = crate::ir::operand_reads(p, inst);
let guarded = st.guards[b][i].is_some();
inst.reads
.iter()
.filter(|&&(r, _)| match r {
Reg::S(c) if c == EXEC || c == EXEC + 1 => false,
Reg::V(_) => ops.contains(&r) || guarded,
_ => true,
})
.map(|r| r.1)
.collect()
}
fn value(inst: &Inst, op: &Operand) -> Option<Value> {
match *op {
Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)),
Operand::Vector { reg, .. } => inst.read(Reg::V(reg)),
_ => None,
}
}
/// The sources of a scalar or unmodified vector operation.
fn args(inst: &Inst) -> Vec<Arg> {
let src: &[Operand] = match &inst.fields {
Fields::Sop { src, .. } => src,
Fields::Valu(v)
if v.dpp.is_none()
&& v.sdwa.is_none()
&& v.abs == 0
&& v.neg == 0
&& !v.clamp
&& v.omod == 0 =>
{
&v.src
}
_ => &[],
};
src.iter()
.map(|o| match (value(inst, o), o) {
(Some(v), _) => Arg::Val(v),
(None, &Operand::Const(c)) => crate::resource::inline(c).map_or(Arg::Other, Arg::K),
(None, &Operand::Literal(x)) => Arg::K(x),
_ => Arg::Other,
})
.collect()
}
/// The other source of a two-source operation that reads `a`.
fn other(inst: &Inst, a: Value) -> Option<Arg> {
match args(inst)[..] {
[Arg::Val(x), o] if x == a => Some(o),
[o, Arg::Val(x)] if x == a => Some(o),
_ => None,
}
}
/// The scalar (not SCC) or vector dword an instruction writes, if it writes one.
fn result(inst: &Inst) -> Option<Value> {
let mut w = inst.writes.iter().filter(|w| w.0 != Reg::Scc);
match (w.next(), w.next()) {
(Some(&(_, v)), None) => Some(v),
_ => None,
}
}
/// The same test as `wave_local`'s and `Lower::inst`'s `effect`, and the messages a program
/// sends.
fn effect(inst: &Inst) -> bool {
let name = inst.name();
matches!(inst.fields, Fields::Exp { .. })
|| matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
|| name.contains("store")
|| name.contains("atomic")
|| matches!(inst.fields, Fields::Ds { .. })
&& !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute"))
|| matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt")
}
impl Ctx<'_> {
fn new<'a>(p: &'a Program, st: &'a Structured) -> Ctx<'a> {
let mut users: HashMap<Value, Vec<User>> = HashMap::new();
let mut def = HashMap::new();
let mut live: HashSet<Value> = HashSet::new();
for (b, block) in p.blocks.iter().enumerate() {
for (k, phi) in block.phis.iter().enumerate() {
for &a in &phi.args {
users.entry(a).or_default().push(User::Phi(b, k));
}
}
for (i, inst) in block.insts.iter().enumerate() {
for v in used(p, st, b, i) {
users.entry(v).or_default().push(User::Inst(b, i));
live.insert(v);
}
for &(_, w) in &inst.writes {
def.insert(w, (b, i));
}
}
}
// through joins
let mut changed = true;
while changed {
changed = false;
for block in &p.blocks {
for phi in &block.phis {
if live.contains(&phi.value) {
for &a in &phi.args {
changed |= live.insert(a);
}
}
}
}
}
let order = crate::ir::reverse_postorder(&p.blocks);
let mut index = vec![usize::MAX; p.blocks.len()];
for (n, &b) in order.iter().enumerate() {
index[b] = n;
}
let idom = crate::ir::idoms(&p.blocks, &order, &index);
let sections = (0..p.blocks.len()).map(|b| wave::sections(p, b)).collect();
Ctx {
p,
st,
users,
def,
live,
idom,
sections,
}
}
fn inst(&self, u: (usize, usize)) -> &Inst {
&self.p.blocks[u.0].insts[u.1]
}
fn at(&self, u: (usize, usize)) -> usize {
self.inst(u).machine.offset
}
/// Whether block `a` dominates block `b`.
fn dominates(&self, a: usize, mut b: usize) -> bool {
loop {
if a == b {
return true;
}
let d = self.idom.get(b).copied().unwrap_or(usize::MAX);
if d == b || d == usize::MAX {
return false;
}
b = d;
}
}
fn readers(&self, v: Value) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = self
.users
.get(&v)
.into_iter()
.flatten()
.filter_map(|u| match *u {
User::Inst(b, i) => Some((b, i)),
User::Phi(..) => None,
})
.collect();
out.sort_unstable();
out.dedup();
out
}
/// The joins reading `v` whose value something reads.
fn joins(&self, v: Value) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = self
.users
.get(&v)
.into_iter()
.flatten()
.filter_map(|u| match *u {
User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)),
_ => None,
})
.collect();
out.sort_unstable();
out.dedup();
out
}
/// The loop of header `h`: the blocks that reach one of its back edges without passing it.
fn natural_loop(&self, h: usize) -> Vec<bool> {
let mut inside = vec![false; self.p.blocks.len()];
let mut work: Vec<usize> = self.p.blocks[h]
.preds
.iter()
.copied()
.filter(|&q| self.dominates(h, q))
.collect();
if work.is_empty() {
return inside;
}
inside[h] = true;
while let Some(b) = work.pop() {
if inside[b] {
continue;
}
inside[b] = true;
work.extend(self.p.blocks[b].preds.iter().copied());
}
inside
}
/// Whether `b` holds only in lanes where `a` does.
fn implied(&self, b: Bool, a: Atom, memo: &mut HashMap<Bool, bool>) -> bool {
if b == Bool::FALSE {
return true;
}
if let Some(&r) = memo.get(&b) {
return r;
}
let r = match self.st.bools.node(b) {
None => false,
Some((x, lo, _)) if x == a => lo == Bool::FALSE,
Some((_, lo, hi)) => self.implied(lo, a, memo) && self.implied(hi, a, memo),
};
memo.insert(b, r);
r
}
/// The conditional branch reading `scc`, as (its place, the block it goes to when SCC is
/// set, the other one).
fn branch(&self, scc: Value) -> Option<((usize, usize), usize, usize)> {
let [u] = self.readers(scc)[..] else {
return None;
};
let Exit::Branch { taken, not_taken } = self.p.blocks[u.0].exit else {
return None;
};
if u.1 + 1 != self.p.blocks[u.0].insts.len() {
return None;
}
match self.inst(u).name() {
"s_cbranch_scc1" => Some((u, taken, not_taken)),
"s_cbranch_scc0" => Some((u, not_taken, taken)),
_ => None,
}
}
/// One wave OR `t` of `x` over the lanes of `mask`, left by a section of block `sb`: the
/// VGPR values its loop keeps alike, or where and why it is not such a loop.
fn site(&self, sb: usize, t: Value, x: Value, mask: Value) -> Result<Vec<Value>, (usize, Why)> {
let p = self.p;
let st = self.st;
let n = p.blocks.len();
let here = p.blocks[sb].offset;
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
// every lane that runs the section is one of the lanes ORed
let &mb = st.masks.get(&mask).ok_or((here, MASK))?;
if st.bools.meet(&[(st.reach[sb], true), (mb, false)]) {
return Err((here, MASK));
}
// ---- the bits still to visit, and the loop's own steps ----
let mut rem: HashSet<Value> = HashSet::from([t]);
let mut pattern: HashSet<(usize, usize)> = HashSet::new();
let mut alike: Vec<Value> = Vec::new();
// an unguarded copy
let copy = |u: (usize, usize)| -> Option<Value> {
let i = self.inst(u);
(matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none())
.then(|| result(i))
.flatten()
};
let mut init = vec![t];
// (SCC, whether it is set when the OR is empty)
let mut zero: Option<(Value, bool)> = None;
for u in self.readers(t) {
let i = self.inst(u);
let name = i.name();
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
&& other(i, t) == Some(Arg::K(0))
&& zero.is_none()
&& let Some(scc) = i.write(Reg::Scc)
{
zero = Some((scc, name.contains("_eq_")));
rem.insert(scc);
} else if let Some(w) = copy(u) {
init.push(w);
rem.insert(w);
if matches!(i.writes[0].0, Reg::V(_)) {
alike.push(w);
}
} else {
return Err((self.at(u), USED));
}
pattern.insert(u);
}
// the loop's join of them
let mut join: Option<(usize, usize)> = None;
for &v in &init {
if v != t
&& let Some(&u) = self.readers(v).first()
{
return Err((self.at(u), USED));
}
for j in self.joins(v) {
if join.is_some_and(|q| q != j) {
return Err((p.blocks[j.0].offset, USED));
}
join = Some(j);
}
}
let (h, k) = join.ok_or((here, NO_LOOP))?;
let phi = &p.blocks[h].phis[k];
let r = phi.value;
rem.insert(r);
let head = p.blocks[h].offset;
let lp = self.natural_loop(h);
if !lp[h] || lp[sb] {
return Err((head, NO_LOOP));
}
// the set as a scalar: the first lane's copy of it
let cur = if matches!(phi.reg, Reg::V(_)) {
alike.push(r);
let [u] = self.readers(r)[..] else {
return Err((head, USED));
};
let i = self.inst(u);
if i.name() != "v_readfirstlane_b32" || args(i).len() != 1 || !lp[u.0] {
return Err((self.at(u), USED));
}
pattern.insert(u);
let c = result(i).ok_or((self.at(u), SHAPE))?;
if !self.joins(r).is_empty() {
return Err((head, USED));
}
c
} else {
r
};
rem.insert(cur);
// its lowest bit, the set without it, the tests for "that was the last"
let mut idx: Option<Value> = None;
let mut next: Option<(Value, Value)> = None;
// (SCC, whether it is set while bits remain)
let mut more: Vec<(Value, bool)> = Vec::new();
let mut bits: Vec<Value> = Vec::new();
for u in self.readers(cur) {
let i = self.inst(u);
let name = i.name();
if !lp[u.0] {
return Err((self.at(u), USED));
}
match (name, &args(i)[..]) {
("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i),
("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => {
let bit = match (name, &args(i)[..]) {
("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b,
("s_xor_b32", _) => match other(i, cur) {
Some(Arg::Val(b)) if b != cur => b,
_ => return Err((self.at(u), USED)),
},
_ => return Err((self.at(u), USED)),
};
let w = result(i).ok_or((self.at(u), SHAPE))?;
next = Some((w, bit));
bits.push(bit);
if let Some(scc) = i.write(Reg::Scc) {
more.push((scc, true));
rem.insert(scc);
}
}
("s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32", _) => {
let (Some(Arg::Val(b)), Some(scc)) = (other(i, cur), i.write(Reg::Scc)) else {
return Err((self.at(u), USED));
};
bits.push(b);
more.push((scc, name.contains("_lg_")));
rem.insert(scc);
}
_ => return Err((self.at(u), USED)),
}
pattern.insert(u);
}
if cur != r && !self.joins(cur).is_empty() {
return Err((head, USED));
}
let (Some(idx), Some((nx, bit))) = (idx, next) else {
return Err((head, SHAPE));
};
if bits.iter().any(|&b| b != bit) {
return Err((head, SHAPE));
}
// the bit: 1 shifted by the lowest set bit's number (a shift takes five bits of it)
let made = |v: Value| self.def.get(&v).map(|&u| (u, self.inst(u)));
let shifted = match made(bit) {
Some((u, i)) if i.name() == "s_lshl_b32" && lp[u.0] => match args(i)[..] {
[Arg::K(1), Arg::Val(sh)] => Some(sh),
_ => None,
},
_ => None,
};
let by_idx = shifted.is_some_and(|sh| {
sh == idx
|| made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31)))
});
if !by_idx {
return Err((head, SHAPE));
}
// the set less the bit: back into the join, or tested for empty
rem.insert(nx);
let mut nexts = vec![nx];
for u in self.readers(nx) {
let i = self.inst(u);
let name = i.name();
if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32")
&& other(i, nx) == Some(Arg::K(0))
&& let Some(scc) = i.write(Reg::Scc)
{
more.push((scc, name.contains("_lg_")));
rem.insert(scc);
} else if let Some(w) = copy(u) {
nexts.push(w);
rem.insert(w);
if matches!(i.writes[0].0, Reg::V(_)) {
alike.push(w);
}
} else {
return Err((self.at(u), USED));
}
pattern.insert(u);
}
for &v in &nexts {
if v != nx
&& let Some(&u) = self.readers(v).first()
{
return Err((self.at(u), USED));
}
if self.joins(v).iter().any(|&j| j != (h, k)) {
return Err((head, USED));
}
}
for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) {
let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) };
if !ok {
return Err((head, SHAPE));
}
}
// the loop goes on while bits remain and is left when none does
let mut leaves: HashSet<usize> = HashSet::new();
for &(scc, set_while_more) in &more {
if !self.joins(scc).is_empty() {
return Err((head, USED));
}
if self.readers(scc).is_empty() {
continue;
}
let (u, set, clear) = self.branch(scc).ok_or((head, USED))?;
let (on, out) = if set_while_more { (set, clear) } else { (clear, set) };
if !lp[u.0] || !lp[on] || lp[out] {
return Err((self.at(u), SHAPE));
}
leaves.insert(u.0);
pattern.insert(u);
}
if leaves.is_empty() {
return Err((head, SHAPE));
}
// "no bit at all" skips the loop; what lies between that test and the loop runs only
// when there is one
let mut pre = vec![false; n];
if let Some((scc, set_when_empty)) = zero {
if !self.joins(scc).is_empty() {
return Err((here, USED));
}
if !self.readers(scc).is_empty() {
let (u, set, clear) = self.branch(scc).ok_or((here, USED))?;
let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) };
if none == some || lp[u.0] {
return Err((self.at(u), SHAPE));
}
if some != h {
if p.blocks[some].preds[..] != [u.0] || !self.dominates(some, h) {
return Err((self.at(u), SHAPE));
}
for b in 0..n {
pre[b] = self.dominates(some, b) && !self.dominates(h, b);
}
for b in (0..n).filter(|&b| pre[b]) {
let inside = match p.blocks[b].exit {
Exit::End | Exit::Indirect => false,
ref e => e.successors().iter().all(|&s| pre[s] || s == h),
};
if !inside {
return Err((p.blocks[b].offset, SHAPE));
}
}
}
pattern.insert(u);
}
}
// ---- the lane's test of its own bit ----
// (the atom of the compare, its block, its index)
let mut tests: Vec<(Atom, usize, usize)> = Vec::new();
for u in self.readers(bit) {
let i = self.inst(u);
if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() {
continue;
}
let Some(y) = result(i) else { continue };
for c in self.readers(y) {
let ci = self.inst(c);
if matches!(
ci.name(),
"v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32"
| "v_cmp_lg_i32" | "v_cmpx_lg_i32"
) && other(ci, y) == Some(Arg::K(0))
&& lp[c.0]
{
tests.extend(ci.writes.iter().map(|w| (Atom::Lane(w.1), c.0, c.1)));
}
}
}
if tests.is_empty() {
return Err((head, TEST));
}
let mut memo: Vec<HashMap<Bool, bool>> = vec![HashMap::new(); tests.len()];
// what a lane only reaches with its own bit set, in the round of that test
let mut body_block = vec![false; n];
for b in (0..n).filter(|&b| lp[b]) {
body_block[b] = tests.iter().enumerate().any(|(j, &(a, tb, _))| {
b != tb && self.dominates(tb, b) && self.implied(st.reach[b], a, &mut memo[j])
});
}
let body_inst = |b: usize, i: usize, memo: &mut Vec<HashMap<Bool, bool>>| {
body_block[b]
|| lp[b]
&& st.guards[b][i].is_some_and(|g| {
tests.iter().enumerate().any(|(j, &(a, tb, ti))| {
(b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j])
})
})
};
// ---- a round outside the body leaves nothing behind ----
for b in (0..n).filter(|&b| lp[b] || pre[b]) {
for (i, inst) in p.blocks[b].insts.iter().enumerate() {
if lp[b] && body_inst(b, i, &mut memo) {
continue;
}
let u = (b, i);
for &(reg, w) in &inst.writes {
if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) {
continue;
}
for user in self.users.get(&w).into_iter().flatten() {
let stays = match *user {
User::Inst(b2, _) => lp[b2] || pre[b2],
User::Phi(b2, k2) => {
body_block[b2] || !self.live.contains(&p.blocks[b2].phis[k2].value)
}
};
if !stays {
return Err((self.at(u), LEAVES));
}
}
}
if pattern.contains(&u) {
continue;
}
if effect(inst) {
return Err((self.at(u), EFFECT));
}
let name = inst.name();
let cross = name.starts_with("ds_swizzle")
|| name.contains("permute")
|| name.starts_with("v_mbcnt")
|| name.contains("lane")
|| matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some())
|| super::lower::reads_mask_as_data(st, inst)
|| self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end);
if cross {
return Err((self.at(u), CROSS));
}
if used(p, st, b, i).iter().any(|v| rem.contains(v)) {
return Err((self.at(u), USED));
}
}
// left only by "no bits left"; the body may leave it as it likes
if lp[b] && !body_block[b] {
let ok = match p.blocks[b].exit {
Exit::End | Exit::Indirect => false,
ref e => leaves.contains(&b) || e.successors().iter().all(|&s| lp[s]),
};
if !ok {
return Err((p.blocks[b].offset, EXIT));
}
}
}
// ---- no mask that depends on the test outlives its round ----
let mut dep: HashSet<Atom> = tests.iter().map(|t| t.0).collect();
let mut changed = true;
while changed {
changed = false;
for (&id, edges) in &st.phi_masks {
if !dep.contains(&Atom::Phi(id))
&& edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a)))
{
dep.insert(Atom::Phi(id));
changed = true;
}
}
}
let mut seen: HashMap<Bool, bool> = HashMap::new();
let mut tainted = |b: Bool| -> bool {
*seen
.entry(b)
.or_insert_with(|| st.bools.support(b).iter().any(|a| dep.contains(a)))
};
for b in 0..n {
if lp[b] && tests.iter().any(|&(_, tb, _)| self.dominates(tb, b)) {
continue;
}
let stale = st.guards[b].iter().flatten().any(|&g| tainted(g))
|| matches!(st.exits[b], LaneExit::Branch { when, .. } if tainted(when));
if stale {
return Err((p.blocks[b].offset, STALE));
}
}
for (&v, &m) in &st.masks {
if !tainted(m) {
continue;
}
for user in self.users.get(&v).into_iter().flatten() {
let outside = match *user {
User::Inst(b2, _) => !lp[b2],
User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value),
};
if outside {
return Err((head, STALE));
}
}
}
Ok(alike)
}
}
/// The wave ORs of `p` that only steer a loop over each lane's own bits (see the module
/// notes). `why`: one line on stderr for each wave OR that is not one.
pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits {
let mut out = OwnBits::default();
let mut ctx: Option<Ctx> = None;
for b in 0..p.blocks.len() {
let sections = wave::sections(p, b);
let mut starts: Vec<_> = sections.keys().copied().collect();
starts.sort_unstable();
for s in starts {
let sec = &sections[&s];
let mut left: Vec<_> = sec.shapes.iter().collect();
left.sort_unstable_by_key(|(v, _)| v.0);
for (&t, &shape) in left {
let Shape::Active(Op::Or, x, mask, 0) = shape else {
continue;
};
let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st));
// (values only the section itself reads are not results)
let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end);
if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) {
continue;
}
match ctx.site(b, t, x, mask) {
Ok(alike) => {
out.totals.insert(t);
out.alike.extend(alike);
}
Err((offset, what)) => {
if why {
eprintln!(
"WAVE64-OWN-BITS the wave OR at {:#x}: not a loop over the lanes' own bits at {offset:#x}: {what}",
p.blocks[b].insts[s].machine.offset
);
}
}
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::emit::wave::WAVE_OR_V7_TO_S7;
const ADD_BIT_NUMBER: u32 = 0x4A0A_0A0A; // v_add_nc_u32 v5, s10, v5
/// The title's scalarised light loop (`indirect_light_probes:CS_IrradianceCache_Shade`,
/// 0x71f8 on), in small: the wave OR of v7 in s7, a loop over its bits with the lowest
/// one's number in s10 and the bit in s11, and `body` for the lanes whose v7 has the bit
/// (`own`) or for every lane; `latch` runs in every lane after the body, `after` after
/// the loop.
fn light_loop(own: bool, body: &[u32], latch: &[u32], after: &[u32]) -> Program {
let mut w = WAVE_OR_V7_TO_S7.to_vec();
let test: &[u32] = if own {
&[
0x3608_0E0B, // v_and_b32 v4, s11, v7
0xBE8C_047E, // s_mov_b64 s[12:13], exec
0x7DAA_0880, // v_cmpx_ne_u32 exec, 0, v4
]
} else {
&[0xBE8C_047E] // s_mov_b64 s[12:13], exec
};
// from the loop's head to its last branch
let head = 3 + test.len() + usize::from(own) + body.len() + 1 + latch.len() + 3;
w.extend_from_slice(&[
0xBF06_8007, // s_cmp_eq_u32 s7, 0
0xBF85_0000 | (3 + head) as u32, // s_cbranch_scc1 past the loop
0x7E06_0207, // v_mov_b32 v3, s7
0xBF82_0001, // s_branch to the loop's head
0x7E06_0209, // again: v_mov_b32 v3, s9
0x7E10_0503, // head: v_readfirstlane_b32 s8, v3
0xBE8A_1308, // s_ff1_i32_b32 s10, s8
0x8F0B_0A81, // s_lshl_b32 s11, 1, s10
]);
w.extend_from_slice(test);
if own {
w.push(0xBF88_0000 | body.len() as u32); // s_cbranch_execz past the body
}
w.extend_from_slice(body);
w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13]
w.extend_from_slice(latch);
w.extend_from_slice(&[
0x8909_080B, // s_xor_b32 s9, s11, s8
0xBF06_0B08, // s_cmp_eq_u32 s8, s11
0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again
]);
w.extend_from_slice(after);
w.push(0xBF81_0000); // s_endpgm
let code: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
crate::ir::build(&code, true, 256).unwrap()
}
fn found(p: &Program) -> OwnBits {
let st = crate::structure::structure(p).unwrap();
find(p, &st, false)
}
#[test]
fn a_wave_or_that_only_steers_a_loop_over_own_bits_is_found() {
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[]);
let insts = || p.blocks.iter().flat_map(|b| &b.insts);
let names: Vec<&str> = insts().map(|i| i.name()).collect();
for n in [
"s_ff1_i32_b32",
"s_lshl_b32",
"v_and_b32",
"v_cmpx_ne_u32",
"s_xor_b32",
"v_readfirstlane_b32",
"s_cbranch_execz",
] {
assert!(names.contains(&n), "{n} in {names:?}");
}
// a loop: its last branch goes back to the copy of the bits still to visit
assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b)));
let own = found(&p);
// the OR is the section's last lane read, and the bits still to visit (v3) are alike
let total = insts()
.rfind(|i| i.name() == "v_readlane_b32")
.and_then(|i| i.write(Reg::S(7)))
.unwrap();
assert_eq!(own.totals, HashSet::from([total]));
let first = insts().find(|i| i.name() == "v_readfirstlane_b32").unwrap();
assert!(own.alike.contains(&first.read(Reg::V(3)).unwrap()));
}
#[test]
fn a_loop_whose_lanes_all_work_at_every_bit_needs_the_whole_waves_or() {
// (the same title's volume loops, 0xa668 on: no test of the lane's own mask)
let p = light_loop(false, &[ADD_BIT_NUMBER], &[], &[]);
assert!(found(&p).totals.is_empty());
}
#[test]
fn a_bit_number_read_after_the_loop_is_not_the_lanes_own() {
// v_mov_b32 v6, s10: the last bit of the OR, which another lane may have set
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020A]);
assert!(found(&p).totals.is_empty());
}
#[test]
fn the_bits_still_to_visit_read_in_the_body_are_not_the_lanes_own() {
// v_add_nc_u32 v5, s8, v5: s8 holds the other lanes' bits too
let p = light_loop(true, &[0x4A0A_0A08], &[], &[]);
assert!(found(&p).totals.is_empty());
}
#[test]
fn a_count_of_the_rounds_is_not_the_lanes_own() {
// s_add_i32 s14, s14, 1 where every lane passes, read after the loop
// (v_mov_b32 v6, s14): one round for each bit any lane has
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]);
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32"));
assert!(found(&p).totals.is_empty());
// (reading s14 there without counting in it is nothing of the loop's)
let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]);
assert_eq!(found(&p).totals.len(), 1);
}
#[test]
fn an_effect_where_every_lane_passes_is_not_the_lanes_own() {
// ds_write_b32 v5, v5 after the body: once for each bit any lane has
let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]);
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32"));
assert!(found(&p).totals.is_empty());
}
}
+115 -3
View File
@@ -21,6 +21,10 @@ use crate::ir::{EXEC, Inst, Program, Reg, Value};
pub(crate) enum Op {
AddU,
AddF,
/// A sum of 16-bit floats in the low halves (`v_add_f16`), each addition rounded to 16
/// bits: not associative, so only the balanced tree over the lanes in their order is
/// followed (see [`buddies`]), which is how the compiler sums a wave.
AddH,
MinU,
MaxU,
MinI,
@@ -39,6 +43,7 @@ impl Op {
// the high one) is the 32-bit sum of the low dwords
"v_add_nc_u32" | "v_add_co_u32" => Op::AddU,
"v_add_f32" => Op::AddF,
"v_add_f16" => Op::AddH,
"v_min_u32" => Op::MinU,
"v_max_u32" => Op::MaxU,
"v_min_i32" => Op::MinI,
@@ -55,7 +60,7 @@ impl Op {
/// Whether `k` leaves the other operand unchanged.
fn identity(self, k: u32) -> bool {
match self {
Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0,
Op::AddU | Op::AddH | Op::Or | Op::Xor | Op::MaxU => k == 0,
Op::AddF => k == 0 || k == 0x8000_0000,
Op::MinU | Op::And => k == u32::MAX,
Op::MinI => k == 0x7FFF_FFFF,
@@ -67,7 +72,26 @@ impl Op {
/// Counting a lane twice changes the result.
fn counts(self) -> bool {
matches!(self, Op::AddU | Op::AddF | Op::Xor)
matches!(self, Op::AddU | Op::AddF | Op::AddH | Op::Xor)
}
}
/// Whether the lane sets `a` and `b` are the two halves of one aligned run of lanes: lanes
/// 2k and 2k+1, then two such pairs side by side, and so on up to the two halves of the
/// wave. Sums joined only that way form the balanced tree over the lanes in their order,
/// whichever of the two a lane adds to the other (the addition is commutative).
fn buddies(a: u64, b: u64) -> bool {
let n = a.count_ones();
if n != b.count_ones() || !n.is_power_of_two() || n == 64 {
return false;
}
let run = |s: u64| {
let first = s.trailing_zeros();
(first.is_multiple_of(n) && s >> first == (1u64 << n) - 1).then_some(first)
};
match (run(a), run(b)) {
(Some(x), Some(y)) => x.min(y) % (2 * n) == 0 && x.abs_diff(y) == n,
_ => false,
}
}
@@ -218,7 +242,8 @@ fn combine(op: Op, a: Sym, b: Sym) -> Sym {
&& op.identity(ident)
&& oa.is_none_or(|o| o == op)
&& ob.is_none_or(|o| o == op)
&& (!op.counts() || la & lb == 0) =>
&& (!op.counts() || la & lb == 0)
&& (op != Op::AddH || buddies(la, lb)) =>
{
Sym::Red {
op: Some(op),
@@ -635,6 +660,32 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> {
Some(Shape::Prefix(op, src, mask, ident, inclusive))
}
/// `WaveActiveBitOr(v7)` into s7 as the console compiler expands it: every lane takes part,
/// those outside the saved EXEC (s[4:5]) with 0.
#[cfg(test)]
pub(super) const WAVE_OR_V7_TO_S7: [u32; 20] = [
0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1
0xD501_0001,
0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5]
0x3802_02E9,
0xDE54_C101, // v_or_b32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6]
0x3802_02E9,
0x9360_1201, // v_or_b32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4]
0x3802_02E9,
0x0009_2401, // v_or_b32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0]
0x3802_02FA,
0xFF09_4001, // v_or_b32 v1, v1, v1 row_mirror bound_ctrl:1
0xD778_0002,
0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0
0x3802_0302, // v_or_b32 v1, v2, v1
0xD760_0007,
0x0001_4101, // v_readlane_b32 s7, v1, 32
0x3802_0207, // v_or_b32 v1, s7, v1
0xD760_0007,
0x0001_0101, // v_readlane_b32 s7, v1, 0
0xBEFE_0404, // s_mov_b64 exec, s[4:5]
];
#[cfg(test)]
mod tests {
use super::*;
@@ -859,6 +910,67 @@ mod tests {
}
}
/// `WaveActiveSum` of 16-bit floats, as compiled in
/// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the
/// lowering reproduces. A tree in another order is not followed.
#[test]
fn a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree() {
let words = |first: [u32; 2], second: [u32; 2]| {
[
0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1
0xD501_0001,
0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5]
first[0],
first[1],
second[0],
second[1],
0x6402_02E9,
0x0009_2401, // v_add_f16 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0]
0x6402_02FA,
0xFF09_4001, // v_add_f16 v1, v1, v1 row_mirror bound_ctrl:1
0xD778_0002,
0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0
0x6402_0302, // v_add_f16 v1, v2, v1
0xD760_0007,
0x0001_4101, // v_readlane_b32 s7, v1, 32
0x6402_0207, // v_add_f16 v1, s7, v1
0xD760_0007,
0x0001_0101, // v_readlane_b32 s7, v1, 0
0xBEFE_0404, // s_mov_b64 exec, s[4:5]
]
};
let pairs = [0x6402_02E9, 0xDE54_C101]; // v_add_f16 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6]
let quads = [0x6402_02E9, 0x9360_1201]; // v_add_f16 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4]
let shape = |w: &[u32]| {
let p = build(w, true);
let insts = &p.blocks[0].insts;
let saved = insts[0].write(Reg::S(4)).unwrap();
let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap();
// ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm
let total = insts[insts.len() - 3].write(Reg::S(7)).unwrap();
(sections(&p, 0)[&0].shapes.get(&total).copied(), Shape::Active(Op::AddH, v7, saved, 0))
};
let (found, want) = shape(&words(pairs, quads));
assert_eq!(found, Some(want));
// lanes two apart first, neighbours second: every lane counted once, but
// (x0 + x2) + (x1 + x3) rounds differently from (x0 + x1) + (x2 + x3)
let (found, _) = shape(&words(quads, pairs));
assert_eq!(found, None);
}
#[test]
fn buddies_are_the_two_halves_of_an_aligned_run() {
assert!(buddies(0b01, 0b10));
assert!(buddies(0b1100, 0b0011));
assert!(buddies(0xF0, 0x0F));
assert!(buddies(u64::from(u32::MAX), u64::from(u32::MAX) << 32));
assert!(!buddies(0b010, 0b100)); // lanes 1 and 2: not one pair
assert!(!buddies(0b0011, 0b110000)); // pairs 0 and 2
assert!(!buddies(0b0101, 0b1010)); // not runs
assert!(!buddies(0b01, 0b1100)); // unequal
assert!(!buddies(0b11, 0b11));
}
#[test]
fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() {
let w = [
@@ -0,0 +1,452 @@
//! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a
//! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`])
//! so that the two host waves can exchange their halves inside it. Lowered, validated by
//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32.
use std::collections::HashSet;
use super::host::{Dispatch, Host, Root, View};
use super::{HostShader, lower, validator};
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
use crate::{ShaderError, io, ir, resource, structure};
const S_ENDPGM: u32 = 0xBF81_0000;
/// 64 threads in one console wave. Each thread t holds the bit `1 << (t >> 1)`; the threads
/// below s0 (a root constant) OR theirs over the wave inside `if (t < s0) { ... }` and store
/// the result to dword 0 of the raw UAV.
/// `skip`: the branch past the body when no thread is below s0: `s_cbranch_execz`, or
/// `s_cbranch_scc0` on the SCC `s_and_saveexec` sets ("some lane is left").
fn program(skip: u32) -> NativeProgram {
let mut words = vec![
0x7E0A_0281, // v_mov_b32 v5, 1
0x2C0C_0081, // v_lshrrev_b32 v6, 1, v0
0x340E_0B06, // v_lshlrev_b32 v7, v6, v5
0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
skip | 23, // the branch to the restore of EXEC
];
words.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7);
words.extend_from_slice(&[
0x7E00_0207, // v_mov_b32 v0, s7
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
0xBEFE_040C, // s_mov_b64 exec, s[12:13]
]);
native(&words)
}
/// A wave64 compute program of 64 threads (one console wave; the thread index in v0) with 4
/// root constants in s0..s3 and a raw UAV's descriptor in s[8:11], then `body`.
fn native(body: &[u32]) -> NativeProgram {
native_of(body, true, 64)
}
/// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads.
fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram {
let mut words = vec![
0xBE85_0380, // s_mov_b32 s5, 0
0x3D << 26 | 0x02 << 18 | 8 << 6 | 2,
125 << 25, // s_load_dwordx4 s[8:11], s[4:5], 0
];
words.extend_from_slice(body);
words.push(S_ENDPGM);
NativeProgram {
stage: HwStage::Cs,
wave64,
vgprs: 16,
layout: vec![
RootParam {
root: RootType::Constants,
table_offset_dwords: 0,
sgprs: 4,
base_register: 0,
user_data: 0,
slot: 0,
},
RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data: 4,
slot: 1,
},
],
used: vec![UsedResource {
kind: ResourceType::Uav,
root: RootType::Table,
table_offset_dwords: 0,
lower_bound: 0,
stride: 0,
dwords: 4,
user_data: 4,
slot: 1,
}],
io: StageIo::Cs(ComputeIo {
rsrc2: 5 << 1, // 5 user SGPRs: s0..s4
threads: [threads, 1, 1],
}),
code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
}
}
/// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide.
fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet<usize>) -> Result<HostShader, ShaderError> {
let st = structure::structure_wide(p, wide).expect("structure");
let res = resource::track(p, &native.layout, native.stage, Some(&st)).expect("resource::track");
let io = io::raise(p, native).expect("io::raise");
let was = lower::TEST_HOST_WAVE.replace(Some(32));
let lowered = lower::lower(&lower::Parts {
native,
p,
st: &st,
io: &io,
res: &res,
inputs: Vec::new(),
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
});
lower::TEST_HOST_WAVE.set(was);
let lowered = lowered?;
Ok(HostShader {
stage: HwStage::Cs,
dxil: lowered.dxil,
user_data: lowered.user_data,
samplers: lowered.samplers,
static_samplers: Vec::new(),
root_cbvs: lowered.root_cbvs,
root_srvs: lowered.root_srvs,
root_uavs: lowered.root_uavs,
root_indexed_views: res.root_indexed_views,
})
}
#[test]
fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() {
// thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd
// mantissas, so that additions round); all of them store the wave's sum
let mut words = vec![
0x340C_0085, // v_lshlrev_b32 v6, 5, v0
0x340E_0082, // v_lshlrev_b32 v7, 2, v0
0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7
0x4A0E_0F00, // v_add_nc_u32 v7, v0, v7
0x4A0E_0EFF,
0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7
];
// (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28)
words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w }));
words.extend_from_slice(&[
0x7E00_0207, // v_mov_b32 v0, s7
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
]);
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6);
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
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");
}
// the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits
// (to nearest, ties to even); values here are normal numbers
let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13);
let narrow = |f: f32| {
let b = f.to_bits();
let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF);
let rest = b & 0x1FFF;
(h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16
};
let add = |a: u16, b: u16| narrow(wide(a) + wide(b));
let terms: Vec<u16> = (0..64u16).map(|t| 0x3C00 + 37 * t).collect();
let mut tree = terms.clone();
while tree.len() > 1 {
tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect();
}
let in_a_row = terms.iter().copied().reduce(add).unwrap();
assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order");
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let (root, pso) = match host.compute_pipeline(&shader) {
Ok(x) => x,
Err(e) => {
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
return;
}
};
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
// (the high half is lane 0's term's: zero)
assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]);
eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]);
}
/// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2
/// (0x4000) is 3 + 1.5 steps of that range, which the console rounds up to 0x4202. The
/// host's `f32tof16` may give 0x4201 (toward zero); with `VICTORY_F16_NEAREST=1` the
/// translation gives the console's whatever the host does.
#[test]
fn a_16_bit_sum_rounds_to_nearest_when_asked_to() {
let words = [
0x7E0E_02FF,
0x0000_3C03, // v_mov_b32 v7, 0x3c03
0x7E0C_02FF,
0x0000_4000, // v_mov_b32 v6, 0x4000
0x6400_0D07, // v_add_f16 v0, v7, v6
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
];
let native = native(&words);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16"));
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for nearest in [false, true] {
let was = lower::TEST_F16_NEAREST.replace(Some(nearest));
let shader = lowered(&native, &p, &HashSet::new());
lower::TEST_F16_NEAREST.set(was);
let shader = shader.expect("lower");
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 Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let Ok((root, pso)) = host.compute_pipeline(&shader) else {
eprintln!("the hardware device does not take this program; not run");
return;
};
let ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
let got = out[0][0] & 0xFFFF;
eprintln!("v_add_f16 0x3c03 + 0x4000 on the hardware device, nearest {nearest}: {got:#x}");
if nearest {
assert_eq!(got, 0x4202);
} else {
assert!(got == 0x4201 || got == 0x4202, "{got:#x}");
}
}
}
#[test]
fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() {
for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] {
a_wave_or_inside(skip, name);
}
}
fn a_wave_or_inside(skip: u32, name: &str) {
let native = program(skip);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let branch = (0..p.blocks.len())
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == name))
.expect("the branch");
// per lane, the two host waves cannot meet inside the branch
lower::take_needs();
let per_lane = lowered(&native, &p, &HashSet::new());
assert!(
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a wave reduction where not every lane runs"),
"{:?}",
per_lane.err()
);
// ... and the lowering names the block, around which that branch is the one to widen
let needs = lower::take_needs();
let st = structure::structure(&p).expect("structure");
assert_eq!(lower::branches_around(&st, &needs), Some(vec![branch]));
// (taken, past the body, when every lane's bit is clear)
assert_eq!(st.wave_any[branch], Some(false));
// wave-wide, every lane runs the reduction (EXEC stays a guard on what it does there)
let wide = HashSet::from([branch]);
let st = structure::structure_wide(&p, &wide).expect("structure");
let inside = match p.blocks[branch].exit {
ir::Exit::Branch { not_taken, .. } => not_taken,
_ => unreachable!(),
};
assert!(st.guards[inside].iter().any(Option::is_some));
let shader = lowered(&native, &p, &wide).expect("lower");
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");
}
// On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of
// both halves, whichever half's lanes take the branch.
let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return;
};
let (root, pso) = match host.compute_pipeline(&shader) {
Ok(x) => x,
Err(e) => {
eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run");
return;
}
};
// (threads below s0 take the branch; thread t gives bit t >> 1)
for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] {
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) {
ud[u.index as usize] = below;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
assert_eq!(out[0][0], expected, "{name}: {below} threads in the branch");
}
eprintln!("ran on the hardware device ({name}): the OR of both halves in every case");
}
/// Runs `shader` on the hardware device with the root constants `s0`, `s1` and gives dword 0
/// of the UAV; None (and a line) without a device that takes it.
fn on_the_card(shader: &HostShader, constants: [u32; 2]) -> Option<u32> {
let Ok(host) = Host::new(false) else {
eprintln!("no SM 6.6 hardware device; not run");
return None;
};
let Ok((root, pso)) = host.compute_pipeline(shader) else {
eprintln!("the hardware device does not take this program; not run");
return None;
};
let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize];
for u in &shader.user_data {
if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) {
ud[u.index as usize] = constants[d as usize];
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(1)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
Some(out[0][0])
}
/// A 32-lane console wave. A register holds a lane mask on one path (the lanes below s0)
/// and a number on the other, and is read as a number after the join, as the trace programs
/// keep their lanes' masks and their node numbers on one stack
/// (`deferred_tiled:CS_LaserLightShadowRaytracing`, s46 at 0x104, 0x75c and 0x188). The
/// mask arrives as the ballot of its lanes.
#[test]
fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() {
let words = [
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
0xBE94_036A, // s_mov_b32 s20, vcc_lo
0xBF06_8001, // s_cmp_eq_u32 s1, 0
0xBF85_0001, // s_cbranch_scc1 over the next
0xBE94_0385, // s_mov_b32 s20, 5
0x7E00_0214, // v_mov_b32 v0, s20
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0
];
let native = native_of(&words, false, 32);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let shader = lowered(&native, &p, &HashSet::new()).expect("lower");
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 _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] {
let Some(got) = on_the_card(&shader, [below, other]) else { return };
assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}");
}
eprintln!("ran on the hardware device: the mask's bits, or the number");
}
/// A 32-lane console wave. `if (t < s0) { ... SCC = (s1 == 7) }` and a branch on SCC after
/// the join: the skip brings the SCC of `s_and_saveexec` ("some lane is left") along
/// (`rtdirectionalshadows:CS_RTShadowTrace32HQ_TiledFarOnly`, 0x360-0x39c). On the console
/// the skip is taken by the wave, so with some lane inside every lane sees the inner test.
/// A lane that skipped on its own would see "some lane is left" instead: refused per lane,
/// right with the branch taken wave-wide. Lane 31 stores what it saw.
#[test]
fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() {
let words = [
0x7D88_0000, // v_cmp_gt_u32 vcc_lo, s0, v0
0xBE8D_3C6A, // s_and_saveexec_b32 s13, vcc_lo
0xBF88_0001, // s_cbranch_execz over the next
0xBF06_8701, // s_cmp_eq_u32 s1, 7
0xBEFE_030D, // s_mov_b32 exec_lo, s13
0xBF85_0002, // s_cbranch_scc1 to "seven"
0x7E0A_0281, // v_mov_b32 v5, 1
0xBF82_0001, // s_branch over the next
0x7E0A_0282, // seven: v_mov_b32 v5, 2
0x7DA4_009F, // v_cmpx_eq_u32 exec_lo, 31, v0
0x38 << 26 | 0x1C << 18,
0x80 << 24 | 2 << 16 | 5 << 8, // buffer_store_dword v5, off, s[8:11], 0
];
let native = native_of(&words, false, 32);
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let branch = (0..p.blocks.len())
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"))
.expect("the skip");
lower::take_needs();
let per_lane = lowered(&native, &p, &HashSet::new());
assert!(
matches!(&per_lane, Err(ShaderError::Unsupported { what, .. }) if *what == "a lane mask read as data"),
"{:?}",
per_lane.err()
);
let st = structure::structure(&p).expect("structure");
assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch]));
let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower");
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 _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
// (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch
for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] {
let Some(got) = on_the_card(&shader, [below, s1]) else { return };
assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}");
}
eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside");
}
+121 -6
View File
@@ -594,12 +594,74 @@ pub(crate) fn without_early_outs(p: &Program) -> Option<Program> {
/// after it could see that (a scalar register or SCC that the region
/// changes and the join merges with the value from before; EXEC aside,
/// which is empty either way). `None` if nothing changes.
pub(crate) fn without_skips(p: &Program) -> Option<Program> {
///
/// `deep` looks closer at what the code after the branch can see. A scalar the region moves
/// away and back (the compiler parks scalars in VGPR lanes around a branch and takes them
/// back before the join, `unspill`) is the value it copies; a join nothing reads shows no
/// one the difference (a restore of EXEC that the next one overwrites reads nothing); and
/// the join may have other ways in (an inner branch that ends together with an outer one).
/// That leaves out most of the skips of the title's large lighting programs, whose bodies
/// are then code every lane runs.
pub(crate) fn without_skips(p: &Program, deep: bool) -> Option<Program> {
let n = p.blocks.len();
let ends = |b: usize| {
p.blocks[b].exit == Exit::End
&& p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. }))
};
// Scalars moved from register to register (a scalar the compiler parked in a VGPR lane
// comes back by such a move, `unspill`) are the value they copy.
let mut copy: std::collections::HashMap<Value, Value> = Default::default();
// Values something reads, directly or through joins. A scalar operation none of whose
// results is read reads nothing either (the compiler restores EXEC from a saved mask
// and overwrites it at once where two branches end together).
let mut live: std::collections::HashSet<Value> = Default::default();
let idle = |inst: &Inst, live: &std::collections::HashSet<Value>| {
let name = inst.name();
matches!(inst.fields, crate::gfx10::Fields::Sop { .. })
&& !(name.starts_with("s_setpc")
|| name.starts_with("s_swappc")
|| name.starts_with("s_call")
|| name.starts_with("s_rfe")
|| name.starts_with("s_movrel")
|| name.starts_with("s_subvector"))
&& inst.writes.iter().all(|w| !live.contains(&w.1))
};
for block in &p.blocks {
for inst in &block.insts {
if matches!(inst.name(), "s_mov_b32" | "s_mov_b64")
&& inst.reads.len() == inst.writes.len()
&& inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_)))
{
copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1)));
}
}
}
let mut changed = true;
while changed {
changed = false;
for block in &p.blocks {
for inst in &block.insts {
if !idle(inst, &live) {
for r in &inst.reads {
changed |= live.insert(r.1);
}
}
}
for phi in &block.phis {
if live.contains(&phi.value) {
for &a in &phi.args {
changed |= live.insert(a);
}
}
}
}
}
let root = |mut v: Value| {
while deep && let Some(&c) = copy.get(&v) {
v = c;
}
v
};
// The region a skip of `b` to `target` leaves out, if it is a pure skip.
let skipped = |b: usize, target: usize, first: usize| -> Option<Vec<bool>> {
let mut inside = vec![false; n];
@@ -631,18 +693,21 @@ pub(crate) fn without_skips(p: &Program) -> Option<Program> {
Reg::Scc => true,
Reg::V(_) => false,
};
if !scalar {
// (a join nothing reads shows no one the difference)
if !scalar || deep && !live.contains(&phi.value) {
continue;
}
let before: Vec<Value> =
join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| *a).collect();
let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| *a);
join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect();
let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a));
if within.into_iter().any(|a| !before.contains(&a)) {
return None;
}
}
// other ways into the join than the branch and the region: not a plain `if`
if join.preds.iter().any(|&q| q != b && !inside[q]) {
// Other ways into the join than the branch and the region (an inner branch that ends
// together with an outer one) change nothing in that: the lanes that would have
// skipped arrive from the region instead, with the same scalars.
if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) {
return None;
}
Some(inside)
@@ -1458,6 +1523,56 @@ mod tests {
p.inputs.iter().find(|i| i.0 == reg).expect("input").1
}
/// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what
/// follows the join.
fn skip(body: &[u32], after: &[u32]) -> Program {
let mut w = vec![
0xBE94_0306, // s_mov_b32 s20, s6
0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0
0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc
0xBF88_0000 | body.len() as u32, // s_cbranch_execz past the body
];
w.extend_from_slice(body);
w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13]
w.extend_from_slice(after);
w.push(S_ENDPGM);
build_words(&w, true)
}
fn skips(p: &Program) -> usize {
p.blocks
.iter()
.filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz"))
.count()
}
#[test]
fn a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read() {
const SET: u32 = 0xBE86_0385; // s_mov_b32 s6, 5
const USE: u32 = 0x7E02_0206; // v_mov_b32 v1, s6
const BACK: u32 = 0xBE86_0314; // s_mov_b32 s6, s20
const READ: u32 = 0x7E04_0206; // v_mov_b32 v2, s6
// s6 is changed in the body and read after the join: the branch stays
let kept = skip(&[SET, USE], &[READ]);
assert_eq!(skips(&kept), 1);
assert!(without_skips(&kept, false).is_none());
assert!(without_skips(&kept, true).is_none());
// ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes
// back): every lane may walk the body
let back = skip(&[SET, USE, BACK], &[READ]);
assert!(without_skips(&back, false).is_none());
assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0);
// ... or not read after the join at all
let unread = skip(&[SET, USE], &[]);
assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0);
assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0);
// ... or read only by a restore of EXEC that nothing uses before the next one
// (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0)
let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]);
assert!(without_skips(&idle, false).is_none());
assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0);
}
#[test]
fn joins_get_phis_only_where_values_differ() {
let code = [
+1 -1
View File
@@ -2671,7 +2671,7 @@ pub(crate) mod tests {
];
// v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10..
words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k));
words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | 0x100 + 10 + k));
words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k)));
words.extend([
0xF000_1700,
0x0004_0D06, // image_load v[13:15], v6, s[16:23]
+71
View File
@@ -434,6 +434,15 @@ pub struct Structured {
/// Incoming lane boolean per predecessor edge (in block predecessor order)
/// for each [`Atom::Phi`] id.
pub phi_masks: HashMap<Value, Vec<Bool>>,
/// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its
/// `when` is still the lane's own bit; the wave goes by all of them.
pub wide: HashSet<usize>,
/// Per block closed by a branch on a lane mask: whether the console takes it when some
/// lane's `when` holds (`true`) or when every lane's does (`false`).
pub wave_any: Vec<Option<bool>>,
/// SCC values a mask operation sets when some lane's bit of its result is set, with that
/// lane bit: as data such an SCC is "some lane of the wave has it".
pub scc_some: HashMap<Value, Bool>,
}
impl Structured {
@@ -448,7 +457,20 @@ impl Structured {
/// Builds the per-lane form of `program`.
pub fn structure(program: &Program) -> Result<Structured, ShaderError> {
structure_wide(program, &HashSet::new())
}
/// [`structure`], with the branches that close the blocks of `wide` kept as the console has
/// them: one decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's
/// bit is set; `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise,
/// [`Structured::wave_any`]), which every lane follows. A lane
/// then learns nothing about its own bit from the way it went, so past such a branch EXEC
/// stays a guard on every vector instruction, as it is on the console. For a console wave
/// run as two host waves, which exchange that decision and can then meet (a group barrier)
/// inside the branch.
pub fn structure_wide(program: &Program, wide: &HashSet<usize>) -> Result<Structured, ShaderError> {
let mut l = Lanes::new(program)?;
l.wide = wide.clone();
loop {
let execs = l.masks_in_order();
let cond = l.paths()?;
@@ -508,6 +530,13 @@ struct Lanes<'a> {
when: Vec<Option<Bool>>,
/// See [`Structured::active`].
active: HashSet<Value>,
/// See [`Structured::wide`].
wide: HashSet<usize>,
/// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of
/// two masks: "no lane differs"); the others are set when some lane's is.
scc_every: HashSet<Value>,
/// See [`Structured::wave_any`].
wave_any: Vec<Option<bool>>,
}
/// A mask join taken as `value` in every lane that reaches `block`: each
@@ -585,6 +614,9 @@ impl<'a> Lanes<'a> {
first: vec![Bool::FALSE; blocks.len()],
when: vec![None; blocks.len()],
active: HashSet::new(),
wide: HashSet::new(),
scc_every: HashSet::new(),
wave_any: vec![None; blocks.len()],
})
}
@@ -594,6 +626,8 @@ impl<'a> Lanes<'a> {
self.other.clear();
self.seen.clear();
self.scc_lane.clear();
self.scc_every.clear();
self.wave_any.fill(None);
self.joins.clear();
self.phi_joins.clear();
self.phi_join_ids.clear();
@@ -652,6 +686,7 @@ impl<'a> Lanes<'a> {
&& let Some(last) = p.blocks[b].insts.last()
{
self.when[b] = Some(self.branch(last));
self.wave_any[b] = self.wave_kind(last);
}
}
execs
@@ -659,6 +694,10 @@ impl<'a> Lanes<'a> {
/// `c` narrowed by the branch at the end of `q` towards one successor.
fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool {
if self.wide.contains(&q) {
// the wave's decision: it says nothing about this lane's own bit
return c;
}
match self.when[q] {
Some(w) if taken => self.b.and(c, w),
Some(w) => {
@@ -809,6 +848,14 @@ impl<'a> Lanes<'a> {
.collect(),
paired_masks: if self.p.wave64 { self.masks } else { Map::default() },
active: self.active,
wide: self.wide,
wave_any: self.wave_any,
scc_some: self
.scc_lane
.iter()
.filter(|(scc, _)| !self.scc_every.contains(scc))
.map(|(&scc, &m)| (scc, m))
.collect(),
phi_masks,
bools: self.b,
exits,
@@ -1184,6 +1231,9 @@ impl<'a> Lanes<'a> {
ne
};
self.scc_lane.insert(scc, m);
if rest.starts_with("eq") {
self.scc_every.insert(scc);
}
}
// `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar
// condition, or EXEC itself): its SCC, "some lane is set", is each lane's own
@@ -1252,6 +1302,27 @@ impl<'a> Lanes<'a> {
}
/// The per-lane condition under which a block's closing branch is taken.
/// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own
/// `when` ([`Self::branch`]): taken when some lane's holds (`true`) or when every lane's
/// does (`false`). `execnz`/`vccnz` ask for some set bit, `execz`/`vccz` for none; SCC
/// of a mask operation is "some lane's bit is set", SCC of `s_cmp_eq` of two masks is
/// "every lane's is" ([`Self::scc_every`]), and `scc0` branches on the opposite. None
/// for a branch on a scalar condition.
fn wave_kind(&self, inst: &Inst) -> Option<bool> {
match inst.name() {
"s_cbranch_execnz" | "s_cbranch_vccnz" => Some(true),
"s_cbranch_execz" | "s_cbranch_vccz" => Some(false),
n @ ("s_cbranch_scc0" | "s_cbranch_scc1") => {
let scc = inst.read(Reg::Scc)?;
self.scc_lane.get(&scc)?;
// set: SCC is 1 when some lane's bit is set (every lane's, for a compare)
let every = self.scc_every.contains(&scc);
Some((n == "s_cbranch_scc1") != every)
}
_ => None,
}
}
fn branch(&mut self, inst: &Inst) -> Bool {
let exec = self.exec(inst);
match inst.name() {