diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 94ce0b37d..50b7cbcf6 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -476,6 +476,7 @@ impl Lw { f32_rm: false, track_frexp_denorm: crate::gpu::recomp::emit::tracks_frexp_f32_denorm(insts), has_f64_round_op: false, + img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), exec_cache: HashMap::new(), xs: None, xw: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 0e270bb60..5b2a42176 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -29,6 +29,9 @@ pub const VAR_WIN: u32 = VAR_BUDGET + 2; /// arrived" flag (`xcl_xk`, `xcl_x_dead`) pub const VAR_XK: u32 = VAR_BUDGET + 3; pub const VAR_XDEAD: u32 = VAR_BUDGET + 4; +/// `tw0 + 1` of the last image store / atomic through the k-th T# of `Lw::img_writes` (16 +/// slots; the recompiler's `xcl_iw{srsrc}`) +pub const VAR_IMG_WRITE: u32 = VAR_BUDGET + 8; /// loop iterations a lane may run (the recompiler's `xcl_budget`) pub const LOOP_BUDGET: u32 = 1 << 16; @@ -115,7 +118,7 @@ impl Init { if var == super::lower_round::VAR_F32_MODE { return s.m.i32c(super::lower_round::MODE_INIT); } - if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD { + if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) { return s.m.i32c(0); } if var >= super::lower_mem::VAR_TMP { @@ -208,6 +211,8 @@ pub struct Lw { pub f32_rm: bool, pub track_frexp_denorm: bool, pub has_f64_round_op: bool, + /// the T# SGPRs of the program's image stores and atomics (`recomp::emit::image_write_srsrcs`) + pub img_writes: Vec, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index 07c5aba4a..3cad6268e 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -800,6 +800,16 @@ impl Lw { let fmt = self.lshrc(tw1, 20); let fmt = self.andc(fmt, 0x1FF); let cls = self.img_cls(fmt); + // an image store / atomic records its T# (`tw0 + 1`): a later image_load of the image + // reads through the UAV (`recomp::emit::image_write_srsrcs`) + if base.starts_with("store") || base.starts_with("atomic_") { + if let Some(k) = self.img_writes.iter().position(|&s| s == srsrc) { + let var = super::lower::VAR_IMG_WRITE + k as u32; + let (cur, t1) = (self.rd(var), self.addc(tw0, 1)); + let nv = self.sel(valid, t1, cur); + self.wr(var, nv); + } + } if ms { return self.mimg_msaa(base, &ic, tw0, lkind, cls, &comps, vdata, d16, act, run); } @@ -810,10 +820,32 @@ impl Lw { for &t in &tmps { self.wr(t, z); } + // an image this invocation stored to: through the UAV, which sees the store (the + // SRV need not within a dispatch); image_load only – a UAV view is one mip + let mut rw = None; + if base == "load" && !self.img_writes.is_empty() { + let t1 = self.addc(tw0, 1); + for k in 0..self.img_writes.len() { + let w = self.rd(super::lower::VAR_IMG_WRITE + k as u32); + let e = self.cmp(Pred::Eq, w, t1); + rw = Some(match rw { + Some(r) => self.lor(r, e), + None => e, + }); + } + } + let ui = self.addc(tw0, 1); for (cv, ct) in [(1u32, CompType::U32), (2, CompType::I32), (0, CompType::F32)] { let is = self.cmpc(Pred::Eq, cls, cv); let c = self.land(run, is); - self.guarded(c, &mut |lw| { + let (c_srv, c_uav) = match rw { + Some(r) => { + let nr = self.lnot(r); + (self.land(c, nr), Some(self.land(c, r))) + } + None => (c, None), + }; + self.guarded(c_srv, &mut |lw| { let tex: Texture = lw.s.heap_texture(tw0, lkind, false, ct, 4, true); let r = lw.s.texture_load(tex, Some(mip), &ic, &[]); for k in 0..4 { @@ -822,6 +854,18 @@ impl Lw { } Ok(()) })?; + if let Some(cu) = c_uav { + self.guarded(cu, &mut |lw| { + lw.s.typed_uav_load_additional_formats(); + let tex: Texture = lw.s.heap_texture(ui, lkind, true, ct, 4, true); + let r = lw.s.texture_load(tex, None, &ic, &[]); + for k in 0..4 { + let b = lw.bits(r[k]); + lw.wr(tmps[k], b); + } + Ok(()) + })?; + } } let r: Vec = tmps.iter().map(|&t| self.rd(t)).collect(); let vals: Vec = if d16 { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 8f257a043..899d6387f 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -68,6 +68,28 @@ 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, + /// the T# SGPRs of the program's image stores and atomics (`image_write_srsrcs`) + img_writes: Vec, +} + +/// The T# SGPRs (SRSRC) of a program's image stores and atomics, at most 16, sorted. An +/// image_load reads through the UAV (`tw0 + 1`) where the invocation stored to the same image +/// before (`xcl_iw{srsrc}` holds `tw0 + 1` of the last such store): the SRV need not see a +/// write of the same dispatch, and RDNA reads its own writes. +pub fn image_write_srsrcs(insts: &[Decoded]) -> Vec { + let mut v: Vec = insts + .iter() + .filter(|d| d.enc.name.starts_with("ENC_MIMG")) + .filter(|d| { + let n = d.inst.name.to_ascii_lowercase(); + n.starts_with("image_store") || n.starts_with("image_atomic") + }) + .map(|d| rdna2::field_value(d.enc, &d.words, "SRSRC").unwrap_or(0) * rdna2::register_scale("SRSRC")) + .collect(); + v.sort_unstable(); + v.dedup(); + v.truncate(16); + v } /// Instructions without an effect in this execution model. @@ -594,6 +616,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + img_writes: Vec::new(), } } @@ -612,6 +635,7 @@ impl Em { /// and multi-warp `s_barrier` usage (for early-exit-safe, bounded `xcl_s_barrier`). pub fn configure_round_modes(&mut self, insts: &[Decoded], stop_at_endpgm: bool) { self.track_frexp_denorm = tracks_frexp_f32_denorm(insts); + self.img_writes = image_write_srsrcs(insts); let mut writes_nonzero_dp = false; let mut has_s_barrier = false; for d in insts { @@ -2849,17 +2873,35 @@ impl Em { return Err("image_load cube"); } self.line(&format!("uint {t}_cls = img_cls(({tw1} >> 20) & 0x1FFu);")); + if (base.starts_with("store") || base.starts_with("atomic_")) && self.img_writes.contains(&srsrc) { + self.line(&format!("if ({t}_ok) xcl_iw{srsrc} = {tw0} + 1u;")); + } match base { "load" | "load_mip" => { self.line(&format!("uint4 {t}_r = uint4(0u, 0u, 0u, 0u);")); let ld = if dim == 6 { format!("{t}_T.Load({icoord}, {})", ic.get(2).cloned().unwrap_or("0u".into())) } else { format!("{t}_T.Load({load_arg})") }; let tex = |vt: &str| format!("Texture{rty}<{vt}4> {t}_T = ResourceDescriptorHeap[NonUniformResourceIndex({tw0})];"); - self.line(&format!( - "if (and({act}, {t}_ok)) {{ if ({t}_cls == 1u) {{ {} {t}_r = {ld}; }} else if ({t}_cls == 2u) {{ {} {t}_r = asuint({ld}); }} else {{ {} {t}_r = asuint({ld}); }} }}", + let srv = format!( + "if ({t}_cls == 1u) {{ {} {t}_r = {ld}; }} else if ({t}_cls == 2u) {{ {} {t}_r = asuint({ld}); }} else {{ {} {t}_r = asuint({ld}); }}", tex("uint"), tex("int"), tex("float") - )); + ); + // an image this invocation stored to: through the UAV, which sees the store (the + // SRV need not within a dispatch); image_load only – a UAV view is one mip + let rw: Vec = if base == "load" && dim != 6 { self.img_writes.iter().map(|s| format!("xcl_iw{s} == {tw0} + 1u")).collect() } else { Vec::new() }; + if rw.is_empty() { + self.line(&format!("if (and({act}, {t}_ok)) {{ {srv} }}")); + } else { + let uav = |vt: &str| format!("RWTexture{rty}<{vt}4> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];"); + self.line(&format!("bool {t}_rw = {};", rw.join(" || "))); + self.line(&format!( + "if (and({act}, {t}_ok)) {{ if ({t}_rw) {{ if ({t}_cls == 1u) {{ {} {t}_r = {t}_U[{icoord}]; }} else if ({t}_cls == 2u) {{ {} {t}_r = asuint({t}_U[{icoord}]); }} else {{ {} {t}_r = asuint({t}_U[{icoord}]); }} }} else {{ {srv} }} }}", + uav("uint"), + uav("int"), + uav("float") + )); + } let cls = format!("{t}_cls"); let half = move |e: &str| format!("(({cls} == 0u) ? f32tof16(asfloat({e})) : ({e} & 0xFFFFu))"); let comps2 = comps.clone(); @@ -4703,6 +4745,9 @@ impl Em { if self.track_frexp_denorm { h.push_str("static uint xcl_frexp_f32_denorm = 0u;\n"); } + for s in &self.img_writes { + let _ = writeln!(h, "static uint xcl_iw{s} = 0u; // tw0 + 1 of the last image store / atomic through s{s}"); + } let mut sg: BTreeSet = self.sgprs.clone(); sg.extend([106, 107, 124, 126, 127]); let load_sgprs = |h: &mut String| { diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index ed683350f..a9c617f7f 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -387,9 +387,9 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t uv.Anonymous.Buffer = D3D12_BUFFER_UAV { NumElements: t.width, ..Default::default() }; } } - if !t.uav { - dev.CreateShaderResourceView(&r, Some(&sv), at(&heap, 2 * i, inc)); - } + // a UAV texture has its SRV too, as D3D12.X gives a console image UAV a companion SRV + // (RDNA images have no SRV / UAV distinction: the shader may read the slot) + dev.CreateShaderResourceView(&r, Some(&sv), at(&heap, 2 * i, inc)); if t.uav { dev.CreateUnorderedAccessView(&r, None::<&ID3D12Resource>, Some(&uv), at(&heap, 2 * i + 1, inc)); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 527dc4e64..44c0072ac 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -2916,6 +2916,62 @@ fn gpu_images_sample_load_store_atomic() { assert_eq!(u32::from_le_bytes(r.textures[2][..4].try_into().unwrap()), 64, "image_atomic_inc (64 lanes, limit 100)"); } +/// An image_load of a T# the program also stores through reads through the UAV when the +/// invocation stored through that T# before (`xcl_iw16`); a program without image stores +/// keeps the SRV-only load. +#[test] +fn image_load_of_a_stored_image_reads_through_the_uav() { + let store = ("IMAGE_STORE", "ENC_MIMG", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)][..], None); + let load = ("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)][..], None); + let t = translate(&prog(&[store, load]), &Options::default()).unwrap(); + assert!(t.hlsl.contains("static uint xcl_iw16 = 0u;") && t.hlsl.contains("xcl_iw16 = s16 + 1u;"), "{}", t.hlsl); + assert!(t.hlsl.contains("_rw = xcl_iw16 == s16 + 1u;") && t.hlsl.matches("RWTexture2D").count() == 2, "{}", t.hlsl); + let t = translate(&prog(&[load]), &Options::default()).unwrap(); + assert!(!t.hlsl.contains("xcl_iw") && !t.hlsl.contains("RWTexture2D"), "{}", t.hlsl); +} + +/// An image the program stores to and then loads in the same dispatch (in-place accumulation, +/// in-place blur, TAA history): RDNA2 reads its own write – the same lane right after the +/// store, a neighbour after the barrier. Each lane stores 1000 + lane to its texel of an 8x8 +/// R32_UINT image, loads that texel back, and after `s_barrier` loads the texel of lane ^ 1. +#[test] +fn gpu_image_load_reads_a_store_of_the_same_dispatch() { + if !gpu_ready() { + return; + } + use runner::{TestTexture, TexDim}; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT; + let mimg = |name: &'static str, f: &[(&str, u64)]| -> Vec { encode(name, "ENC_MIMG", f, None).unwrap() }; + let mut code = Vec::new(); + // T# in s[16:23] (SRSRC = 4): own texel (v0, v1), neighbour's texel (v3, v4) + code.extend(mimg("IMAGE_STORE", &[("VDATA", 2), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(encode("S_BARRIER", "ENC_SOPP", &[], None).unwrap()); + code.extend(mimg("IMAGE_LOAD", &[("VDATA", 11), ("VADDR", 3), ("SRSRC", 4), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&tsharp(0, 20, 9)); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let n = l ^ 1; + r[0] = (l % 8) as u32; + r[1] = (l / 8) as u32; + r[2] = 1000 + l as u32; + r[3] = (n % 8) as u32; + r[4] = (n / 8) as u32; + } + let tex = [TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 8, height: 8, depth: 1, texel_bytes: 4, data: vec![0xEE; 8 * 8 * 4], uav: true }]; + let r = runner::run_code_with(&code, &st, &[], &tex, &[]).unwrap(); + let t: Vec = r.textures[0].chunks(4).map(|c| u32::from_le_bytes(c.try_into().unwrap())).collect(); + for l in 0..64 { + assert_eq!(t[l], 1000 + l as u32, "image_store texel {l}"); + } + let bad: Vec = (0..64) + .filter(|&l| r.vgpr[l][10] != 1000 + l as u32 || r.vgpr[l][11] != 1000 + (l ^ 1) as u32) + .map(|l| format!("lane {l}: own {:#x}, neighbour {:#x}", r.vgpr[l][10], r.vgpr[l][11])) + .collect(); + assert!(bad.is_empty(), "image_load after image_store of the same dispatch (want 1000 + lane, 1000 + (lane ^ 1)):\n{}", bad.join("\n")); +} + /// Static samplers: the program builds two S# from constants (point / linear, clamp) – as /// the console compiler places a root signature's static samplers – and samples the same /// texel boundary with each; they become static samplers of the root signature.