diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b84298be5e..f508ecba89 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -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}; @@ -78,9 +78,13 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let mut ids: HashMap<(Vec, &'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 = if lw.region_budgets { crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)) } else { Vec::new() }; 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(®ions, 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); @@ -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 = if lw.region_budgets { crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)) } else { Vec::new() }; + 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); @@ -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(®ions, 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); @@ -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])?; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index e0bb2e8935..287fbf8484 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -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| 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 { 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(); @@ -210,7 +249,7 @@ fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() { let code = two_segments(8192); let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; - let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len(); + let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only, true).unwrap().dxil.len(); let (compact, plain) = (size(true), size(false)); assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves"); } diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..ef85fc5e61 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -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; @@ -91,39 +91,39 @@ pub fn compact_nest_tag() -> Option { /// `translate_full` in the compact form (`compact = true`) or the plain one. #[cfg(test)] pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result { - translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32, true) } /// `translate_full` in the compact form with an explicit dispatch nesting policy. #[cfg(test)] pub fn translate_full_nested(code: &[u8], o: KernelOptions, nest: super::compact::Nest) -> Result { - translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32, true) } pub fn translate_full(code: &[u8], o: KernelOptions) -> Result { - translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32, true) } /// A mesh-mode (NGG) program: the first pass that writes one record per group into /// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result { - translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0) + translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0, true) } /// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result { - translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0) + translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0, true) } /// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result { - translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0) + translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0, true) } /// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per /// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result { - translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0, true) } /// The entry ABI. @@ -139,13 +139,21 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { - translate_compute_on(code, o, cs, true) + translate_compute_on(code, o, cs, true, true) } -/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables. -pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result { +/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables, +/// and one whose compute programs keep the single loop budget (`recomp::Options::region_budgets`, +/// `pso::region_budgets`) passes `region_budgets` false. +pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool, region_budgets: bool) -> Result { let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; - translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) + translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables, region_budgets) +} + +/// `translate_compute_on` in the compact form (`compact = true`) or the plain one. +#[cfg(test)] +pub fn translate_compute_as(code: &[u8], o: KernelOptions, cs: &CsInterface, compact: bool, region_budgets: bool) -> Result { + translate_entry(code, o, Entry::Compute(cs.clone()), Some(compact), None, super::compact::TABLE_WORDS_WAVE32, region_budgets) } fn translate_entry( @@ -155,6 +163,7 @@ fn translate_entry( compact: Option, nest: Option, tables: usize, + region_budgets: bool, ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs @@ -162,7 +171,7 @@ fn translate_entry( std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables, region_budgets)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -193,6 +202,7 @@ fn translate_on_this_thread( compact: Option, nest: Option, tables: usize, + region_budgets: bool, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -209,6 +219,8 @@ fn translate_on_this_thread( let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + // a compute program's region budgets only where the caller wants them (`compact` reads this too) + lw.region_budgets &= kernel || region_budgets; let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); @@ -343,6 +355,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 lw.region_budgets { + 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); @@ -358,8 +377,19 @@ 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(®ions, 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); @@ -367,6 +397,11 @@ fn translate_on_this_thread( 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); @@ -553,6 +588,7 @@ impl Lw { guard_override: None, mask_override: None, local_masks: false, + region_budgets: kernel || cs.is_some(), exchange_error: None, pc: 0, }; diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..b5defac984 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -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 { @@ -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 { @@ -264,6 +271,9 @@ pub struct Lw { /// when it is never read whole. Set by a caller that reads back only each lane's own bit /// (the per-lane form's bridge), so no exchange meets the other half. pub local_masks: bool, + /// the program's loop regions get their own budgets (`recomp::budget_regions`): kernels, + /// and compute programs unless the adapter's are kept on one (`kernel::translate_compute_on`) + pub region_budgets: bool, } impl Lw { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..793b24fb53 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -528,11 +528,15 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// a compute program's loop regions get their own budgets ([`budget_regions`]). false: it + /// keeps the one budget of the other stages (`pso::region_budgets`: an AMD adapter, whose + /// shader compiler crashed on compute programs with region budgets, #2947) + pub region_budgets: bool, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, region_budgets: true } } } @@ -565,6 +569,8 @@ struct Ctx<'a> { starts: &'a BTreeSet, 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 @@ -647,6 +653,55 @@ 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 iterations a region and all the regions of a program get in HLSL when the loop budget +/// is `budget` ([`LOOP_BUDGETS_PER_REGION`], [`LOOP_BUDGETS_IN_ALL`]; saturating). A switch for +/// the budget (`XCL_LOOP_BUDGET`, #1284) scales the region budgets by passing its value here: +/// without that they would stay at 2 and 4 times 65 536 whatever it says. (The direct +/// translator has its own `dxil::lower::LOOP_BUDGET`, which no switch changes.) +pub(crate) fn region_budget_limits(budget: u32) -> (u32, u32) { + (budget.saturating_mul(LOOP_BUDGETS_PER_REGION), budget.saturating_mul(LOOP_BUDGETS_IN_ALL)) +} + +/// 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 { + 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--;", + region_budget_limits(1 << 16).0 + ), + 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), @@ -656,7 +711,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) { @@ -1098,7 +1153,7 @@ fn emit_structured( } let raised: BTreeSet = 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 { @@ -1219,7 +1274,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); @@ -1597,13 +1652,20 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = 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, and compute programs where `region_budgets` is off. + let regions = if matches!(opt.mode, Mode::Kernel) || (matches!(opt.mode, Mode::Compute(_)) && opt.region_budgets) { + 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: ®ions, 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: ®ions, 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) @@ -1619,6 +1681,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } 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", region_budget_limits(1 << 16).1)); + } for &t in &flags { body.push_str(&format!(" bool {} = false;\n", skip_flag(t))); } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5d000775ef..b54c2c2ce4 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -118,6 +118,37 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// The PCI vendor id of AMD's adapters (`DXGI_ADAPTER_DESC1::VendorId`). +const VENDOR_AMD: u32 = 0x1002; + +/// The vendor of the adapter this process translates for; 0 until `note_adapter_vendor`. +static ADAPTER_VENDOR: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// Who creates the D3D12 device says which vendor's adapter it is on, before anything is +/// translated for it (`region_budgets`). +pub fn note_adapter_vendor(vendor: u32) { + ADAPTER_VENDOR.store(vendor, std::sync::atomic::Ordering::Relaxed); +} + +/// Whether compute programs get a loop budget per loop region (`Options::region_budgets`). +/// Not on an AMD adapter: its shader compiler crashed on retail compute programs with region +/// budgets (`amdxc64.dll`, an RX 6800, #2874 / #2947), so there they keep the single budget, +/// as before region budgets and as the graphics stages do. `XCL_REGION_BUDGETS=1` gives them +/// to an AMD adapter too, `=0` takes them from every adapter. Compute shaders are cached by +/// it, in memory (`ShaderKey`) and on disk (`translated::budget_identity`). +pub fn region_budgets() -> bool { + static ENV: OnceLock> = OnceLock::new(); + region_budgets_for(ENV.get_or_init(|| std::env::var("XCL_REGION_BUDGETS").ok()).as_deref(), ADAPTER_VENDOR.load(std::sync::atomic::Ordering::Relaxed)) +} + +fn region_budgets_for(switch: Option<&str>, vendor: u32) -> bool { + match switch.map(str::trim) { + Some("1") => true, + Some("0") => false, + _ => vendor != VENDOR_AMD, + } +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); @@ -163,6 +194,7 @@ pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wa sampler_base, windows, split_wave64, + region_budgets: stage != Stage::Compute || region_budgets(), cache_dir: dxc::cache_dir(), }; // with `XCL_DIRECT_DXIL` the disk entries live under their own identity (backend tag, @@ -219,6 +251,17 @@ mod translated { } } + /// `ident` for a `stage` program when compute programs keep the single loop budget + /// (`pso::region_budgets` false: an AMD adapter, or `XCL_REGION_BUDGETS=0`): those are other + /// translations, under an identity of their own, so a cache directory that an AMD and + /// another adapter both fill gives neither the other's. Zero (no disk cache) stays zero. + pub(super) fn budget_identity(ident: u64, stage: Stage, region_budgets: bool) -> u64 { + if ident == 0 || region_budgets || stage != Stage::Compute { + return ident; + } + identity_for(&ident.to_string(), "xcl-single-loop-budget") + } + /// The direct translator's version: `TRANSLATOR_VERSION` and the hash of its sources (build.rs). pub(super) fn direct_version(version: u32, source: &str) -> u64 { identity_for(source, &version.to_string()) @@ -486,7 +529,7 @@ mod translated { split: bool, translate: impl FnOnce() -> Result<(Compiled, bool), String>, ) -> Result { - cached_rerouted(dir, identity(), direct_output(), blob, stage, sampler_base, windows, split, translate) + cached_rerouted(dir, budget_identity(identity(), stage, super::region_budgets()), direct_output(), blob, stage, sampler_base, windows, split, translate) } /// What the direct translator's output depends on besides the HLSL path's identity: its @@ -732,6 +775,8 @@ struct ShaderKey { sampler_base: u32, windows: u32, split_wave64: bool, + /// a compute program's: with loop region budgets (`region_budgets`); true for the others + region_budgets: bool, cache_dir: PathBuf, } @@ -972,7 +1017,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; + let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64, region_budgets())?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } @@ -1018,7 +1063,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, return Err("an FSPX (driver) container in a graphics slot".into()); } let cs = super::CsInterface::from_rsrc2(f.threads, f.rsrc2); - let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, region_budgets: region_budgets(), ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1047,7 +1092,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, region_budgets: region_budgets(), ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1152,6 +1197,7 @@ fn console_mesh_with( sampler_base: 0, windows, split_wave64: split, + region_budgets: true, cache_dir: cache_dir.to_path_buf(), }; let from_disk = || translated::cached(cache_dir, blob, Stage::Mesh, 0, windows, split, || compile_one().map(|c| (c, false))); @@ -1659,6 +1705,7 @@ mod shader_cache_tests { sampler_base: 0, windows: 1, split_wave64: false, + region_budgets: true, cache_dir: "cache".into(), } } @@ -1807,6 +1854,10 @@ mod shader_cache_tests { windows: 2, ..original.clone() }, + ShaderKey { + region_budgets: false, + ..original.clone() + }, ShaderKey { cache_dir: "other cache".into(), ..original.clone() @@ -1986,6 +2037,35 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + /// Compute programs keep the single loop budget on an AMD adapter (#2947) unless + /// `XCL_REGION_BUDGETS` says otherwise, and their disk entries are then others. + #[test] + fn region_budgets_are_off_on_amd_and_change_the_compute_identity() { + for vendor in [0, 0x10de, 0x8086] { + assert!(region_budgets_for(None, vendor)); + assert!(!region_budgets_for(Some("0"), vendor)); + } + assert!(!region_budgets_for(None, VENDOR_AMD)); + assert!(region_budgets_for(Some("1"), VENDOR_AMD)); + assert!(region_budgets_for(Some(" 1 "), VENDOR_AMD)); + assert!(!region_budgets_for(Some("on"), VENDOR_AMD), "anything else leaves it to the adapter"); + assert!(region_budgets_for(Some(""), 0x10de)); + + use translated::budget_identity; + let ident = translated::identity_for("source", "toolchain"); + let single = budget_identity(ident, Stage::Compute, false); + assert_ne!(single, ident); + assert_ne!(single, 0); + assert_eq!(budget_identity(ident, Stage::Compute, true), ident, "with region budgets the entries are the ones of before"); + for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert_eq!(budget_identity(ident, stage, false), ident, "{stage:?} has no region budgets to lose"); + } + assert_eq!(budget_identity(0, Stage::Compute, false), 0, "no disk cache stays none"); + // the entries of the two live in different files + let dir = std::path::Path::new("cache"); + assert_ne!(translated::file(dir, single, b"a", Stage::Compute, 0, 1, false), translated::file(dir, ident, b"a", Stage::Compute, 0, 1, false)); + } + #[test] fn shader_cache_bypasses_debug_overrides() { for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_DXIL_NO_OPT"] { diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 34b5c65201..09fccf3a91 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -99,6 +99,7 @@ fn init() -> Result { .into_iter() .next() .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + super::pso::note_adapter_vendor(desc.VendorId); (a, crate::gpu::adapter::name(&desc)) }; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(e)?; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..2be2375209 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1426,6 +1426,160 @@ fn gpu_scalar_loop_and_scc() { assert_eq!((r.sgpr[41], r.sgpr[42], r.sgpr[43]), (48, 33, u32::MAX), "flbit_i64 high-then-low scan"); } +/// A spin of `spin` tries (a retail FSR pass polls a flag up to 0x10000 times, the loop budget), +/// inside an outer loop that runs once when `nested` (as in that pass), then a loop of `n` +/// iterations, then `s2 = 7`. +fn spin_then_loop(spin: u32, n: u32, nested: bool) -> Vec { + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + let mut v = i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None); // s0 = 0 + if nested { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None)); // outer: s3 += 1 + } + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); // spin: s0 += 1 + 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)); // → spin + if nested { + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None)); // until s3 == 1 + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None)); // → outer + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None)); // s1 = 0 + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); // loop: s1 += 1 + 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)); // → loop + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None)); // s2 = 7 + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +/// A program's own spin that gives up at the loop budget, or just before it, must not leave the +/// loops after it short of iterations: the FSR pass then published a flag built from a register +/// its main loop never set, and the pass waiting on it spun for 260 ms a frame. Both HLSL forms. +#[test] +fn gpu_a_loop_after_a_spin_to_the_budget_still_runs() { + if !gpu_ready() { + return; + } + for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] { + let code = spin_then_loop(spin, n, nested); + for structured in [true, false] { + let opt = Options { structured, ..runner::options(Mode::Kernel) }; + let t = translate(&code, &opt).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + let what = format!("spin {spin:#x}, loop {n}, nested {nested}, structured {structured}"); + assert_eq!(r.sgpr[0], spin, "{what}: the spin ran to its own end"); + assert_eq!((r.sgpr[1], r.sgpr[2]), (n, 7), "{what}: the loop after it ran all its iterations"); + } + } +} + +/// Loops that never end still stop: four budgets in all, then every loop leaves. (The direct +/// translator ends the program where a budget runs out, so this is the HLSL path's.) +#[test] +fn gpu_endless_loops_in_many_regions_stop_after_four_budgets() { + if !gpu_ready() { + return; + } + // six regions, each `s0 += 1` until s0 == 0 (2^32 tries); s1 counts the regions reached + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..6 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let t = translate(&prog(&list), &runner::options(Mode::Kernel)).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + assert_eq!(r.sgpr[1], 6, "every region was reached"); + assert_eq!(r.sgpr[0], super::LOOP_BUDGETS_IN_ALL << 16, "four budgets of iterations in all"); +} + +/// Per-region loop budgets (`xcl_bown` / `xcl_btotal`) are compute-only: Compute and Kernel +/// modes emit them for multi-region loops, while Pixel and Mesh stages keep the single-budget +/// CFG (avoiding multi-PHI mesh loop headers that crash AMD LLPC). +#[test] +fn per_region_loop_budgets_are_compute_only() { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..2 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 130)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let code = prog(&list); + + let cs = super::CsInterface { threads: [64, 1, 1], ..Default::default() }; + let ps = super::PsInterface::default(); + let ms = super::MsInterface { threads: 64, max_vertices: 64, max_primitives: 64, ..Default::default() }; + + for mode in [Mode::Kernel, Mode::Compute(cs.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("xcl_bown") && t.hlsl.contains("xcl_btotal"), "compute/kernel should emit per-region budgets"); + } + for mode in [Mode::Pixel(ps), Mode::Mesh(ms.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(!t.hlsl.contains("xcl_bown") && !t.hlsl.contains("xcl_btotal"), "pixel/mesh must not emit per-region budgets"); + } + + // Direct DXIL compute & mesh both translate cleanly for a multi-region loop program. + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + assert!(!crate::gpu::dxil::kernel::translate_compute(&code, o, &cs).unwrap().dxil.is_empty()); + assert!(!crate::gpu::dxil::kernel::translate_mesh(&code, o, &ms).unwrap().dxil.is_empty()); +} + +/// `regions` loops one after the other, each `s0 += 1` while s0 < 2. +fn loops_in_a_row(regions: usize) -> Vec { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..regions { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 130)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + prog(&list) +} + +/// With `Options::region_budgets` off (`pso::region_budgets`: an AMD adapter, whose compiler +/// crashed on compute programs with region budgets, #2947) a compute program keeps the single +/// budget, in HLSL and in both direct forms; a kernel keeps its regions either way. +#[test] +fn a_compute_program_without_region_budgets_keeps_the_single_budget() { + let code = loops_in_a_row(2); + let cs = super::CsInterface { threads: [64, 1, 1], ..Default::default() }; + let hlsl = |mode: Mode, region_budgets: bool| translate(&code, &Options { mode, region_budgets, ..Default::default() }).unwrap().hlsl; + + let with = hlsl(Mode::Compute(cs.clone()), true); + assert!(with.contains("xcl_bown") && with.contains("xcl_btotal"), "region budgets by default"); + assert_eq!(with.matches(super::LOOP_GUARD).count(), 0); + let without = hlsl(Mode::Compute(cs.clone()), false); + assert!(!without.contains("xcl_bown") && !without.contains("xcl_btotal"), "no region budgets when they are off"); + assert_eq!(without.matches(super::LOOP_GUARD).count(), 2, "both loops spend the single budget"); + assert!(hlsl(Mode::Kernel, false).contains("xcl_bown"), "kernels are not compute programs"); + + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let one = loops_in_a_row(1); + for compact in [false, true] { + let direct = |code: &[u8], region_budgets: bool| crate::gpu::dxil::kernel::translate_compute_as(code, o, &cs, compact, region_budgets).unwrap().dxil; + let (with, without) = (direct(&code, true), direct(&code, false)); + assert!(without.len() < with.len(), "compact {compact}: {} B without the region guards, {} B with them", without.len(), with.len()); + assert_eq!(direct(&one, true), direct(&one, false), "compact {compact}: one region has no region budget to lose"); + } +} + +/// A region gets two loop budgets and all of them four, of whatever the loop budget is +/// (`region_budget_limits`; `XCL_LOOP_BUDGET` of #1284 is to pass its value there), and the +/// default's HLSL is the text of before. +#[test] +fn region_budgets_are_two_and_four_loop_budgets() { + use super::region_budget_limits as f; + assert_eq!(f(1 << 16), (131_072, 262_144)); + assert_eq!(f(4096), (8192, 16_384)); + assert_eq!(f(1), (2, 4)); + assert_eq!(f(0x6000_0000), (0xC000_0000, u32::MAX)); + assert_eq!(f(u32::MAX), (u32::MAX, u32::MAX)); + let hlsl = translate(&loops_in_a_row(2), &Options::default()).unwrap().hlsl; + assert!(hlsl.contains("xcl_budget = 131072u; }") && hlsl.contains("uint xcl_btotal = 262144u;\n"), "{hlsl}"); +} + #[test] fn gpu_divergence_through_exec() { if !gpu_ready() { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 19eedfe6ac..ad729ebe45 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -536,6 +536,7 @@ pub(super) fn init_with_remap(allow_driver_remap: bool) -> Result> 20); break; } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ff9c5eb851..3a64c271e2 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1497,7 +1497,8 @@ impl Pipelines { let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| e.to_string())?; crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? } else { - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + recomp::pso::note_adapter_vendor(desc.VendorId); crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? }; let most = pipeline_threads();