From 8a0d1e3c163817ed4b261cfb8dc911ade79ac28f Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Sat, 28 Nov 2026 09:51:04 +0400 Subject: [PATCH] fix(shader): keep the lanes past a dispatch's thread count outside EXEC where they cannot leave A dispatch counted in threads (DispatchX with its thread-dimensions flag) may end in a part of a group. The console starts only the threads the dispatch counts; the other lanes of the last wave are there with their EXEC bit clear. Here the host runs whole groups, and the translation asked for such a dispatch branches the lanes past the count to a return at the entry (Lower::leave_past_the_count). That is possible only where no lane waits for another: a program with a group barrier, with LDS barriers for narrow waves, or in 32-lane halves that pass values needs every lane at each barrier. Such a program had no form for the dispatch, and its last group ran whole ("cannot leave the lanes past the count"). That is wrong for the lanes that do run, not only for stores past the count: EXEC on entry held every lane, so a program that counts its lanes (s_bcnt1_i32_b64 of EXEC), ballots, sums over the wave or reads the first lane computed with the lanes the console never starts. GTA VI's acceleration-structure builder dispatches 28918b7150a7aad5 and caa78b8ca62bc3d6 that way (1,606 and 12 threads in groups of 64); both add s_bcnt1 of EXEC into every lane's addresses. Those lanes now stay, with EXEC on entry clear, as the console has them. For the translation with thread limits the structure pass takes EXEC on entry as a new atom, "the dispatch runs this lane" (structure::structure_limited, Atom::Dispatched), instead of every lane; its lane bit is thread < count (or count 0) from the same user-data word. Every mask derived from EXEC carries it through the mask algebra that is already there: guards of loads and stores, ballots and bit counts, sums and prefixes over the wave, first-lane reads, and the stay conditions of loops, so such a lane neither stores nor votes to stay. A mask the program itself sets to all lanes still holds all of them: the compiler's whole-wave sections run the lanes not started too and select on the saved EXEC, as on the console. The return at the entry stays for the programs that can use it. The new form is tried where it cannot be (lower_limited), in one dimension, for the per-lane form only (literal halves take EXEC as the console wave's whole: no word there); where it is refused the program is as before. Translations without thread limits do not change. Of the builder's 52 programs, 37 had a form for such a dispatch; 51 have one now (the other has one thread per group). Tests, on hardware (M5 Pro, D3DMetal) against the console's values: - a wave64 program in groups of 64 with LDS, a group barrier, a loop run in lockstep with an atomic counter, s_bcnt1 of EXEC, EXEC as two dwords, a first-lane read and the compiler's whole-wave sum, in dispatches of 0 (all), 1, 2, 7, 12, 31, 32, 33, 40, 63, 64, 65, 74, 96, 127 and 128 threads over two groups: every lane that runs stores the console's eight dwords, no other lane stores, and the loop's passes are counted for the lanes that run only; - the existing count test (each lane adds 1 to a counter) also with a group barrier and with console lanes (v_mbcnt), in wave32 and wave64. And natively: the limited structure guards an instruction under EXEC on entry by the new atom and one under EXEC set to all lanes by nothing. Co-Authored-By: Claude Fable 5.2 --- crates/victory-gpu/src/pipeline.rs | 13 +- .../victory-shader/src/emit/halves_tests.rs | 346 +++++++++++++++++- crates/victory-shader/src/emit/lower.rs | 11 +- crates/victory-shader/src/emit/lower/retry.rs | 49 ++- .../src/emit/lower/thread_limits.rs | 36 +- crates/victory-shader/src/emit/mod.rs | 19 +- crates/victory-shader/src/structure.rs | 82 ++++- 7 files changed, 514 insertions(+), 42 deletions(-) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 52840b140..d602bf78a 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -523,12 +523,13 @@ fn may_limit_threads(threads: Option<[u32; 3]>) -> bool { } /// The host pipeline of compute pipeline `p` whose lanes past a dispatch's -/// count of threads leave at once (`emit::Options::thread_limits`), made on -/// the first dispatch counted in threads that ends in a part of a group -/// (`draw::State::dispatch_x`): its shader translated again, so programs -/// no such dispatch reaches keep their translation. None where the program -/// cannot leave them (a group barrier, 32-lane halves passing values) or -/// that translation or pipeline fails; asked once per shader. +/// count of threads do not run (`emit::Options::thread_limits`: they leave +/// at once, or stay outside EXEC where the program's lanes wait for each +/// other), made on the first dispatch counted in threads that ends in a +/// part of a group (`draw::State::dispatch_x`): its shader translated +/// again, so programs no such dispatch reaches keep their translation. +/// None where the program has no such form (literal halves, or a refusal) +/// or that translation or pipeline fails; asked once per shader. #[cfg(windows)] pub(crate) fn thread_limited(p: &host::HostPipeline) -> Option<&'static host::HostPipeline> { type Made = HashMap<[u8; 32], Option<&'static host::HostPipeline>>; diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 54a64759d..73efefbed 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -3766,11 +3766,12 @@ fn thread_limit(l: &lower::Lowered) -> Option { l.user_data.iter().copied().find(|u| u.root == code) } -/// Which programs leave the lanes past a dispatch's count of threads: -/// those of one dimension whose lanes never wait for each other, not in -/// 32-lane halves that pass values nor in literal halves, and only when the -/// translation asks for it; the word is past the console's user data and -/// names the group's width. +/// Which programs know a dispatch's count of threads: those of one +/// dimension, only when the translation asks for it; not literal halves. +/// Where no lane waits for another the lanes past the count leave at the +/// start; with a group barrier or in 32-lane halves that pass values they +/// stay, outside EXEC. The word is past the console's user data and names +/// the group's width. #[test] fn only_programs_whose_lanes_never_wait_leave_past_a_count_of_threads() { let limited = |words: &[u32], wave64, threads, host_wave32| { @@ -3808,24 +3809,29 @@ fn only_programs_whose_lanes_never_wait_leave_past_a_count_of_threads() { }); let l = lower_halves_limited(&flat, true, true, true, true).unwrap(); assert_eq!(thread_limit(&l), None, "two dimensions"); - // s_barrier: lanes that left would never reach it. - assert_eq!( - limited(&counted_lanes(&[0xBF8A_0000]), false, 64, true), - None, + // s_barrier: lanes that left would never reach it. They stay, outside + // EXEC from the entry on. + assert!( + limited(&counted_lanes(&[0xBF8A_0000]), false, 64, true).is_some(), "a group barrier" ); // v_mbcnt reads console lanes: a wave64 group of 64 runs in halves, - // which pass values between them at barriers; one of 32 does not. + // which pass values between them at barriers (the lanes stay there + // too); one of 32 does not. let lanes = counted_lanes(&[0xD765_0003, 0x0001_00C1]); - assert_eq!(limited(&lanes, true, 64, true), None, "in halves"); + assert!(limited(&lanes, true, 64, true).is_some(), "in halves"); assert!(limited(&lanes, true, 32, true).is_some(), "one host wave"); assert!( limited(&lanes, true, 64, false).is_some(), "one host wave64" ); - // A lane read across the halves translates only as literal halves, - // whose group must take one path: no word there. + // A lane read across the halves, under a guard: in halves, the lanes + // stay. let n = native(&literal_lane_reads(false), true, 64, 0); + let l = lower_halves_limited(&n, true, true, true, true).expect("in halves"); + assert!(thread_limit(&l).is_some(), "a lane read across the halves"); + // Literal halves take EXEC as the console wave's whole: no word there. + let n = native(&literal_exec_dwords(), true, 64, 0); let l = lower_halves_limited(&n, true, true, true, true).expect("literal halves"); assert_eq!(thread_limit(&l), None, "literal halves"); let code: Vec = lanes.iter().flat_map(|w| w.to_le_bytes()).collect(); @@ -3876,10 +3882,22 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { }, View::RawUav(64), ]; + // Plain (the lanes past the count leave at the start), with a group + // barrier, and reading console lanes (`v_mbcnt`: in halves where the + // host's waves are 32 lanes): in the last two the lanes stay, outside + // EXEC. + let extras: [(&str, &[u32]); 3] = [ + ("plain", &[]), + ("s_barrier", &[0xBF8A_0000]), + ("v_mbcnt", &[0xD765_0003, 0x0001_00C1]), + ]; for (adapter, host) in &hosts { let wave32 = host.wave32().unwrap_or(false); - for wave64 in [false, true] { - let n = native(&counted_lanes(&[]), wave64, 64, 0); + for (wave64, (kind, extra)) in [false, true] + .into_iter() + .flat_map(|w| extras.iter().map(move |e| (w, *e))) + { + let n = native(&counted_lanes(extra), wave64, 64, 0); let l = lower_halves_limited(&n, wave32, wave32, true, true).expect("translates"); let limit = thread_limit(&l).expect("a word for the count"); let shader = shader(l); @@ -3889,7 +3907,7 @@ fn the_lanes_past_a_count_of_threads_do_not_run() { v.validate(&mut shader.dxil.clone()) .expect("DXIL validation failed"); } - let label = format!("{adapter} (wave64 {wave64})"); + let label = format!("{adapter} (wave64 {wave64}, {kind})"); let Ok((root, pso)) = host.compute_pipeline(&shader) else { panic!("{label}: no pipeline"); }; @@ -6023,3 +6041,299 @@ fn a_register_index_waterfall_matches_the_console_on_every_gpu() { } assert!(failed.is_empty(), "{}", failed.join("\n")); } + +/// A wave64 program in groups of 64 that cannot leave the lanes past a +/// dispatch's count of threads at the start: it has LDS, a group barrier +/// and a loop its 32-lane halves run in lockstep. It reads EXEC as the +/// console's last wave has it, the way GTA VI's structure builder does +/// (`28918b7150a7aad5`, `caa78b8ca62bc3d6`): +/// +/// - `s_bcnt1_i32_b64 s26, exec`: how many lanes the wave runs; +/// - EXEC as two dwords (`s_mov_b64 s[20:21], exec`) and the first lane's +/// thread id plus 1 (`v_readfirstlane_b32`); +/// - the compiler's whole-wave sum ([`emit_reduction_body`]) of the thread +/// id plus 1: under `s_or_saveexec_b64 s[12:13], -1` every lane of the +/// wave runs, started or not, and `v_cndmask_b32` on the saved EXEC gives +/// the lanes not started 0; +/// - each lane writes its thread id plus 1 to its LDS dword, and after +/// `s_barrier` reads the dword of lane `lane / 2`; +/// - a `while` loop a lane stays in for `lane & 7` passes, adding the first +/// lane left in each pass and, atomically, 1 to a counter past the lanes' +/// dwords. +/// +/// Each lane stores eight dwords at `(64 group + lane) * 32`: the count, +/// EXEC's dwords, the first lane, the LDS dword read, the wave's sum, the +/// loop's sum and its passes. +fn counted_in_halves() -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E1E_0201, // v_mov_b32 v15, s1 + 0x341E_1E8B, // v_lshlrev_b32 v15, 11, v15 + 0x4A20_1F10, // v_add_nc_u32 v16, v16, v15 + 0x4A10_0081, // v_add_nc_u32 v8, 1, v0 + 0x4A06_0081, // v_add_nc_u32 v3, 1, v0 + ]); + emit_reduction_body(&mut w, 0x25, 0x80); // v_add_nc_u32, 0: the sum in s15 + w.extend([ + 0x7E0E_020F, // v_mov_b32 v7, s15 + 0xBE9A_107E, // s_bcnt1_i32_b64 s26, exec + 0x7E02_021A, // v_mov_b32 v1, s26 + 0xBE94_047E, // s_mov_b64 s[20:21], exec + 0x7E04_0214, // v_mov_b32 v2, s20 + 0x7E2C_0215, // v_mov_b32 v22, s21 + 0x7E0C_0508, // v_readfirstlane_b32 s6, v8 + 0x7E08_0206, // v_mov_b32 v4, s6 + 0x340A_0082, // v_lshlrev_b32 v5, 2, v0 + 0xD834_0000, + 0x0000_0805, // ds_write_b32 v5, v8 + S_WAITCNT_LGKM, + 0xBF8A_0000, // s_barrier + 0x2C12_0081, // v_lshrrev_b32 v9, 1, v0 + 0x3412_1282, // v_lshlrev_b32 v9, 2, v9 + 0xD8D8_0000, + 0x0A00_0009, // ds_read_b32 v10, v9 + S_WAITCNT_LGKM, + 0x7E24_02FF, + 0x0000_1000, // v_mov_b32 v18, 0x1000 + 0x7E26_0281, // v_mov_b32 v19, 1 + 0x7E18_0280, // v_mov_b32 v12, 0 + 0x7E1A_0280, // v_mov_b32 v13, 0 + 0x361C_0087, // v_and_b32 v14, 7, v0 + 0xBEA4_047E, // s_mov_b64 s[36:37], exec + 0xBF82_0005, // s_branch (the test) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A1A_1A06, // v_add_nc_u32 v13, s6, v13 + 0x4A18_1881, // v_add_nc_u32 v12, 1, v12 + 0xE0C8_1000, + 0x800A_1312, // buffer_atomic_add v19, v18, s[40:43], 0 offen + 0x7D82_1D0C, // v_cmp_lt_u32 vcc, v12, v14 + 0x87FE_6A7E, // s_and_b64 exec, exec, vcc + 0xBF89_FFF8, // s_cbranch_execnz (the body) + 0xBEFE_0424, // s_mov_b64 exec, s[36:37] + ]); + for (vdata, slot) in [ + (1, 0), + (2, 1), + (22, 2), + (4, 3), + (10, 4), + (7, 5), + (13, 6), + (12, 7), + ] { + w.extend(store(vdata, 4 * slot)); + } + w.push(S_ENDPGM); + w +} + +/// [`native`] for [`counted_in_halves`]: 64 threads, the group's x in `s1` +/// (after the one user-data SGPR), LDS. +fn native_counted_in_halves() -> NativeProgram { + let mut n = native(&counted_in_halves(), true, 64, 512); + n.io = StageIo::Cs(ComputeIo { + rsrc2: 1 << 1 | 1 << 7 | 1 << 15, + threads: [64, 1, 1], + }); + n +} + +#[test] +fn the_program_counted_in_halves_is_what_its_comments_say() { + let words = counted_in_halves(); + 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 v15, s1", + "v_lshlrev_b32 v15, 11, v15", + "v_add_nc_u32 v16, v16, v15", + "v_add_nc_u32 v8, 1, v0", + "v_add_nc_u32 v3, 1, v0", + "s_or_saveexec_b64 s[12:13], -1", + "v_cndmask_b32 v1, 0, v3, s[12:13]", + "v_add_nc_u32 v1, v1, v1 ", + "v_add_nc_u32 v1, v1, v1 ", + "v_add_nc_u32 v1, v1, v1 ", + "v_add_nc_u32 v1, v1, v1 ", + "v_permlanex16_b32 v2, v1, 0, 0", + "v_add_nc_u32 v1, v2, v1", + "v_readlane_b32 s14, v1, 32", + "v_add_nc_u32 v1, s14, v1", + "v_readlane_b32 s15, v1, 0", + "s_mov_b64 exec, s[12:13]", + "v_mov_b32 v7, s15", + "s_bcnt1_i32_b64 s26, exec", + "v_mov_b32 v1, s26", + "s_mov_b64 s[20:21], exec", + "v_mov_b32 v2, s20", + "v_mov_b32 v22, s21", + "v_readfirstlane_b32 s6, v8", + "v_mov_b32 v4, s6", + "v_lshlrev_b32 v5, 2, v0", + "ds_write_b32 v5, v8", + "s_waitcnt lgkmcnt(0)", + "s_barrier", + "v_lshrrev_b32 v9, 1, v0", + "v_lshlrev_b32 v9, 2, v9", + "ds_read_b32 v10, v9", + "s_waitcnt lgkmcnt(0)", + "v_mov_b32 v18, lit(0x00001000)", + "v_mov_b32 v19, 1", + "v_mov_b32 v12, 0", + "v_mov_b32 v13, 0", + "v_and_b32 v14, 7, v0", + "s_mov_b64 s[36:37], exec", + "s_branch", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v13, s6, v13", + "v_add_nc_u32 v12, 1, v12", + "buffer_atomic_add v19, v18, s[40:43], 0 offen", + "v_cmp_lt_u32 vcc, v12, v14", + "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:?}"); + } +} + +/// What the console stores for [`counted_in_halves`] in a dispatch of +/// `count` threads (0: every lane of `groups` groups): eight dwords per +/// lane, and the counter of the loop's passes. +#[cfg(windows)] +fn console_counted_in_halves(count: u32, groups: u32) -> (Vec<[u32; 8]>, u32) { + let runs = |g: u32, t: u32| count == 0 || 64 * g + t < count; + let mut passes = 0; + let lanes = (0..groups) + .flat_map(|g| (0..64).map(move |t| (g, t))) + .map(|(g, t)| { + if !runs(g, t) { + return [0; 8]; + } + let live: Vec = (0..64).filter(|&l| runs(g, l)).collect(); + let mask = live.iter().fold(0u64, |m, &l| m | 1 << l); + let stays = t & 7; + passes += stays; + // The first lane still in the loop in each pass. + let sum = (0..stays) + .map(|pass| *live.iter().find(|&&l| l & 7 > pass).expect("this one")) + .sum(); + [ + live.len() as u32, + mask as u32, + (mask >> 32) as u32, + live[0] + 1, + t / 2 + 1, + live.iter().map(|l| l + 1).sum(), + sum, + stays, + ] + }) + .collect(); + (lanes, passes) +} + +/// The program gets the word for a dispatch's count of threads, in halves. +#[test] +fn a_program_with_barriers_keeps_the_lanes_past_a_count_out_of_exec() { + let n = native_counted_in_halves(); + let l = lower_halves_limited(&n, true, true, true, true).expect("translates"); + assert!(thread_limit(&l).is_some(), "a word for the count"); + assert_eq!(l.wave_size, Some(32)); + // Not asked for, there is none. + let l = lower_halves_limited(&n, true, true, true, false).expect("translates"); + assert!(thread_limit(&l).is_none()); +} + +/// A dispatch counted in threads that ends in a part of a group, in a +/// program whose lanes wait for each other: the lanes past the count are +/// outside EXEC from the entry on, as in the console's last wave. The +/// lanes that run store what the console's do (its count of lanes, EXEC, +/// first lanes, LDS, the whole-wave sum over the lanes started, the loop's +/// sum and passes), the others store nothing, and the loop's passes are +/// counted for the lanes that run only. +#[cfg(windows)] +#[test] +fn lanes_past_a_count_stay_out_of_exec_in_halves_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; + } + const GROUPS: u32 = 2; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Buffer { + data: &[0; 4], + stride: Stride::Structured(16), + }, + View::RawUav(GROUPS * 64 * 8 + 1), + ]; + let mut failed = Vec::new(); + for (adapter, host) in &hosts { + let wave32 = host.wave32().unwrap_or(false); + let n = native_counted_in_halves(); + let l = lower_halves_limited(&n, wave32, wave32, true, true).expect("translates"); + let limit = thread_limit(&l).expect("a word for the count"); + let shader = shader(l); + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } + let Ok((root, pso)) = host.compute_pipeline(&shader) else { + panic!("{adapter}: no pipeline"); + }; + for count in [ + 0u32, 1, 2, 7, 12, 31, 32, 33, 40, 63, 64, 65, 74, 96, 127, 128, + ] { + let mut ud = vec![0; shader.user_data_dwords() as usize]; + ud[limit.index as usize] = count; + 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!("{adapter}: dispatch failed: {e}")); + let (want, passes) = console_counted_in_halves(count, GROUPS); + let mut wrong = 0; + for (t, want) in want.iter().enumerate() { + let got = &out[0][t * 8..t * 8 + 8]; + if got != want { + wrong += 1; + failed.push(format!( + "{adapter}: count {count}: lane {t}: {got:?}, the console {want:?}" + )); + } + } + let counted = out[0][want.len() * 8]; + if counted != passes { + wrong += 1; + failed.push(format!( + "{adapter}: count {count}: {counted} passes counted, the console {passes}" + )); + } + eprintln!("{adapter}: count {count}: {wrong} differ from the console"); + } + } + assert!(failed.is_empty(), "{}", failed.join("\n")); +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 6769b102b..7aa0433cf 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -401,6 +401,8 @@ struct Lower<'a> { loop_act_phis: Vec<(V, usize, usize)>, /// [`Lower::relabelled_flat`], once made. relabelled: Option, + /// [`Lower::dispatched`], once made. + dispatched: Option, /// Lower non-provoking per-vertex pixel reads (P10/P20) to zero and /// hardware-interpolate float P0 at pixel center (`Options::per_vertex_center`). per_vertex_center: bool, @@ -956,6 +958,7 @@ impl<'a> Lower<'a> { loop_outer_active: Map::default(), loop_act_phis: Vec::new(), relabelled: None, + dispatched: None, per_vertex_center, group_scalars, cap_escaped, @@ -1588,7 +1591,10 @@ impl<'a> Lower<'a> { fn run(mut self, limits: bool) -> Result { let p = self.x.p; self.halves_only = self.places_read_as_halves(); - if limits && self.can_leave_past_a_count() { + if self.x.st.limited { + // The word for the count, whatever the program reads of EXEC. + self.dispatched(); + } else if limits && self.can_leave_past_a_count() { self.leave_past_the_count(); } let order = crate::ir::reverse_postorder(&p.blocks); @@ -3290,6 +3296,7 @@ impl<'a> Lower<'a> { } Atom::Opaque(_) => Err("an opaque lane mask"), Atom::Constant(_) => Err("a constant lane mask"), + Atom::Dispatched => Ok(self.dispatched()), } } @@ -11477,7 +11484,7 @@ impl<'a> Lower<'a> { } None } - Atom::Constant(_) => None, + Atom::Constant(_) | Atom::Dispatched => None, }; if v.is_some_and(|v| tainted.contains(&v)) { return true; diff --git a/crates/victory-shader/src/emit/lower/retry.rs b/crates/victory-shader/src/emit/lower/retry.rs index 4b3338af8..2f6330a7c 100644 --- a/crates/victory-shader/src/emit/lower/retry.rs +++ b/crates/victory-shader/src/emit/lower/retry.rs @@ -19,15 +19,58 @@ pub(crate) fn lower_pruned( lower_limited(parts, keep, per_vertex_center, literal_halves, false) } -/// [`lower_pruned`]; `limits`: a compute program that can leave the lanes -/// past a dispatch's count of threads does so at once -/// ([`Lower::leave_past_the_count`]; never in literal halves). +/// [`lower_pruned`]; `limits`: a dispatch counted in threads may end in a +/// part of a group, whose other lanes the console does not start. A +/// compute program that can leave them at the start does +/// ([`Lower::leave_past_the_count`]; never in literal halves). One that +/// cannot (they would miss its group barriers and its exchanges between +/// 32-lane halves) keeps them, outside EXEC from the entry on, as the +/// console has them in its last wave +/// ([`crate::structure::structure_limited`]). Where that form is refused +/// too, the program is as without `limits`: its last group runs whole. pub(crate) fn lower_limited( parts: &Parts, keep: Option<&KeptOutputs>, per_vertex_center: bool, literal_halves: bool, limits: bool, +) -> Result { + let first = lower_limited_as_structured(parts, keep, per_vertex_center, literal_halves, limits); + let counted = |l: &Lowered| { + l.user_data + .iter() + .any(|u| u.root == RootType::Other(super::super::USER_DISPATCH_THREADS_X)) + }; + let one_row = matches!( + &parts.native.io, + StageIo::Cs(cs) if cs.threads[0] > 1 && cs.threads[1..] == [1, 1] + ); + if !limits || !one_row || parts.st.limited || first.as_ref().is_ok_and(counted) { + return first; + } + let limited = crate::structure::structure_limited(parts.p).and_then(|st| { + let native = parts.native; + let res = crate::resource::track(parts.p, &native.layout, native.stage, Some(&st))?; + let parts = Parts { + st: &st, + res: &res, + ..parts.clone() + }; + lower_limited_as_structured(&parts, keep, per_vertex_center, false, limits) + }); + match limited { + Ok(limited) if counted(&limited) => Ok(limited), + _ => first, + } +} + +/// [`lower_limited`] with the lanes as `parts.st` has them. +fn lower_limited_as_structured( + parts: &Parts, + keep: Option<&KeptOutputs>, + per_vertex_center: bool, + literal_halves: bool, + limits: bool, ) -> Result { // Retry refusals from the legacy cross-half gates with whole-wave control flow. let original = lower_with_structure(parts, keep, per_vertex_center, limits); diff --git a/crates/victory-shader/src/emit/lower/thread_limits.rs b/crates/victory-shader/src/emit/lower/thread_limits.rs index 7a85cda4d..5aa5e5570 100644 --- a/crates/victory-shader/src/emit/lower/thread_limits.rs +++ b/crates/victory-shader/src/emit/lower/thread_limits.rs @@ -1,6 +1,8 @@ //! A dispatch counted in threads (the console's `DispatchX` with its //! thread-dimensions flag): the lanes past the count leave at the start -//! ([`Lower::leave_past_the_count`]), in the programs that can. +//! ([`Lower::leave_past_the_count`]), in the programs that can. In the +//! others they stay, outside EXEC from the entry on +//! ([`Lower::dispatched`]). use super::*; @@ -42,6 +44,32 @@ impl Lower<'_> { /// their digests. pub(super) fn leave_past_the_count(&mut self) { let original = self.s.entry; + let runs = self.runs_at(original); + let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(original, Term::CondBr(runs, body, done)); + self.s.m.terminate(done, Term::Ret); + self.s.entry = body; + } + + /// Whether the dispatch runs this lane ([`crate::structure::Atom::Dispatched`]): + /// made once, in the entry block. In a program that cannot leave the + /// lanes past the count at the start (its lanes wait for each other at + /// group barriers, or pass values between 32-lane halves), they stay, + /// with EXEC on entry clear, as the console has them in its last wave: + /// what they do is what the program does with lanes outside EXEC. + pub(super) fn dispatched(&mut self) -> V { + if let Some(d) = self.dispatched { + return d; + } + let d = self.runs_at(self.s.entry); + self.dispatched = Some(d); + d + } + + /// Whether this lane's thread is below the dispatch's count of threads + /// along x ([`super::super::USER_DISPATCH_THREADS_X`]; 0: every lane + /// runs), computed in block `original`. + fn runs_at(&mut self, original: usize) -> V { let width = self.s.threads.expect("compute thread count")[0]; // A dword past the console's user data. let layout = self @@ -75,10 +103,6 @@ impl Lower<'_> { let zero = self.s.m.i32(0); let all = self.s.m.cmp(original, pred::EQ, limit, zero); let inside = self.s.m.cmp(original, pred::IULT, x, limit); - let runs = self.s.m.bin(original, Bin::Or, all, inside); - let (body, done) = (self.s.m.new_block(), self.s.m.new_block()); - self.s.m.terminate(original, Term::CondBr(runs, body, done)); - self.s.m.terminate(done, Term::Ret); - self.s.entry = body; + self.s.m.bin(original, Bin::Or, all, inside) } } diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 6d1f82abf..7139ecdbb 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -475,11 +475,12 @@ pub const ROOT_UAV_VIEW: u32 = 3; pub const ROOT_VIEW_OFFSET: u32 = 4; /// `RootType::Other` code of a user-data dword the host fills at a dispatch /// whose counts are threads, not groups (the console's `DispatchX` with its -/// thread-dimensions flag): how many threads along x run, the lanes past -/// that count leaving at once; 0, every lane of every group. Its -/// [`UserData::dword`] is the group's width. Read only in translations -/// with [`Options::thread_limits`], by compute programs of one dimension -/// whose lanes never wait for each other (`Lower::leave_past_the_count`). +/// thread-dimensions flag): how many threads along x run; 0, every lane of +/// every group. Its [`UserData::dword`] is the group's width. Read only in +/// translations with [`Options::thread_limits`], by compute programs of +/// one dimension: the lanes past the count leave at once where no lane +/// waits for another (`Lower::leave_past_the_count`), and elsewhere stay, +/// outside EXEC from the entry on (`structure::structure_limited`). /// After DexNom/VIctory bc3cd4b0. pub const USER_DISPATCH_THREADS_X: u32 = 0x106; @@ -599,9 +600,11 @@ pub struct Options { /// a read across the halves is refused. The translation differs, so /// the shader cache keys on it. pub halves_rendezvous: bool, - /// A compute program of one dimension whose lanes never wait for each - /// other reads [`USER_DISPATCH_THREADS_X`]: the lanes past a dispatch's - /// count of threads leave at once, as the console never starts them. + /// A compute program of one dimension reads + /// [`USER_DISPATCH_THREADS_X`]: the console never starts the lanes past + /// a dispatch's count of threads. They leave at once where no lane + /// waits for another; where lanes wait (a group barrier, 32-lane halves + /// passing values) they stay, outside EXEC from the entry on. /// The host asks for it only for programs a dispatch counted in threads /// ends in a part of a group of (`victory_gpu::pipeline::thread_limited`). pub thread_limits: bool, diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index 8e5b4e834..f967e69c6 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -65,6 +65,11 @@ pub enum Atom { OpaquePair(Value, Value), /// A constant mask other than all lanes or none. Constant(u64), + /// The dispatch runs this lane: EXEC on entry in a compute program whose + /// dispatch may end in a part of a group ([`structure_limited`]). The + /// console starts only the threads the dispatch counts; the other lanes + /// of the last wave are there with their EXEC bit clear. + Dispatched, } /// Reduced ordered binary decision diagrams over [`Atom`]s. @@ -452,6 +457,8 @@ pub struct Structured { pub bools: Bools, /// Every lane follows the console wave through the blocks. pub(crate) literal: bool, + /// EXEC on entry holds the lanes the dispatch runs ([`structure_limited`]). + pub(crate) limited: bool, /// The incoming lane predicates of each literal mask join. pub(crate) mask_inputs: Map>, /// SCC values computed by votes over a mask in literal mode. @@ -526,6 +533,14 @@ pub fn killing(program: &Program) -> Result { structure_as(program, false) } +/// [`structure`] for a compute program whose dispatch may end in a part of +/// a group: EXEC on entry holds the lanes the dispatch runs +/// ([`Atom::Dispatched`]) instead of every lane, and every mask derived from +/// it carries that. +pub fn structure_limited(program: &Program) -> Result { + structure_with(program, true, true) +} + /// Builds the whole-wave form with the console's EXEC at each vector use. pub(crate) fn split_literal(program: &Program) -> Result { let mut l = Lanes::new(program, true)?; @@ -535,7 +550,16 @@ pub(crate) fn split_literal(program: &Program) -> Result Result { + structure_with(program, helpers, false) +} + +fn structure_with( + program: &Program, + helpers: bool, + limited: bool, +) -> Result { let mut l = Lanes::new(program, false)?; + l.limited = limited; if !helpers { l.kills.clear(); } @@ -558,6 +582,8 @@ type Key = (Value, Value); struct Lanes<'a> { p: &'a Program, literal: bool, + /// EXEC on entry holds the lanes the dispatch runs ([`structure_limited`]). + limited: bool, pair_joins: Map>, order: Vec, /// Reverse-postorder index per block. @@ -696,6 +722,7 @@ impl<'a> Lanes<'a> { let mut l = Lanes { p, literal, + limited: false, pair_joins: Map::default(), order, index, @@ -803,7 +830,12 @@ impl<'a> Lanes<'a> { } else { lo }; - self.masks.insert((lo, hi), Bool::TRUE); + let entry = if self.limited { + self.b.atom(Atom::Dispatched, 0) + } else { + Bool::TRUE + }; + self.masks.insert((lo, hi), entry); self.active.insert(lo); } let mut execs: Vec>> = @@ -994,6 +1026,7 @@ impl<'a> Lanes<'a> { }); Ok(Structured { literal: self.literal, + limited: self.limited, mask_inputs, scc_votes: self.scc_votes, masks: words.clone().map(|(&(lo, _), &m)| (lo, m)).collect(), @@ -1624,6 +1657,53 @@ mod tests { /// `exp null done vm`: a pixel program's end with no color output. const EXP_NULL_DONE: [u32; 2] = [0xF800_1890, 0x0000_0000]; + /// In the limited form EXEC on entry holds the lanes the dispatch runs: + /// a vector instruction under it is guarded by that, one under a mask + /// the program sets to all lanes is not, and one under the saved EXEC + /// again is. + #[test] + fn exec_on_entry_holds_the_dispatched_lanes_in_the_limited_form() { + let words = [ + 0x7E02_0281, // v_mov_b32 v1, 1 (EXEC on entry) + 0xBE8C_037E, // s_mov_b32 s12, exec_lo + 0xBEFE_03C1, // s_mov_b32 exec_lo, -1 + 0x7E04_0282, // v_mov_b32 v2, 2 (every lane) + 0xBEFE_030C, // s_mov_b32 exec_lo, s12 + 0x7E06_0283, // v_mov_b32 v3, 3 (EXEC on entry again) + S_ENDPGM, + ]; + let p = build(&words, false); + let text: Vec = p.blocks[0] + .insts + .iter() + .map(|i| i.machine.text(false)) + .collect(); + assert_eq!( + text[..6], + [ + "v_mov_b32 v1, 1", + "s_mov_b32 s12, exec_lo", + "s_mov_b32 exec_lo, -1", + "v_mov_b32 v2, 2", + "s_mov_b32 exec_lo, s12", + "v_mov_b32 v3, 3", + ] + ); + let plain = structure(&p).unwrap(); + assert_eq!(guarded(&plain), 0, "every lane runs, as EXEC says"); + let limited = structure_limited(&p).unwrap(); + let guards = &limited.guards[0]; + let dispatched = |g: Option| { + g.is_some_and(|g| { + limited.bools.node(g) == Some((Atom::Dispatched, Bool::FALSE, Bool::TRUE)) + }) + }; + assert!(dispatched(guards[0]), "under EXEC on entry"); + assert_eq!(guards[3], None, "under EXEC set to every lane"); + assert!(dispatched(guards[5]), "under the saved EXEC"); + assert_eq!(guarded(&limited), 2); + } + /// A loop that leaves through `s_andn2 X, X, exec` and its SCC to a /// program end with no output (a pixel program that only writes /// through atomics), which gives EXEC back the mask saved before the