From 40c2f29c5aa5dd4cdbf9696e52909338625bb87e Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:07:22 +0100 Subject: [PATCH 1/9] Run wave64 compute programs in a paired form on 32-lane hosts (port of fxceless#854) Port of 26600c6 from fxceless/victory-fork#854 by PiloteCode ("wave64 programs in a paired form on 32-lane hosts, mesh programs over 32 KiB linked with their pixel program, and more"). Each console wave runs as one host wave of 32 lanes, each thread two console lanes (n and n + 32), with every per-lane branch taken by the whole wave and EXEC as each lane's guard. It is tried after every other form for a wave64 compute program the host refuses (VICTORY_WAVE_PAIRS=0 turns it off). On the 31 wave64 compute containers from the RTX 5060 preload, 29 get a pipeline (22 before): 02384a60fda6f2d0, 1d434307d981352a, 22338086ea4c5364, 2da4beb386509b77, 3b02415f67c6b0d8, 6832a9da15c2e584 and 6b82bc7d22016cb5 now take the paired form; the other 22 are unchanged. Adapted to this branch: - Kept from this branch: scalar_built() and the v_readfirstlane own-lane read, lds_subtract() with Module::negated() (the PR's own LDS subtraction loop is left out), the wave-wide last resort from DexNom#40 (now inside emit_forms), the POPS translation from pops.rs, the structured view record count / picked address / puddle texture size paths and scalar UINT views (moved into descriptor_data.rs next to the PR's unused-descriptor path, which now only runs where this branch refused). - Left out: the PR's second POPS implementation (ir::without_pops_wait, Shader::ordered and its test), which would have run beside pops.rs. - The ray-tracing structure builder's programs (a spilled user-data table, as victory-gpu classifies them) are refused by the paired form: forcing them onto 32-lane hosts hung NVIDIA GPUs in Marvisak/VIctory#2711. 28918b7150a7aad5 and caa78b8ca62bc3d6 stay refused. - The new modules are classified in lib.rs; a test that expected the parked mask to be opaque when built alone checks only the shared build; the descriptor size test fills the record-count root word the runtime fills. Co-Authored-By: Pilote Production <75377040+PiloteCode@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- apps/victory/src/translate.rs | 48 +- crates/victory-gpu/src/pipeline/host.rs | 71 +- crates/victory-shader/src/emit/bitcode.rs | 2 + crates/victory-shader/src/emit/bitcode/opt.rs | 10 +- crates/victory-shader/src/emit/container.rs | 137 +- .../src/emit/descriptor_data.rs | 372 ++++ .../src/emit/descriptor_tests.rs | 244 +++ crates/victory-shader/src/emit/float64.rs | 320 +++ crates/victory-shader/src/emit/idiom.rs | 331 +++ crates/victory-shader/src/emit/link.rs | 204 ++ crates/victory-shader/src/emit/lower.rs | 1766 +++++++---------- crates/victory-shader/src/emit/mod.rs | 673 ++++++- crates/victory-shader/src/emit/rect.rs | 1 + crates/victory-shader/src/emit/shader.rs | 3 +- crates/victory-shader/src/emit/valu_tests.rs | 166 +- crates/victory-shader/src/emit/wave.rs | 320 +-- .../victory-shader/src/emit/wave64_tests.rs | 668 ++++++- crates/victory-shader/src/ir.rs | 270 ++- crates/victory-shader/src/lib.rs | 5 + 19 files changed, 4351 insertions(+), 1260 deletions(-) create mode 100644 crates/victory-shader/src/emit/descriptor_data.rs create mode 100644 crates/victory-shader/src/emit/descriptor_tests.rs create mode 100644 crates/victory-shader/src/emit/float64.rs create mode 100644 crates/victory-shader/src/emit/idiom.rs create mode 100644 crates/victory-shader/src/emit/link.rs diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index c22f82c2f2..6f14447b4d 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -140,14 +140,17 @@ impl Tally { } } -/// Emitted shaders by label, shared between threads. -type Kept = std::sync::Arc>>; +/// Emitted shaders by label, with their containers, shared between threads. +type Kept = std::sync::Arc)>>>; /// The optional checks after emission, one set per thread. struct Checks { /// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings), - /// kept to build those pipelines after the walk. + /// kept to build those pipelines after the walk: the names, and the + /// container being translated when its label holds one of them. keep: Option, + names: Vec, + current: Option>, validator: Option, host: Option<(Host, emit::HostShader)>, } @@ -216,6 +219,8 @@ pub fn run( }; let mut checks = Checks { keep: (!pairs.is_empty()).then(|| kept.clone()), + names: pairs.iter().flat_map(|(v, p)| [v.clone(), p.clone()]).collect(), + current: None, validator: validate .then(|| Validator::load(dll.as_deref()).ok()) .flatten(), @@ -284,10 +289,34 @@ pub fn run( if !pairs.is_empty() { let host = Host::new(false).map_err(anyhow::Error::msg)?; let kept = lock(&kept); - let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); + let find = |name: &str| kept.iter().find(|(l, _, _)| l.contains(name)); + let mut validator = Validator::load(dll.as_deref()).ok(); for (v, p) in &pairs { let made = match (find(v), find(p)) { - (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { + // A mesh program whose outputs pass the host's 32 KiB alone: linked with + // this pixel program, as the runtime makes its pipeline + // (`emit::link_mesh`), each of the two validated. + (Some((_, ms, msc)), Some((_, ps, psc))) if ms.stage == HwStage::Ms && !emit::mesh_fits(&ms.dxil).unwrap_or(true) => { + match emit::link_mesh(msc, ms, psc, ps) { + Ok(Some((lms, lps))) => { + let mut checked = Vec::new(); + for (what, s) in [("mesh", &lms), ("pixel", &lps)] { + if let Some(v) = validator.as_mut() { + let mut copy = s.dxil.clone(); + checked.push(match v.validate(&mut copy) { + Ok(()) => format!("{what} validated"), + Err(e) => format!("{what} invalid: {}", e.lines().find(|l| l.contains("error")).unwrap_or(&e)), + }); + } + } + let made = host.mesh_pipeline(&lms, &lps).map(|_| "pipeline created".to_owned()).unwrap_or_else(|e| e); + format!("linked, {}, {made}", checked.join(", ")) + } + Ok(None) => "not linked (over 32 KiB)".to_owned(), + Err(e) => format!("not linked: {e}"), + } + } + (Some((_, vs, _)), Some((_, ps, _))) => if vs.stage == HwStage::Ms { host.mesh_pipeline(vs, ps) } else { host.pipeline(vs, ps) @@ -463,6 +492,11 @@ fn translate( let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]); } } + // (`VICTORY_PAIRS`: a container whose label names a shader of a pair is kept) + checks.current = (!checks.names.is_empty()) + .then(example) + .filter(|line| checks.names.iter().any(|n| line.contains(n.as_str()))) + .map(|_| bytes.to_vec()); if !lock(seen).insert(code) { t.duplicates += 1; if t.list { @@ -632,8 +666,8 @@ fn check( checks: &mut Checks, label: impl Fn() -> String, ) { - if let Some(keep) = &checks.keep { - lock(keep).push((label(), shader.clone())); + if let (Some(keep), Some(bytes)) = (&checks.keep, &checks.current) { + lock(keep).push((label(), shader.clone(), bytes.clone())); } // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. if t.list diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 7f4c2b1db1..60e2fa258b 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -633,7 +633,19 @@ impl HostPipeline { false }; let state = g.describe(); - if mesh.is_some() { + if let Some(ms) = mesh { + // A mesh program whose outputs pass D3D12's 32 KiB is linked with this pixel + // program ([`linked`]): the pipeline gets the two made for each other, which bind + // as the shared translations do. + let pair = stages.get(1).and_then(|(ps, _)| linked(ms, ps)); + let bytecode = |dxil: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: dxil.as_ptr().cast(), + BytecodeLength: dxil.len(), + }; + let (ms_code, ps_code) = match &pair { + Some(pair) => (bytecode(&pair.0.dxil), bytecode(&pair.1.dxil)), + None => (code(0), code(1)), + }; // "triangles": the stream names its topology since it did not // load from the library without one (see `mesh_pipeline`); a // new name keeps such entries, stored before, from being @@ -641,10 +653,10 @@ impl HostPipeline { let name = super::library::name( "mesh triangles", &root_blob, - &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &[&code_bytes(&ms_code), &code_bytes(&ps_code)], &state, ); - let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, depth_bounds, &name) { + let pso = match mesh_pipeline(&host.device, &root, ms_code, ps_code, g, depth_bounds, &name) { Ok(pso) => pso, Err(e) => { tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); @@ -899,6 +911,59 @@ fn graphics_depth_bounds_pipeline( } } +/// The mesh program `ms` and the pixel program `ps` translated for one pipeline +/// ([`victory_shader::emit::link_mesh`]), when `ms`'s outputs pass D3D12's 32 KiB as it is +/// translated alone: 71 of the title's mesh programs (pedestrian, vehicle and prop transforms +/// with fire, spatter, decal and transmission variants) declare 65 to 71 output components +/// for 128 vertices, which the validator refuses; NVIDIA's driver built them anyway. Linked, +/// the mesh program writes only the outputs `ps` reads and `ps` declares only the inputs it +/// reads. Made once per pair (both programs translated again, not kept on disk: the pipeline +/// library keeps the pipeline); `None` when `ms` fits, or the pair does not link (then the +/// pipeline is made of the shared translations, as before). `VICTORY_MESH_LINK=0` turns it +/// off. +fn linked( + ms: &Arc, + ps: &Arc, +) -> Option> { + type Pair = Option>; + static PAIRS: std::sync::Mutex>> = + std::sync::Mutex::new(None); + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("VICTORY_MESH_LINK").is_none_or(|v| v != "0")) { + return None; + } + let (tm, tp) = (ms.translated()?, ps.translated()?); + // (most mesh programs fit: nothing more to do for them) + if victory_shader::emit::mesh_fits(&tm.host.dxil).unwrap_or(true) { + return None; + } + let key = (ms.hash.clone(), ps.hash.clone()); + if let Some(pair) = PAIRS.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Default::default).get(&key) { + return pair.clone(); + } + // (translated outside the lock: two workers on one pair translate it twice at worst) + let pair = match victory_shader::emit::link_mesh(&ms.container, &tm.host, &ps.container, &tp.host) { + Ok(Some(pair)) => { + tracing::info!(shaders = ?[ms, ps], "mesh outputs over 32 KiB: the pair is linked for its pipeline"); + Some(Arc::new(pair)) + } + Ok(None) => { + tracing::warn!(shaders = ?[ms, ps], "mesh outputs over 32 KiB, and the pair does not link"); + None + } + Err(e) => { + tracing::warn!(shaders = ?[ms, ps], error = %e, "mesh outputs over 32 KiB, and the pair does not translate linked"); + None + } + }; + PAIRS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(Default::default) + .insert(key, pair.clone()); + pair +} + /// A mesh pipeline from the title's graphics state: the pipeline-state /// stream form (no input layout). /// diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs index ba49c0fb54..5b98004d74 100644 --- a/crates/victory-shader/src/emit/bitcode.rs +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -30,6 +30,7 @@ enum TypeDef { Void, Int(u32), Float, + /// A 64-bit float. Double, /// Pointee and address space. Ptr(Ty, u32), @@ -108,6 +109,7 @@ pub(crate) enum Cast { FpToSi = 4, UiToFp = 5, SiToFp = 6, + FpExt = 8, Bitcast = 11, } diff --git a/crates/victory-shader/src/emit/bitcode/opt.rs b/crates/victory-shader/src/emit/bitcode/opt.rs index 2c551ca616..1dbbd56cd2 100644 --- a/crates/victory-shader/src/emit/bitcode/opt.rs +++ b/crates/victory-shader/src/emit/bitcode/opt.rs @@ -67,6 +67,7 @@ pub(crate) struct Usage { pub int64: bool, /// A typed load of several components from a UAV. pub typed_uav_loads: bool, + /// A handle annotated as a rasterizer-ordered view. pub rovs: bool, /// A handle from the view heap. pub heap_views: bool, @@ -74,6 +75,8 @@ pub(crate) struct Usage { pub heap_samplers: bool, /// A 64-bit atomic. pub atomic64: bool, + /// A 64-bit float, as a result or an operand. + pub doubles: bool, } /// What makes two instructions without an effect the same value. @@ -969,6 +972,7 @@ impl Module { let mut u = Usage::default(); let reached = self.reached(); let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64); + let double = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Double; // The first field of a handle's annotation: its kind, with the UAV // bit; the second: the component type and count. let annotation = |h: V| -> Option<(i64, i64)> { @@ -997,7 +1001,11 @@ impl Module { for &i in blk.phis.iter().chain(&blk.body) { let inst = &self.insts[i as usize]; u.int64 |= wide(inst.ty); - for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + u.doubles |= double(inst.ty); + for_each_operand(&inst.op, |v| { + u.int64 |= wide(self.type_of(v)); + u.doubles |= double(self.type_of(v)); + }); let Op::Call(f, args) = &inst.op else { continue; }; diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs index 0b68165570..e1e27a0c28 100644 --- a/crates/victory-shader/src/emit/container.rs +++ b/crates/victory-shader/src/emit/container.rs @@ -72,7 +72,11 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { // Validator 1.6 writes one name per element in element order, repeats // included, except that system values share theirs (it keys names by // the semantic's string, which is one static string per system value); - // the rows sorted by register (unallocated last), then name offset. + // the rows sorted by register (unallocated last), then by name offset: + // of two elements packed into one register, the one first in element + // order comes first whatever its columns (a sort by column made the + // validator refuse 72 of the title's vertex, mesh and pixel programs: + // "does not match expected for module"). let mut offsets: Vec = Vec::new(); let mut next = 8 + 32 * elements.len() as u32; let mut names = Vec::new(); @@ -115,6 +119,52 @@ pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec { out } +/// One interpolation mode per register. The console's compiler packs only elements of one +/// mode into a register, and the validator refuses two ("has interpolation mode that differs +/// from another element packed into the same row"), but the modes here are partly defaults: a +/// float is linear unless a pixel program's reads say otherwise, so a float the console +/// declared `nointerpolation` beside an integer came out linear. Where a register's modes +/// differ, the elements whose mode is fixed give it to the others if they agree on one: an +/// integer or the front face (constant only) and, with `read` (pixel inputs), an element the +/// program reads (the mode its reads asked for). The others' mode decides nothing: an +/// output's interpolation is the pixel input's, and an input no read asks for is never +/// interpolated. A register whose modes agree stays as it was. +/// The title's 70 programs that packed two modes into a register (23 vertex and mesh, 47 +/// pixel) each had a float of the console's constant mode (its `PSV0`) beside an integer, the +/// front face, or an input read at its vertices, that float written (outputs) or not read +/// (inputs). +pub(crate) fn one_mode_per_register(elements: &mut [SigElement], read: bool) { + let fixed = |e: &SigElement| e.comp != 9 || e.kind == 13 || (read && e.usage != 0); + let mut rows: Vec = elements.iter().filter_map(|e| e.row).collect(); + rows.sort_unstable(); + rows.dedup(); + for row in rows { + // (an undefined mode, 0, takes the others' in the validator) + let of = |e: &SigElement| e.row == Some(row) && e.interp != 0; + let mut modes: Vec = elements + .iter() + .filter(|e| of(e)) + .map(|e| e.interp) + .collect(); + modes.sort_unstable(); + modes.dedup(); + if modes.len() < 2 { + continue; + } + let mut given: Vec = elements + .iter() + .filter(|e| of(e) && fixed(e)) + .map(|e| e.interp) + .collect(); + given.sort_unstable(); + given.dedup(); + let [mode] = given[..] else { continue }; + for e in elements.iter_mut().filter(|e| of(e) && !fixed(e)) { + e.interp = mode; + } + } +} + /// The most a mesh shader's outputs may take, in bytes (D3D12). pub(crate) const MESH_OUTPUT_LIMIT: u64 = 32 * 1024; @@ -413,6 +463,91 @@ fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { mod tests { use super::*; + /// Two elements packed into one register are written in element order, not by column + /// (the title's packed pedestrian outputs: TEXCOORD22 in columns 1-2 of the register + /// whose column 0 is COLOR0, listed after it). + #[test] + fn rows_of_one_register_keep_the_element_order() { + let element = |name: &str, index, row, col, cols| SigElement { + name: name.into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: false, + }; + let part = signature( + &[ + element("TEXCOORD", 19, 13, 0, 3), + element("TEXCOORD", 22, 14, 1, 2), + element("COLOR", 0, 14, 0, 1), + element("TEXCOORD", 21, 15, 0, 3), + ], + false, + ); + let u32_at = |at: usize| u32::from_le_bytes(part[at..at + 4].try_into().unwrap()); + // (register, semantic index, mask) of each 32-byte row after the 8-byte header + let rows: Vec<(u32, u32, u8)> = (0..4) + .map(|k| 8 + 32 * k) + .map(|at| (u32_at(at + 20), u32_at(at + 8), part[at + 24])) + .collect(); + assert_eq!(rows, [(13, 19, 0b111), (14, 22, 0b110), (14, 0, 0b1), (15, 21, 0b111)]); + } + + /// The registers of the title's programs that packed two modes: a float beside an integer + /// or the front face, an unread input beside one read at its vertices. Registers whose modes + /// agree, and those whose fixed elements disagree, keep their modes. + #[test] + fn one_register_takes_the_mode_of_its_fixed_elements() { + let element = |name: &str, row, col, cols, comp, interp, usage| SigElement { + name: name.into(), + index: 0, + kind: if name == "SV_IsFrontFace" { 13 } else { 0 }, + comp, + interp, + row: Some(row), + col, + cols, + usage, + half: false, + }; + let modes = |els: &[SigElement]| els.iter().map(|e| e.interp).collect::>(); + // VS_Transform_VfxVBuffer_AlphaClip's outputs: TEXCOORD2 (float2) beside TEXCOORD14 + // (uint2) in register 7; register 6 holds two linear floats. + let mut outputs = vec![ + element("TEXCOORD", 6, 0, 3, 9, 2, 0b111), + element("TEXCOORD", 6, 3, 1, 9, 2, 0b1), + element("TEXCOORD", 7, 0, 2, 9, 2, 0b11), + element("TEXCOORD", 7, 2, 2, 5, 1, 0b11), + ]; + one_mode_per_register(&mut outputs, false); + assert_eq!(modes(&outputs), [2, 2, 1, 1]); + // A pixel program's inputs: an unread float beside the front face; another beside an + // input read at its vertices (constant), where the float would be linear. + let mut inputs = vec![ + element("TEXCOORD", 9, 0, 1, 9, 2, 0), + element("SV_IsFrontFace", 9, 1, 1, 5, 1, 0b1), + element("NORMAL", 5, 0, 3, 9, 2, 0), + element("TEXCOORD", 5, 3, 1, 9, 1, 0b1), + ]; + one_mode_per_register(&mut inputs, true); + assert_eq!(modes(&inputs), [1, 1, 1, 1]); + // Two floats a pixel program reads in two modes: no element gives the register one. + let mut both = vec![ + element("TEXCOORD", 3, 0, 2, 9, 2, 0b11), + element("TEXCOORD", 3, 2, 2, 9, 3, 0b11), + ]; + one_mode_per_register(&mut both, true); + assert_eq!(modes(&both), [2, 3]); + // As outputs nothing is read: the floats keep their defaults too. + one_mode_per_register(&mut both, false); + assert_eq!(modes(&both), [2, 3]); + } + #[test] fn fixed_wave_size_requires_matching_lanes_in_complete_runtime_info() { let mut p = Psv { diff --git a/crates/victory-shader/src/emit/descriptor_data.rs b/crates/victory-shader/src/emit/descriptor_data.rs new file mode 100644 index 0000000000..6f3efab1ca --- /dev/null +++ b/crates/victory-shader/src/emit/descriptor_data.rs @@ -0,0 +1,372 @@ +//! Descriptor loads whose dwords the code reads as numbers: the console compiler computes a +//! texture's or a buffer's size from its descriptor's bits instead of asking for it, and walks +//! the memory a buffer's address points at. The fields the host can tell are rebuilt from its +//! view; the others have no value. + +use super::{ + Attr, Bin, Fields, Inst, Lower, Operand, Reg, ResourceType, Role, RootType, Site, Source, UsedResource, V, + Val, Why, +}; + +impl<'a> Lower<'a> { + /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords + /// the code reads as numbers, besides using the descriptor or (an image's + /// size) instead of it: the console compiler computes sizes + /// from descriptor bits (an image's width, height, depth, levels; a + /// buffer's record count) instead of querying them. Those fields are + /// rebuilt from the host view's dimensions in the GFX10 layout (image + /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits + /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at + /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). + // shortcut: the base level reads 0 (the host view starts at its own + // level 0, so sizes the code shifts by it come out right) and the other + // dwords (addresses, formats, tiling) have no host value: reading them + // stops the program. + pub(super) fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + const OTHER: Why = "a descriptor's address or format read as data"; + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar memory read as data"); + }; + 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 memory read as data"), + }; + // How the program uses the descriptor tells the view's kind: an image or buffer + // instruction before a scalar buffer load, which reads any buffer. + let x = self.x; + let uses = |of: Site| { + x.res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .filter_map(move |d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } if load == of => Some((d.site, first)), + _ => None, + }) + }) + }; + let by_scalar_load = |u: &(Site, u8)| { + matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) + }; + let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); + // The console compiler loads a descriptor again wherever it needs it, and for a + // size it reads the dwords of a load that nothing uses as a descriptor (a texture + // picked from the heap by an index held per lane: one load for its width, one for + // its base level, one for each read of the image). Another load of as many dwords + // from the same address reads the same descriptor, so what uses that one tells + // this one's kind. The handle is still made from this load's own operands, which + // hold here. + let address = self.scalar.get(&site).copied(); + let twin = || { + let a = address?; + let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); + x.res + .scalar + .iter() + .filter(|(s, b)| *s != site && *b == a && same(*s)) + .find_map(|(s, _)| use_of(*s)) + }; + let use_at = use_of(site).or_else(twin); + // `sized`: no instruction uses the descriptor, the code reads a size from it + // ([`Self::unused_descriptor_kind`]). + let (first, used, uav, props, image, sized) = if let Some((at, first)) = use_at { + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + let ty = if !uav && self.scalar_uint_srv(&src, kind) { 0x105 } else { 0x409 }; + ((kind | u, ty), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + let ty = if !uav && self.scalar_uint_srv(&src, 10) { 0x105 } else { 0x409 }; + (10 | u, ty) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) + { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + (props, None) + } + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. + Fields::Smem { .. } => { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + _ => return Err("a scalar memory read as data"), + }; + (first, used, uav, props, image, false) + } else { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as a + // descriptor's address or format is. + let sampler = x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk the memory behind it + // (a ray-tracing structure), or tests a structured view's record count: the + // address from the host, the record count where it is a structured view's, the + // other dwords have no value. + let mut pointer = if count <= 4 { self.view_address(site) } else { None }; + if pointer.is_none() && count == 4 && self.picked_address_words(site, code) { + pointer = Some(self.picked_address(site)?); + } + // Puddle detection looks up a 2D texture's dimensions by heap index without + // sampling it: that index queries the bound host view. Only the heap supplies + // this otherwise untyped 2D lookup. + let puddle = count == 8 + && address.is_some_and(|a| { + a.dynamic.is_some() + && x.native + .layout + .get(a.param) + .is_some_and(|p| p.root == RootType::ResourceHeap) + }); + if count <= 4 + && let Some((lo, hi)) = pointer + { + let records = inst + .write(Reg::S(code + 2)) + .and_then(|value| self.structured_srv_records(site, value)); + for k in 0..count { + let reg = Reg::S(code + k as u8); + match (k, records) { + (0, _) => self.write(inst, reg, lo, None), + (1, _) => self.write(inst, reg, hi, None), + (2, Some(n)) => self.write(inst, reg, n, None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); + } else if puddle { + (0, None, false, (2, 0x409), Some(2), false) + } else if let Some((used, uav, props, image)) = + self.unused_descriptor_kind(inst, site, code, count) + { + (0, used, uav, props, image, true) + } else { + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + eprintln!( + "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", + inst.machine.offset, + inst.name(), + address, + self.x.res.lane_copied.contains(&site) + ); + } + return Err("a descriptor read only as data"); + } + }; + let src = Source::Loaded { load: site, first }; + let h = self.handle(site, &src, false, props)?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = if image.is_some() && !uav { + self.s.m.i32(0) + } else { + self.s.m.undef(i32t) + }; + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); + let words: Vec<(u32, V)> = match image { + Some(kind) => { + let one = self.s.m.i32(1); + let w = field(self, 0); + let (height, depth) = match kind { + 1 => (one, one), + 2 => (field(self, 1), one), + 6 => (one, field(self, 1)), + _ => (field(self, 1), field(self, 2)), + }; + let levels = if uav { one } else { field(self, 3) }; + let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); + let (w, height, depth, levels) = ( + less(self, w), + less(self, height), + less(self, depth), + less(self, levels), + ); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k30, k2, k14, k16, mask) = ( + k(self, 30), + k(self, 2), + k(self, 14), + k(self, 16), + k(self, 0x3FFF), + ); + let d1 = self.s.m.bin(c, Bin::Shl, w, k30); + let hi = self.s.m.bin(c, Bin::LShr, w, k2); + let hi = self.s.m.bin(c, Bin::And, hi, mask); + let ht = self.s.m.bin(c, Bin::Shl, height, k14); + let d2 = self.s.m.bin(c, Bin::Or, hi, ht); + let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; + let base = k(self, 0xFAC | ty << 28); + let last = self.s.m.bin(c, Bin::Shl, levels, k16); + let d3 = self.s.m.bin(c, Bin::Or, base, last); + vec![(1, d1), (2, d2), (3, d3), (4, depth)] + } + None => { + // A raw view counts bytes; the descriptor's record count is in elements. + let n = field(self, 0); + let stride = used.map_or(0, |u| u.stride); + let n = if props.0 & 0xFF == 11 && stride > 1 { + let k = self.s.m.i32(stride); + self.s.m.bin(c, Bin::UDiv, n, k) + } else { + n + }; + let mut words = vec![(2, n)]; + // Its address too, where the code computes with it and the + // host can tell it. + let computed = (0..2u8).any(|k| { + inst.write(Reg::S(code + first + k)) + .is_some_and(|v| self.computed_with(v, 6)) + }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) + if first == 0 + && (computed || sized) + && let Some((lo, hi)) = self.view_address(site) + { + words.extend([(0, lo), (1, hi)]); + } + words + } + }; + for k in 0..count { + let rel = k.wrapping_sub(u32::from(first)); + match words.iter().find(|w| w.0 == rel) { + Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), + None => { + if let Some(v) = inst.write(Reg::S(code + k as u8)) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + Ok(()) + } + + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose size the code reads (the console compiler computes `GetDimensions` + /// from the descriptor's bits): its used-resource entry, whether it is an unordered view, + /// the handle properties and the image kind (none for a buffer). None for anything else + /// (a constant buffer, a buffer whose address alone is read). The caller has handled + /// descriptors kept per lane and samplers'. + /// - An image's eight dwords: a 2D texture's (the title's puddle and shadow mask programs + /// take the texel size of a heap texture they do not sample). + /// - A buffer's four dwords whose table entry says what it is: a view as the title made + /// it, structured where its elements are whole dwords (the title's water simulation + /// tests a structured buffer it does not read for being empty, by its record count). + /// A raw handle of the structured view the heap holds answers wrong: 2 records for 9 + /// of 16 bytes on an RTX 5090 (`descriptor_tests`, run with a raw handle). + /// With no entry, a raw view where the code reads the record count (dword 2). + // shortcut: an image whose kind nothing tells is taken for a 2D texture; a host view of + // another kind is queried through a 2D texture's handle. + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(Option<&'a UsedResource>, bool, (u32, u32), Option)> { + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + 8 if used.is_none_or(|u| u.dwords == 8) => Some((used, uav, (2 | u, 0x409), Some(2))), + 4 if used.is_some_and(|u| u.dwords == 4) || used.is_none() && read(2) => { + let stride = used.map_or(0, |u| u.stride); + let props = if stride >= 4 && stride.is_multiple_of(4) { + (12 | u, stride) + } else { + (11 | u, 0) + }; + Some((used, uav, props, None)) + } + _ => None, + } + } +} diff --git a/crates/victory-shader/src/emit/descriptor_tests.rs b/crates/victory-shader/src/emit/descriptor_tests.rs new file mode 100644 index 0000000000..b71ffaac19 --- /dev/null +++ b/crates/victory-shader/src/emit/descriptor_tests.rs @@ -0,0 +1,244 @@ +//! End-to-end tests of descriptors that no instruction names alone: an image's or a buffer's +//! descriptor the code reads only the size of, and an immediate sampler each arm of a uniform +//! branch sets its own of. Synthetic GFX10 compute programs translated ([`super::emit`]), +//! validated by `dxil.dll` when present, and run on the host GPU and WARP. + +use super::host::{Dispatch, Host, Root, View}; +use super::{HostShader, validator}; +use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, +}; +use crate::{Container, dxbc, io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// A wave32 compute program of one thread: 4 root constants in s0..s3 and, in s4, a table +/// with a texture's descriptor at dword 0 and a raw UAV's at dword 8; `body` follows the +/// loads of the texture's descriptor into s[8:15] and the UAV's into s[16:19]. +fn native(body: &[u32]) -> NativeProgram { + native_of(body, 8, 0) +} + +/// [`native`] with a view of `dwords` dwords (8: a texture, 4: a buffer of elements of +/// `stride` bytes) at dword 0, loaded into s8 on. +fn native_of(body: &[u32], dwords: u8, stride: u32) -> NativeProgram { + let load = match dwords { + 8 => 0xF40C_0202, // s_load_dwordx8 s[8:15], s[4:5], null + _ => 0xF408_0202, // s_load_dwordx4 s[8:11], s[4:5], null + }; + let mut words = vec![ + 0xBE85_0380, // s_mov_b32 s5, 0 + load, + 0xFA00_0000, + 0xF408_0402, + 0xFA00_0020, // s_load_dwordx4 s[16:19], s[4:5], 0x20 + ]; + words.extend_from_slice(body); + words.push(S_ENDPGM); + let range = |kind, table_offset_dwords, dwords, stride| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords, + lower_bound: 0, + stride, + dwords, + user_data: 4, + slot: 1, + }; + NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 16, + layout: vec![ + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![ + range(ResourceType::Srv, 0, dwords, stride), + range(ResourceType::Uav, 8, 4, 0), + ], + io: StageIo::Cs(ComputeIo { + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [1, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + } +} + +/// `native` translated as the title's programs are, and validated. +fn translate(native: &NativeProgram) -> HostShader { + let container = dxbc::build(&[]); + let c = Container::parse(&container).expect("container"); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("track"); + let io = io::raise(&p, native).expect("io::raise"); + let shader = super::emit(&c, native, &p, &st, &io, &res).expect("emit"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + v.validate(&mut shader.dxil.clone()) + .expect("DXIL validation failed"); + } else { + eprintln!("no dxil.dll; validation skipped"); + } + shader +} + +/// Runs `shader` with root constant 0 at `s0`, the texture and a UAV of 4 dwords at heap +/// indices 0 and 1, on the hardware GPU and on WARP (each skipped without a device), and +/// returns per one that ran the UAV's dwords. +fn run(shader: &HostShader, s0: u32, texture: View) -> Vec<(&'static str, Vec)> { + run_with_records(shader, s0, texture, 0) +} + +/// [`run`] with `records` in the root word a structured view's record count is read from +/// (`USER_VIEW_RECORDS`, which the runtime fills from the bound view). +fn run_with_records( + shader: &HostShader, + s0: u32, + texture: View, + records: u32, +) -> Vec<(&'static str, Vec)> { + let views = [texture, View::RawUav(4)]; + let mut out = Vec::new(); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + 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 constant is s0; the table starts at heap index 0. + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + ud[u.index as usize] = match (u.root, u.dword) { + (RootType::Constants, 0) => s0, + (RootType::Other(super::USER_VIEW_RECORDS), _) => records, + _ => 0, + }; + } + let words = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + out.push((label, words[0].clone())); + } + out +} + +#[test] +fn a_texture_read_only_for_its_size_gives_the_views_size() { + // The console compiler's `GetDimensions` of a texture the program does not sample: width + // and height from the descriptor's bits, and its last level; stored to the UAV. + let shader = translate(&native(&[ + 0x9014_9E09, // s_lshr_b32 s20, s9, 30 + 0x8F15_820A, // s_lshl_b32 s21, s10, 2 + 0x8814_1514, // s_or_b32 s20, s20, s21 + 0x8714_FF14, + 0x0000_3FFF, // s_and_b32 s20, s20, 0x3fff + 0x8114_8114, // s_add_i32 s20, s20, 1 + 0x9396_FF0A, + 0x000E_000E, // s_bfe_u32 s22, s10, 0x000e000e (bits 14-27) + 0x8116_8116, // s_add_i32 s22, s22, 1 + 0x9397_FF0B, + 0x0004_0010, // s_bfe_u32 s23, s11, 0x00040010 (bits 16-19) + 0x7E02_0214, // v_mov_b32 v1, s20 + 0x7E04_0216, // v_mov_b32 v2, s22 + 0x7E06_0217, // v_mov_b32 v3, s23 + 0xE070_0000, + 0x8004_0100, // buffer_store_dword v1, off, s[16:19], 0 + 0xE070_0004, + 0x8004_0200, // buffer_store_dword v2, off, s[16:19], 0 offset:4 + 0xE070_0008, + 0x8004_0300, // buffer_store_dword v3, off, s[16:19], 0 offset:8 + ])); + let texels = [[0.0f32; 4]; 13 * 7]; + let results = run(&shader, 0, View::Texture(13, 7, &texels)); + for (label, words) in results { + // 13 x 7 texels, one level (the last is level 0). + assert_eq!(words, [13, 7, 0, 0], "{label}"); + } +} + +#[test] +fn a_buffer_read_only_for_its_size_gives_the_views_element_count() { + // The title's water simulation: whether a structured buffer has any elements, from its + // descriptor's record count, the buffer itself not read; stored to the UAV. + let shader = translate(&native_of( + &[ + 0x7E02_020A, // v_mov_b32 v1, s10 + 0xE070_0000, + 0x8004_0100, // buffer_store_dword v1, off, s[16:19], 0 + ], + 4, + 16, + )); + let data = [0u32; 4 * 9]; + let buffer = View::Buffer { + data: &data, + stride: super::host::Stride::Structured(16), + }; + for (label, words) in run_with_records(&shader, 0, buffer, 9) { + // nine elements of 16 bytes + assert_eq!(words[0], 9, "{label}"); + } +} + +#[test] +fn a_sampler_each_arm_of_a_uniform_branch_sets_samples_as_that_arm_says() { + // The title's terrain programs: an immediate sampler that clamps (0x92: clamp in x, y and + // z) or wraps (0) by a root constant, joined before one sample. Point filtering at u = + // 1.25 of a 2 x 1 texture: wrapped, texel 0 (red 1.0); clamped, texel 1 (red 2.0). + let shader = translate(&native(&[ + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // s_cbranch_scc1 -> s_mov_b32 s20, 0 + 0xB014_0092, // s_movk_i32 s20, 0x92 + 0xBF82_0001, // s_branch -> the join + 0xBE94_0380, // s_mov_b32 s20, 0 + 0xBE95_03FF, + 0x00C0_0000, // s_mov_b32 s21, 0x00c00000 (levels up to 12) + 0xBE96_0380, // s_mov_b32 s22, 0 (point filtering) + 0xBE97_0380, // s_mov_b32 s23, 0 + 0x7E02_02FF, + 0x3FA0_0000, // v_mov_b32 v1, 1.25 + 0x7E04_02FF, + 0x3F00_0000, // v_mov_b32 v2, 0.5 + 0xF09C_0F08, + 0x00A2_0301, // image_sample_lz v[3:6], v[1:2], s[8:15], s[20:23] dmask:0xf 2D + 0xE070_0000, + 0x8004_0300, // buffer_store_dword v3, off, s[16:19], 0 + ])); + // One immediate sampler per arm, each the arm's own. + assert_eq!(shader.static_samplers.len(), 2); + let texels = [[1.0f32, 0.0, 0.0, 1.0], [2.0, 0.0, 0.0, 1.0]]; + for (s0, red) in [(0, 1.0f32), (1, 2.0)] { + for (label, words) in run(&shader, s0, View::Texture(2, 1, &texels)) { + assert_eq!(f32::from_bits(words[0]), red, "{label}, s0 = {s0}"); + } + } +} diff --git a/crates/victory-shader/src/emit/float64.rs b/crates/victory-shader/src/emit/float64.rs new file mode 100644 index 0000000000..5a6c16eb52 --- /dev/null +++ b/crates/victory-shader/src/emit/float64.rs @@ -0,0 +1,320 @@ +//! 64-bit floats: `v_add_f64`, `v_mul_f64` and `v_cvt_f64_f32` as the host's doubles, +//! `v_cvt_f32_f64` on 32-bit integers, and the 64-bit float wave sums of whole-wave sections +//! ([`super::super::wave::Shape::Sum64`]). The title's water volumetrics count their lanes in +//! doubles (`WaveActiveSum(1.0L)`, `v_add_f64` over DPP-moved dword pairs) and take the count +//! back as a float. +//! +//! The host's doubles are IEEE, rounded to nearest with denormals kept, as the console's FP64 +//! mode is. A double is made from its two dwords (`dx.op.makeDouble`) and taken apart again +//! (`dx.op.splitDouble`), so no 64-bit integer is needed. `v_cvt_f32_f64` takes the double's +//! dwords apart itself, rounding as IEEE does with float denormals kept, so a conversion alone +//! asks no double support of the host. + +use super::{Attr, Bin, Cast, Fields, Inst, Lower, MaskData, Operand, Reg, V, Value, Why, flags, need, pred}; +use crate::gfx10::NULL; + +impl Lower<'_> { + /// The 64-bit float operations, if `name` is one. + pub(super) fn valu_f64(&mut self, inst: &Inst, name: &str, guard: Option) -> Option> { + let c = self.cur; + Some(match name { + "v_cvt_f32_f64" => self.f64_pair(inst, 0).and_then(|(lo, hi)| { + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + self.write_f(inst, r, guard) + }), + "v_cvt_f64_f32" => self.fsrc(inst, 0).and_then(|x| { + let f64t = self.s.m.double(); + self.s.flags |= flags::DOUBLES; + let r = self.s.m.cast(c, Cast::FpExt, x, f64t); + self.write_f64(inst, r, guard) + }), + "v_add_f64" | "v_mul_f64" => (|| { + let (a, b) = (self.fsrc64(inst, 0)?, self.fsrc64(inst, 1)?); + let op = if name == "v_add_f64" { Bin::Add } else { Bin::Mul }; + let r = self.s.m.bin(c, op, a, b); + self.write_f64(inst, r, guard) + })(), + _ => return None, + }) + } + + /// The 64-bit float `WaveActiveSum` over the console's wave of each lane's own + /// `mask ? (lo, hi) : 0.0`, as its two dwords: the host's wave operation on doubles, and + /// on two host waves of 32 their sums added (the lower half's first). Made once per + /// block, for both dwords. + /// shortcut: the host adds a wave's terms in its own order, not the console's tree of + /// lanes; the sum can differ in its last bits where terms round (as for 32-bit sums). + pub(super) fn sum64(&mut self, lo: Value, hi: Value, mask: Value) -> Result<[V; 2], Why> { + let key = (lo, hi, mask, self.cur); + if let Some(&d) = self.sums64.get(&key) { + return Ok(d); + } + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self.x.st.masks.get(&mask).ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let (l, h) = (self.i32_of(lo)?, self.i32_of(hi)?); + let x = self.masked_double(on, l, h); + let r = self.wave_sum_f64(x); + // two host waves of 32 hold the console's 64 lanes: their sums add up + let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { + r + } else if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (rl, rh) = self.split_double(r); + let c = self.cur; + let (lower_lo, upper_lo) = self.exchange_halves(c, rl); + let (lower_hi, upper_hi) = self.exchange_halves(c, rh); + let lower = self.make_double(lower_lo, lower_hi); + let upper = self.make_double(upper_lo, upper_hi); + self.s.m.bin(self.cur, Bin::Add, lower, upper) + } else { + r + }; + let (dl, dh) = self.split_double(r); + self.sums64.insert(key, [dl, dh]); + Ok([dl, dh]) + } + + /// [`Self::sum64`] in the paired form: the lower lanes' sum, then the upper lanes' added, + /// as two host waves add theirs; dword `high` of it, for both lanes of this thread. + pub(super) fn paired_sum64(&mut self, high: bool, lo: Value, hi: Value, mask: Value) -> Result<[V; 2], Why> { + let key = (lo, hi, mask, self.cur); + let d = match self.sums64.get(&key) { + Some(&d) => d, + None => { + let &m = self.x.st.masks.get(&mask).ok_or("a wave reduction's untracked mask")?; + let c = self.cur; + let [x0, x1] = self.both(|l| { + let on = l.boolean(m, c)?; + let (dl, dh) = (l.i32_of(lo)?, l.i32_of(hi)?); + Ok(l.masked_double(on, dl, dh)) + })?; + let (s0, s1) = (self.wave_sum_f64(x0), self.wave_sum_f64(x1)); + let total = self.s.m.bin(self.cur, Bin::Add, s0, s1); + let (dl, dh) = self.split_double(total); + self.sums64.insert(key, [dl, dh]); + [dl, dh] + } + }; + let x = d[usize::from(high)]; + Ok([x, x]) + } + + /// `on ? (lo, hi) : +0.0` as a double. + fn masked_double(&mut self, on: V, lo: V, hi: V) -> V { + let x = self.make_double(lo, hi); + let z = self.s.m.i32(0); + let zero = self.make_double(z, z); + self.s.m.select(self.cur, on, x, zero) + } + + /// `WaveActiveSum` of the double `x` over this host wave's active lanes. + fn wave_sum_f64(&mut self, x: V) -> V { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let f64t = self.s.m.double(); + let (sum, signed) = (self.s.m.i8(0), self.s.m.i8(0)); + self.s.op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[x, sum, signed]) + } + + /// The double whose dwords are `lo` and `hi` (`dx.op.makeDouble`). + fn make_double(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let f64t = self.s.m.double(); + self.s.flags |= flags::DOUBLES; + self.s.op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]) + } + + /// The low and high dwords of the double `d` (`dx.op.splitDouble`). + fn split_double(&mut self, d: V) -> (V, V) { + let c = self.cur; + let i32t = self.s.t.i32; + let pair = self.s.m.named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let r = self.s.op(c, "splitDouble.f64", Attr::ReadNone, pair, 102, &[d]); + (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)) + } + + /// A 64-bit float source as a double ([`Self::f64_pair`]). + fn fsrc64(&mut self, inst: &Inst, k: usize) -> Result { + let (lo, hi) = self.f64_pair(inst, k)?; + Ok(self.make_double(lo, hi)) + } + + /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying + /// `abs` and `neg` input modifiers on operand `k`. + fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok((lo, hi)) + }; + let (lo, mut hi) = match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1))? + } + Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), + Operand::Const(c @ 240..=248) => { + const INLINE_F64: [f64; 9] = [ + 0.5, + -0.5, + 1.0, + -1.0, + 2.0, + -2.0, + 4.0, + -4.0, + // 1 / (2 pi) as the hardware holds it (the nearest double ends in ...883) + f64::from_bits(0x3FC4_5F30_6DC9_C882), + ]; + let bits = INLINE_F64[(c - 240) as usize].to_bits(); + (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) + } + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), + _ => return Err("a 64-bit float operand"), + }; + let c = self.cur; + if v.abs >> k & 1 != 0 { + let mask = self.s.m.i32(0x7FFF_FFFF); + hi = self.s.m.bin(c, Bin::And, hi, mask); + } + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000_0000); + hi = self.s.m.bin(c, Bin::Xor, hi, sign); + } + Ok((lo, hi)) + } + + /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, + /// without requiring host `DOUBLES` (`f64`) support. + fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k0 = self.s.m.i32(0); + let k1 = self.s.m.i32(1); + let sign_mask = self.s.m.i32(0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + + let k20 = self.s.m.i32(20); + let k7ff = self.s.m.i32(0x7FF); + let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); + let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); + + let frac_mask = self.s.m.i32(0x000F_FFFF); + let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); + let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); + let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); + + let k3 = self.s.m.i32(3); + let k29 = self.s.m.i32(29); + let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); + let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); + let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); + + let rem_mask = self.s.m.i32(0x1FFF_FFFF); + let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); + let half_rem = self.s.m.i32(0x1000_0000); + let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); + let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); + let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); + let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); + let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); + let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); + let norm_inc = self.s.m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + let k896 = self.s.m.i32(896); + let k23 = self.s.m.i32(23); + let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); + let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); + let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); + let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); + let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + let k897 = self.s.m.i32(897); + let k32 = self.s.m.i32(32); + let k31 = self.s.m.i32(31); + let imp = self.s.m.i32(0x0080_0000); + let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); + let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); + let shift = self.s.m.select(c, lt1, k1, raw_shift); + let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); + let shift = self.s.m.select(c, gt23, k23, shift); + let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); + let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); + let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); + let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); + let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); + let low31 = self.s.m.i32(0x7FFF_FFFF); + let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); + let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); + let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); + let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); + let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); + let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); + let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); + let sub_inc = self.s.m.select(c, sub_round, k1, k0); + let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); + let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). + let k873 = self.s.m.i32(873); + let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); + let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); + let min_bit = self.s.m.select(c, round_min, k1, k0); + let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); + let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); + let inf_bits = self.s.m.i32(0x7F80_0000); + let qnan_bits = self.s.m.i32(0x7FC0_0000); + let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); + let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); + let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + let k874 = self.s.m.i32(874); + let k1151 = self.s.m.i32(1151); + let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); + let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); + let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); + let r = self.s.m.select(c, is_over, over_res, norm_res); + let r = self.s.m.select(c, is_sub, sub_res, r); + self.s.m.select(c, is_under, under_res, r) + } + + /// A 64-bit float result into its VGPR pair. + fn write_f64(&mut self, inst: &Inst, d: V, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.clamp || v.omod != 0 { + return Err("64-bit float output modifiers"); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split_double(d); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + Ok(()) + } +} diff --git a/crates/victory-shader/src/emit/idiom.rs b/crates/victory-shader/src/emit/idiom.rs new file mode 100644 index 0000000000..450944799e --- /dev/null +++ b/crates/victory-shader/src/emit/idiom.rs @@ -0,0 +1,331 @@ +//! Whether a console wave64 program's wave operations are the allocation idiom +//! ([`wave_local`]), which each host wave may run on its own: moved out of `lower` whole. + +use std::collections::{HashMap, HashSet}; + +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Inst, Program, Reg, Value}; +use crate::structure::{Atom, LaneExit, Structured}; + +type Why = &'static str; + +/// What a register value holds, for [`wave_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Wave { + /// Nothing that depends on how the threads are divided into waves. + Plain, + /// The number of the wave's first lane in a mask (`s_ff1`). + First, + /// A reduction over the wave's lanes: a count, a sum, a minimum... + Total(super::wave::Op), + /// A count or sum over the lanes below this one. + Prefix, + /// Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + /// A mix the idiom does not make. + Mixed, +} + +/// Whether a console wave64 program may run with each host wave as a wave of its own +/// ([`super::lower::with_local_waves`]): its wave-wide values are used only as the allocation idiom uses +/// them, which does not care how the threads are divided into waves. A first-lane number only +/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; +/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. +/// Anything else done with them takes one wave to be the whole thread group (a tile's result, +/// say) and is refused, with the offset and what was found. +/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections +/// are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this +// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is +// the only mix of old and new lanes that is looked at. +pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { + use super::wave::{Op, Shape}; + const FIRST: Why = "a wave's first-lane number used as data"; + const TOTAL: Why = "a count or sum over the wave used as data"; + const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; + const MIXED: Why = "a value that depends on the wave on some paths only"; + const EFFECT: Why = "a write by the wave's first lane other than its reservation"; + fn of(kind: &HashMap, v: Option) -> Wave { + v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) + } + fn put(kind: &mut HashMap, v: Value, k: Wave) { + if k == Wave::Plain { + kind.remove(&v); + } else { + kind.insert(v, k); + } + } + let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); + let why = |k: Wave| match k { + Wave::First => FIRST, + Wave::Total(_) => TOTAL, + Wave::Prefix => PREFIX, + _ => MIXED, + }; + // a mask (by its low dword) under which only a wave's first lane runs + let first_mask = |firsts: &HashSet, m: Option| { + m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { + st.bools + .support(b) + .iter() + .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) + }) + }; + // One instruction outside a section: the kind of what it writes, and whether it is a + // first lane's reservation. + let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { + let name = inst.name(); + let val = |op: &Operand| match *op { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let ops: Vec = match &inst.fields { + Fields::Valu(v) => v.src.clone(), + Fields::Sop { dst, src, .. } => { + let mut o = src.clone(); + if matches!(name, "s_addk_i32" | "s_mulk_i32") { + o.extend(dst.iter().copied()); + } + o + } + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + data.iter().copied().collect() + } + _ => Vec::new(), + }; + let kinds: Vec = ops.iter().map(|o| of(kind, val(o))).collect(); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide + // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it + // writes, which only the lanes outside EXEC keep. + let named: Vec = ops.iter().filter_map(&val).collect(); + for &(r, v) in &inst.reads { + let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); + if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + continue; + } + let k = of(kind, Some(v)); + if wild(k) { + return Err(why(k)); + } + } + let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); + let sum = |k: Wave| k == Wave::Total(Op::AddU); + let is_mask = |o: &Operand| { + val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) + }; + let mut reserved = false; + let out = match (name, &kinds[..]) { + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, + ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::Total(Op::AddU) + } + // bits of a mask below the lane; with -1 for the mask, the lane's number + ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { + match (matches!(ops[0], Operand::Scalar { .. }), *b) { + (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, + (false, Wave::Plain | Wave::Base) => Wave::Plain, + (_, k) => return Err(why(k)), + } + } + // nothing wave-dependent goes in; what derives from a reserved base stays marked + _ if !kinds.iter().any(|&k| wild(k)) => { + let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); + if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } + } + ("v_mov_b32" | "s_mov_b32", [k]) => *k, + ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { + // the lane whose own number is the first lane's + let lane = match (*a, *b) { + (Wave::First, k) if !wild(k) => &ops[1], + (k, Wave::First) if !wild(k) => &ops[0], + _ => return Err(why(w)), + }; + if !matches!(lane, Operand::Vector { .. }) { + return Err(FIRST); + } + let mask = match &inst.fields { + _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), + Fields::Valu(v) => match v.dst { + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), + _ => None, + }, + _ => None, + }; + firsts.extend(mask); + Wave::Plain + } + ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { + (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, + (x, y) if sum(x) && sum(y) => x, + _ => return Err(why(w)), + }, + ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { + (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain) => Wave::Prefix, + (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, + _ => return Err(why(w)), + }, + ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { + (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, + _ => return Err(why(w)), + }, + ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) + if sum(*x) || *x == Wave::Prefix => + { + *x + } + ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the prefix in units of a plain size, onto the base: the lens-flare scans reserve + // their count times the size, and each lane takes base + below × size + ("v_mad_u32_u24" | "v_mad_u32_u16", [Wave::Prefix, Wave::Plain, c] | [Wave::Plain, Wave::Prefix, c]) + if !wild(*c) => + { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the reservation: the first lane adds its wave's total to a shared counter + (_, [Wave::Total(op)]) if name.contains("_atomic_") => { + let want = match op { + Op::AddU => "buffer_atomic_add", + Op::MinU => "buffer_atomic_umin", + Op::MaxU => "buffer_atomic_umax", + Op::MinI => "buffer_atomic_smin", + Op::MaxI => "buffer_atomic_smax", + Op::Or => "buffer_atomic_or", + Op::And => "buffer_atomic_and", + Op::Xor => "buffer_atomic_xor", + _ => "", + }; + if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err(TOTAL); + } + reserved = true; + Wave::Base + } + _ => return Err(why(w)), + }; + Ok((out, reserved)) + }; + let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + let order = crate::ir::reverse_postorder(&p.blocks); + let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + for &b in &order { + let block = &p.blocks[b]; + for phi in &block.phis { + let mut k = Wave::Plain; + for (n, &a) in phi.args.iter().enumerate() { + let x = of(kind, Some(a)); + k = match (k, x) { + _ if n == 0 => x, + (k, x) if k == x => k, + (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) + | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, + _ => Wave::Mixed, + }; + } + put(kind, phi.value, k); + } + for (i, inst) in block.insts.iter().enumerate() { + // inside a whole-wave section: what the simulation found each value to be + if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { + for &(_, w) in &inst.writes { + let k = match sec.shapes.get(&w) { + None => Wave::Mixed, + Some(&Shape::K(_)) => Wave::Plain, + Some(&Shape::Value(v)) => of(kind, Some(v)), + Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), + Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Total(op), + // the first lane's own sum of a total is that total + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + _ => Wave::Mixed, + }, + Some(_) => Wave::Mixed, + }; + put(kind, w, k); + } + continue; + } + let name = inst.name(); + if name.starts_with("s_cbranch") { + continue; // with the block's exit, below + } + let (k, reserved) = match step(inst, kind, firsts) { + Ok(r) => r, + Err(why) if check => return Err((inst.machine.offset, why)), + Err(_) => (Wave::Mixed, false), + }; + // the same test as `Lower::inst`'s `effect` + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err((inst.machine.offset, EFFECT)); + } + let guarded = st.guards[b][i].is_some(); + for &(r, w) in &inst.writes { + let mut kw = match r { + // "some lane is counted" keeps the count's kind; any other SCC is one bit of data + Reg::Scc if !name.starts_with("s_bcnt1") => { + if wild(k) { Wave::Mixed } else { Wave::Plain } + } + _ => k, + }; + // a guarded write leaves the old value in the lanes outside EXEC + if guarded + && matches!(r, Reg::V(_)) + && kw == Wave::Plain + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + { + kw = Wave::Mixed; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's + // own bit (the mask is EXEC under a scalar condition) + if check + && let Some(last) = block.insts.last() + && last.name().starts_with("s_cbranch_scc") + && let Some(scc) = last.read(Reg::Scc) + && wild(of(kind, Some(scc))) + { + let own = matches!(st.exits[b], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); + if !own { + return Err((last.machine.offset, TOTAL)); + } + } + } + Ok(()) + }; + let mut kind: HashMap = HashMap::new(); + let mut firsts: HashSet = HashSet::new(); + // to a fixpoint (values carried around loops), then once more to say what is wrong + let mut settled = false; + for _ in 0..16 { + let before = (kind.clone(), firsts.len()); + pass(&mut kind, &mut firsts, false)?; + if (&before.0, before.1) == (&kind, firsts.len()) { + settled = true; + break; + } + } + if !settled { + return Err((0, MIXED)); + } + pass(&mut kind, &mut firsts, true) +} diff --git a/crates/victory-shader/src/emit/link.rs b/crates/victory-shader/src/emit/link.rs new file mode 100644 index 0000000000..6d28e7b147 --- /dev/null +++ b/crates/victory-shader/src/emit/link.rs @@ -0,0 +1,204 @@ +//! A mesh program and the pixel program drawn with it, translated for one host pipeline +//! ([`link_mesh`]). +//! +//! D3D12 caps a mesh shader's outputs at 32 KiB: 4 bytes per component of every vertex +//! element times the declared vertex maximum rounded up to 32, plus the same for primitive +//! elements (`container::mesh_output_bytes`, as the validator measures it). 71 of the +//! title's mesh programs pass it as the console declares their outputs: pedestrian, +//! vehicle and prop transforms with fire, spatter, decal and transmission variants, 128 +//! vertices of 65 to 71 components (33,280 to 36,352 bytes). NVIDIA's driver builds their +//! pipelines anyway, but the programs are invalid. D3D12 links the two stages by semantic, +//! and a pipeline needs only the outputs its pixel program reads: of the title's pixel +//! programs whose inputs such a mesh program writes, the one that reads most reads 55 +//! components (a pedestrian fire prepass). So the pair is translated again for its +//! pipeline: the mesh program declares and writes only the outputs the pixel program reads +//! (and its system values), and the pixel program leaves out the inputs it never reads, +//! which D3D12 would otherwise refuse as inputs the mesh program does not write. The +//! elements kept keep their rows and columns, each program its code and bindings. Measured +//! offline (`victory translate` with `VICTORY_PAIRS`): the ten pixel programs that read most +//! for each of the 71, and the three pairs drawn in the runs so far, all link, validate and +//! get a pipeline on an RTX 5090. + +use super::container::{MESH_OUTPUT_LIMIT, SigElement, mesh_output_bytes}; +use super::{HostShader, translate}; +use crate::dxbc::{Container, FourCC, u32_at}; +use crate::native::HwStage; +use crate::ShaderError; + +thread_local! { + /// See [`with_linked`]. + static LINKED: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// What a stage leaves out of its signatures for its partner in one host pipeline +/// ([`link_mesh`]): elements of arbitrary semantics, by name and index. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(super) struct Linked { + pub inputs: Vec<(String, u32)>, + pub outputs: Vec<(String, u32)>, +} + +/// Runs `f` with programs lowered for a linked pipeline: the elements `linked` names leave +/// the signatures; stores to such an output are not made, and the other elements keep their +/// rows and modes (ids count only what is kept). An input left out must be one the program +/// never reads: a lowering that reads one fails. +pub(super) fn with_linked(linked: Linked, f: impl FnOnce() -> R) -> R { + let was = LINKED.replace(Some(linked)); + let r = f(); + LINKED.set(was); + r +} + +/// Per element of `inputs` and of `outputs` (the signatures as the console declares them), +/// whether the stage being lowered leaves it out ([`with_linked`]); empty when not linking. +pub(super) fn left_out(inputs: &[SigElement], outputs: &[SigElement]) -> (Vec, Vec) { + LINKED.with_borrow(|l| match l { + Some(l) => { + let of = |els: &[SigElement], names: &[(String, u32)]| { + els.iter() + .map(|e| e.kind == 0 && names.iter().any(|(n, i)| n.eq_ignore_ascii_case(&e.name) && *i == e.index)) + .collect::>() + }; + (of(inputs, &l.inputs), of(outputs, &l.outputs)) + } + None => (Vec::new(), Vec::new()), + }) +} + +/// The translations of the mesh program `ms` (container `ms_container`) and the pixel program +/// `ps` (container `ps_container`) for one host pipeline, when `ms`'s outputs pass D3D12's 32 +/// KiB as translated alone: the mesh program without the outputs the pixel program does not +/// read, the pixel program without the inputs it does not read (see the module notes). +/// +/// `None` (make the pipeline of `ms` and `ps` as they are) when `ms` fits, when the pixel +/// program reads every output `ms` has, when the linked mesh program still does not fit, or +/// when a linked translation binds anything differently from its shared one (the pipeline's +/// root signature is made from the shared ones). +pub fn link_mesh( + ms_container: &[u8], + ms: &HostShader, + ps_container: &[u8], + ps: &HostShader, +) -> Result, ShaderError> { + if ms.stage != HwStage::Ms || ps.stage != HwStage::Ps || mesh_fits(&ms.dxil)? { + return Ok(None); + } + let named = |e: &Element| (e.name.clone(), e.index); + let inputs = elements(&ps.dxil, FourCC::ISG1)?; + let read = |e: &Element| { + inputs + .iter() + .any(|i| i.arbitrary() && i.used != 0 && i.name.eq_ignore_ascii_case(&e.name) && i.index == e.index) + }; + let outputs: Vec<(String, u32)> = elements(&ms.dxil, FourCC::OSG1)? + .iter() + .filter(|e| e.arbitrary() && !read(e)) + .map(named) + .collect(); + if outputs.is_empty() { + return Ok(None); + } + let unread: Vec<(String, u32)> = inputs.iter().filter(|i| i.arbitrary() && i.used == 0).map(named).collect(); + let linked_ms = with_linked( + Linked { + inputs: Vec::new(), + outputs, + }, + || translate(ms_container), + )?; + let linked_ps = if unread.is_empty() { + ps.clone() + } else { + with_linked( + Linked { + inputs: unread, + outputs: Vec::new(), + }, + || translate(ps_container), + )? + }; + let same = |a: &HostShader, b: &HostShader| HostShader { dxil: Vec::new(), ..a.clone() } == HostShader { dxil: Vec::new(), ..b.clone() }; + if !mesh_fits(&linked_ms.dxil)? || !same(ms, &linked_ms) || !same(ps, &linked_ps) { + return Ok(None); + } + Ok(Some((linked_ms, linked_ps))) +} + +/// Whether an emitted mesh program's outputs fit D3D12's 32 KiB (a program of another stage +/// fits). +pub fn mesh_fits(dxil: &[u8]) -> Result { + let c = Container::parse(dxil)?; + let Some(psv) = c.part(FourCC::PSV0) else { + return Ok(true); + }; + // runtime info (its size first): shader kind at byte 24, mesh maxima at bytes 12 and 14 + let info = psv.data.get(4..).ok_or(ShaderError::Malformed("truncated"))?; + if info.get(24) != Some(&13) { + return Ok(true); + } + let half = |at: usize| info.get(at..at + 2).map_or(0, |b| u32::from(u16::from_le_bytes([b[0], b[1]]))); + let declared = |fourcc| -> Result, ShaderError> { + Ok(elements(dxil, fourcc)? + .into_iter() + .map(|e| SigElement { + name: e.name, + index: e.index, + kind: 0, + comp: 0, + interp: 0, + row: None, + col: 0, + cols: e.mask.count_ones() as u8, + usage: 0, + half: false, + }) + .collect()) + }; + let bytes = mesh_output_bytes(&declared(FourCC::OSG1)?, &declared(FourCC::PSG1)?, half(12), half(14)); + Ok(bytes <= MESH_OUTPUT_LIMIT) +} + +/// A row of an emitted signature part (`container::signature`). +struct Element { + name: String, + index: u32, + /// The system value (0: an arbitrary semantic). + sv: u32, + mask: u8, + /// Inputs: the components read. + used: u8, +} + +impl Element { + fn arbitrary(&self) -> bool { + self.sv == 0 + } +} + +fn elements(dxil: &[u8], fourcc: FourCC) -> Result, ShaderError> { + let c = Container::parse(dxil)?; + let Some(part) = c.part(fourcc) else { + return Ok(Vec::new()); + }; + let part = part.data; + let count = u32_at(part, 0)? as usize; + let base = u32_at(part, 4)? as usize; + (0..count) + .map(|i| { + let at = base + 32 * i; + let name_at = u32_at(part, at + 4)? as usize; + let name = part + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let bytes = part.get(at + 24..at + 26).ok_or(ShaderError::Malformed("truncated"))?; + Ok(Element { + name: String::from_utf8_lossy(name).into_owned(), + index: u32_at(part, at + 8)?, + sv: u32_at(part, at + 12)?, + mask: bytes[0], + used: bytes[1], + }) + }) + .collect() +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 3d764ab18a..62339cfc88 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -16,7 +16,7 @@ use crate::ShaderError; use crate::gfx10::{Dpp, Fields, NULL, Operand}; use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; -use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage}; +use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source}; use crate::structure::{Atom, Bool, LaneExit, Structured}; @@ -32,6 +32,16 @@ mod packed_mask; #[path = "typed_views.rs"] mod typed_views; +/// Descriptors whose dwords the code reads as numbers (`descriptor_data`), a child module so it +/// shares the emitter's state. +#[path = "descriptor_data.rs"] +mod descriptor_data; + +/// 64-bit floats (the water volumetrics' wave sums of doubles, taken back as floats), a child +/// module so it shares the emitter's state. +#[path = "float64.rs"] +mod float64; + type Why = &'static str; /// How an interpolation evaluates an input channel. @@ -261,6 +271,9 @@ struct Lower<'a> { console_lanes: bool, /// Mesh: the thread index in the group (made in the entry block). flat: Option, + /// 64-bit float wave sums made (their two dwords), by the terms' dwords, mask and the + /// block made in: a section's result asks for each dword on its own. + sums64: HashMap<(Value, Value, Value, usize), [V; 2]>, /// Mesh: IR blocks whose `s_barrier` is left out. no_barrier: HashSet, /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane @@ -330,8 +343,46 @@ struct Lower<'a> { /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by /// IR block, and its incoming (value, DXIL block) pairs. counters: HashMap)>, + /// The program tests rays against tree nodes (`image_bvh*`): its loops + /// are cut at [`TRACE_LOOP_LIMIT`]. + traces: bool, /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. abort: Option, + /// The paired form ([`with_paired_lanes`]): what the lowering keeps per lane for the other + /// console lane of this thread, and whether the lane being lowered is the upper one (its + /// console lane the host lane plus 32). + twin: Option>, + upper: bool, + /// The paired form: whether the last LDS access of the IR block being lowered wrote (none + /// at its start), for the fences between accesses ([`Self::paired_inst`]). + lds_last: Option, + /// The paired form: scalars each lane has its own of (a waterfall loop's first-lane reads + /// and what is computed from them), on which no branch takes both lanes of a thread. + lane_scalars: HashSet, + /// Linked for one pipeline ([`super::link`]): per input and output element, whether it + /// is left out (empty when not linking). + drop_in: Vec, + drop_out: Vec, +} + +/// What the lowering keeps per console lane, for the paired form ([`with_paired_lanes`]): each +/// host thread runs two lanes of one console wave, and what a lane runs is lowered once for +/// each with this state exchanged between them ([`Lower::swap_lanes`]): the values (scalar ones +/// too, the same in both), the lane booleans and their joins, the handles of descriptors a lane +/// may have its own of, the phis still to fill. +#[derive(Default)] +struct LaneState { + vals: HashMap, + floats: HashMap, + bools: HashMap<(usize, Bool), V>, + lane_bits: HashMap, + lane_fail: HashMap, + mask_phis: HashMap, + pending_masks: Vec<(V, usize, usize)>, + data_phis: Vec<(V, usize, usize)>, + handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, + strides: HashMap<(usize, Site, u8), V>, + clane: Option, } /// Iterations after which a loop is left (per entry into it), unless @@ -343,6 +394,18 @@ struct Lower<'a> { // shortcut: a genuine loop of more iterations than this is cut short too. pub(super) const LOOP_LIMIT: u32 = 1 << 20; +/// Iterations after which a loop of a program that tests rays against tree +/// nodes is left, unless [`super::loop_limit`] names a limit for all. +/// +/// A ray's walk of a well-formed tree visits some hundreds of nodes at +/// most. The title's shadow-mask rays ran to the compute limit of 4,096: the +/// trees of moving objects are built by the title's builder, which is off, +/// so a walk into one follows whatever its memory holds. At 4,096 the +/// shadow mask took 11.7 ms of the card a frame, at 1,024 2.4 ms (timing +/// runs of the opening of the gameplay, RTX 5090); a ray stopped either way +/// leaves the program as killed, as before. +pub(super) const TRACE_LOOP_LIMIT: u32 = 1 << 10; + /// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar /// compares, bit tests) are ballots of the lanes' booleans, taken where the /// mask is written: structurisation's `active` masks hold only lanes that @@ -369,6 +432,9 @@ pub(super) const LANE_MASK: Why = "a lane mask read as data"; /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that /// run that block are not all of the wave. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; +/// A descriptor joined from the ways into a block, where one of them brings what a heap index +/// cannot stand for (an immediate sampler, say), or comes from later in the program. +pub(super) const CHOSEN: Why = "a descriptor chosen by control flow"; /// Instructions that read a lane mask (not EXEC implicitly, not a lane's /// bit) as a number. @@ -645,318 +711,36 @@ fn scalar_built(p: &Program, st: &Structured, all: &[bool]) -> (HashSet, (built, guarded) } -/// What a register value holds, for [`wave_local`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Wave { - /// Nothing that depends on how the threads are divided into waves. - Plain, - /// The number of the wave's first lane in a mask (`s_ff1`). - First, - /// A reduction over the wave's lanes: a count, a sum, a minimum... - Total(super::wave::Op), - /// A count or sum over the lanes below this one. - Prefix, - /// Derived from what a first-lane atomic returned: the slots the wave reserved. - Base, - /// A mix the idiom does not make. - Mixed, -} - -/// Whether a console wave64 program may run with each host wave as a wave of its own -/// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses -/// them, which does not care how the threads are divided into waves. A first-lane number only -/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; -/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. -/// Anything else done with them takes one wave to be the whole thread group (a tile's result, -/// say) and is refused, with the offset and what was found. -/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections -/// are stopped by the lowering itself. -// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this -// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is -// the only mix of old and new lanes that is looked at. -pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { - use super::wave::{Op, Shape}; - const FIRST: Why = "a wave's first-lane number used as data"; - const TOTAL: Why = "a count or sum over the wave used as data"; - const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; - const MIXED: Why = "a value that depends on the wave on some paths only"; - const EFFECT: Why = "a write by the wave's first lane other than its reservation"; - fn of(kind: &HashMap, v: Option) -> Wave { - v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) - } - fn put(kind: &mut HashMap, v: Value, k: Wave) { - if k == Wave::Plain { - kind.remove(&v); - } else { - kind.insert(v, k); - } +/// The paired form: scalar values each console lane has its own of in the lowering, a waterfall +/// loop's first-lane reads (the lane's own dword, `resource::Waterfall`) and what scalar code +/// and joins make of them. +fn lane_scalars(p: &Program, res: &Resources) -> HashSet { + let mut own: HashSet = res.waterfall.reads.iter().copied().collect(); + if own.is_empty() { + return own; } - let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); - let why = |k: Wave| match k { - Wave::First => FIRST, - Wave::Total(_) => TOTAL, - Wave::Prefix => PREFIX, - _ => MIXED, - }; - // a mask (by its low dword) under which only a wave's first lane runs - let first_mask = |firsts: &HashSet, m: Option| { - m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { - st.bools - .support(b) - .iter() - .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) - }) - }; - // One instruction outside a section: the kind of what it writes, and whether it is a - // first lane's reservation. - let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { - let name = inst.name(); - let val = |op: &Operand| match *op { - Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), - Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), - _ => None, - }; - let ops: Vec = match &inst.fields { - Fields::Valu(v) => v.src.clone(), - Fields::Sop { dst, src, .. } => { - let mut o = src.clone(); - if matches!(name, "s_addk_i32" | "s_mulk_i32") { - o.extend(dst.iter().copied()); - } - o - } - Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { - data.iter().copied().collect() - } - _ => Vec::new(), - }; - let kinds: Vec = ops.iter().map(|o| of(kind, val(o))).collect(); - // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide - // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it - // writes, which only the lanes outside EXEC keep. - let named: Vec = ops.iter().filter_map(&val).collect(); - for &(r, v) in &inst.reads { - let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); - if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { - continue; - } - let k = of(kind, Some(v)); - if wild(k) { - return Err(why(k)); - } - } - let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); - let sum = |k: Wave| k == Wave::Total(Op::AddU); - let is_mask = |o: &Operand| { - val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) - }; - let mut reserved = false; - let out = match (name, &kinds[..]) { - ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, - ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { - Wave::Total(Op::AddU) - } - // bits of a mask below the lane; with -1 for the mask, the lane's number - ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { - match (matches!(ops[0], Operand::Scalar { .. }), *b) { - (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, - (false, Wave::Plain | Wave::Base) => Wave::Plain, - (_, k) => return Err(why(k)), - } - } - // nothing wave-dependent goes in; what derives from a reserved base stays marked - _ if !kinds.iter().any(|&k| wild(k)) => { - let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); - if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } - } - ("v_mov_b32" | "s_mov_b32", [k]) => *k, - ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { - // the lane whose own number is the first lane's - let lane = match (*a, *b) { - (Wave::First, k) if !wild(k) => &ops[1], - (k, Wave::First) if !wild(k) => &ops[0], - _ => return Err(why(w)), - }; - if !matches!(lane, Operand::Vector { .. }) { - return Err(FIRST); - } - let mask = match &inst.fields { - _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), - Fields::Valu(v) => match v.dst { - Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), - _ => None, - }, - _ => None, - }; - firsts.extend(mask); - Wave::Plain - } - ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { - (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, - (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, - (x, y) if sum(x) && sum(y) => x, - _ => return Err(why(w)), - }, - ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { - (Wave::Base, Wave::Prefix) => Wave::Base, - (Wave::Prefix, Wave::Plain) => Wave::Prefix, - (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, - _ => return Err(why(w)), - }, - ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { - (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, - _ => return Err(why(w)), - }, - ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) - if sum(*x) || *x == Wave::Prefix => - { - *x - } - ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { - if *c == Wave::Base { Wave::Base } else { Wave::Prefix } - } - // the reservation: the first lane adds its wave's total to a shared counter - (_, [Wave::Total(op)]) if name.contains("_atomic_") => { - let want = match op { - Op::AddU => "buffer_atomic_add", - Op::MinU => "buffer_atomic_umin", - Op::MaxU => "buffer_atomic_umax", - Op::MinI => "buffer_atomic_smin", - Op::MaxI => "buffer_atomic_smax", - Op::Or => "buffer_atomic_or", - Op::And => "buffer_atomic_and", - Op::Xor => "buffer_atomic_xor", - _ => "", - }; - if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { - return Err(TOTAL); - } - reserved = true; - Wave::Base - } - _ => return Err(why(w)), - }; - Ok((out, reserved)) - }; - let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); let order = crate::ir::reverse_postorder(&p.blocks); - let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + loop { + let before = own.len(); for &b in &order { let block = &p.blocks[b]; for phi in &block.phis { - let mut k = Wave::Plain; - for (n, &a) in phi.args.iter().enumerate() { - let x = of(kind, Some(a)); - k = match (k, x) { - _ if n == 0 => x, - (k, x) if k == x => k, - (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) - | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, - _ => Wave::Mixed, - }; + if !matches!(phi.reg, Reg::V(_)) && phi.args.iter().any(|a| own.contains(a)) { + own.insert(phi.value); } - put(kind, phi.value, k); } - for (i, inst) in block.insts.iter().enumerate() { - // inside a whole-wave section: what the simulation found each value to be - if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { - for &(_, w) in &inst.writes { - let k = match sec.shapes.get(&w) { - None => Wave::Mixed, - Some(&Shape::K(_)) => Wave::Plain, - Some(&Shape::Value(v)) => of(kind, Some(v)), - Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), - Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { - Wave::Plain | Wave::Base => Wave::Total(op), - // the first lane's own sum of a total is that total - Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), - _ => Wave::Mixed, - }, - Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { - Wave::Plain | Wave::Base => Wave::Prefix, - Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, - _ => Wave::Mixed, - }, - Some(_) => Wave::Mixed, - }; - put(kind, w, k); - } - continue; - } - let name = inst.name(); - if name.starts_with("s_cbranch") { - continue; // with the block's exit, below - } - let (k, reserved) = match step(inst, kind, firsts) { - Ok(r) => r, - Err(why) if check => return Err((inst.machine.offset, why)), - Err(_) => (Wave::Mixed, false), - }; - // the same test as `Lower::inst`'s `effect` - let effect = matches!(inst.fields, Fields::Exp { .. }) - || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") - || name.contains("store") - || name.contains("atomic") - || matches!(inst.fields, Fields::Ds { .. }) - && !(name.starts_with("ds_read") - || name.starts_with("ds_swizzle") - || name.contains("permute")); - if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { - return Err((inst.machine.offset, EFFECT)); - } - let guarded = st.guards[b][i].is_some(); - for &(r, w) in &inst.writes { - let mut kw = match r { - // "some lane is counted" keeps the count's kind; any other SCC is one bit of data - Reg::Scc if !name.starts_with("s_bcnt1") => { - if wild(k) { Wave::Mixed } else { Wave::Plain } - } - _ => k, - }; - // a guarded write leaves the old value in the lanes outside EXEC - if guarded - && matches!(r, Reg::V(_)) - && kw == Wave::Plain - && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) - { - kw = Wave::Mixed; - } - put(kind, w, kw); - } - } - // a branch on "some lane is counted": fine where the structure made it the lane's - // own bit (the mask is EXEC under a scalar condition) - if check - && let Some(last) = block.insts.last() - && last.name().starts_with("s_cbranch_scc") - && let Some(scc) = last.read(Reg::Scc) - && wild(of(kind, Some(scc))) - { - let own = matches!(st.exits[b], LaneExit::Branch { when, .. } - if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); - if !own { - return Err((last.machine.offset, TOTAL)); + for inst in &block.insts { + if matches!(inst.fields, Fields::Sop { .. } | Fields::Smem { .. }) + && inst.reads.iter().any(|r| own.contains(&r.1)) + { + own.extend(inst.writes.iter().map(|w| w.1)); } } } - Ok(()) - }; - let mut kind: HashMap = HashMap::new(); - let mut firsts: HashSet = HashSet::new(); - // to a fixpoint (values carried around loops), then once more to say what is wrong - let mut settled = false; - for _ in 0..16 { - let before = (kind.clone(), firsts.len()); - pass(&mut kind, &mut firsts, false)?; - if (&before.0, before.1) == (&kind, firsts.len()) { - settled = true; - break; + if own.len() == before { + return own; } } - if !settled { - return Err((0, MIXED)); - } - pass(&mut kind, &mut firsts, true) } /// The mode of a group barrier the translation adds (host waves meeting): @@ -1093,6 +877,31 @@ thread_local! { static LOCAL_WAVES: std::cell::Cell = const { std::cell::Cell::new(false) }; /// See [`with_local_waves_any`]. static LOCAL_ANY: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// See [`with_paired_lanes`]. + static PAIRED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with console wave64 compute programs on 32-lane hosts lowered in the paired form: +/// each console wave is one host wave of 32 lanes, and host lane n runs console lanes n and +/// n + 32. The group has half the console's threads; each thread runs what a lane does twice, +/// once for each of its lanes, in the order of the console's instructions, so the wave's lanes +/// stay together as on the console: what one writes to LDS, the next instruction of another +/// reads (a fence between the accesses keeps the host compiler from reordering them; no thread +/// waits for another). Cross-lane operations reach any of the 64 lanes through the host wave's +/// own operations on either half (lane n + 32 is lane n's upper half), and a lane mask is the +/// two ballots. The caller makes every per-lane branch one the wave takes together, as the +/// console does (`structure::structure_wide`): the wave goes where some lane has to, and EXEC +/// stays each lane's guard. So control flow is the same in every thread of a host wave, and +/// the program's barriers are reached as on the console. +// shortcut: D3D12 orders no groupshared accesses of two threads without a group barrier; the +// host is taken to run a wave's threads in step where they all go the same way (as for the +// console's 32-lane programs that share LDS within a wave), the fences only keeping its +// compiler from moving one thread's accesses past each other. +pub(super) fn with_paired_lanes(f: impl FnOnce() -> R) -> R { + let was = PAIRED.replace(true); + let r = f(); + PAIRED.set(was); + r } /// As [`with_local_waves`], with every other use of a lane mask as a number @@ -1160,6 +969,10 @@ fn own_bits_on() -> bool { *ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0")) } +/// The refusal of a first half of an interpolation whose result is read +/// as data ([`Lower::interp`]). +pub(super) const FIRST_HALF: &str = "the first half of an interpolation"; + /// What [`set_host_max_wave`] was told (0: nothing). pub fn host_max_wave() -> u32 { #[cfg(test)] @@ -1379,6 +1192,9 @@ impl<'a> Lower<'a> { let mut s = Shader::new(x.native.stage == HwStage::Ps); s.inputs = x.inputs.clone(); s.outputs = x.outputs.clone(); + // (the signatures stay whole while the program is lowered: rows of 16-bit values and + // the like are found by the elements around them; what is left out goes at the end) + let (drop_in, drop_out) = super::link::left_out(&x.inputs, &x.outputs); let insts = || p.blocks.iter().flat_map(|b| &b.insts); let writes_uavs = insts().any(|i| { matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) @@ -1394,7 +1210,25 @@ impl<'a> Lower<'a> { let mut exchange: Option<(u32, bool, Vec)> = None; // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter let mut halves: Option = None; - if let StageIo::Cs(cs) = x.native.io { + let paired = PAIRED.get() && x.native.wave64 && host_max_wave() == 32; + if let StageIo::Cs(cs) = x.native.io + && paired + { + // (`with_paired_lanes`) a host wave of 32 for each console wave of the group, its + // threads in a row; the caller has checked that the console's waves are full + let waves = cs.threads.iter().product::().div_ceil(64); + s.threads = Some([32 * waves, 1, 1]); + s.lds_dwords = cs.lds_bytes() / 4; + if waves > 1 { + // `wave_base`'s counter: a dword past the program's LDS, or the program's + // first where it takes all a host group has (32 KiB) + let slot = if s.lds_dwords < 8192 { s.lds_dwords } else { 0 }; + s.lds_dwords = s.lds_dwords.max(slot + 1); + halves = Some(slot); + } + console_lanes = true; + s.wave_size = Some(32); + } else if let StageIo::Cs(cs) = x.native.io { s.threads = Some(cs.threads); s.lds_dwords = cs.lds_bytes() / 4; // Code reading other lanes needs the console's wave size and @@ -1689,6 +1523,7 @@ impl<'a> Lower<'a> { halves, wave_base: None, flat: None, + sums64: HashMap::new(), no_barrier, fence_only, half_outputs: half_outputs(&x.native.io, &x.outputs), @@ -1717,7 +1552,65 @@ impl<'a> Lower<'a> { section_out: HashSet::new(), code_table: None, counters: HashMap::new(), + traces: p.blocks.iter().any(|b| b.insts.iter().any(|i| i.name().starts_with("image_bvh"))), abort: None, + twin: paired.then(Box::default), + upper: false, + lds_last: None, + lane_scalars: if paired { lane_scalars(p, x.res) } else { HashSet::new() }, + drop_in, + drop_out, + } + } + + /// Element `id` of the inputs (`input`) or the vertex outputs as the finished signature + /// numbers it, without those left out ([`super::link`]). + fn sig_id(&self, input: bool, id: usize) -> u32 { + let drop = if input { &self.drop_in } else { &self.drop_out }; + (id - drop.iter().take(id).filter(|&&d| d).count()) as u32 + } + + /// The paired form: makes the other console lane of this thread the one being lowered. + fn swap_lanes(&mut self) { + let Some(t) = self.twin.as_deref_mut() else { + return; + }; + std::mem::swap(&mut self.vals, &mut t.vals); + std::mem::swap(&mut self.floats, &mut t.floats); + std::mem::swap(&mut self.bools, &mut t.bools); + std::mem::swap(&mut self.lane_bits, &mut t.lane_bits); + std::mem::swap(&mut self.lane_fail, &mut t.lane_fail); + std::mem::swap(&mut self.mask_phis, &mut t.mask_phis); + std::mem::swap(&mut self.pending_masks, &mut t.pending_masks); + std::mem::swap(&mut self.data_phis, &mut t.data_phis); + std::mem::swap(&mut self.handles, &mut t.handles); + std::mem::swap(&mut self.strides, &mut t.strides); + std::mem::swap(&mut self.clane, &mut t.clane); + self.upper = !self.upper; + } + + /// The paired form: `f` for each console lane of this thread, the lower one first; the lane + /// being lowered stays the same. + fn both(&mut self, mut f: impl FnMut(&mut Self) -> Result) -> Result<[T; 2], Why> { + let was = self.upper; + if was { + self.swap_lanes(); + } + let lo = f(self); + self.swap_lanes(); + let hi = f(self); + if !was { + self.swap_lanes(); + } + Ok([lo?, hi?]) + } + + /// The paired form: `lo` as the lower lane's value of `v`, `hi` as the upper lane's. + fn put_lanes(&mut self, v: Value, lo: Val, hi: Val) { + let (mine, other) = if self.upper { (hi, lo) } else { (lo, hi) }; + self.vals.insert(v, mine); + if let Some(t) = self.twin.as_deref_mut() { + t.vals.insert(v, other); } } @@ -1934,6 +1827,29 @@ impl<'a> Lower<'a> { } } + /// [`Self::section_inst`] in the paired form: a value over the wave's lanes takes both + /// lanes of every thread ([`Self::paired_shape`]), a lane's own value each lane's. + fn paired_section_inst(&mut self, b: usize, i: usize, start: usize) { + use super::wave::Shape; + const UNKNOWN: Why = "a whole-wave section step the simulation does not follow"; + let inst = &self.x.p.blocks[b].insts[i]; + for &(_, w) in &inst.writes { + let shape = match self.section_out.contains(&w) { + true => self.sections[&b][&start].shapes.get(&w).copied(), + false => None, + }; + let made = match shape { + None => Err(UNKNOWN), + Some(sh @ (Shape::Active(..) | Shape::Prefix(..) | Shape::Sum64 { .. })) => self.paired_shape(sh), + Some(sh) => self.both(|l| l.shape(sh, false)), + }; + match made { + Ok([lo, hi]) => self.put_lanes(w, Val::I32(lo), Val::I32(hi)), + Err(why) => self.put_lanes(w, Val::Missing(why), Val::Missing(why)), + } + } + } + /// A value a whole-wave section leaves, as DXIL wave operations over the /// host's active lanes: the console's result with console lanes; on /// another wave size, what the HLSL wave operation the console compiler @@ -1947,10 +1863,10 @@ impl<'a> Lower<'a> { let (op, src, mask, ident, prefix) = match shape { Shape::K(k) => return Ok(self.s.m.i32(k)), Shape::Value(v) => return self.i32_of(v), - Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), - Shape::ActiveF64(lo, hi, mask, high) => { - return self.active_f64_sum(lo, hi, mask, high); + Shape::Sum64 { high, lo, hi, mask } => { + return self.sum64(lo, hi, mask).map(|d| d[usize::from(high)]); } + Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), Shape::Masked(src, mask, ident) => { let c = self.cur; let &m = self @@ -2005,53 +1921,7 @@ impl<'a> Lower<'a> { let arg = if float { self.as_float(x) } else { x }; let ty = if float { f32t } else { i32t }; let sfx = if float { "f32" } else { "i32" }; - let r = match (op, prefix) { - (Op::AddU | Op::AddF, Some(inclusive)) => { - let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); - let r = self.s.op( - c, - &format!("wavePrefixOp.{sfx}"), - Attr::NoUnwind, - ty, - 121, - &[arg, k0, k1], - ); - if inclusive { - self.s.m.bin(c, Bin::Add, r, arg) - } else { - r - } - } - (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), - (Op::Or | Op::And | Op::Xor, None) => { - let k = self.s.m.i8(match op { - Op::And => 0, - Op::Or => 1, - _ => 2, - }); - self.s - .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) - } - (_, None) => { - let (code, unsigned) = match op { - Op::AddU => (0, 1), - Op::AddF => (0, 0), - Op::MinU => (2, 1), - Op::MaxU => (3, 1), - Op::MinI | Op::MinF => (2, 0), - _ => (3, 0), - }; - let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); - self.s.op( - c, - &format!("waveActiveOp.{sfx}"), - Attr::NoUnwind, - ty, - 119, - &[arg, k, u], - ) - } - }; + let r = self.host_wave_op(op, arg, float, prefix)?; // two host waves of 32 hold the console's 64 lanes: their results combine let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { // this host wave's own result (and prefix): each wave on its own, or a group of @@ -2090,24 +1960,7 @@ impl<'a> Lower<'a> { let c = self.cur; let (lo, hi) = self.exchange_halves(c, rb); let (lo, hi) = (back(self, lo), back(self, hi)); - match op { - Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), - Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), - Op::And => self.s.m.bin(c, Bin::And, lo, hi), - Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), - _ => { - // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 - let code = match op { - Op::MaxF => 35, - Op::MinF => 36, - Op::MinU => 40, - Op::MaxU => 39, - Op::MinI => 38, - _ => 37, - }; - self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) - } - } + self.join_halves(op, lo, hi, float) } } } else { @@ -2116,72 +1969,145 @@ impl<'a> Lower<'a> { Ok(if float { self.as_int(r) } else { r }) } - /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), - /// returning the low (`!high`) or high (`high`) 32-bit word. - fn active_f64_sum( + /// `op` of `arg` (`float`: a float, else bits) over this host wave's active lanes; with + /// `prefix` the sum over the lanes below each lane (`Some(true)`: and the lane's own). + fn host_wave_op( &mut self, - lo: Value, - hi: Value, - mask: Value, - high: bool, + op: super::wave::Op, + arg: V, + float: bool, + prefix: Option, ) -> Result { - if self.mask_data == MaskData::None { - return Err("a wave reduction in a mesh shader"); + use super::wave::Op; + let c = self.cur; + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let ty = if float { f32t } else { i32t }; + let sfx = if float { "f32" } else { "i32" }; + Ok(match (op, prefix) { + (Op::AddU | Op::AddF, Some(inclusive)) => { + let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); + let r = self.s.op( + c, + &format!("wavePrefixOp.{sfx}"), + Attr::NoUnwind, + ty, + 121, + &[arg, k0, k1], + ); + if inclusive { + self.s.m.bin(c, Bin::Add, r, arg) + } else { + r + } + } + (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), + (Op::Or | Op::And | Op::Xor, None) => { + let k = self.s.m.i8(match op { + Op::And => 0, + Op::Or => 1, + _ => 2, + }); + self.s + .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) + } + (_, None) => { + let (code, unsigned) = match op { + Op::AddU => (0, 1), + Op::AddF => (0, 0), + Op::MinU => (2, 1), + Op::MaxU => (3, 1), + Op::MinI | Op::MinF => (2, 0), + _ => (3, 0), + }; + let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); + self.s.op( + c, + &format!("waveActiveOp.{sfx}"), + Attr::NoUnwind, + ty, + 119, + &[arg, k, u], + ) + } + }) + } + + /// The results of a reduction by `op` (`float`: floats, else bits) over the two halves of + /// a console wave, joined into the wave's. + fn join_halves(&mut self, op: super::wave::Op, lo: V, hi: V, float: bool) -> V { + use super::wave::Op; + let c = self.cur; + let ty = if float { self.s.t.f32 } else { self.s.t.i32 }; + let sfx = if float { "f32" } else { "i32" }; + match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), + Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), + Op::And => self.s.m.bin(c, Bin::And, lo, hi), + Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), + _ => { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + let code = match op { + Op::MaxF => 35, + Op::MinF => 36, + Op::MinU => 40, + Op::MaxU => 39, + Op::MinI => 38, + _ => 37, + }; + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + } + } + } + + /// [`Self::shape`] of a reduction or prefix in the paired form, over the console wave's 64 + /// lanes: for the lower and the upper lane of this thread. Each half is a host wave + /// operation over the lower or the upper lanes, and the halves join as two host waves' do + /// in `shape`: a reduction of the two results, a prefix of the upper lanes after the lower + /// lanes' total. + fn paired_shape(&mut self, shape: super::wave::Shape) -> Result<[V; 2], Why> { + use super::wave::{Op, Shape}; + if let Shape::Sum64 { high, lo, hi, mask } = shape { + return self.paired_sum64(high, lo, hi, mask); } + let (op, src, mask, ident, prefix) = match shape { + Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::Prefix(op, src, mask, ident, inclusive) => (op, src, mask, ident, Some(inclusive)), + _ => return Err("a whole-wave section value of another shape"), + }; + let &m = self.x.st.masks.get(&mask).ok_or("a wave reduction's untracked mask")?; let c = self.cur; - let &m = self - .x - .st - .masks - .get(&mask) - .ok_or("a wave reduction's untracked mask")?; - let on = self.boolean(m, c)?; - let lo = self.i32_of(lo)?; - let hi = self.i32_of(hi)?; - let z = self.s.m.i32(0); - let lo = self.s.m.select(c, on, lo, z); - let hi = self.s.m.select(c, on, hi, z); - self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; - let f64t = self.s.m.double(); - let i32t = self.s.t.i32; - let split_ty = self - .s - .m - .named_struct("dx.types.splitdouble", vec![i32t, i32t]); - let arg = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); - let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); - let sum = self - .s - .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); - let mut r_lo = self.s.m.extract(c, split, 0); - let mut r_hi = self.s.m.extract(c, split, 1); - if self.exchange.is_some() { - if !self.all_lanes(self.cur_ir) { - need(self.cur_ir); - return Err("a wave reduction where not every lane runs"); + let [lo, hi] = self.both(|l| { + let on = l.boolean(m, c)?; + let x = l.i32_of(src)?; + let id = l.s.m.i32(ident); + Ok(l.s.m.select(c, on, x, id)) + })?; + self.s.flags |= flags::WAVE_OPS; + if op == Op::AddH { + if prefix.is_some() { + return Err("a wave prefix of an operation other than a sum"); } - let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); - let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); - let c = self.cur; - let d0 = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); - let d1 = self - .s - .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); - let total = self.s.m.bin(c, Bin::Add, d0, d1); - let split = self - .s - .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); - r_lo = self.s.m.extract(c, split, 0); - r_hi = self.s.m.extract(c, split, 1); + let (lo, hi) = (self.half_tree(lo, 5), self.half_tree(hi, 5)); + let r = self.join_half_sums(lo, hi); + return Ok([r, r]); } - Ok(if high { r_hi } else { r_lo }) + let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); + let (lo, hi) = if float { (self.as_float(lo), self.as_float(hi)) } else { (lo, hi) }; + let r = match prefix { + Some(inclusive) => { + let mine = self.host_wave_op(op, lo, float, Some(inclusive))?; + let theirs = self.host_wave_op(op, hi, float, Some(inclusive))?; + let below = self.host_wave_op(op, lo, float, None)?; + [mine, self.s.m.bin(c, Bin::Add, theirs, below)] + } + None => { + let lo = self.host_wave_op(op, lo, float, None)?; + let hi = self.host_wave_op(op, hi, float, None)?; + let r = self.join_halves(op, lo, hi, float); + [r, r] + } + }; + Ok(if float { r.map(|x| self.as_int(x)) } else { r }) } /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's @@ -2259,11 +2185,24 @@ impl<'a> Lower<'a> { // block only the lanes inside the matrix reach.) return Ok(self.half_sum_here(x)); } + let c = self.cur; + let mine = self.half_tree(x, if halves { 5 } else { 6 }); + if !halves { + return Ok(mine); + } + let (lo, hi) = self.exchange_halves(c, mine); + Ok(self.join_half_sums(lo, hi)) + } + + /// The first `steps` levels of [`Self::half_sum`]'s tree over this host wave: its lanes' + /// sum when they are all of its waves' lanes (6 steps for 64, 5 for 32), in the low half; + /// the high half lane 0's. + fn half_tree(&mut self, x: V, steps: u32) -> V { let c = self.cur; let i32t = self.s.t.i32; let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let mut sum = x; - for step in 0..if halves { 5 } else { 6 } { + for step in 0..steps { let bit = self.s.m.i32(1 << step); let partner = self.s.m.bin(c, Bin::Xor, lane, bit); let theirs = self.read_lane(sum, partner); @@ -2273,16 +2212,18 @@ impl<'a> Lower<'a> { let first = self.read_lane(x, zero); let first = self.s.m.bin(c, Bin::And, first, high); let sum = self.s.m.bin(c, Bin::And, sum, low); - let mine = self.s.m.bin(c, Bin::Or, first, sum); - if !halves { - return Ok(mine); - } - let (lo, hi) = self.exchange_halves(c, mine); + self.s.m.bin(c, Bin::Or, first, sum) + } + + /// The last addition of [`Self::half_sum`]'s tree: the sums of a console wave's two halves + /// (from [`Self::half_tree`]), with the high half of the lower one's (lane 0's). + fn join_half_sums(&mut self, lo: V, hi: V) -> V { let c = self.cur; let total = self.add_halves(lo, hi); + let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF)); let total = self.s.m.bin(c, Bin::And, total, low); let first = self.s.m.bin(c, Bin::And, lo, high); - Ok(self.s.m.bin(c, Bin::Or, first, total)) + self.s.m.bin(c, Bin::Or, first, total) } fn run(mut self, partial: bool) -> Result { @@ -2335,6 +2276,13 @@ impl<'a> Lower<'a> { self.cur = self.s.entry; self.find_sections(); self.inputs()?; + if self.twin.is_some() { + // (the upper lanes' inputs: their own thread ids) + self.swap_lanes(); + let r = self.inputs(); + self.swap_lanes(); + r?; + } if let Some(mesh) = self.s.mesh { self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; self.block[order[0]] = Some(self.cur); @@ -2349,32 +2297,30 @@ impl<'a> Lower<'a> { .filter(|&q| self.block[q].is_some()) .collect(); self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q)); - for (i, phi) in p.blocks[b].phis.iter().enumerate() { - let val = match phi.reg { - Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), - _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), - Reg::Scc => { - let v = self.s.m.phi(self.cur, self.s.t.i1); - self.data_phis.push((v, b, i)); - Val::Bit(v) - } - _ => { - let v = self.s.m.phi(self.cur, self.s.t.i32); - self.data_phis.push((v, b, i)); - Val::I32(v) - } - }; - self.vals.insert(phi.value, val); + self.block_phis(b); + if self.twin.is_some() { + self.swap_lanes(); + self.block_phis(b); + self.swap_lanes(); } if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) { self.lds_meeting(); } + self.lds_last = None; let mut i = 0; while i < p.blocks[b].insts.len() { - self.inst(b, i)?; + if self.twin.is_some() { + self.paired_inst(b, i)?; + } else { + self.inst(b, i)?; + } if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) { for j in i + 1..end { - self.section_inst(b, j, i); + if self.twin.is_some() { + self.paired_section_inst(b, j, i); + } else { + self.section_inst(b, j, i); + } } i = end; continue; @@ -2389,6 +2335,35 @@ impl<'a> Lower<'a> { self.exit(b)?; } self.fill_phis()?; + // (the paired form: the other lane's joins too; filling one lane's can ask for lane + // masks joined in either lane, until neither has any left) + while self.twin.is_some() { + self.swap_lanes(); + let r = self.fill_phis(); + self.swap_lanes(); + r?; + let left = self.twin.as_deref().is_some_and(|t| !t.pending_masks.is_empty()); + if self.pending_masks.is_empty() && !left { + break; + } + self.fill_phis()?; + } + // A linked stage's signatures without what it leaves out; an input left out must not + // have been read. + if !self.drop_in.is_empty() || !self.drop_out.is_empty() { + if self.s.inputs.iter().zip(&self.drop_in).any(|(e, &d)| d && e.usage != 0) { + return Err(unsupported(0, "an input left out of a linked pipeline read")); + } + let keep = |els: &mut Vec, drop: &[bool]| { + let mut d = drop.iter(); + els.retain(|_| !d.next().copied().unwrap_or(false)); + }; + keep(&mut self.s.inputs, &self.drop_in); + keep(&mut self.s.outputs, &self.drop_out); + } + // (the reads have given the pixel inputs their modes) + super::container::one_mode_per_register(&mut self.s.inputs, self.s.pixel); + super::container::one_mode_per_register(&mut self.s.outputs, false); let user_data = self.user_reads.values().copied().collect(); self.s.samplers = self.samplers.len() as u32; let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); @@ -2414,6 +2389,29 @@ impl<'a> Lower<'a> { }) } + /// The joins at the start of IR block `b`, filled once every block is lowered + /// ([`Self::fill_phis`]). + fn block_phis(&mut self, b: usize) { + let p = self.x.p; + for (i, phi) in p.blocks[b].phis.iter().enumerate() { + let val = match phi.reg { + Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), + _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), + Reg::Scc => { + let v = self.s.m.phi(self.cur, self.s.t.i1); + self.data_phis.push((v, b, i)); + Val::Bit(v) + } + _ => { + let v = self.s.m.phi(self.cur, self.s.t.i32); + self.data_phis.push((v, b, i)); + Val::I32(v) + } + }; + self.vals.insert(phi.value, val); + } + } + fn exported_out(&self, b: usize) -> bool { self.exported[b] || self.has_done_export(b) } @@ -2610,8 +2608,9 @@ impl<'a> Lower<'a> { ".f32" }; let entry = self.s.entry; + let sig = self.sig_id(true, id); let args = [ - self.s.m.i32(id as u32), + self.s.m.i32(sig), self.s.m.i32(0), self.s.m.i8(col), self.s.m.undef(self.s.t.i32), @@ -3345,9 +3344,11 @@ impl<'a> Lower<'a> { let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; // A mask that holds lanes outside EXEC where it is written (the complement of one, // say) is the ballot of the lanes that are there: all of them, where two exchanging - // host waves know every lane runs that block. + // host waves know every lane runs that block, and in the paired form, whose host wave + // runs every block with all its lanes. let made = self.def_block.get(&lo).copied(); - let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + let whole = self.twin.is_some() + || self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); if !self.x.st.active.contains(&lo) && !whole { if let Some(source) = self.copied_mask_word(v) { return self.i32_of(source); @@ -3372,9 +3373,14 @@ impl<'a> Lower<'a> { if !self.balloting.insert(lo) { return Err("a lane mask whose lanes depend on its own value"); } - let bit = self.boolean(m, at); + // (the paired form: the upper lanes' bits too, lanes 32-63) + let bits = if self.twin.is_some() { + self.both(|l| l.boolean(m, at)).map(|[a, b]| (a, Some(b))) + } else { + self.boolean(m, at).map(|a| (a, None)) + }; self.balloting.remove(&lo); - let bit = bit?; + let (bit, upper) = bits?; let i32t = self.s.t.i32; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let r = self @@ -3382,7 +3388,10 @@ impl<'a> Lower<'a> { .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); self.s.flags |= flags::WAVE_OPS; let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); - if self.exchange.is_some() { + if let Some(upper) = upper { + let r = self.s.op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[upper]); + xy.1 = self.s.m.extract(at, r, 0); + } else if self.exchange.is_some() { // a host wave's ballot is its half's 32 bits: the halves exchange them let b = self.def_block.get(&lo).copied(); if self.local { @@ -3878,10 +3887,11 @@ impl<'a> Lower<'a> { } /// A console wave64 program in host waves of 32: the first console thread of this host wave - /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's - /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread - /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it - /// found. Branch-free, in the entry block, which every thread runs. + /// (0, 32, 64, ...; in the paired form 0, 64, 128, ...). A GPU need not give a host wave + /// consecutive thread indices (NVIDIA's 8 x 8 groups), so each wave takes the next 32 (64) + /// from an LDS counter instead: every thread zeroes it, the group meets, each wave's first + /// lane adds 32 (64) and the wave takes what it found. Branch-free, in the entry block, + /// which every thread runs. fn wave_base(&mut self) -> Option { let slot = self.halves?; if let Some(v) = self.wave_base { @@ -3896,21 +3906,36 @@ impl<'a> Lower<'a> { self.group_sync(e); let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let first = self.s.m.cmp(e, pred::EQ, lane, zero); - let k32 = self.s.m.i32(32); - let add = self.s.m.select(e, first, k32, zero); + let step = self.s.m.i32(if self.twin.is_some() { 64 } else { 32 }); + let add = self.s.m.select(e, first, step, zero); let ptr = self.s.m.element(e, lds, k); let old = self.s.m.atomic(e, Rmw::Add, ptr, add); let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); self.s.flags |= flags::WAVE_OPS; + // a counter in the program's own LDS (the paired form's, when it has no dword to + // spare): every wave has its base before any thread runs the program + if matches!(self.x.native.io, StageIo::Cs(cs) if slot < cs.lds_bytes() / 4) { + self.group_sync(e); + } self.wave_base = Some(base); Some(base) } /// The console thread index of this thread in the group: `wave_base` plus the host lane - /// (host waves of 32), else the wave's first thread index rounded down plus the lane. + /// (host waves of 32), else the wave's first thread index rounded down plus the lane. In + /// the paired form, of the lane being lowered: its console wave's first thread, plus the + /// host lane, plus 32 for the upper lane. fn console_thread(&mut self) -> V { let (e, i32t) = (self.s.entry, self.s.t.i32); let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + if self.twin.is_some() { + let half = self.s.m.i32(if self.upper { 32 } else { 0 }); + let t = self.s.m.bin(e, Bin::Add, lane, half); + return match self.wave_base() { + Some(base) => self.s.m.bin(e, Bin::Add, base, t), + None => t, + }; + } if let Some(base) = self.wave_base() { return self.s.m.bin(e, Bin::Add, base, lane); } @@ -3923,9 +3948,10 @@ impl<'a> Lower<'a> { } /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host - /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane. + /// wave holds a 32-aligned run of console lanes (in the paired form, the lane being + /// lowered). Without `exchange` or the paired form: the host lane. fn console_lane(&mut self) -> V { - if self.exchange.is_none() { + if self.exchange.is_none() && self.twin.is_none() { return self.lane_index(); } if let Some(v) = self.clane { @@ -4017,19 +4043,28 @@ impl<'a> Lower<'a> { /// console wave has its bit of the result, asked where the operation stands. The lanes /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with /// the console's waves the host wave's answer is the console's; two host waves of 32 - /// exchange theirs, which needs every lane there. + /// exchange theirs, which needs every lane there. In the paired form the host wave asks + /// both lanes of each thread. fn scc_some(&mut self, scc: Value) -> Result { let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?; + let made = self.def_block.get(&scc).copied(); + let at = |l: &Self| match made { + None => Ok(l.s.entry), + Some(b) if b == l.cur_ir => Ok(l.cur), + Some(b) => l.tail[b].ok_or("a lane mask written after its use"), + }; + if self.twin.is_some() { + let at = at(self)?; + let [lo, hi] = self.both(|l| l.boolean(m, at))?; + let either = self.s.m.bin(at, Bin::Or, lo, hi); + self.s.flags |= flags::WAVE_OPS; + return Ok(self.s.op(at, "waveAnyTrue", Attr::NoUnwind, self.s.t.i1, 113, &[either])); + } // (not for a console wave cut into host waves that do not exchange) if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() { return Err(LANE_MASK); } - let made = self.def_block.get(&scc).copied(); - let at = match made { - None => self.s.entry, - Some(b) if b == self.cur_ir => self.cur, - Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, - }; + let at = at(self)?; let bit = self.boolean(m, at)?; let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); @@ -4051,6 +4086,18 @@ impl<'a> Lower<'a> { fn wave_wide(&mut self, b: usize, when: Bool) -> Result { const WHY: Why = "a wave-wide branch where not every lane runs"; let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; + if self.twin.is_some() { + // The paired form: the host wave is the console's, each thread with two of its + // lanes; every lane is here (control flow is the wave's), and a lane outside EXEC + // says what it says on the console (no set bit for "some lane", no objection to + // "every lane"). + let c = self.cur; + let [lo, hi] = self.both(|l| l.boolean(when, c))?; + let pair = self.s.m.bin(c, if any { Bin::Or } else { Bin::And }, lo, hi); + self.s.flags |= flags::WAVE_OPS; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + return Ok(self.s.op(c, name, Attr::NoUnwind, self.s.t.i1, code, &[pair])); + } if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { // The host's waves are the console's: the wave's own answer. The lanes that are // elsewhere have no bit set, as on the console, so "some lane" needs no one but @@ -4099,7 +4146,7 @@ impl<'a> Lower<'a> { /// This lane's bit of the mask `lo`, `hi` (wave64). fn lane_bit(&mut self, at: usize, lo: V, hi: Option) -> V { self.s.flags |= flags::WAVE_OPS; - let lane = if self.exchange.is_some() { + let lane = if self.exchange.is_some() || self.twin.is_some() { self.console_lane() } else { self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) @@ -4333,15 +4380,20 @@ impl<'a> Lower<'a> { /// thread is relabelled so that its host lane is its console lane: the /// flat id is the wave's first lane's, rounded down to the wave size, /// plus the lane index. (A bijection while each host wave holds a - /// wave-aligned run of flat ids, as the console's waves do.) + /// wave-aligned run of flat ids, as the console's waves do.) In the paired form, of the + /// console lane being lowered, in the console's group (the host's is a row of half as + /// many threads). fn thread_id(&mut self, c: u8) -> Val { if !self.console_lanes { return self.compute_id("threadIdInGroup.i32", 95, c); } - let [x, y, _] = self.s.threads.expect("compute"); + let [x, y, _] = match self.x.native.io { + StageIo::Cs(cs) => cs.threads, + _ => self.s.threads.expect("compute"), + }; let e = self.s.entry; let i32t = self.s.t.i32; - if self.halves.is_some() { + if self.halves.is_some() || self.twin.is_some() { let f = self.console_thread(); self.s.flags |= flags::WAVE_OPS; let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); @@ -4408,7 +4460,15 @@ impl<'a> Lower<'a> { // never reached: they come down to the lane count when the outputs // do not fit. use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes}; - let (outputs, prims) = (&self.s.outputs, &self.s.prims); + // (linked: the outputs the pixel program reads, which are all that is declared) + let kept: Vec; + let outputs = if self.drop_out.is_empty() { + &self.s.outputs + } else { + kept = self.s.outputs.iter().zip(&self.drop_out).filter(|(_, d)| !**d).map(|(e, _)| e.clone()).collect(); + &kept + }; + let prims = &self.s.prims; let fits = |m: super::shader::Mesh| { mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT }; @@ -4954,6 +5014,12 @@ impl<'a> Lower<'a> { } fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V { + self.lds_rmw_loop(p, |l, old| l.lds_float_pick(old, data, max)) + } + + /// A read-modify-write of the LDS dword at `p` as a compare-exchange loop: `new` gives, + /// in the loop's one block, what is written over the old value; the old value returns. + fn lds_rmw_loop(&mut self, p: V, new: impl FnOnce(&mut Self, V) -> V) -> V { let pre = self.cur; let init = self.s.m.load(pre, p); let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); @@ -4961,7 +5027,7 @@ impl<'a> Lower<'a> { let i32t = self.s.t.i32; let old = self.s.m.phi(lp, i32t); self.cur = lp; - let new = self.lds_float_pick(old, data, max); + let new = new(self, old); let prev = self.s.m.cmpxchg(lp, p, old, new); let done = self.s.m.cmp(lp, pred::EQ, prev, old); self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); @@ -5126,6 +5192,150 @@ impl<'a> Lower<'a> { } } + /// Instruction `i` of IR block `b` in the paired form ([`with_paired_lanes`]), for both + /// console lanes of the thread: what a lane does is lowered for the lower lane, then for + /// the upper one, which keeps the console's order of the wave's instructions; scalar + /// control (the title's barrier) and scalar memory writes once; a read of other lanes once + /// with what both lanes hold ([`Self::paired_cross`]). An LDS access that follows another + /// gets a fence first unless both read: what one lane wrote (or still read) must not move + /// past another lane's access the console made after it. + fn paired_inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { + let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; + let name = inst.name(); + let once = matches!(inst.fields, Fields::Sopp { .. }) + || matches!(inst.fields, Fields::Smem { .. }) + && (name.contains("store") || name.contains("atomic")); + if once { + self.inst(b, i)?; + self.mirror(inst); + return Ok(()); + } + let cross = match name { + "v_readlane_b32" | "ds_bpermute_b32" => true, + // (not a waterfall loop's read, the lane's own dword: `Self::valu`) + "v_readfirstlane_b32" => { + !inst.writes.first().is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) + } + _ => false, + }; + if cross { + if let Err(why) = self.paired_cross(inst, b, i) { + for &(_, w) in &inst.writes { + self.put_lanes(w, Val::Missing(why), Val::Missing(why)); + } + } + return Ok(()); + } + if matches!(inst.fields, Fields::Ds { .. }) + && !name.starts_with("ds_swizzle") + && !name.contains("permute") + { + let write = !name.starts_with("ds_read"); + if write || self.lds_last != Some(false) { + let (mode, void) = (self.s.m.i32(8), self.s.t.void); + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + self.lds_last = Some(write); + } + self.inst(b, i)?; + self.swap_lanes(); + let r = self.inst(b, i); + self.swap_lanes(); + r + } + + /// The paired form: what `inst` wrote in the lane being lowered, for the other lane too (a + /// scalar result, the same in both). + fn mirror(&mut self, inst: &Inst) { + let Some(t) = self.twin.as_deref_mut() else { + return; + }; + for &(_, w) in &inst.writes { + if let Some(&v) = self.vals.get(&w) { + t.vals.insert(w, v); + } + } + } + + /// The paired form: an instruction that reads other lanes of the console wave, any of its + /// 64: `v_readlane_b32` and `v_readfirstlane_b32` (scalar results, the same in both lanes of + /// the thread) and `ds_bpermute_b32`. Lane n and lane n + 32 are the lower and the upper + /// lane of host lane n. + fn paired_cross(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + self.cross_lane(false)?; + let c = self.cur; + let (k31, k32, z) = (self.s.m.i32(31), self.s.m.i32(32), self.s.m.i32(0)); + // a lane's value from the lower or upper value of the host lane `at` (of 0..63) + let pick = |l: &mut Self, lo: V, hi: V, at: V| { + let host = l.s.m.bin(c, Bin::And, at, k31); + let upper = l.s.m.bin(c, Bin::And, at, k32); + let upper = l.s.m.cmp(c, pred::NE, upper, z); + let (lo, hi) = (l.read_lane(lo, host), l.read_lane(hi, host)); + l.s.m.select(c, upper, hi, lo) + }; + match inst.name() { + "v_readlane_b32" => { + // the lane: a scalar or a constant + let lane = self.src(inst, 1)?; + let [lo, hi] = self.both(|l| l.src(inst, 0))?; + let r = pick(self, lo, hi, lane); + self.write_i(inst, r, None)?; + } + "v_readfirstlane_b32" => { + let [(lo, in_lo), (hi, in_hi)] = self.both(|l| { + let x = l.src(inst, 0)?; + let guard = l.guard(b, i)?; + Ok(l.first_lane(x, guard)) + })?; + // the first lane in EXEC is a lower one if there is one; with none, lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + let r = self.s.m.select(c, in_lo, lo, hi); + self.write_i(inst, r, None)?; + } + _ => { + // `ds_bpermute_b32`: each lane reads the lane its address names, which gives + // its data, or 0 outside EXEC + let Fields::Ds { + dst: Some(Operand::Vector { reg, .. }), + addr: Some(addr), + data, + offset0, + offset1, + .. + } = &inst.fields + else { + return Err("a permute's operands"); + }; + let data = data.first().ok_or("a permute source")?; + let offset = u32::from(*offset0) | u32::from(*offset1) << 8; + let [(from_lo, x_lo, g_lo), (from_hi, x_hi, g_hi)] = self.both(|l| { + let at = l.vgprs(inst, addr, 1)?[0]; + let x = l.vgprs(inst, data, 1)?[0]; + let guard = l.guard(b, i)?; + let (o, two) = (l.s.m.i32(offset), l.s.m.i32(2)); + let at = l.s.m.bin(c, Bin::Add, at, o); + let from = l.s.m.bin(c, Bin::LShr, at, two); + let x = match guard { + Some(g) => l.s.m.select(c, g, x, z), + None => x, + }; + Ok((from, x, guard)) + })?; + let read = [pick(self, x_lo, x_hi, from_lo), pick(self, x_lo, x_hi, from_hi)]; + let guards = [g_lo, g_hi]; + let reg = *reg; + self.both(|l| { + let n = usize::from(l.upper); + l.write(inst, Reg::V(reg), read[n], guards[n]); + Ok(()) + })?; + return Ok(()); + } + } + self.mirror(inst); + Ok(()) + } + /// The two host waves of a console wave meet (a group barrier with a shared-memory /// fence): LDS writes before are seen by reads after. fn lds_meeting(&mut self) { @@ -5907,308 +6117,6 @@ impl<'a> Lower<'a> { Ok(()) } - /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords - /// the code also reads as numbers: the console compiler computes sizes - /// from descriptor bits (an image's width, height, depth, levels; a - /// buffer's record count) instead of querying them. Those fields are - /// rebuilt from the host view's dimensions in the GFX10 layout (image - /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits - /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at - /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). - // shortcut: the base level reads 0 (the host view starts at its own - // level 0, so sizes the code shifts by it come out right) and the other - // dwords (addresses, formats, tiling) have no host value: reading them - // stops the program. - fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { - const OTHER: Why = "a descriptor's address or format read as data"; - let Fields::Smem { - data: Some(Operand::Scalar { code, .. }), - .. - } = inst.fields - else { - return Err("a scalar memory read as data"); - }; - 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 memory read as data"), - }; - // How the program uses the descriptor tells the view's kind: an image or buffer - // instruction before a scalar buffer load, which reads any buffer. - let x = self.x; - let uses = |of: Site| { - x.res - .descriptors - .iter() - .filter(|d| d.role == Role::Resource) - .filter_map(move |d| { - d.source.leaves().into_iter().find_map(|l| match *l { - Source::Loaded { load, first } if load == of => Some((d.site, first)), - _ => None, - }) - }) - }; - let by_scalar_load = |u: &(Site, u8)| { - matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) - }; - let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); - // The console compiler loads a descriptor again wherever it needs it, and for a - // size it reads the dwords of a load that nothing uses as a descriptor (a texture - // picked from the heap by an index held per lane: one load for its width, one for - // its base level, one for each read of the image). Another load of as many dwords - // from the same address reads the same descriptor, so what uses that one tells - // this one's kind. The handle is still made from this load's own operands, which - // hold here. - let address = self.scalar.get(&site).copied(); - let twin = || { - let a = address?; - let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); - x.res - .scalar - .iter() - .filter(|(s, b)| *s != site && *b == a && same(*s)) - .find_map(|(s, _)| use_of(*s)) - }; - let use_at = use_of(site).or_else(twin); - let Some((at, first)) = use_at else { - // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only - // copies its dwords and compares them, lane against first lane, and every load - // that reaches those lanes reads one address. Each dword stands in as its place - // in the table, so the lanes compare equal as they do on the console. - if self.x.res.lane_copied.contains(&site) - && let Some(a) = self.scalar.get(&site).copied() - { - for k in 0..count { - let x = self.s.m.i32(a.offset / 4 + k); - self.write(inst, Reg::S(code + k as u8), x, None); - } - return Ok(()); - } - // A sampler's descriptor: no program reads its dwords as numbers, so where one - // meets numbers at a join the register is dead on that path (`dead`), as a - // descriptor's address or format is. - let sampler = x.res.descriptors.iter().any(|d| { - d.role == Role::Sampler - && d.source.leaves().into_iter().any( - |l| matches!(*l, Source::Loaded { load, .. } if load == site), - ) - }); - if sampler { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a sampler's descriptor read as data"); - } - // Code may walk the title address or test a structured view's record count. - let mut pointer = if count <= 4 { self.view_address(site) } else { None }; - if pointer.is_none() && count == 4 && self.picked_address_words(site, code) { - pointer = Some(self.picked_address(site)?); - } - if count <= 4 && let Some((lo, hi)) = pointer - { - let records = inst.write(Reg::S(code + 2)) - .and_then(|value| self.structured_srv_records(site, value)); - for k in 0..count { - let reg = Reg::S(code + k as u8); - match (k, records) { - (0, _) => self.write(inst, reg, lo, None), - (1, _) => self.write(inst, reg, hi, None), - (2, Some(n)) => self.write(inst, reg, n, None), - _ => { - if let Some(v) = inst.write(reg) { - self.vals.insert(v, Val::Missing(OTHER)); - self.stale.insert(v); - } - } - } - } - return Ok(()); - } - // Puddle detection looks up a 2D texture's dimensions by heap index - // without sampling it. Use that index to query the bound host view. - // Only the heap supplies this otherwise untyped 2D lookup. - if count == 8 && address.is_some_and(|a| { - a.dynamic.is_some() - && x.native.layout.get(a.param).is_some_and(|p| p.root == RootType::ResourceHeap) - }) { - let src = Source::Loaded { load: site, first: 0 }; - let h = self.handle(site, &src, false, (2, 0x409))?; - let words = self.image_size_words(h, 2, false); - self.write_descriptor_words(inst, code, count, 0, &words); - return Ok(()); - } - if std::env::var_os("VICTORY_DESC_WHY").is_some() { - eprintln!( - "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", - inst.machine.offset, - inst.name(), - address, - self.x.res.lane_copied.contains(&site) - ); - } - return Err("a descriptor read only as data"); - }; - let src = Source::Loaded { load: site, first }; - let used = self.used_kind(&src); - let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; - let un = ui.name(); - let uav = un.contains("store") - || un.contains("atomic") - || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; - let (props, image) = match &ui.fields { - // A ray-tracing structure in a buffer of the host: read raw. - Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), - Fields::Image { dim, .. } => { - let kind = match dim { - 0 => 1, - 1 => 2, - 2 => 4, - 4 => 6, - 5 => 7, - _ => return Err("an image dimension (cube or MSAA)"), - }; - let ty = if !uav && self.scalar_uint_srv(&src, kind) { 0x105 } else { 0x409 }; - ((kind | u, ty), Some(kind)) - } - Fields::Buffer { idxen, format, .. } => { - let stride = used.map_or(0, |u| u.stride); - let props = if un.starts_with("buffer_load_format") - || un.starts_with("buffer_store_format") - { - let ty = if !uav && self.scalar_uint_srv(&src, 10) { 0x105 } else { 0x409 }; - (10 | u, ty) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { - (12 | u, stride) - } else { - (11 | u, 0) - }; - if used.is_some_and(|u| u.kind == ResourceType::Cbv) { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a constant buffer's descriptor read as data"); - } - (props, None) - } - // Read by scalar buffer loads alone: the raw view `smem` reads it through. - Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { - ((11, 0), None) - } - // A constant buffer: nothing of its descriptor is a number. - Fields::Smem { .. } => { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a constant buffer's descriptor read as data"); - } - _ => return Err("a scalar memory read as data"), - }; - let h = self.handle(site, &src, false, props)?; - let words: Vec<(u32, V)> = match image { - Some(kind) => self.image_size_words(h, kind, uav), - None => { - let c = self.cur; - let i32t = self.s.t.i32; - let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); - let mip = self.s.m.undef(i32t); - let d = self - .s - .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); - // A raw view counts bytes; the descriptor's record count is in elements. - let n = self.s.m.extract(c, d, 0); - let stride = used.map_or(0, |u| u.stride); - let n = if props.0 & 0xFF == 11 && stride > 1 { - let k = self.s.m.i32(stride); - self.s.m.bin(c, Bin::UDiv, n, k) - } else { - n - }; - let mut words = vec![(2, n)]; - // Its address too, where the code computes with it and the - // host can tell it. - let computed = (0..2u8).any(|k| { - inst.write(Reg::S(code + first + k)) - .is_some_and(|v| self.computed_with(v, 6)) - }); - if first == 0 - && computed - && let Some((lo, hi)) = self.view_address(site) - { - words.extend([(0, lo), (1, hi)]); - } - words - } - }; - self.write_descriptor_words(inst, code, count, u32::from(first), &words); - Ok(()) - } - - /// An image descriptor's size fields in the GFX10 layout, from the dimensions of the - /// host view `h` of `kind` (as `descriptor_data` explains): (dword, value). - fn image_size_words(&mut self, h: V, kind: u32, uav: bool) -> Vec<(u32, V)> { - let c = self.cur; - let i32t = self.s.t.i32; - let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); - let mip = if uav { self.s.m.undef(i32t) } else { self.s.m.i32(0) }; - let d = self - .s - .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); - let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); - let one = self.s.m.i32(1); - let w = field(self, 0); - let (height, depth) = match kind { - 1 => (one, one), - 2 => (field(self, 1), one), - 6 => (one, field(self, 1)), - _ => (field(self, 1), field(self, 2)), - }; - let levels = if uav { one } else { field(self, 3) }; - let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); - let (w, height, depth, levels) = ( - less(self, w), - less(self, height), - less(self, depth), - less(self, levels), - ); - let k = |l: &mut Self, v: u32| l.s.m.i32(v); - let (k30, k2, k14, k16, mask) = ( - k(self, 30), - k(self, 2), - k(self, 14), - k(self, 16), - k(self, 0x3FFF), - ); - let d1 = self.s.m.bin(c, Bin::Shl, w, k30); - let hi = self.s.m.bin(c, Bin::LShr, w, k2); - let hi = self.s.m.bin(c, Bin::And, hi, mask); - let ht = self.s.m.bin(c, Bin::Shl, height, k14); - let d2 = self.s.m.bin(c, Bin::Or, hi, ht); - let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; - let base = k(self, 0xFAC | ty << 28); - let last = self.s.m.bin(c, Bin::Shl, levels, k16); - let d3 = self.s.m.bin(c, Bin::Or, base, last); - vec![(1, d1), (2, d2), (3, d3), (4, depth)] - } - - /// The `count` dwords an `s_load_dword*` writes from `s[code]` on, the descriptor's - /// dword `first` first: those of `words` (dword, value) get their value, the others - /// have none (reading them stops the program). - fn write_descriptor_words( - &mut self, inst: &Inst, code: u8, count: u32, first: u32, words: &[(u32, V)], - ) { - const OTHER: Why = "a descriptor's address or format read as data"; - for k in 0..count { - let rel = k.wrapping_sub(first); - match words.iter().find(|w| w.0 == rel) { - Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), - None => { - if let Some(v) = inst.write(Reg::S(code + k as u8)) { - self.vals.insert(v, Val::Missing(OTHER)); - self.stale.insert(v); - } - } - } - } - } - /// `s_load_dword*` from the program's constant table. fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { let Fields::Smem { @@ -6603,7 +6511,7 @@ impl<'a> Lower<'a> { sampler: bool, depth: u32, ) -> Result { - const WHY: Why = "a descriptor chosen by control flow"; + const WHY: Why = CHOSEN; let p = self.x.p; let mut incoming = Vec::new(); for (&q, arg) in p.blocks[block].preds.iter().zip(args) { @@ -6709,6 +6617,10 @@ impl<'a> Lower<'a> { let clear = self.lane_heap_index(b, sampler)?; Ok(self.s.m.select(self.cur, cond, set, clear)) } + // (in the paired form a thread comes the wave's way, not each lane its own) + Source::LanePhi { .. } if self.twin.is_some() => { + Err("a per-lane descriptor chosen by the lanes' ways, in paired lanes") + } Source::LanePhi { block, args } => { // Each predecessor computes its heap index at its end (what // it reads is there: the dwords are, on that edge); the join @@ -6979,7 +6891,9 @@ impl<'a> Lower<'a> { if let Some((rows, banks)) = masks { // Row (16 lanes) and bank (4 lanes of a row) write masks. let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3)); - let ri = self.s.m.bin(c, Bin::LShr, lane, four); + // (in the paired form rows 2 and 3 are the upper lanes') + let row_lane = if self.twin.is_some() { self.console_lane() } else { lane }; + let ri = self.s.m.bin(c, Bin::LShr, row_lane, four); let ri = self.s.m.bin(c, Bin::And, ri, three); let bi = self.s.m.bin(c, Bin::LShr, lane, two); let bi = self.s.m.bin(c, Bin::And, bi, three); @@ -7014,6 +6928,9 @@ impl<'a> Lower<'a> { if let Some(op) = name.strip_prefix("v_pk_") { return self.packed16(inst, op, guard); } + if let Some(r) = self.valu_f64(inst, name, guard) { + return r; + } match name { "v_mad_u64_u32" => { // a * b + c, c and the result 64 bits wide; the carry out @@ -7508,12 +7425,6 @@ impl<'a> Lower<'a> { let r = self.read_lane(x, from); int(self, r) } - "v_cvt_f32_f64" => { - let (lo, hi) = self.f64_pair(inst, 0)?; - let bits = self.f64_to_f32_bits(lo, hi); - let r = self.as_float(bits); - float(self, r) - } "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { let mut a = s(self, 0)?; @@ -7571,9 +7482,13 @@ impl<'a> Lower<'a> { let Some(Operand::Vector { reg, .. }) = v.dst else { return Err("a mixed-precision result"); }; - let old = match inst.read(Reg::V(reg)) { - Some(o) => self.i32_of(o)?, - None => self.s.m.i32(0), + // (a first interpolation half held there before keeps nothing anyone reads: + // its pair is evaluated by the second half, and code reads the f16 result's + // half of the register) + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + Some(Err(FIRST_HALF)) | None => self.s.m.i32(0), + Some(Err(why)) => return Err(why), }; let h = self .s @@ -7784,6 +7699,14 @@ impl<'a> Lower<'a> { return Err("a lane write in a half-wave"); } let me = self.console_lane(); + // (the paired form: a wave64 lane select takes the low six bits) + let lane = match self.twin { + Some(_) => { + let k63 = self.s.m.i32(63); + self.s.m.bin(c, Bin::And, lane, k63) + } + None => lane, + }; let is = self.s.m.cmp(c, pred::EQ, me, lane); let r = self.s.m.select(c, is, a, old); int(self, r) @@ -7909,159 +7832,6 @@ impl<'a> Lower<'a> { } } - /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying - /// `abs` and `neg` input modifiers on operand `k`. - fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { - let Fields::Valu(v) = &inst.fields else { - unreachable!() - }; - if v.sdwa.is_some() || v.dpp.is_some() { - return Err("64-bit operand modifiers"); - } - let op = *v.src.get(k).ok_or("a missing operand")?; - let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { - let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; - let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; - Ok((lo, hi)) - }; - let (lo, mut hi) = match op { - Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, - Operand::Scalar { code, .. } if code != NULL => { - pair(self, Reg::S(code), Reg::S(code + 1))? - } - Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), - Operand::Const(c @ 240..=248) => { - const INLINE_F64: [f64; 9] = [ - 0.5, - -0.5, - 1.0, - -1.0, - 2.0, - -2.0, - 4.0, - -4.0, - 1.0 / std::f64::consts::TAU, - ]; - let bits = INLINE_F64[(c - 240) as usize].to_bits(); - (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) - } - // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. - Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), - _ => return Err("a 64-bit float operand"), - }; - let c = self.cur; - if v.abs >> k & 1 != 0 { - let mask = self.s.m.i32(0x7FFF_FFFF); - hi = self.s.m.bin(c, Bin::And, hi, mask); - } - if v.neg >> k & 1 != 0 { - let sign = self.s.m.i32(0x8000_0000); - hi = self.s.m.bin(c, Bin::Xor, hi, sign); - } - Ok((lo, hi)) - } - - /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, - /// without requiring host `DOUBLES` (`f64`) support. - fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { - let c = self.cur; - let k0 = self.s.m.i32(0); - let k1 = self.s.m.i32(1); - let sign_mask = self.s.m.i32(0x8000_0000); - let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); - - let k20 = self.s.m.i32(20); - let k7ff = self.s.m.i32(0x7FF); - let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); - let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); - - let frac_mask = self.s.m.i32(0x000F_FFFF); - let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); - let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); - let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); - - let k3 = self.s.m.i32(3); - let k29 = self.s.m.i32(29); - let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); - let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); - let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); - - let rem_mask = self.s.m.i32(0x1FFF_FFFF); - let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); - let half_rem = self.s.m.i32(0x1000_0000); - let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); - let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); - let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); - let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); - let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); - let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); - let norm_inc = self.s.m.select(c, norm_round, k1, k0); - - // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. - let k896 = self.s.m.i32(896); - let k23 = self.s.m.i32(23); - let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); - let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); - let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); - let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); - let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); - - // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. - let k897 = self.s.m.i32(897); - let k32 = self.s.m.i32(32); - let k31 = self.s.m.i32(31); - let imp = self.s.m.i32(0x0080_0000); - let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); - let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); - // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. - let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); - let shift = self.s.m.select(c, lt1, k1, raw_shift); - let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); - let shift = self.s.m.select(c, gt23, k23, shift); - let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); - let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); - let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); - let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); - let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); - let low31 = self.s.m.i32(0x7FFF_FFFF); - let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); - let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); - let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); - let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); - let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); - let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); - let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); - let sub_inc = self.s.m.select(c, sub_round, k1, k0); - let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); - let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); - - // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). - let k873 = self.s.m.i32(873); - let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); - let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); - let min_bit = self.s.m.select(c, round_min, k1, k0); - let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); - - // Overflow / Inf / NaN: exp64 >= 1151. - let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); - let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); - let inf_bits = self.s.m.i32(0x7F80_0000); - let qnan_bits = self.s.m.i32(0x7FC0_0000); - let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); - let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); - let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); - - // Select final result by exponent range. - let k874 = self.s.m.i32(874); - let k1151 = self.s.m.i32(1151); - let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); - let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); - let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); - let r = self.s.m.select(c, is_over, over_res, norm_res); - let r = self.s.m.select(c, is_sub, sub_res, r); - self.s.m.select(c, is_under, under_res, r) - } - fn join64(&mut self, lo: V, hi: V) -> V { let c = self.cur; let ty = self.s.m.int(64); @@ -8072,69 +7842,6 @@ impl<'a> Lower<'a> { self.s.m.bin(c, Bin::Or, lo, hi) } - /// The bits of the float nearest the double whose dwords are `lo` and - /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN - /// kept (a NaN stays quiet), a result below the smallest normal float - /// signed zero (flushed, as the console's default float mode does). - // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's - // float mode for this instruction is checked. - #[allow(dead_code)] - fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V { - let c = self.cur; - let k = |l: &mut Self, x: u32| l.s.m.i32(x); - let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23)); - let sign_mask = k(self, 0x8000_0000); - let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); - let e = self.s.m.bin(c, Bin::LShr, hi, k20); - let e_mask = k(self, 0x7ff); - let e = self.s.m.bin(c, Bin::And, e, e_mask); - // The top 23 bits of the 52-bit mantissa, and the 29 below them. - let m_mask = k(self, 0x000f_ffff); - let mh = self.s.m.bin(c, Bin::And, hi, m_mask); - let mh = self.s.m.bin(c, Bin::Shl, mh, k3); - let ml = self.s.m.bin(c, Bin::LShr, lo, k29); - let m = self.s.m.bin(c, Bin::Or, mh, ml); - let rest_mask = k(self, 0x1fff_ffff); - let rest = self.s.m.bin(c, Bin::And, lo, rest_mask); - // Round to nearest even: up past half, or at half when odd. - let half = k(self, 0x1000_0000); - let one = k(self, 1); - let above = self.s.m.cmp(c, pred::IUGT, rest, half); - let at = self.s.m.cmp(c, pred::EQ, rest, half); - let odd = self.s.m.bin(c, Bin::And, m, one); - let zero = k(self, 0); - let odd = self.s.m.cmp(c, pred::NE, odd, zero); - let tie = self.s.m.bin(c, Bin::And, at, odd); - let up = self.s.m.bin(c, Bin::Or, above, tie); - let up = self.s.m.select(c, up, one, zero); - // Rebias the exponent (1023 → 127); a carry out of the mantissa - // steps the exponent, up to infinity. - let bias = k(self, 1023 - 127); - let e32 = self.s.m.bin(c, Bin::Sub, e, bias); - let ex = self.s.m.bin(c, Bin::Shl, e32, k23); - let normal = self.s.m.bin(c, Bin::Add, ex, m); - let normal = self.s.m.bin(c, Bin::Add, normal, up); - let normal = self.s.m.bin(c, Bin::Or, normal, sign); - // Exponents out of the float's range (signed, after rebiasing). - let inf = k(self, 0x7f80_0000); - let inf = self.s.m.bin(c, Bin::Or, inf, sign); - let k255 = k(self, 255); - let big = self.s.m.cmp(c, pred::SGE, e32, k255); - let small = self.s.m.cmp(c, pred::SLE, e32, zero); - let r = self.s.m.select(c, big, inf, normal); - let r = self.s.m.select(c, small, sign, r); - // Infinity and NaN (a NaN with any mantissa bit set stays a NaN). - let all = k(self, 0x7ff); - let special = self.s.m.cmp(c, pred::EQ, e, all); - let any = self.s.m.bin(c, Bin::Or, mh, ml); - let any = self.s.m.bin(c, Bin::Or, any, rest); - let nan = self.s.m.cmp(c, pred::NE, any, zero); - let quiet = k(self, 0x0040_0000); - let quiet = self.s.m.select(c, nan, quiet, zero); - let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet); - self.s.m.select(c, special, special_bits, r) - } - /// The low and high dwords of an i64. fn split64(&mut self, x: V) -> (V, V) { let c = self.cur; @@ -9305,7 +9012,13 @@ impl<'a> Lower<'a> { fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { let Some(&interp) = self.interps.get(&site) else { - return Err("the first half of an interpolation"); + // The first half of a pair: its second half interpolates the attribute itself, so + // this half has no value of its own. Where its register is kept, a 16-bit write over + // it reads 0 for the half it keeps (`v_fma_mix*`); read as data, the program is + // translated once more with first halves evaluated as the pairs they start + // ([`with_first_half_pairs`]). (Writing 0 here for every first half changed 59 of + // the title's pixel programs that translated already, and translated none more.) + return Err(FIRST_HALF); }; let name = inst.name(); let (dst, src) = match &inst.fields { @@ -9562,8 +9275,9 @@ impl<'a> Lower<'a> { }; self.s.flags |= flags::BARYCENTRICS; let entry = self.s.entry; + let sig = self.sig_id(true, id); let args = [ - self.s.m.i32(id as u32), + self.s.m.i32(sig), self.s.m.i32(0), self.s.m.i8(col), self.s.m.i8(k), @@ -10008,6 +9722,10 @@ impl<'a> Lower<'a> { return Err("an image result"); }; let f32t = self.s.t.f32; + // The level comes from the coordinates the size divides: an array's layer + // is none of them (DXIL wants it undefined). + let mut at = [fu; 3]; + at[..spatial].copy_from_slice(&cs[..spatial]); for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { let clamped = self.s.m.bool(ch == 0); let lod = self.s.op( @@ -10016,7 +9734,7 @@ impl<'a> Lower<'a> { Attr::ReadOnly, f32t, 81, - &[h, sh, cs[0], cs[1], cs[2], clamped], + &[h, sh, at[0], at[1], at[2], clamped], ); let x = self.as_int(lod); self.write(inst, Reg::V(reg + k as u8), x, guard); @@ -11141,6 +10859,10 @@ impl<'a> Lower<'a> { None }; for (id, col, value, half) in stores { + // (an output a linked pixel program does not read: neither stored nor declared) + if !primitive && self.drop_out.get(id).copied().unwrap_or(false) { + continue; + } let mut x = self.i32_of(value)?; if let Some(high) = half { // An f16 half, declared a 32-bit float on the host. @@ -11168,6 +10890,7 @@ impl<'a> Lower<'a> { } _ => (".i32", x), }; + let sig = if primitive { id as u32 } else { self.sig_id(false, id) }; if let Some(rgb) = ambient.filter(|_| col < 3 && suffix == ".f32") { let c = self.cur; let base = self.s.m.extract(c, rgb, u32::from(col)); @@ -11176,7 +10899,7 @@ impl<'a> Lower<'a> { x = self.s.op(c, "binary.f32", Attr::ReadNone, self.s.t.f32, 35, &[x, fill]); } let mut args = vec![ - self.s.m.i32(id as u32), + self.s.m.i32(sig), self.s.m.i32(0), self.s.m.i8(col), x, @@ -11307,6 +11030,16 @@ impl<'a> Lower<'a> { let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; (c, taken, not_taken) } + // (the paired form: a branch the wave does not take together must be one + // that both lanes of every thread take the same way) + _ if self.twin.is_some() + && !self.x.st.bools.support(when).iter().all( + |a| matches!(a, Atom::Uniform(v) if !self.lane_scalars.contains(v)), + ) => + { + const APART: Why = "a branch the two lanes of a thread may not take together"; + return Err(unsupported(offset, APART)); + } Some((atom, Bool::TRUE, Bool::FALSE)) => { let a = self .atom(atom, self.cur) @@ -11399,6 +11132,7 @@ impl<'a> Lower<'a> { let limit = match super::loop_limit() { LOOP_LIMIT if self.s.pixel => 1 << 7, LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, + LOOP_LIMIT if self.traces => TRACE_LOOP_LIMIT, LOOP_LIMIT => 1 << 12, named => named, }; diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 0928cbbe78..63ee640585 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -2,7 +2,10 @@ //! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts. //! Compute shaders keep the console's thread-group size; one that depends //! on the lane layout (cross-lane operations) declares the console's wave -//! size (`WaveSize`), so the host device must support it. +//! size (`WaveSize`), so the host device must support it. On a host of +//! 32-lane waves, a wave64 program that no form in 32-lane waves gives as +//! the console runs it takes the paired form instead (`paired`): a host +//! wave for each console wave, two console lanes a thread, half the threads. //! //! What the host binds for a translated shader ([`HostShader`]): //! @@ -85,6 +88,8 @@ mod container; #[cfg(all(test, windows))] mod cube_lod_tests; #[cfg(all(test, windows))] +mod descriptor_tests; +#[cfg(all(test, windows))] mod diff_tests; #[cfg(all(test, windows))] mod helper_lane_tests; @@ -92,6 +97,8 @@ mod helper_lane_tests; mod intersect_tests; #[cfg(all(windows, any(test, feature = "host")))] pub mod host; +mod idiom; +mod link; mod lower; mod own_bits; mod pops; @@ -114,6 +121,7 @@ use crate::native::{HwStage, NativeProgram, RootType}; use crate::{ShaderError, io, ir, resource, structure}; pub use bitcode::census; +pub use link::{link_mesh, mesh_fits}; pub use sampler::StaticSampler; pub use lower::{host_max_wave, set_host_max_wave}; @@ -428,6 +436,132 @@ pub fn emit( if native.stage == HwStage::Ps && !pops::active(native) { pops::check(p)?; } + let r = emit_any(c, native, p, st, io, res); + if r.is_ok() && !permutes_outside_sections(p) { + return r; + } + // A lane mask parked in two lanes of a VGPR, one of which holds a single scalar at other + // times, came back as two scalars: once more with the program built so that it comes back + // as the mask it is ([`ir::with_shared_slots`]). The original's error if that does not + // translate either. + if matches!(&r, Err(ShaderError::Unsupported { what, .. }) if *what == "an opaque lane mask") { + let again = ir::with_shared_slots(|| crate::spill::build(native)).and_then(|q| { + let st = structure::structure(&q)?; + let io = io::raise(&q, native)?; + let res = resource::track(&q, &native.layout, native.stage, Some(&st))?; + emit_any(c, native, &q, &st, &io, &res) + }); + if again.is_ok() { + return again; + } + } + // A whole-wave section that a jump splits (two reductions a branch chooses between that + // share their end): once more with each such section in one block + // ([`ir::whole_sections`]), where the simulation follows it. The original's result if that + // does not translate. Tried for a program that translates too where it permutes lanes + // outside the sections followed (the title's water optical depth: `v_permlanex16_b32` + // before the jump): such a permute lowered on its own reads the lanes the host has as they + // are, where the console's section reads every lane, a lane outside the saved mask with + // the reduction's identity. + let mut q = None; + for _ in 0..4 { + match ir::whole_sections(q.as_ref().unwrap_or(p)) { + Some(next) => q = Some(next), + None => break, + } + } + let Some(q) = q else { return r }; + let again = (|| { + let st = structure::structure(&q)?; + let io = io::raise(&q, native)?; + let res = resource::track(&q, &native.layout, native.stage, Some(&st))?; + emit_any(c, native, &q, &st, &io, &res) + })(); + match again { + Ok(shader) => Ok(shader), + Err(_) => r, + } +} + +/// Whether `p` has a `v_permlane16_b32` or `v_permlanex16_b32` that no whole-wave section the +/// simulation follows ([`wave::sections`]) holds. +fn permutes_outside_sections(p: &ir::Program) -> bool { + let permute = |inst: &ir::Inst| matches!(inst.name(), "v_permlane16_b32" | "v_permlanex16_b32"); + p.blocks.iter().enumerate().any(|(b, block)| { + if !block.insts.iter().any(permute) { + return false; + } + let sections = wave::sections(p, b); + let held = |i: usize| sections.iter().any(|(&start, s)| start < i && i < s.end); + block.insts.iter().enumerate().any(|(i, inst)| permute(inst) && !held(i)) + }) +} + +/// [`emit`] of `p` as it is. +fn emit_any( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result { + let r = emit_forms(c, native, p, st, io, res); + // A console wave64 compute program on a host of 32-lane waves that no form above gives + // the host (it still asks for 64-lane waves, or does not translate): once more in the + // paired form, each console wave run by one host wave (`paired`; `VICTORY_WAVE_PAIRS=0` + // turns it off). + let refused = match &r { + Ok((_, wave)) => *wave == Some(64), + Err(e) => matches!(e, ShaderError::Unsupported { .. }), + }; + if refused + && native.stage == HwStage::Cs + && native.wave64 + && lower::host_max_wave() == 32 + && pairs_on() + { + let again = paired(c, native, p, io, res); + if std::env::var_os("VICTORY_WAVE_WHY").is_some() { + match &again { + Ok((_, wave)) => eprintln!("WAVE64-RETRY paired lanes: wave {wave:?}"), + Err(e) => eprintln!("WAVE64-RETRY paired lanes: {e}"), + } + } + if let Ok((shader, _)) = again { + return Ok(shader); + } + } + r.map(|(shader, _)| shader) +} + +/// Whether console wave64 compute programs may take the paired form ([`paired`]): +/// `VICTORY_WAVE_PAIRS=0` turns it off (a test can choose for its own thread). +fn pairs_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_PAIRS.get() { + return on; + } + std::env::var_os("VICTORY_WAVE_PAIRS").is_none_or(|v| v != "0") +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`pairs_on`], for its thread only. + static TEST_PAIRS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// [`emit`] in every form but the paired one, with the wave size the result requires of the +/// host; where an approximate form translates the program, the paired form instead if it +/// does. +fn emit_forms( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option), ShaderError> { // (what an earlier program's lowering on this thread left behind) lower::take_needs(); let original = emit_program(c, native, p, st, io, res); @@ -459,12 +593,12 @@ pub fn emit( // for programs still stopped where not every lane runs. let local_on = std::env::var_os("VICTORY_WAVE_LOCAL").is_none_or(|v| v != "0"); // Where the wave operations are the allocation idiom - // ([`lower::wave_local`]) that is exact. Other programs are taken + // ([`idiom::wave_local`]) that is exact. Other programs are taken // the same way last of all, each half-wave giving its own results // (approximate: a tile-wide result becomes two half-tile ones); // `VICTORY_WAVE_LOCAL=idiom` refuses those instead. let strict = std::env::var_os("VICTORY_WAVE_LOCAL").is_some_and(|v| v == "idiom"); - let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) { + let idiom = |p: &ir::Program, st: &structure::Structured| match idiom::wave_local(p, st) { Ok(()) => true, Err((offset, what)) => { if why { @@ -492,7 +626,7 @@ pub fn emit( let again = emit_program(c, native, p, st, io, res); report(name, &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } } @@ -502,6 +636,30 @@ pub fn emit( // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which // has no barrier, stays on. let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); + // Where an approximate form below translates the program, the paired form + // ([`paired`]) is tried first: it runs each console wave as one host wave and gives + // what the console's 64 lanes compute, at no barrier but the entry's; the approximate + // form is kept for a program the paired form does not take. Before, the paired form + // was tried only where no form took the program, and 39 of the title's programs ran + // approximate, each half-wave counting, ORing or electing over its own 32 lanes + // (shadow-mask tiles and traces, temporal resolves, irradiance-cache and fallback + // lighting, light clustering, scattering gathers, decal and fire resolves, the light + // atlas, lens-flare scans). 36 now take the paired form; the other three (lens-flare + // scans) were the allocation idiom with a multiply-add (`idiom::wave_local` now knows it) + // and keep the per-half form, which is exact for them. Only these change: a program + // an approximate form does not take goes on as before, and the paired form stays + // last for it (`emit_any`). (`VICTORY_WAVE_PAIRS=0` turns the paired form off here + // too.) + let exactly = |approximate: Result<(HostShader, Option), ShaderError>| { + if pairs_on() { + let again = paired(c, native, p, io, res); + report("paired lanes, before an approximate form", &again); + if again.is_ok() { + return again; + } + } + approximate + }; // exact first: each host wave on its own where that is exact (the idiom, every // form; no barriers), then the other exact forms; then approximate for exact in [true, false] { @@ -517,7 +675,7 @@ pub fn emit( let again = emit_program(c, native, p, st, io, res); report("without skips, scalars followed", &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } // Still stopped where not every lane runs: the per-lane branches around @@ -534,7 +692,7 @@ pub fn emit( let again = widen(c, native, base, why); report("wave-wide branches", &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } } @@ -552,7 +710,7 @@ pub fn emit( let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); if done(&local) { - return local.map(|(shader, _)| shader); + return if exact { local } else { exactly(local) }; } } } @@ -560,7 +718,7 @@ pub fn emit( let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); if done(&local) { - return local.map(|(shader, _)| shader); + return if exact { local } else { exactly(local) }; } } } @@ -572,14 +730,14 @@ pub fn emit( let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); if done(&local) { - return local.map(|(shader, _)| shader); + return exactly(local); } } } let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); report("local waves (APPROXIMATE, any mask)", &local); if done(&local) { - return local.map(|(shader, _)| shader); + return exactly(local); } } } @@ -602,7 +760,7 @@ pub fn emit( let again = widen(c, native, base, why); report("wave-wide branches (last resort)", &again); if done(&again) { - return again.map(|(shader, _)| shader); + return again; } } } @@ -624,7 +782,16 @@ pub fn emit( } other => other, }; - let original = original.map(|(shader, _)| shader); + // A descriptor joined from what each way into a block brings, where a way brings what no + // heap index stands for (the title's terrain programs pick an immediate sampler that + // clamps or wraps by a uniform condition, each arm setting its own constant): once more + // with that block copied for each way in ([`split_choices`]). + let original = match original { + Err(ShaderError::Unsupported { what, .. }) if what == lower::CHOSEN => { + split_choices(c, native, p, res).unwrap_or(original) + } + other => other, + }; // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. if !matches!(original, Err(ShaderError::Unsupported { .. })) { @@ -638,7 +805,54 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res) +} + +/// `p` translated with the joins of its descriptors chosen by control flow copied for each way +/// in ([`ir::split_joins`]), so that each copy holds one descriptor; again while the choice +/// moves on to a later join (a use further down), a few times at most. `None` unless a form +/// translates. +fn split_choices( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + res: &resource::Resources, +) -> Option), ShaderError>> { + /// The joins where a descriptor is chosen from what a heap index cannot stand for: a way + /// in that brings neither a loaded descriptor nor an earlier join's choice. + fn joins(res: &resource::Resources) -> Vec { + fn walk(s: &resource::Source, out: &mut Vec) { + use resource::Source; + if let Source::Phi { block, args } = s { + let other = |a: &Source| !matches!(a, Source::Loaded { .. } | Source::Phi { .. }); + if args.iter().any(other) && !out.contains(block) { + out.push(*block); + } + for a in args { + walk(a, out); + } + } + } + let mut out = Vec::new(); + for d in &res.descriptors { + walk(&d.source, &mut out); + } + out + } + let mut form = ir::split_joins(p, &joins(res))?; + for _ in 0..4 { + let st = structure::structure(&form).ok()?; + let io = io::raise(&form, native).ok()?; + let res = resource::track(&form, &native.layout, native.stage, Some(&st)).ok()?; + match emit_program(c, native, &form, &st, &io, &res) { + Err(ShaderError::Unsupported { what, .. }) if what == lower::CHOSEN => { + form = ir::split_joins(&form, &joins(&res))?; + } + Ok(done) => return Some(Ok(done)), + Err(_) => return None, + } + } + None } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -722,6 +936,66 @@ fn tiled_lighting_uint_srvs(digest: [u8; 16]) -> &'static [(u8, u32, u32)] { } } +/// `p` (a console wave64 compute program on a host of 32-lane waves) in the paired form +/// ([`lower::with_paired_lanes`]): each console wave run by one host wave of 32 lanes, each +/// thread two of its lanes, with every per-lane branch taken by the whole wave as the console +/// takes it ([`structure::structure_wide`]), so that a host wave's threads go the same way and +/// EXEC stays each lane's guard. The program's barriers are reached by whole host waves where +/// the console's waves reach them; the only barriers added are on entry, before the program, +/// where a group of several console waves numbers its waves (`Lower::wave_base`). A thread +/// group whose console waves are not full would need the lanes past its end kept out of every +/// effect: refused. +/// Descriptors and addresses stay those traced on the lanes' own paths (`res`, as for every +/// other form): the per-lane form rests on a lane that reads a scalar after a join having +/// come the way the wave did, and knowing less of a lane's way the wave-wide form would miss +/// some of them (a sampler set in a skip that only a wave with no lane left for it skips). +fn paired( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option), ShaderError> { + let crate::native::StageIo::Cs(cs) = native.io else { + return Err(ShaderError::Unsupported { + offset: 0, + what: "paired lanes outside compute", + }); + }; + // The ray-tracing structure builder's programs (a spilled user-data table, as + // `victory-gpu` tells them) exchange across the halves, and forcing them onto 32-lane + // hosts hung NVIDIA cards (Marvisak/VIctory#2711): they stay refused. + if crate::spill::is_spilled(native) { + return Err(ShaderError::Unsupported { + offset: 0, + what: "paired lanes for the ray-tracing structure builder", + }); + } + if cs.threads.iter().product::() % 64 != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "paired lanes in a thread group that does not fill its console waves", + }); + } + // every per-lane branch the wave's; again while that leaves another branch per lane + let mut wide = std::collections::HashSet::new(); + let st = loop { + let st = structure::structure_wide(p, &wide)?; + let lanes: Vec = (0..st.exits.len()) + .filter(|b| !wide.contains(b)) + .filter(|&b| { + matches!(st.exits[b], structure::LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().all(|a| matches!(a, structure::Atom::Uniform(_)))) + }) + .collect(); + if lanes.is_empty() { + break st; + } + wide.extend(lanes); + }; + lower::with_paired_lanes(|| emit_program(c, native, p, &st, io, res)) +} + /// The translated program, and the wave size it requires of the host. fn emit_program( c: &Container, @@ -1897,7 +2171,7 @@ mod atomic_tests { mod barycentric_tests { use super::container::SigElement; use super::*; - use crate::native::{PsInput, StageIo, Usage}; + use crate::native::{PsInput, ResourceType, RootParam, RootType, StageIo, Usage, UsedResource}; /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. const PERSP_CENTER: u32 = 1 << 1; @@ -2041,13 +2315,27 @@ mod barycentric_tests { words: &[u32], input_addr: u32, inputs: &[SigElement], + ) -> Result { + pixel_of(words, input_addr, inputs, false, Vec::new(), Vec::new()) + } + + /// [`pixel_with_inputs`] with the inputs' first row a 16-bit attribute when `fp16` (one + /// value in the low half of each dword), and the root parameters `layout` and used + /// resources `used`. + fn pixel_of( + words: &[u32], + input_addr: u32, + inputs: &[SigElement], + fp16: bool, + layout: Vec, + used: Vec, ) -> Result { let native = NativeProgram { stage: HwStage::Ps, wave64: false, vgprs: 8, - layout: vec![], - used: vec![], + layout, + used, io: StageIo::Ps { inputs: vec![PsInput { usage: Usage::Generic, @@ -2055,7 +2343,7 @@ mod barycentric_tests { mask: 0b1111, attr: 0, flat: false, - fp16: false, + fp16, pack2: false, row2: 0, }], @@ -2144,6 +2432,75 @@ mod barycentric_tests { validate(&shader); } + /// A 16-bit result written over a first interpolation half's register + /// (`v_fma_mixlo_f16` keeps the other half): the second half evaluates the pair, and + /// what the first half leaves in the half kept is no number the code reads. + #[test] + fn a_half_written_over_a_first_interpolation_half_translates() { + let [e0, e1] = exp_mrt0(4); + let words = [ + 0xD742_0002, + 0x0002_0000, // v_interp_p1ll_f16 v2, v0, attr0.x + 0xD75A_0003, + 0x040A_0200, // v_interp_p2_f16 v3, v1, attr0.x, v2 + 0xCC21_0002, + 0x0A01_E503, // v_fma_mixlo_f16 v2, sel_lo(v3), 1.0, 0 + 0x7E08_1702, // v_cvt_f32_f16 v4, v2 + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel_of(&words, PERSP_CENTER, &[element("TEXCOORD", 0, 0)], true, Vec::new(), Vec::new()).unwrap(); + validate(&shader); + } + + /// A level-of-detail query of a 2D array texture: the layer is no coordinate of the + /// level, and DXIL wants it undefined (the validator refused three of the title's + /// deferred programs: "out of bound coord must be undef"). + #[test] + fn a_level_query_of_an_array_leaves_the_layer_out() { + // A table of textures at s0, one of samplers at s1. + let table = |user_data| RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data, + slot: user_data, + }; + let range = |kind, dwords, user_data| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords, + user_data, + slot: user_data, + }; + let [e0, e1] = exp_mrt0(4); + let words = [ + 0xBE82_0300, // s_mov_b32 s2, s0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0101, + 0xFA00_0000, // s_load_dwordx8 s[4:11], s[2:3], null + 0xBE8C_0301, // s_mov_b32 s12, s1 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0406, + 0xFA00_0000, // s_load_dwordx4 s[16:19], s[12:13], null + 0x7E04_0280, // v_mov_b32 v2, 0 (layer 0) + 0xF180_0328, + 0x0081_0400, // image_get_lod v[4:5], v[0:2], s[4:11], s[16:19] dmask:0x3 2D array + e0, + e1, + 0xBF81_0000, + ]; + let layout = vec![table(0), table(1)]; + let used = vec![range(ResourceType::Srv, 8, 0), range(ResourceType::Sampler, 4, 1)]; + let shader = pixel_of(&words, PERSP_CENTER, &[element("TEXCOORD", 0, 0)], false, layout, used).unwrap(); + validate(&shader); + } + /// Two kinds of barycentrics read directly: one element per mode. #[test] fn two_barycentric_modes_get_two_elements() { @@ -2295,6 +2652,160 @@ mod barycentric_tests { validate(&shader); } + /// The `PSV0` interpolation mode of the element at `row`, `col` with `cols` columns and + /// signature component type `comp` (1 u32, 3 f32). + fn mode_at(shader: &HostShader, row: u8, col: u8, cols: u8, comp: u8) -> u8 { + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + let element = [1, row, 0x40 | col << 4 | cols, 0, comp]; + let at = psv.windows(5).position(|w| w == element).unwrap(); + psv[at + 5] + } + + /// A program of `stage` with the signature parts `isg1`, `osg1` and stage data `io`. + fn translate_with( + stage: HwStage, + words: &[u32], + io: StageIo, + isg1: &[SigElement], + osg1: &[SigElement], + ) -> HostShader { + let native = NativeProgram { + stage, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let isg1 = container::signature(isg1, true); + let osg1 = container::signature(osg1, false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + emit(&c, &native, &p, &st, &io, &res).unwrap() + } + + fn packed(name: &str, kind: u8, comp: u8, row: u32, col: u8, cols: u8) -> SigElement { + SigElement { + col, + cols, + comp, + ..element(name, kind, row) + } + } + + /// VS_Transform_VfxVBuffer_AlphaClip's register 1: a float2 the console declared + /// `nointerpolation` beside a uint2. The float's default, linear, packed two modes into + /// the register (refused by the validator); it takes the uint's. + #[test] + fn a_vertex_output_beside_an_integer_takes_its_mode() { + use crate::native::VsOutput; + let words = [ + 0x7E02_02F2, // v_mov_b32 v1, 1.0 + 0x7E04_0287, // v_mov_b32 v2, 7 + 0xF800_020F, + 0x0202_0101, // exp param0, v1, v1, v2, v2 + 0xF800_08CF, + 0x0101_0101, // exp pos0, v1, v1, v1, v1 done + S_ENDPGM, + ]; + let io = StageIo::Vs { + inputs: vec![], + outputs: vec![VsOutput { + usage: Usage::Generic, + row: 1, + param: 0, + fp16: false, + pack2: false, + }], + }; + let osg1 = [ + element("SV_Position", 3, 0), + packed("TEXCOORD", 0, 9, 1, 0, 2), + SigElement { + index: 14, + ..packed("TEXCOORD", 0, 5, 1, 2, 2) + }, + ]; + let shader = translate_with(HwStage::Vs, &words, io, &[], &osg1); + assert_eq!(mode_at(&shader, 1, 0, 2, 3), 1, "the float2"); + assert_eq!(mode_at(&shader, 1, 2, 2, 1), 1, "the uint2"); + validate(&shader); + } + + /// The pixel side of that register: the program reads the uint2 at its provoking vertex + /// (`v_interp_mov`, constant) and never the float2, whose default would be linear. + #[test] + fn an_unread_pixel_input_takes_the_mode_of_its_register() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC80A_0202, // v_interp_mov_f32 v2, p0, attr0.z + e0, + e1, + S_ENDPGM, + ]; + let io = StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0b1100, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let isg1 = [ + packed("TEXCOORD", 0, 9, 0, 0, 2), + SigElement { + index: 14, + ..packed("TEXCOORD", 0, 5, 0, 2, 2) + }, + ]; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let shader = translate_with(HwStage::Ps, &words, io, &isg1, &[target]); + assert_eq!(mode_at(&shader, 0, 0, 2, 3), 1, "the float2"); + assert_eq!(mode_at(&shader, 0, 2, 2, 1), 1, "the uint2"); + validate(&shader); + } + + /// PS_PropFoliageDeferred_Fire_ExportDepth's register 9: a float the program never reads + /// beside the front face (constant). + #[test] + fn an_unread_pixel_input_beside_the_front_face_is_constant() { + let words = [ + 0x7E04_02F2, // v_mov_b32 v2, 1.0 + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + S_ENDPGM, + ]; + let io = StageIo::Ps { + inputs: vec![], + input_addr: 1 << 12, + db_shader_control: 0, + patches: vec![], + }; + let isg1 = [ + packed("TEXCOORD", 0, 9, 0, 0, 1), + packed("SV_IsFrontFace", 13, 5, 0, 1, 1), + ]; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let shader = translate_with(HwStage::Ps, &words, io, &isg1, &[target]); + assert_eq!(mode_at(&shader, 0, 0, 1, 3), 1, "the float"); + validate(&shader); + } + /// P10 of an attribute the program interpolates is P1 - P0. #[test] fn p10_of_an_interpolated_attribute() { @@ -2316,4 +2827,132 @@ mod barycentric_tests { let words = [0xC812_0000, e0, e1, S_ENDPGM]; assert!(pixel(&words, PERSP_CENTER).is_err()); } + + /// A pixel program with TEXCOORD0..2 in rows 0..2 that reads only attribute 2's z + /// (`v_interp_mov_f32 v2, p0, attr2.z`), translated with `linked` (`link_mesh`'s pixel + /// side). + fn linked_pixel(linked: link::Linked) -> Result { + let [e0, e1] = exp_mrt0(2); + let words = [0xC80A_0A02, e0, e1, S_ENDPGM]; + let input = |row: u8| PsInput { + usage: Usage::Generic, + row, + mask: 0b1111, + attr: row, + flat: true, + fp16: false, + pack2: false, + row2: row, + }; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![input(0), input(1), input(2)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let texcoord = |i: u32| SigElement { + index: i, + ..element("TEXCOORD", 0, i) + }; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let isg1 = container::signature(&[texcoord(0), texcoord(1), texcoord(2)], true); + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage, None)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + link::with_linked(linked, || emit(&c, &native, &p, &st, &io, &res)) + } + + /// `link_mesh`'s pixel side: the inputs the program never reads leave its signature, the + /// one it reads keeps its row and is read as the signature's first element now; leaving + /// out an input it reads is refused. + #[test] + fn a_linked_pixel_program_declares_only_the_inputs_it_reads() { + let rows = |s: &HostShader| -> Vec<(u32, Option)> { + let c = Container::parse(&s.dxil).unwrap(); + let isg1 = signature(c.part(FourCC::ISG1).unwrap().data).unwrap(); + isg1.iter().map(|e| (e.index, e.row)).collect() + }; + let whole = linked_pixel(link::Linked::default()).unwrap(); + assert_eq!(rows(&whole), [(0, Some(0)), (1, Some(1)), (2, Some(2))]); + let unread = vec![("TEXCOORD".to_owned(), 0), ("texcoord".to_owned(), 1)]; + let linked = linked_pixel(link::Linked { + inputs: unread, + outputs: Vec::new(), + }) + .unwrap(); + assert_eq!(rows(&linked), [(2, Some(2))]); + // (dxil.dll checks each read against the element its id names) + validate(&whole); + validate(&linked); + let read = linked_pixel(link::Linked { + inputs: vec![("TEXCOORD".to_owned(), 2)], + outputs: Vec::new(), + }); + assert!( + matches!(&read, Err(ShaderError::Unsupported { what, .. }) if *what == "an input left out of a linked pipeline read"), + "{:?}", + read.err() + ); + } + + /// The other side, for a stage whose outputs a pixel program reads: an output left out is + /// neither stored nor declared, the others keep their rows and are stored to their element + /// as the signature numbers it now (SV_Position 0, TEXCOORD1 1). + #[test] + fn a_linked_stage_stores_only_the_outputs_it_keeps() { + use crate::native::VsOutput; + let words = [ + 0x7E02_02F2, // v_mov_b32 v1, 1.0 + 0x7E04_0287, // v_mov_b32 v2, 7 + 0xF800_020F, + 0x0202_0101, // exp param0, v1, v1, v2, v2 + 0xF800_021F, + 0x0101_0101, // exp param1, v1, v1, v1, v1 + 0xF800_08CF, + 0x0101_0101, // exp pos0, v1, v1, v1, v1 done + S_ENDPGM, + ]; + let output = |row: u8, param: u8| VsOutput { + usage: Usage::Generic, + row, + param, + fp16: false, + pack2: false, + }; + let io = StageIo::Vs { + inputs: vec![], + outputs: vec![output(1, 0), output(2, 1)], + }; + let osg1 = [ + element("SV_Position", 3, 0), + element("TEXCOORD", 0, 1), + SigElement { + index: 1, + ..element("TEXCOORD", 0, 2) + }, + ]; + let linked = link::Linked { + inputs: Vec::new(), + outputs: vec![("TEXCOORD".to_owned(), 0)], + }; + let shader = link::with_linked(linked, || translate_with(HwStage::Vs, &words, io, &[], &osg1)); + let c = Container::parse(&shader.dxil).unwrap(); + let out = signature(c.part(FourCC::OSG1).unwrap().data).unwrap(); + let rows: Vec<(&str, u32, Option)> = out.iter().map(|e| (e.name.as_str(), e.index, e.row)).collect(); + assert_eq!(rows, [("SV_Position", 0, Some(0)), ("TEXCOORD", 1, Some(2))]); + validate(&shader); + } } diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index 10878e891b..07ce7cedaa 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -87,6 +87,7 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result u32 { - let r = x as f32; - if r.is_subnormal() || (r == 0.0 && x != 0.0) { - r.to_bits() & 0x8000_0000 - } else { - r.to_bits() - } -} - +/// 64-bit floats, which the title's water volumetrics count their lanes in: `v_add_f64` and +/// `v_mul_f64` of register pairs (one operand negated, one an inline double), +/// `v_cvt_f64_f32`, and `v_cvt_f32_f64` rounding to nearest (1 + 0.75 of a float's last +/// place becomes 1 + one place). The doubles come in s0..s3 (v1..v4): a in v[1:2], b in +/// v[3:4]. #[test] -#[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"] -fn v_cvt_f32_f64_rounds_to_nearest_even() { - // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f) - let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); - let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0 - let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp - let values = [ - 0.0, - -0.0, - 1.0, - -2.5, - std::f64::consts::PI, - 1.0e-3, - 123_456_789.123, - tie_even, - tie_odd, - 1.0 + f64::from(f32::EPSILON) * 0.75, - f64::from(f32::MAX), - f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity - 1.0e300, - -1.0e300, - 1.0e-40, // a float denormal: flushed - -1.0e-300, - f64::from(f32::MIN_POSITIVE), - f64::INFINITY, - f64::NEG_INFINITY, - f64::NAN, +fn f64_arithmetic_and_conversions_are_ieee() { + let to_f32 = vop1(0x0F, 0, vgpr(5)); // v_cvt_f32_f64 v0, v[5:6] + let d = |a: f64, b: f64| { + let (a, b) = (a.to_bits(), b.to_bits()); + [a as u32, (a >> 32) as u32, b as u32, (b >> 32) as u32] + }; + let with = |first: &[u32]| { + let mut w = first.to_vec(); + w.push(to_f32); + w + }; + let add = with(&vop3(0x164, 5, vgpr(1), vgpr(3), 0)); // v_add_f64 v[5:6], v[1:2], v[3:4] + let neg_mul = with(&vop3_mod(0x165, 5, vgpr(1), vgpr(3), 0, 0, 1, 0, false)); // -a * b + let half = with(&vop3(0x164, 5, 240, vgpr(1), 0)); // v_add_f64 v[5:6], 0.5, v[1:2] + let mut wide = vec![vop1(0x10, 5, vgpr(1))]; // v_cvt_f64_f32 v[5:6], v1 + wide.extend(vop3(0x164, 5, vgpr(5), vgpr(5), 0)); // v_add_f64 v[5:6], v[5:6], v[5:6] + wide.push(to_f32); + let near = 1.0 + 3.0 * 2f64.powi(-25); + let cases: [(&[u32], [u32; 4], f32); 6] = [ + (&add, d(1.5, 2.25), 3.75), + (&add, d(near, 0.0), f32::from_bits(0x3F80_0001)), + (&add, d(1e300, -1e300), 0.0), + (&neg_mul, d(3.0, 0.5), -1.5), + (&half, d(2.0, 0.0), 2.5), + (&wide, [1.25f32.to_bits(), 0, 0, 0], 2.5), ]; - let inputs: Vec<[u32; 4]> = values - .iter() - .map(|x| { - let b = x.to_bits(); - [b as u32, (b >> 32) as u32, 0, 0] - }) - .collect(); - run_cases(&shader, &inputs, |backend, i, _, got| { - let x = values[i]; - if x.is_nan() { - assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); - return; - } - let want = cvt_f32_f64_reference(x); - assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); - }); + for (body, inputs, want) in cases { + let shader = build_valu_cs(body); + run_cases(&shader, &[inputs], |backend, _, _, got| { + assert_eq!(f32::from_bits(got), want, "{backend}: {body:08x?} on {inputs:08x?}"); + }); + } } /// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads @@ -1379,6 +1360,81 @@ fn ds_min_max_f32_are_atomic_across_waves() { } } +const DS_ADD_RTN_U32: u8 = 0x20; +const DS_SUB_RTN_U32: u8 = 0x21; + +/// `buffer_store_dword v, v, s[8:11], 0 offen offset:`. +const fn store_at(data: u8, addr: u8, offset: u16) -> [u32; 2] { + [0xE070_1000 | offset as u32, 0x8002_0000 | (data as u32) << 8 | addr as u32] +} + +/// One console wave of 32 threads takes slots off an LDS counter as the title's +/// `weatherParticle:CS_BeginUpdate` does: `v_sub_nc_u32 v7, 0, v6` then `ds_add_rtn_u32` of +/// that negation (HLSL's `InterlockedAdd(shared, -x)`), and the same with `ds_sub_rtn_u32`. +/// NVIDIA's compiler refuses either as an atomic on group-shared memory (`E_OUTOFMEMORY` at +/// pipeline creation, RTX 5090): the translation's compare-exchange loop gets a pipeline. +/// Thread t takes t ^ s1 (s1 = 0x100, unknown to any compiler: the negation stays one) from +/// 1,000,000; each must get the counter as it stood before its own subtraction, in some +/// order of the threads, and the counter must end at the total. +#[test] +fn lds_subtractions_get_a_pipeline_and_stay_atomic() { + const INIT: u32 = 1_000_000; + const S1: u32 = 0x100; + for (op, negate, what) in [(DS_ADD_RTN_U32, true, "ds_add_rtn_u32 of 0 - x"), (DS_SUB_RTN_U32, false, "ds_sub_rtn_u32")] { + let mut body = vec![vop1(0x001, 5, 0x80)]; // v_mov_b32 v5, 0: the counter's address + body.extend(ds(DS_WRITE_B32, 0, 5, 1)); // the counter = s0 (every thread the same) + body.push(S_BARRIER); + body.push(vop2(0x1D, 6, sgpr(1), 0)); // v_xor_b32 v6, s1, v0: x = t ^ s1 + body.push(vop2(0x26, 7, 0x80, 6)); // v_sub_nc_u32 v7, 0, v6: -x + body.extend(ds(op, 2, 5, if negate { 7 } else { 6 })); // v2: the counter found + body.push(vop2(0x1A, 3, 0x82, 0)); // v_lshlrev_b32 v3, 2, v0 + body.extend(store_at(2, 3, 4)); // dword t + 1: what thread t got + body.push(S_BARRIER); + body.extend(ds(DS_READ_B32, 0, 5, 0)); // dword 0: the counter at the end + let shader = build_cs(&body, 32, 512); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return; + }; + // (the refusal this is about: a pipeline must be made) + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{what}: compute_pipeline failed: {e}")); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=1) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = [INIT, S1][d as usize]; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(33)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{what}: dispatch failed: {e}")); + let got = &out[0]; + // In the order the subtractions took effect (largest counter first), each thread + // found what the one before left. + let mut order: Vec<(u32, u32)> = (0..32).map(|t| (got[t as usize + 1], t ^ S1)).collect(); + order.sort_unstable_by(|a, b| b.cmp(a)); + let mut counter = INIT; + for (old, x) in order { + assert_eq!(old, counter, "{what}: the thread taking {x} found {old}, the counter stood at {counter}"); + counter -= x; + } + assert_eq!(got[0], counter, "{what}: the counter at the end"); + assert_eq!(counter, INIT - (0..32).map(|t| t ^ S1).sum::()); + } + eprintln!("ran on the hardware device: LDS subtractions as compare-exchange loops, atomic"); +} + #[test] fn v_cmp_class_f16_matches_rdna2() { // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 1d7a91b7f4..df6013422b 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -112,17 +112,120 @@ pub(crate) enum Sym { ident: u32, lanes: u64, }, - /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over - /// `lanes` of `mask ? f64(lo, hi) : 0.0`. - Red64F { + /// The low (`high` clear) or high dword of the 64-bit float sum (`v_add_f64`) over + /// `lanes` of `mask ? (lo, hi) : 0.0`, the double whose dwords are `lo` and `hi`. + Half64 { + high: bool, lo: Value, hi: Value, mask: Value, lanes: u64, - high: bool, }, } +/// Both dwords of a 64-bit float in one lane, as [`add64`] takes them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Pair { + /// +0.0, the sum's identity. + Zero, + /// The sum over `lanes` of `mask ? (lo, hi) : 0.0` (one lane's own value when `lanes` is + /// that lane). + Sum { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + }, +} + +impl Pair { + /// The pair a lane's two dwords hold, if they are one. + fn of(lo: Sym, hi: Sym) -> Option { + match (lo, hi) { + (Sym::K(0), Sym::K(0)) => Some(Pair::Zero), + // a lane's own masked value: both dwords picked by one mask, beside +0.0 + ( + Sym::Red { + op: None, + src: lo, + mask, + ident: 0, + lanes, + }, + Sym::Red { + op: None, + src: hi, + mask: m, + ident: 0, + lanes: l, + }, + ) if (mask, lanes) == (m, l) => Some(Pair::Sum { lo, hi, mask, lanes }), + ( + Sym::Half64 { + high: false, + lo, + hi, + mask, + lanes, + }, + Sym::Half64 { + high: true, + lo: l2, + hi: h2, + mask: m2, + lanes: n2, + }, + ) if (lo, hi, mask, lanes) == (l2, h2, m2, n2) => Some(Pair::Sum { lo, hi, mask, lanes }), + _ => None, + } + } + + /// The lane's two dwords. + fn syms(self) -> (Sym, Sym) { + match self { + Pair::Zero => (Sym::K(0), Sym::K(0)), + Pair::Sum { lo, hi, mask, lanes } => { + let half = |high| Sym::Half64 { + high, + lo, + hi, + mask, + lanes, + }; + (half(false), half(true)) + } + } + } +} + +/// The 64-bit float sum of two pairs: of the same terms over lanes that do not meet, or one +/// of them +0.0. +fn add64(a: Pair, b: Pair) -> Option { + match (a, b) { + (Pair::Zero, x) | (x, Pair::Zero) => Some(x), + ( + Pair::Sum { + lo, + hi, + mask, + lanes: la, + }, + Pair::Sum { + lo: l2, + hi: h2, + mask: m2, + lanes: lb, + }, + ) if (lo, hi, mask) == (l2, h2, m2) && la & lb == 0 => Some(Pair::Sum { + lo, + hi, + mask, + lanes: la | lb, + }), + _ => None, + } +} + /// What a value a section leaves holds in every lane. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum Shape { @@ -132,10 +235,16 @@ pub(crate) enum Shape { Masked(Value, Value, u32), /// `op` over every lane. Active(Op, Value, Value, u32), - /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. - ActiveF64(Value, Value, Value, bool), /// `op` over the lanes below (`inclusive`: and including) each lane. Prefix(Op, Value, Value, u32, bool), + /// The low (`high` clear) or high dword of the 64-bit float sum over every lane of the + /// lane's own `mask ? (lo, hi) : 0.0`. + Sum64 { + high: bool, + lo: Value, + hi: Value, + mask: Value, + }, } /// The section starting at instruction `start` of a block: its restore @@ -233,7 +342,8 @@ fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> { fn combine(op: Op, a: Sym, b: Sym) -> Sym { match (a, b) { - (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x, + // (a dword of a 64-bit sum is no 32-bit term: not even a float's identity keeps it) + (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) && !matches!(x, Sym::Half64 { .. }) => x, ( Sym::Red { op: oa, @@ -316,6 +426,9 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { { masked.push(w); } + // A scalar copied: what its source holds (a dword of a 64-bit sum read from a lane + // and moved to the register the code reads it from, `s_mov_b32 s20, s18` after + // `v_readlane_b32 s18, v2, 0`; a value from before the section; a constant). if name == "s_mov_b32" && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) && *dc != NULL @@ -331,6 +444,19 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { }; uni.insert(w, sym); } + // both dwords of a 64-bit sum moved at once + if name == "s_mov_b64" + && inst.reads.len() == inst.writes.len() + && inst + .reads + .iter() + .all(|r| matches!(r.0, Reg::S(_)) && matches!(uni.get(&r.1), Some(Sym::Half64 { .. }))) + { + for (w, r) in inst.writes.iter().zip(&inst.reads) { + let s = uni[&r.1]; + uni.insert(w.1, s); + } + } for &(_, w) in &inst.writes { uni.entry(w).or_insert(Sym::Unknown); } @@ -365,6 +491,50 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } }; let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some(); + if name == "v_add_f64" { + // Each lane adds its two pairs of dwords; a sum the simulation does not follow + // leaves both dwords unknown. + let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { + continue; + }; + let pair = |op: Option<&Operand>| -> Vec> { + let (lo, hi) = match op { + Some(&Operand::Vector { reg, .. }) => ( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes(&Operand::Vector { reg: reg + 1, dwords: 1 }, &vec, &uni), + ), + Some(&Operand::Scalar { code, .. }) if code != NULL => ( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes(&Operand::Scalar { code: code + 1, dwords: 1 }, &vec, &uni), + ), + Some(&Operand::Const(128)) => (vec![Sym::K(0); wave as usize], vec![Sym::K(0); wave as usize]), + _ => return vec![None; wave as usize], + }; + lo.into_iter().zip(hi).map(|(l, h)| Pair::of(l, h)).collect() + }; + let (a, b) = (pair(v.src.first()), pair(v.src.get(1))); + let follows = !modifiers && v.dpp.is_none(); + let old = |r: u8| lanes(&Operand::Vector { reg: r, dwords: 1 }, &vec, &uni); + let (old_lo, old_hi) = (old(dreg), old(dreg + 1)); + let (mut lo, mut hi) = (Vec::with_capacity(wave as usize), Vec::with_capacity(wave as usize)); + for l in 0..wave as usize { + let sum = match (a[l], b[l]) { + (Some(x), Some(y)) if follows => add64(x, y), + _ => None, + }; + let (sl, sh) = sum.map_or((Sym::Unknown, Sym::Unknown), Pair::syms); + let writes = exec >> l & 1 != 0; + lo.push(if writes { sl } else { old_lo[l] }); + hi.push(if writes { sh } else { old_hi[l] }); + } + if let Some(w) = inst.write(Reg::V(dreg)) { + vec.insert(w, lo); + } + if let Some(w) = inst.write(Reg::V(dreg + 1)) { + vec.insert(w, hi); + } + continue; + } if name == "v_readlane_b32" { let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) = (v.dst, v.src.first(), v.src.get(1)) @@ -385,130 +555,6 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { } continue; } - if name == "v_add_f64" - && !modifiers - && v.dpp.is_none() - && let Some(Operand::Vector { reg: dreg, .. }) = v.dst - && let (Some(dst_lo), Some(dst_hi)) = - (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) - { - let pair_lanes = |op: Option<&Operand>| -> Option<(Vec, Vec)> { - match *op? { - Operand::Vector { reg, .. } => Some(( - lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), - lanes( - &Operand::Vector { - reg: reg + 1, - dwords: 1, - }, - &vec, - &uni, - ), - )), - Operand::Scalar { code, .. } if code != NULL => Some(( - lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), - lanes( - &Operand::Scalar { - code: code + 1, - dwords: 1, - }, - &vec, - &uni, - ), - )), - _ => None, - } - }; - let old_lo = lanes( - &Operand::Vector { - reg: dreg, - dwords: 1, - }, - &vec, - &uni, - ); - let old_hi = lanes( - &Operand::Vector { - reg: dreg + 1, - dwords: 1, - }, - &vec, - &uni, - ); - let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { - match (lo_s, hi_s) { - ( - Sym::Red { - op: None, - src: lo, - mask: ml, - ident: 0, - lanes: ll, - }, - Sym::Red { - op: None, - src: hi, - mask: mh, - ident: 0, - lanes: lh, - }, - ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), - ( - Sym::Red64F { - lo: lo1, - hi: hi1, - mask: m1, - lanes: l1, - high: false, - }, - Sym::Red64F { - lo: lo2, - hi: hi2, - mask: m2, - lanes: l2, - high: true, - }, - ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), - _ => None, - } - }; - let mut out_lo = vec![Sym::Unknown; wave as usize]; - let mut out_hi = vec![Sym::Unknown; wave as usize]; - if let (Some((alo, ahi)), Some((blo, bhi))) = - (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) - { - for l in 0..wave as usize { - let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { - (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) - if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => - { - ( - Sym::Red64F { - lo: lo1, - hi: hi1, - mask: m1, - lanes: la | lb, - high: false, - }, - Sym::Red64F { - lo: lo1, - hi: hi1, - mask: m1, - lanes: la | lb, - high: true, - }, - ) - } - _ => (Sym::Unknown, Sym::Unknown), - }; - out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; - out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; - } - } - vec.insert(dst_lo, out_lo); - vec.insert(dst_hi, out_hi); - continue; - } let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { for &(_, w) in &inst.writes { uni.insert(w, Sym::Unknown); @@ -710,13 +756,13 @@ fn shapes( ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), - Sym::Red64F { + Sym::Half64 { + high, lo, hi, mask, lanes, - high, - } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), + } if lanes == all => Some(Shape::Sum64 { high, lo, hi, mask }), _ => None, }; for (v, s) in uni { @@ -760,13 +806,13 @@ fn per_lane(lanes: &[Sym], all: u64) -> Option { ident, lanes, } if lanes == all => Some(Shape::Active(op, src, mask, ident)), - Sym::Red64F { + Sym::Half64 { + high, lo, hi, mask, lanes, - high, - } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), + } if lanes == all => Some(Shape::Sum64 { high, lo, hi, mask }), _ => None, }; } diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index c9a42af7ac..881f09c330 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -1,7 +1,10 @@ //! A console wave64 compute program on a host of 32-lane waves: a wave reduction inside a //! per-lane branch, with that branch taken wave-wide ([`crate::structure::structure_wide`]) -//! so that the two host waves can exchange their halves inside it. Lowered, validated by -//! `dxil.dll` when present, and run on the host GPU when it takes waves of 32. +//! so that the two host waves can exchange their halves inside it; and programs in the +//! paired form (one host wave for each console wave, two lanes a thread: `super::paired`), +//! whose LDS, lane reads and masks cross the halves without barriers, checked against what +//! the console's 64 lanes compute. Lowered, validated by `dxil.dll` when present, and run on +//! the host GPU when it takes waves of 32 (WARP's are 4 lanes: neither form runs there). use std::collections::HashSet; @@ -46,6 +49,11 @@ fn native(body: &[u32]) -> NativeProgram { /// The same for a console of 32-lane waves when `wave64` is not set, with `threads` threads. fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { + native_with(body, wave64, threads, 0) +} + +/// [`native_of`] with `lds` bytes of LDS (512-byte granules). +fn native_with(body: &[u32], wave64: bool, threads: u32, lds: u32) -> NativeProgram { let mut words = vec![ 0xBE85_0380, // s_mov_b32 s5, 0 0x3D << 26 | 0x02 << 18 | 8 << 6 | 2, @@ -86,7 +94,7 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { slot: 1, }], io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + rsrc2: 5 << 1 | lds.div_ceil(512) << 15, // 5 user SGPRs: s0..s4 threads: [threads, 1, 1], }), code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), @@ -226,10 +234,11 @@ fn copied_mask_keeps_both_numeric_words_inside_a_lane_branch() { eprintln!("four native wave64 low/high word readbacks passed"); } -#[test] -fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { - // thread t holds the 16-bit float with bits 0x3C00 + 37 t (1.0 and up, with odd - // mantissas, so that additions round); all of them store the wave's sum +/// 64 threads in one console wave: thread t holds the 16-bit float with bits 0x3C00 + 37 t +/// (1.0 and up, with odd mantissas, so that additions round); all of them store the wave's sum +/// (`WaveActiveSum` of halves) to dword 0. With the console's sum (its tree) and the terms' +/// sum added in a row, which differs from it. +fn half_sum_program() -> (NativeProgram, u16, u16) { let mut words = vec![ 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 @@ -245,14 +254,6 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { 0x38 << 26 | 0x1C << 18, 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 ]); - let native = native(&words); - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); - let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - let mut copy = shader.dxil.clone(); - v.validate(&mut copy).expect("DXIL validation failed"); - } // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits // (to nearest, ties to even); values here are normal numbers let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); @@ -269,7 +270,20 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); } let in_a_row = terms.iter().copied().reduce(add).unwrap(); - assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order"); + (native(&words), tree[0], in_a_row) +} + +#[test] +fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { + let (native, tree, in_a_row) = half_sum_program(); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); + let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + assert_ne!(tree, in_a_row, "these terms tell the tree from another order"); let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let Ok(host) = Host::new(false) else { eprintln!("no SM 6.6 hardware device; not run"); @@ -296,8 +310,8 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { ) .unwrap_or_else(|e| panic!("dispatch failed: {e}")); // (the high half is lane 0's term's: zero) - assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]); - eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); + assert_eq!(out[0][0], u32::from(tree), "tree {tree:#x}, in a row {in_a_row:#x}"); + eprintln!("ran on the hardware device: the sum {tree:#x} of the console's tree"); } /// One `v_add_f16` whose exact result lies between two halves: 1 + 3/1024 (0x3C03) plus 2 @@ -666,3 +680,621 @@ fn an_lds_addition_of_a_negated_value_is_a_compare_exchange_loop() { assert_eq!(got, expected, "{name}"); } } + +/// One console wave of 64 threads, thread t holding t + 1. A branch on s0 (the wave's) picks +/// `WaveActiveMax` (s0 not 0) or `WaveActiveMin`, and the two reductions share their end: +/// each arm saves EXEC and reduces up to the read of lane 32, the join reads lane 0 and +/// restores EXEC (`deferred_tiled:CS_WaterTransmittanceOpticalDepthProcessing`, 0xb3c-0xbe0). +/// Neither block holds a whole section; `v_permlanex16_b32` lowered on its own reads the lanes +/// the host has, so the translation is the one with the join's code in each arm +/// ([`ir::whole_sections`]), where each section is whole. +#[test] +fn two_reductions_that_share_their_end_translate_as_two_sections() { + // an arm: save EXEC, the identity `init`, then `op` over the wave up to lane 32's read + let arm = |init: u32, op: u32| { + let mut w = vec![ + 0xBE8C_25C1, // s_or_saveexec_b64 s[12:13], -1 + 0x7E04_02FF, + init, // v_mov_b32 v2, init + 0xD501_0002, + 0x0032_0902, // v_cndmask_b32 v2, v2, v4, s[12:13] + ]; + for dpp in [0xDE54_C102, 0x9360_1202, 0x0009_2402] { + w.extend([op << 25 | 0x0004_04E9, dpp]); // v__f32 v2, v2, v2 dpp8:[...] + } + w.extend([ + op << 25 | 0x0004_04FA, + 0xFF09_4002, // v__f32 v2, v2, v2 row_mirror bound_ctrl:1 + 0xD778_0003, + 0x0201_0102, // v_permlanex16_b32 v3, v2, 0, 0 + op << 25 | 0x0004_0503, // v__f32 v2, v3, v2 + 0xD760_000E, + 0x0001_4102, // v_readlane_b32 s14, v2, 32 + op << 25 | 0x0004_040E, // v__f32 v2, s14, v2 + ]); + w + }; + let mut words = vec![ + 0x7E08_0D00, // v_cvt_f32_u32 v4, v0 + 0x0608_08F2, // v_add_f32 v4, 1.0, v4 + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 + 0xBF85_0014, // s_cbranch_scc1 to the minimum + ]; + words.extend(arm(0xFF80_0000, 0x10)); // the maximum from -inf + words.push(0xBF82_0013); // s_branch to the join + words.extend(arm(0x7F80_0000, 0x0F)); // the minimum from +inf + words.extend([ + 0xD760_000E, + 0x0001_0102, // v_readlane_b32 s14, v2, 0 + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0x7E00_020E, // v_mov_b32 v0, s14 + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + // the section starts in the arms and ends in the join; afterwards each block holds whole ones + let sections = |p: &ir::Program| (0..p.blocks.len()).map(|b| super::wave::sections(p, b).len()).sum::(); + assert_eq!(sections(&p), 0); + let q = ir::whole_sections(&p).expect("sections to join"); + assert_eq!(sections(&q), 2); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let st_q = structure::structure(&q).expect("structure"); + let io_q = io::raise(&q, &native).expect("io::raise"); + let res_q = resource::track(&q, &native.layout, native.stage, Some(&st_q)).expect("track"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let joined = super::emit_any(&c, &native, &q, &st_q, &io_q, &res_q); + let shader = super::emit(&c, &native, &p, &st, &io, &res); + lower::TEST_HOST_WAVE.set(was); + let shader = shader.expect("emit"); + let joined = joined.expect("the joined sections"); + assert!(shader.dxil == joined.dxil, "the split sections' translation was taken"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for (s0, expected) in [(1u32, 64.0f32), (0, 1.0)] { + let Some(got) = on_the_card(&shader, [s0, 0]) else { return }; + assert_eq!(f32::from_bits(got), expected, "s0 = {s0}"); + } + eprintln!("ran on the hardware device: the maximum or the minimum over the console's 64 lanes"); +} + +/// One console wave of 64 threads summing doubles over the lanes below s0 as the title's +/// water volumetrics count their lanes (`water_shading:CS_TransmissionVolumetrics`, +/// 0x5c4-0x68c): `v_add_f64` of each dword pair moved by DPP, `v_permlanex16` and lane 32, +/// the sum moved to s[20:21] and taken back as a float (`v_cvt_f32_f64`). The terms here are +/// the thread index as a double (`v_cvt_f64_f32`), so the sum is s0 (s0 - 1) / 2. +#[test] +fn a_wave_sum_of_doubles_is_the_consoles() { + let mut words = vec![ + 0x7E3E_0D00, // v_cvt_f32_u32 v31, v0 + 0x7E3A_211F, // v_cvt_f64_f32 v[29:30], v31 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_046A, // s_mov_b64 s[12:13], vcc + 0xBE90_25C1, // s_or_saveexec_b64 s[16:17], -1 + 0x7E04_0280, // v_mov_b32 v2, 0 + 0x7E06_0280, // v_mov_b32 v3, 0 + 0x8792_100C, // s_and_b64 s[18:19], s[12:13], s[16:17] + 0xD501_0002, + 0x004A_3B02, // v_cndmask_b32 v2, v2, v29, s[18:19] + 0xD501_0003, + 0x004A_3D03, // v_cndmask_b32 v3, v3, v30, s[18:19] + ]; + // v_mov_b32 v4, v2 / v5, v3 with each DPP pattern, then v_add_f64 v[2:3], v[4:5], v[2:3] + for (code, dpp) in [(0xE9, 0xDE54_C100), (0xE9, 0x9360_1200), (0xE9, 0x0009_2400), (0xFA, 0xFF09_4000)] { + words.extend([0x7E08_0200 | code, dpp | 2, 0x7E0A_0200 | code, dpp | 3, 0xD564_0002, 0x0002_0504]); + } + words.extend([ + 0xD778_0004, + 0x0201_0102, // v_permlanex16_b32 v4, v2, 0, 0 + 0xD778_0005, + 0x0201_0103, // v_permlanex16_b32 v5, v3, 0, 0 + 0xD564_0002, + 0x0002_0504, // v_add_f64 v[2:3], v[4:5], v[2:3] + 0xD760_0012, + 0x0001_4102, // v_readlane_b32 s18, v2, 32 + 0xD760_0013, + 0x0001_4103, // v_readlane_b32 s19, v3, 32 + 0xD564_0002, + 0x0002_0412, // v_add_f64 v[2:3], s[18:19], v[2:3] + 0xD760_0012, + 0x0001_0102, // v_readlane_b32 s18, v2, 0 + 0xD760_0013, + 0x0001_0103, // v_readlane_b32 s19, v3, 0 + 0xBE94_0312, // s_mov_b32 s20, s18 + 0xBE95_0313, // s_mov_b32 s21, s19 + 0xBEFE_0410, // s_mov_b64 exec, s[16:17] + 0x7E00_1E14, // v_cvt_f32_f64 v0, s[20:21] + 0x38 << 26 | 0x1C << 18, + 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 + ]); + let native = native(&words); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + // the section leaves the sum's two dwords in s20 and s21 + let block = (0..p.blocks.len()).find(|&b| !super::wave::sections(&p, b).is_empty()).expect("a section"); + let sums = super::wave::sections(&p, block) + .into_values() + .flat_map(|s| s.shapes.into_values()) + .filter(|s| matches!(s, super::wave::Shape::Sum64 { .. })) + .count(); + assert!(sums >= 2, "{sums} dwords of 64-bit sums"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let shader = super::emit(&c, &native, &p, &st, &io, &res); + lower::TEST_HOST_WAVE.set(was); + let shader = shader.expect("emit"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for s0 in [64u32, 40, 33, 1, 0] { + let Some(got) = on_the_card(&shader, [s0, 0]) else { return }; + let want = (s0 * s0.saturating_sub(1) / 2) as f32; + assert_eq!(f32::from_bits(got), want, "the lanes below {s0}"); + } + eprintln!("ran on the hardware device: the sums of doubles over the console's 64 lanes"); +} + +// ---- the paired form: a host wave of 32 for each console wave, two lanes a thread ---- + +// Operands as the hardware numbers them: SGPR n is n, VCC 106 (its high dword 107), EXEC 126, +// an inline integer n 128 + n (-1: 193), a literal (the next dword) 255, VGPR n 256 + n. +const VCC: u32 = 106; +const EXEC: u32 = 126; +const LIT: u32 = 255; + +const fn v(n: u32) -> u32 { + 256 + n +} + +const fn k(n: u32) -> u32 { + 128 + n +} + +const fn sop1(op: u32, sdst: u32, src0: u32) -> u32 { + 0xBE80_0000 | sdst << 16 | op << 8 | src0 +} + +const fn sop2(op: u32, sdst: u32, src0: u32, src1: u32) -> u32 { + 0x8000_0000 | op << 23 | sdst << 16 | src1 << 8 | src0 +} + +/// A branch by `imm` dwords from the next instruction (or `s_barrier`, `imm` 0). +const fn sopp(op: u32, imm: i16) -> u32 { + 0xBF80_0000 | op << 16 | imm as u16 as u32 +} + +const fn vop1(op: u32, vdst: u32, src0: u32) -> u32 { + 0x7E00_0000 | vdst << 17 | op << 9 | src0 +} + +const fn vop2(op: u32, vdst: u32, src0: u32, vsrc1: u32) -> u32 { + op << 25 | vdst << 17 | vsrc1 << 9 | src0 +} + +const fn vopc(op: u32, src0: u32, vsrc1: u32) -> u32 { + 0x7C00_0000 | op << 17 | vsrc1 << 9 | src0 +} + +const fn vop3(op: u32, dst: u32, src0: u32, src1: u32) -> [u32; 2] { + [0xD400_0000 | op << 16 | dst, src0 | src1 << 9] +} + +const fn ds(op: u32, vdst: u32, addr: u32, data: u32, offset: u32) -> [u32; 2] { + [0xD800_0000 | op << 18 | offset, vdst << 24 | data << 8 | addr] +} + +/// `buffer_store_dword v, v, s[8:11], 0 offen offset:` +const fn store(data: u32, addr: u32, offset: u32) -> [u32; 2] { + [0xE070_1000 | offset, 0x8002_0000 | data << 8 | addr] +} + +/// `v` stored as each thread's dwords of the UAV, the thread's index (v0) times 16 on. +fn stores(regs: [u32; 4]) -> Vec { + let mut w = vec![vop2(0x1A, 15, k(4), 0)]; // v_lshlrev_b32 v15, 4, v0 + for (n, r) in regs.into_iter().enumerate() { + w.extend(store(r, 15, 4 * n as u32)); + } + w +} + +/// `native` in the paired form on a host of 32-lane waves, validated by `dxil.dll` when +/// present. Where no other form gives the host the program (each still asks for 64-lane +/// waves, or fails), it is also what [`super::emit`] gives it. +fn paired(native: &NativeProgram) -> HostShader { + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let others = super::emit_forms(&c, native, &p, &st, &io, &res); + let shader = super::paired(&c, native, &p, &io, &res); + let chosen = super::emit(&c, native, &p, &st, &io, &res); + lower::TEST_HOST_WAVE.set(was); + let (shader, wave) = shader.expect("the paired form"); + assert_eq!(wave, Some(32)); + if !matches!(others, Ok((_, wave)) if wave != Some(64)) { + assert_eq!(chosen.expect("emit").dxil, shader.dxil, "emit's choice"); + } + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + shader +} + +/// `shader` on the hardware device: one group, root constants `s0..s3`, a raw UAV of `dwords` +/// zeroed dwords, which come back; None (and a line) without a device that takes it. +fn run_paired(shader: &HostShader, constants: [u32; 4], dwords: u32) -> Option> { + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 hardware device; not run"); + return None; + }; + let (root, pso) = match host.compute_pipeline(shader) { + Ok(x) => x, + Err(e) => { + eprintln!("the hardware device does not take this program: {e}; not run"); + return None; + } + }; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if let (RootType::Constants, 0, d @ 0..=3) = (u.root, u.slot, u.dword) { + ud[u.index as usize] = constants[d as usize]; + } + } + let mut out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(ud))], + views: &[View::RawUav(dwords)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("dispatch failed: {e}")); + Some(out.swap_remove(0)) +} + +/// Panics at the first dword of `got` that is not the console's (`want`), naming the thread +/// and which of its four dwords. +fn same_as_console(got: &[u32], want: &[u32]) { + assert_eq!(got.len(), want.len()); + if let Some(n) = (0..want.len()).find(|&n| got[n] != want[n]) { + panic!("thread {}, dword {}: {:#x}, the console's {:#x}", n / 4, n % 4, got[n], want[n]); + } +} + +/// One console wave of 64 threads with 256 bytes of LDS. The even lanes write their dword in +/// one arm of a per-lane branch; the odd lanes theirs in the other arm, then, in that arm and +/// with no barrier, read their mirror lane's (63 - n, an even lane's); the even lanes read +/// theirs (an odd lane's) after the join. Then lanes 5 and 40 are read (`v_readlane_b32`), the +/// lanes holding more than 250 are counted (`s_bcnt1_i32_b64` of the compare's mask) and +/// counted below each lane (`v_mbcnt_lo/hi`): each of these takes lanes of both halves. +#[test] +fn paired_lanes_share_lds_and_lanes_across_halves_without_barriers() { + let mut w = vec![vop2(0x1A, 1, k(2), 0)]; // v_lshlrev_b32 v1, 2, v0: this lane's dword + w.extend(vop3(0x169, 2, v(0), k(7))); // v_mul_lo_u32 v2, v0, 7 + w.extend([ + vop2(0x26, 5, k(63), 0), // v_sub_nc_u32 v5, 63, v0: the mirror lane + vop2(0x1A, 5, k(2), 5), // v_lshlrev_b32 v5, 2, v5: its dword + vop2(0x1B, 3, k(1), 0), // v_and_b32 v3, 1, v0 + vopc(0xC2, k(0), 3), // v_cmp_eq_u32 vcc, 0, v3: the even lanes + sop1(0x24, 12, VCC), // s_and_saveexec_b64 s[12:13], vcc + sopp(0x08, 4), // s_cbranch_execz past the even lanes' arm + vop2(0x25, 4, LIT, 2), // v_add_nc_u32 v4, 100, v2 + 100, + ]); + w.extend(ds(0x0D, 0, 1, 4, 0)); // ds_write_b32 v1, v4 + w.extend([ + sop2(0x15, EXEC, 12, EXEC), // s_andn2_b64 exec, s[12:13], exec: the odd lanes + sopp(0x08, 6), // s_cbranch_execz past their arm + vop2(0x25, 4, LIT, 2), // v_add_nc_u32 v4, 200, v2 + 200, + ]); + w.extend(ds(0x0D, 0, 1, 4, 0)); // ds_write_b32 v1, v4 + w.extend(ds(0x36, 6, 5, 0, 0)); // ds_read_b32 v6, v5: an even lane's, from the other arm + w.extend([ + sop1(0x04, EXEC, 12), // s_mov_b64 exec, s[12:13] + sop1(0x24, 12, VCC), // s_and_saveexec_b64 s[12:13], vcc: the even lanes again + ]); + w.extend(ds(0x36, 6, 5, 0, 0)); // ds_read_b32 v6, v5: an odd lane's + w.push(sop1(0x04, EXEC, 12)); // s_mov_b64 exec, s[12:13] + w.extend(vop3(0x360, 14, v(6), k(5))); // v_readlane_b32 s14, v6, 5 + w.extend(vop3(0x360, 15, v(6), k(40))); // v_readlane_b32 s15, v6, 40 + w.extend([ + sop2(0x00, 14, 14, 15), // s_add_u32 s14, s14, s15 + vopc(0xC1, LIT, 6), // v_cmp_lt_u32 vcc, 250, v6 + 250, + sop1(0x10, 16, VCC), // s_bcnt1_i32_b64 s16, vcc + ]); + w.extend(vop3(0x365, 7, VCC, k(0))); // v_mbcnt_lo_u32_b32 v7, vcc_lo, 0 + w.extend(vop3(0x366, 7, VCC + 1, v(7))); // v_mbcnt_hi_u32_b32 v7, vcc_hi, v7 + w.extend([ + vop1(0x01, 9, 14), // v_mov_b32 v9, s14 + vop1(0x01, 10, 16), // v_mov_b32 v10, s16 + ]); + w.extend(stores([6, 9, 10, 7])); + let shader = paired(&native_with(&w, true, 64, 256)); + // the console: lane n's dword is 7n + 100 (even n) or 7n + 200, and lane n reads 63 - n's + let dword = |n: u32| 7 * n + if n.is_multiple_of(2) { 100 } else { 200 }; + let read: Vec = (0..64).map(|n| dword(63 - n)).collect(); + let big = (0..64).filter(|&n| read[n] > 250).fold(0u64, |m, n| m | 1 << n); + assert!(big as u32 != 0 && big >> 32 != 0, "lanes of both halves counted"); + let want: Vec = (0..64) + .flat_map(|n| [read[n], read[5] + read[40], big.count_ones(), (big & ((1 << n) - 1)).count_ones()]) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = run_paired(&shader, [0; 4], 256) else { return }; + same_as_console(&got, &want); + eprintln!("ran on the hardware device: LDS, lane reads and masks across the halves as on the console"); +} + +/// Two console waves of 64 in a group of 128 (two host waves of 32, 512 bytes of LDS). In +/// each, lane 0 zeroes the wave's dword of LDS; every lane loops (lane & 3) + 1 + wave times, +/// adding its lane number to its sum and 1 to the wave's dword each round (`ds_add_u32`; the +/// loop's branch is the wave's: it goes round while some lane is left); after the loop each +/// lane reads the wave's total, with no barrier; lanes 40-63 read their first lane's sum +/// (`v_readfirstlane_b32`: lane 40, an upper lane), then lanes 20-63 (lane 20, a lower one, +/// though upper lanes have one too); past the barrier, each lane reads the other wave's total. +#[test] +fn paired_lanes_loop_apart_and_meet_the_other_wave_at_the_barrier() { + let mut w = vec![ + vop2(0x16, 1, k(6), 0), // v_lshrrev_b32 v1, 6, v0: the console wave + vop2(0x1B, 2, k(63), 0), // v_and_b32 v2, 63, v0: the lane in it + vop2(0x1A, 11, k(2), 1), // v_lshlrev_b32 v11, 2, v1: the wave's dword + vop1(0x01, 12, k(0)), // v_mov_b32 v12, 0 + sop1(0x04, 22, EXEC), // s_mov_b64 s[22:23], exec + vopc(0xD2, k(0), 2), // v_cmpx_eq_u32 exec, 0, v2: lane 0 + ]; + w.extend(ds(0x0D, 0, 11, 12, 0)); // ds_write_b32 v11, v12 + w.extend([ + sop1(0x04, EXEC, 22), // s_mov_b64 exec, s[22:23] + vop2(0x1B, 3, k(3), 2), // v_and_b32 v3, 3, v2 + vop2(0x25, 3, k(1), 3), // v_add_nc_u32 v3, 1, v3 + vop2(0x25, 3, v(1), 3), // v_add_nc_u32 v3, v1, v3: the rounds + vop1(0x01, 4, k(0)), // v_mov_b32 v4, 0 + vop1(0x01, 13, k(1)), // v_mov_b32 v13, 1 + sop1(0x04, 20, EXEC), // s_mov_b64 s[20:21], exec + vop2(0x25, 4, v(2), 4), // loop: v_add_nc_u32 v4, v2, v4 + ]); + w.extend(ds(0x00, 0, 11, 13, 0)); // ds_add_u32 v11, v13 + w.extend([ + vop2(0x25, 3, 193, 3), // v_add_nc_u32 v3, -1, v3 + vopc(0xC5, k(0), 3), // v_cmp_ne_u32 vcc, 0, v3 + sop2(0x0F, EXEC, EXEC, VCC), // s_and_b64 exec, exec, vcc + sopp(0x09, -7), // s_cbranch_execnz loop + sop1(0x04, EXEC, 20), // s_mov_b64 exec, s[20:21] + ]); + w.extend(ds(0x36, 5, 11, 0, 0)); // ds_read_b32 v5, v11: the wave's total + w.extend([ + sop1(0x04, 24, EXEC), // s_mov_b64 s[24:25], exec + vopc(0xD1, k(39), 2), // v_cmpx_lt_u32 exec, 39, v2: lanes 40-63 + vop1(0x02, 6, v(4)), // v_readfirstlane_b32 s6, v4 + sop1(0x04, EXEC, 24), // s_mov_b64 exec, s[24:25] + vopc(0xD1, k(19), 2), // v_cmpx_lt_u32 exec, 19, v2: lanes 20-63 + vop1(0x02, 7, v(4)), // v_readfirstlane_b32 s7, v4 + sop1(0x04, EXEC, 24), // s_mov_b64 exec, s[24:25] + vop1(0x01, 6, 6), // v_mov_b32 v6, s6 + vop1(0x01, 9, 7), // v_mov_b32 v9, s7 + 0xD400_0000 | 0x346 << 16 | 6, // v_lshl_add_u32 v6, v9, 16, v6 + v(9) | k(16) << 9 | v(6) << 18, + sopp(0x0A, 0), // s_barrier + vop2(0x1D, 14, k(4), 11), // v_xor_b32 v14, 4, v11: the other wave's dword + ]); + w.extend(ds(0x36, 7, 14, 0, 0)); // ds_read_b32 v7, v14 + w.extend(stores([4, 5, 6, 7])); + let shader = paired(&native_with(&w, true, 128, 512)); + let rounds = |wave: u32, lane: u32| (lane & 3) + 1 + wave; + let total = |wave: u32| (0..64).map(|lane| rounds(wave, lane)).sum::(); + let first = |wave: u32, lane: u32| lane * rounds(wave, lane); + let want: Vec = (0..128) + .flat_map(|t| { + let (wave, lane) = (t / 64, t % 64); + [first(wave, lane), total(wave), first(wave, 20) << 16 | first(wave, 40), total(1 - wave)] + }) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = run_paired(&shader, [0; 4], 512) else { return }; + same_as_console(&got, &want); + eprintln!("ran on the hardware device: two console waves, their loops and LDS as on the console"); +} + +/// One console wave: `ds_bpermute_b32` from the mirror lane; a DPP row shift whose row mask +/// leaves rows 0 and 3 alone (rows 2 and 3 are lanes 32-63: rows are counted in console lanes); a +/// `ds_swizzle_b32` swapping the two 16-lane rows of each 32 lanes; `v_writelane_b32` of s0 +/// into lane 45. +#[test] +fn paired_lanes_permute_shift_and_write_lanes_of_both_halves() { + let mut w = vop3(0x169, 1, v(0), k(3)).to_vec(); // v_mul_lo_u32 v1, v0, 3 + w.extend([ + vop2(0x25, 1, k(1), 1), // v_add_nc_u32 v1, 1, v1 + vop2(0x26, 2, k(63), 0), // v_sub_nc_u32 v2, 63, v0 + vop2(0x1A, 2, k(2), 2), // v_lshlrev_b32 v2, 2, v2: the mirror lane's address + ]); + w.extend(ds(0xB3, 3, 2, 1, 0)); // ds_bpermute_b32 v3, v2, v1 + w.extend([ + vop1(0x01, 4, LIT), // v_mov_b32 v4, 1000 + 1000, + vop1(0x01, 4, 0xFA), // v_mov_b32 v4, v1 row_shr:1 row_mask:0x6 bank_mask:0xf + 0x6 << 28 | 0xF << 24 | 0x111 << 8 | 1, + ]); + w.extend(ds(0x35, 5, 1, 0, 0x401F)); // ds_swizzle_b32 v5, v1 offset:swizzle(BITMASK_PERM, xor 16) + w.push(vop1(0x01, 6, v(0))); // v_mov_b32 v6, v0 + w.extend(vop3(0x361, 6, 0, k(45))); // v_writelane_b32 v6, s0, 45 + w.extend(stores([3, 4, 5, 6])); + let shader = paired(&native_with(&w, true, 64, 0)); + let s0 = 0xABCD_1234; + let x = |n: u32| 3 * n + 1; + let want: Vec = (0..64) + .flat_map(|n| { + let shifted = if matches!(n >> 4, 1 | 2) && n & 15 != 0 { x(n - 1) } else { 1000 }; + let swizzled = x(n & 32 | (n & 31) ^ 16); + [x(63 - n), shifted, swizzled, if n == 45 { s0 } else { n }] + }) + .collect(); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = run_paired(&shader, [s0, 0, 0, 0], 256) else { return }; + same_as_console(&got, &want); + eprintln!("ran on the hardware device: permutes, row masks, swizzles and lane writes as on the console"); +} + +/// [`program`]'s wave OR inside a per-lane branch, in the paired form: the OR of both halves' +/// lanes, whichever take the branch; nothing stored when none does. +#[test] +fn paired_lanes_or_a_wave_inside_a_lane_branch() { + for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] { + let shader = paired(&program(skip)); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let cases = [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1), (0, 0)]; + for (below, expected) in cases { + let Some(got) = on_the_card(&shader, [below, 0]) else { return }; + assert_eq!(got, expected, "{name}: {below} threads in the branch"); + } + } + eprintln!("ran on the hardware device: the OR of both halves in every case"); +} + +/// One console wave of 64 threads, thread t holding the bit `1 << (t >> 1)`: the threads below +/// s0 OR theirs over the wave inside `if (t < s0) { ... }` ([`super::wave::WAVE_OR_V7_TO_S7`] +/// into s7, which holds 0x77 before), and every thread stores s7 after the branch: the wave's +/// OR, or 0x77 when no thread took the branch and the wave skipped it. A wave-wide value used +/// past a per-lane branch, as the title's tile classification and light clustering programs +/// use theirs: no form in two host waves takes it (they would meet inside the branch, and the +/// skip cannot be left out: s7 would no longer keep 0x77), and the approximate form, each host +/// wave a wave of its own, gives each half its own OR, 0x77 to the upper half while s0 <= 32. +/// The title's 39 such programs ran approximate; [`super::emit`] now gives the paired form. +#[test] +fn a_wave_value_used_past_a_lane_branch_takes_the_paired_form_not_an_approximate_one() { + let mut w = vec![ + sop1(0x03, 7, LIT), // s_mov_b32 s7, 0x77 + 0x77, + vop1(0x01, 5, k(1)), // v_mov_b32 v5, 1 + vop2(0x16, 6, k(1), 0), // v_lshrrev_b32 v6, 1, v0 + vop2(0x1A, 7, v(6), 5), // v_lshlrev_b32 v7, v6, v5 + vopc(0xC4, 0, 0), // v_cmp_gt_u32 vcc, s0, v0 + sop1(0x24, 12, VCC), // s_and_saveexec_b64 s[12:13], vcc + sopp(0x08, 20), // s_cbranch_execz past the OR + ]; + w.extend_from_slice(&super::wave::WAVE_OR_V7_TO_S7); + w.extend([ + sop1(0x04, EXEC, 12), // s_mov_b64 exec, s[12:13] + vop1(0x01, 8, 7), // v_mov_b32 v8, s7 + ]); + w.extend(stores([8, 7, 6, 0])); + let native = native_with(&w, true, 64, 0); + let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); + let st = structure::structure(&p).expect("structure"); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); + let io = io::raise(&p, &native).expect("io::raise"); + let bytes = crate::dxbc::build(&[]); + let c = super::Container::parse(&bytes).expect("container"); + let was = lower::TEST_HOST_WAVE.replace(Some(32)); + let pairs = super::paired(&c, &native, &p, &io, &res); + let chosen = super::emit(&c, &native, &p, &st, &io, &res); + // (as before: the paired form only where no other form takes the program) + let off = super::TEST_PAIRS.replace(Some(false)); + let approximate = super::emit(&c, &native, &p, &st, &io, &res); + super::TEST_PAIRS.set(off); + lower::TEST_HOST_WAVE.set(was); + let (pairs, wave) = pairs.expect("the paired form"); + assert_eq!(wave, Some(32)); + let (chosen, approximate) = (chosen.expect("emit"), approximate.expect("an approximate form")); + assert!(chosen.dxil == pairs.dxil, "emit's choice is not the paired form"); + assert!(approximate.dxil != pairs.dxil, "without the paired form, emit gives it anyway"); + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = chosen.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + // the console: every thread stores the OR of the threads below s0, or 0x77 with none + let want = |s0: u32| -> Vec { + let or = (0..64u32).filter(|&t| t < s0).fold(0u32, |m, t| m | 1 << (t >> 1)); + let s7 = if s0 == 0 { 0x77 } else { or }; + (0..64u32).flat_map(|t| [s7, 1 << (t >> 1), t >> 1, t]).collect() + }; + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + for s0 in [64u32, 40, 33, 32, 10, 1, 0] { + let Some(got) = run_paired(&chosen, [s0, 0, 0, 0], 256) else { return }; + same_as_console(&got, &want(s0)); + } + // each half on its own: with s0 = 10 the upper half took no branch and kept 0x77 + let Some(halves) = run_paired(&approximate, [10, 0, 0, 0], 256) else { return }; + assert_eq!((want(10)[0], want(10)[4 * 40]), (0x1F, 0x1F)); + assert_eq!((halves[0], halves[4 * 40]), (0x1F, 0x77), "the approximate form's lanes 0 and 40"); + eprintln!("ran on the hardware device: the wave's OR past the branch in every lane, not each half's"); +} + +/// [`half_sum_program`] in the paired form: each half's tree over its 32 lanes, then the two +/// halves' sums, the console's last addition. +#[test] +fn paired_lanes_sum_halves_as_the_consoles_tree() { + let (native, tree, _) = half_sum_program(); + let shader = paired(&native); + let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let Some(got) = on_the_card(&shader, [0, 0]) else { return }; + assert_eq!(got, u32::from(tree)); + eprintln!("ran on the hardware device: the sum {tree:#x} of the console's tree"); +} + +/// The lens-flare scans' allocation (`lens_flares:CS_ScanMip1`, 0x5c0-0x61c): in a branch +/// of the lanes below s0, the first lane adds the wave's count times a size (s1) to a +/// counter, and each lane takes base + below × size with `v_mad_u32_u24`. That is the +/// idiom a host wave may run alone ([`super::idiom::wave_local`]): each half reserves its own +/// count's slots. The same with the count where the base goes is not. +#[test] +fn an_allocation_in_units_of_a_size_is_the_idiom() { + let program = |base: u32| -> Vec { + let words = [ + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 0xBF88_0016, // s_cbranch_execz past the allocation + 0xBE82_047E, // s_mov_b64 s[2:3], exec + 0xBE84_147E, // s_ff1_i32_b64 s4, exec + 0xD765_0004, + 0x0001_00C1, // v_mbcnt_lo_u32_b32 v4, -1, 0 + 0xD766_0004, + 0x0002_08C1, // v_mbcnt_hi_u32_b32 v4, -1, v4: the lane + 0xBE86_047E, // s_mov_b64 s[6:7], exec + 0x7DA4_0804, // v_cmpx_eq_u32 exec, s4, v4: the first lane + 0xBE82_1002, // s_bcnt1_i32_b64 s2, s[2:3]: the count + 0x7E02_0201, // v_mov_b32 v1, s1: the size + 0x160A_0202, // v_mul_u32_u24 v5, s2, v1 + 0x7E16_0280, // v_mov_b32 v11, 0 + 0xE0C8_6000, + 0x8002_050B, // buffer_atomic_add v5, v11, s[8:11], 0 idxen glc + 0xBEFE_0406, // s_mov_b64 exec, s[6:7] + 0xD765_0004, + 0x0001_007E, // v_mbcnt_lo_u32_b32 v4, exec_lo, 0 + 0xD766_0004, + 0x0002_087F, // v_mbcnt_hi_u32_b32 v4, exec_hi, v4: the lanes below + 0x7E0A_0505, // v_readfirstlane_b32 s5, v5: the base + 0xD543_0006, + 0x0002_0304 | base << 18, // v_mad_u32_u24 v6, v4, v1, s + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + S_ENDPGM, + ]; + words.iter().flat_map(|w| w.to_le_bytes()).collect() + }; + let idiom = |code: &[u8]| { + let p = ir::build(code, true, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + super::idiom::wave_local(&p, &st) + }; + assert_eq!(idiom(&program(5)), Ok(())); + assert!(idiom(&program(2)).is_err(), "the count as the base"); +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c6d0..146163107d 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -123,6 +123,27 @@ impl Inst { } } +thread_local! { + /// See [`with_shared_slots`]. + static SHARED_SLOTS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with programs built so that a register pair parked in two lanes of a VGPR moves +/// as a pair wherever its save or restore comes together, also where the lower lane holds a +/// single scalar at other times ([`unspill`] otherwise moves every half alone then). Each +/// save and restore keeps its meaning either way (a pair move is the two moves at once, where +/// nothing in between sees the difference); what changes is that a parked lane mask then comes +/// back as the mask it is. `PS_VoxelizeVisiblity` parks a lane mask in lanes 3 and 4 of v56 and +/// later a single scalar in lane 3: its mask came back as two scalars, a mask the +/// structurisation cannot see into ("an opaque lane mask"). A retry ([`crate::emit::emit`]), +/// so that the programs that translate as they are keep their form. +pub fn with_shared_slots(f: impl FnOnce() -> R) -> R { + let was = SHARED_SLOTS.replace(true); + let r = f(); + SHARED_SLOTS.set(was); + r +} + /// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR /// count. Fails on instructions the IR cannot express yet /// ([`ShaderError::Unsupported`]). @@ -245,7 +266,9 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result = Vec::new(); + // ([`with_shared_slots`]) the upper lanes' parks that move with a lower one + let mut taken: Vec = Vec::new(); + let shared = SHARED_SLOTS.get(); for &(reg, lane) in &slots { if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { continue; @@ -396,8 +422,12 @@ fn unspill( let mut distinct: Vec = partners.iter().flatten().copied().collect(); distinct.sort_unstable(); distinct.dedup(); - if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + let found = partners.iter().flatten().count(); + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() + || shared && found > 0 && distinct.len() == found + { pairs.push((reg, lane)); + taken.extend(distinct); } } // Codes for the parked scalars: the trap temporaries (108..=123), then @@ -450,7 +480,8 @@ fn unspill( continue; }; let Some(slot) = code_of(reg, lane) else { return Vec::new() }; - if pairs.contains(&(reg, lane)) { + let alone = shared && (pairs.contains(&(reg, lane)) && partner(i).is_none() || lane > 0 && pairs.contains(&(reg, lane - 1)) && !taken.contains(&i)); + if pairs.contains(&(reg, lane)) && !alone { let Some(j) = partner(i) else { return Vec::new() }; // A save moves the pair where its second half is saved; a // restore where its first half is restored. @@ -458,7 +489,7 @@ fn unspill( let (dst, src) = if save { (slot, code) } else { (code, slot) }; edits.push((at, Some((true, dst, src)))); edits.push((gone, None)); - } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + } else if lane > 0 && pairs.contains(&(reg, lane - 1)) && !alone { // the upper half of a pair: moved with the lower } else { let (dst, src) = if save { (slot, code) } else { (code, slot) }; @@ -580,6 +611,161 @@ pub(crate) fn thread_edges( Ok(rename(blocks, p.wave64, p.vgprs)) } +/// Each of `joins` copied for every way into it but the first, each copy entered from its own +/// predecessor and left as the join is: a value the join merged from its ways in is one +/// value in each copy. Every instruction still runs once on each path. A loop header (a +/// block with a way in from later in reverse postorder) is left as it is. `None` if nothing +/// changes. +pub(crate) fn split_joins(p: &Program, joins: &[usize]) -> Option { + let order = reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + let mut any = false; + for &join in joins { + let mut preds = p.blocks[join].preds.clone(); + preds.dedup(); + if preds.len() < 2 || preds.iter().any(|&q| index[q] >= index[join]) { + continue; + } + for &pred in &preds[1..] { + let target = blocks.len(); + blocks.push(blocks[join].clone()); + match &mut blocks[pred].exit { + Exit::Jump(t) => *t = target, + Exit::Branch { taken, not_taken } => { + if *taken == join { + *taken = target; + } + if *not_taken == join { + *not_taken = target; + } + } + _ => unreachable!("a way into a join"), + } + } + any = true; + } + if !any { + return None; + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// The program with each whole-wave section (`s_or_saveexec -1` up to the restore of the +/// saved mask, `emit::wave`) that a jump splits in one block: the block the section starts +/// in, when it jumps to the block that restores the mask, takes that block's code and exit +/// (a copy where other ways lead there too). The compiler shares the end of two sections +/// whose start a branch chooses (`cond ? WaveActiveMax(x) : WaveActiveMin(x)` in the title's +/// water optical depth: each arm reduces up to the read of lane 32, the join reads lane 0 +/// and restores), and a section is followed within one block. Every instruction still runs +/// once on each path. A join that is a loop header is left as it is. `None` if nothing +/// changes. +pub(crate) fn whole_sections(p: &Program) -> Option { + use crate::gfx10::{Fields, Operand}; + /// The saved mask's scalar code if `inst` starts a section: EXEC becomes every lane + /// (`s_or_saveexec -1`, `s_nand_saveexec 0`). + fn start(inst: &Inst) -> Option { + let all = match inst.name() { + "s_or_saveexec_b64" | "s_or_saveexec_b32" => Operand::Const(193), + "s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Operand::Const(128), + _ => return None, + }; + match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + src, + .. + } if src.first() == Some(&all) => Some(*code), + _ => None, + } + } + let order = reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + // (block, the join whose code it takes) + let mut fuse = Vec::new(); + for &b in &order { + let block = &p.blocks[b]; + let Exit::Jump(join) = block.exit else { continue }; + // the last section start of the block, unless its restore is in the block too + let Some((at, code)) = block + .insts + .iter() + .enumerate() + .rev() + .find_map(|(i, inst)| start(inst).map(|c| (i, c))) + else { + continue; + }; + let saved = block.insts[at].write(Reg::S(code)); + let restores = |i: &Inst, held: Option| { + i.write(Reg::S(EXEC)).is_some() && i.read(Reg::S(code)).is_some_and(|v| Some(v) == held) + }; + if block.insts[at + 1..].iter().any(|i| restores(i, saved)) { + continue; + } + let z = &p.blocks[join]; + if join == b || z.preds.iter().any(|&q| index[q] >= index[join]) { + continue; + } + // what the saved register holds in the join: the value itself, or a join of it + let held = match z.phis.iter().find(|phi| phi.reg == Reg::S(code)) { + Some(phi) => { + let from_b = z.preds.iter().position(|&q| q == b).map(|k| phi.args[k]); + if from_b != saved { + continue; + } + Some(phi.value) + } + None => saved, + }; + // the join's first write of EXEC is the restore, and nothing before it writes the + // saved register + let first = z + .insts + .iter() + .position(|i| i.write(Reg::S(EXEC)).is_some() || i.write(Reg::S(code)).is_some()); + if first.is_some_and(|k| restores(&z.insts[k], held)) { + fuse.push((b, join)); + } + } + if fuse.is_empty() { + return None; + } + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + for &(b, join) in &fuse { + if blocks[b].insts.last().is_some_and(|i| i.name() == "s_branch") { + blocks[b].insts.pop(); + } + let tail = p.blocks[join].insts.clone(); + blocks[b].insts.extend(tail); + blocks[b].exit = p.blocks[join].exit; + } + // a join whose every way in took its code is left: nothing reaches it + for &(_, join) in &fuse { + if p.blocks[join].preds.iter().all(|q| fuse.contains(&(*q, join))) { + blocks[join].insts.clear(); + blocks[join].exit = Exit::End; + } + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + /// The program without its early-outs: an `s_cbranch_execz` to a block that /// only ends the program (`if (!inBounds) return;`, the outermost branch of /// most compute programs) is left out, so the lanes that would have left @@ -1607,6 +1793,33 @@ mod tests { assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); } + #[test] + fn a_split_join_gives_each_way_in_its_own_copy() { + let code = [ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0002, // s_cbranch_scc1 -> s_mov_b32 s2, 0 + 0xB002_0092, // s_movk_i32 s2, 0x92 + 0xBF82_0001, // s_branch -> the join + 0xBE82_0380, // s_mov_b32 s2, 0 + 0x7E02_0202, // v_mov_b32 v1, s2 (the join) + S_ENDPGM, + ]; + let p = build_words(&code, false); + let join = p.blocks.iter().position(|b| b.preds.len() == 2).expect("a join"); + assert_eq!(p.blocks[join].phis.len(), 1, "s2 differs by the way in"); + let q = split_joins(&p, &[join]).expect("split"); + // two blocks read s2 into v1, neither through a phi + let reads: Vec<&Block> = q + .blocks + .iter() + .filter(|b| b.insts.first().is_some_and(|i| i.name() == "v_mov_b32")) + .collect(); + assert_eq!(reads.len(), 2); + assert!(reads.iter().all(|b| b.preds.len() == 1 && b.phis.is_empty())); + // a block with one way in is left as it is + assert!(split_joins(&q, &[0]).is_none()); + } + #[test] fn joins_get_phis_only_where_values_differ() { let code = [ @@ -1788,4 +2001,53 @@ mod tests { assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4))); assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs"); } + + /// `PS_VoxelizeVisiblity`'s parking (0xa18-0xa38, 0xe44-0xe4c, 0x2df8, 0x3184): a lane + /// mask parked in lanes 3 and 4 of v56 and taken back to make EXEC, later a single scalar + /// parked in lane 3. Built as it is, the mask comes back as two scalars, which the + /// structurisation cannot see into; with [`with_shared_slots`] it comes back as the pair + /// it is, and EXEC as the compare's lanes. + #[test] + fn a_mask_parked_in_lanes_another_scalar_shares_comes_back_whole_with_shared_slots() { + let writelane = |lane: u32, s: u32| [0xD761_0038, s | (128 + lane) << 9]; // v_writelane_b32 v56, s, lane + let readlane = |s: u32, lane: u32| [0xD760_0000 | s, (256 + 56) | (128 + lane) << 9]; // v_readlane_b32 s, v56, lane + let mut w = vec![ + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBEA2_046A, // s_mov_b64 s[34:35], vcc + ]; + w.extend(writelane(3, 34)); + w.extend(writelane(4, 35)); + w.push(0xBEA2_0480); // s_mov_b64 s[34:35], 0 + w.extend(readlane(34, 3)); + w.extend(readlane(35, 4)); + let restore = 4 * (w.len() - 4) as u64; // (the first restore's offset) + w.extend([ + 0xBE82_2422, // s_and_saveexec_b64 s[2:3], s[34:35] + 0x7E02_0281, // v_mov_b32 v1, 1 + 0xBEFE_0402, // s_mov_b64 exec, s[2:3] + ]); + w.extend(writelane(3, 1)); + w.push(0xBE81_0380); // s_mov_b32 s1, 0 + w.extend(readlane(1, 3)); + w.push(S_ENDPGM); + let code: Vec = w.iter().flat_map(|w| w.to_le_bytes()).collect(); + let at = |p: &Program| { + let i = p.blocks.iter().flat_map(|b| &b.insts).find(|i| i.machine.offset as u64 == restore).expect("the restore"); + i.name() + }; + let alone = build(&code, true, 64).unwrap(); + assert_eq!(at(&alone), "s_mov_b32"); + let shared = with_shared_slots(|| build(&code, true, 64)).unwrap(); + assert_eq!(at(&shared), "s_mov_b64"); + let opaque = |p: &Program| { + let st = crate::structure::structure(p).unwrap(); + let v1 = p.blocks.iter().enumerate().flat_map(|(b, blk)| blk.insts.iter().enumerate().map(move |(i, inst)| (b, i, inst))); + let (b, i, _) = v1.into_iter().find(|(_, _, inst)| inst.name() == "v_mov_b32").expect("the guarded move"); + let guard = st.guards[b][i].expect("a guard"); + st.bools.support(guard).iter().any(|a| matches!(a, crate::structure::Atom::Opaque(_))) + }; + // (built alone, this branch may already see the compare's mask: only the shared build + // is checked) + assert!(!opaque(&shared), "the pair is the compare's mask"); + } } diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index bb397d4790..f83256d335 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -59,8 +59,12 @@ translation_inputs! { "emit/bitcode/census.rs", "emit/bitcode/opt.rs", "emit/container.rs", + "emit/descriptor_data.rs", + "emit/float64.rs", "emit/guest_address.rs", + "emit/idiom.rs", "emit/intersect.rs", + "emit/link.rs", "emit/lower.rs", "emit/mod.rs", "emit/own_bits.rs", @@ -94,6 +98,7 @@ mod source_tests { // remaining modules are only compiled by the Windows execution tests. const OUTSIDE_TRANSLATION: &[&str] = &[ "emit/cube_lod_tests.rs", + "emit/descriptor_tests.rs", "emit/diff_tests.rs", "emit/helper_lane_tests.rs", "emit/host.rs", From a65db62416e607672dbf5f044ee83f5f4287aecf Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:32:12 +0100 Subject: [PATCH 2/9] Let the paired form take the ray-tracing structure builder's programs The two BVH builder programs (28918b7150a7aad5, caa78b8ca62bc3d6) were the last wave64 compute programs refused on 32-lane hosts. They exchange across the console wave's halves, which the per-half form got wrong and which hung NVIDIA cards (Marvisak/VIctory#2711). The paired form keeps both halves in one host wave, so the refusal is dropped: all 31 wave64 compute containers from the RTX 5060 preload now get a pipeline. The builder still runs only when victory-gpu allows it (VICTORY_BVH_BUILDER=1 or VICTORY_RAY_TRACING=1) and every one of its pipelines has a host pipeline; by default its dispatches stay dropped. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/emit/mod.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 63ee640585..099f7f7ce3 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -962,15 +962,11 @@ fn paired( what: "paired lanes outside compute", }); }; - // The ray-tracing structure builder's programs (a spilled user-data table, as - // `victory-gpu` tells them) exchange across the halves, and forcing them onto 32-lane - // hosts hung NVIDIA cards (Marvisak/VIctory#2711): they stay refused. - if crate::spill::is_spilled(native) { - return Err(ShaderError::Unsupported { - offset: 0, - what: "paired lanes for the ray-tracing structure builder", - }); - } + // The ray-tracing structure builder's programs (a spilled user-data table) exchange + // across the halves. The per-half form got that wrong and hung NVIDIA cards + // (Marvisak/VIctory#2711); the paired form keeps both halves in one host wave, as the + // console does. The builder still runs only when `victory-gpu` allows it + // (`VICTORY_BVH_BUILDER=1`) and every one of its pipelines exists. if cs.threads.iter().product::() % 64 != 0 { return Err(ShaderError::Unsupported { offset: 0, From 3a9874c9563f5a9fe390a8f23bb2d813169916ae Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:03:43 +0100 Subject: [PATCH 3/9] Make compute pipelines from programs the title compiled itself (device method 0x218) The title calls device method 0x218 at start for every variant of its small compute programs (mip generation of texture arrays), handing over a 0x60-byte description: the root signature, then (address, size) pairs of the program's registers, its code and its resource table. Until now the call failed with a null output and the title went without these pipelines. The program is now read from the description (registers, console resource table, code without its s_code_end padding) and wrapped in a container of its own, which is translated and cached as the title's containers are. Descriptions that cannot be read still fail with E_NOTIMPL and a null output. Method 0x1c8 (native graphics pipelines) stays refused: it needs the draw's render-target formats. The descriptor tracer also folds s_bfm_b32 and a 64-bit s_mov of a literal (zero extended), the two instructions these programs use to build their fixed sampler; without them the sampler's origin was lost and the pipeline refused. On the five 0x218 captures from the RTX 5060, all five now get a hardware pipeline and are created by the runtime. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/device.rs | 24 +- crates/victory-gpu/src/pipeline.rs | 114 ++++++ crates/victory-shader/src/dxbc.rs | 5 +- crates/victory-shader/src/lib.rs | 3 + crates/victory-shader/src/native.rs | 5 + crates/victory-shader/src/native_build.rs | 436 ++++++++++++++++++++++ crates/victory-shader/src/resource.rs | 38 +- 7 files changed, 599 insertions(+), 26 deletions(-) create mode 100644 crates/victory-shader/src/native_build.rs diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index dfbf2b2253..8a02250953 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -346,25 +346,17 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } -/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both -/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface -/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the -/// object `out` names and draws with it; on failure it goes without that -/// pipeline, silently. What the descriptions hold is not known: the calls -/// fail as they always did, with `out` null, and the first ones log the -/// description's words and what its first word points at, so that the two -/// methods can be written. -/// shortcut: not implemented. Answering `S_OK` here without making the -/// pipeline would hand the title whatever its stack held as an object. -extern "system" fn unknown_pipeline( +/// Device method 0x1c8. Native graphics state still needs render-target +/// formats from the draw. Leave the output null so the caller can fall back. +extern "system" fn unknown_graphics_pipeline( _: This, desc: *const u8, _iid: *const Iid, out: *mut This, ) -> HRESULT { use std::sync::atomic::{AtomicU32, Ordering}; - static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; - let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1; + static CALLS: AtomicU32 = AtomicU32::new(0); + let calls = CALLS.fetch_add(1, Ordering::Relaxed) + 1; if !out.is_null() { // SAFETY: the title's out pointer (a local of its own). unsafe { *out = std::ptr::null() }; @@ -389,7 +381,7 @@ extern "system" fn unknown_pipeline( .as_ref() .and_then(|w| words(w[0] as usize)); tracing::warn!( - slot = format_args!("{:#x}", SLOT), + slot = "0x1c8", calls, description = format_args!("{description:x?}"), first_points_at = format_args!("{first:x?}"), @@ -435,10 +427,10 @@ static FUNCTIONS: Table<160> = { f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 f[48] = queue::create_x as *const (); // 0x180 - f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8 + f[57] = unknown_graphics_pipeline as *const (); // 0x1c8 f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 f[62] = pipeline::create_compute_x as *const (); // 0x1f0 - f[67] = unknown_pipeline::<0x218> as *const (); // 0x218 + f[67] = pipeline::create_native_compute as *const (); // 0x218 f[69] = object::ignore as *const (); // 0x228 debug error filter f[70] = descriptor::create_placed_srv as *const (); // 0x230 f[71] = descriptor::create_placed_uav as *const (); // 0x238 diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 5904fd5810..43ff4cc63e 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -668,6 +668,88 @@ pub(crate) extern "system" fn create_compute_x( create_compute(this, desc, iid, out) } +/// Device method 0x218: a compute pipeline from a program the title has +/// compiled already and put in its own memory. `desc` is a record of 0x60 +/// bytes: the root signature, then (address, size) pairs of the program's +/// registers (0x1c bytes), of a second register block, of its code and of +/// its resource table, two addresses and the program's 64-bit hash. The +/// title makes one for every variant of its small compute programs (mip +/// generation of texture arrays) at start. +/// +/// The code is not that of the title's container of the same program: it is +/// compiled again, for a root signature whose table can hold more ranges. +/// So the program is read from the record +/// ([`victory_shader::native::console_compute_container`]) and put in a container of +/// its own, which is translated and cached as the title's containers are. +pub(crate) extern "system" fn create_native_compute( + _: This, + desc: *const u8, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + use std::sync::atomic::{AtomicU32, Ordering}; + static MADE: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; + if !out.is_null() { + // SAFETY: the title's out pointer. + unsafe { *out = std::ptr::null() }; + } + let program = (|| { + let registers = title_bytes(desc, 1)?; + let code = title_bytes(desc, 5)?; + let table = title_bytes(desc, 7)?; + victory_shader::native::console_compute_container(®isters, &table, &code) + .map_err(|e| tracing::debug!(error = %e, "a compute program compiled by the title is not read")) + .ok() + })(); + let made = MADE[usize::from(program.is_none())].fetch_add(1, Ordering::Relaxed) + 1; + let Some(container) = program else { + if made.is_power_of_two() { + tracing::warn!(missed = made, "a compute pipeline from compiled code that is not read: the title goes without it"); + } + return crate::object::E_NOTIMPL; + }; + let shader = shader("compute", &container); + if made.is_power_of_two() { + tracing::info!(made, hash = %shader.hash, "native compute descriptions decoded"); + } + hand_out( + vec![shader], + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// The bytes named by words `at` (address) and `at + 1` (size) of the +/// title's description `desc`, read through the kernel: the title's own +/// memory, which may not be mapped. +fn title_bytes(desc: *const u8, at: usize) -> Option> { + #[cfg(windows)] + { + let mut words = [0u8; 16]; + if desc.is_null() { + return None; + } + let start = desc.wrapping_add(8 * at); + if !crate::host::read_into(start, &mut words) { + return None; + } + let address = u64::from_le_bytes(words[..8].try_into().ok()?) as usize; + let size = u64::from_le_bytes(words[8..].try_into().ok()?) as usize; + if address == 0 || !(4..=1 << 20).contains(&size) { + return None; + } + let mut bytes = vec![0u8; size]; + crate::host::read_into(address as *const u8, &mut bytes).then_some(bytes) + } + #[cfg(not(windows))] + { + let _ = (desc, at); + None + } +} + /// A pipeline described as a stream: its size and the subobjects, each a /// type then its data, padded to 8 bytes. #[repr(C)] @@ -845,6 +927,38 @@ mod tests { .collect() } + #[cfg(windows)] + #[test] + fn native_compute_slot_reads_the_description_and_clears_failed_outputs() { + type Create = extern "system" fn(This, *const u8, *const Iid, *mut This) -> HRESULT; + let device = crate::device::device(); + let create = slot::(device, 0x218); + let regs = [0u32, 0, 0, 1 << 16 | 1, 1, 0, 0]; + let code = [0xBF81_0000u32]; + // Short table header and a terminal hash entry, with no resources. + let mut table = [0u32; 12]; + table[1] = 36; + table[4] = 0x43; + let mut desc = [0usize; 12]; + for (at, words) in [(1, regs.as_slice()), (5, &code[..]), (7, &table[..])] { + desc[at] = words.as_ptr() as usize; + desc[at + 1] = size_of_val(words); + } + let mut out = std::ptr::null(); + assert_eq!(create(device, desc.as_ptr().cast(), &PIPELINE_IIDS[0], &mut out), S_OK); + let shaders = shaders(out); + assert_eq!(shaders.len(), 1); + assert_eq!(shaders[0].0, "compute"); + let c = victory_shader::Container::parse(&shaders[0].1).unwrap(); + let programs = victory_shader::native_programs(c.part(victory_shader::FourCC::DXIL).unwrap().data).unwrap(); + assert_eq!(programs[0].code, code[0].to_le_bytes()); + assert_eq!(slot:: u32>(out, 0x10)(out), 0); + + desc[6] = 0; + assert_eq!(create(device, desc.as_ptr().cast(), &PIPELINE_IIDS[0], &mut out), crate::object::E_NOTIMPL); + assert!(out.is_null()); + } + #[test] fn pipelines_keep_their_shaders() { let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs index 7a20963b60..c377ad1ed7 100644 --- a/crates/victory-shader/src/dxbc.rs +++ b/crates/victory-shader/src/dxbc.rs @@ -129,9 +129,8 @@ pub(crate) fn u64_at(data: &[u8], at: usize) -> Result { .ok_or(ShaderError::Malformed("truncated")) } -/// Builds a container from parts (test helper). -#[cfg(test)] -pub fn build(parts: &[(FourCC, &[u8])]) -> Vec { +/// Packs parts into an unsigned container for the internal shader reader. +pub(crate) fn build(parts: &[(FourCC, &[u8])]) -> Vec { let table = HEADER_SIZE + 4 * parts.len(); let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); let mut out = Vec::with_capacity(total); diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index f83256d335..b7bc71b545 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -98,6 +98,9 @@ mod source_tests { // remaining modules are only compiled by the Windows execution tests. const OUTSIDE_TRANSLATION: &[&str] = &[ "emit/cube_lod_tests.rs", + // (programs the title hands over compiled, wrapped in a container that the + // translation then reads as any other) + "native_build.rs", "emit/descriptor_tests.rs", "emit/diff_tests.rs", "emit/helper_lane_tests.rs", diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index 4c267e17c7..43d0a62abf 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -71,6 +71,11 @@ use crate::ShaderError::{self, Malformed}; use crate::dxbc::{u32_at, u64_at}; +/// Programs handed to us compiled, outside a container, and a container for them. +#[path = "native_build.rs"] +mod build; +pub use build::console_compute_container; + const XDAT_OFFSET: usize = 0x18; const MAX_XDAT_ENTRIES: usize = 64; const KIND_NATIVE: u32 = 0x0d; diff --git a/crates/victory-shader/src/native_build.rs b/crates/victory-shader/src/native_build.rs new file mode 100644 index 0000000000..1eb027a942 --- /dev/null +++ b/crates/victory-shader/src/native_build.rs @@ -0,0 +1,436 @@ +//! Console programs that reach us compiled already, outside a container, +//! and the container that holds such a program as the title's own do. +//! +//! A title can make a pipeline from a program it has put in its own memory +//! (device methods 0x218 for compute, 0x1c8 for graphics). Such a program +//! comes as its code, a block of registers and a resource table. The table, +//! as observed (the title's mip generation programs, against their +//! containers): +//! +//! ```text +//! +0x00 u32 kind (bit 10: 8 bytes more of header), u32 size of the rest +//! (from +0x0c, or +0x14), u32, u32 ..., the last u32 of the header +//! holding the count of 0x41 entries in its high half (`n << 16 | 0x440`) +//! entries of 0x20 bytes from the end of the header: +//! 0x41 a descriptor the program reads: u32 0x41, u32 root type << 8 | +//! resource type (0 SRV, 1 sampler, 2 CBV, 3 UAV), u32 table offset +//! (dwords), u32 shader register, u32 first user-data dword, +//! u32 root slot << 16 | stride << 8 | descriptor dwords, then +//! u32 -1, u32 0 +//! 0x42 a table range (not read: the 0x41 entries name the same ranges) +//! 0x43 the program's 128-bit hash, last +//! ``` +//! +//! The registers of a compute program, 0x1c bytes: u32 flags (bit 5: 32 +//! lanes, as the container record's flags), u32, u32, u16 x2 and u32 +//! thread-group size, u32 `COMPUTE_PGM_RSRC1`, u32 `COMPUTE_PGM_RSRC2`. + +use super::{ + ABSENT, CS_RSRC2, CS_THREADS, ComputeIo, ENTRY_SIZE, MAX_UNPACKED, FSSM_HEADER, FSSM_VERSION, GRAPHICS_SLOT_COUNT, HwStage, + KIND_NATIVE, NativeProgram, RECORD_COUNTS, RECORD_FLAGS, RECORD_LAYOUT, RECORD_REGS, + RECORD_SIZE, RECORD_USED, ResourceType, RootParam, RootType, SLOTS, StageIo, UsedResource, + XBCH_HEADER, XBCH_VERSION, XDAT_OFFSET, +}; +use crate::ShaderError::{self, Malformed}; +use crate::dxbc::u32_at; +use crate::{FourCC, dxbc}; + +const S_CODE_END: u32 = 0xBF9F_0000; + +/// The descriptors a console resource table names, and the root parameters +/// they come through (one per table range, and one per fixed sampler). +fn resources(table: &[u8]) -> Result<(Vec, Vec), ShaderError> { + let kind = u32_at(table, 0)?; + let header = if kind & 0x400 != 0 { 0x18 } else { 0x10 }; + let size = u32_at(table, 4)? as usize; + if table.len().checked_sub(header - 4) != Some(size) { + return Err(Malformed("resource table size disagrees")); + } + let count = (u32_at(table, header - 4)? >> 16) as usize; + let (entries, tail) = table[header..].as_chunks::<0x20>(); + let Some((hash, entries)) = entries.split_last() else { + return Err(Malformed("missing resource table hash")); + }; + if !tail.is_empty() || u32_at(hash, 0)? != 0x43 || count > entries.len() { + return Err(Malformed("incomplete resource table")); + } + let (descriptors, ranges) = entries.split_at(count); + if ranges.iter().any(|entry| super::le32(entry, 0) != 0x42) { + return Err(Malformed("unexpected resource range")); + } + let (mut layout, mut used) = (Vec::new(), Vec::new()); + for entry in descriptors { + let word = |k: usize| u32::from_le_bytes(entry[4 * k..4 * k + 4].try_into().unwrap()); + if word(0) != 0x41 { + return Err(Malformed("unexpected resource descriptor")); + } + let (types, offset, register, user_data, packed) = + (word(1), word(2), word(3), word(4), word(5)); + let root = RootType::from_raw(types >> 8); + let slot = u8::try_from(packed >> 16).map_err(|_| Malformed("implausible root slot"))?; + let user_data = + u8::try_from(user_data).map_err(|_| Malformed("implausible user-data dword"))?; + used.push(UsedResource { + kind: match types & 0xFF { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n as u8), + }, + root, + table_offset_dwords: offset, + lower_bound: register, + stride: packed >> 8 & 0xFF, + dwords: packed as u8, + user_data, + slot, + }); + let sgprs = match root { + RootType::Table => 1, + RootType::ImmediateSampler => 0, + _ => { + return Err(Malformed( + "a console resource table entry of a root type not seen yet", + )); + } + }; + layout.push(RootParam { + root, + table_offset_dwords: offset, + sgprs, + base_register: register, + user_data, + slot, + }); + } + Ok((layout, used)) +} + +/// The code without the `s_code_end` the title pads it with. +fn trimmed(code: &[u8]) -> &[u8] { + let mut end = code.len(); + while end >= 4 && u32_at(code, end - 4).ok() == Some(S_CODE_END) { + end -= 4; + } + &code[..end] +} + +/// A compute program from its registers (0x1c bytes), resource table and +/// code, as the title hands them to device method 0x218. +fn console_compute( + registers: &[u8], + table: &[u8], + code: &[u8], +) -> Result { + if registers.len() < 0x1c { + return Err(Malformed("compute registers too short")); + } + let flags = u32_at(registers, 0)?; + let size = u32_at(registers, 0x0c)?; + let threads = [size & 0xFFFF, size >> 16, u32_at(registers, 0x10)?]; + let rsrc1 = u32_at(registers, 0x14)?; + let rsrc2 = u32_at(registers, 0x18)?; + if threads.contains(&0) + || threads[2] > 64 + || threads + .into_iter() + .try_fold(1u32, u32::checked_mul) + .is_none_or(|lanes| lanes > 1024) + { + return Err(Malformed("implausible thread-group size")); + } + let wave64 = flags & super::FLAG_WAVE32 == 0; + // COMPUTE_PGM_RSRC1.VGPRS: granules of 4 (64 lanes) or 8 (32 lanes), less one. + let vgprs = ((rsrc1 & 0x3F) + 1) * if wave64 { 4 } else { 8 }; + if vgprs > 256 || !code.len().is_multiple_of(4) { + return Err(Malformed("invalid compute register count or code length")); + } + let (layout, used) = resources(table)?; + let code = trimmed(code); + if code.is_empty() { + return Err(Malformed("no code")); + } + Ok(NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: vgprs as u16, + layout, + used, + io: StageIo::Cs(ComputeIo { rsrc2, threads }), + code: code.to_vec(), + }) +} + +fn root_raw(root: RootType) -> u32 { + match root { + RootType::Constants => 0, + RootType::Descriptor => 1, + RootType::Table => 3, + RootType::ImmediateSampler => 4, + RootType::ResourceHeap => 5, + RootType::SamplerHeap => 6, + RootType::Other(n) => n, + } +} + +fn kind_raw(kind: ResourceType) -> u8 { + match kind { + ResourceType::Srv => 0, + ResourceType::Sampler => 1, + ResourceType::Cbv => 2, + ResourceType::Uav => 3, + ResourceType::Other(n) => n, + } +} + +/// An internal shader container built from the three blocks in a native compute description. +pub fn console_compute_container( + registers: &[u8], + table: &[u8], + code: &[u8], +) -> Result, ShaderError> { + let program = console_compute(registers, table, code)?; + compute_container(&program) +} + +/// A container holding `program` (a compute program) as the title's +/// containers hold theirs, for everything that reads programs from +/// containers: [`super::native_programs`] gives `program` back. +fn compute_container(program: &NativeProgram) -> Result, ShaderError> { + let StageIo::Cs(cs) = &program.io else { + return Err(Malformed("not a compute program")); + }; + let put32 = + |v: &mut Vec, at: usize, x: u32| v[at..at + 4].copy_from_slice(&x.to_le_bytes()); + let put64 = + |v: &mut Vec, at: usize, x: u64| v[at..at + 8].copy_from_slice(&x.to_le_bytes()); + // payload: slot count and record offsets, the record, its stage data, code, tables + let mut payload = vec![0u8; SLOTS.iter().map(|s| s.1).max().unwrap() + 8]; + put64(&mut payload, 0, GRAPHICS_SLOT_COUNT); + for (_, at) in SLOTS { + put64(&mut payload, at, ABSENT); + } + let record = payload.len(); + put64( + &mut payload, + super::SLOTS.iter().find(|s| s.0 == HwStage::Cs).unwrap().1, + record as u64, + ); + payload.resize(record + RECORD_SIZE as usize + CS_THREADS + 12, 0); + let stage = record + RECORD_SIZE as usize; + put32(&mut payload, stage + CS_RSRC2, cs.rsrc2); + for (k, n) in cs.threads.iter().enumerate() { + put32(&mut payload, stage + CS_THREADS + 4 * k, *n); + } + let code_at = payload.len(); + payload.extend_from_slice(&program.code); + let layout_at = payload.len(); + for p in &program.layout { + let mut e = [0u8; ENTRY_SIZE as usize]; + e[0..4].copy_from_slice(&root_raw(p.root).to_le_bytes()); + e[4..8].copy_from_slice(&p.table_offset_dwords.to_le_bytes()); + e[8..12].copy_from_slice(&p.sgprs.to_le_bytes()); + e[12..16].copy_from_slice(&p.base_register.to_le_bytes()); + e[16] = p.user_data; + e[17] = p.slot; + payload.extend_from_slice(&e); + } + let used_at = payload.len(); + for u in &program.used { + let mut e = [0u8; ENTRY_SIZE as usize]; + e[0] = kind_raw(u.kind); + e[1] = root_raw(u.root) as u8; + e[4..8].copy_from_slice(&u.table_offset_dwords.to_le_bytes()); + e[8..12].copy_from_slice(&u.lower_bound.to_le_bytes()); + e[12..16].copy_from_slice(&u.stride.to_le_bytes()); + e[16] = u.dwords; + e[17] = u.user_data; + e[18] = u.slot; + payload.extend_from_slice(&e); + } + put64(&mut payload, record, code_at as u64); + put64(&mut payload, record + 8, program.code.len() as u64); + put32( + &mut payload, + record + RECORD_FLAGS, + if program.wave64 { + 0 + } else { + super::FLAG_WAVE32 + }, + ); + put64(&mut payload, record + RECORD_LAYOUT, layout_at as u64); + put64(&mut payload, record + RECORD_USED, used_at as u64); + put32( + &mut payload, + record + RECORD_COUNTS, + program.layout.len() as u32, + ); + put32( + &mut payload, + record + RECORD_COUNTS + 4, + program.used.len() as u32, + ); + put32(&mut payload, record + RECORD_REGS, u32::from(program.vgprs)); + // FSSM, then XBCH around its zlib stream + let mut fssm = b"FSSM".to_vec(); + fssm.extend(FSSM_VERSION.to_le_bytes()); + fssm.extend((payload.len() as u64).to_le_bytes()); + debug_assert_eq!(fssm.len(), FSSM_HEADER); + fssm.extend(payload); + if fssm.len() as u64 > MAX_UNPACKED { + return Err(Malformed( + "native compute program exceeds the container size limit", + )); + } + let mut compressed = vec![0; zlib_rs::compress_bound(fssm.len())]; + let config = zlib_rs::DeflateConfig { + level: 0, + ..Default::default() + }; + let (stream, status) = zlib_rs::compress_slice(&mut compressed, &fssm, config); + if status != zlib_rs::ReturnCode::Ok { + return Err(Malformed("could not encode native compute program")); + } + let mut xbch = b"XBCH".to_vec(); + xbch.extend(XBCH_VERSION.to_le_bytes()); + xbch.extend((stream.len() as u64).to_le_bytes()); + xbch.extend((fssm.len() as u64).to_le_bytes()); + debug_assert_eq!(xbch.len(), XBCH_HEADER); + xbch.extend_from_slice(stream); + // the DXIL part: a header up to the index, the index of one entry, the blob + let mut dxil = vec![0u8; XDAT_OFFSET]; + dxil.extend_from_slice(b"XDAT"); + dxil.extend(1u32.to_le_bytes()); + dxil.extend(0x24u32.to_le_bytes()); + let blob_at = dxil.len() + 12; + dxil.extend(KIND_NATIVE.to_le_bytes()); + dxil.extend((blob_at as u32).to_le_bytes()); + dxil.extend((xbch.len() as u32).to_le_bytes()); + dxil.extend(xbch); + Ok(dxbc::build(&[(FourCC::DXIL, &dxil)])) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A synthetic table with a fixed + /// sampler and a table of an SRV, two UAVs and a CBV, then a range and + /// the hash. + fn table() -> Vec { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 5 << 16] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| { + for w in words { + t.extend(w.to_le_bytes()); + } + }; + entry([0x41, 0x401, 0, 3, 0, 0x0002_0004, u32::MAX, 0]); + entry([0x41, 0x300, 0, 9, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x303, 8, 2, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x303, 16, 3, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x302, 24, 1, 0, 0x404, u32::MAX, 0]); + entry([0x42, 0, 0, 9, 1, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + t + } + + fn registers() -> Vec { + [0u32, 0, 0, 8 << 16 | 8, 1, 3, 5 << 1] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect() + } + + #[test] + fn a_console_compute_program_reads_its_registers_and_table() { + let code = [0x7E00_0280u32, 0xBF81_0000, S_CODE_END, S_CODE_END]; + let code: Vec = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = console_compute(®isters(), &table(), &code).unwrap(); + assert!(p.wave64); + assert_eq!(p.vgprs, 16); + assert_eq!(p.code.len(), 8, "the s_code_end padding is left out"); + let StageIo::Cs(cs) = p.io else { panic!() }; + assert_eq!( + (cs.rsrc2, cs.threads, cs.user_sgprs()), + (5 << 1, [8, 8, 1], 5) + ); + assert_eq!(p.used.len(), 5); + assert_eq!( + p.used[2], + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 8, + lower_bound: 2, + stride: 4, + dwords: 8, + user_data: 4, + slot: 0, + } + ); + assert_eq!( + (p.used[0].kind, p.used[0].root, p.used[0].slot), + (ResourceType::Sampler, RootType::ImmediateSampler, 2) + ); + assert_eq!(p.layout[4].table_offset_dwords, 24); + } + + #[test] + fn incomplete_or_unknown_descriptions_are_refused() { + let t = table(); + let code = 0xBF81_0000u32.to_le_bytes(); + let regs = registers(); + for end in 0..t.len() { + assert!(console_compute(®s, &t[..end], &code).is_err()); + } + for (offset, value) in [(20, 20u32 << 16), (24, 0x44), (t.len() - 32, 0x42)] { + let mut bad = t.clone(); + bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + assert!(console_compute(®s, &bad, &code).is_err()); + } + assert!(console_compute(®s, &t, &code[..3]).is_err()); + assert!(console_compute(®s, &t, &S_CODE_END.to_le_bytes()).is_err()); + let mut large = regs; + large[12..16].copy_from_slice(&(64u32 << 16 | 32).to_le_bytes()); + assert!(console_compute(&large, &t, &code).is_err()); + } + + #[test] + fn short_header_wave32_and_multiblock_code_round_trip() { + let mut t = table(); + t.drain(8..16); + t[..4].copy_from_slice(&3u32.to_le_bytes()); + let mut regs = registers(); + regs[..4].copy_from_slice(&super::super::FLAG_WAVE32.to_le_bytes()); + let code = vec![0; 65536]; + let p = console_compute(®s, &t, &code).unwrap(); + assert!(!p.wave64); + assert_eq!(p.vgprs, 32); + let bytes = console_compute_container(®s, &t, &code).unwrap(); + let c = crate::Container::parse(&bytes).unwrap(); + assert_eq!( + super::super::native_programs(c.part(FourCC::DXIL).unwrap().data).unwrap(), + vec![p] + ); + } + + #[test] + fn its_container_gives_the_program_back() { + let code: Vec = [0x7E00_0280u32, 0xBF81_0000] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = console_compute(®isters(), &table(), &code).unwrap(); + let container = compute_container(&p).unwrap(); + let c = crate::Container::parse(&container).unwrap(); + let back = super::super::native_programs(c.part(FourCC::DXIL).unwrap().data).unwrap(); + assert_eq!(back, vec![p]); + } +} diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 2b6edd4652..d6aab60a24 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -2264,7 +2264,7 @@ impl Tracer<'_> { let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + self.spilled(inst.read(Reg::V(reg))?, constant_operand(lane)?, &mut Vec::new()) .ok() .flatten() } @@ -2298,7 +2298,7 @@ impl Tracer<'_> { if inst.name() != "v_writelane_b32" { return Err(()); } - if lane_of(*at).ok_or(())? != lane { + if constant_operand(*at).ok_or(())? != lane { return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); } match *value { @@ -2314,8 +2314,8 @@ impl Tracer<'_> { } } -/// A lane select given as a constant. -fn lane_of(op: Operand) -> Option { +/// An inline or literal constant operand. +fn constant_operand(op: Operand) -> Option { match op { Operand::Const(c) => inline(c), Operand::Literal(x) => Some(x), @@ -2331,16 +2331,21 @@ fn copy_source(inst: &Inst, k: usize) -> Option { if inst.name() == "s_movk_i32" { return Some(Moved::Const(i32::from((*imm)? as i16) as u32)); } + if inst.name() == "s_bfm_b32" && k == 0 { + let [width, shift] = src.as_slice() else { return None }; + let width = constant_operand(*width)? & 31; + let shift = constant_operand(*shift)? & 31; + return Some(Moved::Const(((1u32 << width) - 1) << shift)); + } let src = src.first()?; match (inst.name(), *src) { ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => { inst.read(Reg::S(code + k as u8)).map(Moved::Value) } ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)), - ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)), + // A literal used by a 64-bit bitwise instruction is zero extended. + ("s_mov_b32" | "s_mov_b64", Operand::Literal(x)) => Some(Moved::Const(if k == 0 { x } else { 0 })), ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const), - // shortcut: only the one-operand ways the compiler makes a constant - // that has no inline form; fold more if descriptors need it. ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())), ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)), // 64-bit inline integers are sign-extended. @@ -2453,6 +2458,25 @@ pub(crate) mod tests { ); } + #[test] + fn a_constant_bitmask_can_supply_a_static_sampler_word() { + let r = track_words( + &[ + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xBE88_0480, // s_mov_b64 s[8:9], 0 + 0xBE8A_04FF, 0x8000_0001, // s_mov_b64 s[10:11], literal + 0x9209_8385, // s_bfm_b32 s9, 5, 3 + 0xF080_0F08, 0x0040_0002, // image_sample using s[8:11] as its sampler + S_ENDPGM, + ], + &[param(Table, 2, 1)], + HwStage::Ps, + ); + let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler).unwrap(); + assert_eq!(sampler.source, Source::Constant(vec![0, 0xf8, 0x8000_0001, 0])); + } + #[test] fn root_descriptors_are_built_in_code() { let r = track_words( From 17b34d2f8e78ebe9ae32f1a18a860aa1957bd406 Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:13:53 +0100 Subject: [PATCH 4/9] Restore the shortcut note on 0x1c8 and classify native_build.rs in order The 0x218 commit cut the note on device method 0x1c8 down to one line and dropped its `shortcut:` marker, which is how the repository lists what is not implemented. It also put native_build.rs in the middle of the sorted list of sources outside the translation, with a comment that did not say why it is outside. The note and its marker are back, and the entry now sits at the end of the list with the reason: native_build only writes containers, which are hashed like any other. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/device.rs | 10 ++++++++-- crates/victory-shader/src/lib.rs | 8 ++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 8a02250953..c00926fa12 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -346,8 +346,14 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } -/// Device method 0x1c8. Native graphics state still needs render-target -/// formats from the draw. Leave the output null so the caller can fall back. +/// Device method 0x1c8 (title+0x2477578): a graphics pipeline from programs +/// the title compiled itself, called as `(this, description, interface id, +/// out)` for `ID3D12PipelineState`. On failure the title goes without that +/// pipeline, silently. The first calls log the description's words and what +/// its first word points at. +/// shortcut: not implemented. A host pipeline also needs the render-target +/// formats, which only the draw gives; answering `S_OK` without making the +/// pipeline would hand the title whatever its stack held as an object. extern "system" fn unknown_graphics_pipeline( _: This, desc: *const u8, diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index b7bc71b545..affb2ab02c 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -94,13 +94,12 @@ translation_inputs! { mod source_tests { use std::path::{Path, PathBuf}; - // host.rs consumes finished DXIL to create or run host pipelines. The + // host.rs consumes finished DXIL to create or run host pipelines. + // native_build.rs only writes containers: what it writes is hashed as + // any container is, so it cannot change a translation kept on disk. The // remaining modules are only compiled by the Windows execution tests. const OUTSIDE_TRANSLATION: &[&str] = &[ "emit/cube_lod_tests.rs", - // (programs the title hands over compiled, wrapped in a container that the - // translation then reads as any other) - "native_build.rs", "emit/descriptor_tests.rs", "emit/diff_tests.rs", "emit/helper_lane_tests.rs", @@ -110,6 +109,7 @@ mod source_tests { "emit/valu_tests.rs", "emit/waterfall_tests.rs", "emit/wave64_tests.rs", + "native_build.rs", ]; #[test] From a97171618112102dbf1ec950ec6256e78788254e Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:21:33 +0100 Subject: [PATCH 5/9] Wait for the heap to go before the in-place test gives its pages back warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset decommitted half of its allocation right after dropping the buffer placed over it. The pages of a heap opened on private memory stay locked until the runtime has destroyed the heap, and WARP may do that a moment after the last reference goes: under the load of the whole victory-gpu suite the decommit was sometimes refused (ERROR_INVALID_PARAMETER) and the test failed, or the run ended in an access violation. About 2 runs in 15 failed this way, already on a65db62. The test now retries the decommit for two seconds at most, drops its command queue before releasing the allocation, and checks that the release succeeds. 40 runs of the library in a row now pass. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/inplace.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 46175ab60c..5113ee6132 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -1333,6 +1333,23 @@ mod tests { } } + /// Tries `free` (a `VirtualFree` of pages a heap was opened on) until + /// it succeeds, for two seconds at most: when the heap's last reference + /// goes, the runtime may destroy it, and unlock its pages, a moment + /// later. Whether it succeeded. + fn once_released(mut free: impl FnMut() -> bool) -> bool { + let until = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + if free() { + return true; + } + if std::time::Instant::now() > until { + return false; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + pub(crate) fn warp() -> Option { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; @@ -1398,10 +1415,13 @@ mod tests { rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); drop(placed); - // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + // Half of it decommitted: turned down, the host not asked. The + // heap's pages stay locked until the runtime has destroyed it, + // which may come a moment after the last reference goes. + assert!(once_released(|| mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0), "the pages are given back once the heap goes"); assert!(matches!(place_part(&device, start, len), Err(None))); - mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + drop(rig); + assert_ne!(mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE), 0); } } From 9eac44a63cd24e20a890636a46d9cb409fc742f9 Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:24:41 +0100 Subject: [PATCH 6/9] Read 0x218 resource tables as the title writes them Descriptions captured in game showed three misreadings in the decoder of programs handed to device method 0x218: - The user-data dword and the stride were swapped. The byte in the packed word is the user-data dword: every entry of root slot k names dword 4 + k, inside the program's COMPUTE_PGM_RSRC2 user-SGPR count. The u32 before it is the stride (0x10 or 0x20 for structured buffer SRVs, 4 for images, as in the title's own containers). With the swap, the CBV of every accepted mip-generation program named user-data dword 0 instead of the table in dword 4. A root parameter that names user data the program does not have is now refused. - The header count is not always that of the 0x41 entries (11 for 12 seen), so the entries are told apart by their tag. - Root type 0 is root constants, read as values from the user SGPRs (`v_mul_f32 v7, s5, v7`). They are now a root parameter of size/4 SGPRs, with no used resource. - The thread-group depth is the low half of its word; the high half holds something else (0x10 seen with 32 x 1 x 1 groups). In game, 0x218 now makes over 2048 pipelines and turns down 32 to 63 descriptions (before: about 512 made, over 1024 turned down). Of eight descriptions captured in game, all now decode and four reach a hardware pipeline; the four others stop at translator limits (a descriptor changed after loading, an address with two computed terms). The five earlier captures still pass. Co-Authored-By: Claude Opus 5.5 --- crates/victory-shader/src/native_build.rs | 134 +++++++++++++++++++--- 1 file changed, 116 insertions(+), 18 deletions(-) diff --git a/crates/victory-shader/src/native_build.rs b/crates/victory-shader/src/native_build.rs index 1eb027a942..a307f13a00 100644 --- a/crates/victory-shader/src/native_build.rs +++ b/crates/victory-shader/src/native_build.rs @@ -10,20 +10,32 @@ //! ```text //! +0x00 u32 kind (bit 10: 8 bytes more of header), u32 size of the rest //! (from +0x0c, or +0x14), u32, u32 ..., the last u32 of the header -//! holding the count of 0x41 entries in its high half (`n << 16 | 0x440`) -//! entries of 0x20 bytes from the end of the header: +//! `n << 16 | 0x440` (n is not always the count of 0x41 entries: 11 +//! for 12 seen, so the entries are told apart by their tag) +//! entries of 0x20 bytes from the end of the header, 0x41 ones first: //! 0x41 a descriptor the program reads: u32 0x41, u32 root type << 8 | //! resource type (0 SRV, 1 sampler, 2 CBV, 3 UAV), u32 table offset -//! (dwords), u32 shader register, u32 first user-data dword, -//! u32 root slot << 16 | stride << 8 | descriptor dwords, then -//! u32 -1, u32 0 +//! (dwords), u32 shader register, u32 stride (bytes; 0 for a CBV, +//! 4 for an image), u32 root slot << 16 | first user-data dword << 8 +//! | descriptor dwords, then u32 -1, u32 0 //! 0x42 a table range (not read: the 0x41 entries name the same ranges) //! 0x43 the program's 128-bit hash, last //! ``` //! +//! The user-data dword is the one byte that agrees across a table: every +//! entry of root slot k names dword 4 + k, which the program's +//! `COMPUTE_PGM_RSRC2` user-SGPR count covers, and a fixed sampler 0. The +//! u32 before it is 0x10 or 0x20 for buffer SRVs (a structured stride), +//! which no user-SGPR count covers. +//! +//! Root type 0 is root constants (resource type 2): the program reads them +//! as values straight from its user SGPRs (`v_mul_f32 v7, s5, v7`), so the +//! descriptor dwords byte is their size in bytes. They give a root parameter +//! and no used resource, as nothing is loaded through them. +//! //! The registers of a compute program, 0x1c bytes: u32 flags (bit 5: 32 -//! lanes, as the container record's flags), u32, u32, u16 x2 and u32 -//! thread-group size, u32 `COMPUTE_PGM_RSRC1`, u32 `COMPUTE_PGM_RSRC2`. +//! lanes, as the container record's flags), u32, u32, u16 x3 thread-group +//! size and u16 not read, u32 `COMPUTE_PGM_RSRC1`, u32 `COMPUTE_PGM_RSRC2`. use super::{ ABSENT, CS_RSRC2, CS_THREADS, ComputeIo, ENTRY_SIZE, MAX_UNPACKED, FSSM_HEADER, FSSM_VERSION, GRAPHICS_SLOT_COUNT, HwStage, @@ -46,14 +58,14 @@ fn resources(table: &[u8]) -> Result<(Vec, Vec), Shader if table.len().checked_sub(header - 4) != Some(size) { return Err(Malformed("resource table size disagrees")); } - let count = (u32_at(table, header - 4)? >> 16) as usize; let (entries, tail) = table[header..].as_chunks::<0x20>(); let Some((hash, entries)) = entries.split_last() else { return Err(Malformed("missing resource table hash")); }; - if !tail.is_empty() || u32_at(hash, 0)? != 0x43 || count > entries.len() { + if !tail.is_empty() || u32_at(hash, 0)? != 0x43 { return Err(Malformed("incomplete resource table")); } + let count = entries.iter().take_while(|entry| super::le32(entry.as_slice(), 0) == 0x41).count(); let (descriptors, ranges) = entries.split_at(count); if ranges.iter().any(|entry| super::le32(entry, 0) != 0x42) { return Err(Malformed("unexpected resource range")); @@ -61,15 +73,26 @@ fn resources(table: &[u8]) -> Result<(Vec, Vec), Shader let (mut layout, mut used) = (Vec::new(), Vec::new()); for entry in descriptors { let word = |k: usize| u32::from_le_bytes(entry[4 * k..4 * k + 4].try_into().unwrap()); - if word(0) != 0x41 { - return Err(Malformed("unexpected resource descriptor")); - } - let (types, offset, register, user_data, packed) = + let (types, offset, register, stride, packed) = (word(1), word(2), word(3), word(4), word(5)); let root = RootType::from_raw(types >> 8); let slot = u8::try_from(packed >> 16).map_err(|_| Malformed("implausible root slot"))?; - let user_data = - u8::try_from(user_data).map_err(|_| Malformed("implausible user-data dword"))?; + let user_data = (packed >> 8) as u8; + if root == RootType::Constants { + let bytes = packed & 0xFF; + if bytes == 0 || !bytes.is_multiple_of(4) { + return Err(Malformed("implausible root constants size")); + } + layout.push(RootParam { + root, + table_offset_dwords: 0, + sgprs: bytes / 4, + base_register: register, + user_data, + slot, + }); + continue; + } used.push(UsedResource { kind: match types & 0xFF { 0 => ResourceType::Srv, @@ -81,7 +104,7 @@ fn resources(table: &[u8]) -> Result<(Vec, Vec), Shader root, table_offset_dwords: offset, lower_bound: register, - stride: packed >> 8 & 0xFF, + stride, dwords: packed as u8, user_data, slot, @@ -128,7 +151,9 @@ fn console_compute( } let flags = u32_at(registers, 0)?; let size = u32_at(registers, 0x0c)?; - let threads = [size & 0xFFFF, size >> 16, u32_at(registers, 0x10)?]; + // The depth is the low half of its word; the high half holds something + // else (0x10 seen with 32 x 1 x 1 groups). + let threads = [size & 0xFFFF, size >> 16, u32_at(registers, 0x10)? & 0xFFFF]; let rsrc1 = u32_at(registers, 0x14)?; let rsrc2 = u32_at(registers, 0x18)?; if threads.contains(&0) @@ -147,6 +172,11 @@ fn console_compute( return Err(Malformed("invalid compute register count or code length")); } let (layout, used) = resources(table)?; + // COMPUTE_PGM_RSRC2.USER_SGPR: what the root parameters can name. + let user_sgprs = rsrc2 >> 1 & 0x1F; + if layout.iter().any(|p| u32::from(p.user_data) + p.sgprs > user_sgprs) { + return Err(Malformed("a resource table names user data the program does not have")); + } let code = trimmed(code); if code.is_empty() { return Err(Malformed("no code")); @@ -390,7 +420,8 @@ mod tests { for end in 0..t.len() { assert!(console_compute(®s, &t[..end], &code).is_err()); } - for (offset, value) in [(20, 20u32 << 16), (24, 0x44), (t.len() - 32, 0x42)] { + // Root constants of no size, an unknown tag, no hash. + for (offset, value) in [(t.len() - 64, 0x41u32), (24, 0x44), (t.len() - 32, 0x42)] { let mut bad = t.clone(); bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); assert!(console_compute(®s, &bad, &code).is_err()); @@ -402,6 +433,73 @@ mod tests { assert!(console_compute(&large, &t, &code).is_err()); } + /// As a title's table (a program with seven user SGPRs): a header count + /// one short of the 0x41 entries, two root slots whose entries name + /// user-data dwords 4 and 5, structured buffer SRVs of a 16-byte stride. + #[test] + fn entries_name_their_user_data_and_stride_as_a_title_does() { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 2 << 16 | 0x440] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| t.extend(words.iter().flat_map(|w| w.to_le_bytes())); + entry([0x41, 0x401, 0, 0, 0, 2 << 16 | 4, u32::MAX, 0]); + entry([0x41, 0x300, 0x130, 0x48, 0x10, 0x404, u32::MAX, 0]); + entry([0x41, 0x303, 0x28, 0x16, 4, 1 << 16 | 0x508, u32::MAX, 0]); + entry([0x42, 0, 0xc_0001, 0x48, 0, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + let mut regs = registers(); + regs[0x18..0x1c].copy_from_slice(&(7u32 << 1).to_le_bytes()); + let code = 0xBF81_0000u32.to_le_bytes(); + let p = console_compute(®s, &t, &code).unwrap(); + let named: Vec<_> = p.used.iter().map(|u| (u.slot, u.user_data, u.stride)).collect(); + assert_eq!(named, [(2, 0, 0), (0, 4, 16), (1, 5, 4)]); + assert_eq!(p.layout.iter().map(|l| l.user_data).collect::>(), [0, 4, 5]); + // Five user SGPRs do not reach dword 5. + regs[0x18..0x1c].copy_from_slice(&(5u32 << 1).to_le_bytes()); + assert!(console_compute(®s, &t, &code).is_err()); + } + + /// A title's gamma pass: a UAV table in dword 4 and one root constant + /// in dword 5, read as a value; and a depth word whose high half is not + /// the depth. + #[test] + fn root_constants_are_a_root_parameter_and_the_depth_its_low_half() { + let mut t = Vec::new(); + for w in [0x403u32, 0, 0, 0, 0, 2 << 16 | 0x440] { + t.extend(w.to_le_bytes()); + } + let mut entry = |words: [u32; 8]| t.extend(words.iter().flat_map(|w| w.to_le_bytes())); + entry([0x41, 0x303, 0, 0x37, 4, 0x408, u32::MAX, 0]); + entry([0x41, 0x002, 0, 0x1f6, 0, 1 << 16 | 0x504, u32::MAX, 0]); + entry([0x42, 0, 0x2_0101, 0x37, 1, 0, u32::MAX, 0]); + entry([0x43, 1, 2, 3, 4, 0, 0, 0]); + let size = (t.len() - 0x14) as u32; + t[4..8].copy_from_slice(&size.to_le_bytes()); + let mut regs = registers(); + regs[0x0c..0x10].copy_from_slice(&(1u32 << 16 | 32).to_le_bytes()); + regs[0x10..0x14].copy_from_slice(&0x0010_0001u32.to_le_bytes()); + regs[0x18..0x1c].copy_from_slice(&0x98cu32.to_le_bytes()); + let code = 0xBF81_0000u32.to_le_bytes(); + let p = console_compute(®s, &t, &code).unwrap(); + let StageIo::Cs(cs) = p.io else { panic!() }; + assert_eq!(cs.threads, [32, 1, 1]); + assert_eq!(p.used.len(), 1, "constants are not a resource read"); + assert_eq!( + p.layout[1], + RootParam { + root: RootType::Constants, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0x1f6, + user_data: 5, + slot: 1, + } + ); + } + #[test] fn short_header_wave32_and_multiblock_code_round_trip() { let mut t = table(); From 88f8f9a6e3065c3aabbeeaba4c5d9d952aba3429 Mon Sep 17 00:00:00 2001 From: Castyan <120135015+Castyan@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:24:41 +0100 Subject: [PATCH 7/9] Say why a 0x218 description is not read, and save it on request A description the decoder turns down used to be logged with a count only, and one whose blocks could not be read was not logged at all. The warning now gives the reason (which block, or the decoder's error) and the description's twelve words. With VICTORY_DUMP_NATIVE=, a description turned down is saved there with the blocks it names, four of each reason and 200 in all, as slot218--desc-
.bin and slot218--dNN-
-.bin with the reason beside them. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/pipeline.rs | 113 ++++++++++++++++++++++++----- 1 file changed, 93 insertions(+), 20 deletions(-) diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 43ff4cc63e..63b3c16a36 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -693,20 +693,27 @@ pub(crate) extern "system" fn create_native_compute( // SAFETY: the title's out pointer. unsafe { *out = std::ptr::null() }; } - let program = (|| { - let registers = title_bytes(desc, 1)?; - let code = title_bytes(desc, 5)?; - let table = title_bytes(desc, 7)?; - victory_shader::native::console_compute_container(®isters, &table, &code) - .map_err(|e| tracing::debug!(error = %e, "a compute program compiled by the title is not read")) - .ok() + let program = (|| -> Result, String> { + let registers = title_bytes(desc, 1).map_err(|e| format!("registers: {e}"))?; + let code = title_bytes(desc, 5).map_err(|e| format!("code: {e}"))?; + let table = title_bytes(desc, 7).map_err(|e| format!("resource table: {e}"))?; + victory_shader::native::console_compute_container(®isters, &table, &code).map_err(|e| e.to_string()) })(); - let made = MADE[usize::from(program.is_none())].fetch_add(1, Ordering::Relaxed) + 1; - let Some(container) = program else { - if made.is_power_of_two() { - tracing::warn!(missed = made, "a compute pipeline from compiled code that is not read: the title goes without it"); + let made = MADE[usize::from(program.is_err())].fetch_add(1, Ordering::Relaxed) + 1; + let container = match program { + Ok(container) => container, + Err(why) => { + dump_native(desc, &why); + if made <= 4 || made.is_power_of_two() { + tracing::warn!( + missed = made, + why, + description = format_args!("{:x?}", title_words(desc)), + "a compute pipeline from compiled code that is not read: the title goes without it" + ); + } + return crate::object::E_NOTIMPL; } - return crate::object::E_NOTIMPL; }; let shader = shader("compute", &container); if made.is_power_of_two() { @@ -723,29 +730,95 @@ pub(crate) extern "system" fn create_native_compute( /// The bytes named by words `at` (address) and `at + 1` (size) of the /// title's description `desc`, read through the kernel: the title's own -/// memory, which may not be mapped. -fn title_bytes(desc: *const u8, at: usize) -> Option> { +/// memory, which may not be mapped. Why not, if not. +fn title_bytes(desc: *const u8, at: usize) -> Result, String> { #[cfg(windows)] { let mut words = [0u8; 16]; if desc.is_null() { - return None; + return Err("no description".to_owned()); } let start = desc.wrapping_add(8 * at); if !crate::host::read_into(start, &mut words) { - return None; + return Err("the description is not readable".to_owned()); } - let address = u64::from_le_bytes(words[..8].try_into().ok()?) as usize; - let size = u64::from_le_bytes(words[8..].try_into().ok()?) as usize; + let address = u64::from_le_bytes(words[..8].try_into().unwrap()) as usize; + let size = u64::from_le_bytes(words[8..].try_into().unwrap()) as usize; if address == 0 || !(4..=1 << 20).contains(&size) { - return None; + return Err(format!("implausible block {address:#x}+{size:#x}")); } let mut bytes = vec![0u8; size]; - crate::host::read_into(address as *const u8, &mut bytes).then_some(bytes) + if crate::host::read_into(address as *const u8, &mut bytes) { + Ok(bytes) + } else { + Err(format!("block {address:#x}+{size:#x} not readable")) + } } #[cfg(not(windows))] { let _ = (desc, at); + Err("not on this host".to_owned()) + } +} + +/// `VICTORY_DUMP_NATIVE=`: a description device method 0x218 could +/// not read is saved there, with the blocks it names, as +/// `slot218--desc-
.bin` and `slot218--dNN-
-.bin` +/// (what `pr64-replay` reads); four of each reason, 200 in all. +fn dump_native(desc: *const u8, why: &str) { + #[cfg(windows)] + { + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + static FOLDER: OnceLock> = OnceLock::new(); + static SEEN: Mutex)>> = Mutex::new(None); + let Some(folder) = FOLDER.get_or_init(|| std::env::var_os("VICTORY_DUMP_NATIVE").map(std::path::PathBuf::from)) else { + return; + }; + let Some(words) = title_words(desc) else { return }; + let n = { + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let (total, reasons) = seen.get_or_insert_with(Default::default); + let reason = reasons.entry(why.to_owned()).or_default(); + if *total >= 200 || *reason >= 4 { + return; + } + *reason += 1; + *total += 1; + *total + }; + let _ = std::fs::create_dir_all(folder); + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-desc-{:x}.bin", desc as usize)), bytes); + for at in [1, 3, 5, 7] { + let (address, size) = (words[at] as usize, words[at + 1] as usize); + if address == 0 || size == 0 || size > 1 << 20 { + continue; + } + let mut block = vec![0u8; size]; + if crate::host::read_into(address as *const u8, &mut block) { + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-d{at:02}-{address:x}-{size:x}.bin")), block); + } + } + let _ = std::fs::write(folder.join(format!("slot218-m{n:03}-why.txt")), why); + } + #[cfg(not(windows))] + let _ = (desc, why); +} + +/// The twelve words of a description (0x60 bytes), for the log. +fn title_words(desc: *const u8) -> Option<[u64; 12]> { + #[cfg(windows)] + { + let mut bytes = [0u8; 0x60]; + if desc.is_null() || !crate::host::read_into(desc, &mut bytes) { + return None; + } + Some(std::array::from_fn(|k| u64::from_le_bytes(bytes[8 * k..8 * k + 8].try_into().unwrap()))) + } + #[cfg(not(windows))] + { + let _ = desc; None } } From 2024577102548b3e26a44ad3e1ab300cc486c226 Mon Sep 17 00:00:00 2001 From: Zhelezniak Artem Date: Thu, 26 Nov 2026 10:09:55 +0300 Subject: [PATCH 8/9] GPU: count selected direct and indirect compute dispatch recordings --- crates/victory-gpu/src/draw.rs | 22 ++++++++ crates/victory-gpu/src/pipeline.rs | 80 ++++++++++++++++++++++++++++++ crates/victory-gpu/src/queue.rs | 2 + 3 files changed, 104 insertions(+) diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 2900faa5d2..197ffb1222 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -2345,6 +2345,12 @@ impl State { /// Runs a dispatch on the host. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32, flags: Option) { + #[cfg(feature = "diagnostics")] + let trace = crate::pipeline::dispatch_trace(self.pipeline as This); + #[cfg(feature = "diagnostics")] + if let Some(trace) = trace { + trace.attempt(false); + } // It may write the arguments a window holds clamped. self.window = None; let builder = crate::pipeline::is_builder(self.pipeline as This); @@ -2450,6 +2456,10 @@ impl State { unsafe { list.list.Dispatch(x, y, z) }; } } + #[cfg(feature = "diagnostics")] + if let Some(trace) = trace { + trace.record(false); + } if let Some((param, word, _)) = tail { // Later ordinary or indirect dispatches use all lanes. unsafe { list.list.SetComputeRoot32BitConstant(param, 0, word) }; @@ -3378,7 +3388,19 @@ impl State { arguments: u64, count: Option, ) -> bool { + #[cfg(feature = "diagnostics")] + let trace = (kind == 2 && max != 0) + .then(|| crate::pipeline::dispatch_trace(self.pipeline as This)) + .flatten(); + #[cfg(feature = "diagnostics")] + if let Some(trace) = trace { + trace.attempt(true); + } let ran = self.run_indirect(list, (kind, stride, max), arguments, count); + #[cfg(feature = "diagnostics")] + if ran && let Some(trace) = trace { + trace.record(true); + } if kind == 2 && max != 0 && crate::pipeline::is_builder(self.pipeline as This) { if !ran { crate::pipeline::builder_off("an indirect builder dispatch could not run"); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 63b3c16a36..e1c5cdcaa9 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -500,6 +500,72 @@ fn skipped_shader(p: &Pipeline) -> Option<&str> { .map(|shader| shader.hash.as_str()) } +/// Command recording counts for a selected compute shader. An indirect +/// recording can still read a count of zero when it runs on the GPU. +#[cfg(all(windows, feature = "diagnostics"))] +#[derive(Default)] +pub(crate) struct DispatchTrace { + direct_attempted: std::sync::atomic::AtomicU64, + direct_recorded: std::sync::atomic::AtomicU64, + indirect_attempted: std::sync::atomic::AtomicU64, + indirect_recorded: std::sync::atomic::AtomicU64, +} + +#[cfg(all(windows, feature = "diagnostics"))] +impl DispatchTrace { + pub(crate) fn attempt(&self, indirect: bool) { + let counter = if indirect { &self.indirect_attempted } else { &self.direct_attempted }; + counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + + pub(crate) fn record(&self, indirect: bool) { + let counter = if indirect { &self.indirect_recorded } else { &self.direct_recorded }; + counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + + fn counts(&self) -> [u64; 4] { + [&self.direct_attempted, &self.direct_recorded, + &self.indirect_attempted, &self.indirect_recorded] + .map(|counter| counter.load(std::sync::atomic::Ordering::Relaxed)) + } +} + +/// VICTORY_TRACE_DISPATCHES takes a comma-separated list of compute hashes. +/// The normal path has no counters or log output when the list is empty. +#[cfg(all(windows, feature = "diagnostics"))] +fn dispatch_traces() -> &'static [(String, DispatchTrace)] { + static TRACES: OnceLock> = OnceLock::new(); + TRACES.get_or_init(|| { + let value = std::env::var("VICTORY_TRACE_DISPATCHES").unwrap_or_default(); + let mut hashes = parse_shader_hashes(&value, "VICTORY_TRACE_DISPATCHES"); + hashes.sort_unstable(); + hashes.dedup(); + hashes.into_iter().map(|hash| (hash, DispatchTrace::default())).collect() + }) +} + +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn dispatch_trace(this: This) -> Option<&'static DispatchTrace> { + let traces = dispatch_traces(); + if traces.is_empty() || this.is_null() { + return None; + } + let shader = pipeline(this).shaders.first().filter(|s| s.stage == "compute")?; + let at = traces.binary_search_by(|(hash, _)| hash.cmp(&shader.hash)).ok()?; + Some(&traces[at].1) +} + +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn report_dispatch_traces(frame: u64) { + if frame == 1 || frame.is_multiple_of(64) { + for (hash, trace) in dispatch_traces() { + let [direct_attempted, direct_recorded, indirect_attempted, indirect_recorded] = trace.counts(); + tracing::info!(%hash, frame, direct_attempted, direct_recorded, + indirect_attempted, indirect_recorded, "selected compute dispatch recording totals"); + } + } +} + /// Recording-time trace, independent of the present and heavy-frame capture. /// The budget is per shader so that a frequent stage cannot silence a later stage. #[cfg(all(windows, feature = "diagnostics"))] @@ -989,6 +1055,20 @@ mod tests { ); } + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn dispatch_trace_distinguishes_attempts_from_recordings() { + let trace = super::DispatchTrace::default(); + assert_eq!(trace.counts(), [0, 0, 0, 0]); + trace.attempt(false); + trace.attempt(false); + trace.record(false); + trace.attempt(true); + assert_eq!(trace.counts(), [2, 1, 1, 0]); + trace.record(true); + assert_eq!(trace.counts(), [2, 1, 1, 1]); + } + use super::*; use crate::object::{S_OK, slot}; diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 32a8387a33..3a853bd549 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -780,6 +780,8 @@ extern "system" fn present( release_held(forces()); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; #[cfg(all(windows, feature = "diagnostics"))] + crate::pipeline::report_dispatch_traces(frame); + #[cfg(all(windows, feature = "diagnostics"))] if frame.is_power_of_two() && std::env::var_os("VICTORY_TRACE_PRESENT_PLANES").is_some() && planes > 0 From 5e107818b48fe94edba883e7abc8fcbd9c42d42c Mon Sep 17 00:00:00 2001 From: Zhelezniak Artem Date: Thu, 26 Nov 2026 10:17:21 +0300 Subject: [PATCH 9/9] GPU: report dispatch totals before a fatal host failure --- crates/victory-gpu/src/host.rs | 2 ++ crates/victory-gpu/src/pipeline.rs | 21 +++++++++++---------- crates/victory-gpu/src/queue.rs | 4 +++- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4b672dfaca..b02a55a5e6 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -521,6 +521,8 @@ pub fn on_failure(report: fn(&str) -> !) { /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a /// diagnostics build names the command). pub(crate) fn fail(what: std::fmt::Arguments) -> ! { + #[cfg(feature = "diagnostics")] + crate::pipeline::report_dispatch_traces(crate::queue::presented()); let mut text = what.to_string(); if let Some(host) = host() { // SAFETY: a plain query. diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index e1c5cdcaa9..24269d35d5 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -520,13 +520,16 @@ impl DispatchTrace { pub(crate) fn record(&self, indirect: bool) { let counter = if indirect { &self.indirect_recorded } else { &self.direct_recorded }; - counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + counter.fetch_add(1, std::sync::atomic::Ordering::Release); } fn counts(&self) -> [u64; 4] { - [&self.direct_attempted, &self.direct_recorded, - &self.indirect_attempted, &self.indirect_recorded] - .map(|counter| counter.load(std::sync::atomic::Ordering::Relaxed)) + use std::sync::atomic::Ordering::{Acquire, Relaxed}; + // Observe a recorded command before reading the attempt count. + let direct_recorded = self.direct_recorded.load(Acquire); + let indirect_recorded = self.indirect_recorded.load(Acquire); + [self.direct_attempted.load(Relaxed), direct_recorded, + self.indirect_attempted.load(Relaxed), indirect_recorded] } } @@ -557,12 +560,10 @@ pub(crate) fn dispatch_trace(this: This) -> Option<&'static DispatchTrace> { #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn report_dispatch_traces(frame: u64) { - if frame == 1 || frame.is_multiple_of(64) { - for (hash, trace) in dispatch_traces() { - let [direct_attempted, direct_recorded, indirect_attempted, indirect_recorded] = trace.counts(); - tracing::info!(%hash, frame, direct_attempted, direct_recorded, - indirect_attempted, indirect_recorded, "selected compute dispatch recording totals"); - } + for (hash, trace) in dispatch_traces() { + let [direct_attempted, direct_recorded, indirect_attempted, indirect_recorded] = trace.counts(); + tracing::info!(%hash, frame, direct_attempted, direct_recorded, + indirect_attempted, indirect_recorded, "selected compute dispatch recording totals"); } } diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 3a853bd549..21368d053d 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -780,7 +780,9 @@ extern "system" fn present( release_held(forces()); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; #[cfg(all(windows, feature = "diagnostics"))] - crate::pipeline::report_dispatch_traces(frame); + if frame == 1 || frame.is_multiple_of(64) { + crate::pipeline::report_dispatch_traces(frame); + } #[cfg(all(windows, feature = "diagnostics"))] if frame.is_power_of_two() && std::env::var_os("VICTORY_TRACE_PRESENT_PLANES").is_some()