From ecc9723b6cdbd8e33ea00fabfa72987ba71337bc Mon Sep 17 00:00:00 2001 From: sip Date: Wed, 25 Nov 2026 00:40:27 +0300 Subject: [PATCH 1/3] Recompiler: emit globallycoherent on compute memory windows only when needed --- crates/xcl/src/gpu/dxil/kernel.rs | 3 +- crates/xcl/src/gpu/recomp/emit.rs | 10 +- crates/xcl/src/gpu/recomp/lower_dxil.rs | 2 +- crates/xcl/src/gpu/recomp/mod.rs | 29 +++++ crates/xcl/src/gpu/recomp/tests.rs | 142 ++++++++++++++++++++++++ 5 files changed, 181 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 94ce0b37d0..d3e29c5008 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -447,7 +447,8 @@ impl Lw { if stage == Stage::Pixel && uses_pops(insts) { s.enable_rov(); } - let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, cs.is_some()); + let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts); + let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8f257a043f..9d522391ce 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -68,6 +68,8 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, + /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) + pub coherent_mem: bool, } /// Instructions without an effect in this execution model. @@ -594,6 +596,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + coherent_mem: false, } } @@ -4658,8 +4661,9 @@ impl Em { h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n"); // compute work across workgroups (bottom-up BVH builds: atomics, then reading what // other groups wrote) relies on GLC / cache invalidation on the console: keep the flat - // memory coherent across the GPU there; graphics keeps the cached (faster) view - let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; + // memory coherent across the GPU only when the program actually uses those; otherwise + // keep the cached (faster) view + let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; let max_win = if self.opt.heap_windows { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; let windows = self.opt.mem_windows.clamp(1, max_win); let _ = writeln!(h, "{coherent}RWByteAddressBuffer mem : register(u2);"); @@ -5127,7 +5131,7 @@ impl Em { } } if windows > 1 { - let coherent = if matches!(self.opt.mode, Mode::Compute(_)) { "globallycoherent " } else { "" }; + let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); } h diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 2c200c7888..688c45cb72 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -45,7 +45,7 @@ struct DxilIr { impl DxilIr { /// The builder state for `insts` at `entry` (a kernel or a compute program), with one memory - /// window; a compute program's is coherent, as the HLSL path declares it. + /// window; a compute program's is coherent when `needs_coherent_mem` holds, matching the HLSL path. fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4e..70a92bc955 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1383,6 +1383,34 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B out } +/// Does the program require `globallycoherent` flat memory windows (`mem`, `mem1`…)? +/// +/// Compute work that coordinates across workgroups (e.g. bottom-up BVH builds: atomics, +/// then reading what other groups wrote) relies on `GLC`/`DLC`/`SLC`, memory atomics, or +/// cache invalidation on the console. Programs without any of those only access read-only +/// or disjointly written memory within the dispatch, so keeping their flat memory windows +/// un-qualified lets the GPU cache them in L1. +pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { + insts.iter().any(|d| { + let name = d.inst.name; + if matches!(name, "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV") { + return true; + } + if name.starts_with("BUFFER_ATOMIC_") + || name.starts_with("GLOBAL_ATOMIC_") + || name.starts_with("FLAT_ATOMIC_") + { + return true; + } + matches!( + d.enc.name, + "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" + ) && ["GLC", "DLC", "SLC"] + .iter() + .any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)) + }) +} + pub fn translate(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; @@ -1433,6 +1461,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } } let mut em = emit::Em::new(opt.clone()); + em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 527dc4e648..fa1d9d71be 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -9027,3 +9027,145 @@ fn gpu_scalar_sext_mulhi_and_vector_i24_sub_co_ci_u64_shifts() { assert_eq!(v[22], subrev, "lane {l} v_subrev_co_ci_u32"); } } + +/// Compute shaders only declare `globallycoherent` on their flat memory windows (`mem`, `mem1`… +/// and `XCL_HEAP_WINDOWS` heap views) when the program uses cross-workgroup coherence: memory +/// atomics, `GLC`/`DLC`/`SLC` memory ops, or cache invalidations. Both the HLSL and direct DXIL +/// backends follow the same predicate. +#[test] +fn compute_globallycoherent_only_when_needed() { + let cs = super::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let prog = |insts: &[(&str, &str, &[(&str, u64)])]| { + let mut c = Vec::new(); + for &(n, e, f) in insts { + c.extend(enc(n, e, f)); + } + c.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + c + }; + + // Plain compute: SMEM + MUBUF load/store + LDS + s_barrier, no GLC/DLC/SLC/atomics/inv. + let plain = prog(&[ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0)]), + ("DS_WRITE_B32", "ENC_DS", &[("ADDR", 0), ("DATA0", 1)]), + ("S_BARRIER", "ENC_SOPP", &[]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0)]), + ]); + + let coherent_cases: Vec<(&str, Vec)> = vec![ + ("smem glc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("GLC", 1)])])), + ("smem dlc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("DLC", 1)])])), + ("mubuf glc", prog(&[("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("GLC", 1)])])), + ("global dlc", prog(&[("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0), ("DLC", 1)])])), + ("mubuf slc", prog(&[("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("SLC", 1)])])), + ("buffer_atomic", prog(&[("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128)])])), + ("global_atomic", prog(&[("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("DATA", 2), ("SADDR", 0)])])), + ("flat_atomic", prog(&[("FLAT_ATOMIC_ADD", "ENC_FLAT", &[("VDST", 1), ("ADDR", 2), ("DATA", 4)])])), + ("s_dcache_inv", prog(&[("S_DCACHE_INV", "ENC_SMEM", &[])])), + ("s_gl1_inv", prog(&[("S_GL1_INV", "ENC_SMEM", &[])])), + ("buffer_gl0_inv", prog(&[("BUFFER_GL0_INV", "ENC_MUBUF", &[])])), + ("buffer_gl1_inv", prog(&[("BUFFER_GL1_INV", "ENC_MUBUF", &[])])), + ]; + + for (windows, heap) in [(1u32, false), (2, false), (2, true)] { + let opt = Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: windows, heap_windows: heap, ..Default::default() }; + let t = translate(&plain, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert!(!t.hlsl.contains("globallycoherent"), "plain CS (windows={windows}, heap={heap}) must not emit globallycoherent:\n{}", t.hlsl); + + for (label, code) in &coherent_cases { + let t = translate(code, &opt).unwrap(); + assert!(t.complete(), "{label}: {:?}", t.unsupported_why); + assert!(t.hlsl.contains("globallycoherent"), "{label} (windows={windows}, heap={heap}) must emit globallycoherent"); + if heap { + assert!(t.hlsl.contains("#define XCL_MW globallycoherent RWByteAddressBuffer"), "{label}: heap window accessor must be globallycoherent"); + } + } + } + + // Kernel mode stays non-coherent even with atomics. + let k = translate(&coherent_cases[6].1, &Options { mode: Mode::Kernel, wave64: false, ..Default::default() }).unwrap(); + assert!(!k.hlsl.contains("globallycoherent"), "kernel mode must not emit globallycoherent"); + + // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties + // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). + for mw in [1u32, super::HEAP_WINDOWS | 2] { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; + let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &cs).unwrap(); + let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); + if super::dxc::location().is_ok() { + let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); + let coh_dis = crate::gpu::dxil::validate::disassemble(&coh_k.dxil).unwrap(); + assert!(!plain_dis.contains("i32 20491"), "direct DXIL plain CS (mw={mw:#x}) must not set IsGloballyCoherent:\n{plain_dis}"); + assert!(coh_dis.contains("i32 20491"), "direct DXIL atomic CS (mw={mw:#x}) must set IsGloballyCoherent:\n{coh_dis}"); + } + } +} + +/// Real GPU check of both non-coherent (cached) and coherent (cross-workgroup atomic + GLC) +/// compute shaders across HLSL and direct DXIL. +#[test] +fn gpu_compute_coherent_and_cached_loads() { + if !gpu_ready() { + return; + } + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + + // 1. Plain cached compute: each thread reads a uniform dword via SMEM (s[0:1] = 0x100) and + // writes (val + group_id * 32 + tid) to mem[0x200 + (group_id * 32 + tid) * 4]. + let mut plain = Vec::new(); + plain.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)])); + plain.extend(enc("S_LSHL_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 2), ("SSRC1", 133)])); // s3 = tgid * 32 + plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 3), ("VSRC1", 0)])); // v1 = tgid * 32 + v0 + plain.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 2), ("SRC0", 4), ("VSRC1", 1)])); // v2 = mem[0x100] + idx + plain.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 3), ("SRC0", 130), ("VSRC1", 1)])); // v3 = idx * 4 + plain.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 128)])); + plain.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 3), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0x200)])); + plain.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + let t_plain = translate(&plain, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t_plain.complete(), "{:?}", t_plain.unsupported_why); + assert!(!t_plain.hlsl.contains("globallycoherent")); + let dxil_plain_hlsl = super::dxc::compile(&t_plain.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil_plain_direct = crate::gpu::dxil::kernel::translate_compute(&plain, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + + let mut io = vec![0u32; super::KERNEL_SGPRS]; + io[0] = 0x100; + let mut mem = vec![0u32; 0x400 / 4]; + mem[0x100 / 4] = 0x1234_0000; + for (tag, dxil) in [("hlsl", &dxil_plain_hlsl), ("direct", &dxil_plain_direct)] { + let out = runner::dispatch(dxil, [4, 1, 1], &io, &mem).unwrap(); + for idx in 0..128usize { + assert_eq!(out[(0x200 + idx * 4) / 4], 0x1234_0000 + idx as u32, "{tag} plain cached idx={idx}"); + } + } + + // 2. Cross-workgroup coherent compute: 16 groups of 32 threads atomically increment a shared + // counter at mem[0x100] and record their returned ticket at mem[0x200 + ticket * 4]. + let mut coh = Vec::new(); + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])); // v1 = 0 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)])); // v2 = 1 + coh.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); + coh.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 3)])); // v4 = ticket * 4 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)])); + coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 3), ("SADDR", 0x7D), ("OFFSET", 0x200), ("GLC", 1)])); + coh.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + let t_coh = translate(&coh, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + assert!(t_coh.complete(), "{:?}", t_coh.unsupported_why); + assert!(t_coh.hlsl.contains("globallycoherent")); + let dxil_coh_hlsl = super::dxc::compile(&t_coh.hlsl, "main", "cs_6_6", &[]).unwrap(); + let dxil_coh_direct = crate::gpu::dxil::kernel::translate_compute(&coh, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + + let mem2 = vec![0u32; (0x200 + 512 * 4) / 4]; + for (tag, dxil) in [("hlsl", &dxil_coh_hlsl), ("direct", &dxil_coh_direct)] { + let out = runner::dispatch(dxil, [16, 1, 1], &io, &mem2).unwrap(); + assert_eq!(out[0x100 / 4], 512, "{tag} coherent cross-group counter"); + for ticket in 0..512usize { + assert_eq!(out[(0x200 + ticket * 4) / 4], ticket as u32, "{tag} coherent ticket={ticket}"); + } + } +} From a03bc75e8bebe1dc9864356fd875abb9c5b165fb Mon Sep 17 00:00:00 2001 From: sip Date: Wed, 25 Nov 2026 05:24:37 +0300 Subject: [PATCH 2/3] Recompiler: emit per-instruction globallycoherent on compute flat memory --- crates/xcl/src/gpu/dxil/kernel.rs | 32 ++- crates/xcl/src/gpu/dxil/lower.rs | 19 +- crates/xcl/src/gpu/dxil/lower_mem.rs | 22 +- crates/xcl/src/gpu/recomp/emit.rs | 305 ++++++++++++++-------- crates/xcl/src/gpu/recomp/lower_dxil.rs | 2 +- crates/xcl/src/gpu/recomp/mod.rs | 80 ++++-- crates/xcl/src/gpu/recomp/pso.rs | 5 +- crates/xcl/src/gpu/recomp/runner.rs | 11 +- crates/xcl/src/gpu/recomp/tests.rs | 147 +++++++++-- crates/xcl/src/hle/d3d12x/bind.rs | 7 +- crates/xcl/src/hle/d3d12x/console_list.rs | 4 +- 11 files changed, 454 insertions(+), 180 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index d3e29c5008..4d7e4a8a0d 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -141,18 +141,27 @@ fn translate_entry(code: &[u8], o: KernelOptions, entry: Entry, compact: Option< } /// The memory windows of `mem_windows` and whether they come from the descriptor heap -/// (`recomp::HEAP_WINDOWS` in the count, `XCL_HEAP_WINDOWS=1`; Some(globallycoherent), and -/// `mems` then only counts them). Compute work across groups relies on coherent memory -/// (as the HLSL compute mode's `globallycoherent` windows). -fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec, Option) { +/// (`recomp::HEAP_WINDOWS` in the count, `XCL_HEAP_WINDOWS=1`). For root-UAV compute shaders +/// in `CoherenceMode::PerInstruction`, `mems` are plain windows `u2..` and `mems_coh` are +/// `globallycoherent` aliases `u6..` bound to the same GPU VAs. +fn mem_windows(s: &mut Shader, mem_windows: u32, coherence: crate::gpu::recomp::CoherenceMode) -> (Vec, Vec, bool) { + use crate::gpu::recomp::CoherenceMode; let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); - return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); + return (vec![RawUav { handle: z, binding: None }; n as usize], Vec::new(), true); + } + match coherence { + CoherenceMode::None => ((0..n).map(|k| s.raw_uav(2 + k, 0)).collect(), Vec::new(), false), + CoherenceMode::AllCoherent => ((0..n).map(|k| s.raw_uav_coherent(2 + k, 0)).collect(), Vec::new(), false), + CoherenceMode::PerInstruction => ( + (0..n).map(|k| s.raw_uav(2 + k, 0)).collect(), + (0..n).map(|k| s.raw_uav_coherent(6 + k, 0)).collect(), + false, + ), } - ((0..n).map(|k| if coherent { s.raw_uav_coherent(2 + k, 0) } else { s.raw_uav(2 + k, 0) }).collect(), None) } fn translate_on_this_thread(code: &[u8], o: KernelOptions, entry: Entry, compact: Option) -> Result { @@ -447,8 +456,12 @@ impl Lw { if stage == Stage::Pixel && uses_pops(insts) { s.enable_rov(); } - let coherent = cs.is_some() && crate::gpu::recomp::needs_coherent_mem(insts); - let (mems, heap_mem) = mem_windows(&mut s, o.mem_windows, coherent); + let coherence = if cs.is_some() { + crate::gpu::recomp::coherence_mode(insts) + } else { + crate::gpu::recomp::CoherenceMode::None + }; + let (mems, mems_coh, heap_mem) = mem_windows(&mut s, o.mem_windows, coherence); let i32 = s.m.i32(); let z = s.m.i32c(0); let mut lw = Lw { @@ -462,7 +475,10 @@ impl Lw { upper: z, half: z, mems, + mems_coh, heap_mem, + coherence, + inst_coherent_load: coherence == crate::gpu::recomp::CoherenceMode::AllCoherent, res, fmt_table: None, fmt_desc_cache: HashMap::new(), diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 0e270bb60d..7b21fda20c 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -181,9 +181,14 @@ pub struct Lw { pub half: Value, /// the memory windows `mem`, `mem1`.. (u2..) pub mems: Vec, - /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): - /// Some(globallycoherent) - pub heap_mem: Option, + /// coherent memory-window aliases `u6..` for root-UAV `CoherenceMode::PerInstruction` + pub mems_coh: Vec, + /// true when the memory windows come from `ResourceDescriptorHeap` (`XCL_HEAP_WINDOWS=1`) + pub heap_mem: bool, + /// flat-memory coherence policy for this shader + pub(crate) coherence: crate::gpu::recomp::CoherenceMode, + /// whether loads emitted while lowering the current instruction use the coherent view + pub inst_coherent_load: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, @@ -937,6 +942,14 @@ impl Lw { let name = d.inst.name.to_ascii_lowercase(); self.pc = d.pc; self.dpp_enable = None; + self.inst_coherent_load = match self.coherence { + crate::gpu::recomp::CoherenceMode::None => false, + crate::gpu::recomp::CoherenceMode::AllCoherent => true, + crate::gpu::recomp::CoherenceMode::PerInstruction => { + crate::gpu::recomp::inst_has_mem_coherence_bits(d) + || crate::gpu::recomp::inst_is_flat_atomic(d) + } + }; if name == "s_sendmsg" && self.mesh.is_some() { return self.mesh_sendmsg(d); } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index a1d034e740..ac8c8fd862 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -161,6 +161,7 @@ impl Lw { &mut self, mut guard: Option, out_tys: &[super::module::Ty], + coherent: bool, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { if let Some(c) = guard { @@ -172,7 +173,7 @@ impl Lw { } // Descriptor-heap windows (`#1693`, `XCL_HEAP_WINDOWS=1`): single guarded heap lookup // combined with `guard`, stacking cleanly with vector loads/stores & FormatLoad opt. - if let Some(coherent) = self.heap_mem { + if self.heap_mem { let windows = self.mems.len() as u32; let w = self.rd(super::lower::VAR_WIN); let inside = self.cmpc(Pred::ULt, w, windows); @@ -218,14 +219,15 @@ impl Lw { } return out; } + let use_coh = coherent && !self.mems_coh.is_empty(); // Single window, or window known at translation time: at most one branch for `guard`. let fixed_mem = if self.mems.len() <= 1 { - Some(self.mems[0]) + Some(if use_coh { self.mems_coh[0] } else { self.mems[0] }) } else { let w = self.rd(super::lower::VAR_WIN); if let Some(k) = self.s.m.const_u64(w) { if (k as usize) < self.mems.len() { - Some(self.mems[k as usize]) + Some(if use_coh { self.mems_coh[k as usize] } else { self.mems[k as usize] }) } else { return out_tys.iter().map(|&t| self.s.m.const_int(t, 0)).collect(); } @@ -268,7 +270,7 @@ impl Lw { // Multi-window dispatch via a single LLVM `switch` (default -> `join` for out-of-range // or inactive lane, matching `#1693` window semantics). let w = self.rd(super::lower::VAR_WIN); - let mems = self.mems.clone(); + let mems = if use_coh { self.mems_coh.clone() } else { self.mems.clone() }; let n = mems.len(); let from = self.cur(); let arms: Vec = (0..n).map(|_| self.block(None)).collect(); @@ -322,7 +324,8 @@ impl Lw { ) -> Vec { let i32 = self.s.m.i32(); let tys = vec![i32; n]; - self.with_mem_many_tys(guard, &tys, f) + let coherent = self.inst_coherent_load; + self.with_mem_many_tys(guard, &tys, coherent, f) } pub(crate) fn with_mem_void( @@ -330,18 +333,21 @@ impl Lw { guard: Option, f: &mut dyn FnMut(&mut Lw, RawUav), ) { - let _ = self.with_mem_many_tys(guard, &[], &mut |lw, m| { + let coherent = self.coherence != crate::gpu::recomp::CoherenceMode::None; + let _ = self.with_mem_many_tys(guard, &[], coherent, &mut |lw, m| { f(lw, m); Vec::new() }); } fn mraw_atomic(&mut self, op: AtomicOp, a: Value, v: Value) -> Value { let ty = self.s.m.type_of(v); - self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] + let coherent = self.coherence != crate::gpu::recomp::CoherenceMode::None; + self.with_mem_many_tys(None, &[ty], coherent, &mut |lw, m| vec![lw.s.raw_atomic(m, op, a, v)])[0] } fn mraw_cmpxchg(&mut self, a: Value, c: Value, n: Value) -> Value { let ty = self.s.m.type_of(c); - self.with_mem_many_tys(None, &[ty], &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] + let coherent = self.coherence != crate::gpu::recomp::CoherenceMode::None; + self.with_mem_many_tys(None, &[ty], coherent, &mut |lw, m| vec![lw.s.raw_cmpxchg(m, a, c, n)])[0] } /// `mem.Load(a & ~3)` pub fn mem_ld(&mut self, a: Value) -> Value { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 9d522391ce..21dd406152 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -68,8 +68,8 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, - /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) - pub coherent_mem: bool, + /// flat-memory coherence policy for this shader (`coherence_mode`) + pub coherence: super::CoherenceMode, } /// Instructions without an effect in this execution model. @@ -596,10 +596,34 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, - coherent_mem: false, + coherence: super::CoherenceMode::None, } } + fn load_is_coherent(&self, d: &Decoded) -> bool { + self.coherence == super::CoherenceMode::PerInstruction && super::inst_has_mem_coherence_bits(d) + } + + fn load_mem(&self, d: &Decoded) -> &'static str { + if self.load_is_coherent(d) { "memc" } else { "mem" } + } + + fn loadx4_fn(&self, d: &Decoded) -> &'static str { + if self.load_is_coherent(d) { "xcl_loadx4_c" } else { "xcl_loadx4" } + } + + fn ld_raw_fn(&self, d: &Decoded) -> &'static str { + if self.load_is_coherent(d) { "ld_raw_c" } else { "ld_raw" } + } + + fn store_mem(&self) -> &'static str { + if self.coherence == super::CoherenceMode::PerInstruction { "memc" } else { "mem" } + } + + fn atomic_mem(&self) -> &'static str { + if self.coherence == super::CoherenceMode::PerInstruction { "memc" } else { "mem" } + } + /// Hardware wave count for Compute / Mesh threadgroups (`None` for other stages). fn compute_or_mesh_hw_waves(&self) -> Option { let threads = match &self.opt.mode { @@ -1892,16 +1916,18 @@ impl Em { // comes out 0. HLSL 2021's `?:` is a branch, and with several memory windows every // access is a switch between them (`windowed`): one per dword made DXC several // times slower on big programs. Four dwords share one switch (`xcl_loadx4`). + let lm = self.load_mem(d); + let lx4 = self.loadx4_fn(d); if count == 1 { self.line(&format!("bool {t}_in = {t}_off < {t}_lim;")); - self.line(&format!("uint {t}_0 = select({t}_in, mem.Load(select({t}_in, {t}_a, 0u)), 0u);")); + self.line(&format!("uint {t}_0 = select({t}_in, {lm}.Load(select({t}_in, {t}_a, 0u)), 0u);")); vals.push(format!("{t}_0")); } else { for g in 0..count.div_ceil(4) { let n = (count - 4 * g).min(4); let o = (0..4).map(|k| format!("{}u", 16 * g + 4 * k.min(n - 1))).collect::>().join(", "); self.line(&format!("bool4 {t}_in{g} = {t}_off + uint4({o}) < {t}_lim;")); - self.line(&format!("uint4 {t}_g{g} = select({t}_in{g}, xcl_loadx4(select({t}_in{g}, {t}_a + uint4({o}), 0u)), 0u);")); + self.line(&format!("uint4 {t}_g{g} = select({t}_in{g}, {lx4}(select({t}_in{g}, {t}_a + uint4({o}), 0u)), 0u);")); vals.extend(["x", "y", "z", "w"][..n].iter().map(|c| format!("{t}_g{g}.{c}"))); } } @@ -1920,18 +1946,19 @@ impl Em { } else { self.line(&format!("uint {t}_a = ({b} + {} + {soff}) & ~3u;", hex(imm))); } + let lm = self.load_mem(d); match count { 1 => { - self.line(&format!("uint {t}_0 = mem.Load({t}_a);")); + self.line(&format!("uint {t}_0 = {lm}.Load({t}_a);")); vals.push(format!("{t}_0")); } 2 => { - self.line(&format!("uint2 {t}_g0 = mem.Load2({t}_a);")); + self.line(&format!("uint2 {t}_g0 = {lm}.Load2({t}_a);")); vals.extend([format!("{t}_g0.x"), format!("{t}_g0.y")]); } _ => { for g in 0..count / 4 { - self.line(&format!("uint4 {t}_g{g} = mem.Load4({t}_a + {}u);", 16 * g)); + self.line(&format!("uint4 {t}_g{g} = {lm}.Load4({t}_a + {}u);", 16 * g)); vals.extend(["x", "y", "z", "w"].iter().map(|c| format!("{t}_g{g}.{c}"))); } } @@ -2115,11 +2142,12 @@ impl Em { if store { self.line(&format!("if (and({act}, {ok})) st_bytes({t}_a, uint4({v}, 0u, 0u, 0u), {n}u);")); } else { + let ldr = self.ld_raw_fn(d); let bits = 8 * n; let val = if signed { - format!("(uint)(((int)(ld_raw({t}_a).x << {}u)) >> {}u)", 32 - bits, 32 - bits) + format!("(uint)(((int)({ldr}({t}_a).x << {}u)) >> {}u)", 32 - bits, 32 - bits) } else { - format!("(ld_raw({t}_a).x & {}u)", (1u64 << bits) - 1) + format!("({ldr}({t}_a).x & {}u)", (1u64 << bits) - 1) }; self.line(&format!("if ({act}) {v} = {ok} ? {val} : 0u;")); } @@ -2129,18 +2157,20 @@ impl Em { BufKind::Load => { // branch-free (see `smem`): a lane that is inactive or out of range reads offset // 0 and keeps its register / gets 0; one window switch per four dwords + let lm = self.load_mem(d); + let lx4 = self.loadx4_fn(d); self.line(&format!("bool {t}_act = {act};")); if count == 1 { let ok = in_range("4u".into()); let v = self.vreg(vdata); self.line(&format!("bool {t}_ok = {ok};")); - self.line(&format!("uint {t}_v = mem.Load(select(and({t}_act, {t}_ok), {t}_a & ~3u, 0u));")); + self.line(&format!("uint {t}_v = {lm}.Load(select(and({t}_act, {t}_ok), {t}_a & ~3u, 0u));")); self.line(&format!("{v} = select({t}_act, select({t}_ok, {t}_v, 0u), {v});")); } else { let oks: Vec = (0..4).map(|i| in_range(format!("{}u", 4 * i.min(count - 1) + 4))).collect(); let o = (0..4).map(|i| format!("{}u", 4 * i.min(count - 1))).collect::>().join(", "); self.line(&format!("bool4 {t}_ok = bool4({});", oks.join(", "))); - self.line(&format!("uint4 {t}_v = xcl_loadx4(select(and({t}_act, {t}_ok), ({t}_a & ~3u) + uint4({o}), 0u));")); + self.line(&format!("uint4 {t}_v = {lx4}(select(and({t}_act, {t}_ok), ({t}_a & ~3u) + uint4({o}), 0u));")); for i in 0..count { let v = self.vreg(vdata + i); let c = ["x", "y", "z", "w"][i as usize]; @@ -2149,21 +2179,23 @@ impl Em { } } BufKind::Store => { + let sm = self.store_mem(); let mut st = Vec::new(); for i in 0..count { let ok = in_range(format!("{}u", 4 * i + 4)); let v = self.vreg(vdata + i); - st.push(format!("if ({ok}) mem.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); + st.push(format!("if ({ok}) {sm}.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); } self.line(&format!("if ({act}) {{ {} }}", st.join(" "))); } BufKind::FormatLoad => { // format from the instruction (tbuffer) or from the V# (dword3 [18:12]); DST_SEL from the V# + let ldr = self.ld_raw_fn(d); let fmt = if d.enc.name == "ENC_MTBUF" { format!("{}u", f("FORMAT")) } else { format!("(({d3} >> 12) & 0x7Fu)") }; self.line(&format!("uint {t}_info = FMT_INFO[min({fmt}, 77u)];")); self.line(&format!("bool {t}_int = ((({t}_info >> 3) & 7u) == 4u) || ((({t}_info >> 3) & 7u) == 5u);")); self.line(&format!("bool {t}_ok = and(({t}_info & 7u) != 0u, {});", in_range(format!("fmt_bytes({t}_info)")))); - self.line(&format!("uint4 {t}_r = ld_raw({t}_a);")); + self.line(&format!("uint4 {t}_r = {ldr}({t}_a);")); self.line(&format!( "uint4 {t}_c = uint4(fmt_comp({t}_r, {t}_info, 0u), fmt_comp({t}_r, {t}_info, 1u), fmt_comp({t}_r, {t}_info, 2u), fmt_comp({t}_r, {t}_info, 3u));" )); @@ -4129,7 +4161,7 @@ impl Em { return self.atomic64(op, &format!("{t}_a"), vdata, vdata + 2, f("GLC") == 1, vdata, &format!("and({act}, {t}_ok)")); } let (v, cmp) = (self.vreg(vdata), self.vreg(vdata + 1)); - let body = rmw32(op, &At::Mem(format!("{t}_a")), &v, &cmp, &format!("{t}_old"), &t).ok_or("buffer_atomic")?; + let body = rmw32(op, &At::Mem(self.atomic_mem(), format!("{t}_a")), &v, &cmp, &format!("{t}_old"), &t).ok_or("buffer_atomic")?; self.line(&format!("uint {t}_old = 0u;")); self.line(&format!("if (and({act}, {t}_ok)) {{ {body} }}")); if f("GLC") == 1 { @@ -4146,7 +4178,7 @@ impl Em { let (lo, hi) = (self.vreg(data), self.vreg(data + 1)); let (clo, chi) = (self.vreg(cmp), self.vreg(cmp + 1)); self.line(&format!("uint64_t {t}_v = (uint64_t){lo} | ((uint64_t){hi} << 32); uint64_t {t}_cmp = (uint64_t){clo} | ((uint64_t){chi} << 32); uint64_t {t}_old = 0;")); - let body = rmw64(op, a, &format!("{t}_v"), &format!("{t}_cmp"), &format!("{t}_old"), &t).ok_or("atomic 64")?; + let body = rmw64(op, self.atomic_mem(), a, &format!("{t}_v"), &format!("{t}_cmp"), &format!("{t}_old"), &t).ok_or("atomic 64")?; self.line(&format!("if ({active}) {{ {body} }}")); if glc { let (r0, r1) = (self.vreg(dst), self.vreg(dst + 1)); @@ -4191,7 +4223,8 @@ impl Em { if store { self.line(&format!("if (and({act}, {ok})) st_bytes({t}_a, uint4({}, 0u, 0u, 0u), {n}u);", d16_data(&v, half))); } else { - let raw = format!("select({ok}, ld_raw({t}_a).x, 0u)"); + let ldr = self.ld_raw_fn(d); + let raw = format!("select({ok}, {ldr}({t}_a).x, 0u)"); self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &raw, n, signed, half))); } Ok(()) @@ -4220,8 +4253,9 @@ impl Em { let v = self.vreg(f("DATA")); self.line(&format!("if ({act}) st_bytes({t}_a, uint4({}, 0u, 0u, 0u), {n}u);", d16_data(&v, half))); } else { + let ldr = self.ld_raw_fn(d); let v = self.vreg(f("VDST")); - self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &format!("ld_raw({t}_a).x"), n, signed, half))); + self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &format!("{ldr}({t}_a).x"), n, signed, half))); } return Ok(()); } @@ -4246,14 +4280,16 @@ impl Em { let t = self.t(); self.emit_flat_addr(global, op.ends_with("_addtid"), saddr, f("ADDR"), off, 0, store, &t); let act = self.act(); + let lm = self.load_mem(d); + let sm = self.store_mem(); let mut st = Vec::new(); for i in 0..count { if store { let v = self.vreg(f("DATA") + i); - st.push(format!("mem.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); + st.push(format!("{sm}.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); } else { let v = self.vreg(f("VDST") + i); - st.push(format!("{v} = mem.Load(({t}_a + {}u) & ~3u);", 4 * i)); + st.push(format!("{v} = {lm}.Load(({t}_a + {}u) & ~3u);", 4 * i)); } } self.line(&format!("if ({act}) {{ {} }}", st.join(" "))); @@ -4324,23 +4360,24 @@ impl Em { let v = self.vreg(f("DATA")); self.line(&format!("uint {t}_old = 0u;")); let cmpv = self.vreg(f("DATA") + 1); + let am = self.atomic_mem(); let body = match op { - "inc" | "dec" | "csub" | "fcmpswap" => rmw32(op, &At::Mem(format!("{t}_a")), &v, &cmpv, &format!("{t}_old"), &t).ok_or("FLAT atomic")?, - "add" => format!("mem.InterlockedAdd({t}_a, {v}, {t}_old);"), - "sub" => format!("mem.InterlockedAdd({t}_a, 0u - {v}, {t}_old);"), - "and" => format!("mem.InterlockedAnd({t}_a, {v}, {t}_old);"), - "or" => format!("mem.InterlockedOr({t}_a, {v}, {t}_old);"), - "xor" => format!("mem.InterlockedXor({t}_a, {v}, {t}_old);"), - "swap" => format!("mem.InterlockedExchange({t}_a, {v}, {t}_old);"), - "umin" => format!("mem.InterlockedMin({t}_a, {v}, {t}_old);"), - "umax" => format!("mem.InterlockedMax({t}_a, {v}, {t}_old);"), - "smin" => format!("int {t}_s; mem.InterlockedMin({t}_a, (int){v}, {t}_s); {t}_old = (uint){t}_s;"), - "smax" => format!("int {t}_s; mem.InterlockedMax({t}_a, (int){v}, {t}_s); {t}_old = (uint){t}_s;"), + "inc" | "dec" | "csub" | "fcmpswap" => rmw32(op, &At::Mem(am, format!("{t}_a")), &v, &cmpv, &format!("{t}_old"), &t).ok_or("FLAT atomic")?, + "add" => format!("{am}.InterlockedAdd({t}_a, {v}, {t}_old);"), + "sub" => format!("{am}.InterlockedAdd({t}_a, 0u - {v}, {t}_old);"), + "and" => format!("{am}.InterlockedAnd({t}_a, {v}, {t}_old);"), + "or" => format!("{am}.InterlockedOr({t}_a, {v}, {t}_old);"), + "xor" => format!("{am}.InterlockedXor({t}_a, {v}, {t}_old);"), + "swap" => format!("{am}.InterlockedExchange({t}_a, {v}, {t}_old);"), + "umin" => format!("{am}.InterlockedMin({t}_a, {v}, {t}_old);"), + "umax" => format!("{am}.InterlockedMax({t}_a, {v}, {t}_old);"), + "smin" => format!("int {t}_s; {am}.InterlockedMin({t}_a, (int){v}, {t}_s); {t}_old = (uint){t}_s;"), + "smax" => format!("int {t}_s; {am}.InterlockedMax({t}_a, (int){v}, {t}_s); {t}_old = (uint){t}_s;"), "cmpswap" => { let cmp = self.vreg(f("DATA") + 1); - format!("mem.InterlockedCompareExchange({t}_a, {cmp}, {v}, {t}_old);") + format!("{am}.InterlockedCompareExchange({t}_a, {cmp}, {v}, {t}_old);") } - "fmin" | "fmax" => float_minmax_mem(op == "fmin", false, &format!("{t}_a"), &v, &format!("{t}_old"), &t), + "fmin" | "fmax" => float_minmax_mem(op == "fmin", false, am, &format!("{t}_a"), &v, &format!("{t}_old"), &t), _ => return Err("FLAT atomic"), }; self.line(&format!("if ({act}) {{ {body} }}")); @@ -4660,21 +4697,38 @@ impl Em { } h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n"); // compute work across workgroups (bottom-up BVH builds: atomics, then reading what - // other groups wrote) relies on GLC / cache invalidation on the console: keep the flat - // memory coherent across the GPU only when the program actually uses those; otherwise - // keep the cached (faster) view - let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; + // other groups wrote) relies on GLC / cache invalidation on the console: + // - `None`: cached plain views only + // - `PerInstruction`: plain views for ordinary loads (`!GLC && !DLC && !SLC`), + // `globallycoherent` aliases (`memc`, `u6..u9` or `XCL_MWC`) for GLC/DLC/SLC loads, + // all stores, and all atomics + // - `AllCoherent`: `globallycoherent` on every memory window (program uses cache-inv) + let coherent = if self.coherence == super::CoherenceMode::AllCoherent { "globallycoherent " } else { "" }; + let split_coh = self.coherence == super::CoherenceMode::PerInstruction; let max_win = if self.opt.heap_windows { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; let windows = self.opt.mem_windows.clamp(1, max_win); + let root_win = windows.min(crate::gpu::uma::MAX_WINDOWS as u32); let _ = writeln!(h, "{coherent}RWByteAddressBuffer mem : register(u2);"); if windows > 1 { - for k in 1..windows.min(crate::gpu::uma::MAX_WINDOWS as u32) { + for k in 1..root_win { let _ = writeln!(h, "{coherent}RWByteAddressBuffer mem{k} : register(u{});", 2 + k); } + if split_coh && !self.opt.heap_windows { + let _ = writeln!(h, "globallycoherent RWByteAddressBuffer memc : register(u6);"); + for k in 1..root_win { + let _ = writeln!(h, "globallycoherent RWByteAddressBuffer memc{k} : register(u{});", 6 + k); + } + } h.push_str("static uint xcl_w = 0u;\nstatic uint xcl_uma_base = 0u;\n"); h.push_str(MEM_ACCESSORS_HERE); } else { + if split_coh { + let _ = writeln!(h, "globallycoherent RWByteAddressBuffer memc : register(u6);"); + } h.push_str(LOADX4_ONE_WINDOW); + if split_coh { + h.push_str(LOADX4_COHERENT_ONE_WINDOW); + } } for (i, (_, cmp)) in self.static_used.iter().enumerate() { let k = self.opt.static_sampler_base as usize + i; @@ -4698,6 +4752,15 @@ impl Em { let infos: Vec = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect(); let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", ")); h.push_str(PRELUDE_MEM); + if split_coh { + h.push_str(PRELUDE_LD_RAW_COHERENT); + } + let sm = self.store_mem(); + let _ = writeln!(h, "void st_part(uint b, uint m, uint v) {{ {sm}.InterlockedAnd(b, ~m); {sm}.InterlockedOr(b, v & m); }}"); + let _ = writeln!( + h, + "void st_bytes(uint a, uint4 r, uint n) {{\n uint s = (a & 3u) * 8u; uint b = a & ~3u;\n if (s == 0u && (n & 3u) == 0u) {{ [unroll] for (uint k = 0u; k < 4u; k++) if (k * 4u < n) {sm}.Store(b + 4u * k, r[k]); return; }}\n uint m = n >= 4u ? 0xFFFFFFFFu : ((1u << (8u * n)) - 1u);\n st_part(b, m << s, r.x << s);\n if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s));\n}}" + ); if self.uses_scratch { h.push_str(PRELUDE_SCRATCH); } @@ -5131,8 +5194,7 @@ impl Em { } } if windows > 1 { - let coherent = if self.coherent_mem { "globallycoherent " } else { "" }; - h = windowed(&h, windows, self.opt.heap_windows.then_some(coherent)); + h = windowed(&h, windows, self.opt.heap_windows, self.coherence); } h } @@ -5413,9 +5475,9 @@ fn cmp_op(rest: &str) -> Option<(&'static str, bool)> { )) } -/// Where a 32-bit atomic works: a byte address in `mem`, or an lvalue (LDS slot, texel). +/// Where a 32-bit atomic works: a byte address in `mem`/`memc`, or an lvalue (LDS slot, texel). enum At { - Mem(String), + Mem(&'static str, String), Ref(String), } @@ -5425,12 +5487,12 @@ enum At { /// loop. Operation names as in buffer / flat / image (`umin`) and DS (`min_u32`). fn rmw32(op: &str, at: &At, v: &str, v2: &str, old: &str, t: &str) -> Option { let direct = |f: &str, val: &str| match at { - At::Mem(a) => format!("mem.{f}({a}, {val}, {old});"), + At::Mem(m, a) => format!("{m}.{f}({a}, {val}, {old});"), At::Ref(r) => format!("{f}({r}, {val}, {old});"), }; let cas = |new: String| { let (load, cx) = match at { - At::Mem(a) => (format!("mem.Load({a})"), format!("mem.InterlockedCompareExchange({a}, {t}_c, {t}_n, {t}_p);")), + At::Mem(m, a) => (format!("{m}.Load({a})"), format!("{m}.InterlockedCompareExchange({a}, {t}_c, {t}_n, {t}_p);")), At::Ref(r) => (r.clone(), format!("InterlockedCompareExchange({r}, {t}_c, {t}_n, {t}_p);")), }; format!( @@ -5439,7 +5501,7 @@ fn rmw32(op: &str, at: &At, v: &str, v2: &str, old: &str, t: &str) -> Option format!("int {t}_s = 0; mem.{f}({a}, (int){v}, {t}_s); {old} = (uint){t}_s;"), + At::Mem(m, a) => format!("int {t}_s = 0; {m}.{f}({a}, (int){v}, {t}_s); {old} = (uint){t}_s;"), At::Ref(_) => cas(format!("(uint){pick}((int){c}, (int){v})")), }; Some(match op { @@ -5452,15 +5514,15 @@ fn rmw32(op: &str, at: &At, v: &str, v2: &str, old: &str, t: &str) -> Option direct("InterlockedMin", v), "umax" | "max_u32" => direct("InterlockedMax", v), "cmpswap" | "cmpst_b32" => match at { - At::Mem(a) => format!("mem.InterlockedCompareExchange({a}, {v2}, {v}, {old});"), + At::Mem(m, a) => format!("{m}.InterlockedCompareExchange({a}, {v2}, {v}, {old});"), At::Ref(r) => format!("InterlockedCompareExchange({r}, {v2}, {v}, {old});"), }, // IEEE-754 float compare-swap: -0.0 == +0.0 swaps, NaN == NaN keeps (XCL-BT-042) "fcmpswap" | "cmpst_f32" => { let (load, cx) = match at { - At::Mem(a) => ( - format!("mem.InterlockedOr({a}, 0u, {t}_c);"), - format!("mem.InterlockedCompareExchange({a}, {t}_c, {v}, {t}_p);"), + At::Mem(m, a) => ( + format!("{m}.InterlockedOr({a}, 0u, {t}_c);"), + format!("{m}.InterlockedCompareExchange({a}, {t}_c, {v}, {t}_p);"), ), At::Ref(r) => ( format!("InterlockedOr({r}, 0u, {t}_c);"), @@ -5476,7 +5538,7 @@ fn rmw32(op: &str, at: &At, v: &str, v2: &str, old: &str, t: &str) -> Option { let min = op == "fmin" || op == "min_f32"; match at { - At::Mem(a) => float_minmax_mem(min, false, a, v, old, t), + At::Mem(m, a) => float_minmax_mem(min, false, m, a, v, old, t), At::Ref(_) => cas(format!("asuint({}(asfloat({c}), asfloat({v})))", if min { "min" } else { "max" })), } } @@ -5492,7 +5554,7 @@ fn rmw32(op: &str, at: &At, v: &str, v2: &str, old: &str, t: &str) -> Option Option { +fn rmw64(op: &str, m: &str, a: &str, v: &str, cmp: &str, old: &str, t: &str) -> Option { if matches!(op, "inc" | "dec") { let c = format!("{t}_c"); let new = if op == "inc" { @@ -5501,7 +5563,7 @@ fn rmw64(op: &str, a: &str, v: &str, cmp: &str, old: &str, t: &str) -> Option {v}) ? {v} : {c} - (uint64_t)1") }; return Some(format!( - "uint2 {t}_l = mem.Load2({a}); uint64_t {t}_c = (uint64_t){t}_l.x | ((uint64_t){t}_l.y << 32); [allow_uav_condition] for (uint {t}_i = 0u; {t}_i < 4096u; {t}_i++) {{ uint64_t {t}_n = {new}; uint64_t {t}_p = 0; mem.InterlockedCompareExchange64({a}, {t}_c, {t}_n, {t}_p); if ({t}_p == {t}_c) break; {t}_c = {t}_p; }} {old} = {t}_c;" + "uint2 {t}_l = {m}.Load2({a}); uint64_t {t}_c = (uint64_t){t}_l.x | ((uint64_t){t}_l.y << 32); [allow_uav_condition] for (uint {t}_i = 0u; {t}_i < 4096u; {t}_i++) {{ uint64_t {t}_n = {new}; uint64_t {t}_p = 0; {m}.InterlockedCompareExchange64({a}, {t}_c, {t}_n, {t}_p); if ({t}_p == {t}_c) break; {t}_c = {t}_p; }} {old} = {t}_c;" )); } let f = match op { @@ -5514,20 +5576,20 @@ fn rmw64(op: &str, a: &str, v: &str, cmp: &str, old: &str, t: &str) -> Option "InterlockedMax64", "smin" | "smax" => { let f = if op == "smin" { "InterlockedMin64" } else { "InterlockedMax64" }; - return Some(format!("int64_t {t}_s = 0; mem.{f}({a}, (int64_t){v}, {t}_s); {old} = (uint64_t){t}_s;")); + return Some(format!("int64_t {t}_s = 0; {m}.{f}({a}, (int64_t){v}, {t}_s); {old} = (uint64_t){t}_s;")); } - "cmpswap" => return Some(format!("mem.InterlockedCompareExchange64({a}, {cmp}, {v}, {old});")), + "cmpswap" => return Some(format!("{m}.InterlockedCompareExchange64({a}, {cmp}, {v}, {old});")), // IEEE-754 f64 compare-swap via pure u64 bitwise checks (no DoubleExtensions needed) "fcmpswap" => { return Some(format!( - "uint64_t {t}_c = 0; mem.InterlockedOr64({a}, (uint64_t)0, {t}_c); [allow_uav_condition] for (uint {t}_i = 0u; {t}_i < 4096u; {t}_i++) {{ if (({t}_c & 0x7FFFFFFFFFFFFFFFull) > 0x7FF0000000000000ull || ({t}_c != {cmp} && (({t}_c | {cmp}) & 0x7FFFFFFFFFFFFFFFull) != 0ull)) break; uint64_t {t}_p = 0; mem.InterlockedCompareExchange64({a}, {t}_c, {v}, {t}_p); if ({t}_p == {t}_c) break; {t}_c = {t}_p; }} {old} = {t}_c;" + "uint64_t {t}_c = 0; {m}.InterlockedOr64({a}, (uint64_t)0, {t}_c); [allow_uav_condition] for (uint {t}_i = 0u; {t}_i < 4096u; {t}_i++) {{ if (({t}_c & 0x7FFFFFFFFFFFFFFFull) > 0x7FF0000000000000ull || ({t}_c != {cmp} && (({t}_c | {cmp}) & 0x7FFFFFFFFFFFFFFFull) != 0ull)) break; uint64_t {t}_p = 0; {m}.InterlockedCompareExchange64({a}, {t}_c, {v}, {t}_p); if ({t}_p == {t}_c) break; {t}_c = {t}_p; }} {old} = {t}_c;" )); } - "fmin" | "fmax" => return Some(float_minmax_mem(op == "fmin", true, a, v, old, t)), + "fmin" | "fmax" => return Some(float_minmax_mem(op == "fmin", true, m, a, v, old, t)), _ => return None, }; let val = if op == "sub" { format!("((uint64_t)0 - {v})") } else { v.to_string() }; - Some(format!("mem.{f}({a}, {val}, {old});")) + Some(format!("{m}.{f}({a}, {val}, {old});")) } /// Float min / max at byte address `a` of the flat memory as one integer atomic (no CAS loop: @@ -5537,14 +5599,14 @@ fn rmw64(op: &str, a: &str, v: &str, cmp: &str, old: &str, t: &str) -> Option String { +fn float_minmax_mem(min: bool, x2: bool, m: &str, a: &str, v: &str, old: &str, t: &str) -> String { let (pos, neg) = if min { ("InterlockedMin", "InterlockedMax") } else { ("InterlockedMax", "InterlockedMin") }; if x2 { format!( - "if ({v} <= 0x7FF0000000000000ull) {{ int64_t {t}_s = 0; mem.{pos}64({a}, (int64_t){v}, {t}_s); {old} = (uint64_t){t}_s; }} else {{ mem.{neg}64({a}, {v}, {old}); }}" + "if ({v} <= 0x7FF0000000000000ull) {{ int64_t {t}_s = 0; {m}.{pos}64({a}, (int64_t){v}, {t}_s); {old} = (uint64_t){t}_s; }} else {{ {m}.{neg}64({a}, {v}, {old}); }}" ) } else { - format!("if ({v} <= 0x7F800000u) {{ int {t}_s = 0; mem.{pos}({a}, asint({v}), {t}_s); {old} = asuint({t}_s); }} else {{ mem.{neg}({a}, {v}, {old}); }}") + format!("if ({v} <= 0x7F800000u) {{ int {t}_s = 0; {m}.{pos}({a}, asint({v}), {t}_s); {old} = asuint({t}_s); }} else {{ {m}.{neg}({a}, {v}, {old}); }}") } } @@ -5554,40 +5616,46 @@ const MEM_ACCESSORS_HERE: &str = "//XCL_MEM_ACCESSORS\n"; /// Four dwords at four addresses (scalar buffer loads with their bounds checks); with several /// windows `mem_accessors` defines it, with one switch for all four. const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }\n"; +const LOADX4_COHERENT_ONE_WINDOW: &str = "uint4 xcl_loadx4_c(uint4 a) { return uint4(memc.Load(a.x), memc.Load(a.y), memc.Load(a.z), memc.Load(a.w)); }\n"; -/// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes -/// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose -/// definitions replace the placeholder. -/// `heap`: Some(storage class) – the accessors take window k from the descriptor heap -/// (`Options::heap_windows`) instead of switching over the root UAVs. -fn windowed(h: &str, windows: u32, heap: Option<&str>) -> String { - let mut out = String::with_capacity(h.len() + 8192); +fn rewrite_mem_calls(h: &str, needle: &str, prefix: &str) -> String { + let mut out = String::with_capacity(h.len() + 4096); let mut rest = h; - while let Some(i) = rest.find("mem.") { + while let Some(i) = rest.find(needle) { let before_ok = rest[..i].chars().next_back().is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_')); - let tail = &rest[i + 4..]; + let tail = &rest[i + needle.len()..]; let name_len = tail.find(|c: char| !c.is_ascii_alphanumeric()).unwrap_or(tail.len()); if before_ok && tail[name_len..].starts_with('(') { out.push_str(&rest[..i]); - out.push_str("xcl_m"); + out.push_str(prefix); out.push_str(&tail[..name_len]); rest = &tail[name_len..]; } else { - out.push_str(&rest[..i + 4]); + out.push_str(&rest[..i + needle.len()]); rest = tail; } } out.push_str(rest); - out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap), 1) + out +} + +/// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes +/// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose +/// definitions replace the placeholder. In `CoherenceMode::PerInstruction`, `memc.Method(` +/// likewise becomes `xcl_mcMethod(`. +fn windowed(h: &str, windows: u32, heap: bool, coherence: super::CoherenceMode) -> String { + let mut out = rewrite_mem_calls(h, "mem.", "xcl_m"); + if coherence == super::CoherenceMode::PerInstruction { + out = rewrite_mem_calls(&out, "memc.", "xcl_mc"); + } + out.replacen(MEM_ACCESSORS_HERE, &mem_accessors(windows, heap, coherence), 1) } /// The accessor functions: one per `mem` method (and overload) the translator emits. /// Only explicit windows `0..windows` touch GPU buffers; any out-of-range `xcl_w` hits /// `default` (reads return 0, stores/atomics are dropped and zero their `out` parameter) so /// out-of-UMA pointers can never wrap onto live memory windows. -/// `heap`: Some(storage class) – window k is taken from the descriptor heap -/// (`Options::heap_windows`) and the same rule is one comparison before the access. -fn mem_accessors(windows: u32, heap: Option<&str>) -> String { +fn mem_accessors(windows: u32, heap: bool, coherence: super::CoherenceMode) -> String { let mut sigs: Vec<(&str, String, &str, &str, &str)> = vec![ ("uint", "Load".into(), "uint a", "a", "return 0u;"), ("uint2", "Load2".into(), "uint a", "a", "return uint2(0u, 0u);"), @@ -5611,40 +5679,56 @@ fn mem_accessors(windows: u32, heap: Option<&str>) -> String { sigs.push(("void", format!("Interlocked{op}64"), "uint a, int64_t v, out int64_t o", "a, v, o", "o = (int64_t)0; break;")); } } - let mut s = String::new(); - if let Some(coherent) = heap { + let emit_heap = |s: &mut String, macro_name: &str, qual: &str, lx4: &str, prefix: &str, list: &[(&str, String, &str, &str, &str)]| { // one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows // does what the switch's `default` does - let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); - let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); - for (ret, name, params, args, def) in sigs { - let r = if ret == "void" { "" } else { "return " }; + let _ = writeln!(s, "#define {macro_name} {qual}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); + let _ = writeln!(s, "uint4 {lx4}(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} {macro_name}; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + for (ret, name, params, args, def) in list { + let r = if *ret == "void" { "" } else { "return " }; // (the switch's `break` leaves the accessor) let outside = def.replace("break;", "return;"); - let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + let _ = writeln!(s, "{ret} {prefix}{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} {macro_name}; {r}m.{name}({args}); }}"); } - return s; - } - let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ "); - let _ = write!(s, "case 0u: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); "); - for k in 1..windows { - let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); "); - } - let _ = writeln!(s, "default: return uint4(0u, 0u, 0u, 0u); }} }}"); - for (ret, name, params, args, def) in sigs { - let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ "); - if ret == "void" { - let _ = write!(s, "case 0u: mem.{name}({args}); break; "); - for k in 1..windows { - let _ = write!(s, "case {k}u: mem{k}.{name}({args}); break; "); - } - } else { - let _ = write!(s, "case 0u: return mem.{name}({args}); "); - for k in 1..windows { - let _ = write!(s, "case {k}u: return mem{k}.{name}({args}); "); + }; + let emit_root = |s: &mut String, buf: &str, lx4: &str, prefix: &str, list: &[(&str, String, &str, &str, &str)]| { + let _ = write!(s, "uint4 {lx4}(uint4 a) {{ [branch] switch (xcl_w) {{ "); + let _ = write!(s, "case 0u: return uint4({buf}.Load(a.x), {buf}.Load(a.y), {buf}.Load(a.z), {buf}.Load(a.w)); "); + for k in 1..windows { + let _ = write!(s, "case {k}u: return uint4({buf}{k}.Load(a.x), {buf}{k}.Load(a.y), {buf}{k}.Load(a.z), {buf}{k}.Load(a.w)); "); + } + let _ = writeln!(s, "default: return uint4(0u, 0u, 0u, 0u); }} }}"); + for (ret, name, params, args, def) in list { + let _ = write!(s, "{ret} {prefix}{name}({params}) {{ [branch] switch (xcl_w) {{ "); + if *ret == "void" { + let _ = write!(s, "case 0u: {buf}.{name}({args}); break; "); + for k in 1..windows { + let _ = write!(s, "case {k}u: {buf}{k}.{name}({args}); break; "); + } + } else { + let _ = write!(s, "case 0u: return {buf}.{name}({args}); "); + for k in 1..windows { + let _ = write!(s, "case {k}u: return {buf}{k}.{name}({args}); "); + } } + let _ = writeln!(s, "default: {def} }} }}"); + } + }; + let mut s = String::new(); + match (heap, coherence) { + (true, super::CoherenceMode::None) => emit_heap(&mut s, "XCL_MW", "", "xcl_loadx4", "xcl_m", &sigs), + (true, super::CoherenceMode::AllCoherent) => emit_heap(&mut s, "XCL_MW", "globallycoherent ", "xcl_loadx4", "xcl_m", &sigs), + (true, super::CoherenceMode::PerInstruction) => { + emit_heap(&mut s, "XCL_MW", "", "xcl_loadx4", "xcl_m", &sigs[..4]); + emit_heap(&mut s, "XCL_MWC", "globallycoherent ", "xcl_loadx4_c", "xcl_mc", &sigs); + } + (false, super::CoherenceMode::None | super::CoherenceMode::AllCoherent) => { + emit_root(&mut s, "mem", "xcl_loadx4", "xcl_m", &sigs); + } + (false, super::CoherenceMode::PerInstruction) => { + emit_root(&mut s, "mem", "xcl_loadx4", "xcl_m", &sigs[..4]); + emit_root(&mut s, "memc", "xcl_loadx4_c", "xcl_mc", &sigs); } - let _ = writeln!(s, "default: {def} }} }}"); } s } @@ -5860,17 +5944,18 @@ uint4 fmt_pack(uint4 v, uint info) { [unroll] for (uint c = 0u; c < 4u; c++) { if (c < n) { uint w = (info >> (8u + 6u * c)) & 63u; put_bits(r, off, w, fmt_encode(v[c], info, c)); off += w; } } return r; } -void st_part(uint b, uint m, uint v) { mem.InterlockedAnd(b, ~m); mem.InterlockedOr(b, v & m); } -void st_bytes(uint a, uint4 r, uint n) { - uint s = (a & 3u) * 8u; uint b = a & ~3u; - if (s == 0u && (n & 3u) == 0u) { [unroll] for (uint k = 0u; k < 4u; k++) if (k * 4u < n) mem.Store(b + 4u * k, r[k]); return; } - uint m = n >= 4u ? 0xFFFFFFFFu : ((1u << (8u * n)) - 1u); - st_part(b, m << s, r.x << s); - if (s != 0u && s + 8u * n > 32u) st_part(b + 4u, m >> (32u - s), r.x >> (32u - s)); -} uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, select(sel == 1u, select(isint, 1u, 0x3F800000u), pick4(c, (sel - 4u) & 3u))); } "#; +const PRELUDE_LD_RAW_COHERENT: &str = r#" +uint4 ld_raw_c(uint a) { + uint b = a & ~3u; uint s = (a & 3u) * 8u; + uint4 w = memc.Load4(b); uint w4 = memc.Load(b + 16u); + uint4 n = uint4(w.yzw, w4); + return select((s == 0u).xxxx, w, (w >> s) | (n << ((32u - s) & 31u))); +} +"#; + /// A console wave64 as two hardware wave32 halves of one thread group (docs/wave64-on-wave32.md): /// per-lane code is unchanged, and the halves meet ("exchange") wherever a value has to be /// the whole wave's – masks, lane reads, coherent scalar loads – so both hold the same SGPRs diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 688c45cb72..978dd74b84 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -45,7 +45,7 @@ struct DxilIr { impl DxilIr { /// The builder state for `insts` at `entry` (a kernel or a compute program), with one memory - /// window; a compute program's is coherent when `needs_coherent_mem` holds, matching the HLSL path. + /// window; a compute program's coherence policy follows `coherence_mode`, matching the HLSL path. fn new(insts: &[Decoded], wave64: bool, entry: &Entry) -> DxilIr { Self::with(insts, KernelOptions { wave64, split: false, mem_windows: 1, sampler_base: 0 }, entry) } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 70a92bc955..7a3f5bbd67 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1383,32 +1383,62 @@ pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> B out } -/// Does the program require `globallycoherent` flat memory windows (`mem`, `mem1`…)? -/// -/// Compute work that coordinates across workgroups (e.g. bottom-up BVH builds: atomics, -/// then reading what other groups wrote) relies on `GLC`/`DLC`/`SLC`, memory atomics, or -/// cache invalidation on the console. Programs without any of those only access read-only -/// or disjointly written memory within the dispatch, so keeping their flat memory windows -/// un-qualified lets the GPU cache them in L1. -pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { - insts.iter().any(|d| { - let name = d.inst.name; - if matches!(name, "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV") { - return true; - } - if name.starts_with("BUFFER_ATOMIC_") - || name.starts_with("GLOBAL_ATOMIC_") - || name.starts_with("FLAT_ATOMIC_") - { - return true; - } - matches!( - d.enc.name, - "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" - ) && ["GLC", "DLC", "SLC"] +/// How a compute shader accesses flat memory windows (`mem`, `mem1`… or `XCL_HEAP_WINDOWS`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CoherenceMode { + /// No flat-memory coherence operations anywhere in the program: every access uses the plain + /// (L1-cached) memory window. + None, + /// Program uses flat-memory atomics and/or `GLC`/`DLC`/`SLC` memory ops, but no data-cache + /// invalidation: + /// - ordinary loads (`!GLC && !DLC && !SLC`) use plain (L1-cached) views, + /// - `GLC`/`DLC`/`SLC` loads, all stores, and all atomics use `globallycoherent` views. + /// + /// Keeping stores on the coherent view preserves cross-workgroup store visibility (matching + /// RDNA2's write-through GL0) while letting ordinary loads stay L1-cached. + PerInstruction, + /// Program executes a data-cache invalidation (`S_DCACHE_INV`, `S_GL1_INV`, `BUFFER_GL0_INV`, + /// `BUFFER_GL1_INV`), which makes subsequent `GLC=0` loads observe cross-workgroup writes. + /// Because D3D12 has no L1-invalidate intrinsic for non-coherent UAVs, keep every memory + /// access in the program `globallycoherent`. + AllCoherent, +} + +pub(crate) fn inst_is_cache_inv(d: &Decoded) -> bool { + matches!(d.inst.name, "S_DCACHE_INV" | "S_GL1_INV" | "BUFFER_GL0_INV" | "BUFFER_GL1_INV") +} + +pub(crate) fn inst_is_flat_atomic(d: &Decoded) -> bool { + let name = d.inst.name; + name.starts_with("BUFFER_ATOMIC_") + || name.starts_with("GLOBAL_ATOMIC_") + || name.starts_with("FLAT_ATOMIC_") + || name.starts_with("S_ATOMIC_") +} + +pub(crate) fn inst_has_mem_coherence_bits(d: &Decoded) -> bool { + matches!(d.enc.name, "ENC_SMEM" | "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL") + && ["GLC", "DLC", "SLC"] .iter() .any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)) - }) +} + +/// Classifies a compute program's flat-memory coherence requirements. +pub(crate) fn coherence_mode(insts: &[Decoded]) -> CoherenceMode { + let mut needs_per_inst = false; + for d in insts { + if inst_is_cache_inv(d) { + return CoherenceMode::AllCoherent; + } + if !needs_per_inst && (inst_is_flat_atomic(d) || inst_has_mem_coherence_bits(d)) { + needs_per_inst = true; + } + } + if needs_per_inst { + CoherenceMode::PerInstruction + } else { + CoherenceMode::None + } } pub fn translate(code: &[u8], opt: &Options) -> Result { @@ -1461,7 +1491,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } } let mut em = emit::Em::new(opt.clone()); - em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); + em.coherence = if matches!(opt.mode, Mode::Compute(_)) { coherence_mode(&insts) } else { CoherenceMode::None }; em.configure_round_modes(&insts, branches == 0); em.static_ss = constant_samplers(&insts, &leaders); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b6dd120ff1..7251b48016 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1046,8 +1046,9 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { - // u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding) - let params: Vec = (0..6) + // u0 io, u1 res, u2..u5 plain memory windows, u6..u9 coherent memory-window aliases + // (`gpu::uma`; unused ones need no binding) + let params: Vec = (0..10) .map(|i| D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: D3D12_ROOT_PARAMETER1_0 { diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ed683350f7..da5e99bc65 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -702,6 +702,7 @@ pub fn run_with_statics( list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, res_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(2, mem_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(6, mem_buf.GetGPUVirtualAddress()); list.Dispatch(1, 1, 1); list.ResourceBarrier(&[ transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), @@ -1545,7 +1546,9 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result)> = vec![ + let per_inst_cases: Vec<(&str, Vec)> = vec![ ("smem glc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("GLC", 1)])])), ("smem dlc", prog(&[("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125), ("DLC", 1)])])), ("mubuf glc", prog(&[("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("GLC", 1)])])), @@ -9063,6 +9064,8 @@ fn compute_globallycoherent_only_when_needed() { ("buffer_atomic", prog(&[("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128)])])), ("global_atomic", prog(&[("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("DATA", 2), ("SADDR", 0)])])), ("flat_atomic", prog(&[("FLAT_ATOMIC_ADD", "ENC_FLAT", &[("VDST", 1), ("ADDR", 2), ("DATA", 4)])])), + ]; + let all_coherent_cases: Vec<(&str, Vec)> = vec![ ("s_dcache_inv", prog(&[("S_DCACHE_INV", "ENC_SMEM", &[])])), ("s_gl1_inv", prog(&[("S_GL1_INV", "ENC_SMEM", &[])])), ("buffer_gl0_inv", prog(&[("BUFFER_GL0_INV", "ENC_MUBUF", &[])])), @@ -9075,26 +9078,40 @@ fn compute_globallycoherent_only_when_needed() { assert!(t.complete(), "{:?}", t.unsupported_why); assert!(!t.hlsl.contains("globallycoherent"), "plain CS (windows={windows}, heap={heap}) must not emit globallycoherent:\n{}", t.hlsl); - for (label, code) in &coherent_cases { + for (label, code) in &per_inst_cases { let t = translate(code, &opt).unwrap(); assert!(t.complete(), "{label}: {:?}", t.unsupported_why); assert!(t.hlsl.contains("globallycoherent"), "{label} (windows={windows}, heap={heap}) must emit globallycoherent"); if heap { - assert!(t.hlsl.contains("#define XCL_MW globallycoherent RWByteAddressBuffer"), "{label}: heap window accessor must be globallycoherent"); + assert!(t.hlsl.contains("#define XCL_MW RWByteAddressBuffer"), "{label}: plain heap window macro expected"); + assert!(t.hlsl.contains("#define XCL_MWC globallycoherent RWByteAddressBuffer"), "{label}: coherent heap window macro expected"); + } else { + assert!(t.hlsl.contains("RWByteAddressBuffer mem : register(u2);"), "{label}: plain mem expected"); + assert!(t.hlsl.contains("globallycoherent RWByteAddressBuffer memc : register(u6);"), "{label}: coherent memc expected"); + } + } + for (label, code) in &all_coherent_cases { + let t = translate(code, &opt).unwrap(); + assert!(t.complete(), "{label}: {:?}", t.unsupported_why); + assert!(t.hlsl.contains("globallycoherent RWByteAddressBuffer mem : register(u2);"), "{label}: all-coherent mem expected"); + assert!(!t.hlsl.contains("memc"), "{label}: all-coherent must not split memc"); + if heap { + assert!(t.hlsl.contains("#define XCL_MW globallycoherent RWByteAddressBuffer"), "{label}: all-coherent heap window accessor expected"); + assert!(!t.hlsl.contains("XCL_MWC"), "{label}: all-coherent must not emit XCL_MWC"); } } } // Kernel mode stays non-coherent even with atomics. - let k = translate(&coherent_cases[6].1, &Options { mode: Mode::Kernel, wave64: false, ..Default::default() }).unwrap(); + let k = translate(&per_inst_cases[6].1, &Options { mode: Mode::Kernel, wave64: false, ..Default::default() }).unwrap(); assert!(!k.hlsl.contains("globallycoherent"), "kernel mode must not emit globallycoherent"); // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). - for mw in [1u32, super::HEAP_WINDOWS | 2] { + for mw in [1u32, 2, super::HEAP_WINDOWS | 2] { let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &cs).unwrap(); - let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); + let coh_k = crate::gpu::dxil::kernel::translate_compute(&per_inst_cases[6].1, o, &cs).unwrap(); if super::dxc::location().is_ok() { let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); let coh_dis = crate::gpu::dxil::validate::disassemble(&coh_k.dxil).unwrap(); @@ -9104,6 +9121,72 @@ fn compute_globallycoherent_only_when_needed() { } } +/// Verifies per-instruction coherence routing: in a compute shader with atomics/GLC but no +/// cache invalidation, ordinary loads (`GLC=0 && DLC=0 && SLC=0`) stay on the cached plain +/// view while `GLC`/`DLC`/`SLC` loads, all stores, and all atomics use the `globallycoherent` +/// view — across single-window, multi-window root UAV, multi-window heap, and direct DXIL. +#[test] +fn compute_per_instruction_globallycoherent() { + let cs = super::CsInterface { threads: [32, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + let enc = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + + let mut mixed = Vec::new(); + // Ordinary loads (GLC=0, DLC=0, SLC=0) -> plain view (`mem` / `xcl_m*` / `ld_raw`) + mixed.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)])); + mixed.extend(enc("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128)])); + mixed.extend(enc("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 0), ("SADDR", 0)])); + // Coherent loads (GLC=1 / DLC=1) -> coherent view (`memc` / `xcl_mc*`) + mixed.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 9), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125), ("GLC", 1)])); + mixed.extend(enc("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 3), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("DLC", 1)])); + mixed.extend(enc("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 4), ("ADDR", 0), ("SADDR", 0), ("GLC", 1)])); + // Ordinary store (GLC=0) -> coherent view (write-through visibility) + mixed.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0)])); + // Atomic -> coherent view + mixed.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 0), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); + mixed.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); + + // 1. Single window + let t1 = translate(&mixed, &Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: 1, ..Default::default() }).unwrap(); + assert!(t1.complete(), "{:?}", t1.unsupported_why); + assert!(t1.hlsl.contains("RWByteAddressBuffer mem : register(u2);")); + assert!(t1.hlsl.contains("globallycoherent RWByteAddressBuffer memc : register(u6);")); + let body1 = t1.hlsl.split("void main(").nth(1).unwrap(); + assert!(body1.contains("mem.Load("), "ordinary loads must use plain mem.Load:\n{body1}"); + assert!(body1.contains("memc.Load("), "GLC/DLC loads must use memc.Load:\n{body1}"); + assert!(body1.contains("memc.Store("), "stores must use memc.Store:\n{body1}"); + assert!(!body1.contains("mem.Store("), "stores must not use plain mem.Store:\n{body1}"); + assert!(body1.contains("memc.InterlockedAdd("), "atomics must use memc.InterlockedAdd:\n{body1}"); + assert!(!body1.contains("mem.Interlocked"), "atomics must not use plain mem.Interlocked:\n{body1}"); + + // 2. Multi-window root UAV + multi-window heap + for heap in [false, true] { + let tm = translate(&mixed, &Options { mode: Mode::Compute(cs.clone()), wave64: false, mem_windows: 2, heap_windows: heap, ..Default::default() }).unwrap(); + assert!(tm.complete(), "heap={heap}: {:?}", tm.unsupported_why); + let bodym = tm.hlsl.split("void main(").nth(1).unwrap(); + assert!(bodym.contains("xcl_mLoad("), "heap={heap}: ordinary loads must use xcl_mLoad:\n{bodym}"); + assert!(bodym.contains("xcl_mcLoad("), "heap={heap}: coherent loads must use xcl_mcLoad:\n{bodym}"); + assert!(bodym.contains("xcl_mcStore("), "heap={heap}: stores must use xcl_mcStore:\n{bodym}"); + assert!(bodym.contains("xcl_mcInterlockedAdd("), "heap={heap}: atomics must use xcl_mcInterlockedAdd:\n{bodym}"); + assert!(!bodym.contains("xcl_mStore("), "heap={heap}: stores must not use xcl_mStore:\n{bodym}"); + assert!(!bodym.contains("xcl_mInterlocked"), "heap={heap}: atomics must not use xcl_mInterlocked:\n{bodym}"); + if super::dxc::location().is_ok() { + super::dxc::compile(&tm.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("DXC compile heap={heap} failed: {e}")); + } + } + + // 3. Direct DXIL: both plain (`i32 4107`) and coherent (`i32 20491`) raw-buffer UAVs present + // and validated for single-window, multi-window root UAV, and multi-window heap. + for mw in [1u32, 2, super::HEAP_WINDOWS | 2] { + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; + let k = crate::gpu::dxil::kernel::translate_compute(&mixed, o, &cs).unwrap(); + if super::dxc::location().is_ok() { + let dis = crate::gpu::dxil::validate::disassemble(&k.dxil).unwrap(); + assert!(dis.contains("i32 4107"), "direct DXIL mixed (mw={mw:#x}) must have plain UAV handle:\n{dis}"); + assert!(dis.contains("i32 20491"), "direct DXIL mixed (mw={mw:#x}) must have coherent UAV handle:\n{dis}"); + } + } +} + /// Real GPU check of both non-coherent (cached) and coherent (cross-workgroup atomic + GLC) /// compute shaders across HLSL and direct DXIL. #[test] @@ -9143,29 +9226,55 @@ fn gpu_compute_coherent_and_cached_loads() { } } - // 2. Cross-workgroup coherent compute: 16 groups of 32 threads atomically increment a shared - // counter at mem[0x100] and record their returned ticket at mem[0x200 + ticket * 4]. + // 2. Mixed per-instruction coherent compute: 16 groups of 32 threads do ordinary cached + // SMEM (`mem[0x100]`) + ordinary cached GLOBAL load (`mem[0x400 + idx*4]`), atomically + // claim a unique ticket at `mem[0x104]`, write `(const + in[idx] + ticket)` coherently + // to `mem[0x1000 + ticket*4]`, and read back `mem[0x104]` with `GLC=1` to `mem[0x1800 + idx*4]`. + let cs_mix = super::CsInterface { threads: [32, 1, 1], user_sgprs: 6, tgid: [true, false, false], tg_size: false, tid_components: 1 }; let mut coh = Vec::new(); - coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 128)])); // v1 = 0 + coh.extend(enc("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 8), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)])); // s8 = mem[0x100] (plain) + coh.extend(enc("S_LSHL_B32", "ENC_SOP2", &[("SDST", 7), ("SSRC0", 6), ("SSRC1", 133)])); // s7 = tgid(s6) * 32 + coh.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 7), ("VSRC1", 0)])); // v6 = idx + coh.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 130), ("VSRC1", 6)])); // v7 = idx * 4 + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)])); // v8 = 0 + coh.extend(enc("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 9), ("ADDR", 7), ("SADDR", 0x7D), ("OFFSET", 0x400)])); // v9 = mem[0x400 + idx*4] (plain) + coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 132)])); // v1 = 4 (offset 0x104 from s[0:1]=0x100) coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 129)])); // v2 = 1 - coh.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); + coh.extend(enc("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("DATA", 2), ("SADDR", 0), ("GLC", 1)])); // v3 = ticket (coherent) + coh.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 8), ("VSRC1", 9)])); // v10 = s8 + v9 + coh.extend(enc("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 10), ("SRC0", 256 + 3), ("VSRC1", 10)])); // v10 = s8 + v9 + ticket coh.extend(enc("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 130), ("VSRC1", 3)])); // v4 = ticket * 4 - coh.extend(enc("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 128)])); - coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 3), ("SADDR", 0x7D), ("OFFSET", 0x200), ("GLC", 1)])); + coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 4), ("DATA", 10), ("SADDR", 2), ("OFFSET", 0)])); // coherent store -> s[2:3]=0x1000 + coh.extend(enc("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 11), ("ADDR", 1), ("SADDR", 0), ("GLC", 1)])); // v11 = coherent read of counter + coh.extend(enc("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 11), ("SADDR", 4), ("OFFSET", 0)])); // coherent store -> s[4:5]=0x1800 coh.extend(enc("S_ENDPGM", "ENC_SOPP", &[])); - let t_coh = translate(&coh, &Options { mode: Mode::Compute(cs.clone()), wave64: false, ..Default::default() }).unwrap(); + let t_coh = translate(&coh, &Options { mode: Mode::Compute(cs_mix.clone()), wave64: false, ..Default::default() }).unwrap(); assert!(t_coh.complete(), "{:?}", t_coh.unsupported_why); - assert!(t_coh.hlsl.contains("globallycoherent")); + assert!(t_coh.hlsl.contains("globallycoherent RWByteAddressBuffer memc : register(u6);")); let dxil_coh_hlsl = super::dxc::compile(&t_coh.hlsl, "main", "cs_6_6", &[]).unwrap(); - let dxil_coh_direct = crate::gpu::dxil::kernel::translate_compute(&coh, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs).unwrap().dxil; + let dxil_coh_direct = crate::gpu::dxil::kernel::translate_compute(&coh, crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }, &cs_mix).unwrap().dxil; - let mem2 = vec![0u32; (0x200 + 512 * 4) / 4]; + let mut io_mix = vec![0u32; super::KERNEL_SGPRS]; + io_mix[0] = 0x100; + io_mix[2] = 0x1000; + io_mix[4] = 0x1800; + let mut mem2 = vec![0u32; (0x1800 + 512 * 4) / 4]; + mem2[0x100 / 4] = 0x1000_0000; + for idx in 0..512usize { + mem2[(0x400 + idx * 4) / 4] = 0x2000; // uniform per-lane input so ticket order still has unique exact value + } for (tag, dxil) in [("hlsl", &dxil_coh_hlsl), ("direct", &dxil_coh_direct)] { - let out = runner::dispatch(dxil, [16, 1, 1], &io, &mem2).unwrap(); - assert_eq!(out[0x100 / 4], 512, "{tag} coherent cross-group counter"); + let out = runner::dispatch(dxil, [16, 1, 1], &io_mix, &mem2).unwrap(); + assert_eq!(out[0x104 / 4], 512, "{tag} coherent cross-group counter"); for ticket in 0..512usize { - assert_eq!(out[(0x200 + ticket * 4) / 4], ticket as u32, "{tag} coherent ticket={ticket}"); + assert_eq!( + out[(0x1000 + ticket * 4) / 4], + 0x1000_2000 + ticket as u32, + "{tag} per-instruction mixed output ticket={ticket}" + ); + let seen = out[(0x1800 + ticket * 4) / 4]; + assert!((1..=512).contains(&seen), "{tag} coherent GLC load saw counter={seen}"); } } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index da5b15ef42..750b711e4f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -973,7 +973,8 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); + let win_vas: [u64; 4] = std::array::from_fn(|k| windows.get(k).copied().unwrap_or(first)); + let views = [va(io_at), va(res_at)].into_iter().chain(win_vas); if gfx { list.SetGraphicsRootSignature(rs); for (k, v) in views.enumerate() { @@ -984,6 +985,10 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi for (k, v) in views.enumerate() { list.SetComputeRootUnorderedAccessView(k as u32, v); } + // u6..u9: coherent aliases of memory windows u2..u5 for per-instruction globallycoherent + for (k, v) in win_vas.into_iter().enumerate() { + list.SetComputeRootUnorderedAccessView(6 + k as u32, v); + } } let real = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 3a3480f18b..fd7316b9a9 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -849,7 +849,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(uma_va)); + let win_va = windows.get(k).copied().unwrap_or(uma_va); + list.SetComputeRootUnorderedAccessView(2 + k as u32, win_va); + list.SetComputeRootUnorderedAccessView(6 + k as u32, win_va); } let raw = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; From 9b35718ffd32170a4fdd88601ce7e60ef8ec0393 Mon Sep 17 00:00:00 2001 From: sip Date: Wed, 25 Nov 2026 06:55:43 +0300 Subject: [PATCH 3/3] Direct DXIL per-lane: preserve per-instruction coherence on single-window shortcuts In single-window per-lane mode, lower::smem and lower::vmem call Ir::mem_load and Ir::mem_store directly instead of going through Lw's foreign bridge. Add an Ir::mem_instruction hook so DxilIr updates Lw::inst_coherent_load and routes GLC/DLC loads and all mixed-policy stores to the coherent alias (mems_coh[0], u6) rather than plain mem (u2). Reported and verified by @WebIdentity1 on #2067. --- crates/xcl/src/gpu/recomp/lower.rs | 3 + crates/xcl/src/gpu/recomp/lower_dxil.rs | 85 ++++++++++++++++++++++++- 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index ca82cf4292..7eae6d874b 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -102,6 +102,8 @@ pub trait Ir: Sink { /// the dword of the flat memory (`mem`, u2) at a byte address (a multiple of 4); out of /// range reads 0 and writes nothing, as D3D12 raw buffers do fn mem_load(&mut self, addr: Self::V) -> Self::V; + /// Memory policy for the single-window shortcuts of the instruction about to be lowered. + fn mem_instruction(&mut self, _d: &Decoded) {} fn mem_store(&mut self, addr: Self::V, value: Self::V); /// the 4 GiB memory windows the program addresses: with more than one, `mem_load` / /// `mem_store` (window 0 only) are not used, and memory instructions go to `foreign` @@ -1753,6 +1755,7 @@ impl Lower<'_, I> { /// Lowers one non-terminator instruction in block `b`, falling back to `bridge`. fn lower_inst(&mut self, b: usize, d: &Decoded) -> R<()> { + self.ir.mem_instruction(d); let name = d.inst.name; let r = if name.starts_with("S_LOAD_") || name.starts_with("S_BUFFER_LOAD_") { self.smem(b, d) diff --git a/crates/xcl/src/gpu/recomp/lower_dxil.rs b/crates/xcl/src/gpu/recomp/lower_dxil.rs index 978dd74b84..712f3210bb 100644 --- a/crates/xcl/src/gpu/recomp/lower_dxil.rs +++ b/crates/xcl/src/gpu/recomp/lower_dxil.rs @@ -305,12 +305,21 @@ impl Ir for DxilIr { let res = self.res.expect("res is bound in kernel mode"); self.lw.s.raw_store(res, a, &[value]); } + fn mem_instruction(&mut self, d: &Decoded) { + self.lw.inst_coherent_load = self.lw.coherence == super::CoherenceMode::AllCoherent + || super::inst_has_mem_coherence_bits(d) + || super::inst_is_flat_atomic(d); + } fn mem_load(&mut self, addr: Value) -> Value { - let mem = self.mem; + let mem = if self.lw.inst_coherent_load { + self.lw.mems_coh.first().copied().unwrap_or(self.mem) + } else { + self.mem + }; self.lw.s.raw_load(mem, addr, 1)[0] } fn mem_store(&mut self, addr: Value, value: Value) { - let mem = self.mem; + let mem = self.lw.mems_coh.first().copied().unwrap_or(self.mem); self.lw.s.raw_store(mem, addr, &[value]); } // through `Lw`, which records the edges for its own variables (the split form's exchange @@ -1005,4 +1014,76 @@ mod tests { } } } + + /// Single-window per-lane memory shortcuts must honor the same per-instruction coherence + /// policy as bridged memory operations (plain loads on u2, GLC/DLC loads and stores on u6). + #[test] + fn per_lane_memory_shortcuts_preserve_coherence() { + use crate::gpu::dxil::module::{Block, InstInfo}; + let lines: &[I] = &[ + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 125)]), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 5), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125), ("GLC", 1)]), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 6), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125), ("DLC", 1)]), + ("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 130), ("VSRC1", 0)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 2), ("ADDR", 1), ("SADDR", 0)]), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 1), ("SADDR", 0), ("GLC", 1)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 4), ("VSRC1", 2)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 5), ("VSRC1", 4)]), + ("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 4), ("SRC0", 6), ("VSRC1", 4)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 4), ("SADDR", 2)]), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 3), ("SADDR", 2), ("OFFSET", 128)]), + ENDPGM, + ]; + let insts = decode(lines); + let cs = crate::gpu::recomp::CsInterface { threads: [32, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let initial = super::DxilIr::new(&insts, false, &super::Entry::Compute(cs.clone())); + let ir = super::lower::lower_compute(&insts, &cs, false, initial).unwrap(); + let m = &ir.lw.s.m; + let binding = |handle| { + let super::Value::Inst(i) = handle else { panic!("handle is not an instruction") }; + let InstInfo::Call(name, args) = m.inst_info(i) else { panic!("handle is not annotated") }; + assert_eq!(name, "dx.op.annotateHandle"); + let super::Value::Inst(i) = args[1] else { panic!("binding is not an instruction") }; + let InstInfo::Call(name, args) = m.inst_info(i) else { panic!("missing binding") }; + assert_eq!(name, "dx.op.createHandleFromBinding"); + m.const_u64(args[2]).unwrap() + }; + let mut counts = [0usize; 4]; // [plain loads, coherent loads, plain stores, coherent stores] + for b in 0..m.block_count() { + for &i in m.block_insts(Block(b as u32)) { + if let InstInfo::Call(name, args) = m.inst_info(i) { + let slot = if name.starts_with("dx.op.rawBufferLoad.") { + 0 + } else if name.starts_with("dx.op.rawBufferStore.") { + 2 + } else { + continue; + }; + if binding(args[1]) == 2 { + counts[slot] += 1; + } + if binding(args[1]) == 6 { + counts[slot + 1] += 1; + } + } + } + } + assert_eq!(counts, [2, 3, 0, 2], "GLC/DLC loads and all mixed-policy stores must use the coherent alias"); + let dxil = ir.finish(cs.threads, 32).unwrap().dxil; + crate::gpu::dxil::validate::validate(&dxil).unwrap(); + if gpu() { + let mut io = vec![0u32; super::super::KERNEL_SGPRS]; + io[0] = 0x100; + io[2] = 0x200; + let mut mem = vec![0u32; 0x400 / 4]; + for lane in 0..32 { + mem[0x100 / 4 + lane] = 100 + lane as u32; + } + let out = runner::dispatch(&dxil, [1, 1, 1], &io, &mem).unwrap(); + for lane in 0..32 { + assert_eq!(out[0x200 / 4 + lane], 403 + lane as u32); + assert_eq!(out[0x280 / 4 + lane], 100 + lane as u32); + } + } + } }