Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions crates/xcl/src/gpu/dxil/compact.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! The compact form: each distinct block of a program lowered once, in a loop over a table.

use super::cfg::{Cfg, Term};
use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET};
use super::lower::{ext_encoding, LResult, Lw, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL};
use super::lower_mem::VAR_TMP;
use super::module::{Block, Pred, Value};
use std::collections::{BTreeSet, HashMap};
Expand Down Expand Up @@ -78,9 +78,13 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option<Plan> {
let mut ids: HashMap<(Vec<u64>, &'static str), u32> = HashMap::new();
let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new());
let mut falls = true;
// a loop head's guard names its loop region: heads of two regions are two classes
let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts));
for (n, &b) in order.iter().enumerate() {
let blk = &cfg.blocks[b];
let mut key = vec![cfg.headers.contains(&b) as u64];
let head = cfg.headers.contains(&b);
let region = if head { crate::gpu::recomp::budget_region(&regions, blk.pc).unwrap_or(0) as u64 } else { 0 };
let mut key = vec![head as u64 + region];
for &i in &blk.insts {
let d = &cfg.insts[i];
key.push(d.words.len() as u64);
Expand Down Expand Up @@ -238,6 +242,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block

let (at, to) = (lw.tmp_var(), lw.tmp_var());
let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET));
let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts));
let owner = if regions.is_empty() { None } else { Some((slot(lw, VAR_BUDGET_OWNER), slot(lw, VAR_BUDGET_TOTAL))) };
lw.s.m.set_block(head);
let b = lw.s.m.load(at, 4);
let w = lw.c(width);
Expand Down Expand Up @@ -300,8 +306,19 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block
lw.ssa.begin_log();
let blk = &cfg.blocks[p.order[r]];
if cfg.headers.contains(&p.order[r]) {
// a loop head spends the loop budget
let left = lw.s.m.load(budget, 4);
// a loop head spends the loop budget (of its region: the recompiler's `loop_guard`)
let region = owner.zip(crate::gpu::recomp::budget_region(&regions, blk.pc));
let mut left = lw.s.m.load(budget, 4);
if let Some(((own_at, total_at), r)) = region {
let own = lw.s.m.load(own_at, 4);
let other = lw.cmpc(Pred::Ne, own, r);
left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left);
let rv = lw.c(r);
lw.s.m.store(own_at, rv, 4);
let total = lw.s.m.load(total_at, 4);
let spent = lw.cmpc(Pred::Eq, total, 0);
left = lw.selc(spent, 0, left);
}
let none = lw.cmpc(Pred::Eq, left, 0);
let (out, body) = (lw.block(Some(1)), lw.block(Some(1)));
lw.cond_br(none, out, body);
Expand All @@ -313,6 +330,11 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block
let one = lw.c(1);
let l = lw.sub(left, one);
lw.s.m.store(budget, l, 4);
if let Some(((_, total_at), _)) = region {
let total = lw.s.m.load(total_at, 4);
let t = lw.sub(total, one);
lw.s.m.store(total_at, t, 4);
}
}
for &i in &blk.insts {
lw.inst(&cfg.insts[i])?;
Expand Down
39 changes: 39 additions & 0 deletions crates/xcl/src/gpu/dxil/compact_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,45 @@ fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() {
assert_eq!(&c.sgpr[..2], &p.sgpr[..2]);
}

/// The direct translator's forms give each loop region its own budget as the HLSL path does
/// (`recomp::tests::gpu_a_loop_after_a_spin_to_the_budget_still_runs`).
#[test]
fn gpu_a_loop_after_a_spin_to_the_budget_still_runs_in_both_forms() {
match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) {
(Ok(_), Ok(true), Ok(_)) => {}
(a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }),
}
let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 };
for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] {
let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option<u32>| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}"));
// a spin of `spin` tries (in an outer loop that runs once when `nested`), a loop of `n`,
// then s2 = 7 (as `recomp::tests::spin_then_loop`)
let mut v = Vec::new();
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None));
if nested {
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None));
}
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None));
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(spin)));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None));
if nested {
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None));
}
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None));
v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None));
v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 255)], Some(n)));
v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None));
v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None));
v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None));
for compact in [true, false] {
let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}"));
let r = runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run");
assert_eq!(&r.sgpr[..3], &[spin, n, 7], "spin {spin:#x}, loop {n}, nested {nested}, compact {compact}");
}
}
}

