Merge agent/shaders: pipelines left out on purpose named; wave64 groups of several console waves on 32-lane hosts

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
readmet3xt-labandClaude Opus 5.5 committed 2026-11-26 17:39:29 +05:30
commit 5876706fb0
6 files changed
+467 -42

No files matched your search

+3 -1
View File
@@ -8740,6 +8740,7 @@ impl Meter {
});
let dropped = crate::draw::take_dropped() as f64 / frames;
let indirect = crate::list::take_indirect() as f64 / frames;
let left_out = crate::pipeline::take_left_out() as f64 / frames;
let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed);
let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames;
let refused = BUDGET_NOTES[0].swap(0, Ordering::Relaxed) as f64 / frames;
@@ -8943,7 +8944,8 @@ impl Meter {
{copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
dropped {dropped:.0} without a host pipeline ({making} being made) and \
{indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
{indirect:.0} indirect ({left_out:.0} of all these left out on purpose: \
ray-tracing passes without the structure builder); heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \
textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \
{picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}",
picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed),
+7
View File
@@ -465,6 +465,13 @@ pub(crate) fn making() -> u64 {
make::waiting()
}
/// Draws and dispatches asked of pipelines left out on purpose since the last
/// call (ray-tracing passes without the structure builder).
#[cfg(windows)]
pub(crate) fn take_left_out() -> u64 {
make::take_left_out()
}
/// Draws and dispatches dropped since the last [`take_drops`], by reason
/// (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
+40 -2
View File
@@ -150,10 +150,16 @@ impl Pending {
}
}
/// Why a pipeline has no host pipeline (diagnostics): its shaders that do
/// not translate, else "refused" or "being made"; `None` if it has one.
/// Why a pipeline has no host pipeline (diagnostics): left out on purpose
/// ([`left_out`]), its shaders that do not translate, else "refused" or
/// "being made"; `None` if it has one. (A pipeline left out is never made:
/// it was counted as "being made" in every frame, some 630 indirect
/// ray-tracing resolves a frame in gameplay, while no pipeline was queued.)
#[cfg(feature = "diagnostics")]
pub(crate) fn missing(p: &Pending) -> Option<String> {
if let Some(why) = p.left_out {
return Some(format!("left out on purpose: {why}"));
}
match p.made.get() {
Some(Some(_)) => None,
None => Some("being made".into()),
@@ -213,6 +219,15 @@ fn screens_first() -> bool {
/// Pipelines queued and not made yet.
static WAITING: AtomicU64 = AtomicU64::new(0);
/// Draws and dispatches (direct and indirect) asked of a pipeline left out on
/// purpose ([`left_out`]), since the last [`take_left_out`].
static LEFT_OUT: AtomicU64 = AtomicU64::new(0);
/// See [`LEFT_OUT`] (for the frame line).
pub(crate) fn take_left_out() -> u64 {
LEFT_OUT.swap(0, Ordering::Relaxed)
}
/// Pipelines queued and not made yet (for the frame line).
pub(crate) fn waiting() -> u64 {
WAITING.load(Ordering::Relaxed)
@@ -222,6 +237,7 @@ pub(crate) fn waiting() -> u64 {
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
if p.left_out.is_some() {
LEFT_OUT.fetch_add(1, Ordering::Relaxed);
return None;
}
// A still-pending pipeline was requested by the title too. Prewarm it
@@ -586,6 +602,28 @@ mod tests {
assert!(matches!(p.made.get(), Some(None)));
}
/// A pipeline left out on purpose (a ray-tracing resolve without the structure builder)
/// is never queued, so never made: it is counted as left out, and named so, not as
/// "being made" (some 630 indirect dispatches a frame were, in every gameplay frame).
#[test]
fn pipelines_left_out_are_counted_and_never_queued() {
let mut p = Pending::new(Vec::new(), None);
p.left_out = Some("shades ray-tracing hits without BVH, left out");
let p = Arc::new(p);
let before = LEFT_OUT.load(Ordering::Relaxed);
assert!(ready(&p).is_none());
assert!(ready(&p).is_none());
assert!(!now(&p));
assert_eq!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED);
assert!(p.made.get().is_none());
assert!(LEFT_OUT.load(Ordering::Relaxed) >= before + 2);
#[cfg(feature = "diagnostics")]
assert_eq!(
missing(&p).as_deref(),
Some("left out on purpose: shades ray-tracing hits without BVH, left out")
);
}
#[test]
fn pending_pipeline_is_recorded_for_the_next_launch() {
let mut p = Pending::new(Vec::new(), None);
+226 -31
View File
@@ -360,6 +360,11 @@ struct Lower<'a> {
/// handed to host waves (`wave_base`), and the base made in the entry block.
halves: Option<u32>,
wave_base: Option<V>,
/// The host waves of a console wave meet on their own ([`with_pair_meetings`]): the first
/// of the LDS dwords that count each console wave's arrivals, and the dword of this
/// thread's console wave (made in the entry block).
pairs: Option<u32>,
meeting: Option<V>,
/// Vertex and mesh outputs holding 16-bit values: row, whether two per
/// dword, and the row packed after it.
half_outputs: HashMap<u8, (bool, Option<u8>)>,
@@ -434,9 +439,16 @@ pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read
/// 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>> {
all_lane_blocks_of(st, false)
}
/// [`all_lane_blocks`]; with `group`, of every console wave of the thread group: the branches
/// a console wave takes together ([`Structured::wide`]) count as per-lane branches too, as
/// two console waves of one group may take them different ways.
fn all_lane_blocks_of(st: &Structured, group: bool) -> Option<Vec<bool>> {
let n = st.exits.len();
let mut all = vec![true; n];
for (_, region) in lane_regions(st)? {
for (_, region) in lane_regions_of(st, group)? {
for b in (0..n).filter(|&b| region[b]) {
all[b] = false;
}
@@ -448,6 +460,15 @@ fn all_lane_blocks(st: &Structured) -> Option<Vec<bool>> {
/// 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>)>> {
lane_regions_of(st, false)
}
/// [`lane_regions`]; with `group`, the wave-wide branches too ([`all_lane_blocks_of`]).
/// With console waves meeting on their own ([`with_pair_meetings`]), a branch that closes a
/// loop (the code leads back to it) is in its own region: a lane that left the loop does not
/// run it again. (Not yet for the other programs: their translations stay as they were.)
fn lane_regions_of(st: &Structured, group: bool) -> Option<Vec<(usize, Vec<bool>)>> {
let loops = PAIR_MEETINGS.get();
let n = st.exits.len();
let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
for (b, e) in st.exits.iter().enumerate() {
@@ -488,14 +509,14 @@ fn lane_regions(st: &Structured) -> Option<Vec<(usize, Vec<bool>)>> {
let mut regions = Vec::new();
for (d, e) in st.exits.iter().enumerate() {
let LaneExit::Branch { when, .. } = *e else { continue };
if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) {
if st.wide.contains(&d) && !group || 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];
let mut stack: Vec<usize> = succ[d].clone();
while let Some(b) = stack.pop() {
if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 {
if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 && !(loops && b == d) {
continue;
}
seen[b] = true;
@@ -1054,8 +1075,35 @@ thread_local! {
static LOCAL_WAVES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// See [`with_local_waves_any`].
static LOCAL_ANY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// See [`with_pair_meetings`].
static PAIR_MEETINGS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// LDS dwords a host thread group has (D3D12: 32 KiB).
const HOST_LDS_DWORDS: u32 = 8192;
/// Runs `f` with the two host waves of each console wave meeting on their own
/// ([`Lower::meet`]) in console wave64 programs on 32-lane hosts whose thread group holds
/// several console waves, instead of with the whole group. Every console wave of such a group
/// takes its wave-wide branches ([`crate::structure::structure_wide`]) its own way, as the
/// console does: a group barrier inside one would wait for threads that took the other way.
/// The meeting is an LDS counter per console wave that its 64 lanes count up and wait on
/// (spinning, bounded): the host has no barrier for part of a group. Groups of whole console
/// waves only.
pub(super) fn with_pair_meetings<R>(f: impl FnOnce() -> R) -> R {
let was = PAIR_MEETINGS.replace(true);
let r = f();
PAIR_MEETINGS.set(was);
r
}
/// Polls of a meeting's counter before a host wave goes on without its partner
/// ([`Lower::meet`]): a partner that never comes (lanes cut out of a loop at
/// [`LOOP_LIMIT`]) costs wrong values, not a hung card. A poll is a few hundred
/// nanoseconds; the partner, in the same group on the same unit, is at most a memory
/// fetch behind.
const MEETING_POLLS: u32 = 1 << 12;
/// As [`with_local_waves`], with every other use of a lane mask as a number
/// and every lane read and write taken per host wave too: the program runs
/// as it would on a console of 32-lane waves, lanes numbered 0..31 or
@@ -1448,6 +1496,8 @@ impl<'a> Lower<'a> {
let mut exchange: Option<(u32, bool, Vec<bool>)> = None;
// a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter
let mut halves: Option<u32> = None;
// its host waves meet per console wave (`with_pair_meetings`): the first counter's dword
let mut pairs: Option<u32> = None;
if let StageIo::Cs(cs) = x.native.io {
s.threads = Some(cs.threads);
s.lds_dwords = cs.lds_bytes() / 4;
@@ -1575,6 +1625,10 @@ impl<'a> Lower<'a> {
// console threads go to host waves in the order the waves take them (`wave_base`)
halves = Some(s.lds_dwords);
s.lds_dwords += 1;
if PAIR_MEETINGS.get() && group > 64 && group % 64 == 0 && (split_lds || exchange.is_some()) {
pairs = Some(s.lds_dwords);
s.lds_dwords += group / 64;
}
}
if console_lanes || one_wave && s.lds_dwords > 0 {
s.wave_size = Some(wave);
@@ -1601,7 +1655,9 @@ impl<'a> Lower<'a> {
.iter()
.enumerate()
.any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t)));
let all = all_lane_blocks(x.st);
// (with console waves meeting on their own, a branch one takes wave-wide may be
// taken another way by the others)
let all = all_lane_blocks_of(x.st, pairs.is_some());
(0..p.blocks.len())
.filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier"))
.filter(|&b| {
@@ -1746,6 +1802,8 @@ impl<'a> Lower<'a> {
pair: None,
halves,
wave_base: None,
pairs,
meeting: None,
flat: None,
no_barrier,
fence_only,
@@ -2142,7 +2200,8 @@ impl<'a> Lower<'a> {
let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]);
let tb = bits(self, total);
let c = self.cur;
let (lo, _) = self.exchange_halves(c, tb);
let (lo, _) = self.exchange_halves(c, tb)?;
let c = self.cur;
let lo = back(self, lo);
let cl = self.console_lane();
let k32 = self.s.m.i32(32);
@@ -2154,7 +2213,8 @@ impl<'a> Lower<'a> {
None => {
let rb = bits(self, r);
let c = self.cur;
let (lo, hi) = self.exchange_halves(c, rb);
let (lo, hi) = self.exchange_halves(c, rb)?;
let c = self.cur;
let (lo, hi) = (back(self, lo), back(self, hi));
match op {
Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi),
@@ -2231,8 +2291,8 @@ impl<'a> Lower<'a> {
need(self.cur_ir);
return Err("a wave reduction where not every lane runs");
}
let (lo0, lo1) = self.exchange_halves(self.cur, r_lo);
let (hi0, hi1) = self.exchange_halves(self.cur, r_hi);
let (lo0, lo1) = self.exchange_halves(self.cur, r_lo)?;
let (hi0, hi1) = self.exchange_halves(self.cur, r_hi)?;
let c = self.cur;
let d0 = self
.s
@@ -2354,7 +2414,7 @@ impl<'a> Lower<'a> {
if !halves {
return Ok(mine);
}
let (lo, hi) = self.exchange_halves(c, 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);
@@ -2364,6 +2424,11 @@ impl<'a> Lower<'a> {
fn run(mut self, counted: bool) -> Result<Lowered, Stop> {
let p = self.x.p;
// A host group has 32 KiB of LDS (D3D12): the program's LDS with the meetings' and
// exchanges' dwords past it must fit (`CS_CollectTriangles_Meshlets` uses all 32 KiB).
if self.pairs.is_some() && self.s.lds_dwords > HOST_LDS_DWORDS {
return Err(unsupported(0, "LDS for the console waves' meetings past the host's 32 KiB"));
}
if counted {
// Before anything else, so that wave counts, reads of the first
// lane and stores know only the lanes that run.
@@ -3582,7 +3647,7 @@ impl<'a> Lower<'a> {
need(b.unwrap_or(0));
return Err(DIVERGENT_MASK_EXCHANGE);
}
xy = self.exchange_halves(at, xy.0);
xy = self.exchange_halves(at, xy.0)?;
}
self.ballots.insert(lo, xy);
xy
@@ -4135,6 +4200,20 @@ impl<'a> Lower<'a> {
let ptr = self.s.m.element(e, lds, k);
let zero = self.s.m.i32(0);
self.s.m.store(e, ptr, zero);
if let (Some(first), StageIo::Cs(cs)) = (self.pairs, &self.x.native.io) {
// the console waves' meeting counters too: thread n zeroes counter n (the last one
// past them)
let waves = cs.threads.iter().product::<u32>() / 64;
let i32t = self.s.t.i32;
let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]);
let last = self.s.m.i32(waves - 1);
let past = self.s.m.cmp(e, pred::IUGT, flat, last);
let n = self.s.m.select(e, past, last, flat);
let first = self.s.m.i32(first);
let at = self.s.m.bin(e, Bin::Add, first, n);
let ptr = self.s.m.element(e, lds, at);
self.s.m.store(e, ptr, zero);
}
self.group_sync(e);
let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]);
let first = self.s.m.cmp(e, pred::EQ, lane, zero);
@@ -4183,6 +4262,99 @@ impl<'a> Lower<'a> {
cl
}
/// With console waves meeting on their own: the ballots of the lane masks `inst` reads as
/// numbers, and "some lane" of the SCC it reads, exchanged before its own code is lowered.
/// Their meetings start new blocks ([`Self::meet`]), and an instruction's code goes on in
/// the block it began in; made here, its code finds them made. What fails here fails
/// again, and is told, where the instruction reads it.
fn exchange_first(&mut self, inst: &Inst) {
let needs = NEEDS.with_borrow(|n| n.clone());
let st = self.x.st;
let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v);
let ops: Vec<Operand> = match &inst.fields {
Fields::Sop { src, .. } => src.clone(),
Fields::Valu(v) => v.src.clone(),
_ => Vec::new(),
};
for op in ops {
let Operand::Scalar { code, .. } = op else { continue };
if code == NULL {
continue;
}
for c in [code, code + 1] {
if let Some(v) = inst.read(Reg::S(c)).filter(|&v| is_mask(v)) {
let lo = st.highs.get(&v).copied().unwrap_or(v);
if !self.ballots.contains_key(&lo) {
let _ = self.mask_dword(v);
}
}
}
}
if let Some(v) = inst.read(Reg::Scc)
&& st.scc_some.contains_key(&v)
&& matches!(self.vals.get(&v), None | Some(Val::Missing(_)))
&& let Ok(x) = self.scc_some(v)
{
self.vals.insert(v, Val::Bit(x));
}
NEEDS.with_borrow_mut(|n| *n = needs);
}
/// The two host waves of this thread's console wave meet: what either wrote to LDS
/// before is seen by both after. A group barrier with an LDS fence; with
/// [`with_pair_meetings`], the console wave's own meeting: each of its 64 lanes counts
/// itself in on the console wave's LDS counter and waits (polling, at most
/// [`MEETING_POLLS`] times) until the count reaches the next multiple of 64. The code
/// after it is in a new block ([`Self::cur`]).
fn meet(&mut self) {
let Some(first) = self.pairs else {
let c = self.cur;
self.group_sync(c);
return;
};
let (i32t, void) = (self.s.t.i32, self.s.t.void);
let fence = self.s.m.i32(8);
let head = self.cur;
self.s.op(head, "barrier", Attr::NoDuplicate, void, 80, &[fence]);
if super::group_sync() == 0 {
return;
}
let index = match self.meeting {
Some(v) => v,
None => {
let e = self.s.entry;
let thread = self.console_thread();
let six = self.s.m.i32(6);
let wave = self.s.m.bin(e, Bin::LShr, thread, six);
let base = self.s.m.i32(first);
let v = self.s.m.bin(e, Bin::Add, base, wave);
self.meeting = Some(v);
v
}
};
let lds = self.s.lds();
let ptr = self.s.m.element(head, lds, index);
let (zero, one) = (self.s.m.i32(0), self.s.m.i32(1));
let old = self.s.m.atomic(head, Rmw::Add, ptr, one);
let (low, k64) = (self.s.m.i32(!63u32), self.s.m.i32(64));
let base = self.s.m.bin(head, Bin::And, old, low);
let target = self.s.m.bin(head, Bin::Add, base, k64);
let (wait, done) = (self.s.m.new_block(), self.s.m.new_block());
self.s.m.terminate(head, Term::Br(wait));
let n = self.s.m.phi(wait, i32t);
let now = self.s.m.atomic(wait, Rmw::Add, ptr, zero);
let short = self.s.m.bin(wait, Bin::Sub, now, target);
let early = self.s.m.cmp(wait, pred::SLT, short, zero);
let n1 = self.s.m.bin(wait, Bin::Add, n, one);
let limit = self.s.m.i32(MEETING_POLLS);
let more = self.s.m.cmp(wait, pred::IULT, n1, limit);
let again = self.s.m.bin(wait, Bin::And, early, more);
self.s.m.terminate(wait, Term::CondBr(again, wait, done));
self.s.m.set_phi(n, vec![(zero, head), (n1, wait)]);
self.cur = done;
self.s.op(done, "barrier", Attr::NoDuplicate, void, 80, &[fence]);
}
/// A group barrier with an LDS fence in `block`.
fn group_sync(&mut self, block: usize) {
let mode = self.s.m.i32(meeting_mode());
@@ -4191,15 +4363,18 @@ impl<'a> Lower<'a> {
}
/// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get
/// (lower half's, upper half's). A group with no upper half gets 0 for it.
fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) {
/// (lower half's, upper half's). A group with no upper half gets 0 for it. The halves
/// meet ([`Self::meet`]): the results are in [`Self::cur`], which may be a new block;
/// with console waves meeting on their own, only where the code is being lowered
/// (`at` is [`Self::cur`]).
fn exchange_halves(&mut self, at: usize, mine: V) -> Result<(V, V), Why> {
let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else {
let z = self.s.m.i32(0);
return (mine, z);
return Ok((mine, z));
};
if small {
let z = self.s.m.i32(0);
return (mine, z);
return Ok((mine, z));
}
if self.local {
// each host wave on its own: its half holds `mine`, the other nothing
@@ -4208,7 +4383,11 @@ impl<'a> Lower<'a> {
let upper = self.s.m.cmp(at, pred::IUGE, cl, k32);
let lo = self.s.m.select(at, upper, z, mine);
let hi = self.s.m.select(at, upper, mine, z);
return (lo, hi);
return Ok((lo, hi));
}
if self.pairs.is_some() && at != self.cur {
// (the meeting would split a block lowered already)
return Err("a lane mask exchanged after its block, in a group of several console waves");
}
// the pair of dwords of this thread's console wave: its half's, then both
let pair = self.exchange_pair(slot);
@@ -4219,7 +4398,13 @@ impl<'a> Lower<'a> {
let lds = self.s.lds();
let ptr = self.s.m.element(at, lds, index);
self.s.m.store(at, ptr, mine);
self.group_sync(at);
let at = if self.pairs.is_some() {
self.meet();
self.cur
} else {
self.group_sync(at);
at
};
let one = self.s.m.i32(1);
let k1 = self.s.m.bin(at, Bin::Add, pair, one);
let p0 = self.s.m.element(at, lds, pair);
@@ -4227,8 +4412,12 @@ impl<'a> Lower<'a> {
let lo = self.s.m.load(at, p0);
let hi = self.s.m.load(at, p1);
// the slots are written again only after every thread read them
self.group_sync(at);
(lo, hi)
if self.pairs.is_some() {
self.meet();
} else {
self.group_sync(at);
}
Ok((lo, hi))
}
/// The first of the two exchange dwords of this thread's console wave (made in the entry
@@ -4284,7 +4473,9 @@ impl<'a> Lower<'a> {
return Err(DIVERGENT_MASK_EXCHANGE);
}
let some = self.s.m.cast(at, Cast::ZExt, some, i32t);
let (lo, hi) = self.exchange_halves(at, some);
let (lo, hi) = self.exchange_halves(at, some)?;
// (the halves met: on in a new block)
let at = if self.pairs.is_some() { self.cur } else { at };
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))
@@ -4326,7 +4517,7 @@ impl<'a> Lower<'a> {
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 (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);
@@ -5347,6 +5538,9 @@ impl<'a> Lower<'a> {
// each host wave answers for itself.
MaskData::None => self.uniform_test(inst),
};
if self.pairs.is_some() && self.mask_ok && reads_mask_as_data(self.x.st, inst) {
self.exchange_first(inst);
}
let effect = matches!(inst.fields, Fields::Exp { .. })
|| matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_")
|| name.contains("store")
@@ -5363,9 +5557,7 @@ impl<'a> Lower<'a> {
{
// the two host waves of a console wave meet before each LDS access: what the other
// half wrote is visible, and what it still reads is not overwritten
let mode = self.s.m.i32(meeting_mode());
let void = self.s.t.void;
self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
self.meet();
}
// The structure builder's threads take turns through atomics (a tree
// built from its leaves up): what one wrote before its atomic is
@@ -5447,9 +5639,7 @@ impl<'a> Lower<'a> {
/// The two host waves of a console wave meet (a group barrier with a shared-memory
/// fence): LDS writes before are seen by reads after.
fn lds_meeting(&mut self) {
let mode = self.s.m.i32(meeting_mode());
let void = self.s.t.void;
self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
self.meet();
}
/// Whether `v` is a register no program reads as a number: a descriptor dword without
@@ -8805,11 +8995,11 @@ impl<'a> Lower<'a> {
let ptr = self.s.m.element(self.cur, lds, k);
self.s.m.store(self.cur, ptr, a);
self.end_guarded(at, &[]);
self.meet();
let c2 = self.cur;
self.group_sync(c2);
let ptr = self.s.m.element(c2, lds, k);
let r = self.s.m.load(c2, ptr);
self.group_sync(c2);
self.meet();
return int(self, r);
}
let r = self.read_lane(a, lane);
@@ -8885,13 +9075,15 @@ impl<'a> Lower<'a> {
// has. No half needs to ask the other whether it has
// a lane (an exchange of the constant 1: two group
// barriers), and the lower half's value is the answer.
let (lo, _) = self.exchange_halves(c, mine);
let (lo, _) = self.exchange_halves(c, mine)?;
lo
} else {
let i32t = self.s.t.i32;
let has = self.s.m.cast(c, Cast::ZExt, any, i32t);
let (lo_has, hi_has) = self.exchange_halves(c, has);
let (lo, hi) = self.exchange_halves(c, mine);
let (lo_has, hi_has) = self.exchange_halves(c, has)?;
let c = self.cur;
let (lo, hi) = self.exchange_halves(c, mine)?;
let c = self.cur;
let z = self.s.m.i32(0);
let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z);
let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z);
@@ -12608,6 +12800,9 @@ impl<'a> Lower<'a> {
LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")),
};
let _ = Exit::End;
// (the exit's own code may have moved on to a new block: the halves of a console wave
// meeting for a wave-wide branch, [`Self::meet`]; the edges out leave from there)
self.tail[b] = Some(self.cur);
self.s.m.terminate(self.cur, term);
Ok(())
}
+29 -8
View File
@@ -549,6 +549,12 @@ pub fn emit(
// an LDS read and write in one lane-branch region, so no other form translates
// them on 32-lane hosts and their dispatches were dropped (no volumetric light
// or fog on NVIDIA). Widened, they translate (4 and 7 branches taken wave-wide).
// The underwater one (`CS_TransmissionVolumetricsSubmerged`) likewise (29 branches).
// The triangle clip's heap defragmentation (`vfx_triangleClip:CS_DefragHeap_
// ComputeRelocations`, groups of 128) holds two console waves, which walk the heap
// each its own way: their host waves meet per console wave ([`widen`]). (Its
// `CS_CollectTriangles_Meshlets`, groups of 1024, does not fit that way: its own LDS
// is the host group's whole 32 KiB.)
let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 64)
&& matches!(
c.digest,
@@ -556,7 +562,10 @@ pub fn emit(
| [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c]
| [0x24, 0x12, 0x6c, 0x14, 0xdc, 0x76, 0x19, 0xb0, 0x82, 0xef, 0x57, 0x12, 0x96, 0x03, 0x88, 0x90]
| [0x70, 0x99, 0xa5, 0x7f, 0xde, 0xd1, 0x42, 0x61, 0x3b, 0x44, 0xf4, 0x10, 0x46, 0x3d, 0x6b, 0xe6]
);
| [0xf1, 0xf1, 0x61, 0xe4, 0x7e, 0xef, 0xa3, 0x64, 0x69, 0x18, 0x39, 0xfd, 0x72, 0x06, 0xcc, 0xf6]
)
|| matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() == 128)
&& c.digest == [0x50, 0xcf, 0x28, 0x32, 0x8b, 0x58, 0x05, 0x3d, 0xa8, 0x9a, 0x8d, 0xa0, 0x1a, 0xa1, 0x23, 0xc6];
let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1");
// A single guest wave can iterate an active-lane loop until both host
// halves have finished. The precise latch and convergence conditions
@@ -595,7 +604,7 @@ pub fn emit(
Some(p),
];
if let Some(base) = bases.into_iter().flatten().next() {
let again = widen(c, native, base, why, driver_loop);
let again = widen(c, native, base, why, driver_loop, wide_on);
report("wave-wide branches", &again);
if done(&again) {
return again.map(|(shader, _)| shader);
@@ -657,7 +666,7 @@ pub fn emit(
&& 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(), false);
let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false, false);
match again {
Ok(_) => again,
Err(_) => emit_program(c, native, p, st, io, res),
@@ -696,15 +705,17 @@ pub fn emit(
/// 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.
/// it translates or a branch cannot be widened. Where a thread group is several console
/// waves, those decide differently and a group barrier inside such a branch would wait for
/// threads that never come: the host waves of each console wave meet on their own there
/// ([`lower::with_pair_meetings`]; whole console waves only), when `groups` allows it.
fn widen(
c: &Container,
native: &NativeProgram,
p: &ir::Program,
why: bool,
active_loop_only: bool,
groups: bool,
) -> Result<(HostShader, Option<u32>), ShaderError> {
const NOT: ShaderError = ShaderError::Unsupported {
offset: 0,
@@ -714,6 +725,7 @@ fn widen(
// (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 groups && cs.threads.iter().product::<u32>() % 64 == 0 => {}
crate::native::StageIo::Cs(cs) => {
if why {
eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads);
@@ -722,13 +734,21 @@ fn widen(
}
_ => return Err(NOT),
}
// (several console waves to a group, each two host waves)
let pairs = native.wave64
&& lower::host_max_wave() == 32
&& matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::<u32>() > 64);
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 r = if pairs {
lower::with_pair_meetings(|| emit_program(c, native, p, &st, &io, &res))
} else {
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)
@@ -756,7 +776,8 @@ fn widen(
}
return r;
}
let more: Vec<usize> = lower::branches_around(&st, &needs)
let around = || lower::branches_around(&st, &needs);
let more: Vec<usize> = if pairs { lower::with_pair_meetings(around) } else { around() }
.unwrap_or_default()
.into_iter()
.filter(|b| !wide.contains(b))
@@ -736,3 +736,165 @@ fn the_lanes_past_a_count_of_threads_do_not_run() {
}
}
}
/// The wave size a lowering of `native` at a host of 32-lane waves asks for, and the shader.
fn lowered_with_wave(
native: &NativeProgram,
p: &ir::Program,
wide: &HashSet<usize>,
) -> (Option<u32>, HostShader) {
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.expect("lower");
let shader = 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,
};
(lowered.wave_size, shader)
}
/// Two console waves in a group of 128 threads, each run as two host waves of 32. Lane t goes
/// round a per-lane loop (t >> 4) + 1 times: it writes its sum to LDS and adds that of lane
/// t ^ 63 (in the other host wave of its console wave) with no barrier between, as one console
/// wave may; after the loop every lane adds lane 63's sum (`v_readlane_b32`). The loop's back
/// edge is taken as the console takes it, by each console wave as a whole, and the two console
/// waves go round 4 and 8 times: their host waves meet per console wave
/// ([`lower::with_pair_meetings`]). A group barrier in the loop would wait for the threads of
/// the console wave that left it (`CS_DefragHeap_ComputeRelocations`, groups of 128, whose
/// console waves walk a heap each its own way).
#[test]
fn console_waves_of_one_group_meet_on_their_own_in_loops_of_their_own() {
let words = [
0x3402_0082, // v_lshlrev_b32 v1, 2, v0: this lane's LDS dword
0x3A06_00BF, // v_xor_b32 v3, 63, v0
0x3406_0682, // v_lshlrev_b32 v3, 2, v3: the partner lane's (other half, same wave)
0x4A04_0000, // v_add_nc_u32 v2, s0, v0: the sum starts at s0 + t
0x2C0E_0084, // v_lshrrev_b32 v7, 4, v0
0x4A0E_0E81, // v_add_nc_u32 v7, 1, v7: rounds (t >> 4) + 1
0x7E0A_0280, // v_mov_b32 v5, 0
0xBE8E_047E, // s_mov_b64 s[14:15], exec
0xD834_0000,
0x0000_0201, // loop: ds_write_b32 v1, v2
0xD8D8_0000,
0x0400_0003, // ds_read_b32 v4, v3
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
0x4A04_0902, // v_add_nc_u32 v2, v2, v4
0x4A0A_0A81, // v_add_nc_u32 v5, 1, v5
0x7DA8_0B07, // v_cmpx_gt_u32 exec, v7, v5: the lanes with rounds left
0xBF89_FFF7, // s_cbranch_execnz loop
0xBEFE_040E, // s_mov_b64 exec, s[14:15]
0xD760_0007,
0x0001_7F02, // v_readlane_b32 s7, v2, 63
0x4A04_0407, // v_add_nc_u32 v2, s7, v2
0xE070_1000,
0x8002_0201, // buffer_store_dword v2, v1, s[8:11], 0 offen
];
let mut native = native_of(&words, true, 128);
if let StageIo::Cs(cs) = &mut native.io {
cs.rsrc2 |= 1 << 15; // 512 bytes of LDS
}
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let back = (0..p.blocks.len())
.find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execnz"))
.expect("the back edge");
// per lane, the loop's LDS write and read stand where not every lane runs: still 64 lanes,
// and the lowering names the loop
lower::take_needs();
let (wave, _) = lower::with_pair_meetings(|| lowered_with_wave(&native, &p, &HashSet::new()));
assert_eq!(wave, Some(64));
let needs = lower::take_needs();
let st = structure::structure(&p).expect("structure");
assert_eq!(lower::with_pair_meetings(|| lower::branches_around(&st, &needs)), Some(vec![back]));
// the back edge taken per console wave: waves of 32, meeting per console wave
let wide = HashSet::from([back]);
let (wave, shader) = lower::with_pair_meetings(|| lowered_with_wave(&native, &p, &wide));
assert_eq!(wave, Some(32));
assert!(lower::take_needs().is_empty());
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: each wave's lanes in step, writes before reads
let console = |s0: u32| {
let mut out = [0u32; 128];
let mut lds = [0u32; 128];
for w in 0..2u32 {
let lanes = 64 * w..64 * w + 64;
let mut sum: Vec<u32> = lanes.clone().map(|t| s0.wrapping_add(t)).collect();
for round in 0..8 {
let on: Vec<u32> = lanes.clone().filter(|t| round < (t >> 4) + 1).collect();
if on.is_empty() {
break;
}
for &t in &on {
lds[t as usize] = sum[(t - 64 * w) as usize];
}
for &t in &on {
let k = (t - 64 * w) as usize;
sum[k] = sum[k].wrapping_add(lds[(t ^ 63) as usize]);
}
}
let last = sum[63];
for t in lanes {
out[t as usize] = sum[(t - 64 * w) as usize].wrapping_add(last);
}
}
out
};
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: {e}; not run");
return;
}
};
for s0 in [0u32, 1000, 0xFFFF_FF00] {
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] = s0;
}
}
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(0, Root::Constants(ud))],
views: &[View::RawUav(128)],
samplers: &[],
groups: [1, 1, 1],
},
)
.unwrap_or_else(|e| panic!("dispatch failed: {e}"));
let want = console(s0);
assert_eq!(&out[0][..128], &want[..], "s0 = {s0:#x}");
}
eprintln!("ran on the hardware device: both console waves' loops, as the console runs them");
}