From ecc9723b6cdbd8e33ea00fabfa72987ba71337bc Mon Sep 17 00:00:00 2001 From: sip Date: Wed, 25 Nov 2026 00:40:27 +0300 Subject: [PATCH] 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 94ce0b37d..d3e29c500 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 8f257a043..9d522391c 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 2c200c788..688c45cb7 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 d1e7d8bc4..70a92bc95 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 527dc4e64..fa1d9d71b 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}"); + } + } +}