fn early_outs(copies: usize) -> Vec<u8> {
let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"));
let mut v = Vec::new();
Expand Down
29 changes: 26 additions & 3 deletions crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::collections::{BTreeSet, HashMap};

use super::cfg::{Cfg, Term};
use super::container::Stage;
use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR};
use super::lower::{ComputeInit, Init, Lw, Partner, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL, VAR_SCC, VAR_VGPR};
use super::module::{Block, Pred, Value};
use super::shader::{RawUav, Shader};
use super::ssa::Ssa;
Expand Down Expand Up @@ -343,6 +343,13 @@ fn translate_on_this_thread(
None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?,
}
}
// Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh
// stages on the single-budget CFG so AMD LLPC does not trip on multi-PHI mesh loop headers.
let regions = if compute || kernel {
crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts))
} else {
Vec::new()
};
for &b in cfg.rpo.iter().filter(|_| plan.is_none()) {
let h = head(&mut lw, b);
lw.s.m.set_block(h);
Expand All @@ -358,15 +365,31 @@ fn translate_on_this_thread(
}
let end = if es_block { switch.unwrap() } else { exit };
if cfg.headers.contains(&b) {
// a lane's loop iterations are capped (the recompiler's LOOP_GUARD)
let left = lw.rd(VAR_BUDGET);
// a lane's loop iterations are capped (the recompiler's LOOP_GUARD / loop_guard)
let region = crate::gpu::recomp::budget_region(&regions, cfg.blocks[b].pc);
let mut left = lw.rd(VAR_BUDGET);
if let Some(r) = region {
let own = lw.rd(VAR_BUDGET_OWNER);
let other = lw.cmpc(Pred::Ne, own, r);
left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left);
let rv = lw.c(r);
lw.wr(VAR_BUDGET_OWNER, rv);
let total = lw.rd(VAR_BUDGET_TOTAL);
let spent = lw.cmpc(Pred::Eq, total, 0);
left = lw.selc(spent, 0, left);
}
let none = lw.cmpc(Pred::Eq, left, 0);
let cont = lw.block(Some(1));
lw.cond_br(none, end, cont);
lw.s.m.set_block(cont);
let one = lw.c(1);
let l = lw.sub(left, one);
lw.wr(VAR_BUDGET, l);
if region.is_some() {
let total = lw.rd(VAR_BUDGET_TOTAL);
let t = lw.sub(total, one);
lw.wr(VAR_BUDGET_TOTAL, t);
}
}
for &i in &cfg.blocks[b].insts {
lw.reload = reloads.get(b, i);
Expand Down
9 changes: 8 additions & 1 deletion crates/xcl/src/gpu/dxil/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ pub const VAR_XDEAD: u32 = VAR_BUDGET + 4;
pub const VAR_IMG_WRITE: u32 = VAR_BUDGET + 8;
/// loop iterations a lane may run (the recompiler's `xcl_budget`)
pub const LOOP_BUDGET: u32 = 1 << 16;
/// the loop region whose budget [`VAR_BUDGET`] holds (the recompiler's `xcl_bown`, `budget_region`)
pub const VAR_BUDGET_OWNER: u32 = VAR_BUDGET + 7;
/// iterations left to all the regions together (the recompiler's `xcl_btotal`)
pub const VAR_BUDGET_TOTAL: u32 = VAR_BUDGET + 24;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dst {
Expand Down Expand Up @@ -115,10 +119,13 @@ impl Init {
if var == VAR_BUDGET {
return s.m.i32c(LOOP_BUDGET);
}
if var == VAR_BUDGET_TOTAL {
return s.m.i32c(LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_IN_ALL);
}
if var == super::lower_round::VAR_F32_MODE {
return s.m.i32c(super::lower_round::MODE_INIT);
}
if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) {
if var == VAR_FP16_RM || var == VAR_BUDGET_OWNER || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) {
return s.m.i32c(0);
}
if var >= super::lower_mem::VAR_TMP {
Expand Down
62 changes: 57 additions & 5 deletions crates/xcl/src/gpu/recomp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,8 @@ struct Ctx<'a> {
starts: &'a BTreeSet<u64>,
leaders: &'a [u64],
loops: &'a [(u64, u64)],
/// [`budget_regions`]
regions: &'a [(u64, u64)],
/// every branch: (address of the branch, target)
edges: &'a [(u64, u64)],
/// split wave64 geometry mode: the ES's s_setpc ends the ES phase and `gs_start` is the GS
Expand Down Expand Up @@ -647,6 +649,46 @@ impl Conts {
/// leaves at its next iteration and the program runs to its end.
const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;";

/// A program with two or more loop regions gives each this many budgets of iterations
/// ([`loop_guard`]): a title's own spin capped at one budget (0x10000 tries) must fit, also
/// when it sits in an outer loop whose head spends from the same count.
pub(crate) const LOOP_BUDGETS_PER_REGION: u32 = 2;
/// ... and all of its regions together at most this many.
pub(crate) const LOOP_BUDGETS_IN_ALL: u32 = 4;

/// The outermost of [`loop_ranges`]: the program's loop regions, in order. Control only moves
/// forward from one to the next (a jump back into an earlier one would make them one range).
/// Empty for a program with fewer than two, whose guards stay [`LOOP_GUARD`].
pub(crate) fn budget_regions(loops: &[(u64, u64)]) -> Vec<(u64, u64)> {
let outer: Vec<(u64, u64)> = loops.iter().copied().filter(|&(a, b)| !loops.iter().any(|&(c, d)| (c, d) != (a, b) && c <= a && b <= d)).collect();
if outer.len() < 2 {
Vec::new()
} else {
outer
}
}

/// The region ([`budget_regions`]) of the loop headed at `head`, numbered from 1.
pub(crate) fn budget_region(regions: &[(u64, u64)], head: u64) -> Option<u32> {
regions.iter().position(|&(a, b)| a <= head && head < b).map(|k| k as u32 + 1)
}

/// The guard of the loop headed at `head`. In a program with loop regions, each region starts
/// with [`LOOP_BUDGETS_PER_REGION`] budgets, and `xcl_btotal` keeps all of them to
/// [`LOOP_BUDGETS_IN_ALL`]: a title's own spin that gives up after 0x10000 tries, the budget,
/// otherwise left every loop after it without an iteration (a retail FSR pass then published a
/// flag made from a register its main loop never set, and the pass waiting on that flag spun
/// 260 ms a frame).
fn loop_guard(regions: &[(u64, u64)], head: u64) -> String {
match budget_region(regions, head) {
Some(r) => format!(
"if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget == 0u || xcl_btotal == 0u) break; xcl_budget--; xcl_btotal--;",
LOOP_BUDGETS_PER_REGION << 16
),
None => LOOP_GUARD.to_string(),
}
}

/// Structured code longer than this many bytes per byte of program falls back to the `pc` form.
/// Each guard of the structured form lists every pending skip flag, so it grows with the
/// square of the flags: one retail program made 455 B per byte (148 MB, 14 MB as `pc` blocks),
Expand All @@ -656,7 +698,7 @@ const STRUCTURED_BYTES_PER_CODE_BYTE: usize = 128;
/// The loops the translator emits: ranges spanned by backward jumps (far jumps included),
/// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the
/// exits through `LOOP_GUARD`.
pub(super) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> {
pub(crate) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> {
let mut loops: Vec<(u64, u64)> = Vec::new();
for d in insts {
if let Some(t) = rdna2::branch_target(d) {
Expand Down Expand Up @@ -1098,7 +1140,7 @@ fn emit_structured(
}
let raised: BTreeSet<u64> = match it {
Item::Loop { a, b, latch, entry } => {
body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n"));
body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(c.regions, a)));
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 {
Expand Down Expand Up @@ -1219,7 +1261,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d
let start = c.leaders[i];
let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied();
if let Some((a, b)) = inner {
body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n"));
body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(c.regions, a)));
emit_range(c, em, body, a, b, depth + 1, blocks, flags);
body.push_str(&format!("{pad}}}\n"));
i = c.leaders.partition_point(|&l| l < b);
Expand Down Expand Up @@ -1597,13 +1639,20 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
// (optimising one big dispatcher loop took minutes on large retail programs).
let leaders: Vec<u64> = leaders.into_iter().filter(|l| starts.contains(l)).collect();
let loops = loop_ranges(&insts);
// Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh
// stages on the single-budget CFG.
let regions = if matches!(opt.mode, Mode::Compute(_) | Mode::Kernel) {
budget_regions(&loops)
} else {
Vec::new()
};
let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect();
let phase_split = gs_jump.is_some_and(|t| t.is_some()) && opt.split_wave64 && opt.wave64;
let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, phase_split, memo: Default::default() };
let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, regions: &regions, edges: &edges, phase_split, memo: Default::default() };
let mut flags = BTreeSet::new();
let mut code = String::new();
let nested = nested_loop_ranges(&insts);
let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, edges: &edges, phase_split, memo: Default::default() };
let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, regions: &regions, edges: &edges, phase_split, memo: Default::default() };
if gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&sctx, 0, u64::MAX).is_some() {
// structured control flow: plain if / loops, no block dispatch on `pc` (much
// smaller for DXC and the driver on big programs)
Expand All @@ -1619,6 +1668,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
}
emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags);
}
if !regions.is_empty() {
body.push_str(&format!(" uint xcl_bown = 0u;\n uint xcl_btotal = {}u;\n", LOOP_BUDGETS_IN_ALL << 16));
}
for &t in &flags {
body.push_str(&format!(" bool {} = false;\n", skip_flag(t)));
}
Expand Down
Loading
Loading