diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index b6e043b7ac..13cfba0788 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -10,6 +10,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; +use victory_shader::emit::{AddressView, UserData}; use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; @@ -149,6 +150,23 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { Some(gpu) } +/// Addresses below this are taken as unset (null, or no buffer): a root SRV +/// at an address in root constants is not bound there and its draw is +/// dropped. +const MIN_ADDRESS: u64 = 0x1_0000; + +/// The address a root SRV at an address in root constants starts at: the +/// two constants' current values, low half first. `None` when the title has +/// not set either or the address is below [`MIN_ADDRESS`]. +fn pair_address(roots: &[Root], view: &AddressView) -> Option { + let half = |u: &UserData| match roots.get(usize::from(u.slot))? { + Root::Constants(c) => c.get(u.dword as usize).copied(), + _ => None, + }; + let address = u64::from(half(&view.lo)?) | u64::from(half(&view.hi)?) << 32; + (address >= MIN_ADDRESS).then_some(address) +} + macro_rules! once { ($($arg:tt)*) => {{ static ONCE: std::sync::Once = std::sync::Once::new(); @@ -344,7 +362,9 @@ impl State { once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); return false; } - self.bind(list, p, false); + if !self.bind(list, p, false) { + return false; + } let l = &list.list; // Vertex buffers the input layout reads. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; @@ -402,8 +422,10 @@ impl State { /// it changed, constant data copied, textures made readable. /// What draws and dispatches share: heaps, our root signature, the /// pipeline, and per stage the user data, root views and the - /// descriptors its tables hold. - fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { + /// descriptors its tables hold. False if a root SRV at an address in + /// root constants has no address to bind: the draw cannot run. + fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + let mut bound = true; let l = &list.list; // Heaps first: a root signature with directly indexed heaps must be // set after them. @@ -488,7 +510,29 @@ impl State { } } } + for &(view, param) in &stage.address_srvs { + let gpu = pair_address(self.roots_ref(compute), &view) + .and_then(|address| root_view(list, address, true)); + let Some(gpu) = gpu else { + once!( + slot = view.lo.slot, + dword = view.lo.dword, + "a shader reads through an address in root constants that is unset; draw dropped" + ); + bound = false; + continue; + }; + // SAFETY: an open list; the address is in live memory. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + } + } } + bound } /// Runs a dispatch on the host. @@ -513,7 +557,12 @@ impl State { once!("a dispatch with a graphics pipeline"); return; } - self.bind(list, p, true); + if !self.bind(list, p, true) { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); + return; + } #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); // SAFETY: an open list with everything set. @@ -553,6 +602,16 @@ impl State { let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); } } + for (view, _) in &stage.address_srvs { + let address = pair_address(self.roots_ref(compute), view); + let host = + address.and_then(|a| crate::shadow::find(a, 1).map(|s| (s.gpu(a), s.left(a)))); + let _ = write!( + text, + " u{}:u{}={address:#x?} host {host:#x?}", + view.lo.index, view.hi.index + ); + } } let _ = write!(text, " tables {:?}", self.reads(compute)); text @@ -988,10 +1047,7 @@ impl State { DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) { - Some(p) if p.compute => { - self.bind(list, p, true); - true - } + Some(p) if p.compute => self.bind(list, p, true), _ => false, }, _ => false, @@ -1180,3 +1236,64 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) { // SAFETY: an open list. unsafe { list.list.OMSetStencilRef(reference) }; } + +#[cfg(test)] +mod tests { + use super::*; + + fn half(slot: u8, dword: u32) -> UserData { + UserData { + index: 0, + slot, + root: RootType::Constants, + dword, + } + } + + /// The low half at dword 1 of root parameter 0, the high half at dword 0 + /// of parameter 2. + fn view() -> AddressView { + AddressView { + lo: half(0, 1), + hi: half(2, 0), + } + } + + fn roots(lo: u32, hi: u32) -> Vec { + vec![ + Root::Constants(vec![7, lo]), + Root::None, + Root::Constants(vec![hi]), + ] + } + + #[test] + fn addresses_in_root_constants_are_composed_from_both_halves() { + assert_eq!( + pair_address(&roots(0x2345_0000, 1), &view()), + Some(0x1_2345_0000) + ); + assert_eq!(pair_address(&roots(0x1_0000, 0), &view()), Some(0x1_0000)); + } + + #[test] + fn an_address_with_a_missing_half_is_unset() { + let set = roots(0x2345_0000, 1); + assert_eq!(pair_address(&set[..2], &view()), None); + let mut no_high = set.clone(); + no_high[2] = Root::Constants(Vec::new()); + assert_eq!(pair_address(&no_high, &view()), None); + let mut not_constants = set.clone(); + not_constants[0] = Root::View(0x1_0000_0000); + assert_eq!(pair_address(¬_constants, &view()), None); + let mut short = set; + short[0] = Root::Constants(vec![7]); + assert_eq!(pair_address(&short, &view()), None); + } + + #[test] + fn null_and_low_addresses_are_unset() { + assert_eq!(pair_address(&roots(0, 0), &view()), None); + assert_eq!(pair_address(&roots(0xFFFF, 0), &view()), None); + } +} diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 00aa9aa10c..52e3706075 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -2,13 +2,16 @@ //! title's graphics state with the translated shaders, under a root //! signature of our own that the translated shaders' bindings define //! (`victory_shader::emit`): per stage one block of root constants for the -//! user data, root views for the title's root views, static samplers for -//! the immediate samplers, and directly indexed heaps. +//! user data, root views for the title's root views and for addresses the +//! title passes in root constants, static samplers for the immediate +//! samplers, and directly indexed heaps. use std::ffi::{CStr, CString}; use std::sync::Arc; -use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use victory_shader::emit::{ + AddressView, ROOT_ADDRESS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE, +}; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; @@ -251,6 +254,10 @@ pub(crate) struct Stage { /// Root parameters of its root views: (title root parameter, ours). pub(crate) root_cbvs: Vec<(u8, u32)>, pub(crate) root_srvs: Vec<(u8, u32)>, + /// Root parameters of its root SRVs at addresses in root constants: + /// (the two constants, ours), `t` in [`ROOT_ADDRESS_SPACE`] for the + /// one at position n. + pub(crate) address_srvs: Vec<(AddressView, u32)>, } impl Stage { @@ -339,6 +346,7 @@ impl HostPipeline { user_data: None, root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), }; let dwords = t.user_data_dwords(); if dwords > 0 { @@ -382,6 +390,20 @@ impl HostPipeline { }); } } + for (n, &view) in t.address_srvs.iter().enumerate() { + stage.address_srvs.push((view, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: n as u32, + RegisterSpace: ROOT_ADDRESS_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } for (n, s) in t.static_samplers.iter().enumerate() { samplers.push(D3D12_STATIC_SAMPLER_DESC { Filter: D3D12_FILTER(s.filter as i32), diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 0cba938f0a..1c5dc0d131 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -14,7 +14,7 @@ use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use victory_pipeline::{Cache, Converter}; -use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::emit::{AddressView, HostShader, StaticSampler, UserData}; use victory_shader::{HwStage, RootType}; static CACHE: OnceLock = OnceLock::new(); @@ -175,11 +175,14 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, stage); word(&mut out, s.dxil.len() as u32); out.extend(&s.dxil); - word(&mut out, s.user_data.len() as u32); - for u in &s.user_data { + let user = |out: &mut Vec, u: &UserData| { for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { - word(&mut out, v); + word(out, v); } + }; + word(&mut out, s.user_data.len() as u32); + for u in &s.user_data { + user(&mut out, u); } word(&mut out, s.samplers.len() as u32); for sampler in &s.samplers { @@ -210,6 +213,11 @@ fn encode(s: &HostShader) -> Vec { word(&mut out, slots.len() as u32); out.extend(slots); } + word(&mut out, s.address_srvs.len() as u32); + for view in &s.address_srvs { + user(&mut out, &view.lo); + user(&mut out, &view.hi); + } out } @@ -228,6 +236,14 @@ fn decode(bytes: &[u8]) -> Option { let n = self.word()? as usize; Some(self.take(n)?.to_vec()) } + fn user(&mut self) -> Option { + Some(UserData { + index: self.word()?, + slot: u8::try_from(self.word()?).ok()?, + root: root_type(self.word()?), + dword: self.word()?, + }) + } } let mut r = Reader(bytes); if r.take(4)? != MAGIC { @@ -238,12 +254,7 @@ fn decode(bytes: &[u8]) -> Option { let n = r.word()? as usize; let mut user_data = Vec::with_capacity(n.min(256)); for _ in 0..n { - user_data.push(UserData { - index: r.word()?, - slot: u8::try_from(r.word()?).ok()?, - root: root_type(r.word()?), - dword: r.word()?, - }); + user_data.push(r.user()?); } let n = r.word()? as usize; let mut samplers = Vec::with_capacity(n.min(256)); @@ -266,6 +277,14 @@ fn decode(bytes: &[u8]) -> Option { } let root_cbvs = r.list()?; let root_srvs = r.list()?; + let n = r.word()? as usize; + let mut address_srvs = Vec::with_capacity(n.min(256)); + for _ in 0..n { + address_srvs.push(AddressView { + lo: r.user()?, + hi: r.user()?, + }); + } r.0.is_empty().then_some(HostShader { stage, dxil, @@ -274,6 +293,7 @@ fn decode(bytes: &[u8]) -> Option { static_samplers, root_cbvs, root_srvs, + address_srvs, }) } @@ -300,6 +320,20 @@ mod tests { ])], root_cbvs: vec![2], root_srvs: vec![0, 3], + address_srvs: vec![AddressView { + lo: UserData { + index: 3, + slot: 0, + root: RootType::Constants, + dword: 3, + }, + hi: UserData { + index: 4, + slot: 4, + root: RootType::Constants, + dword: 0, + }, + }], } } diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index dabd4a4dc5..3ba56b7c8e 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -113,7 +113,8 @@ impl Host { } /// The root signature for these stages: user data of stage k is root - /// parameter k, root views follow. + /// parameter k, root views follow, then the root SRVs at addresses in + /// root constants. pub fn root_signature_for( &self, stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], @@ -158,6 +159,23 @@ impl Host { ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); } + // Root SRVs at addresses in root constants follow, per stage in + // order (each stage numbers its own from 0). + for &(s, vis) in stages { + for n in 0..s.address_srvs.len() as u32 { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: n, + RegisterSpace: super::ROOT_ADDRESS_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: vis, + }); + } + } let mut samplers = Vec::new(); for &(s, vis) in stages { for (n, d) in s.static_samplers.iter().enumerate() { @@ -528,6 +546,7 @@ fn stub(pixel: bool, outputs: Vec) -> HostShader { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), } } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index ca5e8988a2..14745a1200 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -8,10 +8,10 @@ use std::collections::{BTreeMap, HashMap, HashSet}; -use super::UserData; use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; use super::container::SigElement; use super::shader::{Shader, flags}; +use super::{AddressView, UserData}; use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; @@ -35,6 +35,7 @@ pub(crate) struct Lowered { pub cmp_samplers: u64, pub root_cbvs: Vec, pub root_srvs: Vec, + pub address_srvs: Vec, pub user_data: Vec, pub samplers: Vec<[u32; 4]>, } @@ -150,6 +151,9 @@ struct Lower<'a> { user_data: Option, user_reads: BTreeMap, samplers: Vec<[u32; 4]>, + /// Root SRVs at addresses in root constants, in the order of the + /// shader's `address_srvs`. + address_views: Vec, descriptors: HashMap<(Site, bool), &'a Source>, scalar: HashMap, exports: HashMap, @@ -450,6 +454,7 @@ impl<'a> Lower<'a> { user_data: None, user_reads: BTreeMap::new(), samplers: Vec::new(), + address_views: Vec::new(), descriptors: x .res .descriptors @@ -887,6 +892,7 @@ impl<'a> Lower<'a> { cmp_samplers, root_cbvs, root_srvs, + address_srvs: self.address_views, dxil: self.s.finish(), user_data, samplers: self.samplers, @@ -2723,6 +2729,14 @@ impl<'a> Lower<'a> { if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { return self.code_smem(inst, a); } + if let Some(a) = self + .scalar + .get(&site) + .copied() + .filter(|a| self.in_constants(a)) + { + return self.pair_smem(inst, a); + } let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { return self.descriptor_data(inst, site); }; @@ -2764,7 +2778,8 @@ impl<'a> Lower<'a> { } return Ok(()); } - if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + let on_pair = matches!(src, Source::Built { address, .. } if self.in_constants(address)); + if on_pair || matches!(kind, Some(u) if u.kind == ResourceType::Srv) { let h = self.handle(site, src, false, (11, 0))?; for k in 0..count { let off = self.s.m.i32(4 * k); @@ -3009,6 +3024,52 @@ impl<'a> Lower<'a> { Ok(()) } + /// `s_load_dword*` through an address in root constants: raw loads from + /// the root SRV at that address, as `s_buffer_load_dword*` on a + /// descriptor built around one. + fn pair_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar load through an address in root constants"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar load through an address in root constants"), + }; + let h = self.address_srv(&a)?; + let c = self.cur; + let mut addr = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + addr = self.s.m.bin(c, Bin::Add, addr, d); + } + for k in 0..count { + let off = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, at, u, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + let x = self.as_int(x); + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + /// The dword at a computed byte address of a constant buffer. fn cbuffer_dword(&mut self, h: V, a: V) -> V { let c = self.cur; @@ -3166,6 +3227,44 @@ impl<'a> Lower<'a> { } } + /// `a` starts from a root-constant pair. + fn in_constants(&self, a: &Address) -> bool { + self.x + .native + .layout + .get(a.param) + .is_some_and(|rp| rp.root == RootType::Constants) + } + + /// The handle of the root SRV at the address the root-constant pair + /// that `a` starts from holds. + fn address_srv(&mut self, a: &Address) -> Result { + let pair = self + .x + .res + .pairs + .iter() + .find(|p| p.lo == (a.param, a.dword)) + .ok_or("an address in root constants without its high half")?; + let half = |(param, dword): (usize, u32)| { + let rp = self.x.native.layout[param]; + UserData { + index: u32::from(rp.user_data) + dword, + slot: rp.slot, + root: rp.root, + dword, + } + }; + let view = AddressView { + lo: half(pair.lo), + hi: half(pair.hi), + }; + if !self.address_views.contains(&view) { + self.address_views.push(view); + } + Ok(self.s.address_srv_handle(view.lo.index)) + } + /// The used-resource entry a descriptor loaded from a table falls in. fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { if let Source::Phi { args, .. } = src { @@ -3247,6 +3346,12 @@ impl<'a> Lower<'a> { .layout .get(address.param) .ok_or("a descriptor built around a table in the code")?; + if rp.root == RootType::Constants { + return match props.0 { + 11 => self.address_srv(address), + _ => Err("a write or typed view through an address in root constants"), + }; + } let kind = self .x .native @@ -6560,7 +6665,9 @@ impl<'a> Lower<'a> { #[cfg(test)] mod tests { use super::{Numeric, Parts, buffer_format, lower}; - use crate::native::{ComputeIo, HwStage, NativeProgram, StageIo}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; use crate::{io, ir, resource, structure}; const S_ENDPGM: u32 = 0xBF81_0000; @@ -6630,6 +6737,135 @@ mod tests { } } + /// Lowers a compute program with four root constants in `s0..s3` and a + /// table in `s4` whose first descriptor is a raw UAV in `s[8:11]`, `body` + /// leaving in `v0` what is stored there: the root SRVs at addresses in + /// root constants, and the other root SRVs. + fn lowers_with_constants( + body: &[u32], + ) -> Result<(Vec, Vec), crate::ShaderError> { + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + ]; + words.extend(body); + words.extend([ + 0xE070_0000, + 0x8002_0000, // buffer_store_dword v0, off, s[8:11], 0 + S_ENDPGM, + ]); + let param = |root, user_data, sgprs, slot| RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot, + }; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + layout: vec![ + param(RootType::Constants, 0, 4, 0), + param(RootType::Table, 4, 1, 1), + ], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 4, + slot: 1, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, 8).unwrap(); + let res = resource::track(&p, &native.layout, native.stage).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|l| (l.address_srvs, l.root_srvs)) + } + + /// `s[12:15]`: a raw buffer descriptor built around the pair `s[2:3]`. + const BUILT_ON_THE_PAIR: [u32; 6] = [ + 0xBE8C_0302, // s_mov_b32 s12, s2 + 0xBE8D_0303, // s_mov_b32 s13, s3 + 0xBE8E_03C1, // s_mov_b32 s14, -1 + 0xBE8F_03FF, + 0x1101_4FAC, // s_mov_b32 s15, 0x11014fac + 0xBF80_0000, // s_nop 0 + ]; + + #[test] + fn reads_through_a_root_constant_pair_are_a_root_srv() { + let half = |dword| super::UserData { + index: dword, + slot: 0, + root: RootType::Constants, + dword, + }; + let view = super::AddressView { + lo: half(2), + hi: half(3), + }; + let global = [ + 0xDC30_8000, + 0x0002_0001, // global_load_dword v0, v1, s[2:3] + ]; + let mut scalar = BUILT_ON_THE_PAIR.to_vec(); + scalar.extend([ + 0xF420_0186, + 0xFA00_0000, // s_buffer_load_dword s6, s[12:15], null + 0x7E00_0206, // v_mov_b32 v0, s6 + ]); + let scalar_load = [ + 0xF400_0181, + 0xFA00_0000, // s_load_dword s6, s[2:3], null + 0x7E00_0206, // v_mov_b32 v0, s6 + ]; + for body in [&global[..], &scalar, &scalar_load] { + let (views, root_srvs) = lowers_with_constants(body).unwrap(); + assert_eq!(views, [view]); + assert!(root_srvs.is_empty()); + } + } + + #[test] + fn other_uses_of_a_root_constant_pair_stop_with_a_reason() { + let reason = |body: &[u32]| match lowers_with_constants(body) { + Err(crate::ShaderError::Unsupported { what, .. }) => what, + other => panic!("{:?}", other.map(|_| ())), + }; + let mut typed = BUILT_ON_THE_PAIR.to_vec(); + typed.extend([ + 0xE000_2000, + 0x8003_0001, // buffer_load_format_x v0, v1, s[12:15], 0 idxen + ]); + assert_eq!( + reason(&typed), + "a write or typed view through an address in root constants" + ); + } + #[test] fn buffer_formats_by_number() { // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0df12339d8..8a404145b8 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -29,6 +29,15 @@ //! `b` / `t` in [`ROOT_CBV_SPACE`], `i` the title's root parameter //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the //! address the title sets is the buffer's. +//! * **Addresses in root constants** (added 2026-11-24): a 64-bit address +//! the title passes as two root-constant dwords (low half first, in +//! consecutive user SGPRs) and the shader only reads through +//! (`global_load_*`, `s_buffer_load_*` on a descriptor built around it) is +//! a root SRV (raw buffer) `t` in [`ROOT_ADDRESS_SPACE`], `n` the +//! position in [`HostShader::address_srvs`]. The host composes the +//! address from the two constants' current values at every draw and binds +//! the buffer there. Writes, typed views and scalar loads through such an +//! address stop the translation. //! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and //! vertex programs fetch vertices themselves with typed-format loads //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, @@ -95,7 +104,7 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use sampler::StaticSampler; -pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +pub use shader::{ROOT_ADDRESS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; /// The loop limit without an override: 2^20. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; @@ -154,6 +163,17 @@ pub struct HostShader { /// Root SRVs (raw buffers) the shader reads: `t` in /// [`ROOT_CBV_SPACE`]. pub root_srvs: Vec, + /// Root SRVs (raw buffers) at addresses in root constants: `t` in + /// [`ROOT_ADDRESS_SPACE`] for the view at position n. + pub address_srvs: Vec, +} + +/// A root SRV at the 64-bit address two root-constant dwords hold (both +/// with `root` [`RootType::Constants`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AddressView { + pub lo: UserData, + pub hi: UserData, } impl HostShader { @@ -202,7 +222,15 @@ pub fn translate(container: &[u8]) -> Result { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; - let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + // A compute program whose root arguments all sit past the 16 user SGPRs + // finds them through the spill table `s[0:1]` points to. + let spilled = native.stage == HwStage::Cs + && !native.layout.is_empty() + && native + .layout + .iter() + .all(|r| native.stage.user_sgpr(r.user_data) >= 16); + let p = ir::build_with(&native.patched_code(), native.wave64, native.vgprs, spilled)?; let res = resource::track(&p, &native.layout, native.stage)?; let io = io::raise(&p, &native)?; let st = structure::structure(&p)?; @@ -296,6 +324,7 @@ pub fn emit( samplers: l.samplers, root_cbvs: l.root_cbvs, root_srvs: l.root_srvs, + address_srvs: l.address_srvs, }) } @@ -490,6 +519,7 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), }; let file = |var: &str, stage| { std::env::var(var).ok().map(|p| super::HostShader { @@ -500,6 +530,7 @@ mod tests { static_samplers: Vec::new(), root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), }) }; let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 8389c17bea..0cf6179802 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -12,6 +12,9 @@ pub const SAMPLER_SPACE: u32 = 0; /// Where root CBVs and SRVs are bound: `b` and /// `t` in this space. pub const ROOT_CBV_SPACE: u32 = 1; +/// Where root SRVs at addresses passed in two root constants are bound: +/// `t` in this space, `n` the position in the shader's list of them. +pub const ROOT_ADDRESS_SPACE: u32 = 2; /// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. pub(crate) mod flags { @@ -64,6 +67,9 @@ pub(crate) struct Shader { pub root_cbvs: Vec<(u8, V)>, /// Root SRVs (raw buffers) read, likewise. pub root_srvs: Vec<(u8, V)>, + /// Root SRVs (raw buffers) at addresses in root constants, by the low + /// half's user-data index, with their handles. + pub address_srvs: Vec<(u32, V)>, pub flags: u64, /// A compute shader with this thread-group size. pub threads: Option<[u32; 3]>, @@ -117,6 +123,7 @@ impl Shader { cmp_samplers: 0, root_cbvs: Vec::new(), root_srvs: Vec::new(), + address_srvs: Vec::new(), flags: 0, threads: None, wave_size: None, @@ -232,6 +239,32 @@ impl Shader { h } + /// The handle of the root SRV (a raw buffer) at the address whose low + /// half is user-data dword `key`: `t` in [`ROOT_ADDRESS_SPACE`], `n` + /// its position in `address_srvs`. + pub fn address_srv_handle(&mut self, key: u32) -> V { + if let Some(&(_, h)) = self.address_srvs.iter().find(|r| r.0 == key) { + return h; + } + let r = self.m.i32(self.address_srvs.len() as u32); + let bind = [r, r, self.m.i32(ROOT_ADDRESS_SPACE), self.m.i8(0)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; + self.address_srvs.push((key, h)); + h + } + /// The handle of immediate sampler `n` (a comparison sampler when its /// bit in `cmp_samplers` is set). pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { @@ -305,6 +338,7 @@ impl Shader { || self.samplers > 0 || !self.root_cbvs.is_empty() || !self.root_srvs.is_empty() + || !self.address_srvs.is_empty() { let empty = self.m.md_str(""); let mut cbvs = None; @@ -359,20 +393,28 @@ impl Shader { cbvs = Some(self.m.md_node(cbv_list)); } let mut srvs = None; - if !self.root_srvs.is_empty() { + if !self.root_srvs.is_empty() || !self.address_srvs.is_empty() { let ty = self .m .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); let p = self.m.ptr(ty); let u = self.m.undef(p); let mut list = Vec::new(); - for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + // Root SRVs by root parameter, then those at addresses in + // root constants by position. + let views = self + .root_srvs + .iter() + .map(|&(slot, _)| (ROOT_CBV_SPACE, u32::from(slot))) + .chain((0..self.address_srvs.len() as u32).map(|n| (ROOT_ADDRESS_SPACE, n))) + .collect::>(); + for (n, (space, register)) in views.into_iter().enumerate() { let ops = vec![ Some(i32c(&mut self, n as u32)), Some(self.m.md_value(u)), Some(empty), - Some(i32c(&mut self, ROOT_CBV_SPACE)), - Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, space)), + Some(i32c(&mut self, register)), Some(i32c(&mut self, 1)), Some(i32c(&mut self, 11)), Some(i32c(&mut self, 0)), @@ -381,8 +423,8 @@ impl Shader { list.push(Some(self.m.md_node(ops))); bindings.push(Binding { kind: 4, - space: ROOT_CBV_SPACE, - register: u32::from(slot), + space, + register, dxil_kind: 11, }); } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index 1b95ca6e40..96865ae4bf 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -147,6 +147,7 @@ fn build_valu_cs(body: &[u32]) -> HostShader { static_samplers: Vec::new(), root_cbvs: lowered.root_cbvs, root_srvs: lowered.root_srvs, + address_srvs: lowered.address_srvs, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -673,3 +674,80 @@ fn bfe_signed_and_unsigned_match_rdna2() { ); }); } + +/// Runs `body` with an address in root constants (`s[2:3]`) and a root SRV +/// bound for it (`t0` in `ROOT_ADDRESS_SPACE`, the root parameter after the +/// user data) holding `0x100 + k` in dword `k`; checks that `v0` ends up +/// holding dword 3. +fn reads_dword_3_through_a_root_constant_pair(body: &[u32]) { + let shader = build_valu_cs(body); + assert!(shader.root_srvs.is_empty()); + let [view] = shader.address_srvs[..] else { + panic!("{:?}", shader.address_srvs) + }; + assert_eq!((view.lo.dword, view.hi.dword), (2, 3)); + let data: Vec = (0..8).map(|k| 0x100 + k).collect(); + let mut ran = 0; + for (label, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { + eprintln!("no SM 6.6 {label} device; skipped"); + continue; + }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + // The constants hold an address the host does not use: it binds the + // buffer itself. + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Constants { + ud[u.index as usize] = 0x1_0000 * (u.dword + 1); + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + ( + 1, + Root::View { + srv: true, + data: data.clone(), + }, + ), + ], + views: &[View::RawUav(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!(out[0][0], data[3], "{label}: byte 12 of the buffer"); + ran += 1; + } + assert!(ran > 0, "neither hardware nor WARP SM 6.6 device available"); +} + +/// A global load through an address the title passes as two root constants +/// reads the root SRV the host binds at that address. +#[test] +fn global_loads_through_a_root_constant_pair_read_its_root_srv() { + reads_dword_3_through_a_root_constant_pair(&[ + vop1(0x001, 5, 128 + 8), // v_mov_b32 v5, 8 + 0xDC30_8004, + 0x0002_0005, // global_load_dword v0, v5, s[2:3] offset:4 + ]); +} + +/// A scalar load through the same address reads it too. +#[test] +fn scalar_loads_through_a_root_constant_pair_read_its_root_srv() { + reads_dword_3_through_a_root_constant_pair(&[ + 0xF400_0181, + 0xFA00_000C, // s_load_dword s6, s[2:3], 0xc + vop1(0x001, 0, sgpr(6)), // v_mov_b32 v0, s6 + ]); +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index cc73a49bb3..637077dca2 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -119,11 +119,225 @@ impl Inst { } } +/// The first user SGPR that the spill table of root arguments stands for. +const SPILL_FIRST: u8 = 16; + +/// Rewrites loads from the spill table (`s[0:1]`, the high dword masked to a +/// 40-bit address, usually through copies in `s2`/`s3`) into `s_mov_b32` from +/// the user SGPRs the table's dwords stand for. Only loads with a constant +/// offset, in code no branch joins after the pointer is set up, are rewritten. +/// +/// The table holds the arguments as they were on entry, but the program may +/// have written the SGPRs those dwords stand for by the time it loads them +/// (a load into `s[8:23]` overwrites what stands for table dwords 0..7). So +/// the program first copies the user SGPRs it reads into a block of SGPRs it +/// never uses, and the loads read that block. Without such a block, or when a +/// branch can return to the entry, nothing is rewritten. +fn spill_loads( + list: Vec, + wave64: bool, + vgprs: u16, + code_len: usize, +) -> Result, ShaderError> { + use gfx10::Fields::{Smem, Sop, Valu}; + let mut targets = std::collections::BTreeSet::new(); + for inst in list.iter() { + let flow = gfx10::control(inst, code_len, |at| { + list[..list.partition_point(|i| i.offset < at)].last() + })?; + if let Flow::Jump(t) | Flow::Branch(t) = flow { + targets.insert(t); + } + } + let Some(entry) = list.first().map(|i| i.offset) else { + return Ok(list); + }; + if targets.contains(&entry) { + return Ok(list); + } + // Every SGPR the program reads or writes, to find a block it never uses. + let mut used = [false; 128]; + for inst in list.iter() { + let Some(name) = inst.name() else { + return Ok(list); + }; + let Ok(effects) = effects( + inst, + &inst.fields(wave64), + name, + 1 + u8::from(wave64), + vgprs, + ) else { + return Ok(list); + }; + for reg in effects + .into_iter() + .flat_map(|(r, w)| r.into_iter().chain(w)) + { + if let Reg::S(c) = reg { + used[usize::from(c).min(127)] = true; + } + } + } + let original = list.clone(); + // Where each rewritten copy is in `out`, and the user SGPR it stands for. + let mut copies: Vec<(usize, u8)> = Vec::new(); + // 1: a copy of s0, 2: a copy of s1 (masked to the address's high bits). + let mut tag = [0u8; 128]; + tag[0] = 1; + tag[1] = 2; + let mut out = Vec::with_capacity(list.len()); + let scalar = |o: &Operand| match *o { + Operand::Scalar { code, dwords } if code < 106 => Some((code, dwords.max(1))), + _ => None, + }; + for inst in list { + if targets.contains(&inst.offset) { + tag = [0; 128]; + } + let f = inst.fields(wave64); + let name = inst.name().unwrap_or(""); + // The load of the table. + if let Smem { + data: Some(ref d), + ref base, + offset, + ref soffset, + .. + } = f + && name.starts_with("s_load_dword") + && let Some((a, 2)) = scalar(base) + && tag[a as usize] == 1 + && tag[a as usize + 1] == 2 + && offset >= 0 + && offset % 4 == 0 + && matches!(*soffset, Operand::Scalar { code: 125, .. }) + && let Some((dst, n)) = scalar(d) + { + let first = u32::from(SPILL_FIRST) + (offset as u32) / 4; + if first + u32::from(n) <= 105 { + for k in 0..n { + let src = (first + u32::from(k)) as u8; + copies.push((out.len(), src)); + out.push(s_mov(dst + k, src, inst.offset)?); + } + for k in 0..n { + tag[(dst + k) as usize] = 0; + } + continue; + } + } + // What this instruction does to the tracked registers. + let mut written: Vec<(u8, u8)> = Vec::new(); + match &f { + Sop { + dst: Some(d), src, .. + } => { + if let Some((dc, dn)) = scalar(d) { + let new = match (name, src.as_slice()) { + ("s_mov_b32", [x]) => match scalar(x) { + Some((c, _)) if tag[c as usize] != 0 => tag[c as usize], + _ => 0, + }, + ("s_and_b32", [x, y]) => { + // `s1 & mask` with a small mask, either way round. + let masked = |reg: &Operand, mask: &Operand| match (scalar(reg), mask) { + (Some((c, _)), Operand::Literal(m)) => { + tag[c as usize] == 2 && *m <= 0xFFFF + } + (Some((c, _)), Operand::Const(k)) => { + tag[c as usize] == 2 && (129..=192).contains(k) + } + _ => false, + }; + if masked(x, y) || masked(y, x) { 2 } else { 0 } + } + _ => 0, + }; + if dn == 1 { + tag[dc as usize] = new; + } else { + written.push((dc, dn)); + } + } + } + Smem { data: Some(d), .. } => written.extend(scalar(d)), + Valu(v) => { + written.extend(v.dst.as_ref().and_then(scalar)); + written.extend(v.carry.as_ref().and_then(scalar)); + } + _ => {} + } + for (c, n) in written { + for k in c..c.saturating_add(n).min(128) { + tag[k as usize] = 0; + } + } + out.push(inst); + } + let Some(last) = copies.iter().map(|c| c.1).max() else { + return Ok(out); + }; + // A block of SGPRs past the user SGPRs the table stands for that the + // program never touches, below VCC. + let size = usize::from(last - SPILL_FIRST) + 1; + let Some(block) = (usize::from(last) + 1..=usize::from(VCC) - size) + .find(|&b| used[b..b + size].iter().all(|u| !u)) + else { + return Ok(original); + }; + let moved = |src: u8| (block + usize::from(src - SPILL_FIRST)) as u8; + let mut read: Vec = copies.iter().map(|c| c.1).collect(); + read.sort_unstable(); + read.dedup(); + for &(at, src) in &copies { + let Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } = out[at].fields(wave64) + else { + unreachable!("a copy is an s_mov_b32"); + }; + out[at] = s_mov(code, moved(src), out[at].offset)?; + } + let mut entries = Vec::with_capacity(read.len() + out.len()); + for &src in &read { + entries.push(s_mov(moved(src), src, entry)?); + } + entries.extend(out); + Ok(entries) +} + +/// `s_mov_b32 s, s`, placed at `offset`. +fn s_mov(dst: u8, src: u8, offset: usize) -> Result { + let word = 0xBE80_0000 | u32::from(dst) << 16 | 3 << 8 | u32::from(src); + let mut bytes = word.to_le_bytes().to_vec(); + bytes.extend(0xBF81_0000u32.to_le_bytes()); // s_endpgm + let mut one = gfx10::decode(&bytes)?.remove(0); + one.offset = offset; + Ok(one) +} + /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result { - let list = gfx10::decode(code)?; + build_with(code, wave64, vgprs, false) +} + +/// [`build`]; with `spilled`, loads from the root-argument spill table that +/// `s[0:1]` points to read the user SGPRs the table stands for (table dword +/// `k` is user SGPR `16 + k`), as plain register copies. +pub fn build_with( + code: &[u8], + wave64: bool, + vgprs: u16, + spilled: bool, +) -> Result { + let mut list = gfx10::decode(code)?; + if spilled { + list = spill_loads(list, wave64, vgprs, code.len())?; + } let lanes = 1 + u8::from(wave64); let isa = |offset, reason| ShaderError::Isa { offset, reason }; @@ -1043,6 +1257,121 @@ mod tests { p.inputs.iter().find(|i| i.0 == reg).expect("input").1 } + /// A compute program whose root arguments are in the spill table `s[0:1]` + /// points to: the loads become copies of the user SGPRs the dwords stand for. + #[test] + fn spill_table_loads_read_user_sgprs() { + let code: Vec = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0x8703_FF01, // s_and_b32 s3, s1, lit + 0x0000_00FF, // 0xff + 0xF408_0201, // s_load_dwordx4 s[8:11], s[2:3], 0x10 + 0xFA00_0010, + 0xBE86_0308, // s_mov_b32 s6, s8 + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let plain = build_with(&code, false, 256, false).unwrap(); + assert!( + plain + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "s_load_dwordx4") + ); + let p = build_with(&code, false, 256, true).unwrap(); + let insts: Vec<_> = p.blocks.iter().flat_map(|b| &b.insts).collect(); + assert!(!insts.iter().any(|i| i.name().starts_with("s_load"))); + // Table dwords 4..8 are user SGPRs 20..24. + for k in 0..4 { + assert!( + p.inputs.iter().any(|i| i.0 == Reg::S(20 + k)), + "s{} read", + 20 + k + ); + } + // s2, the four entry copies of s20..s23, the four loaded dwords, s6. + assert_eq!( + insts.iter().filter(|i| i.name() == "s_mov_b32").count(), + 1 + 4 + 4 + 1 + ); + } + + /// A later table load still reads the arguments as they were on entry, + /// although an earlier load overwrote the SGPRs its dwords stand for. + #[test] + fn spill_table_loads_read_entry_values() { + let code: Vec = [ + 0xBE82_0300u32, // s_mov_b32 s2, s0 + 0x8703_FF01, // s_and_b32 s3, s1, lit + 0x0000_00FF, // 0xff + 0xF40C_0301, // s_load_dwordx8 s[12:19], s[2:3], 0x10 (writes s16..s19) + 0xFA00_0010, + 0xF404_0101, // s_load_dwordx2 s[4:5], s[2:3], 0 (table dwords 0..1) + 0xFA00_0000, + 0xBE86_0304, // s_mov_b32 s6, s4 + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build_with(&code, false, 256, true).unwrap(); + let insts: Vec<_> = p.blocks.iter().flat_map(|b| &b.insts).collect(); + assert!(!insts.iter().any(|i| i.name().starts_with("s_load"))); + // Table dwords 0..1 and 4..11 are user SGPRs 16..17 and 20..27, all + // read on entry. + for reg in (16..18).chain(20..28) { + assert!( + p.inputs.iter().any(|i| i.0 == Reg::S(reg)), + "s{reg} read on entry" + ); + } + // s6 holds what s16 held on entry, not what the first load put there. + let entry = input(&p, Reg::S(16)); + let copied = |v: Value| { + insts + .iter() + .find(|i| i.name() == "s_mov_b32" && i.writes.iter().any(|w| w.1 == v)) + .and_then(|i| i.reads.first().map(|r| r.1)) + }; + let mut value = insts + .iter() + .rev() + .find_map(|i| i.write(Reg::S(6))) + .expect("s6 written"); + while value != entry { + value = copied(value).expect("a chain of copies back to the entry value"); + } + } + + /// Loads from a pointer that is not the spill table stay loads. + #[test] + fn spill_table_leaves_other_loads() { + let code: Vec = [ + 0xF408_0A00u32, // s_load_dwordx4 s[8:11], s[0:1], 0 (s0:1 not yet copied: tagged) + 0xFA00_0000, + 0xBE82_0380, // s_mov_b32 s2, 0 + 0xF408_0201, // s_load_dwordx4 s[8:11], s[2:3], 0 (s2 overwritten) + 0xFA00_0000, + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build_with(&code, false, 256, true).unwrap(); + let loads = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name().starts_with("s_load")) + .count(); + // The first load is from s[0:1] itself, so it is rewritten; the second + // reads a pointer the program overwrote, so it stays. + assert_eq!(loads, 1); + } + #[test] fn joins_get_phis_only_where_values_differ() { let code = [ diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 46cf891627..6782fa061f 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -11,6 +11,11 @@ //! descriptor's address itself. Each descriptor operand and each scalar //! memory address is traced through the SSA values back to those //! parameters, by data flow: copies, phis that agree, and additions. +//! +//! A title can also pass a 64-bit address as two root constants, low half +//! first, in consecutive user SGPRs (within one parameter or across two). +//! Such a pair is recognised from its high half, which the code uses only +//! as the high half of an address (or adds a carry to): [`Pair`]. use crate::ShaderError; use crate::gfx10::{Fields, NULL, Operand}; @@ -26,12 +31,23 @@ pub type Site = (usize, usize); pub struct Address { /// Index into the layout, or [`CODE`]. pub param: usize, + /// The dword of the base within `param`: 0 except for an address in + /// root constants ([`Pair`]), where it is the low half's. + pub dword: u32, /// Added modulo 2^32 (with carry into the high half of a root /// descriptor's address). pub offset: u32, pub dynamic: Option, } +/// A 64-bit address in two root-constant dwords: layout index and dword +/// of its low half and of its high half (the next user SGPR). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Pair { + pub lo: (usize, u32), + pub hi: (usize, u32), +} + /// [`Address::param`] of the program's own code: a constant table the /// compiler appends after the code and reads through `s_getpc_b64`; the /// offset is then the byte offset in the code. @@ -89,6 +105,8 @@ pub struct Resources { /// User SGPRs holding root parameters: value on entry, layout index, /// dword within the parameter. pub params: Vec<(Value, usize, u32)>, + /// The root-constant pairs the addresses above start from, once each. + pub pairs: Vec, } /// Traces every descriptor and scalar address of `p`, which runs as @@ -154,6 +172,18 @@ pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result Some(*address), + _ => None, + }) + }); + let addresses: Vec
= out.scalar.iter().map(|s| s.1).chain(built).collect(); + for pair in addresses.into_iter().filter_map(|a| t.pair(a)) { + if !out.pairs.contains(&pair) { + out.pairs.push(pair); + } + } Ok(out) } @@ -164,8 +194,8 @@ enum Term { Value(Value), } -/// A 32-bit sum: optional root parameter (as its first dword), constant, -/// optional computed term. +/// A 32-bit sum: optional root parameter (as its first dword, or the low +/// half of a [`Pair`]), constant, optional computed term. struct Sum { base: Option, offset: u32, @@ -337,7 +367,9 @@ impl<'a> Tracer<'a> { )) } - fn sum(&self, t: Term) -> Sum { + /// The sum `t` computes; `pair`, the low half of a root-constant pair, + /// counts as a base too. + fn sum(&self, t: Term, pair: Option) -> Sum { let v = match t { Term::Const(c) => { return Sum { @@ -355,6 +387,11 @@ impl<'a> Tracer<'a> { }; if let Some(reg) = self.inputs[v.0 as usize] { return match self.param_of(reg) { + _ if pair == Some(v) => Sum { + base: Some(v), + offset: 0, + dynamic: None, + }, Some((_, 0)) => Sum { base: Some(v), offset: 0, @@ -377,7 +414,7 @@ impl<'a> Tracer<'a> { else { return dynamic; }; - let (x, y) = (self.sum(a), self.sum(b)); + let (x, y) = (self.sum(a, pair), self.sum(b, pair)); if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { return dynamic; } @@ -465,7 +502,7 @@ impl<'a> Tracer<'a> { return Err("an address not in SGPRs"); }; let v = inst.read(Reg::V(reg)).ok_or("a global address")?; - let mut extra = self.sum(self.vorigin(v)); + let mut extra = self.sum(self.vorigin(v), None); if extra.base.is_some() { return Err("an offset from a root parameter"); } @@ -493,7 +530,10 @@ impl<'a> Tracer<'a> { /// The address `lo` and `hi` hold, plus `extra` (an instruction's /// immediate and offset register). fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { - let s = self.sum(lo); + if let Some(a) = self.pair_address(lo, hi, &extra) { + return a; + } + let s = self.sum(lo, None); if s.dynamic.is_some() && extra.dynamic.is_some() { return Err("an address with two computed terms"); } @@ -506,6 +546,7 @@ impl<'a> Tracer<'a> { } return Ok(Address { param: CODE, + dword: 0, offset: (pc.machine.offset as u32 + 4) .wrapping_add(s.offset) .wrapping_add(extra.offset), @@ -535,11 +576,91 @@ impl<'a> Tracer<'a> { } Ok(Address { param, + dword: 0, offset: s.offset.wrapping_add(extra.offset), dynamic: s.dynamic.or(extra.dynamic), }) } + /// The address a root-constant pair holds: `hi` is the pair's high half + /// (possibly plus a carry) and the sum of `lo` starts from its low half. + /// `None` when `lo` and `hi` are no pair; the other kinds of address + /// never have a root constant as their high half. + fn pair_address( + &self, + lo: Term, + hi: Term, + extra: &Sum, + ) -> Option> { + let (low, high) = self.pair_high(hi)?; + let s = self.sum(lo, Some(low)); + if s.base != Some(low) { + return None; + } + let (param, dword) = self.param_of(self.inputs[low.0 as usize]?)?; + if s.dynamic.is_some() && extra.dynamic.is_some() { + return Some(Err("an address with two computed terms")); + } + let dynamic = s.dynamic.or(extra.dynamic); + if !self.high_half(hi, Some(high)) && !(dynamic.is_some() && self.carried(hi, high)) { + return Some(Err("an address with an untracked high half")); + } + Some(Ok(Address { + param, + dword, + offset: s.offset.wrapping_add(extra.offset), + dynamic, + })) + } + + /// The root-constant input `hi` is, or adds a carry to (`s_addc_u32`, + /// `v_add_co_ci_u32`, as [`Tracer::carried`] walks), when the user SGPR + /// below it holds a root constant too: (low half, high half) on entry. + fn pair_high(&self, hi: Term) -> Option<(Value, Value)> { + let Term::Value(v) = hi else { return None }; + if let Some(Reg::S(code)) = self.inputs[v.0 as usize] { + let below = code.checked_sub(1)?; + if !self.is_constant(code) || !self.is_constant(below) { + return None; + } + let low = self.p.inputs.iter().find(|i| i.0 == Reg::S(below))?.1; + return Some((low, v)); + } + if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + return self.pair_high(a).or_else(|| self.pair_high(b)); + } + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if inst.name() != "v_add_co_ci_u32" { + return None; + } + f.src[..2.min(f.src.len())] + .iter() + .find_map(|o| self.pair_high(self.vterm(inst, o)?)) + } + + /// User SGPR `code` holds a root-constant dword. + fn is_constant(&self, code: u8) -> bool { + self.param_of(Reg::S(code)) + .is_some_and(|(i, _)| self.layout[i].root == RootType::Constants) + } + + /// The pair an address in root constants starts from. + fn pair(&self, a: Address) -> Option { + let rp = self.layout.get(a.param)?; + if rp.root != RootType::Constants { + return None; + } + let low = u32::from(self.stage.user_sgpr(rp.user_data)) + a.dword; + let high = u8::try_from(low + 1).ok()?; + Some(Pair { + lo: (a.param, a.dword), + hi: self.param_of(Reg::S(high))?, + }) + } + /// `hi` is `high` (0 for a table), possibly plus a carry. fn high_half(&self, hi: Term, high: Option) -> bool { let want = high.map_or(Term::Const(0), Term::Value); @@ -619,6 +740,7 @@ impl<'a> Tracer<'a> { let mut extra = self.sum( self.term(inst, soffset) .ok_or("an unknown offset operand")?, + None, ); if extra.base.is_some() { return Err("an offset from a root parameter"); @@ -931,6 +1053,7 @@ mod tests { fn at(param: usize, offset: u32) -> Address { Address { param, + dword: 0, offset, dynamic: None, } @@ -1113,4 +1236,113 @@ mod tests { } ); } + + /// `global_load_dword v1, v0, s[base:base+1]`. + fn global_load(base: u8) -> [u32; 2] { + [0xDC30_8000, 0x0100_0000 | u32::from(base) << 16] + } + + /// The pair and the address of the one global load in `words`. + fn pair_load(words: &[u32], layout: &[RootParam]) -> (Vec, Address) { + let r = track_words(words, layout, HwStage::Cs); + let [(_, a)] = r.scalar[..] else { + panic!("{:?}", r.scalar) + }; + (r.pairs, a) + } + + #[test] + fn root_constant_pairs_are_addresses() { + let [l0, l1] = global_load(0); + let (pairs, a) = pair_load(&[l0, l1, S_ENDPGM], &[param(Constants, 0, 2)]); + assert_eq!( + pairs, + [Pair { + lo: (0, 0), + hi: (0, 1) + }] + ); + assert_eq!((a.param, a.dword, a.offset), (0, 0, 0)); + assert!(a.dynamic.is_some(), "the VGPR offset is the computed term"); + } + + #[test] + fn a_root_constant_pair_at_a_later_dword() { + let [l0, l1] = global_load(2); + let (pairs, a) = pair_load(&[l0, l1, S_ENDPGM], &[param(Constants, 0, 4)]); + assert_eq!( + pairs, + [Pair { + lo: (0, 2), + hi: (0, 3) + }] + ); + assert_eq!((a.param, a.dword), (0, 2)); + } + + #[test] + fn a_root_constant_pair_across_two_parameters() { + let [l0, l1] = global_load(2); + let (pairs, a) = pair_load( + &[l0, l1, S_ENDPGM], + &[param(Constants, 0, 3), param(Constants, 3, 1)], + ); + assert_eq!( + pairs, + [Pair { + lo: (0, 2), + hi: (1, 0) + }] + ); + assert_eq!((a.param, a.dword), (0, 2)); + } + + #[test] + fn a_root_constant_pair_plus_an_offset_with_its_carry() { + let (pairs, a) = pair_load( + &[ + 0xD70F_6A02, + 0x0002_0000, // v_add_co_u32 v2, vcc_lo, s0, v0 + 0xD528_6A03, + 0x01A9_0001, // v_add_co_ci_u32 v3, vcc_lo, s1, 0, vcc_lo + 0xDC30_8000, + 0x017D_0002, // global_load_dword v1, v[2:3], off + S_ENDPGM, + ], + &[param(Constants, 0, 2)], + ); + assert_eq!( + pairs, + [Pair { + lo: (0, 0), + hi: (0, 1) + }] + ); + assert_eq!((a.param, a.dword, a.offset), (0, 0, 0)); + assert!(a.dynamic.is_some()); + } + + #[test] + fn a_root_constant_without_its_high_half_is_no_address() { + let [l0, l1] = global_load(0); + for hi in [ + 0xBE81_0303, // s_mov_b32 s1, s3: the high half of another pair + 0xBE81_0380, // s_mov_b32 s1, 0: a 32-bit address + ] { + let code: Vec = [hi, l0, l1, S_ENDPGM] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Constants, 0, 4)], HwStage::Cs).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 4, + what: "an address from a root parameter that is no address" + }, + "{hi:#x}" + ); + } + } }