diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ae0ba7aab..cb0595b78 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1561,7 +1561,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] diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index a723df799..a3f431b5e 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -11,15 +11,19 @@ #[cfg(windows)] use super::host::{Dispatch, Host, Root, Stride, View}; + use super::lower; + #[cfg(windows)] use super::validator; + use crate::native::{ ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, }; use crate::{gfx10, io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; + const S_WAITCNT_LGKM: u32 = 0xBF8C_C07F; // s_waitcnt lgkmcnt(0) /// `s[40:43]`: the raw UAV at table dword 16 (s0 is the table's address). @@ -555,8 +559,11 @@ fn in_a_loop(body: &[u32], result: u32, count: Count) -> Vec { /// VOP2 opcodes of the operations [`reduction`] takes. const V_ADD_F32: u32 = 0x03; + const V_MIN_U32: u32 = 0x13; + const V_MAX_U32: u32 = 0x14; + /// `v_mov_b32 v3, v0`. const V_MOV_V3_V0: u32 = 0x7E06_0300; @@ -1616,7 +1623,9 @@ const fn permlanex16(fetch_inactive: bool, bound_ctrl: bool) -> [u32; 2] { /// The selectors: every nibble of `s8` is odd and every one of `s9` is even. const PERM_LOW: u32 = 0x1357_9BDF; + const PERM_HIGH: u32 = 0x2468_ACE0; + /// What `v1` holds before an instruction that may leave it alone. const PERM_OLD: u32 = 0xAAAA; @@ -2128,7 +2137,6 @@ fn literal_wave64_programs_match_the_console_on_every_gpu() { } } - /// A number kept in VCC_HI on its way into a scalar load's offset: the /// console wave's first thread id, plus one, times 16 bytes, read from the /// structured buffer, and a branch on the dword read. Every lane stores the @@ -3616,14 +3624,17 @@ const MASK_LANES_8_9: [u32; 2] = [ 0x2C06_0081, // v_lshrrev_b32 v3, 1, v0 0x7D84_0684, // v_cmp_eq_u32 vcc, 4, v3 ]; + const MASK_LANES_40_41: [u32; 2] = [ 0x2C06_0081, // v_lshrrev_b32 v3, 1, v0 0x7D84_0694, // v_cmp_eq_u32 vcc, 20, v3 ]; + const MASK_LANES_12_44: [u32; 2] = [ 0x3606_009F, // v_and_b32 v3, 31, v0 0x7D84_068C, // v_cmp_eq_u32 vcc, 12, v3 ]; + const MASK_EMPTY: [u32; 2] = [ 0x2C06_0081, // v_lshrrev_b32 v3, 1, v0 0x7D84_06C0, // v_cmp_eq_u32 vcc, 64, v3 @@ -4019,7 +4030,6 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { } } - /// A program whose only cross-half operations are first-lane reads goes to /// halves for them (#522). Where halves cannot pass the read between them, /// here in a loop counted to the console wave's first lane, it is refused, @@ -4268,55 +4278,6 @@ fn mac_read_in_a_region(mask_words: &[u32], per_lane: bool) -> Vec { w } -/// A register-index waterfall as the console compiler writes one for a -/// per-lane `v[3 + index]`: `v3..v10` hold `k * 1000 + thread id`, the index -/// is `(thread id >> 2) & 7`, and the loop reads one index left -/// (`v_readfirstlane_b32 s38, v28`), runs the lanes holding it with -/// `m0 = s38` and `v_movrels_b32 v31, v3`, drops them, and loops while any -/// lane is left. Every lane stores `v31`: `index * 1000 + thread id`. -/// `with_mbcnt` asks for console lanes as well (so the program runs in -/// halves); `after` is put after the loop, `body` before the loop's -/// `s_xor_b64`. -fn index_waterfall(with_mbcnt: bool, body: &[u32], after: &[u32]) -> Vec { - let mut w = PROLOGUE.to_vec(); - w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 - if with_mbcnt { - w.extend([ - 0xD765_0001, - 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 - ]); - } - for k in 0..8u32 { - // v_add_nc_u32 v(3 + k), k * 1000, v0 - w.extend([0x4A00_00FF | (3 + k) << 17, k * 1000]); - } - w.extend([ - 0x2C38_0082, // v_lshrrev_b32 v28, 2, v0 - 0x3638_3887, // v_and_b32 v28, 7, v28 - 0xBEA4_047E, // s_mov_b64 s[36:37], exec - ]); - let looped = [ - &[ - 0x7E4C_051C, // v_readfirstlane_b32 s38, v28 - 0x7D84_3826, // v_cmp_eq_u32 vcc, s38, v28 - 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc - 0xBEFC_0326, // s_mov_b32 m0, s38 - 0x7E3E_8703, // v_movrels_b32 v31, v3 - ][..], - body, - &[0x89FE_067E], // s_xor_b64 exec, exec, s[6:7] - ] - .concat(); - let back = -(looped.len() as i32 + 1); - w.extend(&looped); - w.push(0xBF89_0000 | (back as u32 & 0xFFFF)); // s_cbranch_execnz (the read) - w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] - w.extend(after); - w.extend(store(31, 0)); - w.push(S_ENDPGM); - w -} - #[test] fn the_mac_read_programs_are_what_their_comments_say() { for per_lane in [false, true] { @@ -4412,6 +4373,888 @@ fn a_first_lane_read_of_a_multiply_accumulate_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")); +} + +/// [`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")); +} + +/// [`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")); +} + +/// A register-index waterfall as the console compiler writes one for a +/// per-lane `v[3 + index]`: `v3..v10` hold `k * 1000 + thread id`, the index +/// is `(thread id >> 2) & 7`, and the loop reads one index left +/// (`v_readfirstlane_b32 s38, v28`), runs the lanes holding it with +/// `m0 = s38` and `v_movrels_b32 v31, v3`, drops them, and loops while any +/// lane is left. Every lane stores `v31`: `index * 1000 + thread id`. +/// `with_mbcnt` asks for console lanes as well (so the program runs in +/// halves); `after` is put after the loop, `body` before the loop's +/// `s_xor_b64`. +fn index_waterfall(with_mbcnt: bool, body: &[u32], after: &[u32]) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.push(0x3420_0085); // v_lshlrev_b32 v16, 5, v0 + if with_mbcnt { + w.extend([ + 0xD765_0001, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v1, -1, 0 + ]); + } + for k in 0..8u32 { + // v_add_nc_u32 v(3 + k), k * 1000, v0 + w.extend([0x4A00_00FF | (3 + k) << 17, k * 1000]); + } + w.extend([ + 0x2C38_0082, // v_lshrrev_b32 v28, 2, v0 + 0x3638_3887, // v_and_b32 v28, 7, v28 + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + ]); + let looped = [ + &[ + 0x7E4C_051C, // v_readfirstlane_b32 s38, v28 + 0x7D84_3826, // v_cmp_eq_u32 vcc, s38, v28 + 0xBE86_246A, // s_and_saveexec_b64 s[6:7], vcc + 0xBEFC_0326, // s_mov_b32 m0, s38 + 0x7E3E_8703, // v_movrels_b32 v31, v3 + ][..], + body, + &[0x89FE_067E], // s_xor_b64 exec, exec, s[6:7] + ] + .concat(); + let back = -(looped.len() as i32 + 1); + w.extend(&looped); + w.push(0xBF89_0000 | (back as u32 & 0xFFFF)); // s_cbranch_execnz (the read) + w.push(0xBEFE_0424); // s_mov_b64 exec, s[36:37] + w.extend(after); + w.extend(store(31, 0)); + w.push(S_ENDPGM); + w +} #[test] fn the_index_waterfall_programs_are_what_their_comments_say() { 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);