From b3df45b18dc40afeb33682c37c047467e5fb42b9 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 19:17:43 +0400 Subject: [PATCH 1/5] fix(shader): run while-shaped divergent loops in lockstep in halves A first-lane read in a loop the 32-lane halves of a console wave do not run together is refused (FIRST_ACROSS): the halves cannot pass the console's first lane between them there. Halves make a divergent loop run together, in lockstep, only where its exit branch is at its latch (a do-while, predication shape 4): the latch branches on group_any_true of the lanes staying, so every host wave of the group runs every pass. The console compiler also lays loops out as while loops: the entry jumps to the test, the test branches back into the body while lanes stay, and the body's last block falls into the test, so the exit branch is at a block other than the latch. GTA VI's 23d507cbb6a22e86 and b0095eb50222e808 choose a table entry in such a loop, reading the entry's offset from the first lane in each pass; refused since #522, their dispatches have been dropped. Predication now takes a single-exit while loop too (shape 5): the exit branch becomes the group-uniform one (FlatExit::LockstepExit), staying while any lane of the group stays, its stay edge carrying the lanes that stay into the rest of the body, and the latch jumps back to the header as before. The same checks as shape 4 hold: one back edge, no nested cycle, no side entry, the exit entered only from the exit branch, and no scalar the body writes read outside it. Of the title's 2,734 compute programs, six translate again (the two above among them) and none is newly refused. 65 others translate differently, with fewer group barriers in all (2,628). Tests: a first-lane read in a while loop gives the console's lanes on hardware in groups of 64 and 128, with lanes leaving the loop one by one (EXEC narrowed) and with a test every lane holds alike; it translates in groups of 64, 128 and 256. Co-Authored-By: Claude Opus 5.5 --- .../victory-shader/src/emit/halves_tests.rs | 136 ++++++++++ .../src/emit/lower/predicate.rs | 243 ++++++++++++++++++ 2 files changed, 379 insertions(+) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index dc0c9fda6..b5ab13075 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -4085,3 +4085,139 @@ fn a_first_lane_read_only_active_lanes_see_matches_the_console_on_every_gpu() { } assert!(failed.is_empty(), "{}", failed.join("\n")); } + +/// A `while` loop as the console compiler lays one out: the entry jumps to +/// the test, which branches back to the body while lanes stay; the body +/// falls into the test. The body reads the first lane's thread id +/// (`v_readfirstlane_b32 s6, v0`) into an accumulator `v2`, and counts its +/// passes in `v1`. `narrow`: a lane stays while `v1 < (tid & 7)`, and the +/// test drops the lanes done from EXEC (`s_and_b64 exec, exec, vcc; +/// s_cbranch_execnz`). Else every lane stays while `v1 < 7`, a test the +/// same in every lane, and EXEC stays (`s_and_b64 vcc, exec, vcc; +/// s_cbranch_vccnz`, as GTA VI's loops test). Every lane stores `v2`. +fn while_loop_first_lane(narrow: bool) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + if narrow { + 0x360A_0087 // v_and_b32 v5, 7, v0 + } else { + 0x7E0A_0287 // v_mov_b32 v5, 7 + }, + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0xBF82_0003, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + ]); + if narrow { + w.extend([ + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFFA, // s_cbranch_execnz (the body) + ]); + } else { + w.extend([ + 0x87EA_6A7E, // s_and_b64 vcc, exec, vcc + 0xBF87_FFFA, // s_cbranch_vccnz (the body) + ]); + } + w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +/// What every lane of [`while_loop_first_lane`] stores on the console: the +/// first lane still in the loop in each pass is the console wave's thread +/// `64 * wave + pass + 1` (narrow), or its first, `64 * wave`, in all 7 +/// passes. +fn console_while_loop_first_lane(narrow: bool, t: u32) -> u32 { + let base = t & !63; + if narrow { + let n = t & 7; + n * base + n * (n + 1) / 2 + } else { + 7 * base + } +} + +#[test] +fn the_while_loop_programs_are_what_their_comments_say() { + for narrow in [false, true] { + let words = while_loop_first_lane(narrow); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let all = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + let tail: &[&str] = if narrow { + &["s_and_b64 exec, exec, vcc", "s_cbranch_execnz"] + } else { + &["s_and_b64 vcc, exec, vcc", "s_cbranch_vccnz"] + }; + let bound = if narrow { + "v_and_b32 v5, 7, v0" + } else { + "v_mov_b32 v5, 7" + }; + for want in [ + bound, + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v1, 1, v1", + "v_cmp_lt_u32 vcc, v1, v5", + "s_mov_b64 exec, s[36:37]", + ] + .iter() + .chain(tail) + { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } + } +} + +/// A first-lane read in a `while` loop (its exit test before the latch's +/// work, as GTA VI's `23d507cbb6a22e86` and `b0095eb50222e808` have) runs in +/// halves with the loop in lockstep: the group stays while any lane stays, +/// so the halves meet in every pass and pass the console wave's first lane +/// between them. Before, the read was refused there. +#[test] +fn a_first_lane_read_in_a_while_loop_translates_in_halves() { + for narrow in [false, true] { + for threads in [64, 128, 256] { + let words = while_loop_first_lane(narrow); + let l = lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("narrow={narrow} {threads} threads: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet in the loop"); + } + } +} + +/// The read in a `while` loop gives the console's lanes on every GPU. +#[cfg(windows)] +#[test] +fn a_first_lane_read_in_a_while_loop_matches_the_console_on_every_gpu() { + let mut failed = Vec::new(); + for narrow in [false, true] { + for threads in [64, 128] { + let words = while_loop_first_lane(narrow); + let want: Vec = (0..threads) + .map(|t| console_while_loop_first_lane(narrow, t)) + .collect(); + failed.extend( + differences(&words, threads, 1, &want) + .into_iter() + .map(|m| format!("narrow={narrow} {threads} threads: {m}")), + ); + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} diff --git a/crates/victory-shader/src/emit/lower/predicate.rs b/crates/victory-shader/src/emit/lower/predicate.rs index 76f7c01b7..435f0c46d 100644 --- a/crates/victory-shader/src/emit/lower/predicate.rs +++ b/crates/victory-shader/src/emit/lower/predicate.rs @@ -62,6 +62,16 @@ pub(super) enum FlatExit { exit: usize, stay_when_true: bool, }, + /// The exit branch of a while-shaped lockstep-predicated loop, at a + /// block other than its latch (which jumps back to `header`): branching + /// to `stay` on `group_any_true(next_active) && iter < LOOP_LIMIT`, else + /// to `exit`. + LockstepExit { + header: usize, + stay: usize, + exit: usize, + stay_when_true: bool, + }, } /// Predication plan computed before `split_wave_barriers` and `Lower::run`. @@ -313,6 +323,42 @@ impl PredicatePlan { } } + if !changed && host_wave32 { + // Shape 5: single-exit while-shaped divergent loop (the exit + // branch at a block other than the latch, which jumps back to + // the header) promoted to group-uniform lockstep execution. + for &h in &order { + if plan.dead_blocks.contains(&h) + || plan.lockstep_headers.contains_key(&h) + || plan.in_diamond.contains(&h) + { + continue; + } + if let Some(lp) = + match_lockstep_while_loop(p, &eff_exits, h, &rpo, &needs, &plan) + { + plan.exits.insert( + lp.exiting, + FlatExit::LockstepExit { + header: h, + stay: lp.stay, + exit: lp.exit, + stay_when_true: lp.stay_when_true, + }, + ); + plan.early_conts.insert(lp.stay, lp.exiting); + plan.lockstep_headers.insert(h, lp.latch); + plan.lockstep_exits.insert(lp.exit, h); + plan.uniform_branches.insert(lp.exiting); + plan.in_lockstep_loop.extend(lp.body); + plan.step = + barriers::in_step_with(p, st, &eff_exits, &plan.uniform_branches); + changed = true; + break; + } + } + } + if !changed { break; } @@ -884,6 +930,165 @@ fn match_lockstep_loop( Some((latch, exit, stay_when_true, body)) } +/// A while-shaped loop [`match_lockstep_while_loop`] found. +struct WhileLoop { + /// The block jumping back to the header, unconditionally. + latch: usize, + /// The block whose branch leaves the loop. + exiting: usize, + /// Its successor inside the loop, and the one outside. + stay: usize, + exit: usize, + /// Whether the branch's condition holds where it stays. + stay_when_true: bool, + body: Set, +} + +/// A single-exit loop whose one exit branch is at a block other than its +/// latch, the latch jumping back to the header `h` (a `while` loop as the +/// console compiler lays one out, the test before the latch's work): it +/// runs in lockstep like [`match_lockstep_loop`]'s, the exit branch taken +/// by the whole group while any lane stays (`FlatExit::LockstepExit`). +fn match_lockstep_while_loop( + p: &Program, + exits: &[LaneExit], + h: usize, + rpo: &[usize], + needs: &[bool], + plan: &PredicatePlan, +) -> Option { + let preds = eff_preds(exits, &plan.dead_blocks, h); + let (back, out): (Vec, Vec) = preds.into_iter().partition(|&q| rpo[q] >= rpo[h]); + let [latch] = back[..] else { + return None; + }; + if out.is_empty() + || exits[latch] != LaneExit::Jump(h) + || plan.exits.contains_key(&latch) + || plan.in_diamond.contains(&latch) + || plan.in_lockstep_loop.contains(&h) + || plan.in_lockstep_loop.contains(&latch) + || !out.iter().all(|&q| plan.step[q]) + { + return None; + } + // The natural loop body, by reverse DFS from `latch` stopping at `h`. + let mut body = Set::default(); + body.insert(h); + let mut stack = vec![latch]; + while let Some(b) = stack.pop() { + if !body.insert(b) { + continue; + } + if body.len() > MAX_LOCKSTEP_LOOP_BLOCKS + || plan.in_diamond.contains(&b) + || plan.in_lockstep_loop.contains(&b) + || plan.dead_blocks.contains(&b) + { + return None; + } + for q in eff_preds(exits, &plan.dead_blocks, b) { + if !body.contains(&q) { + if rpo[q] < rpo[h] { + return None; // side entry into loop body + } + stack.push(q); + } + } + } + // One edge leaves the body, from a branch whose other side stays; no + // cycle inside the body but the latch's. + let mut leaving = None; + for &b in &body { + let succs: Vec = match exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { + taken, not_taken, .. + } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => return None, + }; + for t in succs { + if !body.contains(&t) { + if leaving.replace((b, t)).is_some() { + return None; // a second exit + } + } else if rpo[t] <= rpo[b] && !(b == latch && t == h) { + return None; // nested cycle inside loop + } + } + } + let (exiting, exit) = leaving?; + let LaneExit::Branch { + taken, not_taken, .. + } = exits[exiting] + else { + return None; + }; + let (stay, stay_when_true) = if not_taken == exit && body.contains(&taken) { + (taken, true) + } else if taken == exit && body.contains(¬_taken) { + (not_taken, false) + } else { + return None; + }; + if exiting == latch + || plan.exits.contains_key(&exiting) + || plan.early_conts.contains_key(&stay) + || eff_preds(exits, &plan.dead_blocks, stay) != [exiting] + || eff_preds(exits, &plan.dead_blocks, exit) != [exiting] + || rpo[exit] <= rpo[h] + || plan.lockstep_exits.contains_key(&exit) + || plan.diamond_joins.contains_key(&exit) + || !body.iter().any(|&b| needs[b] && !plan.step[b]) + { + return None; + } + // As for `match_lockstep_loop`: no scalar the body writes (but EXEC and + // VCC) is read outside it, since lanes spinning inactive in lockstep + // still run the body's scalar instructions. + let is_mask_reg = + |r: Reg| matches!(r, Reg::S(k) if [EXEC, EXEC + 1, VCC, VCC + 1].contains(&k)); + let mut loop_scalars: Set = Set::default(); + for &b in &body { + for phi in &p.blocks[b].phis { + if matches!(phi.reg, Reg::S(_) | Reg::Scc) && !is_mask_reg(phi.reg) { + loop_scalars.insert(phi.value); + } + } + for inst in &p.blocks[b].insts { + for &(r, v) in &inst.writes { + if matches!(r, Reg::S(_) | Reg::Scc) && !is_mask_reg(r) { + loop_scalars.insert(v); + } + } + } + } + for (b, block) in p.blocks.iter().enumerate() { + if body.contains(&b) || plan.dead_blocks.contains(&b) { + continue; + } + if block + .phis + .iter() + .any(|phi| phi.args.iter().any(|v| loop_scalars.contains(v))) + || block + .insts + .iter() + .any(|i| i.reads.iter().any(|(_, v)| loop_scalars.contains(v))) + { + return None; + } + } + Some(WhileLoop { + latch, + exiting, + stay, + exit, + stay_when_true, + body, + }) +} + fn post_dominators(exits: &[LaneExit]) -> Vec> { let n = exits.len(); let words = n.div_ceil(64); @@ -1423,6 +1628,44 @@ impl Lower<'_> { exit_blk, ))) } + FlatExit::LockstepExit { + header, + stay, + exit, + stay_when_true, + } => { + let LaneExit::Branch { when, .. } = self.x.st.exits[b] else { + return Ok(None); + }; + let cond = self + .boolean(when, cur) + .map_err(|w| unsupported(offset, w))?; + let stays = if stay_when_true { + cond + } else { + let t = self.s.m.bool(true); + self.s.m.bin(cur, Bin::Xor, cond, t) + }; + let next_act = and_base(self, stays); + self.pred_edge_active.insert((b, stay), next_act); + let any = self + .group_any_true(next_act, cur) + .map_err(|w| unsupported(offset, w))?; + let ok = self.count_iteration(header, pred::IULT); + let go = self.s.m.bin(cur, Bin::And, any, ok); + let exit_blk = self.edge(b, exit); + let from = if Some(exit_blk) == self.block[exit] { + cur + } else { + exit_blk + }; + self.enter_loop(b, exit, from); + Ok(Some(Term::CondBr( + go, + self.block[stay].expect("reachable"), + exit_blk, + ))) + } FlatExit::EarlyOut { cont } => { self.record_branch_edge_actives(b, cur, offset, base_act)?; self.enter_loop(b, cont, cur); From 36795fe898ede52d254b26c8dad37e7d5d33fd3e Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 21:51:16 +0400 Subject: [PATCH 2/5] test(shader): a store in a while loop run in lockstep is made by the lanes still in it A while loop run in lockstep keeps every lane of the group in its body until no lane of any wave stays: a lane that left runs the body inactive. while_loop_with_a_store has a store in that body, each pass a lane makes storing its count of passes at a dword of its own, lanes leaving after 0 to 7 passes. On hardware, in groups of 64 and 128, each lane's dwords up to its count hold their index and the rest stay 0: a lane that left stores no more. Co-Authored-By: Claude Fable 5.2 --- .../victory-shader/src/emit/halves_tests.rs | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index b5ab13075..4d320afbc 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -4221,3 +4221,98 @@ fn a_first_lane_read_in_a_while_loop_matches_the_console_on_every_gpu() { } assert!(failed.is_empty(), "{}", failed.join("\n")); } + +/// [`while_loop_first_lane`] (the form lanes leave one by one: a lane stays +/// while `v1 < (tid & 7)`) with a store in its body: each pass a lane makes +/// stores its count of passes `v1` at dword `v1` of its own eight. A lane +/// that has left the loop stores no more. +fn while_loop_with_a_store() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x360A_0087, // v_and_b32 v5, 7, v0 + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0xBF82_0007, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x3422_0282, // v_lshlrev_b32 v17, 2, v1 + 0x4A22_2310, // v_add_nc_u32 v17, v16, v17 + 0xE070_1000, + 0x800A_0111, // buffer_store_dword v1, v17, s[40:43], 0 offen + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFF6, // s_cbranch_execnz (the body) + 0xBEFE_0424, // s_mov_b64 exec, s[36:37] + ]); + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_while_loop_with_a_store_is_what_its_comments_say() { + let words = while_loop_with_a_store(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let text: Vec = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect(); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", + "v_and_b32 v5, 7, v0", + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v1, 1, v1", + "v_lshlrev_b32 v17, 2, v1", + "v_add_nc_u32 v17, v16, v17", + "buffer_store_dword v1, v17, s[40:43], 0 offen", + "v_cmp_lt_u32 vcc, v1, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execnz", + "s_mov_b64 exec, s[36:37]", + ]; + // The prologue's five words are four instructions. + for (n, want) in want.iter().enumerate() { + let got = &text[PROLOGUE.len() - 1 + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } +} + +/// A store in a `while` loop run in lockstep is made by the lanes still in +/// the loop only: a lane that left keeps running the body with the group, +/// inactive, and stores nothing. Each lane's dwords 1 to `tid & 7` hold +/// their own index, the rest stay 0; dword 0 is the accumulator of +/// [`console_while_loop_first_lane`]. +#[cfg(windows)] +#[test] +fn a_store_in_a_while_loop_is_made_by_the_lanes_still_in_it_on_every_gpu() { + let words = while_loop_with_a_store(); + let mut failed = Vec::new(); + for threads in [64, 128] { + let want: Vec = (0..threads) + .flat_map(|t| { + let n = t & 7; + let mut lane = [0; 8]; + lane[0] = console_while_loop_first_lane(true, t); + for p in 1..=n { + lane[p as usize] = p; + } + lane + }) + .collect(); + failed.extend( + differences(&words, threads, 8, &want) + .into_iter() + .map(|m| format!("{threads} threads: {m}")), + ); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} From 9aab56e7e119d3362e74588b94679484b27fdabc Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Sat, 28 Nov 2026 02:42:05 +0400 Subject: [PATCH 3/5] test(shader): lockstep while loops in groups of rows, a wave-prefix sum and LDS written per pass The while loops run in lockstep were tested in groups of one row (64, 128, 256 threads). GTA VI has them in groups of rows (8x8, 8x6, 16x16), where the 32-lane host waves take their thread ids from the thread ticket, and in two more shapes: a sum over the group's earlier console waves carried from pass to pass through the first lane (its acceleration-structure builder's prefix sums), and LDS written in each pass by a group of one console wave. Three hardware tests, each against the console's result computed in the test: - a while loop whose lanes leave at passes 0 to 7, differing by group, in groups of 8x8, 8x6 and 16x16, in dispatches of 1, 5 and 37 groups: the accumulator of first lanes, the stores of each pass, each lane's count of passes, and each thread id held by one host lane (its id added atomically to its own dword). Left by no lane, the loop ends at the limit of passes (16,383) in every lane of every group; - the sum over earlier waves, in groups of 128, 256 and 512; - LDS written per pass in a group of 64 and read from the other half after the loop (translated with LDS synced for narrow waves; refused without). On an M5 Pro (D3DMetal) no lane differs in any of them. 2,048 groups of 8x8 take 22 to 25 ms, and 56 to 62 ms with every group at the limit of passes, so the test prints its times and does not check them. Co-Authored-By: Claude Fable 5.2 --- .../victory-shader/src/emit/halves_tests.rs | 603 ++++++++++++++++++ 1 file changed, 603 insertions(+) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 4d320afbc..d7a08f10b 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -4316,3 +4316,606 @@ fn a_store_in_a_while_loop_is_made_by_the_lanes_still_in_it_on_every_gpu() { } assert!(failed.is_empty(), "{}", failed.join("\n")); } + +/// [`native`] for a group of two dimensions: thread ids x and y in `v0` and +/// `v1`, the group's x in `s1` (after the one user-data SGPR). +fn native_2d(words: &[u32], threads: [u32; 2]) -> NativeProgram { + let mut n = native(words, true, threads[0] * threads[1], 0); + n.io = StageIo::Cs(ComputeIo { + // One user-data SGPR, the group's x (bit 7), thread ids x and y + // (bits 11-12: 1). + rsrc2: 1 << 1 | 1 << 7 | 1 << 11, + threads: [threads[0], threads[1], 1], + }); + n +} + +/// [`while_loop_with_a_store`] in a group `width` threads wide (8 or 16), of +/// several rows, in a dispatch of several groups: the thread's flat id +/// `width y + x` is in `v0`, and a lane stays while +/// `v1 < ((flat + group) & 7)`, so the lanes leave at passes that differ +/// from group to group. Each lane has 16 dwords at +/// `(256 group + flat) * 64`: the accumulator of first lanes, its passes +/// at dwords 1 to 7, `flat + 1` added (atomically, so a thread id two +/// host lanes hold shows) at dword 8, and its count of passes at dword 9. `forever`: no lane ever leaves (the +/// loop then runs to the translation's limit of passes), and no pass stores. +fn while_loop_in_rows(forever: bool, width: u32) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3406_0280 | width.trailing_zeros(), // v_lshlrev_b32 v3, 3 or 4, v1 + 0x4A00_0700, // v_add_nc_u32 v0, v0, v3 + 0x3420_0086, // v_lshlrev_b32 v16, 6, v0 + 0x7E08_0201, // v_mov_b32 v4, s1 + 0x3408_088E, // v_lshlrev_b32 v4, 14, v4 + 0x4A20_0910, // v_add_nc_u32 v16, v16, v4 + 0x4A0C_0001, // v_add_nc_u32 v6, s1, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x7E04_0280, // v_mov_b32 v2, 0 + if forever { + 0x7E0A_02C1 // v_mov_b32 v5, -1 + } else { + 0x360A_0C87 // v_and_b32 v5, 7, v6 + }, + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + ]); + if forever { + w.extend([ + 0xBF82_0003, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFFA, // s_cbranch_execnz (the body) + ]); + } else { + w.extend([ + 0xBF82_0007, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A02_0281, // v_add_nc_u32 v1, 1, v1 + 0x3422_0282, // v_lshlrev_b32 v17, 2, v1 + 0x4A22_2310, // v_add_nc_u32 v17, v16, v17 + 0xE070_1000, + 0x800A_0111, // buffer_store_dword v1, v17, s[40:43], 0 offen + 0x7D82_0B01, // v_cmp_lt_u32 vcc, v1, v5 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFF6, // s_cbranch_execnz (the body) + ]); + } + w.extend([ + 0xBEFE_0424, // s_mov_b64 exec, s[36:37] + 0x4A0E_0081, // v_add_nc_u32 v7, 1, v0 + 0xE0C8_1020, + 0x800A_0710, // buffer_atomic_add v7, v16, s[40:43], 0 offen offset:32 + ]); + w.extend(store(1, 36)); + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_while_loop_in_rows_is_what_its_comments_say() { + for (forever, width) in [(false, 8), (true, 8), (false, 16)] { + let words = while_loop_in_rows(forever, width); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let text: Vec = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect(); + let bound = if forever { + "v_mov_b32 v5, -1" + } else { + "v_and_b32 v5, 7, v6" + }; + let rows = if width == 8 { + "v_lshlrev_b32 v3, 3, v1" + } else { + "v_lshlrev_b32 v3, 4, v1" + }; + let mut want = vec![ + rows, + "v_add_nc_u32 v0, v0, v3", + "v_lshlrev_b32 v16, 6, v0", + "v_mov_b32 v4, s1", + "v_lshlrev_b32 v4, 14, v4", + "v_add_nc_u32 v16, v16, v4", + "v_add_nc_u32 v6, s1, v0", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", + bound, + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v1, 1, v1", + ]; + if !forever { + want.extend([ + "v_lshlrev_b32 v17, 2, v1", + "v_add_nc_u32 v17, v16, v17", + "buffer_store_dword v1, v17, s[40:43], 0 offen", + ]); + } + want.extend([ + "v_cmp_lt_u32 vcc, v1, v5", + "s_and_b64 exec, exec, vcc", + "s_cbranch_execnz", + "s_mov_b64 exec, s[36:37]", + "v_add_nc_u32 v7, 1, v0", + "buffer_atomic_add v7, v16, s[40:43], 0 offen offset:32", + "buffer_store_dword v1, v16, s[40:43], 0 offen offset:36", + ]); + // The prologue's five words are four instructions. + for (n, want) in want.iter().enumerate() { + let got = &text[PROLOGUE.len() - 1 + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } + } +} + +/// What the console stores for [`while_loop_in_rows`]'s lanes of group +/// `group`, `lanes` threads in console waves of 64: 16 dwords each. +#[cfg(windows)] +fn console_while_loop_in_rows(lanes: u32, group: u32) -> Vec<[u32; 16]> { + let stays = |t: u32| (t + group) & 7; + (0..lanes) + .map(|t| { + let mut lane = [0; 16]; + let wave = (t & !63)..lanes.min((t & !63) + 64); + for pass in 0..stays(t) { + // The first lane of its wave still in the loop in this pass. + lane[0] += wave.clone().find(|&f| stays(f) > pass).expect("this one"); + lane[pass as usize + 1] = pass + 1; + } + lane[8] = t + 1; + lane[9] = stays(t); + lane + }) + .collect() +} + +/// A `while` loop in lockstep translates in halves in groups of rows. +#[test] +fn a_while_loop_in_rows_translates_in_halves() { + for threads in [[8, 8], [8, 6], [16, 16]] { + for forever in [false, true] { + let n = native_2d(&while_loop_in_rows(forever, threads[0]), threads); + let l = + lowered(&n, true).unwrap_or_else(|e| panic!("{threads:?} forever={forever}: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet in the loop"); + } + } +} + +/// A `while` loop in lockstep in groups of rows (8x8: two full host waves; +/// 8x6: 48 threads, the console wave's upper half 16 lanes; 16x16: four +/// console waves, as GTA VI's programs with such a loop have), several groups +/// to a dispatch, lanes leaving at different passes: every lane stores what +/// the console's does, its count of passes too, and each thread id is held +/// by one host lane. Left by no lane, the loop ends at the translation's +/// limit of passes in every lane of every group. +/// +/// A group that stayed in the loop after its last lane left would store +/// nothing more, so that shows only in time. Time does not tell here: on an +/// M5 Pro 2,048 groups of 8x8 took 22 to 25 ms, and 56 to 62 ms with every +/// group at the limit (16,383 passes, two exchanges each), so the times are +/// printed, not checked. +#[cfg(windows)] +#[test] +fn a_while_loop_in_rows_matches_the_console_and_leaves_on_every_gpu() { + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + let hosts = Host::each_hardware(); + if hosts.is_empty() { + eprintln!("no SM 6.6 hardware device; skipped"); + return; + } + let mut failed = Vec::new(); + for (adapter, host) in &hosts { + for threads in [[8u32, 8], [8, 6], [16, 16]] { + let lanes = threads[0] * threads[1]; + for narrow_waves in [false, true] { + let label = format!("{adapter} {threads:?} narrow_waves={narrow_waves}"); + let make = |forever: bool| { + let n = native_2d(&while_loop_in_rows(forever, threads[0]), threads); + let s = shader(lower_halves(&n, true, narrow_waves, false).expect("halves")); + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut s.dxil.clone()) + .expect("DXIL validation failed"); + } + let Ok((root, pso)) = host.compute_pipeline(&s) else { + panic!("{label}: no pipeline"); + }; + (s, root, pso) + }; + let leaves = make(false); + let stays = make(true); + let run = |forever: bool, groups: u32| { + let (s, root, pso) = if forever { &stays } else { &leaves }; + let ud = vec![0u32; s.user_data_dwords().max(1) as usize]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(groups * 256 * 16), + ]; + let start = std::time::Instant::now(); + let out = host + .dispatch( + root, + pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [groups, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + (out, start.elapsed()) + }; + for groups in [1u32, 5, 37] { + let (out, _) = run(false, groups); + let mut wrong = 0; + for g in 0..groups { + let want = console_while_loop_in_rows(lanes, g); + for (t, want) in want.iter().enumerate() { + let at = (g as usize * 256 + t) * 16; + let got = &out[0][at..at + 16]; + if got != want { + wrong += 1; + failed.push(format!( + "{label}: {groups} groups: group {g} lane {t}: {got:?}, the console {want:?}" + )); + } + } + // Nothing stored where the group has no thread. + let past = (g as usize * 256 + lanes as usize) * 16; + let end = (g as usize + 1) * 256 * 16; + if out[0][past..end].iter().any(|&d| d != 0) { + wrong += 1; + failed.push(format!( + "{label}: {groups} groups: group {g}: stores past its {lanes} threads" + )); + } + } + eprintln!("{label}: {groups} groups: {wrong} lanes differ from the console"); + } + // Many groups, the best of three, and the loop no lane leaves + // (every group at the limit of passes). + let groups = 512; + let best = (0..3).map(|_| run(false, groups).1).min().expect("three"); + let (out, limit) = run(true, groups); + // Every lane of every group ran to the limit of passes. + let passes: std::collections::BTreeSet = (0..groups as usize * 256) + .filter(|t| t % 256 < lanes as usize) + .map(|t| out[0][t * 16 + 9]) + .collect(); + eprintln!("{label}: passes at the limit: {passes:?}"); + if passes != [super::DEFAULT_LOOP_LIMIT - 1].into() { + failed.push(format!("{label}: passes at the limit: {passes:?}")); + } + eprintln!( + "{label}: {groups} groups: {best:?}; with every group at the limit of passes {limit:?}" + ); + } + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// A sum over the group's earlier console waves, in a `while` loop whose +/// exit test is in its header and whose latch reads the first lane (the +/// shape of the loops in GTA VI's acceleration-structure builder): every +/// lane writes its wave's number plus 5 to the wave's LDS dword; after a +/// barrier, the lanes of wave `w > 0` add dwords 0 to `w - 1` up, carrying +/// the sum from pass to pass through the first lane (`s17`), and leave when +/// the pass count `s18` is their wave. Each lane stores its sum. +fn sum_of_earlier_waves() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x2C0E_0086, // v_lshrrev_b32 v7, 6, v0 + 0x3410_0E82, // v_lshlrev_b32 v8, 2, v7 + 0x4A12_0E85, // v_add_nc_u32 v9, 5, v7 + 0xD834_0000, + 0x0000_0908, // ds_write_b32 v8, v9 + S_WAITCNT_LGKM, + 0xBF8A_0000, // s_barrier + 0x7E10_0280, // v_mov_b32 v8, 0 + 0xBE80_047E, // s_mov_b64 s[0:1], exec + 0x7DAA_0E80, // v_cmpx_ne_u32 exec, 0, v7 + 0xBF88_0012, // s_cbranch_execz (the end) + 0xBE82_047E, // s_mov_b64 s[2:3], exec + 0xBE86_047E, // s_mov_b64 s[6:7], exec + 0xBE92_0380, // s_mov_b32 s18, 0 + 0xBE91_0380, // s_mov_b32 s17, 0 + 0xBF82_0002, // s_branch (the header) + 0x87FE_0610, // s_and_b64 exec, s[16:17], s[6:7] + 0x7E22_0508, // v_readfirstlane_b32 s17, v8 + 0x8F10_8212, // s_lshl_b32 s16, s18, 2 + 0x8112_8112, // s_add_i32 s18, s18, 1 + 0x7E10_0210, // v_mov_b32 v8, s16 + 0xD8D8_0000, + 0x0800_0008, // ds_read_b32 v8, v8 + S_WAITCNT_LGKM, + 0x4A10_1011, // v_add_nc_u32 v8, s17, v8 + 0xBE90_047E, // s_mov_b64 s[16:17], exec + 0x7DA4_0E12, // v_cmpx_eq_u32 exec, s18, v7 + 0x8A86_7E06, // s_andn2_b64 s[6:7], s[6:7], exec + 0xBF85_FFF3, // s_cbranch_scc1 (the latch) + 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + ]); + w.extend(store(8, 0)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_sum_of_earlier_waves_is_what_its_comments_say() { + let words = sum_of_earlier_waves(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let text: Vec = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect(); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_lshrrev_b32 v7, 6, v0", + "v_lshlrev_b32 v8, 2, v7", + "v_add_nc_u32 v9, 5, v7", + "ds_write_b32 v8, v9", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "v_mov_b32 v8, 0", + "s_mov_b64 s[0:1], exec", + "v_cmpx_ne_u32 exec, 0, v7", + "s_cbranch_execz", + "s_mov_b64 s[2:3], exec", + "s_mov_b64 s[6:7], exec", + "s_mov_b32 s18, 0", + "s_mov_b32 s17, 0", + "s_branch", + "s_and_b64 exec, s[16:17], s[6:7]", + "v_readfirstlane_b32 s17, v8", + "s_lshl_b32 s16, s18, 2", + "s_add_i32 s18, s18, 1", + "v_mov_b32 v8, s16", + "ds_read_b32 v8, v8", + "s_waitcnt lgkmcnt(0)", + "v_add_nc_u32 v8, s17, v8", + "s_mov_b64 s[16:17], exec", + "v_cmpx_eq_u32 exec, s18, v7", + "s_andn2_b64 s[6:7], s[6:7], exec", + "s_cbranch_scc1", + "s_mov_b64 exec, s[0:1]", + ]; + // The prologue's five words are four instructions. + for (n, want) in want.iter().enumerate() { + let got = &text[PROLOGUE.len() - 1 + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } + // The three branches go to the end, the header and the latch. + let at = |name: &str| { + let i = gfx10::decode(&code).expect("decodes"); + i.iter() + .find(|i| i.text(true).starts_with(name)) + .map(|i| i.text(true)) + .expect("there") + }; + let offset = |n: usize| { + let i = gfx10::decode(&code).expect("decodes"); + i[PROLOGUE.len() - 1 + n].offset + }; + assert!( + at("s_cbranch_execz").contains(&format!("{:04X}", offset(28))), + "{}", + at("s_cbranch_execz") + ); + assert!( + at("s_branch").contains(&format!("{:04X}", offset(18))), + "{}", + at("s_branch") + ); + assert!( + at("s_cbranch_scc1").contains(&format!("{:04X}", offset(16))), + "{}", + at("s_cbranch_scc1") + ); +} + +/// The sum translates in halves, its loop in lockstep. +#[test] +fn a_sum_of_earlier_waves_translates_in_halves() { + for threads in [128, 256, 512] { + for narrow_waves in [false, true] { + let n = native(&sum_of_earlier_waves(), true, threads, 512); + let l = lowered_with(&n, true, narrow_waves) + .unwrap_or_else(|e| panic!("{threads} threads narrow_waves={narrow_waves}: {e}")); + assert_eq!(l.wave_size, Some(32)); + } + } +} + +/// Each lane of wave `w` stores `5 + 6 + ... + (w + 4)`, as on the console. +#[cfg(windows)] +#[test] +fn a_sum_of_earlier_waves_matches_the_console_on_every_gpu() { + let words = sum_of_earlier_waves(); + let mut failed = Vec::new(); + for threads in [128u32, 256, 512] { + let want: Vec = (0..threads) + .map(|t| (0..t >> 6).map(|k| k + 5).sum()) + .collect(); + for narrow_waves in [false, true] { + failed.extend( + differences_with(&words, threads, 1, &want, 512, narrow_waves) + .into_iter() + .map(|m| format!("{threads} threads narrow_waves={narrow_waves}: {m}")), + ); + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + +/// LDS written in a `while` loop of a group of one console wave (64 +/// threads), the shape of the loops in the builder's `28918b7150a7aad5` and +/// `caa78b8ca62bc3d6`: each lane clears its eight LDS dwords; the lanes whose +/// count `tid & 7` is not 0 then loop, writing the pass number `s28` at +/// dword `s28 - 1` of theirs in each pass, and leave when `s28` is their +/// count (the latch restores EXEC from the mask of lanes left, `s[16:17]`). +/// After the loop each lane reads the eight dwords of lane `tid ^ 63`, in +/// the wave's other half, and stores them. +fn lds_written_in_a_while_loop() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x3614_0087, // v_and_b32 v10, 7, v0 + 0x3418_0085, // v_lshlrev_b32 v12, 5, v0 + 0x7E16_0280, // v_mov_b32 v11, 0 + ]); + for k in 0..8 { + w.extend([0xD834_0000 | (4 * k), 0x0000_0B0C]); // ds_write_b32 v12, v11 offset:4k + } + w.extend([ + 0xBE8C_047E, // s_mov_b64 s[12:13], exec + 0x7DAA_1480, // v_cmpx_ne_u32 exec, 0, v10 + 0xBF88_000F, // s_cbranch_execz (the end) + 0xBE8E_047E, // s_mov_b64 s[14:15], exec + 0xBE90_047E, // s_mov_b64 s[16:17], exec + 0xBE9C_0380, // s_mov_b32 s28, 0 + 0xBF82_0001, // s_branch (the header) + 0x87FE_1012, // s_and_b64 exec, s[18:19], s[16:17] + 0x8F12_821C, // s_lshl_b32 s18, s28, 2 + 0x811C_811C, // s_add_i32 s28, s28, 1 + 0x4A1A_1812, // v_add_nc_u32 v13, s18, v12 + 0x7E1E_021C, // v_mov_b32 v15, s28 + 0xBE92_047E, // s_mov_b64 s[18:19], exec + 0xD834_0000, + 0x0000_0F0D, // ds_write_b32 v13, v15 + 0x7DA4_141C, // v_cmpx_eq_u32 exec, s28, v10 + 0x8A90_7E10, // s_andn2_b64 s[16:17], s[16:17], exec + 0xBF85_FFF5, // s_cbranch_scc1 (the latch) + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x3A1C_00BF, // v_xor_b32 v14, 63, v0 + 0x341C_1C85, // v_lshlrev_b32 v14, 5, v14 + ]); + for k in 0..8 { + w.extend([0xD8D8_0000 | (4 * k), 0x0000_000E | (20 + k) << 24]); // ds_read_b32 v(20+k), v14 offset:4k + } + w.push(S_WAITCNT_LGKM); + for k in 0..8 { + w.extend(store(20 + k as u8, 4 * k)); + } + w.push(S_ENDPGM); + w +} + +#[test] +fn the_lds_while_loop_is_what_its_comments_say() { + let words = lds_written_in_a_while_loop(); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let list = gfx10::decode(&code).expect("decodes"); + let text: Vec = list.iter().map(|i| i.text(true)).collect(); + let all = text.join("\n"); + for want in [ + "v_lshlrev_b32 v16, 5, v0", + "v_and_b32 v10, 7, v0", + "v_lshlrev_b32 v12, 5, v0", + "v_mov_b32 v11, 0", + "ds_write_b32 v12, v11\n", + "ds_write_b32 v12, v11 offset:28", + "s_mov_b64 s[12:13], exec", + "v_cmpx_ne_u32 exec, 0, v10", + "s_mov_b64 s[14:15], exec", + "s_mov_b64 s[16:17], exec", + "s_mov_b32 s28, 0", + "s_and_b64 exec, s[18:19], s[16:17]", + "s_lshl_b32 s18, s28, 2", + "s_add_i32 s28, s28, 1", + "v_add_nc_u32 v13, s18, v12", + "v_mov_b32 v15, s28", + "s_mov_b64 s[18:19], exec", + "ds_write_b32 v13, v15", + "v_cmpx_eq_u32 exec, s28, v10", + "s_andn2_b64 s[16:17], s[16:17], exec", + "s_mov_b64 exec, s[12:13]", + "v_xor_b32 v14, 63, v0", + "v_lshlrev_b32 v14, 5, v14", + "ds_read_b32 v20, v14\n", + "ds_read_b32 v27, v14 offset:28", + ] { + assert!(all.contains(want), "{want:?} not in:\n{all}"); + } + // The branches: to the end, the header and the latch. + let at = |name: &str| { + list.iter() + .position(|i| i.text(true).starts_with(name)) + .expect("there") + }; + let target = |n: usize| format!("{:04X}", list[n].offset); + let (end, header, latch) = ( + at("s_mov_b64 exec, s[12:13]"), + at("s_lshl_b32 s18"), + at("s_and_b64 exec, s[18:19]"), + ); + assert!( + text[at("s_cbranch_execz")].contains(&target(end)), + "{}", + text[at("s_cbranch_execz")] + ); + assert!( + text[at("s_branch")].contains(&target(header)), + "{}", + text[at("s_branch")] + ); + assert!( + text[at("s_cbranch_scc1")].contains(&target(latch)), + "{}", + text[at("s_cbranch_scc1")] + ); +} + +/// Each lane stores the dwords of lane `tid ^ 63`: 1 to that lane's count, +/// then zeros, as on the console. +#[cfg(windows)] +#[test] +fn lds_written_in_a_while_loop_matches_the_console_on_every_gpu() { + let words = lds_written_in_a_while_loop(); + let want: Vec = (0..64u32) + .flat_map(|t| { + let n = (t ^ 63) & 7; + (1..=8).map(move |p| if p <= n { p } else { 0 }) + }) + .collect(); + let mut failed = Vec::new(); + for narrow_waves in [true, false] { + let n = native(&words, true, 64, 2048); + match lowered_with(&n, true, narrow_waves) { + Ok(l) => eprintln!( + "narrow_waves={narrow_waves}: translates, {} barriers", + l.barriers + ), + Err(e) => { + eprintln!("narrow_waves={narrow_waves}: refused: {e}"); + continue; + } + } + failed.extend( + differences_with(&words, 64, 8, &want, 2048, narrow_waves) + .into_iter() + .map(|m| format!("narrow_waves={narrow_waves}: {m}")), + ); + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} From 94118a720980f5a00404855e498c208277822cdc Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Sat, 28 Nov 2026 03:07:34 +0400 Subject: [PATCH 4/5] fix(gpu): the structure builder runs only when asked to The acceleration-structure builder ran in every frame in which all its pipelines were made. Three of its 53 were refused on 32-lane hosts (first-lane reads in while loops), so on those it never ran. With them translated it runs, and its lists address title memory that no host copy holds: such memory reads 0 and takes no writes, and what a list that missed wrote is withheld from title memory. On an M5 Pro (D3DMetal), with all 53 made: the builder's first frame had 12,387 dispatches using title memory and missed 14,469 pages and 94 regions of 256 MiB; later frames missed 200 to 2,700 pages. In four runs (163 to 495 frames with title-memory lists each) no frame copied a page back. The cell's picture was dark, and macOS ended submissions in four of five runs. Held back, the same build missed 2 or 3 pages a frame (at address 0) and ended none. The builder now runs only with every pipeline made and VICTORY_BVH_BUILDER=1; otherwise it is held back as before, and the log says why ("its lists address title memory with no host copy"). Other forks gate it by the same switch (101Leafy/victory-leafy d24d3a4888, trustno1-coder/VIctory-NVIDIA 30b979ee48). Test: the rule (every pipeline made, and asked) and the switch's one value. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/draw.rs | 2 +- crates/victory-gpu/src/pipeline/builder.rs | 60 ++++++++++++++++++++-- 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index c1d5c8152..f2aa2944e 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1552,7 +1552,7 @@ impl State { // The acceleration-structure builder runs whole or not at all // (`pipeline::builder`). if crate::pipeline::held_back(self.pipeline as This) { - once!("a dispatch of the BVH builder held back: not all its pipelines are made"); + once!("a dispatch of the BVH builder held back"); DROPPED.fetch_add(1, Ordering::Relaxed); #[cfg(feature = "diagnostics")] dropped(list, self.pipeline, "dispatch"); diff --git a/crates/victory-gpu/src/pipeline/builder.rs b/crates/victory-gpu/src/pipeline/builder.rs index f27c10b46..bc5c3f4be 100644 --- a/crates/victory-gpu/src/pipeline/builder.rs +++ b/crates/victory-gpu/src/pipeline/builder.rs @@ -12,6 +12,17 @@ //! pipeline it has created has its host pipeline; otherwise none of them //! run (the structures keep what they held). //! +//! With every pipeline made it still runs only when asked to +//! (`VICTORY_BVH_BUILDER=1`): its lists address title memory that no host +//! copy holds (`crate::memory`: such memory reads 0 and takes no writes), +//! in every frame it runs in. A run on an M5 Pro with all 53 pipelines made +//! missed 14,469 pages and 94 regions of 256 MiB in the builder's first +//! frame and 200 to 2,700 pages in each later one; none of the pages its +//! lists wrote went back into title memory (all withheld, as computed from +//! zeros), in any frame of four runs. What it leaves in the host copies is +//! what the frame's trace passes read. In those runs the cell's picture was +//! dark, and macOS ended submissions for holding the GPU in four of five. +//! //! Its pipelines are known by where they come from: created by its code (a //! return address in its image on the stack) or from bytecode in its image. @@ -93,6 +104,29 @@ pub(crate) fn note(p: &Arc) { /// The frame [`runs`] last decided for, and its decision. static DECIDED: Mutex<(u64, bool)> = Mutex::new((u64::MAX, true)); +/// Whether the builder is asked to run (`VICTORY_BVH_BUILDER=1`); read +/// once. +fn asked() -> bool { + static ASKED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ASKED.get_or_init(|| asked_value(std::env::var_os("VICTORY_BVH_BUILDER").as_deref())) +} + +fn asked_value(value: Option<&std::ffi::OsStr>) -> bool { + value == Some(std::ffi::OsStr::new("1")) +} + +/// Why the builder is held back, if it is: `made` (every pipeline has its +/// host pipeline) and `asked` ([`asked`]). +fn held(made: bool, asked: bool) -> Option<&'static str> { + if !made { + Some("not all its pipelines are made") + } else if !asked { + Some("its lists address title memory with no host copy (VICTORY_BVH_BUILDER=1 runs it)") + } else { + None + } +} + /// Whether the builder's dispatches run in the current frame: decided once /// per frame, so that a frame never runs part of the builder. pub(crate) fn runs() -> bool { @@ -111,7 +145,8 @@ pub(crate) fn runs() -> bool { .map(|p| make::state(&p)) .collect() }; - let open = all_made(&states); + let why = held(all_made(&states), asked()); + let open = why.is_none(); if open != decided.1 || !SAID.swap(true, Ordering::Relaxed) { let (made, refused) = ( states.iter().filter(|s| **s == Some(true)).count(), @@ -123,10 +158,9 @@ pub(crate) fn runs() -> bool { made, refused, "BVH builder {}", - if open { - "runs" - } else { - "held back: not all its pipelines are made" + match why { + None => "runs".to_owned(), + Some(why) => format!("held back: {why}"), } ); } @@ -164,6 +198,22 @@ mod tests { assert!(!all_made(&[Some(true), None]), "one still being made"); } + /// With every pipeline made the builder still runs only when asked to: + /// `VICTORY_BVH_BUILDER=1`, nothing else. + #[test] + fn the_builder_runs_only_when_asked_to() { + let os = std::ffi::OsStr::new; + assert!(!asked_value(None)); + assert!(asked_value(Some(os("1")))); + for other in ["", "0", "on", "true", " 1"] { + assert!(!asked_value(Some(os(other))), "{other:?}"); + } + assert_eq!(held(true, true), None); + assert!(held(true, false).unwrap().contains("no host copy")); + assert!(held(false, true).unwrap().contains("not all its pipelines")); + assert!(held(false, false).unwrap().contains("not all its pipelines")); + } + /// Pipelines are the builder's by their bytecode in its image, or by /// its code among the callers; not otherwise. #[test] From 15748ff3c0e42d43f56b60168e83e8d552f00399 Mon Sep 17 00:00:00 2001 From: Pragyaan Gaur Date: Sat, 28 Nov 2026 05:35:49 +0530 Subject: [PATCH 5/5] Keep both sides of the test file after merging main --- .../victory-shader/src/emit/halves_tests.rs | 249 ++++++++++-------- 1 file changed, 136 insertions(+), 113 deletions(-) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index bc799f1f5..88c62ac54 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -4227,6 +4227,142 @@ fn a_first_lane_read_only_active_lanes_see_matches_the_console_on_every_gpu() { assert!(failed.is_empty(), "{}", failed.join("\n")); } +/// A first-lane read of a value a multiply-accumulate made, in an +/// `s_and_saveexec_b64` region whose EXEC is `mask_words`'s, its result +/// used in the region only (as GTA VI's `ef154ebc9e03d1b1` reads a function +/// of a constant-buffer value): `v4 = f32(s14)`, `s14` the first dword of +/// the SRV buffer at table dword 8, then `v_mac_f32 v4, v7, v8` with +/// `v7 = 2.0`, so `v4 += 2.0 * v8`. `v8` is 2.0 (the same in every lane of +/// the region), or with `per_lane` the lane's thread id. The region's lanes +/// store the read; the others 0. +fn mac_read_in_a_region(mask_words: &[u32], per_lane: bool) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0xF408_0B02, + 0xFA00_0020, // s_load_dwordx4 s[44:47], s[4:5], 0x20 + S_WAITCNT_LGKM, + 0xF420_0396, + 0xFA00_0000, // s_buffer_load_dword s14, s[44:47], 0x0 + S_WAITCNT_LGKM, + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E04_0280, // v_mov_b32 v2, 0 + ]); + w.extend(mask_words); + w.extend([ + 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc + 0xBF88_0006, // s_cbranch_execz (past the region) + 0x7E08_0C0E, // v_cvt_f32_u32 v4, s14 + 0x7E0E_02F4, // v_mov_b32 v7, 2.0 + if per_lane { + 0x7E10_0D00 // v_cvt_f32_u32 v8, v0 + } else { + 0x7E10_02F4 // v_mov_b32 v8, 2.0 + }, + 0x3E08_1107, // v_mac_f32 v4, v7, v8 + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x7E04_020C, // v_mov_b32 v2, s12 + 0xBEFE_0400, // s_mov_b64 exec, s[0:1] + ]); + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +#[test] +fn the_mac_read_programs_are_what_their_comments_say() { + for per_lane in [false, true] { + let words = mac_read_in_a_region(&MASK_LANES_12_44, per_lane); + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let all = gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + .join("\n"); + for want in [ + "s_buffer_load_dword s14, s[44:47]", + "s_and_saveexec_b64 s[0:1], vcc", + "s_cbranch_execz", + "v_cvt_f32_u32 v4, s14", + "v_mov_b32 v7, 2.0", + if per_lane { + "v_cvt_f32_u32 v8, v0" + } else { + "v_mov_b32 v8, 2.0" + }, + "v_mac_f32 v4, v7, v8", + "v_readfirstlane_b32 s12, v4", + "v_mov_b32 v2, s12", + "s_mov_b64 exec, s[0:1]", + ] { + assert!(all.contains(want), "per_lane={per_lane}: {want:?} not in:\n{all}"); + } + } +} + +/// A multiply-accumulate adds to its old destination. Where that, like its +/// operands, is the same in every lane of the read's EXEC, so is its +/// result, and each half makes the read by itself: no halves for it, no +/// exchange. Before, any multiply-accumulate in the value's chain sent the +/// read to the halves. With a per-lane operand the read still takes them. +#[test] +fn a_first_lane_read_of_a_multiply_accumulate_is_made_in_each_half() { + for threads in [64, 128] { + let of = |per_lane: bool| { + let words = mac_read_in_a_region(&MASK_LANES_12_44, per_lane); + lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("per_lane={per_lane} {threads} threads: {e}")) + }; + let alike = of(false); + assert_eq!(alike.barriers, 0, "{threads} threads: no exchange"); + let per_lane = of(true); + assert_eq!(per_lane.wave_size, Some(32)); + assert!(per_lane.barriers > 0, "{threads} threads: the halves pass the first lane"); + } +} + +/// Both give the console's lanes on every GPU: the region's lanes store +/// `41.0 + 2.0 * 2.0`, or with a per-lane operand `41.0 + 2.0 *` the thread +/// id of the console wave's first lane in the region. +#[cfg(windows)] +#[test] +fn a_first_lane_read_of_a_multiply_accumulate_matches_the_console_on_every_gpu() { + type InRegion = fn(u32) -> bool; + let masks: [(&str, &[u32; 2], InRegion, &[u32]); 3] = [ + ("lower_8_9", &MASK_LANES_8_9, |t| t >> 1 == 4, &[64]), + ("upper_40_41", &MASK_LANES_40_41, |t| t >> 1 == 20, &[64]), + ("both_12_44", &MASK_LANES_12_44, |t| t & 31 == 12, &[64, 128]), + ]; + let mut failed = Vec::new(); + for (label, mask, in_region, groups) in masks { + for &threads in groups { + for per_lane in [false, true] { + let words = mac_read_in_a_region(mask, per_lane); + let want: Vec = (0..threads) + .map(|t| { + if !in_region(t) { + return 0; + } + let base = t & !63; + let first = (base..base + 64).find(|&l| in_region(l)).expect("in it"); + let operand = if per_lane { first as f32 } else { 2.0 }; + (41.0 + 2.0 * operand).to_bits() + }) + .collect(); + let found = differences_with_buffer( + true, &words, threads, 1, &want, 0, false, false, &[41, 0, 0, 0], + ); + failed.extend( + found + .into_iter() + .map(|m| format!("{label}(per_lane={per_lane}) {threads} threads: {m}")), + ); + } + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} + /// A `while` loop as the console compiler lays one out: the entry jumps to /// the test, which branches back to the body while lanes stay; the body /// falls into the test. The body reads the first lane's thread id @@ -4266,42 +4402,6 @@ fn while_loop_first_lane(narrow: bool) -> Vec { ]); } w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] -/// A first-lane read of a value a multiply-accumulate made, in an -/// `s_and_saveexec_b64` region whose EXEC is `mask_words`'s, its result -/// used in the region only (as GTA VI's `ef154ebc9e03d1b1` reads a function -/// of a constant-buffer value): `v4 = f32(s14)`, `s14` the first dword of -/// the SRV buffer at table dword 8, then `v_mac_f32 v4, v7, v8` with -/// `v7 = 2.0`, so `v4 += 2.0 * v8`. `v8` is 2.0 (the same in every lane of -/// the region), or with `per_lane` the lane's thread id. The region's lanes -/// store the read; the others 0. -fn mac_read_in_a_region(mask_words: &[u32], per_lane: bool) -> Vec { - let mut w = PROLOGUE.to_vec(); - w.extend([ - 0xF408_0B02, - 0xFA00_0020, // s_load_dwordx4 s[44:47], s[4:5], 0x20 - S_WAITCNT_LGKM, - 0xF420_0396, - 0xFA00_0000, // s_buffer_load_dword s14, s[44:47], 0x0 - S_WAITCNT_LGKM, - 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 - 0x7E04_0280, // v_mov_b32 v2, 0 - ]); - w.extend(mask_words); - w.extend([ - 0xBE80_246A, // s_and_saveexec_b64 s[0:1], vcc - 0xBF88_0006, // s_cbranch_execz (past the region) - 0x7E08_0C0E, // v_cvt_f32_u32 v4, s14 - 0x7E0E_02F4, // v_mov_b32 v7, 2.0 - if per_lane { - 0x7E10_0D00 // v_cvt_f32_u32 v8, v0 - } else { - 0x7E10_02F4 // v_mov_b32 v8, 2.0 - }, - 0x3E08_1107, // v_mac_f32 v4, v7, v8 - 0x7E18_0504, // v_readfirstlane_b32 s12, v4 - 0x7E04_020C, // v_mov_b32 v2, s12 - 0xBEFE_0400, // s_mov_b64 exec, s[0:1] - ]); w.extend(store(2, 0)); w.push(S_ENDPGM); w @@ -4325,10 +4425,6 @@ fn console_while_loop_first_lane(narrow: bool, t: u32) -> u32 { fn the_while_loop_programs_are_what_their_comments_say() { for narrow in [false, true] { let words = while_loop_first_lane(narrow); -#[test] -fn the_mac_read_programs_are_what_their_comments_say() { - for per_lane in [false, true] { - let words = mac_read_in_a_region(&MASK_LANES_12_44, per_lane); let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let all = gfx10::decode(&code) .expect("decodes") @@ -4360,23 +4456,6 @@ fn the_mac_read_programs_are_what_their_comments_say() { .chain(tail) { assert!(all.contains(want), "{want:?} not in:\n{all}"); - for want in [ - "s_buffer_load_dword s14, s[44:47]", - "s_and_saveexec_b64 s[0:1], vcc", - "s_cbranch_execz", - "v_cvt_f32_u32 v4, s14", - "v_mov_b32 v7, 2.0", - if per_lane { - "v_cvt_f32_u32 v8, v0" - } else { - "v_mov_b32 v8, 2.0" - }, - "v_mac_f32 v4, v7, v8", - "v_readfirstlane_b32 s12, v4", - "v_mov_b32 v2, s12", - "s_mov_b64 exec, s[0:1]", - ] { - assert!(all.contains(want), "per_lane={per_lane}: {want:?} not in:\n{all}"); } } } @@ -4804,62 +4883,6 @@ fn a_while_loop_in_rows_matches_the_console_and_leaves_on_every_gpu() { } eprintln!( "{label}: {groups} groups: {best:?}; with every group at the limit of passes {limit:?}" -/// A multiply-accumulate adds to its old destination. Where that, like its -/// operands, is the same in every lane of the read's EXEC, so is its -/// result, and each half makes the read by itself: no halves for it, no -/// exchange. Before, any multiply-accumulate in the value's chain sent the -/// read to the halves. With a per-lane operand the read still takes them. -#[test] -fn a_first_lane_read_of_a_multiply_accumulate_is_made_in_each_half() { - for threads in [64, 128] { - let of = |per_lane: bool| { - let words = mac_read_in_a_region(&MASK_LANES_12_44, per_lane); - lowered(&native(&words, true, threads, 0), true) - .unwrap_or_else(|e| panic!("per_lane={per_lane} {threads} threads: {e}")) - }; - let alike = of(false); - assert_eq!(alike.barriers, 0, "{threads} threads: no exchange"); - let per_lane = of(true); - assert_eq!(per_lane.wave_size, Some(32)); - assert!(per_lane.barriers > 0, "{threads} threads: the halves pass the first lane"); - } -} - -/// Both give the console's lanes on every GPU: the region's lanes store -/// `41.0 + 2.0 * 2.0`, or with a per-lane operand `41.0 + 2.0 *` the thread -/// id of the console wave's first lane in the region. -#[cfg(windows)] -#[test] -fn a_first_lane_read_of_a_multiply_accumulate_matches_the_console_on_every_gpu() { - type InRegion = fn(u32) -> bool; - let masks: [(&str, &[u32; 2], InRegion, &[u32]); 3] = [ - ("lower_8_9", &MASK_LANES_8_9, |t| t >> 1 == 4, &[64]), - ("upper_40_41", &MASK_LANES_40_41, |t| t >> 1 == 20, &[64]), - ("both_12_44", &MASK_LANES_12_44, |t| t & 31 == 12, &[64, 128]), - ]; - let mut failed = Vec::new(); - for (label, mask, in_region, groups) in masks { - for &threads in groups { - for per_lane in [false, true] { - let words = mac_read_in_a_region(mask, per_lane); - let want: Vec = (0..threads) - .map(|t| { - if !in_region(t) { - return 0; - } - let base = t & !63; - let first = (base..base + 64).find(|&l| in_region(l)).expect("in it"); - let operand = if per_lane { first as f32 } else { 2.0 }; - (41.0 + 2.0 * operand).to_bits() - }) - .collect(); - let found = differences_with_buffer( - true, &words, threads, 1, &want, 0, false, false, &[41, 0, 0, 0], - ); - failed.extend( - found - .into_iter() - .map(|m| format!("{label}(per_lane={per_lane}) {threads} threads: {m}")), ); } }