From e0b0d07100a1ca5888a7ae845c272ca9e47a4be6 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 20:21:01 +0400 Subject: [PATCH] fix(shader): keep lanes that break out of a counted loop in it, in halves A first-lane read the 32-lane halves of a console wave cannot pass between them is refused: one in a block the lanes of the group do not run together. 9991e29feaa26e3e has been refused so since #522, for a read behind two shapes predication did not take. A counted loop lanes break out of one by one (its code at 0x1f08): loop: ... v_cmpx_lt_f32 exec, 0, v28 ; the lanes that break s_andn2_b64 s[26:27], s[26:27], exec ; the lanes left s_cbranch_scc0 past ; none left: leave s_and_b64 exec, s[10:11], s[26:27] s_add_i32 s30, s30, 1 s_cmp_gt_i32 s30, 2 s_cbranch_scc0 loop The loop's own end is one every lane takes together, but the break put it, and all the code after it, out of step. The break is now predicated away like an early-out (shape 6, match_break_loop): the lanes that break stay in the loop, inactive, to its own end. Each vector write being guarded by the lanes still active, a lane that broke holds past the loop what it held when it broke. Nothing else the loop makes may be seen past it: no lane mask is joined at the exit, no scalar or lane mask written in the loop is read after it, and its body holds no scalar store, atomic or message (the console wave leaves once its every lane broke, and here it runs on). The block taken after the break must dominate the latch and the loop's own end, so the lanes active there are among those that stayed. Only where the loop and its exit are in step afterwards. A guard in a guard, both skipping to one join (0x2158): s_and_saveexec_b64 s[28:29], s[12:13] s_cbranch_execz join ... s_and_saveexec_b64 s[12:13], s[12:13] s_cbranch_execz join v_readfirstlane_b32 s39, v13 The outer one became a skip guard, whose join the inner one could then not share, so what the inner one guards stayed out of step. Where that holds a block that needs to be in step and the whole region can be laid out flat (shape 3), that is done instead. No new lowering. 9991e29feaa26e3e translates again, with 9 group barriers. Over the 2,734 compute programs our runs passed, none is newly refused; 134 others translate differently, 125 of them by the flat layout alone, with 556 fewer group barriers in all. Tests: a loop of three passes lanes break out of (by lane, all of them early, and by half) with a first-lane read in it, and a first-lane read under two guards in a counted loop, give the console's lanes on hardware in groups of 64 and 128; both translate in halves where they were refused; the break stays where the loop's count is read after it. Co-Authored-By: Claude Fable 5.2 --- .../victory-shader/src/emit/halves_tests.rs | 332 +++++++++++++++ .../src/emit/lower/predicate.rs | 382 ++++++++++++++++++ 2 files changed, 714 insertions(+) diff --git a/crates/victory-shader/src/emit/halves_tests.rs b/crates/victory-shader/src/emit/halves_tests.rs index 7c996c684..4ed7690bd 100644 --- a/crates/victory-shader/src/emit/halves_tests.rs +++ b/crates/victory-shader/src/emit/halves_tests.rs @@ -5442,6 +5442,80 @@ fn index_waterfall(with_mbcnt: bool, body: &[u32], after: &[u32]) -> Vec { w } +/// How the lanes of [`break_loop`] break out of it. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Breaks { + /// Lane `l` in pass `l & 3`: the lanes with 3 never, so the loop runs + /// to its own end. + ByLane, + /// Lane `l` in pass `l & 1`: no lane is left after the second pass, and + /// the console wave leaves the loop there. + AllEarly, + /// By half: the lanes of host wave `w` in pass `w & 3`, so from the + /// second pass on a console wave's first lane left is in its upper half. + ByHalf, +} + +/// A loop of three passes, counted in `s30`, that lanes break out of one by +/// one, as the console compiler lays one out (GTA VI's `9991e29feaa26e3e` +/// at 0x1f08): each pass takes the lanes whose `v5` is the pass out of the +/// mask of lanes left (`v_cmpx_eq_u32 exec, s30, v5; s_andn2_b64 s[26:27], +/// s[26:27], exec`), leaves if none is left (`s_cbranch_scc0`), and else +/// goes on with those left (`s_and_b64 exec, s[22:23], s[26:27]`). Each +/// pass reads the first lane left (`v_readfirstlane_b32 s6, v0`) into an +/// accumulator `v2` and counts in `v3`; a lane that breaks sets `v1` to 1, +/// one that never does gets 2 after the last pass. Every lane stores +/// `v2 + (v3 << 16) + (v1 << 24)`. `late`: stores `s30` too, a scalar the +/// loop writes. +fn break_loop(breaks: Breaks, late: 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 + 0x7E06_0280, // v_mov_b32 v3, 0 + ]); + match breaks { + Breaks::ByLane => w.push(0x360A_0083), // v_and_b32 v5, 3, v0 + Breaks::AllEarly => w.push(0x360A_0081), // v_and_b32 v5, 1, v0 + Breaks::ByHalf => w.extend([ + 0x2C0A_0085, // v_lshrrev_b32 v5, 5, v0 + 0x360A_0A83, // v_and_b32 v5, 3, v5 + ]), + } + w.extend([ + 0xBE9E_0380, // s_mov_b32 s30, 0 + 0xBE9A_047E, // s_mov_b64 s[26:27], exec + 0xBE96_047E, // s_mov_b64 s[22:23], exec + // the loop + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + 0x4A06_0681, // v_add_nc_u32 v3, 1, v3 + 0x7DA4_0A1E, // v_cmpx_eq_u32 exec, s30, v5 + 0x7E02_0281, // v_mov_b32 v1, 1 + 0x8A9A_7E1A, // s_andn2_b64 s[26:27], s[26:27], exec + 0xBF84_0005, // s_cbranch_scc0 (past the loop) + 0x87FE_1A16, // s_and_b64 exec, s[22:23], s[26:27] + 0x811E_811E, // s_add_i32 s30, s30, 1 + 0xBF02_821E, // s_cmp_gt_i32 s30, 2 + 0xBF84_FFF5, // s_cbranch_scc0 (the loop) + 0x7E02_0282, // v_mov_b32 v1, 2 + // past the loop + 0xBEFE_0416, // s_mov_b64 exec, s[22:23] + 0x3406_0690, // v_lshlrev_b32 v3, 16, v3 + 0x3402_0298, // v_lshlrev_b32 v1, 24, v1 + 0x4A04_0503, // v_add_nc_u32 v2, v3, v2 + 0x4A04_0501, // v_add_nc_u32 v2, v1, v2 + ]); + w.extend(store(2, 0)); + if late { + w.push(0x7E08_021E); // v_mov_b32 v4, s30 + w.extend(store(4, 4)); + } + w.push(S_ENDPGM); + w +} + #[test] fn the_index_waterfall_programs_are_what_their_comments_say() { let words = index_waterfall(true, &[], &[]); @@ -5522,3 +5596,261 @@ fn a_register_index_waterfall_matches_the_console_on_every_gpu() { } assert!(failed.is_empty(), "{}", failed.join("\n")); } + +/// What each thread of a group of `threads` stores in [`break_loop`] on the +/// console: its wave64s run by the instructions' own rules. +#[cfg(windows)] +fn console_break_loop(breaks: Breaks, threads: u32) -> Vec { + let mut out = vec![0; threads as usize]; + for base in (0..threads).step_by(64) { + let lanes: Vec = (base..threads.min(base + 64)).collect(); + let v5 = |t: u32| match breaks { + Breaks::ByLane => t & 3, + Breaks::AllEarly => t & 1, + Breaks::ByHalf => t >> 5 & 3, + }; + let (mut v1, mut v2, mut v3) = (vec![0u32; 64], vec![0u32; 64], vec![0u32; 64]); + let mut left = vec![true; lanes.len()]; + let mut pass = 0; + loop { + let first = lanes[left.iter().position(|&l| l).expect("a lane is left")]; + for (n, &t) in lanes.iter().enumerate() { + if !left[n] { + continue; + } + v2[n] += first; + v3[n] += 1; + if v5(t) == pass { + v1[n] = 1; + left[n] = false; + } + } + if !left.contains(&true) { + break; + } + pass += 1; + if pass > 2 { + for n in 0..lanes.len() { + if left[n] { + v1[n] = 2; + } + } + break; + } + } + for (n, &t) in lanes.iter().enumerate() { + out[t as usize] = v2[n] + (v3[n] << 16) + (v1[n] << 24); + } + } + out +} + +/// A loop of three passes whose body is a guard in a guard, both skipping +/// to the loop's end (`if (a) { if (b) { .. } }`, as in GTA VI's +/// `9991e29feaa26e3e` at 0x2158): in the inner one, a first-lane read +/// (`v_readfirstlane_b32 s6, v0`) into an accumulator `v2`, which every +/// lane stores. The outer guard takes the odd lanes, or with `upper` the +/// upper half of each console wave; the inner one the lanes with bit 1. +fn nested_guards_first_lane(upper: bool) -> Vec { + let mut w = PROLOGUE.to_vec(); + w.extend([ + 0x3420_0085, // v_lshlrev_b32 v16, 5, v0 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0xBE9E_0380, // s_mov_b32 s30, 0 + // the loop + if upper { + 0x2C0A_0085 // v_lshrrev_b32 v5, 5, v0 + } else { + 0x7E0A_0300 // v_mov_b32 v5, v0 + }, + 0x360A_0A81, // v_and_b32 v5, 1, v5 + 0x7D84_0A81, // v_cmp_eq_u32 vcc, 1, v5 + 0xBE9C_246A, // s_and_saveexec_b64 s[28:29], vcc + 0xBF88_0006, // s_cbranch_execz (the loop's end) + 0x360C_0082, // v_and_b32 v6, 2, v0 + 0x7D84_0C82, // v_cmp_eq_u32 vcc, 2, v6 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0002, // s_cbranch_execz (the loop's end) + 0x7E0C_0500, // v_readfirstlane_b32 s6, v0 + 0x4A04_0406, // v_add_nc_u32 v2, s6, v2 + // the loop's end + 0xBEFE_041C, // s_mov_b64 exec, s[28:29] + 0x811E_811E, // s_add_i32 s30, s30, 1 + 0xBF02_821E, // s_cmp_gt_i32 s30, 2 + 0xBF84_FFF1, // s_cbranch_scc0 (the loop) + ]); + w.extend(store(2, 0)); + w.push(S_ENDPGM); + w +} + +/// What thread `t` of a group of `threads` stores in +/// [`nested_guards_first_lane`] on the console: three times the first +/// thread of its wave64 that both guards take, if they take it. +#[cfg(windows)] +fn console_nested_guards_first_lane(upper: bool, threads: u32, t: u32) -> u32 { + let takes = |t: u32| (if upper { t >> 5 } else { t }) & 1 == 1 && t & 2 == 2; + let base = t & !63; + let first = (base..threads.min(base + 64)).find(|&l| takes(l)); + match first { + Some(first) if takes(t) => 3 * first, + _ => 0, + } +} + +#[test] +fn the_break_loop_programs_are_what_their_comments_say() { + let text = |words: &[u32]| { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + gfx10::decode(&code) + .expect("decodes") + .iter() + .map(|i| i.text(true)) + .collect::>() + }; + // The prologue's five words are four instructions. + let skip = PROLOGUE.len() - 1; + let all = text(&break_loop(Breaks::ByHalf, true)); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_mov_b32 v1, 0", + "v_mov_b32 v2, 0", + "v_mov_b32 v3, 0", + "v_lshrrev_b32 v5, 5, v0", + "v_and_b32 v5, 3, v5", + "s_mov_b32 s30, 0", + "s_mov_b64 s[26:27], exec", + "s_mov_b64 s[22:23], exec", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "v_add_nc_u32 v3, 1, v3", + "v_cmpx_eq_u32 exec, s30, v5", + "v_mov_b32 v1, 1", + "s_andn2_b64 s[26:27], s[26:27], exec", + "s_cbranch_scc0", + "s_and_b64 exec, s[22:23], s[26:27]", + "s_add_i32 s30, s30, 1", + "s_cmp_gt_i32 s30, 2", + "s_cbranch_scc0", + "v_mov_b32 v1, 2", + "s_mov_b64 exec, s[22:23]", + "v_lshlrev_b32 v3, 16, v3", + "v_lshlrev_b32 v1, 24, v1", + "v_add_nc_u32 v2, v3, v2", + "v_add_nc_u32 v2, v1, v2", + ]; + for (n, want) in want.iter().enumerate() { + let got = &all[skip + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } + assert!(all.iter().any(|t| t == "v_mov_b32 v4, s30"), "{all:?}"); + let has = |words: &[u32], want: &str| text(words).iter().any(|t| t == want); + assert!(has(&break_loop(Breaks::ByLane, false), "v_and_b32 v5, 3, v0")); + assert!(has(&break_loop(Breaks::AllEarly, false), "v_and_b32 v5, 1, v0")); + let all = text(&nested_guards_first_lane(true)); + let want = [ + "v_lshlrev_b32 v16, 5, v0", + "v_mov_b32 v2, 0", + "s_mov_b32 s30, 0", + "v_lshrrev_b32 v5, 5, v0", + "v_and_b32 v5, 1, v5", + "v_cmp_eq_u32 vcc, 1, v5", + "s_and_saveexec_b64 s[28:29], vcc", + "s_cbranch_execz", + "v_and_b32 v6, 2, v0", + "v_cmp_eq_u32 vcc, 2, v6", + "s_and_saveexec_b64 s[12:13], vcc", + "s_cbranch_execz", + "v_readfirstlane_b32 s6, v0", + "v_add_nc_u32 v2, s6, v2", + "s_mov_b64 exec, s[28:29]", + "s_add_i32 s30, s30, 1", + "s_cmp_gt_i32 s30, 2", + "s_cbranch_scc0", + ]; + for (n, want) in want.iter().enumerate() { + let got = &all[skip + n]; + assert!(got.starts_with(want), "{n}: {got:?}, not {want:?}"); + } + assert!(has(&nested_guards_first_lane(false), "v_mov_b32 v5, v0")); +} + +/// A first-lane read in a counted loop that lanes break out of one by one +/// runs in halves: the break is predicated away (the lanes that broke stay +/// in the loop, inactive, to its own end), so every lane of the group runs +/// every pass and the halves pass the console wave's first lane left +/// between them. Before, the read was refused there. +#[test] +fn a_first_lane_read_in_a_loop_lanes_break_out_of_translates_in_halves() { + for breaks in [Breaks::ByLane, Breaks::AllEarly, Breaks::ByHalf] { + for threads in [64, 128, 256] { + let words = break_loop(breaks, false); + let l = lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("{breaks:?} {threads} threads: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet in the loop"); + } + } +} + +/// A scalar the loop writes, read after it, keeps the break as it is: the +/// console wave leaves once its every lane broke, with the count of that +/// pass, and the lanes kept in the loop would count on. The read stays +/// refused. +#[test] +fn a_loop_lanes_break_out_of_whose_count_is_read_after_it_is_refused() { + for threads in [64, 128] { + let words = break_loop(Breaks::AllEarly, true); + let e = lowered(&native(&words, true, threads, 0), true) + .err() + .unwrap_or_else(|| panic!("{threads} threads: translated")); + assert!(e.to_string().contains("a first-lane read"), "{e}"); + } +} + +/// A first-lane read under a guard in a guard, both skipping to one join, +/// runs in halves: the region is laid out flat, the inner guard's body in +/// step with it. Before, only the outer guard's own block was, and the +/// read was refused. +#[test] +fn a_first_lane_read_under_nested_guards_translates_in_halves() { + for upper in [false, true] { + for threads in [64, 128, 256] { + let words = nested_guards_first_lane(upper); + let l = lowered(&native(&words, true, threads, 0), true) + .unwrap_or_else(|e| panic!("upper={upper} {threads} threads: {e}")); + assert_eq!(l.wave_size, Some(32)); + assert!(l.barriers > 0, "the halves meet at the read"); + } + } +} + +/// Both give the console's lanes on every GPU. +#[cfg(windows)] +#[test] +fn first_lane_reads_past_a_break_and_under_nested_guards_match_the_console_on_every_gpu() { + let mut failed = Vec::new(); + for threads in [64, 128] { + for breaks in [Breaks::ByLane, Breaks::AllEarly, Breaks::ByHalf] { + let words = break_loop(breaks, false); + let want = console_break_loop(breaks, threads); + failed.extend( + differences(&words, threads, 1, &want) + .into_iter() + .map(|m| format!("{breaks:?} {threads} threads: {m}")), + ); + } + for upper in [false, true] { + let words = nested_guards_first_lane(upper); + let want: Vec = (0..threads) + .map(|t| console_nested_guards_first_lane(upper, threads, t)) + .collect(); + failed.extend( + differences(&words, threads, 1, &want) + .into_iter() + .map(|m| format!("nested upper={upper} {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 435f0c46d..def496833 100644 --- a/crates/victory-shader/src/emit/lower/predicate.rs +++ b/crates/victory-shader/src/emit/lower/predicate.rs @@ -244,6 +244,17 @@ impl PredicatePlan { &needs, &plan, ) + // A guard nested in the body that skips to the same join + // (`if (a) { if (b) { .. } }`) cannot be a skip guard of + // its own, the join being this one's, so what it guards + // stays out of step. Where that needs to be in step and + // the whole region can be laid out flat instead (shape + // 3), that is done. + && !(guards_to_join(&eff_exits, body, join, &needs) + && match_sese_diamond( + p, &eff_exits, d, taken, not_taken, join, &rpo, &needs, &plan, + ) + .is_some()) { plan.exits.insert(d, FlatExit::SkipGuard { body }); plan.skip_bodies.insert(body, d); @@ -359,6 +370,47 @@ impl PredicatePlan { } } + if !changed && host_wave32 { + // Shape 6: a loop every lane ends together but for a break + // lanes take one by one: the break predicated away, the + // lanes that broke kept inactive to the loop's own end. + let wanted = (0..n).any(|b| needs[b] && !plan.step[b]); + 'shape6: for &h in &order { + if !wanted || plan.dead_blocks.contains(&h) || plan.in_diamond.contains(&h) { + continue; + } + let Some(two) = two_exits(&eff_exits, h, &rpo, &plan) else { + continue; + }; + for (breaking, _) in two.leaving { + let Some(lp) = + match_break_loop(p, st, &eff_exits, &rpo, &plan, &two, breaking) + else { + continue; + }; + // Only where the loop is then in step, and the + // block after it. + let mut exits = eff_exits.clone(); + exits[lp.breaking] = LaneExit::Jump(lp.stay); + let step = barriers::in_step_with(p, st, &exits, &plan.uniform_branches); + if !(lp.body.iter().all(|&b| step[b]) && step[lp.exit]) { + continue; + } + plan.exits + .insert(lp.breaking, FlatExit::EarlyOut { cont: lp.stay }); + plan.early_conts.insert(lp.stay, lp.breaking); + plan.skipped_edges.insert((lp.breaking, lp.exit)); + plan.lockstep_headers.insert(h, lp.latch); + plan.lockstep_exits.insert(lp.exit, h); + plan.in_lockstep_loop.extend(lp.body); + eff_exits = exits; + plan.step = step; + changed = true; + break 'shape6; + } + } + } + if !changed { break; } @@ -682,6 +734,56 @@ fn match_skip_guard( Some(body) } +/// Whether a block reached from `body` before `join` branches one way to +/// `join` itself, with a block that needs to be in step (`needs`) on its +/// other way: a guard nested in a skip guard's body, skipping to the same +/// join, around such a block. +fn guards_to_join(exits: &[LaneExit], body: usize, join: usize, needs: &[bool]) -> bool { + // Whether a block reached from `from` before `join` needs to be in step. + let needed = |from: usize| { + let mut seen = Set::default(); + let mut stack = vec![from]; + while let Some(b) = stack.pop() { + if b == join || !seen.insert(b) { + continue; + } + if needs[b] { + return true; + } + match exits[b] { + LaneExit::Jump(t) => stack.push(t), + LaneExit::Branch { + taken, not_taken, .. + } => stack.extend([taken, not_taken]), + LaneExit::End | LaneExit::Indirect => {} + } + } + false + }; + let mut seen = Set::default(); + let mut stack = vec![body]; + while let Some(b) = stack.pop() { + if b == join || !seen.insert(b) { + continue; + } + match exits[b] { + LaneExit::Jump(t) => stack.push(t), + LaneExit::Branch { + taken, not_taken, .. + } => { + if taken == join && not_taken != join && needed(not_taken) + || not_taken == join && taken != join && needed(taken) + { + return true; + } + stack.extend([taken, not_taken]); + } + LaneExit::End | LaneExit::Indirect => {} + } + } + false +} + #[allow(clippy::too_many_arguments)] fn match_sese_diamond( p: &Program, @@ -930,6 +1032,24 @@ fn match_lockstep_loop( Some((latch, exit, stay_when_true, body)) } +/// Whether a block outside the loop `body` reads one of `values` (the +/// scalars the body writes), in an instruction or a phi. +fn read_outside(p: &Program, plan: &PredicatePlan, body: &Set, values: &Set) -> bool { + !values.is_empty() + && p.blocks.iter().enumerate().any(|(b, block)| { + !body.contains(&b) + && !plan.dead_blocks.contains(&b) + && (block + .phis + .iter() + .any(|phi| phi.args.iter().any(|v| values.contains(v))) + || block + .insts + .iter() + .any(|i| i.reads.iter().any(|(_, v)| values.contains(v)))) + }) +} + /// A while-shaped loop [`match_lockstep_while_loop`] found. struct WhileLoop { /// The block jumping back to the header, unconditionally. @@ -1089,6 +1209,268 @@ fn match_lockstep_while_loop( }) } +/// A loop [`match_break_loop`] found. +struct BreakLoop { + /// The block whose branch lanes leave the loop by, one by one. + breaking: usize, + /// Its successor inside the loop, and the one outside. + stay: usize, + exit: usize, + /// The block jumping (or branching) back to the header. + latch: usize, + body: Set, +} + +/// A loop two edges leave ([`two_exits`]). +struct TwoExits { + header: usize, + /// The block jumping (or branching) back to the header. + latch: usize, + body: Set, + /// The two edges, each (from, to). + leaving: [(usize, usize); 2], +} + +/// The loop of header `h`, if it has one latch, is entered only at `h` +/// from blocks in step, holds no cycle of its own and nothing predicated +/// yet, and exactly two edges leave it. +fn two_exits( + exits: &[LaneExit], + h: usize, + rpo: &[usize], + 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() + || !out.iter().all(|&q| plan.step[q]) + || plan.lockstep_headers.contains_key(&h) + { + 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 b == h || !body.insert(b) { + continue; + } + if body.len() > MAX_LOCKSTEP_LOOP_BLOCKS { + 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); + } + } + } + if body.iter().any(|b| { + plan.in_diamond.contains(b) + || plan.in_lockstep_loop.contains(b) + || plan.dead_blocks.contains(b) + || plan.exits.contains_key(b) + || plan.early_conts.contains_key(b) + }) { + return None; + } + // Two edges leave the body: the break's and the loop's own end's. No + // cycle inside the body but the latch's. + let mut leaving = Vec::new(); + 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) { + leaving.push((b, t)); + } else if rpo[t] <= rpo[b] && !(b == latch && t == h) { + return None; // nested cycle inside loop + } + } + } + let [e0, e1] = leaving[..] else { + return None; + }; + Some(TwoExits { + header: h, + latch, + body, + leaving: [e0, e1], + }) +} + +/// A loop with two exits to one block `exit`: a branch lanes leave by one +/// by one (a `break`: `breaking -> exit`), and the loop's own end, taken +/// by every lane left (`ending -> exit`, directly or through one block of +/// its own). The break is predicated away like an early-out: the lanes that +/// break stay in the loop, inactive, to its own end, and reach `exit` with +/// the others. Every vector write is guarded by the lanes still active, so +/// a lane that broke holds at `exit` what it held when it broke: what the +/// edge it would have taken carries. +/// +/// The caller checks that the loop's own end is then one every lane of the +/// group takes together ([`barriers::in_step_with`]). +fn match_break_loop( + p: &Program, + st: &Structured, + exits: &[LaneExit], + rpo: &[usize], + plan: &PredicatePlan, + lp: &TwoExits, + breaking: usize, +) -> Option { + let TwoExits { + header: h, + latch, + ref body, + leaving: [(b0, t0), (b1, t1)], + } = *lp; + let (exit, (ending, after)) = if b0 == breaking { + (t0, (b1, t1)) + } else if b1 == breaking { + (t1, (b0, t0)) + } else { + return None; + }; + if ending == breaking { + return None; + } + let LaneExit::Branch { + taken, not_taken, .. + } = exits[breaking] + else { + return None; + }; + let stay = if taken == exit { not_taken } else { taken }; + if !body.contains(&stay) || eff_preds(exits, &plan.dead_blocks, stay) != [breaking] { + return None; + } + // `stay` dominates the latch and the loop's own end: a lane there came + // past the break in that pass, so the lanes active there (each block's + // are its immediate dominator's, or fewer) are among those that stayed. + let below_stay = |mut b: usize| loop { + if b == stay { + break true; + } + let up = plan.idom.get(b).copied().unwrap_or(usize::MAX); + if b == h || up == b || up == usize::MAX { + break false; + } + b = up; + }; + if !below_stay(latch) || !below_stay(ending) { + return None; + } + // The loop's own end reaches `exit` directly, or through one block + // only it enters. + let mut exit_preds = eff_preds(exits, &plan.dead_blocks, exit); + exit_preds.sort_unstable(); + let through = if after == exit { + ending + } else { + if exits[after] != LaneExit::Jump(exit) + || eff_preds(exits, &plan.dead_blocks, after) != [ending] + || !p.blocks[after].phis.is_empty() + || plan.exits.contains_key(&after) + || plan.in_diamond.contains(&after) + || plan.skip_joins.contains_key(&after) + || plan.diamond_joins.contains_key(&after) + || plan.lockstep_exits.contains_key(&after) + { + return None; + } + after + }; + let mut want = vec![breaking, through]; + want.sort_unstable(); + if exit_preds != want + || rpo[exit] <= rpo[h] + || plan.lockstep_exits.contains_key(&exit) + || plan.diamond_joins.contains_key(&exit) + || plan.skip_joins.contains_key(&exit) + || plan.skip_bodies.contains_key(&exit) + || plan.early_conts.contains_key(&exit) + { + return None; + } + // A lane that broke keeps its vector registers, each write being + // guarded by the lanes still active. It keeps nothing else the loop + // makes: so none of that may be seen past the loop. + // + // No lane mask is joined at `exit` (a mask is a function of what each + // edge carries, and the lanes that broke would read the other edge's), + // and none written in the loop is read after it (a compare there is made + // again in every pass, of scalars that change). + let is_mask = |v: &Value| st.masks.contains_key(v) || st.highs.contains_key(v); + let is_mask_reg = + |r: Reg| matches!(r, Reg::S(k) if [EXEC, EXEC + 1, VCC, VCC + 1].contains(&k)); + if p.blocks[exit] + .phis + .iter() + .any(|phi| is_mask(&phi.value) || is_mask_reg(phi.reg)) + { + return None; + } + // No scalar the loop writes is read after it, as for + // `match_lockstep_loop`: the console wave leaves once its every lane + // broke, and here it runs the loop to its own end. The block the loop's + // own end leaves through is run by the lanes that never broke, as on + // the console: it may read them. + let mut inside = body.clone(); + inside.insert(through); + let mut written: Set = Set::default(); + for &b in &inside { + let block = &p.blocks[b]; + written.extend( + block + .phis + .iter() + .filter(|phi| matches!(phi.reg, Reg::S(_) | Reg::Scc) || is_mask(&phi.value)) + .map(|phi| phi.value), + ); + for inst in &block.insts { + // Scalar code runs whatever lanes are active: no scalar effect + // may be in a pass the console wave does not make. + let name = inst.name(); + if name.starts_with("s_store") + || name.starts_with("s_atomic") + || name.starts_with("s_buffer_store") + || name.starts_with("s_buffer_atomic") + || name.starts_with("s_sendmsg") + { + return None; + } + written.extend( + inst.writes + .iter() + .filter(|(r, v)| matches!(r, Reg::S(_) | Reg::Scc) || is_mask(v)) + .map(|w| w.1), + ); + } + } + if read_outside(p, plan, &inside, &written) { + return None; + } + Some(BreakLoop { + breaking, + stay, + exit, + latch, + body: body.clone(), + }) +} + fn post_dominators(exits: &[LaneExit]) -> Vec> { let n = exits.len(); let words = n.div_ceil(64);