From 13b4a79d94bf41011357afa2491a184ec5e88f14 Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Tue, 24 Nov 2026 15:54:58 +0100 Subject: [PATCH] Recompiler: one skip variable for all forward jumps of structured code Every forward jump out of nested structured code had its own flag, and the code after it ran under `if (!(flag_a || flag_b || ...))` over every jump pending at that level, written again after each block that raised another. In a long run of crossing jumps that is quadratic: a retail compute program of 76 699 instructions had 10 877 such guards of up to 600 flags, 95 of its 147 MB of HLSL. At most one of these jumps is taken at a time: once one is, no code runs until its target. They now share one variable holding the taken jump's target (0: none). A guard is `xcl_skip == 0u` (plus the targets inside a loop it enters), a target clears the variable if it is the one taken, and a loop is left with one `if (xcl_skip != 0u) break;` after its `continue`. That program's HLSL goes from 147 MB to 51 MB. Other programs barely change (a retail pack's compute programs: 6.11 GB to 6.01 GB). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/mod.rs | 78 +++++++++++++++++++----------- crates/xcl/src/gpu/recomp/tests.rs | 53 ++++++++++++++++++++ 2 files changed, 103 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 0f4a9049d2..a196e6cc41 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -7,8 +7,8 @@ //! * structured form where possible (DXC compiles it much faster): forward skips as `if`, //! if / else, loops with the back edge at their end (also entered in the middle: rotated), //! and any other forward jump – loop breaks, jumps past a join, s_endpgm before the end – -//! as a skip flag (`xcl_skip_`: set at the jump, the code up to the target runs -//! under `if (!flag)`, loops `break`); retail pack: 90% of the programs need no `pc`, +//! as a skip (`xcl_skip` = the target: set at the jump, the code up to the target runs +//! under `if (xcl_skip == 0u)`, loops `break`); retail pack: 90% of the programs need no `pc`, //! * SGPRs, VCC, EXEC, M0 and SCC are ordinary variables that every lane computes alike //! (uniform); lane masks produced by vector instructions come from `WaveActiveBallot`, //! * VGPRs are per-lane variables; vector writes are masked by the lane's EXEC bit, @@ -588,7 +588,7 @@ type MemoKey = (u64, u64, Option, usize, Conts, Vec); struct Conts { /// the innermost one: a jump back to it is `continue` inner: Option, - /// the ones around that: a jump back to one sets its flag (`skip_flag` of the head), which + /// the ones around that: a jump back to one is a skip to the head (`skip_id`), which /// leaves the loops inside it and is `continue` there outer: Vec, } @@ -672,16 +672,32 @@ const CONT: u64 = u64::MAX - 1; /// run out of stack). const MAX_NEST: usize = 24; -/// Flag of a forward jump out of nested structured code: set at the jump, every level skips -/// its following code while it is set, cleared where its target starts. -fn skip_flag(t: u64) -> String { +/// Forward jumps out of nested structured code share one variable, `xcl_skip`: the jump sets it +/// to its target (`skip_id`), every level skips its following code while it is not 0, and it +/// is cleared where the target starts. At most one such jump is taken at a time: once one is, +/// no code runs until its target, so no other one can be. A level's guard is therefore +/// `xcl_skip == 0u` whatever jumps are pending there. One flag per target made it an `||` of +/// all of them, written again after every block that raised another (a retail compute program: +/// 10 877 such guards of up to 600 flags, 95 of its 147 MB of HLSL). +fn skip_id(t: u64) -> String { if t == END { - "xcl_skip_end".into() + "0xFFFFFFFFu".into() } else { - format!("xcl_skip_{t:x}") + // (+1: a loop at offset 0 may be continued through a skip to its head; 0 is "none") + format!("{}u", t + 1) } } +/// The jump to `t` was taken. +fn skip_taken(t: u64) -> String { + format!("xcl_skip == {}", skip_id(t)) +} + +/// Ends the jump to `t` if it is the one taken (nothing otherwise). +fn skip_clear(t: u64) -> String { + format!("if ({}) xcl_skip = 0u;", skip_taken(t)) +} + /// One item of a structured level. #[derive(Clone, Copy, Debug)] enum Item { @@ -973,35 +989,41 @@ fn emit_structured( Item::Loop { a, b, entry: None, .. } => enter_loop(&mut pending, a, b), _ => BTreeSet::new(), }; + // the target of a taken jump: it ends here, outside the guard that skipped up to here + if resolved { + if guard.take().is_some() { + body.push_str(&format!("{pad}}}\n")); + } + body.push_str(&format!("{pad}{}\n", skip_clear(s))); + } if guard.as_ref() != Some(&pending).filter(|p| !p.is_empty()) { if guard.take().is_some() { body.push_str(&format!("{pad}}}\n")); } if !pending.is_empty() { - let cond: Vec = pending.iter().map(|&t| skip_flag(t)).collect(); - body.push_str(&format!("{pad}if (!({})) {{\n", cond.join(" || "))); + // the taken jump, if any, is one of `pending` or goes into the loop (`inner`) + let into: String = inner.iter().map(|&t| format!(" || {}", skip_taken(t))).collect(); + body.push_str(&format!("{pad}if (xcl_skip == 0u{into}) {{\n")); guard = Some(pending.clone()); } } let d = depth + guard.is_some() as usize; let ipad = " ".repeat(d); - if resolved { - body.push_str(&format!("{ipad}{} = false;\n", skip_flag(s))); - } let raised: BTreeSet = match it { Item::Loop { a, b, latch, entry } => { body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n")); let (lcont, lin) = if entry.is_none() { (cont.enter(Some(a)), &inner) } else { (cont.enter(None), &none) }; let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, &lcont, lin, d + 1, blocks, flags); - for &t in &r { - if t == latch && latch != b { - body.push_str(&format!("{ipad} {} = false;\n", skip_flag(t))); - } else if t == a { - // `continue` from a loop inside this one - body.push_str(&format!("{ipad} if ({0}) {{ {0} = false; continue; }}\n", skip_flag(t))); - } else { - body.push_str(&format!("{ipad} if ({}) break;\n", skip_flag(t))); - } + if latch != b && r.contains(&latch) { + body.push_str(&format!("{ipad} {}\n", skip_clear(latch))); + } + if r.contains(&a) { + // `continue` from a loop inside this one + body.push_str(&format!("{ipad} if ({}) {{ xcl_skip = 0u; continue; }}\n", skip_taken(a))); + } + // any other jump taken leaves the loop + if r.iter().any(|&t| t != a && !(t == latch && latch != b)) { + body.push_str(&format!("{ipad} if (xcl_skip != 0u) break;\n")); } if latch != b { r.remove(&latch); @@ -1017,7 +1039,7 @@ fn emit_structured( if let Some(u) = entry { // rotated: the head after the latch, falling into the next iteration for t in emit_structured(c, em, body, a, u, None, nest + 1, &cont.enter(None), &none, d + 1, blocks, flags) { - body.push_str(&format!("{ipad} {} = false;\n", skip_flag(t))); + body.push_str(&format!("{ipad} {}\n", skip_clear(t))); } } body.push_str(&format!("{ipad}}}\n")); @@ -1051,8 +1073,8 @@ fn emit_structured( Some(t) => { flags.insert(t); match flow { - emit::Flow::Cond(cond, _) => body.push_str(&format!("{ipad}if ({cond}) {} = true;\n", skip_flag(t))), - _ => body.push_str(&format!("{ipad}{} = true;\n", skip_flag(t))), + emit::Flow::Cond(cond, _) => body.push_str(&format!("{ipad}if ({cond}) xcl_skip = {};\n", skip_id(t))), + _ => body.push_str(&format!("{ipad}xcl_skip = {};\n", skip_id(t))), } BTreeSet::from([t]) } @@ -1118,7 +1140,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d if let Some(x) = structured_span(c, i, hi) { body.push_str(&format!("{pad}if (pc == {start}u) {{\n")); for t in emit_structured(c, em, body, start, x, None, 0, &Conts::default(), &BTreeSet::new(), depth + 1, blocks, flags) { - body.push_str(&format!("{pad} {} = false;\n", skip_flag(t))); + body.push_str(&format!("{pad} {}\n", skip_clear(t))); } let next = if x == u64::MAX || !c.starts.contains(&x) { "0xFFFFFFFFu".to_string() } else { format!("{x}u") }; body.push_str(&format!("{pad} pc = {next};\n{pad}}}\n")); @@ -1461,8 +1483,8 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags); } - for &t in &flags { - body.push_str(&format!(" bool {} = false;\n", skip_flag(t))); + if !flags.is_empty() { + body.push_str(" uint xcl_skip = 0u;\n"); } body.push_str(&code); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 5a8d735396..e537c659b1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -7589,3 +7589,56 @@ fn jumps_to_outer_loop_heads_are_structured() { println!("{structured} of 120 programs structured ({entered} jumps into a loop), {ran} run both ways"); assert!(structured >= 100 && entered > 20, "{structured} structured, {entered} jumps into loops"); } + +/// Forward jumps whose ranges cross (from block k to target k, every target after every jump) +/// cannot nest as `if`s: each one is a skip, all of them pending at once. The code between them +/// is guarded by one test of the shared skip variable, not by one test per pending jump (the +/// guard after the k-th jump listed all k: quadratic, 95 of a retail program's 147 MB of HLSL), +/// and the program computes what the block dispatcher computes. +#[test] +fn crossing_forward_jumps_guard_in_linear_size() { + let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let build = |n: usize| -> Vec { + let mut code: Vec = Vec::new(); + let mut jumps = Vec::new(); + for k in 0..n { + // s1 += 1; SCC = bit k % 8 of s0 + code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)])); + code.extend(i("S_BITCMP1_B32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128 + (k as u64 % 8))])); + jumps.push(code.len()); + code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0)])); + } + for &at in &jumps { + // target k: s2 ^= s1 + k + let d = ((code.len() - at) / 4 - 1) as u16; + code[at..at + 2].copy_from_slice(&d.to_le_bytes()); + code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 1)])); + code.extend(i("S_XOR_B32", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 2), ("SSRC1", 129)])); + } + code.extend(i("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)])); + code + }; + let skips = |n: usize| translate(&build(n), &Options::default()).unwrap().hlsl.matches("xcl_skip").count(); + let (a, b) = (skips(40), skips(160)); + assert!(a > 0, "the crossing jumps are skips"); + assert!(b <= 5 * a, "uses of the skip variable grow linearly with the jumps: {a} for 40, {b} for 160"); + + // and they skip what they should: the same state as the dispatcher, for several jump patterns + if !gpu_waves().contains(&true) { + return; + } + let code = build(24); + let t = |s: bool| translate(&code, &Options { structured: s, ..Options::default() }).unwrap(); + let (a, b) = (t(true), t(false)); + assert!(!a.hlsl.contains("if (pc =="), "structured"); + let mem: Vec = code.chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + let dxil = |h: &str| super::dxc::compile(h, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e} +{h}")); + let (da, db) = (dxil(&a.hlsl), dxil(&b.hlsl)); + for s0 in [0u32, 1, 0x5A, 0xA5, 0xFF, 0x80] { + let mut st = KernelState::default(); + st.sgpr[0] = s0; + let (u, w) = (runner::run(&da, &st, &mem).unwrap(), runner::run(&db, &st, &mem).unwrap()); + assert_eq!(&u.sgpr[..3], &w.sgpr[..3], "s0={s0:#x}"); + } +}