diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index c88ead868b..ac2c9635ec 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -119,7 +119,7 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() { let cfg = super::cfg::Cfg::build(&v).unwrap(); let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; - let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); + let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel, false); let p = super::compact::plan(&cfg, &lw).unwrap(); assert_eq!(p.order.len(), 4); assert_ne!(p.class[0], p.class[2]); diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 01a48a1b42..3076890595 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -581,3 +581,255 @@ fn gpu_direct_unaligned_multi_dword_format_store() { let got: Vec = r.mem.iter().flat_map(|v| v.to_le_bytes()).collect(); assert_eq!(&got[0xFC..0x118], &want[0xFC..0x118], "bytes 0xFC..0x118 after the store at 0x102"); } + +// ------------------------------------------------------------ s_barrier (`group_barrier`) + +/// The `s_barrier` policy follows the recompiler's (`Em::configure_round_modes`): the kernel +/// ABI keeps its group sync, one hardware wave fences, several get the safe barrier when the +/// program has an `s_barrier` (unless `XCL_SAFE_BARRIER=0`). +#[test] +fn s_barrier_policy_matches_the_recompiler() { + use super::group_barrier::{policy, SBarrier}; + assert_eq!(policy(true, None, 32, true), SBarrier::Sync, "kernel ABI"); + assert_eq!(policy(true, None, 64, true), SBarrier::Sync, "kernel ABI"); + for (threads, hw) in [(1, 32), (32, 32), (64, 64), (33, 64)] { + assert_eq!(policy(true, Some(threads), hw, true), SBarrier::Fence, "{threads} threads, wave{hw}"); + assert_eq!(policy(false, Some(threads), hw, true), SBarrier::Fence, "{threads} threads, wave{hw}"); + } + for (threads, hw) in [(33, 32), (64, 32), (128, 32), (128, 64), (1024, 64)] { + assert_eq!(policy(true, Some(threads), hw, true), SBarrier::Safe, "{threads} threads, wave{hw}"); + assert_eq!(policy(true, Some(threads), hw, false), SBarrier::Sync, "XCL_SAFE_BARRIER=0: {threads} threads, wave{hw}"); + assert_eq!(policy(false, Some(threads), hw, true), SBarrier::Sync, "no s_barrier: {threads} threads, wave{hw}"); + } +} + +fn cs(threads: [u32; 3]) -> crate::gpu::recomp::CsInterface { + crate::gpu::recomp::CsInterface { threads, user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 1 } +} + +/// Disassembly of a compute translation (validated by `translate_compute` in tests). +fn cs_dis(code: &[u8], wave64: bool, split: bool, threads: [u32; 3]) -> String { + let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let k = super::kernel::translate_compute(code, o, &cs(threads)) + .unwrap_or_else(|e| panic!("wave64 {wave64} split {split} {threads:?}: {}", &e[..e.len().min(1500)])); + super::validate::disassemble(&k.dxil).unwrap() +} + +/// `Barrier(mode)` calls (`ops::barrier`: 9 = group sync, 8 = group-shared fence). +fn barriers(dis: &str, mode: u32) -> usize { + dis.matches(&format!("@dx.op.barrier(i32 80, i32 {mode})")).count() +} + +/// Group-shared atomics that leave the live count (`atomicrmw add .., i32 -1`). +fn alive_decrements(dis: &str) -> usize { + dis.lines().filter(|l| l.contains("atomicrmw add") && l.contains("i32 -1")).count() +} + +fn gs_globals(dis: &str) -> Vec<&str> { + dis.lines().filter(|l| l.contains("addrspace(3) global")).collect() +} + +const S_BARRIER: (&str, &str, &[(&str, u64)], Option) = ("S_BARRIER", "ENC_SOPP", &[], None); + +/// (wave64, split, threads) of thread groups of several hardware waves: wave32, native +/// wave64, split wave64 with one console wave (two hardware halves) and with several. +const MULTI_WAVE: [(bool, bool, [u32; 3]); 6] = [ + (false, false, [64, 1, 1]), + (false, false, [8, 8, 1]), + (true, false, [128, 1, 1]), + (true, true, [64, 1, 1]), + (true, true, [128, 1, 1]), + (false, false, [256, 1, 1]), +]; + +/// Programs without `s_barrier` pay nothing for the safe barrier: no live count, no +/// arrival loop, no extra group-shared words. +#[test] +fn programs_without_s_barrier_have_no_safe_barrier() { + let code = prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None)]); + for (wave64, split, threads) in MULTI_WAVE { + let dis = cs_dis(&code, wave64, split, threads); + assert!(!dis.contains("cmpxchg"), "wave64 {wave64} split {split} {threads:?}:\n{dis}"); + assert_eq!(alive_decrements(&dis), 0, "wave64 {wave64} split {split} {threads:?}:\n{dis}"); + if !split { + assert!(gs_globals(&dis).iter().all(|g| !g.contains("[2 x i32]")), "wave64 {wave64} {threads:?}:\n{dis}"); + } + } + // with LDS: the program keeps the whole block (no clamp below the top words) + let lds = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None)]); + let dis = cs_dis(&lds, false, false, [64, 1, 1]); + assert!(!dis.contains("8188"), "{dis}"); +} + +/// Several hardware waves and an `s_barrier`: the live count is set up at entry (two group +/// syncs, every thread present), the `s_barrier` is the bounded arrival barrier (fences and +/// a compare-exchange, no group sync of its own), and the wave leaves the count once at the +/// end (and on giving up). +#[test] +fn multi_wave_s_barrier_is_early_exit_safe() { + if !super::group_barrier::safe_barrier_enabled() { + return; + } + let base = prog(&[]); + let one = prog(&[S_BARRIER]); + let two = prog(&[S_BARRIER, ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)], None), S_BARRIER]); + for (wave64, split, threads) in MULTI_WAVE { + let at = format!("wave64 {wave64} split {split} {threads:?}"); + let b = cs_dis(&base, wave64, split, threads); + for (code, n) in [(&one, 1), (&two, 2)] { + let dis = cs_dis(code, wave64, split, threads); + assert_eq!(barriers(&dis, 9), barriers(&b, 9) + 2, "{at}: only the entry's two group syncs:\n{dis}"); + assert_eq!(barriers(&dis, 8), barriers(&b, 8) + 2 * n, "{at}: two fences per s_barrier:\n{dis}"); + assert_eq!(dis.matches("cmpxchg").count(), 2 * n, "{at}: open the next generation, or on giving up:\n{dis}"); + assert_eq!(alive_decrements(&dis), 1 + n, "{at}: one decrement at the end, one per give-up path:\n{dis}"); + if !split { + assert_eq!(gs_globals(&dis).iter().filter(|g| g.contains("[2 x i32]")).count(), 1, "{at}: the two words of their own:\n{dis}"); + } + } + } +} + +/// `s_endpgm` before the `s_barrier`, and a loop around it (whose budget may run out): every +/// way out goes through the one decrement. +#[test] +fn safe_barrier_decrements_on_every_exit() { + if !super::group_barrier::safe_barrier_enabled() { + return; + } + let early_end = prog(&[ + ("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 1)], None), + ("S_ENDPGM", "ENC_SOPP", &[], None), + S_BARRIER, + ]); + let looped = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None), + S_BARRIER, + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 132)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None), + ]); + for (wave64, split, threads) in MULTI_WAVE { + for (name, code) in [("early s_endpgm", &early_end), ("loop", &looped)] { + let dis = cs_dis(code, wave64, split, threads); + assert_eq!(alive_decrements(&dis), 2, "{name}, wave64 {wave64} split {split} {threads:?}:\n{dis}"); + assert_eq!(dis.matches("cmpxchg").count(), 2, "{name}, wave64 {wave64} split {split} {threads:?}:\n{dis}"); + } + } +} + +/// One hardware wave: `s_barrier` is a group-shared fence (nothing to wait for), no live +/// count. +#[test] +fn single_wave_s_barrier_is_a_fence() { + let base = prog(&[]); + let code = prog(&[S_BARRIER]); + for (wave64, split, threads) in [(false, false, [32, 1, 1]), (true, false, [64, 1, 1]), (false, false, [16, 1, 1]), (true, true, [32, 1, 1])] { + let at = format!("wave64 {wave64} split {split} {threads:?}"); + let b = cs_dis(&base, wave64, split, threads); + let dis = cs_dis(&code, wave64, split, threads); + assert_eq!(barriers(&dis, 9), barriers(&b, 9), "{at}: no group sync:\n{dis}"); + assert_eq!(barriers(&dis, 8), barriers(&b, 8) + 1, "{at}: one fence:\n{dis}"); + assert!(!dis.contains("cmpxchg"), "{at}:\n{dis}"); + assert_eq!(alive_decrements(&dis), 0, "{at}:\n{dis}"); + } +} + +/// The kernel ABI (one console wave, as the HLSL kernel) keeps its group sync. +#[test] +fn kernel_s_barrier_stays_a_group_sync() { + let base = prog(&[]); + let code = prog(&[S_BARRIER]); + for (wave64, split) in [(false, false), (true, false), (true, true)] { + let o = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let b = super::validate::disassemble(&translate(&base, o).unwrap()).unwrap(); + let dis = super::validate::disassemble(&translate(&code, o).unwrap()).unwrap(); + assert_eq!(barriers(&dis, 9), barriers(&b, 9) + 1, "wave64 {wave64} split {split}:\n{dis}"); + assert!(!dis.contains("cmpxchg"), "wave64 {wave64} split {split}:\n{dis}"); + } +} + +/// With LDS the safe barrier's words are the top of the one 32 KB block (8189, 8190; the +/// split form's lane counter keeps 8191, its exchange moves below): no second group-shared +/// array past the D3D12 limit, and the program's accesses are kept off them. +#[test] +fn safe_barrier_words_live_in_the_lds_block() { + if !super::group_barrier::safe_barrier_enabled() { + return; + } + let code = prog(&[ + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None), + S_BARRIER, + ("DS_READ_B32", "ENC_DS", &[("ADDR", 1), ("VDST", 2)], None), + ]); + for (wave64, split, threads) in [(false, false, [64, 1, 1]), (true, false, [128, 1, 1]), (false, false, [8, 8, 1])] { + let at = format!("wave64 {wave64} split {split} {threads:?}"); + let dis = cs_dis(&code, wave64, split, threads); + let g = gs_globals(&dis); + assert_eq!(g.len(), 1, "{at}: only the LDS block:\n{dis}"); + assert!(g[0].contains("[8192 x i32]"), "{at}:\n{dis}"); + assert!(dis.contains("i32 8188"), "{at}: accesses to the barrier words go below them:\n{dis}"); + assert!(dis.contains("i32 8189") && dis.contains("i32 8190"), "{at}:\n{dis}"); + } + for threads in [[64, 1, 1], [128, 1, 1]] { + let dis = cs_dis(&code, true, true, threads); + let g = gs_globals(&dis); + assert_eq!(g.len(), 1, "split {threads:?}: only the LDS block:\n{dis}"); + assert!(g[0].contains("[8192 x i32]"), "split {threads:?}:\n{dis}"); + assert!(dis.contains("i32 8189") && dis.contains("i32 8190") && dis.contains("i32 8191"), "split {threads:?}:\n{dis}"); + } +} + +/// Non-split form with the safe barrier: only words 8189 and 8190 are the barrier's, so the +/// program's words 8188 and 8191 stay two words. After storing 11 and 22 to them and an +/// `s_barrier`, every thread reads both back. +#[test] +fn gpu_safe_barrier_keeps_lds_words_8188_and_8191_apart() { + use crate::gpu::recomp::runner; + if !super::group_barrier::safe_barrier_enabled() { + return; + } + const LIT: u64 = 255; + let code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", LIT)], Some(4 * 8188)), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", LIT)], Some(4 * 8191)), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 128 + 11)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128 + 22)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 3)], None), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 2), ("DATA0", 4)], None), + S_BARRIER, + ("DS_READ_B32", "ENC_DS", &[("ADDR", 1), ("VDST", 5)], None), + ("DS_READ_B32", "ENC_DS", &[("ADDR", 2), ("VDST", 6)], None), + // global memory at s0 + tid * 8: the two words read + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 128 + 3), ("VSRC1", 0)], None), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 5), ("SADDR", 0x7D)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 6), ("SADDR", 0x7D), ("OFFSET", 4)], None), + ]); + if runner::adapter().is_err() { + return runner::skip_test("no GPU"); + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + // two hardware waves each, so the safe barrier is used + let runs = [(false, 64u32, runner::wave32_supported(), "no wave32"), (true, 128, runner::wave64_supported(), "no wave64")]; + for (wave64, threads, supported, skip) in runs { + if supported != Ok(true) { + runner::skip_test(skip); + continue; + } + let o = KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }; + let csi = crate::gpu::recomp::CsInterface { user_sgprs: 2, ..cs([threads, 1, 1]) }; + let k = super::kernel::translate_compute(&code, o, &csi).unwrap_or_else(|e| panic!("wave64 {wave64}: {}", &e[..e.len().min(1500)])); + let base = 0x100usize; + let mut io = vec![0u32; 128]; + io[0] = base as u32; + let mem = vec![0u32; base / 4 + 2 * threads as usize]; + let out = runner::dispatch(&k.dxil, [1, 1, 1], &io, &mem).unwrap_or_else(|e| panic!("wave64 {wave64}: {e}")); + for (tid, read) in out[base / 4..].chunks(2).enumerate() { + assert_eq!(read, [11, 22], "wave64 {wave64} thread {tid}: LDS words 8188 and 8191"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/group_barrier.rs b/crates/xcl/src/gpu/dxil/group_barrier.rs new file mode 100644 index 0000000000..f8aeab52ab --- /dev/null +++ b/crates/xcl/src/gpu/dxil/group_barrier.rs @@ -0,0 +1,229 @@ +//! `s_barrier` for compute and mesh thread groups (the recompiler's `xcl_s_barrier`, +//! `recomp/emit.rs` `PRELUDE_SAFE_BARRIER`). +//! +//! On RDNA2, `s_endpgm` removes the exiting wave from the workgroup's barrier count, so the +//! waves still running do not wait for it at `s_barrier`. A D3D12 group sync +//! (`GroupMemoryBarrierWithGroupSync`, `bar.sync 0` on NVIDIA) waits for every hardware +//! wave of the group: one that has ended (`s_endpgm`), run out of its loop budget, or +//! diverged after a split-wave64 desync hangs the others for good. +//! +//! So a thread group of several hardware waves whose program has `s_barrier` gets a +//! bounded arrival barrier in group-shared memory instead (on unless `XCL_SAFE_BARRIER=0`): +//! `alive` counts the live hardware waves (set at entry, decremented once when a wave +//! leaves the program โ€” every exit of the translated program goes through one block); +//! `state` packs (generation: 20 bits, arrived: 12 bits) so advancing the generation +//! resets the arrivals. A single hardware wave needs no synchronization: a memory fence. + +use super::lower::{Lw, VAR_BAR_DEAD}; +use super::module::{Pred, RmwOp}; +use super::ops::{barrier, GroupShared}; +use crate::gpu::rdna2::Decoded; + +/// How `s_barrier` is lowered. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SBarrier { + /// a plain group sync (the kernel ABI: one console wave, as the HLSL kernel) + Sync, + /// one hardware wave in the group: a group-shared memory fence + Fence, + /// several hardware waves: the bounded arrival barrier + Safe, +} + +/// Rounds a waiting wave spins before it gives up (the HLSL `1u << 20`). +pub const SPIN_LIMIT: u32 = 1 << 20; + +/// With LDS, the first of the two words of the LDS block the safe barrier takes (`alive`, +/// then `state`; the split form's lane counter keeps 8191). +pub const LDS_BAR_AT: u32 = 8189; + +/// The early-exit-safe barrier is on unless `XCL_SAFE_BARRIER=0` (the recompiler's switch). +pub fn safe_barrier_enabled() -> bool { + std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") +} + +/// The program has an `s_barrier`. +pub fn has_s_barrier(insts: &[Decoded]) -> bool { + insts.iter().any(|d| d.inst.name.eq_ignore_ascii_case("S_BARRIER")) +} + +/// The recompiler's policy (`Em::configure_round_modes` / `compute_or_mesh_hw_waves`): +/// `group_threads` is Some for compute and mesh groups, `hw_lanes` the hardware wave size. +pub fn policy(has_barrier: bool, group_threads: Option, hw_lanes: u32, enabled: bool) -> SBarrier { + let Some(t) = group_threads else { return SBarrier::Sync }; + let waves = t.div_ceil(hw_lanes).max(1); + if waves == 1 { + SBarrier::Fence + } else if has_barrier && enabled { + SBarrier::Safe + } else { + SBarrier::Sync + } +} + +impl Lw { + /// Words the safe barrier takes from the top of the LDS block (`alive`, `state` at + /// 8189..=8190, below the split form's lane counter at 8191). + pub fn bar_lds_words(&self) -> u32 { + if self.sbar == SBarrier::Safe { + 2 + } else { + 0 + } + } + + /// The safe barrier's two words (after [`Lw::setup_storage`]): in the LDS block when + /// the program has one (D3D12 allows 32 KB, all of it already the LDS: + /// `Lw::lds_index` keeps the program's accesses off them), else two words of their own. + pub fn setup_barrier_storage(&mut self) { + if self.sbar != SBarrier::Safe { + return; + } + if let Some(g) = self.lds { + // split form: `setup_storage` put the exchange below them (`bar_lds_words`) + self.bar = Some((g, LDS_BAR_AT)); + } else { + let i32 = self.s.m.i32(); + let g = self.s.groupshared("xcl_bar", i32, 2); + self.bar = Some((g, 0)); + } + } + + fn bar_storage(&self) -> (GroupShared, u32) { + self.bar.expect("safe barrier storage") + } + + /// At entry (every thread of the group present, no branch yet โ€” the entry block): + /// `alive` = the group's hardware waves, `state` = 0 (`xcl_s_barrier_init`). + pub fn barrier_init(&mut self) { + if self.sbar != SBarrier::Safe { + return; + } + let (g, at) = self.bar_storage(); + // every thread stores the same 0 (no branch in the entry block) + let z = self.c(0); + let ia = self.c(at); + let pa = self.s.gs_ptr(g, ia); + self.s.m.store(pa, z, 4); + let is = self.c(at + 1); + let ps = self.s.gs_ptr(g, is); + self.s.m.store(ps, z, 4); + self.s.barrier(barrier::GROUP_SYNC); + let first = self.s.wave_is_first_lane(); + let k = self.selc(first, 1, z); + let pa = self.s.gs_ptr(g, ia); + self.s.m.atomic_rmw(RmwOp::Add, pa, k); + self.s.barrier(barrier::GROUP_SYNC); + } + + /// Where the program ends (`s_endpgm`, the end of the code, an exhausted loop budget): + /// a live wave leaves the count once (`xcl_s_barrier_exit`). + pub fn barrier_exit(&mut self) { + if self.sbar != SBarrier::Safe { + return; + } + let (g, at) = self.bar_storage(); + let dead = self.rd(VAR_BAR_DEAD); + let alive = self.cmpc(Pred::Eq, dead, 0); + let first = self.s.wave_is_first_lane(); + let go = self.land(alive, first); + let _ = self.guarded(go, &mut |lw| { + let ia = lw.c(at); + let m1 = lw.c(u32::MAX); + lw.s.gs_atomic(RmwOp::Add, g, ia, m1); + Ok(()) + }); + } + + /// `s_barrier`. + pub fn s_barrier(&mut self) { + match self.sbar { + SBarrier::Sync => self.s.barrier(barrier::GROUP_SYNC), + SBarrier::Fence => self.s.barrier(barrier::TGSM_FENCE), + SBarrier::Safe => self.safe_barrier(), + } + } + + /// The bounded arrival barrier (`xcl_s_barrier`): the wave's first lane counts the + /// wave in, then waits (bounded) until the arrivals reach the live waves or another + /// wave opened the next generation. A wave that gives up leaves the count and from + /// then on only fences. + fn safe_barrier(&mut self) { + let (g, at) = self.bar_storage(); + let ia = at; + let is = at + 1; + self.s.barrier(barrier::TGSM_FENCE); + let dead = self.rd(VAR_BAR_DEAD); + let alive = self.cmpc(Pred::Eq, dead, 0); + let first = self.s.wave_is_first_lane(); + let go = self.land(alive, first); + let ok = self.tmp_var(); + let one = self.c(1); + self.wr(ok, one); + let _ = self.guarded(go, &mut |lw| { + let i32 = lw.s.m.i32(); + let si = lw.c(is); + let ai = lw.c(ia); + let one = lw.c(1); + let z = lw.c(0); + let old = lw.s.gs_atomic(RmwOp::Add, g, si, one); + let gen = lw.lshrc(old, 12); + let g1 = lw.addc(gen, 1); + let g1 = lw.andc(g1, 0xF_FFFF); + let next = lw.shlc(g1, 12); + let pre = lw.cur(); + // lp: the generation still open? chk: all live waves in (or none)? cas: open + // the next one; tmo: count the round, give up after SPIN_LIMIT + let lp = lw.block(Some(2)); + let chk = lw.block(Some(1)); + let cas = lw.block(Some(1)); + let tmo = lw.block(Some(2)); + let fail = lw.block(Some(1)); + let ex = lw.block(Some(3)); + lw.br(lp); + lw.s.m.set_block(lp); + let n = lw.s.m.phi(i32); + lw.s.m.add_incoming(n, z, pre); + let st = lw.s.gs_atomic(RmwOp::Add, g, si, z); + let sg = lw.lshrc(st, 12); + let same = lw.cmp(Pred::Eq, sg, gen); + lw.cond_br(same, chk, ex); + lw.s.m.set_block(chk); + let live = lw.s.gs_atomic(RmwOp::Add, g, ai, z); + let none = lw.cmp(Pred::SLe, live, z); + let arrived = lw.andc(st, 0xFFF); + let all = lw.cmp(Pred::UGe, arrived, live); + let open = lw.lor(none, all); + lw.cond_br(open, cas, tmo); + lw.s.m.set_block(cas); + let orig = lw.s.gs_cmpxchg(g, si, st, next); + let won = lw.cmp(Pred::Eq, orig, st); + lw.cond_br(won, ex, tmo); + lw.s.m.set_block(tmo); + let out = lw.cmpc(Pred::UGe, n, SPIN_LIMIT); + let n1 = lw.addc(n, 1); + lw.s.m.add_incoming(n, n1, tmo); + lw.cond_br(out, fail, lp); + lw.s.m.set_block(fail); + let m1 = lw.c(u32::MAX); + lw.s.gs_atomic(RmwOp::Add, g, ai, m1); + lw.s.gs_cmpxchg(g, si, st, next); + lw.br(ex); + lw.s.m.set_block(ex); + let okp = lw.s.m.phi(i32); + let (one, z) = (lw.c(1), lw.c(0)); + lw.s.m.add_incoming(okp, one, lp); + lw.s.m.add_incoming(okp, one, cas); + lw.s.m.add_incoming(okp, z, fail); + lw.wr(ok, okp); + Ok(()) + }); + let okv = self.rd(ok); + let okf = self.s.wave_read_lane_first(okv); + let gave_up = self.cmpc(Pred::Eq, okf, 0); + let dead = self.rd(VAR_BAR_DEAD); + let dead = self.selc(gave_up, 1, dead); + self.wr(VAR_BAR_DEAD, dead); + self.s.barrier(barrier::TGSM_FENCE); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 94ce0b37d0..529b9cb0e4 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -169,7 +169,7 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact let compute = matches!(entry, Entry::Compute(_)); 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); + let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry, true); let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); @@ -218,6 +218,9 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact [1, 1, 1] } }; + // the safe `s_barrier`'s words and their initial values (entry block, whole group present) + lw.setup_barrier_storage(); + lw.barrier_init(); // the HLSL kernel loads and stores every register its emitted instructions name: all of // them in a program with branches, those up to the first s_endpgm in straight-line code let branchy = cfg.insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); @@ -365,6 +368,9 @@ fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact let tail = lw.block(Some(1)); lw.br(tail); lw.s.m.set_block(tail); + // every way out of the program (`s_endpgm`, the end of the code, an exhausted loop budget) + // comes through here: the wave leaves the safe `s_barrier`'s live count + lw.barrier_exit(); if let (Some(res), true) = (res, kernel) { store_registers(&mut lw, res); } @@ -422,8 +428,10 @@ impl Lw { /// partner. The caller then sets up the lanes for its entry (`setup_lanes*`), lowers the /// program's blocks, branches from `Block(0)` to the first of them and ends with /// [`Lw::finish`]. #1426's block walk (`translate_on_this_thread`) and the recompiler's - /// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here. - pub fn new(insts: &[Decoded], leaders: &BTreeSet, o: KernelOptions, entry: &Entry) -> Lw { + /// per-lane lowering (`recomp::lower_dxil`) both build their `Lw` here. `safe_barrier`: the + /// caller also runs the safe `s_barrier`'s setup (`setup_barrier_storage`, `barrier_init` + /// in the entry block, `barrier_exit` on the one way out; `group_barrier`). + pub fn new(insts: &[Decoded], leaders: &BTreeSet, o: KernelOptions, entry: &Entry, safe_barrier: bool) -> Lw { let split = o.wave64 && o.split; let kernel = matches!(entry, Entry::Kernel); let cs = match entry { @@ -497,6 +505,8 @@ impl Lw { mask_override: None, exchange_error: None, pc: 0, + sbar: super::group_barrier::SBarrier::Sync, + bar: None, }; { let Lw { s, ssa, init, .. } = &mut lw; @@ -537,6 +547,14 @@ impl Lw { if let (Some(t), true) = (group_threads, split) { lw.waves = t.div_ceil(64).max(1); } + // `s_barrier`: the recompiler's policy for compute and mesh (one hardware wave: a + // fence; several, with an `s_barrier`: the early-exit-safe barrier) โ€” before the storage + // (LDS words). Geometry, and a caller without the safe barrier's setup, keep the sync. + let hw_lanes = if split || !o.wave64 { 32 } else { 64 }; + let has_barrier = super::group_barrier::has_s_barrier(insts); + let barrier_threads = group_threads.filter(|_| !matches!(entry, Entry::Geometry(_))); + let safe = safe_barrier && super::group_barrier::safe_barrier_enabled(); + lw.sbar = super::group_barrier::policy(has_barrier, barrier_threads, hw_lanes, safe); if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 04491ba070..55173e0d39 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -28,7 +28,7 @@ impl Lw { // HLSL: exchange base = 8192 - slots - counters - 1 (slots = 4 ยท slot per console // wave, 2 counters each); the program's LDS stops below it let slots = 4 * self.xslot * self.waves; - let base = 8192 - slots - 2 * self.waves - 1; + let base = 8192 - slots - 2 * self.waves - 1 - self.bar_lds_words(); self.lds_top = base - 1; self.xs = Some((g, base)); self.xc = Some((g, base + slots)); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 0e270bb60d..c8eb3ed004 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -29,6 +29,8 @@ pub const VAR_WIN: u32 = VAR_BUDGET + 2; /// arrived" flag (`xcl_xk`, `xcl_x_dead`) pub const VAR_XK: u32 = VAR_BUDGET + 3; pub const VAR_XDEAD: u32 = VAR_BUDGET + 4; +/// this hardware wave has left the safe `s_barrier`'s live count (`xcl_bar_alive` false; `group_barrier`) +pub const VAR_BAR_DEAD: u32 = VAR_BUDGET + 6; /// loop iterations a lane may run (the recompiler's `xcl_budget`) pub const LOOP_BUDGET: u32 = 1 << 16; @@ -115,7 +117,7 @@ impl Init { 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 { + if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || var == VAR_BAR_DEAD { return s.m.i32c(0); } if var >= super::lower_mem::VAR_TMP { @@ -252,6 +254,10 @@ pub struct Lw { /// When set, the wave-wide mask cross-lane instructions see (DPP source lanes, /// readfirstlane, ds_swizzle / bpermute) instead of the SSA EXEC. pub mask_override: Option<(Value, Value)>, + /// how `s_barrier` is lowered (`group_barrier`) and, for the safe barrier, its two + /// group-shared words (`alive`, `state`: storage and index of `alive`) + pub sbar: super::group_barrier::SBarrier, + pub bar: Option<(super::ops::GroupShared, u32)>, } impl Lw { @@ -1003,7 +1009,7 @@ impl Lw { fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { match name { "s_barrier" => { - self.s.barrier(super::ops::barrier::GROUP_SYNC); + self.s_barrier(); Ok(()) } "s_round_mode" => { diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index a1d034e740..4e70010ec0 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -3,6 +3,7 @@ //! `recomp/emit.rs` `smem` / `mubuf` / `flat` / `ds` / `export` and //! `PRELUDE_MEM`). Accesses of disabled lanes are real branches. +use super::group_barrier::{SBarrier, LDS_BAR_AT}; use super::lower::{err, Dst, LResult, Lw, VAR_VGPR}; use super::module::{BinOp, Pred, RmwOp, Value}; use super::ops::AtomicOp; @@ -1979,14 +1980,22 @@ impl Lw { // ------------------------------------------------------------ LDS / DS - /// LDS dword index of byte address `at` (`(at >> 2) & 8191`, below the exchange words - /// in the split form). + /// LDS dword index of byte address `at` (`(at >> 2) & 8191`), kept off the words the + /// translator uses itself. Split form: clamped below the exchange words (the safe + /// barrier's are above them). Otherwise, with the safe barrier, only its two words are + /// taken: an access to one of them goes to the word below, and every other word, 8191 + /// included, stays the program's own. fn lds_index(&mut self, at: Value) -> Value { let i = self.lshrc(at, 2); let i = self.andc(i, 8191); if self.split { let k = self.c(self.lds_top); self.umin(i, k) + } else if self.sbar == SBarrier::Safe { + let past = self.addc(i, 0u32.wrapping_sub(LDS_BAR_AT)); + let taken = self.cmpc(Pred::ULt, past, 2); + let below = self.c(LDS_BAR_AT - 1); + self.sel(taken, below, i) } else { i } diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index f8ce756509..3224aff2b2 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -17,6 +17,7 @@ mod compact; pub mod container; pub mod coverage; pub mod graphics; +mod group_barrier; pub mod kernel; mod lanes; pub mod lower; diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 2c200c7888..91cddf22a5 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -70,7 +70,8 @@ impl DxilIr { leaders.extend(insts.get(i + 1).map(|n| n.pc)); } } - let mut lw = Lw::new(insts, &leaders, o, entry); + // no safe `s_barrier` here: its entry and exit setup is the block walk's + let mut lw = Lw::new(insts, &leaders, o, entry, false); // the rounding modes the program sets, as `kernel::translate_on_this_thread` finds them: // #1426's `s_round_mode` / `s_setreg` refuse a mode they cannot honour from these let branchy = insts.iter().any(|d| crate::gpu::rdna2::branch_target(d).is_some()); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b6dd120ff1..5ca94df7b3 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -667,7 +667,7 @@ fn cached_shader( } fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { - !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] + !["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_SAFE_BARRIER"] .iter() .any(|name| present(name)) && (stage != Stage::Pixel @@ -1479,7 +1479,7 @@ mod shader_cache_tests { #[test] fn shader_cache_bypasses_debug_overrides() { - for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN"] { + for name in ["XCL_RECOMP_NO_STRUCTURED", "XCL_RECOMP_WHY", "XCL_X64_ALL_MASKS", "XCL_WAVE64_SPIN", "XCL_SAFE_BARRIER"] { assert!(!cache_allowed(Stage::Compute, |v| v == name)); assert!(!cache_allowed(Stage::Vertex, |v| v == name)); assert!(!cache_allowed(Stage::Pixel, |v| v == name));